branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>WilliamJohns/BGAPI-Spike<file_sep>/README.md
There is a line in btle_driver.c -> handle_data() called print_bytes(); that is commented out.
It can be toggled to print raw data, however it has some memory issues at the moment.
Messages are printed in doubles for an unknown reason at the moment.
<file_sep>/main.c
/*
* main.c
*
* Created on: Nov 3, 2014
* Author: jcobb
*/
#define F_CPU 8000000
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "btle/btle.h"
#include "usart/usart_btle.h"
#include "usart/usart_wan.h"
#include "wan/wan_driver.h"
#include "wan/wan.h"
volatile char term_in = 0;
void terminal_in_cb(uint8_t c)
{
term_in = c;
}
void main()
{
// Blinky test!
DDRD |= _BV(PD6); // data direction bit
DDRD |= _BV(PD7);
DDRB &= _BV(PB0); // WAN_INT_01
//debug_init(terminal_in_cb);
btle_usart_init_cb(terminal_in_cb);
// btle is on usart1
btle_init();
// wan is on usart0
wan_init();
sei();
while(true)
{
btle_tick();
wan_tick();
term_in = 0;
}
}
| c4e1a178fdad1ee7a500f4ea63826622f0583ace | [
"Markdown",
"C"
] | 2 | Markdown | WilliamJohns/BGAPI-Spike | c8e7f0ec1d768e7d7598a1f76057319c7d288918 | e95f4c9eb3dd7f219c7de836463606e206d8cfaf |
refs/heads/master | <file_sep>package Builder;
public interface MealBuilder {
public void addSides(String side);
public void addDrink(String drink);
public void addSandwich(String sandwich);
public void addOffer(String offer);
public Meal getMeal();
public void setPrice(double d);
}<file_sep>package Builder;
public class MealDirector {
public Meal makeMeal(MealBuilder b){
b.addDrink("Coca Cola");
b.addSides("french fries");
b.addOffer("0");
b.setPrice(120.00);
return b.getMeal();
}
} | d32fbce862265a8b48858f7cacc556f6a9fd5425 | [
"Java"
] | 2 | Java | carlos114771/Tarea_Vanguardia | 9351c42edacd121551adba1929af797f7a9ddb48 | f2aaa30d6c94a5058e95f3b40ccb985be5477244 |
refs/heads/master | <file_sep>package net.vinid.demodaggerandroid.di
import android.content.Context
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import net.vinid.demodaggerandroid.MainApplication
import net.vinid.demodaggerandroid.di.activitymodule.MainActivityBuilder
import net.vinid.demodaggerandroid.di.viewmodelmodule.ViewModelModule
/**
* Created by <NAME> on 2/26/2020.
*/
@Component(
modules = [AppModule::class,
ViewModelModule::class,
MainActivityBuilder::class,
AndroidSupportInjectionModule::class]
)
interface AppComponent : AndroidInjector<MainApplication> {
@Component.Factory
interface Factory {
fun create(@BindsInstance applicationContext: Context): AppComponent
}
}<file_sep>package net.vinid.demodaggerandroid.di
import dagger.Module
import dagger.Provides
import net.vinid.demodaggerandroid.data.remote.ApiService
import net.vinid.demodaggerandroid.data.remote.ApiServiceImp
import net.vinid.demodaggerandroid.repository.Repository
import net.vinid.demodaggerandroid.repository.RepositoryImp
/**
* Created by <NAME> on 2/26/2020.
*/
@Module
class AppModule {
@Provides
fun provideApiService(apiServiceImp: ApiServiceImp): ApiService {
return apiServiceImp
}
@Provides
fun provideRepository(repositoryImp: RepositoryImp): Repository {
return repositoryImp
}
}<file_sep>package net.vinid.demodaggerandroid.repository
import android.util.Log
import net.vinid.demodaggerandroid.data.local.LocalDataSource
import net.vinid.demodaggerandroid.data.remote.RemoteDataSource
import javax.inject.Inject
/**
* Created by <NAME> on 2/26/2020.
*/
class RepositoryImp @Inject constructor(
private val localDataSource: LocalDataSource,
private val remoteDataSource: RemoteDataSource
) :Repository {
init {
Log.d("TAG","instance Repository")
}
override fun getAllData(): String{
return " Result: Repository"
}
}<file_sep>package net.vinid.demodaggerandroid.repository
/**
* Created by <NAME> on 2/27/2020.
*/
interface Repository {
fun getAllData(): String
}<file_sep>package net.vinid.demodaggerandroid.di.activitymodule
import dagger.Module
import dagger.android.ContributesAndroidInjector
import net.vinid.demodaggerandroid.MainActivity
@Module
interface MainActivityBuilder {
@ContributesAndroidInjector(modules = [MainActivityModule::class])
fun contributeMainActivity(): MainActivity
}<file_sep>package net.vinid.demodaggerandroid.di.activitymodule
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
import net.vinid.demodaggerandroid.MainActivity
import net.vinid.demodaggerandroid.di.viewmodelmodule.ViewModelKey
import net.vinid.demodaggerandroid.viewmodel.DataViewModel
@Module
interface MainActivityModule {
@Binds
fun bindMainActivity(activity: MainActivity): AppCompatActivity
@Binds
@IntoMap
@ViewModelKey(DataViewModel::class)
fun bindDataViewModel(
dataViewModel: DataViewModel
): ViewModel
}<file_sep>package net.vinid.demodaggerandroid.data.local
import android.util.Log
import javax.inject.Inject
/**
* Created by <NAME> on 2/26/2020.
*/
class LocalDataSource @Inject constructor(){
init {
Log.d("TAG","instance LocalDataSource")
}
fun getData():String {
return "Hello Local"
}
}<file_sep>package net.vinid.demodaggerandroid
import dagger.android.AndroidInjector
import dagger.android.support.DaggerApplication
import net.vinid.demodaggerandroid.di.DaggerAppComponent
/**
* Created by <NAME> on 2/26/2020.
*/
class MainApplication : DaggerApplication(){
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.factory().create(applicationContext)
}
}<file_sep>package net.vinid.demodaggerandroid.data.remote
import android.util.Log
import net.vinid.demodaggerandroid.data.remote.ApiService
import javax.inject.Inject
/**
* Created by <NAME> on 2/26/2020.
*/
class RemoteDataSource @Inject constructor(
private val apiService: ApiService
){
init {
Log.d("TAG","instance RemoteDataSource")
}
fun getData():String{
return "Hello Remote"
}
}<file_sep>package net.vinid.demodaggerandroid
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import dagger.android.support.DaggerAppCompatActivity
import net.vinid.demodaggerandroid.di.viewmodelmodule.ViewModelFactory
import net.vinid.demodaggerandroid.viewmodel.DataViewModel
import javax.inject.Inject
class MainActivity : DaggerAppCompatActivity() {
@Inject
lateinit var viewModelFactory: ViewModelFactory
private val dataViewModel : DataViewModel by lazy {
ViewModelProvider(this,viewModelFactory).get(DataViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_main)
super.onCreate(savedInstanceState)
dataViewModel.dataViewModel()
dataViewModel.data.observe(this, Observer<String> { data ->
Log.d("TAG",data)
})
}
}
<file_sep>package net.vinid.demodaggerandroid.data.remote
/**
* Created by <NAME> on 2/26/2020.
*/
interface ApiService {
fun getData(): String
}<file_sep>include ':app'
rootProject.name='DemoDaggerAndroid'
<file_sep>package net.vinid.demodaggerandroid.di
import dagger.Binds
import dagger.Module
import net.vinid.demodaggerandroid.data.remote.ApiService
import net.vinid.demodaggerandroid.data.remote.ApiServiceImp
import net.vinid.demodaggerandroid.repository.Repository
import net.vinid.demodaggerandroid.repository.RepositoryImp
/**
* Created by <NAME> on 2/27/2020.
*/
@Module
interface BIindingModule {
@Binds
fun bindApiService(apiServiceImp: ApiServiceImp): ApiService
@Binds
fun bindRepository(repositoryImp: RepositoryImp): Repository
}<file_sep># DaggeAndroidSample
Dagger Android Practice
<file_sep>package net.vinid.demodaggerandroid.data.remote
import android.util.Log
import net.vinid.demodaggerandroid.data.remote.ApiService
import javax.inject.Inject
/**
* Created by <NAME> on 2/26/2020.
*/
class ApiServiceImp @Inject constructor() :
ApiService {
init {
Log.d("TAG","instance ApiServiceImp")
}
override fun getData(): String {
return "ApiServiceImp"
}
}<file_sep>package net.vinid.demodaggerandroid.viewmodel
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import net.vinid.demodaggerandroid.repository.Repository
import javax.inject.Inject
/**
* Created by <NAME> on 2/26/2020.
*/
class DataViewModel @Inject constructor(
private val repository: Repository
) : ViewModel(){
private val _data = MutableLiveData<String>()
val data :LiveData<String>
get() = _data
init {
Log.d("TAG","instance DataViewModel")
}
private val compositeDisposable: CompositeDisposable = CompositeDisposable()
fun dataViewModel(){
_data.value = repository.getAllData()
}
override fun onCleared() {
compositeDisposable.clear()
super.onCleared()
}
} | 269d602b9cf4599848f4d0c849b5393e60dba279 | [
"Markdown",
"Kotlin",
"Gradle"
] | 16 | Kotlin | lieuvan94/DemoDaggerAndroid | 93c4adb1d5e49d8cdccda5c96fdba06f290f6c66 | e97d1095988ef04bf29322b3bee301c31fe09c3b |
refs/heads/master | <file_sep>package com.study.pattern.behavioraltype.chain;
/**
* 责任链模式(Chain of Responsibility)
* Created by panxiaoming on 17/1/27.
*/
public class MyHandler extends AbstractHandler implements Handler {
private String name;
public MyHandler(String name) {
this.name = name;
}
@Override
public void operator() {
System.out.println(name + "deal!");
if(getHandler() != null) {
getHandler().operator();
}
}
}
<file_sep>package com.study.pattern.behavioraltype.strategy;
/**
* 策略模式
* Created by panxiaoming on 17/1/27.
*/
public abstract class AbstractCalculator {
public int[] split(String exp, String opt) {
String array[] = exp.split(opt);
int arrayInt[] = new int[2];
arrayInt[0] = Integer.parseInt(array[0]);
arrayInt[1] = Integer.parseInt(array[1]);
return arrayInt;
}
}
<file_sep>package com.study.algorithm.search;
/**
* 二分查找
* Created by panxiaoming on 17/1/31.
*/
public class BinarySearch {
public int search(int[] a, int key) {
int low = 0;
int high = a.length-1;
int mid = 0;
while(low <= high) {
mid = (low+high)/2;
if(a[mid] == key)
return mid;
if(a[mid] < key)
high = mid-1;
if(a[mid] > key)
low = mid+1;
}
return -1;
}
}
<file_sep>package com.study.pattern.behavioraltype.visitor;
/**
* 访问者模式(Visitor)
* Created by panxiaoming on 17/1/27.
*/
public class MyVisitor implements Visitor {
@Override
public void visit(Subject subject) {
System.out.println("visit the subject: " + subject.getSubject());
}
}
<file_sep>package com.study.algorithm.sort;
import java.util.ArrayList;
import java.util.List;
/**
* 冒泡排序
* 平均时间:O(n2) 最差时间:O(n2) 稳定度:稳定 额外空间:O(1)
* n小的时候效率较高
* Created by panxiaoming on 17/1/30.
*/
public class BubbleSort {
public static void sort(List<Integer> list, int n) {
int i, j, lastSwap, tmp;
for(j=n-1; j>0; j=lastSwap) {
lastSwap = 0;
for(i=0; i<j; i++) {
if(list.get(i) > list.get(i+1)) {
tmp = list.get(i);
list.set(i, list.get(i+1));
list.set(i+1, tmp);
lastSwap = i;
}
}
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(-3);
list.add(192);
list.add(10);
list.add(123);
sort(list, list.size());
for(int i=0; i<list.size(); i++) {
System.out.print(list.get(i)+" ");
}
System.out.println();
}
}
<file_sep>package com.study.pattern.createtype.singleton;
/**
* 将创建和getInstance()分开,单独为创建加synchronized关键字
* Created by panxiaoming on 17/1/26.
*/
public class Singleton2 {
private static Singleton2 instance = null;
private Singleton2() {
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new Singleton2();
}
}
public static Singleton2 getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
}
<file_sep>package com.study.struct;
import java.util.LinkedList;
import java.util.List;
/**
* 二叉树
* Created by panxiaoming on 17/1/31.
*/
public class BinaryTree {
public static List<Node> nodeList = null;
public static void createBinTree(int[] array) {
nodeList = new LinkedList<Node>();
//将一个数组的值依次转换为Node节点
for(int nodeIndex=0; nodeIndex<array.length; nodeIndex++) {
nodeList.add(new Node(array[nodeIndex]));
}
//对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树
for(int parentIndex=0; parentIndex<array.length/2-1; parentIndex++) {
nodeList.get(parentIndex).leftChild = nodeList.get(parentIndex*2+1);
nodeList.get(parentIndex).rightChild = nodeList.get(parentIndex*2+2);
}
//最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
int lastParentIndex = array.length/2-1;
nodeList.get(lastParentIndex).leftChild = nodeList.get(lastParentIndex*2+1);
//右孩子,如果数组的长度为奇数才建立右孩子
if(array.length%2 == 1) {
nodeList.get(lastParentIndex).rightChild = nodeList.get(lastParentIndex*2+2);
}
}
//先序遍历
public static void preOrder(Node node) {
if(node == null)
return;
System.out.print(node.data + " ");
preOrder(node.leftChild);
preOrder(node.rightChild);
}
//中序遍历
public static void inOrder(Node node) {
if(node == null)
return;
inOrder(node.leftChild);
System.out.print(node.data + " ");
inOrder(node.rightChild);
}
//后序遍历
public static void postOrder(Node node) {
if(node == null)
return;
postOrder(node.leftChild);
postOrder(node.rightChild);
System.out.print(node.data + " ");
}
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
BinaryTree.createBinTree(array);
Node root = nodeList.get(0);
System.out.println("先序遍历:");
preOrder(root);
System.out.println();
System.out.println("中序遍历:");
inOrder(root);
System.out.println();
System.out.println("后序遍历:");
postOrder(root);
}
}
<file_sep>package com.study.pattern.createtype.factorymethod;
/**
* Created by panxiaoming on 17/1/26.
*/
public interface Sender {
public void send();
}
<file_sep>package com.study.pattern.structuraltype.adapter;
/**
* Created by panxiaoming on 17/1/27.
*/
public class Source {
public void method1() {
System.out.println("this is original method!");
}
}
<file_sep>package com.study.pattern.behavioraltype.templatemethod;
/**
* 模板方法模式
* Created by panxiaoming on 17/1/27.
*/
public class Plus extends AbstractCalculator {
@Override
public int calculate(int num1, int num2) {
return num1 + num2;
}
}
<file_sep>package com.study.pattern.structuraltype.adapter;
/**
* Created by panxiaoming on 17/1/27.
*/
public interface Targetable {
//与原类中的方法相同
public void method1();
//新类的方法
public void method2();
}
<file_sep>package com.study.pattern.createtype.abstractfactory;
import com.study.pattern.createtype.factorymethod.Sender;
/**
* Created by panxiaoming on 17/1/26.
*/
public interface Provider {
public Sender produce();
}
<file_sep>package com.study.pattern.behavioraltype.chain;
/**
* Created by panxiaoming on 17/1/27.
*/
public interface Handler {
public void operator();
}
<file_sep>package com.study.algorithm.sort;
import java.util.ArrayList;
import java.util.List;
/**
* 快速排序
* 平均时间:O(nlogn) 最差时间:O(n2) 稳定度:不稳定 额外空间:O(nlogn)
* n大的时候效率较高
* Created by panxiaoming on 17/1/30.
*/
public class QuickSort {
public static int partition(List<Integer> list, int start, int end, int pivotIndex) {
int pivot = list.get(pivotIndex);
swap(list, pivot, end);
int storeIndex = start;
for(int i=start; i<end; i++) {
if(list.get(i) < pivot) {
swap(list, i, storeIndex);
storeIndex++;
}
}
swap(list, storeIndex, end);
return storeIndex;
}
public static void swap(List<Integer> list, int i, int j) {
Integer tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
public static int mpartition(List<Integer> list, int l, int r) {
int pivot = list.get(l);
while(l < r) {
while(l<r && pivot<=list.get(r))
r--;
if(l < r)
list.set(l++, list.get(r));
while(l<r && pivot>list.get(l))
l++;
if(l < r)
list.set(r--, list.get(l));
}
list.set(l, pivot);
return l;
}
public static void sort(List<Integer> list, int l, int r) {
if(l < r) {
int q = mpartition(list, l, r);
sort(list, l, q-1);
sort(list, q+1, r);
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(-3);
list.add(192);
list.add(10);
list.add(123);
sort(list, 0, list.size()-1);
for(int i=0; i<list.size(); i++) {
System.out.print(list.get(i)+" ");
}
System.out.println();
}
}
<file_sep>package com.study.pattern.behavioraltype.memento;
/**
* Created by panxiaoming on 17/1/27.
*/
public class Test {
public static void main(String[] args) {
//创建原始类
Original origi = new Original("egg");
//创建备忘录
Storage storage = new Storage(origi.createMemento());
//修改原始类的状态
System.out.println("初始化状态为:" + origi.getValue());
origi.setValue("pan");
System.out.println("修改后状态为:" + origi.getValue());
origi.restoreMemento(storage.getMemento());
System.out.println("恢复后状态为:" + origi.getValue());
}
}
<file_sep>package com.study.algorithm.sort;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 基数排序
* 平均时间:O(logRB) 最差时间:O(logRB) 稳定度:稳定 额外空间:O(n)
* B是真数(0-9),R是基数(个十百)
* Created by panxiaoming on 17/1/31.
*/
public class RadixSort {
/**
* 基数排序的步骤:以整数为例,将整数按十进制位划分,从低位到高位执行以下过程。
* 1. 从个位开始,根据0~9的值将数据分到10个桶桶,例如12会划分到2号桶中。
* 2. 将0~9的10个桶中的数据顺序放回到数组中。
* 重复上述过程,一直到最高位。
* 上述方法称为LSD(Least significant digital),还可以从高位到低位,称为MSD。
*/
//获得某个数字的第pos位的值
public static int getNumInPos(int num, int pos) {
int tmp = 1;
for(int i=0; i<pos-1; i++)
tmp *= 10;
return (num/tmp) % 10;
}
public static void sort(List<Integer> pDataArray, int iDataNum) {
Map<Integer, List> map = new HashMap<>();
for(int i=0; i<10; i++) {
List<Integer> list = new ArrayList<>();
for(int j=0; j<iDataNum+1; j++)
list.add(0);
map.put(i, list);
}
//从个位开始
for(int pos=1; pos<=5; pos++) {
for(int i=0; i<iDataNum; i++) {
int num = Math.abs(getNumInPos(pDataArray.get(i), pos));
List<Integer> list = map.get(num);
int index = list.get(0)+1;
list.set(0, index);
list.set(index, pDataArray.get(i));
}
for(int i=0, j=0; i<10; i++) {
List<Integer> list = map.get(i);
for(int k=1; k<=list.get(0); k++) {
pDataArray.set(j++, list.get(k));
}
list.set(0, 0);
}
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(192);
list.add(10);
list.add(123);
sort(list, list.size());
for(int i=0; i<list.size(); i++) {
System.out.print(list.get(i)+" ");
}
System.out.println();
}
}
<file_sep>package com.study.pattern.createtype.prototype;
import java.io.Serializable;
/**
* Created by panxiaoming on 17/1/27.
*/
public class SerializableObject implements Serializable {
private static final long serialVersionUID = 1L;
}
<file_sep>package com.study.algorithm.sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 归并排序
* 平均时间:O(nlogn) 最差时间:O(nlogn) 稳定度:稳定 额外空间:O(1)
* n大的时候效率较高
* Created by panxiaoming on 17/1/31.
*/
public class MergeSort {
public static void mergeArray(List<Integer> list, int first, int mid, int last, List<Integer> tmp) {
int i=first, j=mid+1;
int m=mid, n=last;
int k=0;
while(i<=m && j<=n) {
if(list.get(i) < list.get(j))
tmp.set(k++, list.get(i++));
else
tmp.set(k++, list.get(j++));
}
while(i <= m)
tmp.set(k++, list.get(i++));
while(j <= n)
tmp.set(k++, list.get(j++));
for(i=0; i<k; i++) {
list.set(first+i, tmp.get(i));
}
}
public static void sort(List<Integer> list, int first, int last, List<Integer> tmp) {
if(first < last) {
int mid = (first+last)/2;
//左边有序
sort(list, first, mid, tmp);
//右边有序
sort(list, mid+1, last, tmp);
//将两个有序数列合并
mergeArray(list, first, mid, last, tmp);
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> tmp = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
list.add(1);
list.add(-3);
list.add(192);
list.add(10);
list.add(123);
sort(list, 0, list.size()-1, tmp);
for(int i=0; i<list.size(); i++) {
System.out.print(list.get(i)+" ");
}
System.out.println();
}
}
<file_sep>package com.study.algorithm.graph;
/**
* Dijkstra算法
* 最短路径
* Created by panxiaoming on 17/1/31.
*/
public class Dijkstra {
private int mEdgNum;
private char[] mVexs;
private int[][] mMatrix;
private static final int INF = Integer.MAX_VALUE;
/**
*
* @param vs 起始顶点(start vertex)。即计算"顶点vs"到其它顶点的最短路径。
* @param prev 前驱顶点数组。即,prev[i]的值是"顶点vs"到"顶点i"的最短路径所经历的全部顶点中,位于"顶点i"之前的那个顶点。
* @param dist 长度数组。即,dist[i]是"顶点vs"到"顶点i"的最短路径的长度。
*/
public void dijkstra(int vs, int[] prev, int[] dist) {
// flag[i]=true表示"顶点vs"到"顶点i"的最短路径已成功获取
boolean[] flag = new boolean[mVexs.length];
//初始化
for(int i=0; i<mVexs.length; i++) {
flag[i] = false; // 顶点i的最短路径还没获取到。
prev[i] = 0; // 顶点i的前驱顶点为0。
dist[i] = mMatrix[vs][i]; // 顶点i的最短路径为"顶点vs"到"顶点i"的权。
}
//对"顶点vs"自身进行初始化
flag[vs] = true;
dist[vs] = 0;
// 遍历mVexs.length-1次;每次找出一个顶点的最短路径。
int k=0;
for(int i=1; i<mVexs.length; i++) {
//寻找当前最小路径
//即,在未获取最短路径的顶点中,找到离vs最近的顶点(k)。
int min = INF;
for(int j=0; j<mVexs.length; j++) {
if(!flag[j] && dist[j]<min) {
min = dist[j];
k = j;
}
}
// 标记"顶点k"为已经获取到最短路径
flag[k] = true;
//修正当前最短路径和前驱顶点
//即,当已经"顶点k的最短路径"之后,更新"未获取最短路径的顶点的最短路径和前驱顶点"。
for(int j=0; j<mVexs.length; j++) {
int tmp = (mMatrix[k][j]==INF)?INF:(min+mMatrix[k][j]);
if(!flag[i] && tmp<dist[j]) {
dist[j] = tmp;
prev[j] = k;
}
}
}
System.out.printf("dijkstra(%c): \n", mVexs[vs]);
for(int i=0; i<mVexs.length; i++)
System.out.printf(" shortest(%c, %c)=%d\n", mVexs[vs], mVexs[i], dist[i]);
}
}
<file_sep>package com.study.pattern.behavioraltype.iterator;
/**
* Created by panxiaoming on 17/1/27.
*/
public interface Collection {
public Iterator iterator();
//取得集合元素
public Object get(int i);
//取得集合大小
public int size();
}
<file_sep># JavaDesignPattern
包含java编写的设计模式的示例,以及一些常见的算法
<file_sep>package com.study.pattern.behavioraltype.interpreter;
/**
* Created by panxiaoming on 17/1/27.
*/
public interface Expression {
public int interpret(Context context);
}
<file_sep>package com.study.pattern.behavioraltype.visitor;
/**
* Created by panxiaoming on 17/1/27.
*/
public interface Visitor {
public void visit(Subject sub);
}
<file_sep>package com.study.struct;
import java.io.Serializable;
/**
* 分页算法
* Created by panxiaoming on 17/3/3.
*/
public class Pageable implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 每页默认的项数(10)
*/
public static final int DEFAULT_ITEMS_PER_PAGE = 10;
/**
* 滑动窗口默认的大小(7)
*/
public static final int DEFAULT_SLIDER_SIZE = 7;
/**
* 表示项数未知(Integer.MAX_VALUE)
*/
public static final int UNKNOWN_ITEMS = Integer.MAX_VALUE;
/**
* 状态量
*/
private int page; //当前页码
private int items; //总共项数
private int itemsPerPage; //每页项数
private int startRow; //开始条数
private int endRow; //结束条数
/**
* 创建一个分页器,初始项数为无限大,默认每页显示10项
*/
public Pageable() {
this(10);
}
/**
* 创建一个分页器,初始项数为无限大,指定每页项数
* @param itemsPerPage
*/
public Pageable(int itemsPerPage) {
this(itemsPerPage, UNKNOWN_ITEMS);
}
/**
* 创建一个分页器,初始项数为无限大,指定每页项数
* @param itemsPerPage
* @param items
*/
public Pageable(int itemsPerPage, int items) {
this.items = (items>=0)?items:0;
this.itemsPerPage = (itemsPerPage>0)?itemsPerPage:DEFAULT_ITEMS_PER_PAGE;
this.page = calcPage(0);
}
/**
* 取得总页数
* @return
*/
public int getPages() {
if(items <= 0)
return 1;
return (int)Math.ceil((double)items/itemsPerPage);
}
/**
* 取得当前页
* @return
*/
public int getPage() {
return page;
}
/**
* 设置并取得当前页
* @param page
* @return
*/
public int setPage(int page) {
return (this.page = calcPage(page));
}
/**
* 取得总项数
* @return
*/
public int getItems() {
return items;
}
/**
* 设置并取得总项数。如果指定的总项数小于0,则被看作0
* @param items
* @return
*/
public int setItems(int items) {
this.items = (items>=0)?items:0;
setPage(page);
return this.items;
}
/**
* 取得每页项数
* @return
*/
public int getItemsPerPage() {
return itemsPerPage;
}
/**
* 设置并取得每页项数。如果指定的每页项数小于等于0,则使用默认值DEFAULT_ITEMS_PER_PAGE
* 并调整当前页使之在改变每页项数前后显示相同的项
* @param itemsPerPage
* @return
*/
public int setItemsPerPage(int itemsPerPage) {
int tmp = this.itemsPerPage;
this.itemsPerPage = (itemsPerPage>0)?itemsPerPage:DEFAULT_ITEMS_PER_PAGE;
if(page > 0)
setPage((int)(((double)(page-1)*tmp)/this.itemsPerPage)+1);
return this.itemsPerPage;
}
/**
* 取得当前页的长度,即当前页的实际项数
* @return
*/
public int getLength() {
if(page > 0)
return Math.min(itemsPerPage*page, items) - (itemsPerPage*(page-1));
else
return 0;
}
/**
* 计算页数,但不改变当前页
* @param page
* @return
*/
protected int calcPage(int page) {
int pages = getPages();
if(pages > 0) {
return (page < 1)?1:(page>pages?pages:page);
}
return 0;
}
/**
* 取得首页页码
* @return
*/
public int getFirstPage() {
return calcPage(1);
}
/**
* 取得末页页码
* @return
*/
public int getLastPage() {
return calcPage(getPages());
}
/**
* 取得前一页页码
* @return
*/
public int getPreviousPage() {
return calcPage(page - 1);
}
/**
* 取得前n页页码
* @param n
* @return
*/
public int getPreviousPage(int n) {
return calcPage(page - n);
}
/**
* 取得后一页页码
* @return
*/
public int getNextPage() {
return calcPage(page+1);
}
/**
* 取得后n页页码
* @param n
* @return
*/
public int getNextPage(int n) {
return calcPage(page + n);
}
/**
* 判断指定页码是否被禁止,也就是说指定页码超出了范围或等于当前页码
* @param page
* @return
*/
public boolean isDisabledPage(int page) {
return ((page<1)||(page>getPages())||(page==this.page));
}
/**
* 创建副本
* @return
*/
public Object clone() {
try {
return super.clone();
} catch(CloneNotSupportedException e) {
return null;
}
}
/**
* 设置开始条数
* @param startRow
*/
public void setStartRow(int startRow) {
this.startRow = startRow;
}
/**
* 设置结束条数
* @param endRow
*/
public void setEndRow(int endRow) {
this.endRow = endRow;
}
/**
* 获得起始条数
* @return
*/
public int getStartRow() {
if(page > 0)
startRow = (page-1)*itemsPerPage + 1;
else
startRow = 0;
return startRow;
}
/**
* 获得结束条数
* @return
*/
public int getEndRow() {
if(page > 0)
endRow = Math.min(itemsPerPage*page, items);
else
endRow = 0;
return endRow;
}
}
| b2babd9d050a11ef13feaf8f4a01e2ed173e1745 | [
"Markdown",
"Java"
] | 24 | Java | termonitor/JavaDesignPattern | c56c82212d757ab63c3c1e19afac2fe6aabd6b68 | d57119293eeceba16a466d440b3fb8daf6ef2272 |
refs/heads/master | <file_sep>package day29;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class ChangeStreamDemo1 {
public static void main(String[] args) throws Exception {
OutputStreamWriter ou = new OutputStreamWriter(new FileOutputStream("d:\\javastest\\cd1.txt"),"gbk");
ou.write("柴金海牛逼");
ou.flush();
ou.close();
// System.out.println(ou.getEncoding());
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("d:\\javastest\\cd1.txt"));
out.write(1233);
out.flush();
out.close();
// System.out.println(out.getEncoding());
FileInputStream in = new FileInputStream("D:\\javastest\\cd1.txt");
int read = 0;
while ((read =in.read())!=-1){
System.out.println(read);
}
}
}<file_sep>package day30;
public class ThreadDemo1 extends Thread {
@Override
public void run() {
for (int i =0;i<=100;i++){
System.out.println(Thread.currentThread().getName()+i+"岁了");
}
}
}
<file_sep>package day29;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class DataSocketDemo1 {
public static void main(String[] args) throws Exception {
DatagramSocket datagramSocket = new DatagramSocket();
byte[] by ="小伙子6666".getBytes();
int length = by.length;
InetAddress Address =InetAddress.getByName("192.168.0.107");
int port =10010;
DatagramPacket packet =new DatagramPacket(by,length,Address,port);
datagramSocket.send(packet);
datagramSocket.close();
}
}
<file_sep>package day32;
import java.util.TimerTask;
public class Timethings extends TimerTask {
@Override
public void run() {
System.out.println("我不信!!!!!!");
}
}
<file_sep>package day27;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class InputDemo2 {
public static void main(String[] args)throws Exception {
FileInputStream in =new FileInputStream("d:\\javastest\\test1.txt");
FileOutputStream out =new FileOutputStream("d:\\javastest\\testinputdemo2");
byte[] by =new byte[10];
int read =0;
while((read=in.read(by))!=-1){
out.write(by);
System.out.println(new String(by,0,read));
}
}
}
<file_sep>package day31;
import java.util.Scanner;
public class Thread3 implements Runnable{
Scanner scanner =new Scanner(System.in);
public synchronized void run() {
// while(true){
System.out.println(Thread.currentThread().getName()+"想要取走多少");
int get =scanner.nextInt();
System.out.println("您和您的爱人当前有"+(10000-get)+"元");
}
}
//}
<file_sep>package day27;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyDemo1 {
public static void main(String[] args) throws Exception {
FileInputStream in =new FileInputStream("d:\\javastest\\1.bmp");
FileOutputStream out =new FileOutputStream("d:\\javastest\\2.bmp");
int read =0;
while((read=in.read())!=-1){
out.write(read);
}
in.close();
out.close();
}
}
<file_sep>package day29;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server2 {
public static void main(String[] args)throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("您好,服务器已经响应;");
Socket accept = serverSocket.accept();
InputStream inputStream = accept.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line =bufferedReader.readLine();
System.out.println(line);
accept.shutdownInput();
OutputStream outputStream = accept.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeUTF("你好啊,小老弟");
objectOutputStream.flush();
accept.shutdownOutput();
}
}
<file_sep>package day27;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class InputbarrayDemo {
public static void main(String[] args) throws Exception {
FileInputStream in =new FileInputStream("D:\\javastest\\test1.txt");
FileOutputStream out =new FileOutputStream("d:\\javastest\\testbarr.txt");
byte[] by =new byte[10];
int read =in.read(by);
System.out.println(new String(by));
}
}
<file_sep>package day31;
public class Thread3Demo {
public static void main(String[] args) {
Thread3 th =new Thread3();
Thread t1 =new Thread(th);
Thread t2 =new Thread(th);
t1.setName("张三");
t2.setName("张三的妻子—柴金海");
t1.start();
t2.start();
}
}
<file_sep>package day32;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CallableDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.submit(new Mycallable("西门庆"));
pool.submit(new Mycallable("大牙"));
pool.submit(new Mycallable("汤斌"));
pool.shutdown();
}
}
| 487994679ce9b0bb30c8ab6e185c6b7ac0da6f83 | [
"Java"
] | 11 | Java | ydl1997/learn- | 83839e606312d93680d644cbca73c09e323c4930 | 4e552fc484fbd5be7d4c60d69b9f734987a46271 |
refs/heads/packaging | <file_sep>#!/bin/sh
VERSION=$(git describe --exact --match "v[0-9]*" HEAD 2>/dev/null)
DO_RELEASE=1 #Assume we're going to release this commit.
if [ "$VERSION" == '' ]; then echo "Commit is not tagged with a version."; DO_RELEASE=0; fi
if [ "$CI_BRANCH" != "$VERSION" ]; then echo "CI branch '$CI_BRANCH' is not version '$VERSION'."; DO_RELEASE=0; fi
if [ $DO_RELEASE -eq 1 ]
then
pip install awscli
echo "Release $VERSION";
mkdir -p release/$VERSION
cp -R dist/* release/$VERSION
aws s3 sync release/$VERSION s3://$S3_BUCKET/$VERSION
fi<file_sep>import axios from 'axios';
const EdbApi = axios.create({
baseURL: 'http://api.theerrordb.com',
headers: {
Accept: 'application/json',
},
});
export default EdbApi;
<file_sep>import Vue from 'vue';
import App from './App';
Vue.config.productionTip = false;
// The following element creation allows is to inline CSS in the app.js artifact
// so that we don't also need to call the app.css styles.
const appDiv = document.createElement('div');
appDiv.setAttribute('id', 'errordb');
// const appEl = document.currentScript.insertBefore(appDiv, document.currentScript);
const appEl = document.currentScript.parentNode.insertBefore(
appDiv, document.currentScript.nextSibling,
);
/* eslint-disable no-new */
new Vue({
el: appEl,
render: h => h(App),
});
| 290e83794b98ab3a60bbc4163ef2497d9889d7a5 | [
"JavaScript",
"Shell"
] | 3 | Shell | devjack/errordb | 4efa1f848920f5f4243399057cf78db686116053 | c125134c9cbc19e4dd59476d7e8a56a8704dde12 |
refs/heads/main | <repo_name>wasbass/CrawlingProfessor<file_sep>/README.md
Crawling NTU Econ professors and their domain.
<file_sep>/NtuEconProfessors.py
import urllib.request as req
from bs4 import BeautifulSoup
import os
import time
import csv
os.chdir("D:\python\gitrepo")
host_key = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"
###請求標頭(request header)含有能令網路協議同級層(peer)識別發出該用戶代理 (en-US)請求的軟體類型或版本號、該軟體使用的作業系統、還有軟體開發者的字詞串。
###網路瀏覽器常用的格式:User-Agent: Mozilla/<version> (<system-information>) <platform> (<platform-details>) <extensions>
###從開發人員工具-Network的html檔案中可以查到
init_url = "http://www.econ.ntu.edu.tw"
init_sub = "/zh_tw/people/faculty0/faculty1/"
url = init_url + init_sub
res = req.Request(url , headers = {"User-Agent":host_key})
with req.urlopen(res) as response:
data0 = response.read().decode('utf-8')
soup = BeautifulSoup(data0 , "html.parser")
profile_head = soup.find_all("ul",class_="i-member-profile-list")
L_suburl = []
num = 0
for p0 in profile_head :
head_data = p0.find( "span" , class_ = "i-member-value member-data-value-name")
sub = head_data.a.get("href")
L_suburl.append(sub)
num += 1
print("num = {}".format(num))
profile = ""
def get_text(item : str ) -> str :
global profile
c = "member-data-value-" + item
try:
t = profile.find("td" , class_ = c).text
except:
t = "NULL"
return t
def intoCSV( L:list):
with open(".\EconProfessors.csv", "a", newline='', encoding='utf-8-sig') as file:
writer = csv.writer(file ,delimiter=',')
writer.writerow(L)
file.close()
n = 0
for p1 in range(num):
sub = L_suburl.pop(0)
url = init_url + sub
res = req.Request(url , headers = {"User-Agent":host_key})
with req.urlopen(res) as response:
data1 = response.read().decode('utf-8')
soup = BeautifulSoup(data1 , "html.parser")
profile = soup.find("div",class_="show-member")
name = get_text("name")
title = get_text("job-title")
expertise = get_text("research-expertise")
edu = get_text("education")
web = get_text("website")
L = [name,title,expertise,edu,web]
intoCSV(L)
print("-", end = "")
n += 1
if n%10 == 0 :
print( n ,"\n")
time.sleep(2)
| 7f7253d3a2aac8905b1bd35553743885aa1cdd94 | [
"Markdown",
"Python"
] | 2 | Markdown | wasbass/CrawlingProfessor | 56e8662688601fa030178a8b7fe771bd0ed3bbf1 | 1a8967c00ff02ec27e006096a67326a1d654aa65 |
refs/heads/main | <file_sep>from flask import Flask, request, jsonify
from flask_cors import CORS
from helpers.database import isInDatabase, getFromDatabase, getExistingTags
from helpers.youTube import getYoutubeVideos
app = Flask(__name__)
CORS(app)
@app.route("/search", methods=["POST"])
def search():
response = "Nothing happened"
search = request.form["q"]
if isInDatabase(search):
response = getFromDatabase(search)
else:
getYoutubeVideos(search)
response = {str(search): "is not in the db"}
return response
@app.after_request
def after_request(response):
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE")
return response
if __name__ == "__main__":
app.run()<file_sep>certifi==2020.12.5
click==7.1.2
ffmpy==0.3.0
Flask==1.1.2
Flask-Cors==3.0.10
gunicorn==20.0.4
h11==0.12.0
httpcore==0.12.3
httpx==0.16.1
idna==3.1
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
PyMySQL==1.0.2
pytube==10.4.1
rfc3986==1.4.0
six==1.15.0
sniffio==1.2.0
typing-extensions==3.7.4.3
Werkzeug==1.0.1
youtube-search-python==1.3.9
<file_sep>from youtubesearchpython import VideosSearch
search = VideosSearch("python")
response = search.result()["result"]
while len(response) < 10:
search.next()
response += search.result()["result"]
print(len(response))
# id,views,title,search,video_thumbnail,duration,channel,channel_thumbnail
print((response[0]["link"]))
print((response[0]["viewCount"]["text"]))
print((response[0]["title"]))
print(str("Cloud SQL"))
print((response[0]["thumbnails"][0]["url"]))
print((response[0]["duration"]))
print((response[0]["channel"]["name"]))
print((response[0]["channel"]["thumbnails"][0]["url"]))<file_sep>import numpy as np
np.set_printoptions(threshold=np.inf) # Showing all the array in Console
import matplotlib.pyplot as plt
import pandas as pd
import pickle
# ------ Importing the DataSet
dataset = pd.read_csv("./voice.csv")
col = ["sp.ent", "meandom", "mindom", "maxdom", "dfrange", "modindx"]
dataset.drop(col, inplace=True, axis=1)
#####################################################
# #
# Starting with Sets and Pre-Processing #
# #
#####################################################
# ------ Separating the Independent and Dependent Variables
# Getting all Columns, except the last one with the genders
X = dataset.iloc[:, :-1].values
# Getting the last column
y = dataset.iloc[:, -1].values
# No Need of Taking Care of Missing Data :)
# ------ Encoding Categorical Data of the Dependent Variable
# male -> 1
# female -> 0
from sklearn.preprocessing import LabelEncoder
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
# ------ Splitting the Dataset into the Training Set and Test Set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)
# ------- Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
#####################################################
# #
# Kernel SVM - RBF #
# #
#####################################################
# Fitting Kernel SVM to the Training set
from sklearn.svm import SVC
classifier = SVC(kernel="rbf", random_state=0)
classifier.fit(X, y)
import pickle
f = open("./model.pickle", "wb")
pickle.dump(classifier, f)
<file_sep>###################################################################### Para descargar mp4
from pytube import YouTube
import os
def downloadYouTube(videourl, path):
yt = YouTube(videourl)
yt = yt.streams.filter(only_audio=True).first()
if not os.path.exists(path):
os.makedirs(path)
yt.download(path)
downloadYouTube("https://www.youtube.com/watch?v=WWy7ZWQiG8s", "./dl")
###################################################################### Para convertir a wav
import os
import ffmpy
inputdir = "/home/cristina/Desktop/hack/"
outdir = "/home/cristina/Desktop/hack/"
for filename in os.listdir(inputdir):
actual_filename = filename[:-4]
if filename.endswith(".mp4"):
os.system(
"ffmpeg -i {} -acodec pcm_s16le -ar 16000 {}/{}.wav".format(
filename, outdir, actual_filename
)
)
else:
continue
##################################################################### Para cortar audio
from pydub import AudioSegment
import math
class SplitWavAudioMubin:
def __init__(self, folder, filename):
self.folder = folder
self.filename = filename
self.filepath = folder + "/" + filename
self.audio = AudioSegment.from_wav(self.filepath)
def get_duration(self):
return self.audio.duration_seconds
def single_split(self, from_min, to_min, split_filename):
t1 = from_min * 60 * 1000
t2 = to_min * 60 * 1000
split_audio = self.audio[t1:t2]
split_audio.export(self.folder + "/" + split_filename, format="wav")
def multiple_split(self, min_per_split):
total_mins = math.ceil(self.get_duration() / 60)
for i in range(0, total_mins, min_per_split):
split_fn = str(i) + "_" + self.filename
self.single_split(i, i + min_per_split, split_fn)
print(str(i) + " Done")
if i == total_mins - min_per_split:
print("All splited successfully")
# # folder = '/home/cristina/Desktop/hack'
filename = "5_ESSENTIAL_Tools_for_New_Coders.wav"
# # split_wav = SplitWavAudioMubin(folder, file)
split_filename = "split_" + filename
# # split_wav.single_split(1,2,split_filename)
###################################################################### Para extraer frecuencias
# Load the required libraries:
# * scipy
# * numpy
# * matplotlib
from scipy.io import wavfile
from matplotlib import pyplot as plt
import numpy as np
# # Load the data and calculate the time of each sample
samplerate, data = wavfile.read(split_filename)
import sys
from aubio import source, pitch
win_s = 4096
hop_s = 512
s = source(split_filename, samplerate, hop_s)
samplerate = s.samplerate
tolerance = 0.8
pitch_o = pitch("yin", win_s, hop_s, samplerate)
pitch_o.set_unit("midi")
pitch_o.set_tolerance(tolerance)
pitches = []
confidences = []
total_frames = 0
while True:
samples, read = s()
pitch = pitch_o(samples)[0]
pitches += [pitch]
confidence = pitch_o.get_confidence()
confidences += [confidence]
total_frames += read
if read < hop_s:
break
k_pitches = np.array(pitches) / 1000.0
def FeatureSpectralFlatness(X, f_s):
norm = X.mean(axis=0, keepdims=True)
norm[norm == 0] = 1
vtf = np.exp(X.mean(axis=0, keepdims=True)) / norm
return np.squeeze(vtf, axis=0)
def spectral_centroid(x, samplerate):
magnitudes = np.abs(np.fft.rfft(x))
length = len(x)
freqs = np.abs(np.fft.fftfreq(length, 1.0 / samplerate)[: length // 2 + 1])
magnitudes = magnitudes[: length // 2 + 1]
return np.sum(magnitudes * freqs) / np.sum(magnitudes)
import csv
import scipy
from scipy import stats
import urllib.parse
urllib.parse.quote("châteu", safe="")
import parselmouth
snd = parselmouth.Sound(split_filename)
pitch = snd.to_pitch()
def get_pitch(pitch):
pitch_values = pitch.selected_array["frequency"]
pitch_values[pitch_values == 0] = np.nan
pitch_values_l = list(pitch_values)
pitch_values_np = np.asarray(pitch_values_l)
return pitch_values_np
f0_prev = get_pitch(pitch)
f0 = np.array([value for value in f0_prev if not math.isnan(value)])
with open("video.csv", "w", newline="") as file:
writer = csv.writer(file, delimiter=",")
# writer.writerow(["Name", "Mean" ,"SD", "Median", "Q25", "Q75",'skew','kurt','entropy','Flatness','mode','centroid','Flatness','Mode', 'f0.mean', 'f0.min','f0.max'])
writer.writerow(
[
str(filename),
k_pitches.mean(),
k_pitches.std(),
np.quantile(k_pitches, 0.5),
np.quantile(k_pitches, 0.25),
np.quantile(k_pitches, 0.75),
np.quantile(k_pitches, 0.75) - np.quantile(k_pitches, 0.25),
scipy.stats.skew(k_pitches, axis=0, bias=True),
scipy.stats.kurtosis(
k_pitches, axis=0, fisher=True, bias=True, nan_policy="propagate"
),
FeatureSpectralFlatness(k_pitches, samplerate),
float(scipy.stats.mode(k_pitches)[0]),
f0.mean(),
f0.min(),
f0.max(),
0,
]
)
# # load the model from disk
import joblib
# with open('video.csv', 'r') as file :
# line = list(csv.reader(file , delimiter = ','))
# line1 = [float(x) for x in line[0][1:]]
import pandas as pd
classifer = joblib.load("/home/cristina/Desktop/hack/model.pickle")
pr = pd.read_csv("video.csv")
pred_cols = list(pr.columns.values)[1:]
pred_cols1 = [float(x) for x in pred_cols]
pred = classifer.predict([pred_cols1])
print(pred)<file_sep>from youtubesearchpython import VideosSearch
from .database import addToDb
def getYoutubeVideos(query):
search = VideosSearch(query)
print("search", search)
response = search.result()["result"]
count = 0
print("len response", len(response))
while len(response) < 100 and count < 10:
search.next()
response += search.result()["result"]
count += 1
response = response[:2]
print("link", response[0]["link"])
for video in response:
# if isFemale(video["link"]):
addToDb(video, query)
# else:
# continue
return None
<file_sep>from pytube import YouTube
import os
import ffmpy
def downloadVideo(url):
yt = YouTube(url)
yt = yt.streams.filter(only_audio=True).first()
if not os.path.exists("./tmp"):
os.makedirs("./tmp")
yt.download("./tmp", filename="video")
os.system("ffmpeg -i ./tmp/video.mp4 -acodec pcm_s16le -ar 16000 ./tmp/video.wav")
videourl = "https://www.youtube.com/watch?v=v4ISo3oB9Lw&ab_channel=MrSuicideSheep"
downloadVideo(
videourl,
)
<file_sep>import os
import pymysql
import json
from .parser import parseVideo
db_username = os.environ.get("DB_USERNAME")
db_pass = os.environ.get("DB_PASS")
db_accepted_videos = os.environ.get("ACCEPTED_VIDEOS")
db_connection_name = os.environ.get("CONNECTION_NAME")
host = os.environ.get("HOST")
def isInDatabase(search):
unix_socket = "/cloudsql/{}".format(db_connection_name)
cnx = pymysql.connect(
user=db_username,
password=<PASSWORD>,
unix_socket=unix_socket,
db=db_accepted_videos,
)
with cnx.cursor() as cursor:
cursor.execute(
"SELECT * FROM accepted_videos WHERE search = '{}'".format(str(search))
)
data = cursor.fetchone()
if data is None:
return False
else:
return True
def getFromDatabase(search):
unix_socket = "/cloudsql/{}".format(db_connection_name)
cnx = pymysql.connect(
user=db_username,
password=<PASSWORD>,
unix_socket=unix_socket,
db=db_accepted_videos,
)
with cnx.cursor() as cursor:
cursor.execute(
"SELECT * FROM accepted_videos WHERE search = '{}'".format(str(search))
)
data = cursor.fetchall()
if data is None:
return "there is nothing here"
else:
return json.dumps(data)
def getExistingTags():
tags = []
while len(tags) < 10:
tags.append("ii")
return {"tags": tags}
def addToDb(video, search):
videoData = parseVideo(video)
unix_socket = "/cloudsql/{}".format(db_connection_name)
cnx = pymysql.connect(
user=db_username,
password=<PASSWORD>,
unix_socket=unix_socket,
db=db_accepted_videos,
)
sql = "insert into accepted_videos(id,views,title,search,video_thumbnail,duration,channel,channel_thumbnail) values('{}',{},'{}','{}','{}','{}','{}','{}');".format(
video
)
with cnx.cursor() as cursor:
cursor.execute(sql)
cnx.commit()
<file_sep>def parseVideo(video):
v_id = video["link"]
title = video["title"]
views = video["viewCount"]["text"]
search = str(search)
video_thumbnail = video["thumbnails"][0]["url"]
duration = video["duration"]
channel = video["channel"]["name"]
channel_thumbnail = video["channel"]["thumbnails"][0]["url"]
return tuple(
v_id,
int(views[:-6].replace(",", "")),
title,
search,
video_thumbnail,
duration,
channel,
channel_thumbnail,
) | 6a9ddcf385b8f0c693cbf54398051d495a9cbf93 | [
"Python",
"Text"
] | 9 | Python | a96lex/hackviolet | 0aea0cc89750b1d9351ea399b86d6c8b2a8ba328 | 5611539a9f815a26ee78fbbfd2357861bb76b9d0 |
refs/heads/master | <repo_name>lolepop/ball-bounce<file_sep>/application.windows64/source/ball_bounce.java
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class ball_bounce extends PApplet {
baal thing;
class baal
{
int xSize = displayWidth/10;
int ySize = displayWidth/10;
float x = displayWidth/2;
float y = displayHeight/2;
float xStep = random(5,20);
float yStep = random(5,20);
public void check()
{
if (y+ySize>height || y<0)
{
yStep = -yStep;
}
if (x+xSize>width || x<0)
{
xStep = -xStep;
}
}
public void move()
{
fill(0,255,0);
stroke(255,100,100);
smooth(8);
ellipse(x, y, xSize, ySize);
check();
y = y + yStep;
x = x + xStep;
}
}
public void setup()
{
thing = new baal();
}
public void draw()
{
thing.move();
}
public void settings() { size(displayWidth, displayHeight); }
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "ball_bounce" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
| 4c0e45c636bcf6d99d408e76e474abc85c6fc9af | [
"Java"
] | 1 | Java | lolepop/ball-bounce | 978bc81e10e7e860bb82e9b9c0888167ac253ecb | de91373c332904f645b07b3529d4b81c2cf55784 |
refs/heads/main | <repo_name>Elish96/week-4-assignment<file_sep>/src/Mainbody.jsx
import Home from './home';
import './Mainbody.css';
// import Navbar from './Navbar';
import Specialties from './Specialties';
import About from './About';
import Service from './Service';
const MainBody = () => {
return (
<main>
{/* <Navbar /> */}
<Home />
<Specialties />
<About />
<Service/>
</main>
);
};
export default MainBody;<file_sep>/src/Roadmap.jsx
import './Roadmap.css'
const Roadmap = () => {
return (
<div>
</div>
);
};
export default Roadmap;<file_sep>/src/home.jsx
import './home.css'
import HeroImage from './images/hero-img.svg';
const Home = () => {
return (
<div className="main-container">
<div className="content-container" >
<div className="content">
<h1 className="tent">Trade and invest in cryto using our platform</h1>
<p className="tent">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Natus, similique eveniet. Error, accusamus animi omnis tempore quis fugit tempora? Quod expedita beatae itaque reiciendis architecto accusamus doloribus explicabo illo vero?
</p>
<a href="#" className="btn-btc">Register Now</a>
</div>
</div>
{/* btc image */}
<div className="btc-container">
<div className="hero">
<img src={HeroImage} alt="hero-image"/>
</div>
</div>
</div>
);
};
export default Home;<file_sep>/src/Service.jsx
import './Service.css'
import BlockChain from './images/blockchain.svg';
import ProjectMgt from './images/bitcoin.svg';
import CryptoOtc from './images/stock.svg'
const Service = () => {
return (
<div className="service-container">
<h1 className="s-header">Our Services</h1>
<section className="main-card">
<div className="v-services">
<div className="images">
<img src={BlockChain} rel="blockchain-educational-services" />
</div>
<h1 className="block services">Blockchain Educational Services</h1>
<p className="block">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem inventore cum ad laborum voluptatem aliquam porro odio hic non error voluptatibus esse, exercitationem eos a eligendi dolore reiciendis ipsum ducimus.
</p>
</div>
<div className="v-services">
<div className="images">
<img src={ProjectMgt} rel="" />
</div>
<h1 className="block services" >Operations/Project Management Services</h1>
<p className="block">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem inventore cum ad laborum voluptatem aliquam porro odio hic non error voluptatibus esse, exercitationem eos a eligendi dolore reiciendis ipsum ducimus.
</p>
</div>
<div className="v-services">
<div className="images">
<img src={CryptoOtc} rel="crypto-otc-services" />
</div>
<h1 className="block services">Cryptocurrency OTC, Crypto/Fiat Services</h1>
<p className="block ">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem inventore cum ad laborum voluptatem aliquam porro odio hic non error voluptatibus esse, exercitationem eos a eligendi dolore reiciendis ipsum ducimus.
</p>
</div>
</section>
<a className="purchase">Purchase Now</a>
</div>
);
};
export default Service;<file_sep>/src/Navbar.jsx
import { NavLink } from 'react-router-dom';
import './Navbar.css';
import React from 'react';
const NavBar = () => {
return (
<div className="nav-bar">
<nav>
<NavLink to = "/">
Home
</NavLink>
<NavLink to ="/specialties">
Specialities
</NavLink>
<NavLink to="/about">
About
</NavLink>
<NavLink to="/service">
Service
</NavLink>
<NavLink to="/roadmap">
Roadmap
</NavLink>
<NavLink to ="/team">
Team
</NavLink>
<NavLink to="/contact">
Contact
</NavLink>
</nav>
</div>
);
};
export default NavBar; | ed14205ce91a92f23b34c159396de2eaac599559 | [
"JavaScript"
] | 5 | JavaScript | Elish96/week-4-assignment | 20b68e2cb5faf9f57cca5cfae15577ee1b35388b | cd3aa1de2f34df9bbaaadaac50612996a7600a51 |
refs/heads/master | <file_sep>import numpy as np
import logging
import torch
import torch.nn.functional as F
## Get the same logger from main"
logger = logging.getLogger("our_model")
def validation(args, model, data_loader, macro_loader, batch_size):
logger.info("Starting Validation")
model.eval()
total_loss = 0
total_acc = 0
with torch.no_grad():
for batch_data in data_loader:
data, label, adj_close_prices, time_list = batch_data
data = torch.from_numpy(data).float()
data = data.cuda()
data = data.permute(1, 0, -1) #32*20*106 batchsize*seq_len*feat_dims
if args.just_price == 'True': # just consider price info
data = data[:, :, -8:]
if data.shape[1] != 20:
continue
# data = data.float().unsqueeze(1).to(device) # add channel dimension
hidden = model.init_hidden(len(data), use_gpu=True)
acc, loss, hidden, coef = model(data, macro_loader, adj_close_prices, time_list, hidden, label)
total_loss += loss
total_acc += acc
total_loss /= len(data_loader) # average loss
total_acc /= len(data_loader)
logger.info('===> Validation set: Average loss: {:.4f}\tAccuracy:{:.4f}\n'.format(
total_loss.item(), total_acc))
return total_acc, total_loss.item()<file_sep>import pandas as pd
import os
from _datetime import datetime
import torch
from torch import nn
import numpy as np
from copula_estimate import GaussianCopula
import scipy
# from scipy.stats import norm
import torch.optim as optim
class MarginNet(torch.nn.Module):
def __init__(self, param_dim, L_param_dim=32):
super(MarginNet, self).__init__()
self.mu_layer = nn.Linear(param_dim, 1)
self.L_layer = nn.Linear(param_dim, L_param_dim)
def forward(self, x): #tau
mu = self.mu_layer(x)
L = self.L_layer(x)
return mu,L
# add last one year macro info
def macro_data_load(start_date_str='2013-01-01', end_date_str='2016-01-02', type = 'whole'):
path = './data/macroeconomics/'
files = os.listdir(path)
files.sort()
print('macro data name:')
# valid_data_list = [d.strftime("%Y-%m-%d") for d in pd.date_range(start_date_str,end_date_str,freq='D')]
macro_data = []
# print('end date str split yyear type:', str(end_date_str.split('-')[0]))
year_interval = int(end_date_str.split('-')[0]) - int(start_date_str.split('-')[0])
for file in files:
print(file.split('_')[0])
csv_data = pd.read_csv(path+file)
valid_data = csv_data[(csv_data['DATE']>=start_date_str)&(csv_data['DATE']<=end_date_str)]
column_name = valid_data.columns.to_numpy()[1]
valid_data = valid_data[(True ^ valid_data[column_name].isin(['.']))] # delete non value
if type == 'daily':
if len(valid_data) > 53*year_interval:
macro_data.append(valid_data)
elif type == 'weekly':
if len(valid_data) > 12*year_interval+1 and len(valid_data) <= 53*year_interval:
macro_data.append(valid_data)
elif type == 'monthly':
if len(valid_data) <=12*year_interval+1 and len(valid_data) > 4*year_interval:
macro_data.append(valid_data)
else:
macro_data.append(valid_data)
return macro_data
def macro_aligned(macro_data, dataset):
'''
fill up macro data in stock timeline
:param macro_data:
:return: filled macro data type:numpy shape:[macro_num, whole_len_time]
'''
macro_num = len(macro_data)
if dataset == 'acl18':
start_date = '2013-01-01'
end_date = '2016-01-02'
else:
start_date = '2007-01-01'
end_date = '2017-01-01'
unified_date = [d.strftime('%Y-%m-%d') for d in pd.date_range(start=start_date, end=end_date, freq='D')]
unified_value = np.zeros((macro_num, len(unified_date)))
for i, m_data in enumerate(macro_data):
m_date = m_data['DATE'].tolist()
column_name = m_data.columns.to_numpy()[1]
# print('unified_date:', unified_date[0])
# print('type unified_date:', type(unified_date[0]))
idxs = [unified_date.index(k) for k in m_date]
m_value = m_data[column_name].tolist()
for j, idx in enumerate(idxs):
unified_value[i, idx] = m_value[j]
if j==0 & idx!=0:
unified_value[i, :idx] = m_value[j]
if j!=len(idxs)-1:
unified_value[i, idx:idxs[j+1]] = m_value[j]
else:
unified_value[i, idx:] = m_value[j]
return unified_date, unified_value
def macro_stock_combine(stock_price, aligned_macro_data, unified_date, stock_prev_time):
'''
:param stock_price: t
:param aligned_macro_data: numpy macro_num*whole_len_time
:param stock_prev_time: time list before the current time
:return: combined stock price and macros shape: time_len * macro_num+1
'''
# print('each stock_price shape:', stock_price.shape)
macro_num = aligned_macro_data.shape[0]
merged = np.zeros((len(stock_prev_time), macro_num+1))
merged[:, 0] = stock_price
for i, s_time in enumerate(stock_prev_time):
idx = unified_date.index(s_time.strftime('%Y-%m-%d'))
merged[i, 1:] = aligned_macro_data[:, idx]
# print(merged[0,:])
return merged
def macro_gating_func(g_cop, margin_params, stock_price, macro_data, macro_valid_len_list, stock_prev_time, dataset):
'''
apply copula model to learn gating function for aggregating macros
:param margin_params (batch_mu, batch_L) tensor batch_mu: batchsize*var_num*1 batch_L: batchsize*var_num *L_dim
:param stock_price: t*batchsize
:param macro_data: [dataframe,...]
:param macro_valid_len_list: valid len of each macro, some may be zeros
:param stock_prev_time: list: time before current step
:return: gating value size: batchsize*macro_num
'''
batch_size = stock_price.shape[1]
vr_num = len(macro_data) + 1
# print('shape stock_price:', stock_price.shape)
gat = torch.zeros(batch_size, vr_num, vr_num)
macro_unified_date, macro_unified_value = macro_aligned(macro_data, dataset)
batch_mu, batch_L = margin_params
loss = 0
for i in range(batch_size):
data = macro_stock_combine(stock_price[:, i], macro_unified_value, macro_unified_date, stock_prev_time) #14 variables
# print('data shape:', data.shape)
# print('data:', data)
hyperparam = []
for k in range(vr_num):
mu = batch_mu[i, k, :]
vec_l = batch_L[i, k, :].unsqueeze(0)
sigma = torch.matmul(vec_l, vec_l.permute(1,0))
# print('sigma:',sigma)
hyperparam.append({'loc':mu, 'scale':sigma})
loss += g_cop(data, margins='Normal', hyperparam=hyperparam)
gat[i, :, :] = g_cop.get_R()
return gat, loss
def macro_context_embedding(macro_data, embedding_dim=32):
macro_num = len(macro_data)
# m_data:dataframe ['DATE','xx']
macro_embedding = dict()
macro_embedding['DATE'] = []
macro_embedding['emb'] = []
multi_grain_num = 0
existed_len = []
hidden = []
autoreg = []
macro_label = []
for i, m_data in enumerate(macro_data):
if len(m_data['DATE']) not in existed_len:
existed_len.append(len(m_data['DATE']))
hidden.append(torch.zeros(1, 1, 64))
autoreg.append(nn.GRU(embedding_dim * 2 + 1, 64, num_layers=1, bidirectional=False, batch_first=True)) # 64
multi_grain_num += 1
macro_label.append(existed_len.index(len(m_data['DATE'])))
for i, m_data in enumerate(macro_data):
multi_grain_index = macro_label[i]
# date embedding
# print('m_data:', m_data)
dayofweeks = pd.to_datetime(m_data['DATE']).dt.dayofweek.tolist()
# print('dayofweeks:', type(dayofweeks))
dayofweeks = torch.from_numpy(np.array(dayofweeks)).long()
# print('dayofweeks:', type(dayofweeks))
dayofweeks_embedding = nn.Embedding(7, embedding_dim)(dayofweeks)
dayofyear = pd.to_datetime(m_data['DATE']).dt.dayofyear.tolist()
for m in dayofyear:
if m > 366:
print('out of range data:', m)
dayofyear = torch.from_numpy(np.array(dayofyear)).long()
# print('dayofyear shape:',dayofyear.shape)
dayofyear_embedding = nn.Embedding(367, embedding_dim)(dayofyear)
# value embedding
# print(m_data.icol(1))
# print(dayofweeks_embedding.shape)
column_name = m_data.columns.to_numpy()[1]
# print(column_name)
# print(type(m_data[column_name]))
value = torch.from_numpy(np.array(list(map(float,m_data[column_name].tolist())))).float()
value = value.unsqueeze(1)
merged = torch.cat((dayofweeks_embedding,dayofyear_embedding),1)
# print(merged.shape)
# print(value.shape)
merged = torch.cat((merged, value),1)
merged = merged.unsqueeze(0) #1*seq_len*dim
e, _ = autoreg[multi_grain_index](merged, hidden[multi_grain_index])
macro_embedding['DATE'].append(m_data['DATE'].tolist())
macro_embedding['emb'].append(e)
# print(macro_each_dict['emb'].shape)
# print(macro_embedding[0]['DATE'].tolist())
return macro_embedding
def stock_price_emb(stock_close_price):
'''
:param stock_close_price: t*batchsize
:return: stock embedding of this batch
'''
# print('stock close price shape:', stock_close_price.shape)
scp = torch.from_numpy(np.transpose(stock_close_price)[...,np.newaxis]).float() #batchsize*t*1
# print('scp shape:',scp.shape)
batchsize = scp.shape[0]
enc = nn.Sequential(
nn.Linear(1, 64),
nn.ReLU()
)
hidden = torch.zeros(1, batchsize, 64)
autoreg = nn.GRU(64, 64, num_layers=1, bidirectional=False, batch_first=True)
z = enc(scp)
e, _ = autoreg(z, hidden)
# print('e shape:', e.shape)
return e
def margin_estimate(stock_embs, macro_embs):
'''
estimate margin distribution based on variable embedding
:param stock_embs: tensor: batchsize * t * dim
:param macro_embs: tensor: macro_num * dim
:return:
'''
emb_dim = macro_embs.shape[-1]
MN = MarginNet(emb_dim)
batchsize = stock_embs.shape[0]
batch_mu = torch.zeros(batchsize, macro_embs.shape[0]+1, 1)
batch_L = torch.zeros(batchsize, macro_embs.shape[0]+1, 32)
batch_merged_embs = torch.zeros(batchsize, macro_embs.shape[0]+1, emb_dim)
for i in range(batchsize):
s_emb = stock_embs[i,-1,:].unsqueeze(0)
# print('shape s_emb:', s_emb.shape)
# print('macro embs:', macro_embs.shape)
stacked_emb = torch.cat((s_emb, macro_embs), 0)
mu, L = MN(stacked_emb)
batch_mu[i,:, :] = mu
batch_L[i,:, :] = L
batch_merged_embs[i, :, :] = stacked_emb
return (batch_mu, batch_L), batch_merged_embs
if __name__ == '__main__':
macro_data = macro_data_load()
macro_context_embedding(macro_data)
<file_sep>from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
import scipy.io as scio
import random
import pandas as pd
import numpy as np
from copula_estimate import GaussianCopula
from utils import macro_context_embedding, macro_gating_func, margin_estimate, stock_price_emb
class CoCPC(nn.Module):
def __init__(self, timestep, batch_size, seq_len, rep_dim, feat_dim, var_num, dataset):
super(CoCPC, self).__init__()
self.batch_size = batch_size
self.seq_len = seq_len
self.timestep = timestep
self.rep_dim = rep_dim
self.dataset = dataset
self.encoder = nn.Sequential(
nn.Linear(feat_dim, rep_dim),
# nn.BatchNorm1d(rep_dim),
nn.ReLU()
).cuda()
self.gat_layer = nn.Sequential(
nn.Linear(var_num, 1),
nn.Sigmoid()
)
self.g_cop = GaussianCopula(dim=var_num).cuda()
self.gru = nn.GRU(rep_dim, rep_dim//2, num_layers=1, bidirectional=False, batch_first=True)
self.Wk = nn.ModuleList([nn.Linear(rep_dim//2+64, rep_dim).cuda() for i in range(timestep)]) #256, 512
self.softmax = nn.Softmax()
self.lsoftmax = nn.LogSoftmax()
self.predictor = nn.Sequential(
# nn.Linear(64, 32),
nn.Linear(self.batch_size, 2),
nn.Softmax()
)
def _weights_init(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if isinstance(m, nn.Conv1d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# initialize gru
for layer_p in self.gru._all_weights:
for p in layer_p:
if 'weight' in p:
nn.init.kaiming_normal_(self.gru.__getattr__(p), mode='fan_out', nonlinearity='relu')
self.apply(_weights_init)
def init_hidden(self, batch_size, use_gpu=True):
if use_gpu: return torch.zeros(1, batch_size, self.rep_dim//2).cuda()
else: return torch.zeros(1, batch_size, self.rep_dim//2)
def regenerate_data(self, x, t, y, adj_p):
'''
generate positive and negative samples in each batch
:param x: batchsize*seq_len*dim
:param t: selected time for split the term and pred term
:param y: seq_len*batchsize*1
:param adj_p: seq_len*batchsize
:return: x:batchsize*seq_len*dim, sample_labels:batchsize*1
'''
data = x
negative_num = self.batch_size//4
pred_terms = t + 1
sentence_labels = np.ones((self.batch_size))
for b in range(negative_num):
# set random predictions for negative samples
# each predicted term draws a result from a distribution that excludes itself
numbers = np.arange(0, self.batch_size)
rand_num = np.random.choice(numbers[numbers!=b], 1)
data[b, -pred_terms:, :] = x[rand_num, -pred_terms:, :]
sentence_labels[b] = 0
#shuffle
idxs = np.random.choice(self.batch_size, self.batch_size, replace=False)
return data[idxs, ...], torch.from_numpy(sentence_labels[idxs]).float(), y[:, idxs, ...], adj_p[:, idxs]
def macro_context(self, stock_close_price, macro_loader, time_list, t_index):
'''
:param stock_close_price: t*batchsize
:param macro_loader:
:param time_list: [datetime.date]*T
:param t_index:
:return: macro aggregated context embedding at time t; shape:1*dim
'''
x_time = time_list[t_index]
print('type x_time:', type(x_time))
batchsize = stock_close_price.shape[1]
## get macro embedding
macro_x = macro_context_embedding(macro_loader) #macro_x dict:{'DATE':[m1_date,...], 'emb':[m1_emb,...]} m1_date:list m1_emb:tensor shape:1*T*dim
macro_num = len(macro_x['emb'])
macro_dim = macro_x['emb'][0].shape[2]
macro_emb = torch.zeros(macro_num, macro_dim)
macro_valid_len_list = []
macro_dates_list = macro_x['DATE']
macro_embs_list = macro_x['emb']
for i in range(macro_num):
m_date = macro_dates_list[i]
valid_m_date = [d for d in m_date if d<=x_time.strftime("%Y-%m-%d")] #probably empty
# print('valid_m_date:',valid_m_date)
t = len(valid_m_date)
if t!=0:
m_emb = macro_embs_list[i][:,t-1,:].squeeze()
else:
m_emb = torch.zeros(macro_dim)
# print('shape m_emb:',m_emb.shape)
macro_emb[i, :] = m_emb
macro_valid_len_list.append(t)
## get gating function for macro
stock_emb = stock_price_emb(stock_close_price) #batchsize*seqlen*dim
margin_params, batch_merged_emb = margin_estimate(stock_emb, macro_emb) #mu: batchsize*variable_num*1 L:batchsize*variable_num*d
batch_merged_emb = batch_merged_emb.cuda()
# print('test gat matmul:', torch.matmul(self.gat_layer(test_macro_gat).permute(0, 2, 1), batch_merged_emb).shape)
# print('batch_merged_emb shape:', batch_merged_emb.shape)
macro_gat, loss_c = macro_gating_func(self.g_cop, margin_params, stock_close_price, macro_loader, macro_valid_len_list, time_list[:t_index+1],self.dataset) #batchsize*macro_num
macro_gat = macro_gat.cuda()
# print('macro_gat shape:', macro_gat.shape)
# print('get a batch coefficients:', macro_gat)
# random_stock_ind = random.randrange(1,batchsize,1) - 1
##get R without back propagation
# scio.savemat('raw_coefficient.mat', {'raw_coef': list(macro_gat[0,:,:].cpu().detach().numpy())})
# return
return torch.matmul(self.gat_layer(macro_gat).permute(0,2,1), batch_merged_emb), loss_c, self.gat_layer(macro_gat)[0,:,:]
def forward(self, x, macro_loader, adj_close_prices, x_time_list, hidden, label):
'''
:param x: stock features shape:batchsize*T*dim
:param hidden: initialized hidden for gru
:param adj_close_prices: T*batchsize
:param x_time_list: str list, list the time of this batch data
:param label: T*batchsize*1
:return:
'''
batch = x.size()[0]
label = torch.from_numpy(label).float().long()
# t_samples = torch.randint(self.seq_len/160-self.timestep, size=(1,)).long() # randomly pick one time stamp in [0,128-12)
# t_samples = random.randint(0, self.seq_len-self.timestep-1) # the right one
t_samples = random.randint(14, self.seq_len - self.timestep - 1) #test for macro
# input sequence is N*C*L, e.g. 8*1*20480
re_x, samples_label, label, adj_close_prices = self.regenerate_data(x, t_samples, label, adj_close_prices)
re_x = re_x.cuda()
label = label.cuda()
samples_label = samples_label.cuda()
z = self.encoder(re_x) #batchsize*seq_len*dim 32*20*64
# encoded sequence is N*C*L, e.g. 8*512*128
# reshape to N*L*C for GRU, e.g. 8*128*512
loss_nce = 0 # average over timestep and batch
correct = 0
# loss = 0
# loss_func = nn.CrossEntropyLoss()
encode_samples = torch.empty((self.timestep,batch,self.rep_dim)).float().cuda() # e.g. size 12*8*512
y = torch.empty((self.timestep, 1, batch)).long().cuda()
# print('z shape:', z.shape)
for i in np.arange(1, self.timestep+1):
# print(z[:,t_samples+i,:].shape)
encode_samples[i-1] = z[:,t_samples+i,:].view(batch,self.rep_dim) # z_tk e.g. size 8*512 samples need to predict
y[i-1] = label[t_samples+i, :, :].view(batch)
forward_seq = z[:,:t_samples+1,:] # e.g. 32*11*64 e.g. size 8*100*512
output, hidden = self.gru(forward_seq, hidden) # output size e.g. 8*100*256
c_x_t = output[:,t_samples,:].view(batch, self.rep_dim//2) # c_x_t e.g. size 8*256
# print('c_x_t shape:', c_x_t.shape)
print('t_samples:', t_samples)
c_q_t, loss_c, coef = self.macro_context(adj_close_prices[:t_samples+1, :], macro_loader, x_time_list, t_samples) #
c_q_t = c_q_t.squeeze()
# print('c_1_t shape:', c_q_t.shape)
c_t = torch.cat((c_x_t, c_q_t), 1)
pred = torch.empty((self.timestep, batch, self.rep_dim)).float().cuda() # e.g. 12*32*64 size 12*8*512
for i in np.arange(0, self.timestep):
linear = self.Wk[i]
pred[i] = linear(c_t) # Wk*c_t e.g. 32*64 size 8*512
for i in np.arange(0, self.timestep):
total = torch.mm(encode_samples[i], torch.transpose(pred[i],0,1)) # e.g. 32*32 size 8*8 z_{t+k}W_{k}c_{t}
pred_v = self.predictor(total)
correct += torch.sum(torch.eq(torch.argmax(pred_v.long(), dim=1), samples_label.long())) # correct if predict the true positive samples or negative samples
loss_nce += torch.sum(torch.diag(self.lsoftmax(total))/torch.sum(torch.triu(total))) # loss_nce is a tensor
# loss += loss_func(pred_v, samples_label.long())
loss_nce /= -1.*batch*self.timestep
loss_c /= batch*self.timestep
accuracy = float(correct) / (batch*self.timestep)
# print('acc:', accuracy, '\tloss_nce:',loss_nce, '\tloss_c:', loss_c)
return accuracy, loss_nce+loss_c, hidden, coef
def predict(self, x):
z = self.encoder(x)
return z
class StockClassifier(nn.Module):
def __init__(self, inputsize):
super(StockClassifier, self).__init__()
self.hidden_size = int(inputsize//2)
self.classifier = nn.LSTM(
input_size=inputsize,
hidden_size=self.hidden_size,
num_layers=1,
batch_first=True
)
self.out = nn.Sequential(
nn.Linear(self.hidden_size, 64),
nn.Linear(64, 2),
nn.Sigmoid()
)
def forward(self, encoder, x):
x = encoder.predict(x)
x, _ = self.classifier(x)
return self.out(x)<file_sep>## Utilities
import argparse
import random
import time
import os
import logging
from timeit import default_timer as timer
import pickle
import sys
import scipy.io as scio
## Libraries
import numpy as np
## Torch
import torch
import torch.nn as nn
from torch.utils import data
import torch.nn.functional as F
import torch.optim as optim
from model import CoCPC, StockClassifier
from utils import *
from training import train, snapshot
from validation import validation
from logger_v1 import setup_logs
from stock_train_pred import stock_train, stock_validation
run_name = "our_model-"
class ScheduledOptim(object):
"""A simple wrapper class for learning rate scheduling"""
def __init__(self, optimizer, n_warmup_steps):
self.optimizer = optimizer
self.d_model = 128
self.n_warmup_steps = n_warmup_steps
self.n_current_steps = 0
self.delta = 1
def state_dict(self):
self.optimizer.state_dict()
def step(self):
"""Step by the inner optimizer"""
self.optimizer.step()
def zero_grad(self):
"""Zero out the gradients by the inner optimizer"""
self.optimizer.zero_grad()
def increase_delta(self):
self.delta *= 2
def update_learning_rate(self):
"""Learning rate scheduling per step"""
self.n_current_steps += self.delta
new_lr = np.power(self.d_model, -0.5) * np.min([
np.power(self.n_current_steps, -0.5),
np.power(self.n_warmup_steps, -1.5) * self.n_current_steps])
for param_group in self.optimizer.param_groups:
param_group['lr'] = new_lr
return new_lr
def CoCPC_main(logger, args, train_loader, validation_loader, macro_loader):
global_timer = timer() # global timer
print('multivariable_num:', args.vr_num)
if args.gpu:
model = CoCPC(args.timestep, args.batch_size, args.seq_len, args.rep_dim, args.feat_dim, args.vr_num, args.dataset).cuda()
# optimizer
optimizer = ScheduledOptim(
optim.Adam(
filter(lambda p: p.requires_grad, model.parameters()),
betas=(0.9, 0.98), eps=1e-09, weight_decay=1e-4, amsgrad=True),
args.n_warmup_steps)
model_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
logger.info('### Model summary below###\n {}\n'.format(str(model)))
logger.info('===> Model total parameter: {}\n'.format(model_params))
## Start co_cpc training
best_acc = 0
best_loss = np.inf
best_epoch = -1
val_acc_list = []
val_loss_list = []
all_epoch_coef = []
for epoch in range(1, args.epochs + 1):
epoch_timer = timer()
# Train and validate
epoch_coef = train(args, model, train_loader, macro_loader, optimizer, epoch, args.batch_size)
val_acc, val_loss = validation(args, model, validation_loader, macro_loader, args.batch_size)
all_epoch_coef.append(epoch_coef)
val_acc_list.append(val_acc)
val_loss_list.append(val_loss)
#Save
# if val_loss < best_loss:
# best_loss = min(val_loss, best_loss)
# snapshot(args.logging_dir, run_name, {
# 'epoch': epoch + 1,
# 'validation_acc': val_acc,
# 'state_dict': model.state_dict(),
# 'validation_loss': val_loss,
# 'optimizer': optimizer.state_dict(),
# })
# best_epoch = epoch + 1
#
if val_acc > best_acc:
best_acc = max(val_acc, best_acc)
snapshot(args.logging_dir, run_name, {
'epoch': epoch + 1,
'validation_acc': val_acc,
'state_dict': model.state_dict(),
'validation_loss': val_loss,
'optimizer': optimizer.state_dict(),
})
best_epoch = epoch + 1
elif epoch - best_epoch > 2:
optimizer.increase_delta()
best_epoch = epoch + 1
end_epoch_timer = timer()
logger.info("#### End epoch {}/{}, elapsed time: {}".format(epoch, args.epochs, end_epoch_timer - epoch_timer))
# scio.savemat('all_epoch_coef.mat', {'all_epoch_coef':all_epoch_coef})
## end
print('val loss mean: {:.4f}, val loss var:{:.4f}, val acc mean: {:.4f}, val acc var: {:.4f}'.format(np.mean(val_loss_list), np.var(val_loss_list), np.mean(val_acc_list), np.var(val_acc_list)))
end_global_timer = timer()
logger.info("################## Success #########################")
logger.info("Total elapsed time: %s" % (end_global_timer - global_timer))
if __name__ == '__main__':
## Settings
parser = argparse.ArgumentParser(description='Copula-CPC Stock Prediction')
parser.add_argument('--logging-dir', type=str, default='log',
help='model save directory')
parser.add_argument('--dataset', type=str, default='acl18', help='choose dataset to run')
parser.add_argument('--epochs', type=int, default=200, metavar='N',
help='number of epochs to train')
parser.add_argument('--batch-size', type=int, default=32,
help='batch size')
parser.add_argument('--rep_dim', type=int, default=108, help='representation dimension')
parser.add_argument('--feat_dim', type=int, default=108, help='if just stock price then 8')
parser.add_argument('--vr_num', type=int, default=14, help='variable num for joint distribution')
parser.add_argument('--seq_len', type=int, default=20,
help='window length to sample from each stock')
parser.add_argument('--timestep', type=int, default=1, help='prediction steps')
parser.add_argument('--gpu', type=str, default='0',help='CUDA training')
parser.add_argument('--log_interval', type=int, default=10)
parser.add_argument('--version', type=str, default='v1', help='define runing version')
parser.add_argument('--cpc_train', type=str, default='False', help='whether to train our co-cpc model or prediction based on trained model')
parser.add_argument('--just_price', type=str, default='False', help='whether features contain tweet info')
parser.add_argument('--macro_type', type=str, default='whole', help='choose macros depends on their time interval')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
run_name = run_name + args.version
logger = setup_logs(args.logging_dir, run_name) # setup logs
logger.info('===> loading train, validation and eval dataset')
if args.dataset == 'acl18':
train_loader = pickle.load(open('./data/stock_datasets/train_stock_200_batchs.pkl', 'rb'))
validation_loader = pickle.load(open('./data/stock_datasets/valid_stock_50_batchs.pkl', 'rb'))
test_loader = pickle.load(open('./data/stock_datasets/test_stock_50_batchs.pkl', 'rb'))
macro_loader = macro_data_load(type=args.macro_type)
if args.just_price == 'True':
args.feat_dim = 8
else:
train_loader = pickle.load(open('./data/kdd17/train_stock_200_batchs.pkl', 'rb'))
validation_loader = pickle.load(open('./data/kdd17/valid_stock_50_batchs.pkl', 'rb'))
test_loader = pickle.load(open('./data/kdd17/test_stock_50_batchs.pkl', 'rb'))
args.feat_dim = 7
macro_loader = macro_data_load(start_date_str='2007-01-01', end_date_str='2017-01-01', type=args.macro_type)
args.vr_num = len(macro_loader) + 1 #add a stock
if args.cpc_train == 'True':
CoCPC_main(logger, args, train_loader[:30], validation_loader[:10], macro_loader) #just use small dataset for training Co-CPC
### load encoder model for prediction
cpc_model = CoCPC(args.timestep, args.batch_size, args.seq_len, args.rep_dim, args.feat_dim, args.vr_num, args.dataset)
checkpoint = torch.load(os.path.join(args.logging_dir,
run_name + '-model_best.pth'))
cpc_model.load_state_dict(checkpoint['state_dict'])
cpc_model.eval()
# print(type(cpc_model))
clsf_model = StockClassifier(args.rep_dim)
if args.gpu:
clsf_model = clsf_model.cuda()
optimizer = optim.Adagrad(clsf_model.parameters(), lr=0.002)
all_train_loss = []
all_valid_loss = []
valid_acc_list = []
valid_mcc_list = []
for epoch in range(1, args.epochs + 1):
train_loss = stock_train(logger, args, cpc_model, clsf_model, train_loader, epoch, optimizer)
valid_loss, valid_acc, valid_mcc = stock_validation(logger, args, cpc_model, clsf_model, test_loader)
all_train_loss.append(train_loss)
all_valid_loss.append(valid_loss)
valid_acc_list.append(valid_acc)
valid_mcc_list.append(valid_mcc)
best_index = valid_acc_list.index(max(valid_acc_list))
logger.info('***** best validation acc :{:.4f}\t mcc:{:.4f}\n'.format(valid_acc_list[best_index],
valid_mcc_list[best_index]))
# scio.savemat('./result/our_model_loss_'+args.version+'.mat', {'train_loss': all_train_loss, 'valid_loss': all_valid_loss})<file_sep># Copula-based Contrastive Prediction Coding (Co-CPC)
This repository releases the code and data for stock movement prediction by considering the coupling with macroeconomic indicators.
Please cite the follow paper if you use this code.
<NAME>, <NAME>, et.al, Coupling Macro-Sector-Micro Financial Indicators for LearningStock Representations with Less Uncertainty, AAAI 2021.
Should you have any query please contact me at [<EMAIL>](mailto:<EMAIL>).
## Dependencies
- Python 3.6.9
- Pytorch 1.0.0
- Scipy 1.3.1
## Directories
- data: dataset consisting of ACL18 dataset, KDD17 dataset and some macroeconomic variables in varied time intervals.
- log: store trained model for prediction. Our trained model for acl18 dataset (our_model-v1-model_best.pth) and kdd17 dataset (our_model-v_kdd17-model_best.pth) are provided.
## Data Preprocess
Due to the upload limit, we just upload the smaller one preprocessed data in pickle format. For larger data, you can generate the data by running load_data.py file.
- ACL18 ([Stocknet Data](https://github.com/yumoxu/stocknet-dataset)): similar to the original paper, we generate each batch data with size 32. The preprocess operation
can be refer to file load_data.py, here we provide the preprocessed file in pickle format.
- KDD17: The raw data is from [Adv-ALSTM](https://github.com/fulifeng/Adv-ALSTM/tree/master/data/kdd17/price_long_50), we process them in load_data.py file, here we also provide the prepprocessed file in pickle format.
- Macroeconomic indicators: The data is from [FRED](https://fred.stlouisfed.org/).
## Running
- directly use pre-trained model for prediction:
python main.py --version v1 --epochs 30
- train Co-CPC model:
python main.py --cpc_train True --version v1
<file_sep>import torch
import logging
import torch.nn as nn
import os
import math
import numpy as np
# logger = logging.getLogger('cdc')
loss_func = nn.CrossEntropyLoss()
def get_accurate(pred, target):
# pred1: T*batchsize*2
# target1: T*batchsize
T = pred.shape[0]
batchsize = pred.shape[1]
pred_ = torch.argmax(pred, dim=2)
acc = float(torch.eq(pred_, target).sum()) / (T*batchsize)
return acc
def create_confision_matrix(target, pred):
"""
shape: [T x batch_size, y_size]
pred: [T x batch_size * 2]
target: [T x batch_size * 1]
"""
# target = target.long()
n_samples = pred.shape[0]
label_ref = target.reshape(n_samples)
# label_hyp = torch.gt(pred, 0.5).long().reshape(n_samples) #T*batch_size
label_hyp = torch.argmax(pred, dim=1).reshape(n_samples)
p_in_hyp = torch.sum(label_hyp)
n_in_hyp = n_samples - p_in_hyp
# positive class: up
tp = torch.sum(label_hyp.mul(label_ref))
fp = p_in_hyp - tp
# negative class: down
# print('label_ref + label_hyp nonzero:', len(torch.nonzero(label_ref + label_hyp)))
tn = n_samples - len(torch.nonzero(label_ref + label_hyp))
fn = n_in_hyp - tn
return float(tp), float(fp), float(tn), float(fn)
def get_mcc(pred, target):
tp, fp, tn, fn = create_confision_matrix(target.reshape(-1, 1), pred.reshape(-1, 2))
core_de = (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)
# print('core_de:', core_de)
return (tp * tn - fp * fn) / math.sqrt(core_de) if core_de else None
def stock_train(logger, args, cpc_model, stock_model, train_loader, epoch, optimizer):
logger.info('********* start stock training *********')
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
stock_model.train()
acc_list = []
mcc_list = []
perm = np.arange(len(train_loader))
np.random.shuffle(perm)
perm = list(perm)
total_loss = 0
for idx, batch_idx in enumerate(perm):
# if idx >= 100: #varify efficient classfication with less labeled data
# break
data, label, _, _= train_loader[batch_idx]
# print('data shape:', data.shape)
data = torch.from_numpy(data).float()
data = data.cuda()
data = data.permute(1, 0, -1) # 32*20*108 batchsize*seq_len*feat_dims
if args.just_price == 'True': # just consider price info
data = data[:, :, -8:]
seq_len = data.shape[1]
# print('reshaped data shape:', data.shape)
# data = data.float().unsqueeze(1).to(device) # add channel dimension
label = torch.from_numpy(label).float().long() #seq_len*batchsize*1
label = label.cuda().squeeze()
optimizer.zero_grad()
data = data.cuda()
pred = stock_model(cpc_model, data)
pred = pred.permute(1, 0, -1) # seq_len*batchsize*2
loss = 0
for j in range(seq_len):
temp = loss_func(pred[j,:,:], label[j,:])
loss += temp
loss = loss/seq_len
total_loss += loss.item()
acc = get_accurate(pred, label)
mcc = get_mcc(pred, label)
mcc = (mcc if mcc != None else 0)
acc_list.append(acc)
mcc_list.append(mcc)
loss.backward()
optimizer.step()
# lr = optimizer.update_learning_rate()
if idx % args.log_interval == 0:
logger.info('Stock Train Epoch: {} [{}/{} ({:.0f}%)]\tacc:{:.4f}\tmcc:{:.4f}\tLoss: {:.6f}'.format(
epoch, idx, len(train_loader),
100. * idx / len(train_loader), acc, mcc, loss.item()))
total_loss /= len(train_loader)
logger.info(' ====> Stock Training Set: Average loss: {:.4f}\t Average acc: {:.4f}\t Var acc: {:.4f}\t Average mcc: {:.4f}\t Var mcc:{:.4f}\n'.format(
total_loss, np.mean(acc_list), np.var(acc_list), np.mean(mcc_list), np.var(mcc_list)
))
return total_loss
def stock_validation(logger, args, cpc_model, stock_model, valid_loader):
logger.info('********* start stock validation *********')
stock_model.eval()
total_loss = 0
total_acc = 0
total_mcc = 0
with torch.no_grad():
for batch_data in valid_loader:
data, label, _, _ = batch_data
data = torch.from_numpy(data).float()
data = data.cuda()
data = data.permute(1, 0, -1) # 32*20*106 batchsize*seq_len*feat_dims
if args.just_price == 'True': # just consider price info
data = data[:, :, -8:]
seq_len = data.shape[1]
label = torch.from_numpy(label).float().long() # seq_len*batchsize*1
label = label.cuda().squeeze()
pred = stock_model(cpc_model, data)
pred = pred.permute(1, 0, -1) # seq_len*batchsize*2
loss = 0
for j in range(seq_len):
loss += loss_func(pred[j, :, :], label[j, :])
loss /= seq_len
acc = get_accurate(pred, label)
mcc = get_mcc(pred, label)
mcc = (mcc if mcc != None else 0)
total_loss += loss.item()
total_acc += acc
total_mcc += mcc
total_loss /= len(valid_loader)
total_acc /= len(valid_loader)
total_mcc /= len(valid_loader)
logger.info('===>Stock Validation set: Average loss: {:.4f}\tAccuracy:{:.4f}\t MCC:{:.4f}\n'.format(
total_loss, total_acc, total_mcc))
return total_loss, total_acc, total_mcc
<file_sep>import numpy as np
from scipy import stats
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from torch.autograd import Variable
import math
class GaussianCopula(torch.nn.Module):
r"""
The Gaussian (Normal) copula. It is elliptical and symmetric which gives it nice analytical properties. The
Gaussian copula is determined entirely by its correlation matrix.
A Gaussian copula is fined as
.. math::
C_\Sigma (u_1, \dots, u_d) = \Phi_\Sigma (N^{-1} (u_1), \dots, N^{-1} (u_d))
where :math:`\Sigma` is the covariance matrix which is the parameter of the Gaussian copula and
:math:`N^{-1}` is the quantile (inverse cdf) function
"""
def __init__(self, dim=2):
"""
Creates a Gaussian copula instance
Parameters
----------
dim: int, optional
Dimension of the copula
"""
super(GaussianCopula, self).__init__()
n = sum(range(dim))
self.dim = int(dim)
self._rhos = np.zeros(n)
self._bounds = np.repeat(-1., n), np.repeat(1., n)
self.sig = nn.Sigmoid()
self.off_diagonal_val = nn.Parameter(torch.rand(int(self.dim*(self.dim-1)/2)).cuda())
self.diagonal_val = nn.Parameter(torch.ones(self.dim).cuda() + torch.ones(self.dim).cuda()*torch.rand(self.dim).cuda())
def forward(self, data, margins='Normal', hyperparam=None):
"""
Fit the copula with specified data
Parameters
----------
data: ndarray
Array of data used to fit copula. Usually, data should be the pseudo observations
marginals : numpy array
The marginals distributions. Use scipy.stats distributions or equivalent that requires pdf and cdf functions according to rv_continuous class from scipy.stat.
hyper_param : numpy array
The hyper-parameters for each marginal distribution. Use None when the hyper-parameter is unknow and must be estimated.
"""
data = self.pobs(data)
if data.ndim != 2:
raise ValueError('Data must be a matrix of dimension (n x d)')
elif self.dim != data.shape[1]:
raise ValueError('Dimension of data does not match copula')
data = torch.from_numpy(data).float()
# print('transformed data:',data)
return self.mle(data, margins, hyperparam)
def pobs(self, data, ties='average'):
"""
Compute the pseudo-observations for the given data matrix
Parameters
----------
data: {array_like, DataFrame}
Random variates to be converted to pseudo-observations
ties: { 'average', 'min', 'max', 'dense', 'ordinal' }, optional
String specifying how ranks should be computed if there are ties in any of the coordinate samples
Returns
-------
ndarray
matrix or vector of the same dimension as `data` containing the pseudo observations
"""
return self.pseudo_obs(data, ties)
def pseudo_obs(self, data, ties='average'):
"""
Compute the pseudo-observations for the given data matrix
Parameters
----------
data: (N, D) ndarray
Random variates to be converted to pseudo-observations
ties: str, optional
The method used to assign ranks to tied elements. The options are 'average', 'min', 'max', 'dense'
and 'ordinal'.
'average': The average of the ranks that would have been assigned to all the tied values is assigned to each
value.
'min': The minimum of the ranks that would have been assigned to all the tied values is assigned to each
value. (This is also referred to as "competition" ranking.)
'max': The maximum of the ranks that would have been assigned to all the tied values is assigned to each value.
'dense': Like 'min', but the rank of the next highest element is assigned the rank immediately after those
assigned to the tied elements. 'ordinal': All values are given a distinct rank, corresponding to
the order that the values occur in `a`.
Returns
-------
ndarray
matrix or vector of the same dimension as `data` containing the pseudo observations
"""
return self.rank_data(data, 1, ties) / (len(data) + 1)
def rank_data(self, obs, axis=0, ties='average'):
"""
Assign ranks to data, dealing with ties appropriately. This function works on core as well as vectors
Parameters
----------
obs: ndarray
Data to be ranked. Can only be 1 or 2 dimensional.
axis: {0, 1}, optional
The axis to perform the ranking. 0 means row, 1 means column.
ties: str, default 'average'
The method used to assign ranks to tied elements. The options are 'average', 'min', 'max', 'dense'
and 'ordinal'.
'average': The average of the ranks that would have been assigned to all the tied values is assigned to each
value.
'min': The minimum of the ranks that would have been assigned to all the tied values is assigned to each
value. (This is also referred to as "competition" ranking.)
'max': The maximum of the ranks that would have been assigned to all the tied values is assigned to each value.
'dense': Like 'min', but the rank of the next highest element is assigned the rank immediately after those
assigned to the tied elements. 'ordinal': All values are given a distinct rank, corresponding to
the order that the values occur in `a`.
Returns
-------
ndarray
matrix or vector of the same dimension as X containing the pseudo observations
"""
obs = np.asarray(obs)
ties = ties.lower()
assert obs.ndim in (1, 2), "Data can only be 1 or 2 dimensional"
if obs.ndim == 1:
return stats.rankdata(obs, ties)
elif obs.ndim == 2:
if axis == 0:
return np.array([stats.rankdata(obs[i, :], ties) for i in range(obs.shape[0])])
elif axis == 1:
return np.array([stats.rankdata(obs[:, i], ties) for i in range(obs.shape[1])]).T
else:
raise ValueError("No axis named 3 for object type {0}".format(type(obs)))
def get_R(self):
'''
:return:
'''
idx = 0
L = torch.zeros(self.dim, self.dim).cuda()
off_diag = torch.zeros(self.dim, self.dim).cuda()
for j in range(self.dim):
for i in range(j):
off_diag[j, i] = torch.tanh(self.off_diagonal_val[idx])
idx += 1
for i in range(self.dim):
for j in range(i+1):
if i == j:
# print('sig diagoal:', self.sig(self.diagonal_val[i]))
L[i, j] = self.sig(self.diagonal_val[i]) + torch.tensor([1.0]).cuda()
else:
L[i, j] = off_diag[i,j]
L = F.normalize(L, p=2, dim=0)
# print('L:', L)
cov = torch.mm(L, L.t())
return cov
def pdf_param(self, x):
# self._check_dimension(x)
'''
:param x: data numpy n*d
:param R: flattened correlation value, not include the redundancy and diagonal value shape: (d*(d-1))/2
:return:
'''
# print('R:',R)
# print('x:',x)
norm = Normal(torch.tensor([0.0]), torch.tensor([1.0]))
u = norm.icdf(x)
# print('shape u:', u.shape)
cov = self.get_R().cuda()
if self.dim == 2:
RDet = cov[0,0] * cov[1,1] - cov[0,1] ** 2
RInv = 1. / RDet * torch.from_numpy(np.asarray([[cov[1,1], -cov[0,1]], [-cov[0,1], cov[0,0]]]))
else:
RDet = torch.det(cov)
RInv = torch.inverse(cov)
u = u.unsqueeze(0).cuda()
# print('u shape', u.shape) #d
I = torch.eye(self.dim).cuda()
# print('u cuda:', u.is_cuda)
# print('cov cuda:', cov.is_cuda)
# print('I cuda:', I.is_cuda)
res = RDet ** (-0.5) * torch.exp(-0.5 * torch.mm(torch.mm(u,(RInv - I)),u.permute(1,0))).cuda()
# print('res:', res)
if res.data == 0.0:
print('RDet:', RDet)
print('RInv shape', RInv.shape)
if math.isnan(res.data):
print('self.diagonal:', self.diagonal_val)
print('self.non_diagonal:', self.off_diagonal_val)
print('RDet:', RDet)
print('RInv:', RInv)
print('cov:', cov)
print('u:', u)
return
return res
def mle(self, X, marginals, hyper_param):
"""
Computes the MLE on specified data.
Parameters
----------
copula : Copula
The copula.
X : numpy array (of size n * copula dimension)
The data to fit.
marginals : numpy array
The marginals distributions. Use scipy.stats distributions or equivalent that requires pdf and cdf functions according to rv_continuous class from scipy.stat.
hyper_param : numpy array
The hyper-parameters for each marginal distribution. Use None when the hyper-parameter is unknow and must be estimated.
Returns
-------
loss : copula loss
"""
hyperOptimizeParams = hyper_param
n, d = X.shape
# The global log-likelihood to maximize
def log_likelihood():
lh = 0
marginCDF = torch.zeros(n,d)
if marginals == 'Normal':
for j in range(d):
norm = Normal(hyperOptimizeParams[j]['loc'], hyperOptimizeParams[j]['scale'])
marginCDF[:,j] = norm.cdf(X[:, j]).cuda()
# print('marginCDF[:,j] shape:', marginCDF[:,j].shape)
# print('marginCDF[:,j]:', marginCDF[:,j])
idx = np.argwhere(marginCDF[:,j] == 1.0)
if idx.nelement() != 0:
for i in range(idx.shape[1]):
marginCDF[idx[0,i].item(),j] -= 1e-2
# The first member : the copula's density
for i in range(n):
pdf_val = self.pdf_param(marginCDF[i, :])
lh += torch.log(pdf_val if pdf_val.data !=0.0 else torch.tensor([[1e-5]]).cuda())
# The second member : sum of PDF
# print("OK")
# print('first lh:', lh)
for j in range(d):
norm = Normal(hyperOptimizeParams[j]['loc'], hyperOptimizeParams[j]['scale'])
lh += (norm.log_prob(X[:, j])).sum().cuda()
# print('lh:', lh)
return lh
loss = -log_likelihood()
return loss
# if __name__ == '__main__':
# data = np.random.random((4,3))
# print('data:', data)
# data[:,-1] = [1,1,1,1]
# print('data:',data)
# gc = GaussianCopula(dim=3)
# res, param = gc.fit(data, margins=[stats.norm, stats.norm,stats.norm], hyperparam=[{'loc':0, 'scale':1.2},{'loc':0.2, 'scale':1.2},{'loc':0.2, 'scale':1.0}])
#
# print('optimizeResult:', res)
# print('estimatedParams:', param)<file_sep>import torch
import logging
import os
import torch.nn.functional as F
import numpy as np
import time
import scipy.io as scio
## Get the same logger from main"
logger = logging.getLogger("our_model")
def train(args, model, train_loader, macro_loader, optimizer, epoch, batch_size):
model.train()
perm = np.arange(len(train_loader))
np.random.shuffle(perm)
perm = list(perm)
# all_coef = []
for idx, batch_idx in enumerate(perm):
data, label, adj_close_prices, time_list = train_loader[batch_idx]
# print('data shape:', data.shape)
data = torch.from_numpy(data).float()
data = data.cuda()
data = data.permute(1,0,-1) #32*20*108 batchsize*seq_len*feat_dims
if args.just_price == 'True': #just consider price info
data = data[:,:,-8:]
# print('reshaped data shape:', data.shape)
# data = data.float().unsqueeze(1).to(device) # add channel dimension
if data.shape[1] != 20:
continue
optimizer.zero_grad()
hidden = model.init_hidden(len(data), use_gpu=True)
acc, loss, hidden, coef = model(data, macro_loader, adj_close_prices, time_list, hidden, label)
loss.backward()
optimizer.step()
lr = optimizer.update_learning_rate()
# if idx % args.log_interval == 0:
logger.info('Train Epoch: {} [{}/{} ({:.0f}%)]\tlr:{:.5f}\tacc:{:.4f}\tLoss: {:.6f}'.format(
epoch, idx, len(train_loader),
100. * idx / len(train_loader), lr, acc, loss.item()))
# all_coef.append(coef.cpu().detach().numpy())
# scio.savemat('coeficients_v3.mat', {'coef': all_coef})
return coef.cpu().detach().numpy()
def snapshot(dir_path, run_name, state):
snapshot_file = os.path.join(dir_path,
run_name + '-model_best.pth')
torch.save(state, snapshot_file)
logger.info("Snapshot saved to {}\n".format(snapshot_file))
<file_sep>
import os
import csv
import numpy as np
from datetime import datetime, timedelta
import random
import pandas as pd
import sklearn
from sklearn.preprocessing import normalize
import io
import pickle
raw_data_path = './data/kdd17/price_long_50/'
preprocess_data_path = './data/kdd17/preprocess/'
class DataLoad():
def __init__(self):
self.movement_path = preprocess_data_path
self.raw_movement_path = raw_data_path
self.batch_size = 32
self.train_start_date = '2007-01-01'
self.train_end_date = '2015-01-01'
self.valid_start_date = '2015-01-01'
self.valid_end_date = '2016-01-01'
self.test_start_date = '2016-01-01'
self.test_end_date = '2016-12-30'
self.max_n_days = 20
self.y_size = 2
self.shuffle = True
self.stock_symbols = []
def _get_stock_symbols(self):
files = os.listdir(self.raw_movement_path)
print(len(files))
stock_symbols = []
for file in files:
# print('file:',file)
stock_symbols.append(file.split('.')[0])
self.stock_symbols = stock_symbols
def _get_start_end_date(self, phase):
if phase == 'train':
return self.train_start_date, self.train_end_date
elif phase == 'valid':
return self.valid_start_date, self.valid_end_date
elif phase == 'test':
return self.test_start_date, self.test_end_date
else:
return None
def _get_prices_and_ts(self, ss, main_target_date, valid_date):
# print('get_prices_and_ts')
def _get_mv_class(data, use_one_hot=False):
mv = float(data[1])
if self.y_size == 2:
if mv <= 1e-7:
return [1.0, 0.0] if use_one_hot else 0
else:
return [0.0, 1.0] if use_one_hot else 1
if self.y_size == 3:
threshold_1, threshold_2 = -0.004, 0.005
if mv < threshold_1:
return [1.0, 0.0, 0.0] if use_one_hot else 0
elif mv < threshold_2:
return [0.0, 1.0, 0.0] if use_one_hot else 1
else:
return [0.0, 0.0, 1.0] if use_one_hot else 2
def _get_prices(data):
return [float(p) for p in data[2:6]]
def _get_mv_percents(data):
return _get_mv_class(data)
ts, ys, ms, prices, raw_adj_close, mv_percents, mv_class, main_mv_percent = list(), list(), list(), list(), list(), list(), list(), 0.0
d_t_min = main_target_date - timedelta(days=10)
stock_movement_path = os.path.join(str(self.movement_path), '{}.txt'.format(ss))
stock_raw_price_path = os.path.join(str(self.raw_movement_path), '{}.csv'.format(ss))
flag = 0
raw_movement_data = pd.read_csv(stock_raw_price_path)
with io.open(stock_movement_path, 'r', encoding='utf8') as movement_f:
for i, line in enumerate(movement_f): # descend
data = line.split('\t')
t = datetime.strptime(data[0], '%Y-%m-%d').date()
# logger.info(t)
# extract previous prices, mv_percents and current target date
if t == main_target_date:
# logger.info(t)
main_mv_percent = data[1]
main_market_share = float(data[-1])/1.0e7
if -0.005 <= float(main_mv_percent) < 0.0055: # discard sample with low movement percent
return None
y = _get_mv_percents(data)
main_mv_class = _get_mv_percents(data)
flag = 1
if t in valid_date:
ts.append(t)
ys.append(_get_mv_percents(data)) #previous mv percent
mv_class.append(_get_mv_percents(data))
prices.append(_get_prices(data)) # open, high, low, close
mv_percents.append(data[1])
ms.append(float(data[-1])/1.0e7)
revised_raw_date = raw_movement_data.Date.copy()
if '/' in raw_movement_data.Date[0]:
for k in range(len(raw_movement_data.Date)):
revised_raw_date[k] = datetime.strptime(raw_movement_data.Date[k], '%m/%d/%Y').date().strftime('%Y-%m-%d')
# print('shape:', raw_movement_data.loc[raw_movement_data.Date==data[0], 'Adj Close'].to_numpy().shape)
raw_adj_close.append(raw_movement_data.loc[revised_raw_date==data[0], 'Adj Close'].to_numpy()[0])
# print('stock:', ss)
# print('t:', data[0])
# print('raw adj close price:', raw_adj_close[-1])
if flag == 0 or len(ts) != len(valid_date):
return None
# ascend
for item in (ts, ys, mv_percents, prices):
item.reverse()
prices_and_ts = {
'ts': ts,
'ys': ys,
'y': y,
'ms': ms,
'main_mv_class': main_mv_class,
'mv_class': mv_class,
'main_mv_percent': main_mv_percent,
'mv_percents': mv_percents,
'main_ms_percent': main_market_share,
'prices': prices,
'raw_adj_close_prices': raw_adj_close,
}
return prices_and_ts
def sample_gen_from_one_stock(self, s, valid_date, main_target_date):
"""
generate samples for the given stock.
=> tuple, (x:dict, y_:int, price_seq: list of floats, prediction_date_str:str)
"""
# logger.info('start _get_prices_and_ts')
prices_and_ts = self._get_prices_and_ts(s, main_target_date, valid_date)
if not prices_and_ts:
# print('none prices and ts')
return None
sample_dict = {
'ms': prices_and_ts['ms'],
'mv_class': prices_and_ts['mv_class'],
'main_mv_class': prices_and_ts['main_mv_class'],
'main_mv_percent': prices_and_ts['main_mv_percent'],
'mv_percents': prices_and_ts['mv_percents'],
# target
'y': prices_and_ts['y'], # one-hot
'ys': prices_and_ts['ys'], # one-hot
'main_ms_percent': prices_and_ts['main_ms_percent'],
# source
'prices': prices_and_ts['prices'],
'raw_adj_close_prices': prices_and_ts['raw_adj_close_prices'],
}
return sample_dict
def get_valid_time_line(self, target_date_str):
try_count = 0
while try_count < 10:
gen_id = random.randint(0, len(self.stock_symbols) - 1)
s = self.stock_symbols[gen_id]
stock_movement_path = os.path.join(str(self.movement_path), '{}.txt'.format(s))
flag = 0
step = 0
valid_dates = []
# print(stock_movement_path)
with open(stock_movement_path, 'r') as movement_f:
for line in movement_f: # descend
data = line.split('\t')
_date = datetime.strptime(data[0], '%Y-%m-%d').date()
date_str = _date.isoformat()
# print('type date_str:', type(date_str))
if flag:
valid_dates.append(_date)
step += 1
if step == self.max_n_days:
break
if date_str == target_date_str:
flag = 1
# print(len(valid_dates))
if len(valid_dates) == self.max_n_days:
break
try_count += 1
# valid_dates.append(target_date_str)
valid_dates.reverse()
return valid_dates
def batch_gen(self, phase):
self._get_stock_symbols()
start_date_str, end_date_str = self._get_start_end_date(phase)
start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date()
end_date = datetime.strptime(end_date_str, '%Y-%m-%d').date()
while True:
rd_time = random.random() * (end_date - start_date) + start_date
valid_time_line = self.get_valid_time_line(rd_time.isoformat())
if len(valid_time_line) != 0:
break
ys_batch = []
y_batch = []
ms_batch = []
main_mv_class_batch = []
mv_class_batch = []
main_mv_percent_batch = []
main_ms_percent_batch = []
mv_percent_batch = []
price_batch = []
raw_adj_close_price_batch = []
sample_id = 0
sampled_stocks = []
loop_step = 0
while sample_id < self.batch_size:
loop_step += 1
if loop_step == 200:
break
# print('sample_id:', sample_id)
gen_id = random.randint(0, len(self.stock_symbols) - 1)
s = self.stock_symbols[gen_id]
if s in sampled_stocks:
continue
sample_dict = self.sample_gen_from_one_stock(s, valid_time_line, rd_time)
# sample_dict = generators[gen_id]
if not sample_dict:
continue
sampled_stocks.append(s)
# target
y_batch.append(sample_dict['y']) # one-hot
ys_batch.append(sample_dict['ys'])
ms_batch.append(sample_dict['ms'])
main_mv_class_batch.append(sample_dict['main_mv_class'])
mv_class_batch.append(sample_dict['mv_class'])
main_mv_percent_batch.append(sample_dict['main_mv_percent'])
mv_percent_batch.append(sample_dict['mv_percents'])
main_ms_percent_batch.append(sample_dict['main_ms_percent'])
# source
price_batch.append(sample_dict['prices'])
raw_adj_close_price_batch.append(sample_dict['raw_adj_close_prices'])
sample_id += 1
if len(y_batch) == self.batch_size:
batch_dict = {
# meta
'main_target_date': rd_time,
'ts': valid_time_line,
# target
'y_batch': y_batch,
'ys_batch': ys_batch,
'main_mv_class_batch': main_mv_class_batch,
'mv_class_batch': mv_class_batch,
'ms_batch': ms_batch,
'main_mv_percent_batch': main_mv_percent_batch,
'mv_percent_batch': mv_percent_batch,
'main_ms_percent_batch': main_ms_percent_batch,
# source
'price_batch': price_batch,
'raw_adj_close_price_batch': raw_adj_close_price_batch,
}
return batch_dict
else:
print('batch gen none!')
return None
def get_square(self, m):
return float(m * m)
def gen_graph(self, data_dict):
# print('gen_graph')
batch_size = self.batch_size
seq_time = len(data_dict['ts'])
labels = np.zeros((seq_time, batch_size, 1))
features = np.zeros((seq_time, batch_size, 7))
raw_adj_close_price_feat = np.zeros((seq_time, batch_size))
ys = data_dict['ys_batch']
y = data_dict['y_batch']
ms = data_dict['ms_batch']
m = data_dict['main_ms_percent_batch']
mv_class_batch = data_dict['mv_class_batch']
# features +ys +ms
mv_percent_batch = data_dict['mv_percent_batch']
price_batch = data_dict['price_batch']
raw_adj_close_price_batch = data_dict['raw_adj_close_price_batch']
# print('ys')
for i, e_ys in enumerate(ys):
re_y = e_ys[1:]
re_y.append(y[i])
labels[:, i, :] = np.array(re_y).reshape((seq_time, 1))
for i in range(batch_size):
price = np.asarray(price_batch[i]) #T*4
raw_adj_close_price = np.asarray(raw_adj_close_price_batch[i]) #T*1
mv_percent = np.asarray(mv_percent_batch[i]).reshape((seq_time, 1))
ys_ = np.asarray(mv_class_batch[i]).reshape((seq_time, 1))
ms_ = np.asarray(ms[i]).reshape((seq_time, 1))
features[:, i, :] = np.hstack((price, mv_percent, ys_, ms_)) #dim:7
raw_adj_close_price_feat[:,i] = raw_adj_close_price
return features, labels, raw_adj_close_price_feat, data_dict['ts']
def _get_dataset(self, phase):
train_batch_datasets = []
test_batch_datasets = []
if phase == 'train':
print('train data process')
b = 0
while b < 200: # 200
batch_data = self.batch_gen(phase='train') # next(train_batch_gen)
if batch_data is None:
print('None batch data')
continue
train_batch_datasets.append(tuple(self.gen_graph(batch_data)))
b += 1
print('b:', b)
print('len dataset:', len(train_batch_datasets))
with open('./data/kdd17/train_stock_200_batchs.pkl', 'wb') as train_f:
pickle.dump(train_batch_datasets, train_f)
elif phase == 'valid':
print('validation data process')
# train_batch_gen = self.pipe.batch_gen(phase='train') # a new gen for a new epoch
b = 0
while b < 50:
# for _ in tqdm(range(200)):
# try:
batch_data = self.batch_gen(phase='valid') # next(train_batch_gen)
if batch_data is None:
print('None batch data')
continue
train_batch_datasets.append(tuple(self.gen_graph(batch_data)))
b += 1
print('b:', b)
# except StopIteration:
# print('wrong')
with open('./data/kdd17/valid_stock_50_batchs.pkl', 'wb') as train_f:
pickle.dump(train_batch_datasets, train_f)
else:
print('test data process')
b = 0
while b < 50:
batch_data = self.batch_gen(phase=phase)
if batch_data is None:
continue
b += 1
print('b:', b)
test_batch_datasets.append(tuple(self.gen_graph(batch_data)))
with open('./data/kdd17/test_stock_50_batchs.pkl', 'wb') as test_f:
pickle.dump(test_batch_datasets, test_f)
def preprocess():
'''
preprocess the raw kdd17 data into unit format
:return:
'''
files = os.listdir(raw_data_path)
for k, file in enumerate(files):
# file = files[0]
with open(os.path.join(raw_data_path,file), 'r') as f:
data = pd.read_csv(f)
date_time = data['Date']
open_price = normalize(data['Open'].to_numpy().reshape(1, -1))
high_price = normalize(data['High'].to_numpy().reshape(1, -1))
low_price = normalize(data['Low'].to_numpy().reshape(1, -1))
close_price = normalize(data['Close'].to_numpy().reshape(1, -1))
# print('shifted mv:', data['Adj Close'].shift(-1)[:3])
mv_percent = ((data['Adj Close'] - data['Adj Close'].shift(-1)) / data['Adj Close'].shift(-1))[:-1].to_numpy()
volume = data['Volume'].to_numpy().reshape(1,-1)
# print('len date time:', len(date_time))
# print(date_time[0])
filename = file.split('.')[0] + '.txt'
with open(os.path.join(preprocess_data_path, filename), 'a+') as wf:
for i in range(len(date_time)-1): #
transform_data = []
if '/' in date_time[i]:
revised_date = datetime.strptime(date_time[i], '%m/%d/%Y').date().strftime('%Y-%m-%d')
else:
revised_date = date_time[i]
transform_data.append(revised_date)
# print(mv_percent[i])
# transform_data = transform_data.join('\t')
transform_data.append(str(round(mv_percent[i], 6)))
transform_data.append(str(round(open_price[0, i], 6)))
transform_data.append(str(round(high_price[0, i], 6)))
transform_data.append(str(round(low_price[0, i], 6)))
transform_data.append(str(round(close_price[0, i], 6)))
transform_data.append(str(volume[0, i]))
wf.write('\t'.join(transform_data))
wf.write('\n')
if __name__ == '__main__':
# preprocess()
obj = DataLoad()
obj._get_dataset('train')
obj._get_dataset('valid')
obj._get_dataset('test')
# data_path = './data/kdd17/'
# filename = 'valid_stock_50_batchs_seqlen_20.pkl'
# new_batch_loader = []
# batch_loader = pickle.load(open(os.path.join(data_path, filename), 'rb'))
# for batch_data in batch_loader:
# _, feature, label, _, _, adj_price, time_list = batch_data
# new_batch_loader.append((feature,label,adj_price,time_list))
# with open(os.path.join(data_path, 'valid_stock_50_batchs.pkl'), 'wb') as wf:
# pickle.dump(new_batch_loader, wf)
| 3e7bb819ac25bdf37efaf6a5f987145a0af4261d | [
"Markdown",
"Python"
] | 9 | Python | Liamsun/CoCPC | d6d82c76b211c9dc2018369e3c5fbce5e5f6ba37 | 7ba5b9bc635aecf4f6d721886be639102acac49a |
refs/heads/master | <repo_name>zha8035/tangjingxuan_tangjiehao_group_android_reader<file_sep>/README.md
tangjingxuan_tangjiehao_group_android_reader
============================================
安卓手机阅读器,可以txt文档阅读,可以在线上传下载。
<file_sep>/myreader/src/com/hck/book/util/AlertDialogs.java
package com.hck.book.util;
import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.hck.book.ui.BaseActivity;
import com.hck.test.R;
public class AlertDialogs {
private Context context;
private Button exitButton;
private Button noButton;
private TextView textView, textView2;
private AlertDialog aDialog;
private BaseActivity activity;
public AlertDialogs(Context context, BaseActivity activity) {
this.context = context;
this.activity = activity;
}
public void alertDialog(String title, String content, String btsString1,
String btString2, String tag) {
final View view;
view = LayoutInflater.from(context).inflate(R.layout.d, null);
exitButton = (Button) view.findViewById(R.id.bt2);
noButton = (Button) view.findViewById(R.id.bt1);
textView = (TextView) view.findViewById(R.id.d_title);
textView2 = (TextView) view.findViewById(R.id.d_content);
exitButton.setText(btsString1);
noButton.setText(btString2);
textView.setText(title);
textView2.setText(content);
aDialog = new AlertDialog.Builder(context).create();
aDialog.show();
WindowManager.LayoutParams params = aDialog.getWindow().getAttributes();
params.width =(int) (MyTool.getWidth()*0.6);
params.height = (int) (MyTool.getHight()*0.2);
aDialog.getWindow().setAttributes(params);
aDialog.getWindow().setContentView(view);
noButton.setTag(tag);
exitButton.setTag(tag);
noButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
aDialog.dismiss();
if (v.getTag().equals("exit")) {
aDialog.dismiss();
} else if (v.getTag().equals("net")) {
aDialog.dismiss();
new Exit(context).exit();
}
}
});
exitButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (v.getTag().equals("exit")) {
aDialog.dismiss();
new Exit(context).exit();
} else if (v.getTag().equals("delete")) {
aDialog.dismiss();
activity.server();
}
}
});
}
}
<file_sep>/myreader/src/com/hck/book/util/SpeekUtil.java
package com.hck.book.util;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.hck.book.ui.Read;
import com.iflytek.speech.SpeechError;
import com.iflytek.speech.SynthesizerPlayer;
import com.iflytek.ui.SynthesizerDialog;
import com.iflytek.ui.SynthesizerDialogListener;
public class SpeekUtil {
private int flag;
private int post;
private int type;
private Context context;
private String appId = "519328ab";
private SynthesizerPlayer mSynthesizerPlayer;
private SynthesizerDialog ttsDialog;
public SpeekUtil(Context context) {
this.context = context;
if (ttsDialog == null) {
ttsDialog = new SynthesizerDialog(context, "appid=" + appId);
}
// if (beans == null) {
// beans = new ArrayList<JokSpeekBean>();
// }
}
public void start(String content) {
Log.i("hck", "start content: "+content);
if (ttsDialog == null) {
ttsDialog = new SynthesizerDialog(context, "appid=" + appId);
}
showSynDialog(content);
ttsDialog.setListener(new SynthesizerDialogListener() {
@Override
public void onEnd(SpeechError arg0) {
((Read) context).nextPage();
}
});
}
public void showSynDialog(String content) {
ttsDialog.setText(content, null);
String role = "vixx";
ttsDialog.setVoiceName(role);
int speed = 65;
ttsDialog.setSpeed(speed);
int volume = 90;
ttsDialog.setVolume(volume);
ttsDialog.show();
}
public void onStop() {
if (null != mSynthesizerPlayer) {
mSynthesizerPlayer.cancel();
}
}
}
<file_sep>/myreader/src/com/hck/book/util/Reserver.java
package com.hck.book.util;
import com.hck.book.ui.MyApplication;
import com.hck.date.FinalDate;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class Reserver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
//接收安装广播
if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
String packageName = intent.getDataString();
Log.i("hck","安装了:" +packageName + "包名的程序");
if (packageName.equals("com.snda.tts.service")) {
FinalDate.isTrue=true;
}
}
}
}
<file_sep>/myreader/src/com/hck/book/ui/BookShelfActivity.java
package com.hck.book.ui;
import java.util.List;
import com.hck.book.util.MangerActivitys;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import com.hck.test.R;
public class BookShelfActivity extends Activity {
private GridView bookShelf;
private String[] name={
"天龙八部","搜神记","水浒传","黑道悲情"
};
private GridView gv;
private SlidingDrawer sd;
private Button iv;
private List<ResolveInfo> apps;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
MangerActivitys.activitys.add(this);
bookShelf = (GridView) findViewById(R.id.bookShelf);
ShlefAdapter adapter=new ShlefAdapter();
bookShelf.setAdapter(adapter);
bookShelf.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});
loadApps();
gv.setAdapter(new GridAdapter());
sd.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener()// 开抽屉
{
@Override
public void onDrawerOpened() {
iv.setText("返回");
iv.setBackgroundResource(R.drawable.btn_local);// 响应开抽屉事件
// ,把图片设为向下的
}
});
sd.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {
@Override
public void onDrawerClosed() {
iv.setText("本地");
iv.setBackgroundResource(R.drawable.btn_local);// 响应关抽屉事件
}
});
}
class ShlefAdapter extends BaseAdapter{
@Override
public int getCount() {
return 5;
}
@Override
public Object getItem(int arg0) {
return arg0;
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(int position, View contentView, ViewGroup arg2) {
contentView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.item1, null);
TextView view=(TextView) contentView.findViewById(R.id.imageView1);
if(5>position){
if(position<name.length){
view.setText(name[position]);
}
}else{
view.setClickable(false);
view.setVisibility(View.INVISIBLE);
}
return contentView;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("你确定退出吗?")
.setCancelable(false)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
}
})
.setNegativeButton("返回",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void loadApps() {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
apps = getPackageManager().queryIntentActivities(intent, 0);
}
public class GridAdapter extends BaseAdapter {
public GridAdapter() {
}
public int getCount() {
// TODO Auto-generated method stub
return apps.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return apps.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = null;
if (convertView == null) {
imageView = new ImageView(BookShelfActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new GridView.LayoutParams(50, 50));
} else {
imageView = (ImageView) convertView;
}
ResolveInfo ri = apps.get(position);
imageView.setImageDrawable(ri.activityInfo
.loadIcon(getPackageManager()));
return imageView;
}
}
} | 0c5bc3f606e9a1d36647a9b210f3b90ffa332f99 | [
"Markdown",
"Java"
] | 5 | Markdown | zha8035/tangjingxuan_tangjiehao_group_android_reader | f210a9dab9812bd73d8c9c440ddcf3b9e9c4a603 | b7a3337c1ee9eecd154983c69deece879f6ff864 |
refs/heads/master | <repo_name>rhiannoncs/ruby-inheritance-lab-v-000<file_sep>/bin/time_for_school
#!/usr/bin/env ruby
require_relative "../lib/user.rb"
require_relative "../lib/teacher.rb"
require_relative "../lib/student.rb"
steve = Student.new
steve.first_name = "Steve"
steve.last_name = "Jobs"
avi = Teacher.new
avi.first_name = "Avi"
avi.last_name = "Flombaum"
some_knowledge = avi.teach
steve.learn(some_knowledge)
#puts "Steve just learned this important knowledge: '#{steve.knowledge.first}' from Avi"
#jim = User.new
#jim.first_name = "Jim"
#jim.last_name = "Slim"
#jim.learn(some_knowledge)
#puts "Here's something Jim learned: #{jim.knowledge.first}."
some_more_knowledge = avi.teach
steve.learn(some_more_knowledge)
charlie = Student.new
charlie.first_name = "Charlie"
charlie.last_name = "Brown"
knowledge1 = avi.teach
knowledge2 = avi.teach
knowledge3 = avi.teach
charlie.learn(knowledge1)
charlie.learn(knowledge2)
charlie.learn(knowledge3)
puts "Here's everything Steve knows:"
steve.knowledge.each {|knowledge| puts knowledge}
puts "Here's everything Charlie knows:"
charlie.knowledge.each {|knowledge| puts knowledge}
| 7c8241e07beb763af29850e8548d064704226eda | [
"Ruby"
] | 1 | Ruby | rhiannoncs/ruby-inheritance-lab-v-000 | b4019daa75b7c418cc9ae6b6fc1aa6162a7fbb3b | 5d3b2f366d116a6dc566c4d7007852733e6ea72c |
refs/heads/master | <repo_name>capusta/torrentStats<file_sep>/README.md
### Kickass-torrent Daily Stats
Kickass torrents makes public data available in their api. They allow a 24 hour dump and full data dump to be downloaded to the public.
You can find the Kickass data export [here](https://https://kickass.to/api/).
#### This project is retired ... cuz ... kickass is no longer operational
[https://www.shinyapps.io/](https://www.shinyapps.io/) is a statistical plotting service run by RStudio.
We can plot the histogram of all torrents uploaded on Kickass for the past 24 hours.
Well ... looks like kickass restricted their access to their API :( ... making this little fun project go defunct. Spoiler alert ... there was a *lot* of porn.
The application in this repository can be seen [here](http://bnngj.shinyapps.io/kickAss).
<file_sep>/server.R
library(shiny)
url <- "https://kickass.so/hourlydump.txt.gz"
download.file(url, "./hourlydump.txt.gz", method="wget")
tbl <- read.table(gzfile('hourlydump.txt.gz'), header=FALSE,
sep='|', fill=T, comment.char="", quote="",
col.names = c("hash", "title", "category", "url", "torrent"))
tt <- table(tbl$category)
labels <- paste(names(tt))
shinyServer(function(input, output, session) {
output$distPlot <- renderPlot({
t <- barplot(tt, xaxt="n", ylim=c(0,300+max(tt)), space=1, las=2,
col=rainbow(input$colors), ylab="Number of Torrents",
xlab="Categories", main="Kickass...")
axis(2,at=seq(0,1000+max(tt),500), cex=.85, las=2)
text(t, labels=labels, par("usr")[3], cex=1.2, srt=45, xpd=TRUE, adj=c(1.1,1.1))
})
})<file_sep>/ui.R
library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("Kickass .... "),
sidebarLayout(
sidebarPanel(
p("so we decided to see what kind of torrents are uploaded on kickass ..."),
sliderInput("colors", label = h3("wow, many colors"), min = 9,
max = 15, value = 9)
),
mainPanel( plotOutput("distPlot") )
)
)
) | 385084b3cf769191a05f1c44bc65487c07ffceb2 | [
"Markdown",
"R"
] | 3 | Markdown | capusta/torrentStats | b57014b999e7da467f55a7574f7b0cdb5217c560 | 083bdf0775f048ce1e79345d4712ee1c744d70b5 |
refs/heads/master | <file_sep>package spliteven
func Find(s []int) int {
if len(s) < 3 {
return -1
}
head := 0
tail := len(s) - 1
sum1 := s[head]
sum2 := s[tail]
for head < tail {
if sum1 > sum2 {
tail -= 1
sum2 += s[tail]
} else {
head += 1
sum1 += s[head]
}
}
if sum1 == sum2 {
return head
}
return -1
}
<file_sep>package main
import (
"fmt"
"github.com/jmgao1983/mygo/fb/stringutil"
)
func main() {
fmt.Printf("Hello, world.\n")
fmt.Printf(stringutil.Reverse("\nhello, world!"))
}
<file_sep>package spliteven
import (
"fmt"
"testing"
)
func TestFind(t *testing.T) {
cases := []struct {
in []int
want int
}{
{[]int{3, 20, 1, 17, 2, 4}, 2},
{[]int{3, 20, 0, 0, 0, 1, 17, 2, 4}, 5},
{[]int{3, 20, 0, 0, 0, 0, 17, 2, 4}, 5},
{[]int{3, 20, 1, 17, 2, 4, 0, 0, 0, 0, 0}, 2},
{[]int{4, 5, 9}, -1},
{[]int{}, -1},
}
for i, c := range cases {
got := Find(c.in)
fmt.Printf("%03d: ", i)
fmt.Print(c.in)
fmt.Printf("Find() == %d, want %d", got, c.want)
if got != c.want {
t.Errorf(" >>Failed!\n")
} else {
fmt.Printf(" >>Success!\n")
}
}
}
<file_sep># gosetup
#### 介绍
利用ansible自动安装配置golang开发环境
#### 安装
以 Ubuntu18.04 为例
- 安装ansible
```
apt install python3-pip
pip3 install ansible==2.6.12
```
- 准备
```
ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa > /dev/null
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
host_if=$(ip route|grep default|cut -d' ' -f5)
host_ip=$(ip a|grep "$host_if$"|awk '{print $2}'|cut -d'/' -f1)
ssh-keyscan -t ecdsa -H "$host_ip" >> /root/.ssh/known_hosts
```
- 安装go
```
ansible-playbook roles/gosetup/gosetup.yml
```
<file_sep># mygo
#### 介绍
learning golang
<file_sep># letgo
LeetCode playground with golang
<file_sep>package stringutil
import (
"testing"
"fmt"
)
func TestReverse(t *testing.T) {
cases := []struct {
in, want string
}{
{"Hello, world", "dlrow ,olleH"},
{"Hello, 世界", "界世 ,olleH"},
{"", ""},
}
for i, c := range cases {
got := Reverse(c.in)
fmt.Printf("[%03d]: Reverse(%q) == %q, want %q", i, c.in, got, c.want)
if got != c.want {
t.Errorf("\tFailed!\n")
}else{
fmt.Printf("\tSuccess!\n")
}
}
}
| a8f65ecc77141a83d1cded4eb622fa0e685916af | [
"Markdown",
"Go"
] | 7 | Go | jmgao1983/mygo | e900f602652be11ffac7b2745aadc74880be8f46 | 8989a5c871bce1e54c73a0a7f11bbe1e0feb8d4c |
refs/heads/master | <repo_name>meaghanbass/GH-ResumeBuilder<file_sep>/TemplatePackage/contact_variables.php
<?php
// Contact Variables
$contactName = "<NAME>";
$contactTitle = "Job Title";
$contactLocation = "Location, USA";
$contactPhone = "888.123.4567";
$contactEmail = "<EMAIL>";
$contactWebsite = "johndoe.com";
$contactGithub = "https://github.com/johndoe";
$contactGithubHandle = "johndoe";
$contactLinkedin = "https://www.linkedin.com/in/johndoe/";
$contactTwitter = "https://twitter.com/johndoe?lang=en";
$contactCodepen = "https://codepen.io/johndoe/";
// About Variables
$aboutMe = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ligula orci, euismod a finibus ac, blandit ultricies risus. Etiam hendrerit, purus ac venenatis rutrum, augue libero tristique nibh, vel rhoncus lorem massa ut neque. Nulla egestas mattis suscipit. Pellentesque mattis, elit finibus lobortis malesuada, purus elit dignissim velit, et finibus nisl enim eu urna.";
$resumeSummary = "";
?><file_sep>/global/variables.php
<?php
$siteTitle = "ProDesigner";
?><file_sep>/TemplatePackage/class_project.php
<?php
class Project {
public function __construct($projectTitle, $projectSummary, $projectTools, $projectLinkResume, $projectLinkGithub, $projectLinkDirect) {
$this->projectTitle = $projectTitle;
$this->projectSummary = $projectSummary;
$this->projectTools = $projectTools;
$this->projectLinkResume = $projectLinkResume;
$this->projectLinkGithub = $projectLinkGithub;
$this->projectLinkDirect = $projectLinkDirect;
}
public function displayProjectCard() {
echo '<div class="card mt-4 col-12 col-md-10" >
<div class="card-body">
<h5 class="card-title">' . $this->projectTitle . '</h5>
<p class="card-text">' . $this->projectSummary . '</p>
<p class="tools">' . $this->projectTools . '</p>
<a href="' . $this->projectLinkGithub . '" target="_blank" class="card-link git-link"><i class="fab fa-github"></i></a>
<a href="' . $this->projectLinkDirect . '" target="_blank" class="card-link direct-link"><i class="fas fa-external-link-alt"></i></a>
</div>
</div>';
}
public function displayProjectWord() {
echo '
<p class=MsoNormal style="margin-bottom:0in;margin-bottom:.0001pt;line-height: 115%">
<strong>
<span style="font-size:9.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif; mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi">'
. $this->projectTitle .
'</span>
</strong>
<span style="font-size:9.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif;mso-bidi-font-family:Arial; mso-bidi-theme-font:minor-bidi; font-weight:normal;mso-bidi-font-weight:bold">
|
</span>
<strong>
<i style="mso-bidi-font-style:normal">
<span style="font-size:9.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif;mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi;color:#7F7F7F;mso-themecolor:text1;mso-themetint:128;font-weight:normal;mso-bidi-font-weight:bold">'
. $this->projectLinkGithub .
'</span>
</i>
</strong>
<strong>
<span style="font-size:9.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif;mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi">
<o:p></o:p>
</span>
</strong>
</p>
<p class=MsoNoSpacing><span style="font-size:9.0pt;font-family:Source Sans Pro,sans-serif">'
. $this->projectSummary .
'<span class=Emphasis-SmallChar> ('
. $this->projectTools .
')</span>
</span>
<span style="font-family:Source Sans Pro,sans-serif">
<o:p></o:p>
</span>
</p>
<p class=MsoNoSpacing><span style="font-family:Source Sans Pro,sans-serif"><o:p> </o:p></span></p>
';
}
};
?>
<?php
$projects = array(
new Project(
"Project Title 1",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed augue magna, fermentum vitae malesuada congue, pellentesque vitae velit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean id magna nec leo mattis elementum.",
"Tools | Tools | Tools | Tools",
"https://google.com",
"https://google.com",
"https://google.com"
),
new Project(
"Project Title 2",
"Phasellus lobortis leo ac ornare venenatis. Suspendisse nec feugiat orci. Sed mollis euismod est, nec efficitur urna bibendum consectetur. Sed tincidunt nulla eu orci convallis, vel placerat ipsum finibus.",
"Tools | Tools | Tools | Tools",
"www.projectsite.com",
"www.projectsite.com",
"www.projectsite.com"
),
new Project(
"Project Title 3",
"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean vitae dignissim neque, at mattis odio.",
"Tools | Tools | Tools | Tools",
"www.projectsite.com",
"www.projectsite.com",
"www.projectsite.com"
)
);
?><file_sep>/TemplatePackage/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css">
<link rel="stylesheet" href="styles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<?php include 'contact_variables.php'; ?>
<?php include 'class_project.php'; ?>
<?php include 'class_job.php'; ?>
<title><?php echo $contactName; ?> | <?php echo $contactTitle; ?></title>
</head>
<body>
<!-- Site Wrapper -->
<div class="container">
<!-- Page 1 Contact -->
<div class="row align-items-center page" id="home">
<div class="col align-self-center text-center">
<div class="row justify-content-center nav fixed-top pt-4 pb-3 bg-white">
<a href="#home" class="mr-3">Home</a>
<a href="#about" class="ml-3 mr-3">About Me</a>
<a href="#portfolio" class="ml-3 mr-3">Portfolio</a>
<a href="resume.php" target="_blank" class="ml-3 mr-3">Resume</a>
<a href="#contact" class="ml-3">Contact</a>
</div>
<!-- Navbar Shadow -->
<script>
var $document = $(document),
$element = $('.nav'),
className = 'nav-shadow';
$document.scroll(function() {
if ($document.scrollTop() >= 200) {
// Change 50 to the value you require
// for the event to trigger
$element.addClass(className);
} else {
$element.removeClass(className);
}
});
</script>
<h1><?php echo $contactName; ?></h1>
<h4><?php echo $contactTitle; ?></h4>
<div class="row justify-content-center social-links">
<a href=<?php echo $contactGithub; ?> target="_blank" title="Github">
<i class="fab fa-github"></i>
</a>
<a href=<?php echo $contactLinkedin; ?> target="_blank" title="LinkedIn">
<i class="fab fa-linkedin"></i>
</a>
<a href=<?php echo $contactTwitter; ?> target="_blank" title="Twitter">
<i class="fab fa-twitter"></i>
</a>
<a href=<?php echo $contactCodepen; ?> target="_blank" title="Codepen">
<i class="fab fa-codepen"></i>
</a>
</div>
</div>
</div>
<!-- Page 2 About Me -->
<div class="row align-items-center page" id="about">
<div class="col align-self-center text-center">
<h3 class="pb-5">About Me</h3>
<div class="col-12 col-sm-10 offset-sm-1 col-md-8 offset-md-2">
<p><?php echo $aboutMe; ?></p>
</div>
</div>
</div>
<!-- Page 3 Portfolio -->
<div class="row justify-content-center pt-5" id="portfolio">
<div class="col-12 text-center pb-5 pt-5">
<h3>Portfolio</h3>
</div>
<!-- Projects -->
<?php
foreach ($projects as $project) {
$project->displayProjectCard();
};
?>
</div>
<!-- Page 4 Contact -->
<div class="row align-items-center page" id="contact">
<div class="col-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2">
<div class="col align-self-center text-center">
<h3 class="pb-5">Contact</h3>
</div>
<?php include 'contact.php'; ?>
</div>
</div>
<!-- Footer -->
<div class="footer text-center pt-5">
<h6>© <?php echo date("Y"); ?> - <?php echo $contactName; ?></h6>
</div>
</div>
<!-- End Site Wrapper -->
</body>
</html><file_sep>/TemplatePackage/class_job.php
<?php
$jobs = array(
array(
"Software Engineer",
"ETrade Financial",
"July 2012",
"Present",
"Main responsibilities include customer service systems.",
"1MySQL | Oracle | Access | SAP",
array(
"Participated in sales presentations due to ability to translate user needs into easy-to-understand software solutions. Helped sales team close five major deals generating more than $150K in revenue."
),
),
array(
"Sytems Programmer",
"Intel Corporation",
"January 2008",
"July 2012",
" ",
"2Java | Visual Basic | ASP | XML",
array(
"Provided user requirements analysis, design and programming support for enhancement of Web application accessed by 5 million users worldwide.",
"Fueled additional revenue stream through responsive customer support, generating $18K in new license sales within first few weeks of new product release"
),
),
array(
"Sytems Programmer",
"Intel Corporation",
"January 2008",
"July 2012",
"Focused on remote servers and SSL product analysis.",
"3Java | Visual Basic | ASP | XML",
array(
"Provided user requirements analysis, design and programming support for enhancement of Web application accessed by 5 million users worldwide.",
"Fueled additional revenue stream through responsive customer support, generating $18K in new license sales within first few weeks of new product release"
),
)
);
?><file_sep>/themes.php
<?php include 'global/nav.php'; ?>
<?php include 'under-construction.php'; ?>
<?php include 'global/footer.php'; ?><file_sep>/global/footer.php
<footer>
<section class="text-center">
<div class="button-container">
<a href="docs.php">
<button type="button" class="btn btn-aqua btn-lg mt-5 mb-5">Get Started</button>
</a>
<a href="tutorial.php">
<button type="button" class="btn btn-link btn-lg mt-5 mb-5 aqua">Take the tutorial
<svg height="12" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4.53657 8.69699"><path d="
M.18254,8.697a.18149.18149,0,0,1-.12886-.31034L4.09723,4.34126.05369.29954a.18149.18149,
0,0,1,.2559-.2559L4.4838,4.21785a.18149.18149,0,0,1,0,.2559L.30958,8.648A.18149.18149,
0,0,1,.18254,8.697Z
" fill="currentColor"></path></svg>
</button>
</a>
</div>
</section>
<div class="row pb-5 justify-content-center">
<div class="col-auto pl-5 pr-5 pt-5 ml-5 mr-5">
<div class="footer-header">
<a href="docs.php">Docs</a>
</div>
<!-- <div class="footer-content">
<a class="footer-content-link" href="#">Installation</a>
<a class="footer-content-link" href="#">Usage</a>
<a class="footer-content-link" href="#">FAQ</a>
</div> -->
<div class="footer-header pt-3">
<a href="themes.php">Themes</a>
</div>
</div>
<div class="col-auto pl-5 pt-5 pr-5 ml-5 mr-5">
<div class="footer-header">
Channels
</div>
<div class="footer-content">
<a class="footer-content-link" href="#">Twitter <i class="fas fa-external-link-alt"></i></a>
<a class="footer-content-link" href="#">LinkedIn <i class="fas fa-external-link-alt"></i></a>
</div>
</div>
<div class="col-auto pl-5 pt-5 pr-5 ml-5 mr-5">
<a class="navbar-brand pl-5 pr-5 mr-0 aqua fw-700" href="index.php">
<?php echo $siteTitle; ?>
<img src="images/check-form.svg" width="30" height="30" class="d-inline-block align-top" alt="">
</a>
<p class="pl-5 pr-5 mt-3">Copyright © 2019 <?php echo $siteTitle; ?></p>
</div>
</div>
</footer>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep>/global/nav.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css">
<link rel="stylesheet" href="style.css">
<?php include 'variables.php'; ?>
<title><?php echo $siteTitle; ?></title>
</head>
<body>
<div class="container-fluid pl-0 pr-0">
<div class="navbar-custom">
<nav class="navbar navbar-expand-lg pt-3 pb-3 w-75 mx-auto">
<a class="navbar-brand pr-5 aqua fw-700" href="index.php">
<?php echo $siteTitle; ?>
<img src="images/check-form.svg" width="30" height="30" class="d-inline-block align-top" alt="">
</a>
<button class="navbar-toggler bg-dark navbar-light" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link pr-4" href="docs.php">Docs<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link pr-4" href="themes.php">Themes<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link pr-4" href="tutorial.php">Tutorial</a>
</li>
</ul>
<!-- <form class="form-inline my-2 my-lg-0">
<div class="input-group">
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Search..." id="example-search-input">
<span class="input-group-append">
<div class="input-group-text bg-white"><i class="fa fa-search"></i></div>
</span>
</div>
</form> -->
</div>
</nav>
</div>
<file_sep>/index.php
<?php include 'global/nav.php'; ?>
<div class="jumbotron jumbotron-fluid text-center header">
<div class="container pt-5 pb-5">
<h1 class="display-4 aqua fw-700 pb-3"><?php echo $siteTitle; ?></h1>
<p class="lead mt-3">A web portfolio and resume template package.</p>
<p class="lead">Updated from a single file. </p>
<section>
<div class="button-container">
<a href="docs.php">
<button type="button" class="btn btn-aqua btn-lg mt-5">Get Started</button>
</a>
<a href="tutorial.php">
<button type="button" class="btn btn-link btn-lg mt-5 aqua">Take the tutorial
<svg height="12" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4.53657 8.69699"><path d="
M.18254,8.697a.18149.18149,0,0,1-.12886-.31034L4.09723,4.34126.05369.29954a.18149.18149,
0,0,1,.2559-.2559L4.4838,4.21785a.18149.18149,0,0,1,0,.2559L.30958,8.648A.18149.18149,
0,0,1,.18254,8.697Z
" fill="currentColor"></path></svg>
</button>
</a>
</div>
</section>
</div>
</div>
<!-- <img src="images/files.svg" class="hero-svg pt-5"> -->
<!-- <img src="images/online-site.svg" class="hero-svg pt-5"> -->
<div class="col-12 col-md-10 offset-md-1 website-demo">
<div class="website-demo-header text-center">
Edit just a few variables here:
</div>
<div class="justify-content-center mx-auto embedded-code pl-3 pt-5 pb-5" style="width:510px;" id="editorjs">
<code>
$contactName = "<NAME>";<br>
$contactTitle = "Job Title";<br>
$contactLocation = "Location, USA";<br>
$contactPhone = "888.123.4567";<br>
$contactEmail = "<EMAIL>";<br>
$contactWebsite = "johndoe.com";<br>
$contactGithub = "https://github.com/johndoe";<br>
$contactGithubHandle = "johndoe";<br>
$contactLinkedin = "https://www.linkedin.com/in/johndoe/";<br>
$contactTwitter = "https://twitter.com/johndoe?lang=en";<br>
$contactCodepen = "https://codepen.io/johndoe/";
</code>
</div>
<div class="website-demo-header text-center">
To automatically populate your portfolio and resume:
<p>Edit your online presence and your resume from a single document.</p>
</div>
<div class="row">
<div class="col-xs-12 col-xl-6 pt-5">
<div class="website-demo-inner">
<embed src="http://resio.meaghanbass.io" class="website-demo-inner-embed">
</div>
</div>
<div class="col-xs-12 col-xl-6 pt-5">
<div class="website-demo-inner">
<embed src="demo-resume.pdf" type="application/pdf" class="website-demo-inner-embed">
</div>
</div>
</div>
</div>
<?php include 'global/footer.php'; ?><file_sep>/TemplatePackage/resume.php
<?php include 'contact_variables.php'; ?>
<?php include 'class_project.php'; ?>
<?php include 'class_job.php'; ?>
<!-- EXPORT BUTTON -->
<style>
.input-button {
background-color: #5468ff;
color: white;
cursor:pointer;
border: 1px solid transparent;
padding: .375rem .75rem;
border-radius: .25rem;
font-size:13px;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
.input-button:focus {
box-shadow: none;
outline:none;
}
form {
font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
color:white !important;
font-size:13px;
line-height:18px;
justify-content:center;
display:flex;
}
a {
color:white !important;
font-size:13px;
line-height:18px;
}
form a:link {
text-decoration:none;
}
</style>
<form name="export-button" action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post">
<input type="submit" name="submit_docs" value="Download Resume - PC" class="input-button" /> $nbsp;
<a href="resume.php" download="<?php echo $contactName; ?> Resume.doc" class="input-button">Download Resume - Mac</a>
</form>
<br><br>
<!-- END EXPORT BUTTON -->
<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 15">
<meta name=Originator content="Microsoft Word 15">
<link rel=File-List href="ResDoc_files/filelist.xml">
<link rel=Edit-Time-Data href="ResDoc_files/editdata.mso">
<title><?php echo $contactName; ?> | Resume</title>
<style>
<!--
/* Font Definitions */
@font-face
{font-family:Wingdings;
panose-1:5 0 0 0 0 0 0 0 0 0;
mso-font-charset:2;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:0;
mso-generic-font-family:roman;
mso-font-pitch:variable;
mso-font-signature:-536869121 1107305727 33554432 0 415 0;}
@font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;
mso-font-charset:0;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:-536859905 -1073732485 9 0 511 0;}
@font-face
{font-family:"Raleway Light";
panose-1:2 11 4 3 3 1 1 6 0 3;
mso-font-charset:0;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:-1610611969 1342185563 0 0 151 0;}
@font-face
{font-family:"Times New Roman \(Headings CS\)";
panose-1:0 0 0 0 0 0 0 0 0 0;
mso-font-charset:0;
mso-generic-font-family:roman;
mso-font-format:other;
mso-font-pitch:auto;
mso-font-signature:0 0 0 0 0 0;}
@font-face
{font-family:"Source Sans Pro";
panose-1:2 11 5 3 3 4 3 2 2 4;
mso-font-charset:0;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:1610613495 33554433 0 0 415 0;}
@font-face
{font-family:"Times New Roman \(Body CS\)";
panose-1:0 0 0 0 0 0 0 0 0 0;
mso-font-alt:"Times New Roman";
mso-font-charset:0;
mso-generic-font-family:roman;
mso-font-format:other;
mso-font-pitch:auto;
mso-font-signature:0 0 0 0 0 0;}
@font-face
{font-family:"Yu Gothic Light";
panose-1:2 11 3 0 0 0 0 0 0 0;
mso-font-charset:128;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:-536870145 717749759 22 0 131231 0;}
@font-face
{font-family:"\@Yu Gothic Light";
mso-font-charset:128;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:-536870145 717749759 22 0 131231 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin-top:0in;
margin-right:0in;
margin-bottom:8.0pt;
margin-left:0in;
line-height:107%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:Arial;
mso-bidi-theme-font:minor-bidi;}
p.MsoTitle, li.MsoTitle, div.MsoTitle
{mso-style-priority:10;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-link:"Title Char";
mso-style-next:Normal;
margin:0in;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:28.0pt;
font-family:"Calibri Light",sans-serif;
mso-ascii-font-family:"Calibri Light";
mso-ascii-theme-font:major-latin;
mso-fareast-font-family:"Yu Gothic Light";
mso-fareast-theme-font:major-fareast;
mso-hansi-font-family:"Calibri Light";
mso-hansi-theme-font:major-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
letter-spacing:-.5pt;
mso-font-kerning:14.0pt;}
p.MsoTitleCxSpFirst, li.MsoTitleCxSpFirst, div.MsoTitleCxSpFirst
{mso-style-priority:10;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-link:"Title Char";
mso-style-next:Normal;
mso-style-type:export-only;
margin:0in;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:28.0pt;
font-family:"Calibri Light",sans-serif;
mso-ascii-font-family:"Calibri Light";
mso-ascii-theme-font:major-latin;
mso-fareast-font-family:"Yu Gothic Light";
mso-fareast-theme-font:major-fareast;
mso-hansi-font-family:"Calibri Light";
mso-hansi-theme-font:major-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
letter-spacing:-.5pt;
mso-font-kerning:14.0pt;}
p.MsoTitleCxSpMiddle, li.MsoTitleCxSpMiddle, div.MsoTitleCxSpMiddle
{mso-style-priority:10;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-link:"Title Char";
mso-style-next:Normal;
mso-style-type:export-only;
margin:0in;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:28.0pt;
font-family:"Calibri Light",sans-serif;
mso-ascii-font-family:"Calibri Light";
mso-ascii-theme-font:major-latin;
mso-fareast-font-family:"Yu Gothic Light";
mso-fareast-theme-font:major-fareast;
mso-hansi-font-family:"Calibri Light";
mso-hansi-theme-font:major-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
letter-spacing:-.5pt;
mso-font-kerning:14.0pt;}
p.MsoTitleCxSpLast, li.MsoTitleCxSpLast, div.MsoTitleCxSpLast
{mso-style-priority:10;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-link:"Title Char";
mso-style-next:Normal;
mso-style-type:export-only;
margin:0in;
margin-bottom:.0001pt;
mso-add-space:auto;
mso-pagination:widow-orphan;
font-size:28.0pt;
font-family:"Calibri Light",sans-serif;
mso-ascii-font-family:"Calibri Light";
mso-ascii-theme-font:major-latin;
mso-fareast-font-family:"Yu Gothic Light";
mso-fareast-theme-font:major-fareast;
mso-hansi-font-family:"Calibri Light";
mso-hansi-theme-font:major-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
letter-spacing:-.5pt;
mso-font-kerning:14.0pt;}
a:link, span.MsoHyperlink
{mso-style-priority:99;
color:#6B9F25;
mso-themecolor:hyperlink;
text-decoration:underline;
text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-noshow:yes;
mso-style-priority:99;
color:#8C8C8C;
mso-themecolor:followedhyperlink;
text-decoration:underline;
text-underline:single;}
p.MsoAcetate, li.MsoAcetate, div.MsoAcetate
{mso-style-noshow:yes;
mso-style-priority:99;
mso-style-link:"Balloon Text Char";
margin:0in;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:9.0pt;
font-family:"Times New Roman",serif;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;}
p.MsoNoSpacing, li.MsoNoSpacing, div.MsoNoSpacing
{mso-style-priority:1;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
mso-style-link:"No Spacing Char";
margin:0in;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:Arial;
mso-bidi-theme-font:minor-bidi;}
span.MsoSubtleEmphasis
{mso-style-priority:19;
mso-style-unhide:no;
mso-style-qformat:yes;
color:#404040;
mso-themecolor:text1;
mso-themetint:191;
font-style:italic;}
span.MsoIntenseEmphasis
{mso-style-priority:21;
mso-style-unhide:no;
mso-style-qformat:yes;
color:#E32D91;
mso-themecolor:accent1;
font-style:italic;}
span.TitleChar
{mso-style-name:"Title Char";
mso-style-priority:10;
mso-style-unhide:no;
mso-style-locked:yes;
mso-style-link:Title;
mso-ansi-font-size:28.0pt;
mso-bidi-font-size:28.0pt;
font-family:"Calibri Light",sans-serif;
mso-ascii-font-family:"Calibri Light";
mso-ascii-theme-font:major-latin;
mso-fareast-font-family:"Yu Gothic Light";
mso-fareast-theme-font:major-fareast;
mso-hansi-font-family:"Calibri Light";
mso-hansi-theme-font:major-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:major-bidi;
letter-spacing:-.5pt;
mso-font-kerning:14.0pt;}
p.Emphasis-Small, li.Emphasis-Small, div.Emphasis-Small
{mso-style-name:"Emphasis - Small";
mso-style-update:auto;
mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"No Spacing";
mso-style-link:"Emphasis - Small Char";
margin-top:0in;
margin-right:0in;
margin-bottom:0in;
margin-left:.5in;
margin-bottom:.0001pt;
line-height:115%;
mso-pagination:widow-orphan;
font-size:9.0pt;
font-family:"Source Sans Pro",sans-serif;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-bidi-font-family:Arial;
mso-bidi-theme-font:minor-bidi;
color:#6663E3;
font-style:italic;
mso-bidi-font-style:normal;}
span.NoSpacingChar
{mso-style-name:"No Spacing Char";
mso-style-priority:1;
mso-style-unhide:no;
mso-style-locked:yes;
mso-style-link:"No Spacing";}
span.Emphasis-SmallChar
{mso-style-name:"Emphasis - Small Char";
mso-style-unhide:no;
mso-style-locked:yes;
mso-style-parent:"No Spacing Char";
mso-style-link:"Emphasis - Small";
mso-ansi-font-size:9.0pt;
mso-bidi-font-size:9.0pt;
font-family:"Source Sans Pro",sans-serif;
mso-ascii-font-family:"Source Sans Pro";
mso-hansi-font-family:"Source Sans Pro";
color:#6663E3;
font-style:italic;
mso-bidi-font-style:normal;}
span.BalloonTextChar
{mso-style-name:"Balloon Text Char";
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-unhide:no;
mso-style-locked:yes;
mso-style-link:"Balloon Text";
mso-ansi-font-size:9.0pt;
mso-bidi-font-size:9.0pt;
font-family:"Times New Roman",serif;
mso-ascii-font-family:"Times New Roman";
mso-hansi-font-family:"Times New Roman";
mso-bidi-font-family:"Times New Roman";}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:Arial;
mso-bidi-theme-font:minor-bidi;}
.MsoPapDefault
{mso-style-type:export-only;
margin-bottom:8.0pt;
line-height:107%;}
@page WordSection1
{size:8.5in 11.0in;
margin:.5in .5in .5in .5in;
mso-header-margin:.5in;
mso-footer-margin:.5in;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;max-width:816px;margin-left:auto;margin-right:auto;}
@page WordSection2
{size:8.5in 11.0in;
margin:.5in .5in .5in .5in;
mso-header-margin:.5in;
mso-footer-margin:.5in;
mso-columns:1 even .5in;
mso-paper-source:0;}
div.WordSection2
{page:WordSection2;}
/* List Definitions */
@list l0
{mso-list-id:1089887273;
mso-list-type:hybrid;
mso-list-template-ids:-1528393688 67698689 67698691 67698693 67698689 67698691 67698693 67698689 67698691 67698693;}
@list l0:level1
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Symbol;}
@list l0:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:"Courier New";}
@list l0:level3
{mso-level-number-format:bullet;
mso-level-text:\F0A7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Wingdings;}
@list l0:level4
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Symbol;}
@list l0:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:"Courier New";}
@list l0:level6
{mso-level-number-format:bullet;
mso-level-text:\F0A7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Wingdings;}
@list l0:level7
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Symbol;}
@list l0:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:"Courier New";}
@list l0:level9
{mso-level-number-format:bullet;
mso-level-text:\F0A7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Wingdings;}
@list l1
{mso-list-id:2145468961;
mso-list-type:hybrid;
mso-list-template-ids:1929252276 67698689 67698691 67698693 67698689 67698691 67698693 67698689 67698691 67698693;}
@list l1:level1
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Symbol;}
@list l1:level2
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:"Courier New";}
@list l1:level3
{mso-level-number-format:bullet;
mso-level-text:\F0A7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Wingdings;}
@list l1:level4
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Symbol;}
@list l1:level5
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:"Courier New";}
@list l1:level6
{mso-level-number-format:bullet;
mso-level-text:\F0A7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Wingdings;}
@list l1:level7
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Symbol;}
@list l1:level8
{mso-level-number-format:bullet;
mso-level-text:o;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:"Courier New";}
@list l1:level9
{mso-level-number-format:bullet;
mso-level-text:\F0A7;
mso-level-tab-stop:none;
mso-level-number-position:left;
text-indent:-.25in;
font-family:Wingdings;}
ol
{margin-bottom:0in;}
ul
{margin-bottom:0in;}
-->
</style>
<!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin-top:0in;
mso-para-margin-right:0in;
mso-para-margin-bottom:8.0pt;
mso-para-margin-left:0in;
line-height:107%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:Arial;
mso-bidi-theme-font:minor-bidi;}
</style>
<![endif]--><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1"/>
</o:shapelayout></xml><![endif]-->
</head>
<body lang=EN-US link="#6B9F25" vlink="#8C8C8C" style='tab-interval:.5in'>
<!-- DO NOT TOUCH THE NEXT 11 LINES OF PHP UNLESS YOU KNOW WHAT YOU ARE DOING - REQUIRED FOR DOWNLOAD! -->
<?php
if(isset($_POST['submit_docs'])){
header("Content-Type: application/vnd.msword");
header("Expires: 0");//no-cache
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");//no-cache
header("content-disposition: attachment;filename=Resume.doc");
}
echo "<html>";
echo "$doc_body";
echo "</html>";
?>
<!-- Now you may touch. -->
<div class=WordSection1>
<!-- Resume Name Heading -->
<p class=MsoTitle align=center style='text-align:center'>
<span style='font-size:32.0pt;font-family:"Raleway Light",sans-serif;mso-bidi-font-family:"Times New Roman \(Headings CS\)";color:black;mso-themecolor:text1;text-transform:uppercase;letter-spacing:10.0pt'>
<?php echo $contactName; ?>
</span>
</p>
<p class=MsoNoSpacing align=center style='text-align:center'><span
style='font-size:9.0pt;mso-bidi-font-size:10.0pt;font-family:"Source Sans Pro",sans-serif;
mso-bidi-font-family:"Times New Roman \(Body CS\)";letter-spacing:1.0pt;
mso-no-proof:yes'><!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600"
o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f"
stroked="f">
<v:stroke joinstyle="miter"/>
<v:formulas>
<v:f eqn="if lineDrawn pixelLineWidth 0"/>
<v:f eqn="sum @0 1 0"/>
<v:f eqn="sum 0 0 @1"/>
<v:f eqn="prod @2 1 2"/>
<v:f eqn="prod @3 21600 pixelWidth"/>
<v:f eqn="prod @3 21600 pixelHeight"/>
<v:f eqn="sum @0 0 1"/>
<v:f eqn="prod @6 1 2"/>
<v:f eqn="prod @7 21600 pixelWidth"/>
<v:f eqn="sum @8 21600 0"/>
<v:f eqn="prod @7 21600 pixelHeight"/>
<v:f eqn="sum @10 21600 0"/>
</v:formulas>
<v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/>
<o:lock v:ext="edit" aspectratio="t"/>
</v:shapetype><![endif]--><![if !vml]><![endif]></span>
<!-- Contact Bar -->
<p class=MsoNoSpacing align=center style='text-align:center;font-size:9.0pt;mso-bidi-font-size:10.0pt; font-family:"Source Sans Pro",sans-serif;mso-bidi-font-family:"Times New Roman \(Body CS\)"'>
<span style='position:relative;top:-1.5pt;mso-text-raise:1.5pt'>
<?php echo $contactLocation; ?> |
</span>
<span>
<span style='position:relative;top:-1.5pt; mso-text-raise:1.5pt' class='Phone-no'>
<?php echo $contactPhone; ?> |
</span>
<span style='position:relative;top:-1.5pt; mso-text-raise:1.5pt'>
<?php echo $contactEmail; ?> |
</span>
<span style='position:relative;top:-1.5pt; mso-text-raise:1.5pt'>
<?php echo $contactWebsite; ?> |
</span>
<span style='position:relative;top:-1.5pt; mso-text-raise:1.5pt'>
<?php echo $contactGithubHandle; ?>
</span>
</span>
</p>
<!-- Line Break -->
<p class=MsoNoSpacing align=center style='text-align:center'><span><o:p> </o:p></span></p>
<!-- Line Break -->
<p class=MsoNoSpacing align=center style='text-align:center'><span><o:p> </o:p></span></p>
<!-- Recent Work & Projects -->
<div style='mso-element:para-border-div;border:none;border-bottom:solid windowtext 1.0pt;mso-border-bottom-alt:solid windowtext .75pt;padding:0in 0in 1.0pt 0in'>
<p class=MsoNoSpacing align=center style='text-align:center;border:none;mso-border-bottom-alt:solid windowtext .75pt;padding:0in;mso-padding-alt:0in 0in 1.0pt 0in'>
<b style='mso-bidi-font-weight:normal'>
<span style='font-family:"Source Sans Pro",sans-serif;mso-bidi-font-family:"Times New Roman \(Body CS\)";letter-spacing:4.0pt'>
RECENT WORK & PROJECTS
<o:p></o:p>
</span>
</b>
</p>
</div>
<!-- Line Break -->
<p class=MsoNoSpacing><span><o:p> </o:p></span></p>
<!-- Recent Work and Projects Loop -->
<!-- Project -->
<?php
foreach ($projects as $project) {
$project->displayProjectWord();
};
?>
<!-- -->
<!-- Experience -->
<div style='mso-element:para-border-div;border:none;border-bottom:solid windowtext 1.0pt;mso-border-bottom-alt:solid windowtext .75pt;padding:0in 0in 1.0pt 0in'>
<p class=MsoNoSpacing align=center style='text-align:center;border:none;mso-border-bottom-alt:solid windowtext .75pt;padding:0in;mso-padding-alt:0in 0in 1.0pt 0in'>
<b style='mso-bidi-font-weight:normal'>
<span style='font-family:"Source Sans Pro",sans-serif; mso-bidi-font-family:"Times New Roman \(Body CS\)";letter-spacing:4.0pt'>
EXPERIENCE
<o:p></o:p>
</span>
</b>
</p>
</div>
<!-- Line Break -->
<p class=MsoNoSpacing><span><o:p> </o:p></span></p>
<!-- Experience Block Loop -->
<?php
foreach ($jobs as $key => $job) {
echo '<p class=MsoNoSpacing style="line-height:115%;tab-stops:right 7.5in">
<strong>
<span style="font-size:9.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif;mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi">'
. $job[0] . ' – ' . $job[1] .
'<span style="mso-tab-count:1">
</span>
</span>
</strong>
<strong>
<span style="font-size:9.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif;mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi;font-weight:normal;mso-bidi-font-weight:bold">'
. $job[2] . ' – ' . $job[3] .
'</span>
</strong>
<span style="font-size:9.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif">
<o:p></o:p>
</span>
</p>';
if ($job[4] == true) {
echo '<p class=MsoNoSpacing><span style="font-size:9.0pt;font-family:Source Sans Pro,sans-serif">' . $job[4] . '</p>';
}
foreach ($job[6] as $key => $attr) {
echo '<p class=MsoNoSpacing style="margin-left:.5in;text-indent:-.25in;line-height: 115%;mso-list:l1 level1 lfo2">
<![if !supportLists]>
<span style="font-size:9.0pt; mso-bidi-font-size:11.0pt;line-height:115%;font-family:Symbol;mso-fareast-font-family: Symbol;mso-bidi-font-family:Symbol">
<span style="mso-list:Ignore">
•<span style="font:7.0pt Times New Roman"> </span>
</span>
</span>
<![endif]>
<span style="font-size:9.0pt;mso-bidi-font-size: 11.0pt;line-height:115%;font-family:Source Sans Pro,sans-serif">'
. $attr .
'<o:p></o:p>
</span>
</p>';
}
if ($job[5] == true) {
echo '<p class=MsoNoSpacing style="margin-left:.5in;line-height: 115%;"><span style="font-size:9.0pt;font-family:Source Sans Pro,sans-serif"><span class=Emphasis-SmallChar> (' . $job[5] . ')</span>
</span>
<span style="font-family:Source Sans Pro,sans-serif">
<o:p></o:p>
</span>
</p>';
}
echo '<p class=MsoNoSpacing><span><o:p> </o:p></span></p>';
}
?>
<!-- -->
<!-- Section Heading Education -->
<div style='mso-element:para-border-div;border:none;border-bottom:solid windowtext 1.0pt; mso-border-bottom-alt:solid windowtext .75pt;padding:0in 0in 1.0pt 0in'>
<p class=MsoNoSpacing align=center style='text-align:center;border:none; mso-border-bottom-alt:solid windowtext .75pt;padding:0in;mso-padding-alt:0in 0in 1.0pt 0in'>
<b style='mso-bidi-font-weight:normal'>
<span style='font-family:"Source Sans Pro",sans-serif; mso-bidi-font-family:"Times New Roman \(Body CS\)";letter-spacing:4.0pt'>
EDUCATION
<o:p></o:p>
</span>
</b>
</p>
</div>
<!-- Line Break -->
<p class=MsoNoSpacing><span><o:p> </o:p></span></p>
<!-- Education Block -->
<p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height: 115%'>
<strong>
<span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif; mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi'>
State University of New York at Oswego –
<o:p></o:p>
</span>
</strong>
<span style='font-size:9.0pt; line-height:115%;font-family:"Source Sans Pro",sans-serif'>
Major in Economics, Minor in Business Administration
<o:p></o:p>
</span>
</p>
<!-- Line Break -->
<p class=MsoNoSpacing><span><o:p> </o:p></span></p>
<!-- Education Block -->
<p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height: 115%'>
<strong>
<span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif; mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi'>
Coursera –
</span>
</strong>
<span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif'>
Front End Web Development with React Specialization
</span>
</p>
<!-- Education Block -->
<p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height: 115%'>
<strong>
<span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif; mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi'>
Coursera –
</span>
</strong>
<span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif'>
Front End JavaScript Frameworks: Angular
</span>
</p>
<!-- Education Block -->
<p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height: 115%'>
<strong>
<span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif; mso-bidi-font-family:Arial;mso-bidi-theme-font:minor-bidi'>
Coursera –
</span>
</strong>
<span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif'>
Building Web Applications in PHP
</span>
</p>
</span>
<strong><span style='font-size:9.0pt;line-height:115%;font-family:"Source Sans Pro",sans-serif;
mso-fareast-font-family:Calibri;mso-fareast-theme-font:minor-latin;mso-bidi-font-family:
Arial;mso-bidi-theme-font:minor-bidi;mso-ansi-language:EN-US;mso-fareast-language:
EN-US;mso-bidi-language:AR-SA'><br clear=all style='page-break-before:auto;
mso-break-type:section-break'>
</span></strong>
<div class=WordSection2>
<p class=MsoNoSpacing style='line-height:115%;tab-stops:13.5pt'><b
style='mso-bidi-font-weight:normal'><span style='font-size:9.0pt;line-height:
115%;font-family:"Source Sans Pro",sans-serif'><o:p> </o:p></span></b></p>
</div>
</body>
</html>
<file_sep>/under-construction.php
<!-- <div class="jumbotron jumbotron-fluid text-center header">
<div class="container pt-5 pb-5">
<h1 class="display-4 aqua fw-700 pb-3">Oops!</h1>
<p class="lead mt-3">We're working on this page right now. Check back shortly!</p>
</div>
</div> -->
<div class="jumbotron jumbotron-fluid text-center header" style="min-height:calc(100vh - 78px - 346px); margin-bottom:0;">
<div class="container pt-5 pb-5">
<h1 class="display-4 aqua fw-700 pb-5"><?php echo $siteTitle; ?></h1>
<p class="lead mt-5">Oops!</p>
<p class="lead mt-5">We're working on this page right now. Check back shortly!</p>
</div>
</div> | 7e9d51b1c2dca5c980e9da4d60f818627932939a | [
"PHP"
] | 11 | PHP | meaghanbass/GH-ResumeBuilder | 865e65dda036bd5d9727517f28e75870a628bbe3 | 765839f7444e7c641466f15995afb511c4727db1 |
refs/heads/master | <file_sep>const express = require('express');
const db = require ('./db');
const mustacheExpress = require('mustache-express');
const bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
// Connect templating engine to app instance
app.engine('mustache', mustacheExpress());
// Connect views folder to views name in app instance
app.set('views', './views');
// Connect view engine to mustache
app.set('view engine', 'mustache');
app.get('/', (request, response, next) => {
db.query('SELECT * FROM runner', [], (err, results) => {
if (err) {
return next(err);
}
response.render('runners', {runners: results.rows});
});
});
app.get('/newRunner', function(request, response) {
response.render('newRunner');
});
app.post('/newRunner', (request, response, next) => {
db.query('INSERT INTO runner (name,sponsor,division) VALUES($1, $2, $3)',[request.body.name, request.body.sponsor, request.body.division], (err, results) => {
if( err){
return next(err);
}
response.redirect('/');
});
});
app.get('/:bib_id', function (request, response, next) {
console.log(request.params.bib_id);
const runnerId = parseInt(request.params.bib_id) - 1;
db.query('SELECT * FROM runner',[], (err,results)=>{
if (err){
return next(err);
}
response.render('runners', { runners: results.rows[runnerId]});
});
});
app.listen(3000,() => {
console.log('Server Farted')
});
| b88d0a561d59483c0bf24c56ee67c595fed924e1 | [
"JavaScript"
] | 1 | JavaScript | Adrianwritenow/runnersSql | 1350c50e445da35691156326babc55449c543f7d | 688c024dcb9872e9ada4bf3b2212e4ca6ec1dbe9 |
refs/heads/master | <file_sep>/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifndef UCT_RC_VERBS_H
#define UCT_RC_VERBS_H
#include <uct/ib/rc/base/rc_iface.h>
#include <uct/ib/rc/base/rc_ep.h>
#include <ucs/type/class.h>
#include "rc_verbs_common.h"
/**
* RC verbs communication context.
*/
typedef struct uct_rc_verbs_ep {
uct_rc_ep_t super;
uct_rc_verbs_txcnt_t txcnt;
#if HAVE_IBV_EX_HW_TM
struct ibv_qp *tm_qp;
#endif
} uct_rc_verbs_ep_t;
/**
* RC verbs interface configuration.
*/
typedef struct uct_rc_verbs_iface_config {
uct_rc_iface_config_t super;
uct_rc_verbs_iface_common_config_t verbs_common;
uct_rc_fc_config_t fc;
#if HAVE_IBV_EX_HW_TM
struct {
int enable;
unsigned list_size;
unsigned rndv_queue_len;
} tm;
#endif
} uct_rc_verbs_iface_config_t;
/**
* RC verbs interface.
*/
typedef struct uct_rc_verbs_iface {
uct_rc_iface_t super;
struct ibv_send_wr inl_am_wr;
struct ibv_send_wr inl_rwrite_wr;
uct_rc_verbs_iface_common_t verbs_common;
#if HAVE_IBV_EX_HW_TM
struct {
uct_rc_srq_t xrq; /* TM XRQ */
unsigned tag_available;
uint8_t enabled;
struct {
void *arg; /* User defined arg */
uct_tag_unexp_eager_cb_t cb; /* Callback for unexpected eager messages */
} eager_unexp;
struct {
void *arg; /* User defined arg */
uct_tag_unexp_rndv_cb_t cb; /* Callback for unexpected rndv messages */
} rndv_unexp;
} tm;
#endif
struct {
unsigned tx_max_wr;
} config;
void (*progress)(void*); /* Progress function (either regular or TM aware) */
} uct_rc_verbs_iface_t;
#define UCT_RC_VERBS_CHECK_AM_SHORT(_iface, _id, _length, _max_inline) \
UCT_CHECK_AM_ID(_id); \
UCT_CHECK_LENGTH(sizeof(uct_rc_am_short_hdr_t) + _length + \
(_iface)->verbs_common.config.notag_hdr_size, \
0, _max_inline, "am_short");
#define UCT_RC_VERBS_CHECK_AM_ZCOPY(_iface, _id, _header_len, _len, _desc_size, _seg_size) \
UCT_RC_CHECK_AM_ZCOPY_DATA(_id, _header_len, _len, _seg_size) \
UCT_CHECK_LENGTH(sizeof(uct_rc_hdr_t) + _header_len + \
(_iface)->verbs_common.config.notag_hdr_size, \
0, _desc_size, "am_zcopy header");
#define UCT_RC_VERBS_GET_TX_TM_DESC(_iface, _mp, _desc, _hdr, _len) \
{ \
UCT_RC_IFACE_GET_TX_DESC(&(_iface)->super, _mp, _desc) \
hdr = _desc + 1; \
len = uct_rc_verbs_notag_header_fill(_iface, _hdr); \
}
#define UCT_RC_VERBS_GET_TX_AM_BCOPY_DESC(_iface, _mp, _desc, _id, _pack_cb, \
_arg, _length, _data_length) \
{ \
void *hdr; \
size_t len; \
UCT_RC_VERBS_GET_TX_TM_DESC(_iface, _mp, _desc, hdr, len) \
(_desc)->super.handler = (uct_rc_send_handler_t)ucs_mpool_put; \
uct_rc_bcopy_desc_fill(hdr + len, _id, _pack_cb, _arg, &(_data_length)); \
_length = _data_length + len + sizeof(uct_rc_hdr_t); \
}
#define UCT_RC_VERBS_GET_TX_AM_ZCOPY_DESC(_iface, _mp, _desc, _id, _header, \
_header_length, _comp, _send_flags, _sge) \
{ \
void *hdr; \
size_t len; \
UCT_RC_VERBS_GET_TX_TM_DESC(_iface, _mp, _desc, hdr, len) \
uct_rc_zcopy_desc_set_comp(_desc, _comp, _send_flags); \
uct_rc_zcopy_desc_set_header(hdr + len, _id, _header, _header_length); \
_sge.length = sizeof(uct_rc_hdr_t) + header_length + len; \
}
#if HAVE_IBV_EX_HW_TM
/* For RNDV TM enabling 2 QPs should be created, one is for sending WRs and
* another one for HW (device will use it for RDMA reads and sending RNDV
* Complete messages).*/
typedef struct uct_rc_verbs_ep_tm_address {
uct_rc_ep_address_t super;
uct_ib_uint24_t tm_qp_num;
} UCS_S_PACKED uct_rc_verbs_ep_tm_address_t;
# define UCT_RC_VERBS_TAG_MIN_POSTED 33
# define UCT_RC_VERBS_TM_ENABLED(_iface) \
(IBV_DEVICE_TM_CAPS(uct_ib_iface_device(&(_iface)->super.super), max_num_tags) && \
(_iface)->tm.enabled)
# define UCT_RC_VERBS_TM_CONFIG(_config, _field) (_config)->tm._field
#else
# define UCT_RC_VERBS_TM_ENABLED(_iface) 0
#endif /* HAVE_IBV_EX_HW_TM */
static UCS_F_ALWAYS_INLINE size_t
uct_rc_verbs_notag_header_fill(uct_rc_verbs_iface_t *iface, void *hdr)
{
#if HAVE_IBV_EX_HW_TM
struct ibv_tm_info tm_info;
uct_ib_device_t *dev = uct_ib_iface_device(&iface->super.super);
if (UCT_RC_VERBS_TM_ENABLED(iface)) {
tm_info.op = IBV_TM_OP_NO_TAG;
return ibv_pack_tm_info(dev->ibv_context, hdr, &tm_info);
}
#endif
return 0;
}
UCS_CLASS_DECLARE_NEW_FUNC(uct_rc_verbs_ep_t, uct_ep_t, uct_iface_h);
UCS_CLASS_DECLARE_DELETE_FUNC(uct_rc_verbs_ep_t, uct_ep_t);
void uct_rc_verbs_ep_am_packet_dump(uct_base_iface_t *iface,
uct_am_trace_type_t type,
void *data, size_t length,
size_t valid_length,
char *buffer, size_t max);
ucs_status_t uct_rc_verbs_ep_put_short(uct_ep_h tl_ep, const void *buffer,
unsigned length, uint64_t remote_addr,
uct_rkey_t rkey);
ssize_t uct_rc_verbs_ep_put_bcopy(uct_ep_h tl_ep, uct_pack_callback_t pack_cb,
void *arg, uint64_t remote_addr,
uct_rkey_t rkey);
ucs_status_t uct_rc_verbs_ep_put_zcopy(uct_ep_h tl_ep,
const uct_iov_t *iov, size_t iovcnt,
uint64_t remote_addr, uct_rkey_t rkey,
uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_get_bcopy(uct_ep_h tl_ep,
uct_unpack_callback_t unpack_cb,
void *arg, size_t length,
uint64_t remote_addr, uct_rkey_t rkey,
uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_get_zcopy(uct_ep_h tl_ep,
const uct_iov_t *iov, size_t iovcnt,
uint64_t remote_addr, uct_rkey_t rkey,
uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_am_short(uct_ep_h tl_ep, uint8_t id, uint64_t hdr,
const void *buffer, unsigned length);
ssize_t uct_rc_verbs_ep_am_bcopy(uct_ep_h tl_ep, uint8_t id,
uct_pack_callback_t pack_cb, void *arg);
ucs_status_t uct_rc_verbs_ep_am_zcopy(uct_ep_h tl_ep, uint8_t id, const void *header,
unsigned header_length, const uct_iov_t *iov,
size_t iovcnt, uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_atomic_add64(uct_ep_h tl_ep, uint64_t add,
uint64_t remote_addr, uct_rkey_t rkey);
ucs_status_t uct_rc_verbs_ep_atomic_fadd64(uct_ep_h tl_ep, uint64_t add,
uint64_t remote_addr, uct_rkey_t rkey,
uint64_t *result, uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_atomic_swap64(uct_ep_h tl_ep, uint64_t swap,
uint64_t remote_addr, uct_rkey_t rkey,
uint64_t *result, uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_atomic_cswap64(uct_ep_h tl_ep, uint64_t compare, uint64_t swap,
uint64_t remote_addr, uct_rkey_t rkey,
uint64_t *result, uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_atomic_add32(uct_ep_h tl_ep, uint32_t add,
uint64_t remote_addr, uct_rkey_t rkey);
ucs_status_t uct_rc_verbs_ep_atomic_fadd32(uct_ep_h tl_ep, uint32_t add,
uint64_t remote_addr, uct_rkey_t rkey,
uint32_t *result, uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_atomic_swap32(uct_ep_h tl_ep, uint32_t swap,
uint64_t remote_addr, uct_rkey_t rkey,
uint32_t *result, uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_atomic_cswap32(uct_ep_h tl_ep, uint32_t compare, uint32_t swap,
uint64_t remote_addr, uct_rkey_t rkey,
uint32_t *result, uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_flush(uct_ep_h tl_ep, unsigned flags,
uct_completion_t *comp);
ucs_status_t uct_rc_verbs_ep_connect_to_ep(uct_ep_h tl_ep,
const uct_device_addr_t *dev_addr,
const uct_ep_addr_t *ep_addr);
ucs_status_t uct_rc_verbs_ep_get_address(uct_ep_h tl_ep, uct_ep_addr_t *addr);
void uct_rc_verbs_iface_progress(void *arg);
ucs_status_t uct_rc_verbs_ep_fc_ctrl(uct_ep_t *tl_ep, unsigned op,
uct_rc_fc_request_t *req);
#endif
<file_sep>
/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2016. ALL RIGHTS RESERVED.
* Copyright (C) UT-Battelle, LLC. 2016. ALL RIGHTS RESERVED.
* Copyright (C) ARM Ltd. 2016.All rights reserved.
* See file LICENSE for terms.
*/
extern "C" {
#include <uct/api/uct.h>
}
#include <common/test.h>
#include "uct_test.h"
class test_error_handling : public uct_test {
public:
virtual void init() {
entity *e1, *e2;
uct_test::init();
set_config("LOG_LEVEL=fatal");
/* To reduce test execution time decrease retransmition timeouts
* where it is relevant */
if (GetParam()->tl_name == "rc" || GetParam()->tl_name == "rc_mlx5" ||
GetParam()->tl_name == "dc" || GetParam()->tl_name == "dc_mlx5") {
set_config("RC_TIMEOUT=0.0001"); /* 100 us should be enough */
set_config("RC_RETRY_COUNT=2");
}
e1 = uct_test::create_entity(0);
m_entities.push_back(e1);
e2 = uct_test::create_entity(0);
m_entities.push_back(e2);
connect(e1, e2);
}
static ucs_status_t am_dummy_handler(void *arg, void *data, size_t length,
unsigned flags) {
return UCS_OK;
}
static ucs_status_t pending_cb(uct_pending_req_t *self)
{
req_count++;
return UCS_OK;
}
static void purge_cb(uct_pending_req_t *self, void *arg)
{
req_count++;
}
static void connect(entity *e1, entity *e2) {
e1->connect(0, *e2, 0);
e2->connect(0, *e1, 0);
uct_iface_set_am_handler(e1->iface(), 0, am_dummy_handler,
NULL, UCT_AM_CB_FLAG_ASYNC);
uct_iface_set_am_handler(e2->iface(), 0, am_dummy_handler,
NULL, UCT_AM_CB_FLAG_ASYNC);
}
void close_peer() {
if (is_ep2ep_tl()) {
m_entities.back()->destroy_ep(0);
} else {
size_t n = m_entities.remove(m_entities.back());
ucs_assert(n == 1);
}
}
uct_ep_h ep() {
return m_entities.front()->ep(0);
}
void flush() {
return m_entities.front()->flush();
}
protected:
bool is_ep2ep_tl() const {
return GetParam()->tl_name == "rc" || GetParam()->tl_name == "rc_mlx5";
}
protected:
static int req_count;
};
int test_error_handling::req_count = 0;
UCS_TEST_P(test_error_handling, peer_failure)
{
check_caps(UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE);
close_peer();
EXPECT_EQ(uct_ep_put_short(ep(), NULL, 0, 0, 0), UCS_OK);
flush();
UCS_TEST_GET_BUFFER_IOV(iov, iovcnt, NULL, 0, NULL, 1);
/* Check that all ep operations return pre-defined error code */
EXPECT_EQ(uct_ep_am_short(ep(), 0, 0, NULL, 0), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_am_bcopy(ep(), 0, NULL, NULL), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_am_zcopy(ep(), 0, NULL, 0, iov, iovcnt, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_put_short(ep(), NULL, 0, 0, 0), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_put_bcopy(ep(), NULL, NULL, 0, 0), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_put_zcopy(ep(), iov, iovcnt, 0, 0, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_get_bcopy(ep(), NULL, NULL, 0, 0, 0, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_get_zcopy(ep(), iov, iovcnt, 0, 0, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_add64(ep(), 0, 0, 0), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_add32(ep(), 0, 0, 0), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_fadd64(ep(), 0, 0, 0, NULL, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_fadd32(ep(), 0, 0, 0, NULL, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_swap64(ep(), 0, 0, 0, NULL, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_swap32(ep(), 0, 0, 0, NULL, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_cswap64(ep(), 0, 0, 0, 0, NULL, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_atomic_cswap32(ep(), 0, 0, 0, 0, NULL, NULL),
UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_flush(ep(), 0, NULL), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_get_address(ep(), NULL), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_pending_add(ep(), NULL), UCS_ERR_ENDPOINT_TIMEOUT);
EXPECT_EQ(uct_ep_connect_to_ep(ep(), NULL, NULL), UCS_ERR_ENDPOINT_TIMEOUT);
}
UCS_TEST_P(test_error_handling, purge_failed_peer)
{
check_caps(UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE);
ucs_status_t status;
int num_pend_sends = 3;
uct_pending_req_t reqs[num_pend_sends];
req_count = 0;
close_peer();
do {
status = uct_ep_put_short(ep(), NULL, 0, 0, 0);
} while (status == UCS_OK);
for (int i = 0; i < num_pend_sends; i ++) {
reqs[i].func = pending_cb;
EXPECT_EQ(uct_ep_pending_add(ep(), &reqs[i]), UCS_OK);
}
flush();
EXPECT_EQ(uct_ep_am_short(ep(), 0, 0, NULL, 0), UCS_ERR_ENDPOINT_TIMEOUT);
uct_ep_pending_purge(ep(), purge_cb, NULL);
EXPECT_EQ(num_pend_sends, req_count);
}
UCT_INSTANTIATE_TEST_CASE(test_error_handling)
<file_sep>/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#include "rc_verbs.h"
#include "rc_verbs_common.h"
#include <uct/api/uct.h>
#include <uct/ib/rc/base/rc_iface.h>
#include <uct/ib/base/ib_device.h>
#include <uct/ib/base/ib_log.h>
#include <uct/base/uct_md.h>
#include <ucs/arch/bitops.h>
#include <ucs/arch/cpu.h>
#include <ucs/debug/log.h>
#include <string.h>
static uct_rc_iface_ops_t uct_rc_verbs_iface_ops;
static ucs_config_field_t uct_rc_verbs_iface_config_table[] = {
{"RC_", "", NULL,
ucs_offsetof(uct_rc_verbs_iface_config_t, super),
UCS_CONFIG_TYPE_TABLE(uct_rc_iface_config_table)},
{"", "", NULL,
ucs_offsetof(uct_rc_verbs_iface_config_t, verbs_common),
UCS_CONFIG_TYPE_TABLE(uct_rc_verbs_iface_common_config_table)},
{"", "", NULL,
ucs_offsetof(uct_rc_verbs_iface_config_t, fc),
UCS_CONFIG_TYPE_TABLE(uct_rc_fc_config_table)},
#if HAVE_IBV_EX_HW_TM
{"TM_ENABLE", "y",
"Enable HW tag matching",
ucs_offsetof(uct_rc_verbs_iface_config_t, tm.enable), UCS_CONFIG_TYPE_BOOL},
{"TM_LIST_SIZE", "64",
"Limits the number of tags posted to the HW for matching. The actual limit \n"
"is a minimum between this value and the maximum value supported by the HW. \n"
"-1 means no limit.",
ucs_offsetof(uct_rc_verbs_iface_config_t, tm.list_size), UCS_CONFIG_TYPE_UINT},
{"TM_RX_RNDV_QUEUE_LEN", "128",
"Length of receive queue in the QP owned by the device. It is used for receiving \n"
"RNDV Complete messages sent by the device",
ucs_offsetof(uct_rc_verbs_iface_config_t, tm.rndv_queue_len), UCS_CONFIG_TYPE_UINT},
#endif
{NULL}
};
static UCS_F_NOINLINE void uct_rc_verbs_handle_failure(uct_ib_iface_t *ib_iface,
void *arg)
{
struct ibv_wc *wc = arg;
uct_rc_verbs_ep_t *ep;
extern ucs_class_t UCS_CLASS_NAME(uct_rc_verbs_ep_t);
uct_rc_iface_t *iface = ucs_derived_of(ib_iface, uct_rc_iface_t);
ep = ucs_derived_of(uct_rc_iface_lookup_ep(iface, wc->qp_num),
uct_rc_verbs_ep_t);
if (ep != NULL) {
ucs_log(iface->super.super.config.failure_level,
"Send completion with error: %s",
ibv_wc_status_str(wc->status));
uct_rc_txqp_purge_outstanding(&ep->super.txqp, UCS_ERR_ENDPOINT_TIMEOUT, 0);
uct_set_ep_failed(&UCS_CLASS_NAME(uct_rc_verbs_ep_t),
&ep->super.super.super,
&iface->super.super.super);
}
}
void uct_rc_verbs_ep_am_packet_dump(uct_base_iface_t *base_iface,
uct_am_trace_type_t type,
void *data, size_t length,
size_t valid_length,
char *buffer, size_t max)
{
uct_rc_verbs_iface_t *iface = ucs_derived_of(base_iface,
uct_rc_verbs_iface_t);
uct_rc_ep_am_packet_dump(base_iface, type,
data + iface->verbs_common.config.notag_hdr_size,
length - iface->verbs_common.config.notag_hdr_size,
valid_length, buffer, max);
}
static UCS_F_ALWAYS_INLINE void
uct_rc_verbs_iface_poll_tx(uct_rc_verbs_iface_t *iface)
{
uct_rc_verbs_ep_t *ep;
uint16_t count;
int i;
unsigned num_wcs = iface->super.super.config.tx_max_poll;
struct ibv_wc wc[num_wcs];
ucs_status_t status;
UCT_RC_VERBS_IFACE_FOREACH_TXWQE(&iface->super, i, wc, num_wcs) {
count = uct_rc_verbs_txcq_get_comp_count(&wc[i]);
ep = ucs_derived_of(uct_rc_iface_lookup_ep(&iface->super, wc[i].qp_num),
uct_rc_verbs_ep_t);
if (ucs_unlikely((wc[i].status != IBV_WC_SUCCESS) || (ep == NULL))) {
iface->super.super.ops->handle_failure(&iface->super.super, &wc[i]);
continue;
}
uct_rc_verbs_txqp_completed(&ep->super.txqp, &ep->txcnt, count);
uct_rc_txqp_completion_desc(&ep->super.txqp, ep->txcnt.ci);
ucs_arbiter_group_schedule(&iface->super.tx.arbiter, &ep->super.arb_group);
}
iface->super.tx.cq_available += num_wcs;
ucs_arbiter_dispatch(&iface->super.tx.arbiter, 1, uct_rc_ep_process_pending, NULL);
}
void uct_rc_verbs_iface_progress(void *arg)
{
uct_rc_verbs_iface_t *iface = arg;
ucs_status_t status;
status = uct_rc_verbs_iface_poll_rx_common(&iface->super);
if (status == UCS_ERR_NO_PROGRESS) {
uct_rc_verbs_iface_poll_tx(iface);
}
}
#if HAVE_IBV_EX_HW_TM
/* This function check whether the error occured due to "MESSAGE_TRUNCATED"
* error in Tag Matching (i.e. if posted buffer was not enough to fit the
* incoming message). If this is the case the error should be reported in
* the corresponding callback and QP should be reset back to normal. Otherwise
* treat the error as fatal. */
static UCS_F_NOINLINE void
uct_rc_verbs_iface_wc_error(uct_rc_verbs_iface_t *iface, struct ibv_wc *wc)
{
/* TODO: handle MSG TRUNCATED error */
ucs_fatal("Receive completion with error on XRQ: %s",
ibv_wc_status_str(wc->status));
}
static UCS_F_ALWAYS_INLINE void
uct_rc_verbs_iface_tag_handle_notag(uct_rc_verbs_iface_t *iface,
struct ibv_wc *wc)
{
struct ibv_tm_info tm_info;
size_t tm_info_len;
uct_ib_device_t *dev = uct_ib_iface_device(&iface->super.super);
uct_ib_iface_recv_desc_t *ib_desc = (uct_ib_iface_recv_desc_t*)(uintptr_t)wc->wr_id;
void *desc = uct_ib_iface_recv_desc_hdr(&iface->super.super, ib_desc);
VALGRIND_MAKE_MEM_DEFINED(desc, wc->byte_len);
tm_info_len = ibv_unpack_tm_info(dev->ibv_context, desc, &tm_info);
if (ucs_likely(tm_info.op == IBV_TM_OP_NO_TAG)) {
uct_rc_verbs_iface_handle_am(&iface->super, wc,
(uct_rc_hdr_t*)((char*)desc + tm_info_len),
wc->byte_len - tm_info_len);
} else {
ucs_error("Unsupported packet arrived %d", tm_info.op);
}
}
static UCS_F_ALWAYS_INLINE ucs_status_t
uct_rc_verbs_iface_poll_rx_tm(uct_rc_verbs_iface_t *iface)
{
unsigned i;
ucs_status_t status;
unsigned num_wcs = iface->super.super.config.rx_max_poll;
struct ibv_wc wc[num_wcs];
status = uct_ib_poll_cq(iface->super.super.recv_cq, &num_wcs, wc);
if (status != UCS_OK) {
goto out;
}
for (i = 0; i < num_wcs; i++) {
if (ucs_unlikely(wc[i].status != IBV_WC_SUCCESS)) {
uct_rc_verbs_iface_wc_error(iface, &wc[i]);
continue;
}
switch (wc[i].opcode) {
case IBV_WC_TM_NO_TAG:
uct_rc_verbs_iface_tag_handle_notag(iface, &wc[i]);
break;
default:
ucs_error("Wrong opcode in CQE %d", wc[i].opcode);
break;
}
}
iface->tm.xrq.available += num_wcs;
UCS_STATS_UPDATE_COUNTER(iface->super.stats, UCT_RC_IFACE_STAT_RX_COMPLETION, num_wcs);
out:
/* All tag unexpected and AM messages arrive to XRQ */
uct_rc_verbs_iface_post_recv_common(&iface->super, &iface->tm.xrq, 0);
return status;
}
void uct_rc_verbs_iface_progress_tm(void *arg)
{
uct_rc_verbs_iface_t *iface = arg;
ucs_status_t status;
status = uct_rc_verbs_iface_poll_rx_tm(iface);
if (status == UCS_ERR_NO_PROGRESS) {
uct_rc_verbs_iface_poll_tx(iface);
}
}
#endif /* HAVE_IBV_EX_HW_TM */
static ucs_status_t uct_rc_verbs_iface_tag_init(uct_rc_verbs_iface_t *iface,
uct_rc_verbs_iface_config_t *config)
{
#if HAVE_IBV_EX_HW_TM
struct ibv_srq_init_attr_ex srq_init_attr;
ucs_status_t status;
uct_ib_md_t *md = ucs_derived_of(iface->super.super.super.md, uct_ib_md_t);
if (UCT_RC_VERBS_TM_ENABLED(iface)) {
/* Create XRQ with TM capability */
memset(&srq_init_attr, 0, sizeof(srq_init_attr));
srq_init_attr.attr.max_sge = 1;
srq_init_attr.attr.max_wr = ucs_max(UCT_RC_VERBS_TAG_MIN_POSTED,
config->super.super.rx.queue_len);
srq_init_attr.attr.srq_limit = 0;
srq_init_attr.srq_type = IBV_SRQT_TAG_MATCHING;
srq_init_attr.srq_context = iface;
srq_init_attr.pd = md->pd;
srq_init_attr.cq = iface->super.super.recv_cq;
srq_init_attr.tm_cap.max_num_tags = iface->tm.tag_available;
srq_init_attr.tm_cap.max_tm_ops = ucs_min(2*iface->tm.tag_available,
IBV_DEVICE_TM_CAPS(&md->dev, max_tag_ops));
srq_init_attr.comp_mask = IBV_SRQ_INIT_ATTR_TYPE |
IBV_SRQ_INIT_ATTR_PD |
IBV_SRQ_INIT_ATTR_CQ |
IBV_SRQ_INIT_ATTR_TAG_MATCHING;
iface->tm.xrq.srq = ibv_create_srq_ex(md->dev.ibv_context, &srq_init_attr);
if (iface->tm.xrq.srq == NULL) {
ucs_error("Failed to create TM XRQ: %m");
return UCS_ERR_IO_ERROR;
}
iface->tm.xrq.available = srq_init_attr.attr.max_wr;
--iface->tm.tag_available; /* 1 tag should be always available */
status = uct_rc_verbs_iface_prepost_recvs_common(&iface->super, &iface->tm.xrq);
if (status != UCS_OK) {
ibv_destroy_srq(iface->tm.xrq.srq);
return status;
}
}
#endif
return UCS_OK;
}
static ucs_status_t uct_rc_verbs_iface_tag_preinit(uct_rc_verbs_iface_t *iface,
uct_md_h md,
uct_rc_verbs_iface_config_t *config,
const uct_iface_params_t *params,
unsigned *srq_size,
unsigned *rx_hdr_len)
{
#if HAVE_IBV_EX_HW_TM
size_t notag_hdr_size;
struct ibv_tm_info tm_info;
uct_ib_md_t *ib_md = ucs_derived_of(md, uct_ib_md_t);
uct_ib_device_t *dev = &ib_md->dev;
iface->tm.enabled = UCT_RC_VERBS_TM_CONFIG(config, enable);
if (IBV_DEVICE_TM_CAPS(dev, max_num_tags) &&
UCT_RC_VERBS_TM_CONFIG(config, enable)) {
iface->progress = uct_rc_verbs_iface_progress_tm;
iface->tm.eager_unexp.cb = params->eager_cb;
iface->tm.eager_unexp.arg = params->eager_arg;
iface->tm.rndv_unexp.cb = params->rndv_cb;
iface->tm.rndv_unexp.arg = params->rndv_arg;
iface->tm.tag_available = ucs_min(IBV_DEVICE_TM_CAPS(dev, max_num_tags),
UCT_RC_VERBS_TM_CONFIG(config, list_size));
/* Get NO_TAG header size */
tm_info.op = IBV_TM_OP_NO_TAG;
notag_hdr_size = ibv_pack_tm_info(dev->ibv_context, NULL, &tm_info);
*srq_size = UCT_RC_VERBS_TM_CONFIG(config, rndv_queue_len);
*rx_hdr_len = sizeof(uct_rc_hdr_t) + notag_hdr_size;
ucs_debug("Tag Matching enabled: tag list size %d", iface->tm.tag_available);
} else
#endif
{
iface->verbs_common.config.notag_hdr_size = 0;
iface->progress = uct_rc_verbs_iface_progress;
*srq_size = config->super.super.rx.queue_len;
*rx_hdr_len = sizeof(uct_rc_hdr_t);
}
return UCS_OK;
}
static void uct_rc_verbs_iface_tag_cleanup(uct_rc_verbs_iface_t *iface)
{
#if HAVE_IBV_EX_HW_TM
if (UCT_RC_VERBS_TM_ENABLED(iface)) {
if (ibv_destroy_srq(iface->tm.xrq.srq)) {
ucs_warn("failed to destroy TM XRQ: %m");
}
}
#endif
}
static void uct_rc_verbs_iface_init_inl_wrs(uct_rc_verbs_iface_t *iface)
{
iface->verbs_common.config.notag_hdr_size =
uct_rc_verbs_notag_header_fill(iface, iface->verbs_common.am_inl_hdr);
memset(&iface->inl_am_wr, 0, sizeof(iface->inl_am_wr));
iface->inl_am_wr.sg_list = iface->verbs_common.inl_sge;
iface->inl_am_wr.num_sge = 2;
iface->inl_am_wr.opcode = IBV_WR_SEND;
iface->inl_am_wr.send_flags = IBV_SEND_INLINE;
memset(&iface->inl_rwrite_wr, 0, sizeof(iface->inl_rwrite_wr));
iface->inl_rwrite_wr.sg_list = iface->verbs_common.inl_sge;
iface->inl_rwrite_wr.num_sge = 1;
iface->inl_rwrite_wr.opcode = IBV_WR_RDMA_WRITE;
iface->inl_rwrite_wr.send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;
}
void uct_rc_verbs_iface_tag_query(uct_rc_verbs_iface_t *iface,
uct_iface_attr_t *iface_attr)
{
#if HAVE_IBV_EX_HW_TM
if (UCT_RC_VERBS_TM_ENABLED(iface)) {
iface_attr->ep_addr_len = sizeof(uct_rc_verbs_ep_tm_address_t);
/* Redefine AM caps, because we have to send TMH (with NO_TAG
* operation) with every AM message. */
iface_attr->cap.am.max_short -= iface->verbs_common.config.notag_hdr_size;
if (iface_attr->cap.am.max_short <= 0) {
iface_attr->cap.flags &= ~UCT_IFACE_FLAG_AM_SHORT;
}
iface_attr->cap.am.max_bcopy -= iface->verbs_common.config.notag_hdr_size;
iface_attr->cap.am.max_zcopy -= iface->verbs_common.config.notag_hdr_size;
iface_attr->cap.am.max_hdr -= iface->verbs_common.config.notag_hdr_size;
iface_attr->latency.growth += 3e-9; /* + 3ns for TM QP */
}
#endif
}
static ucs_status_t uct_rc_verbs_iface_query(uct_iface_h tl_iface, uct_iface_attr_t *iface_attr)
{
uct_rc_verbs_iface_t *iface = ucs_derived_of(tl_iface, uct_rc_verbs_iface_t);
uct_rc_iface_query(&iface->super, iface_attr);
uct_rc_verbs_iface_common_query(&iface->verbs_common, &iface->super, iface_attr);
iface_attr->latency.growth += 3e-9; /* 3ns per each extra QP */
uct_rc_verbs_iface_tag_query(iface, iface_attr);
return UCS_OK;
}
static UCS_CLASS_INIT_FUNC(uct_rc_verbs_iface_t, uct_md_h md, uct_worker_h worker,
const uct_iface_params_t *params,
const uct_iface_config_t *tl_config)
{
uct_rc_verbs_iface_config_t *config =
ucs_derived_of(tl_config, uct_rc_verbs_iface_config_t);
ucs_status_t status;
struct ibv_qp_cap cap;
struct ibv_qp *qp;
unsigned srq_size;
unsigned rx_hdr_len;
size_t am_hdr_len;
uct_rc_verbs_iface_tag_preinit(self, md, config, params, &srq_size,
&rx_hdr_len);
UCS_CLASS_CALL_SUPER_INIT(uct_rc_iface_t, &uct_rc_verbs_iface_ops, md,
worker, params, &config->super, 0,
config->super.super.rx.queue_len,
rx_hdr_len, srq_size, sizeof(uct_rc_fc_request_t));
self->config.tx_max_wr = ucs_min(config->verbs_common.tx_max_wr,
self->super.config.tx_qp_len);
self->super.config.tx_moderation = ucs_min(self->super.config.tx_moderation,
self->config.tx_max_wr / 4);
am_hdr_len = ucs_max(config->verbs_common.max_am_hdr, rx_hdr_len);
status = uct_rc_verbs_iface_common_init(&self->verbs_common, &self->super,
&config->verbs_common, &config->super,
am_hdr_len);
if (status != UCS_OK) {
goto err;
}
status = uct_rc_verbs_iface_tag_init(self, config);
if (status != UCS_OK) {
goto err_common_cleanup;
}
uct_rc_verbs_iface_init_inl_wrs(self);
/* Check FC parameters correctness */
status = uct_rc_init_fc_thresh(&config->fc, &config->super, &self->super);
if (status != UCS_OK) {
goto err_tag_cleanup;
}
/* Create a dummy QP in order to find out max_inline */
status = uct_rc_iface_qp_create(&self->super, IBV_QPT_RC, &qp, &cap,
self->super.rx.srq.srq,
self->super.config.tx_qp_len);
if (status != UCS_OK) {
goto err_tag_cleanup;
}
ibv_destroy_qp(qp);
self->verbs_common.config.max_inline = cap.max_inline_data;
uct_ib_iface_set_max_iov(&self->super.super, cap.max_send_sge);
status = uct_rc_verbs_iface_prepost_recvs_common(&self->super,
&self->super.rx.srq);
if (status != UCS_OK) {
goto err_tag_cleanup;
}
return UCS_OK;
err_tag_cleanup:
uct_rc_verbs_iface_tag_cleanup(self);
err_common_cleanup:
uct_rc_verbs_iface_common_cleanup(&self->verbs_common);
err:
return status;
}
static UCS_CLASS_CLEANUP_FUNC(uct_rc_verbs_iface_t)
{
uct_rc_verbs_iface_common_cleanup(&self->verbs_common);
uct_rc_verbs_iface_tag_cleanup(self);
}
UCS_CLASS_DEFINE(uct_rc_verbs_iface_t, uct_rc_iface_t);
static UCS_CLASS_DEFINE_NEW_FUNC(uct_rc_verbs_iface_t, uct_iface_t, uct_md_h,
uct_worker_h, const uct_iface_params_t*,
const uct_iface_config_t*);
static UCS_CLASS_DEFINE_DELETE_FUNC(uct_rc_verbs_iface_t, uct_iface_t);
static uct_rc_iface_ops_t uct_rc_verbs_iface_ops = {
{
{
.iface_query = uct_rc_verbs_iface_query,
.iface_flush = uct_rc_iface_flush,
.iface_close = UCS_CLASS_DELETE_FUNC_NAME(uct_rc_verbs_iface_t),
.iface_wakeup_open = uct_ib_iface_wakeup_open,
.iface_wakeup_get_fd = uct_ib_iface_wakeup_get_fd,
.iface_wakeup_arm = uct_ib_iface_wakeup_arm,
.iface_wakeup_wait = uct_ib_iface_wakeup_wait,
.iface_wakeup_signal = uct_ib_iface_wakeup_signal,
.iface_wakeup_close = uct_ib_iface_wakeup_close,
.ep_create = UCS_CLASS_NEW_FUNC_NAME(uct_rc_verbs_ep_t),
.ep_get_address = uct_rc_verbs_ep_get_address,
.ep_connect_to_ep = uct_rc_verbs_ep_connect_to_ep,
.iface_get_device_address = uct_ib_iface_get_device_address,
.iface_is_reachable = uct_ib_iface_is_reachable,
.ep_destroy = UCS_CLASS_DELETE_FUNC_NAME(uct_rc_verbs_ep_t),
.ep_am_short = uct_rc_verbs_ep_am_short,
.ep_am_bcopy = uct_rc_verbs_ep_am_bcopy,
.ep_am_zcopy = uct_rc_verbs_ep_am_zcopy,
.ep_put_short = uct_rc_verbs_ep_put_short,
.ep_put_bcopy = uct_rc_verbs_ep_put_bcopy,
.ep_put_zcopy = uct_rc_verbs_ep_put_zcopy,
.ep_get_bcopy = uct_rc_verbs_ep_get_bcopy,
.ep_get_zcopy = uct_rc_verbs_ep_get_zcopy,
.ep_atomic_add64 = uct_rc_verbs_ep_atomic_add64,
.ep_atomic_fadd64 = uct_rc_verbs_ep_atomic_fadd64,
.ep_atomic_swap64 = uct_rc_verbs_ep_atomic_swap64,
.ep_atomic_cswap64 = uct_rc_verbs_ep_atomic_cswap64,
.ep_atomic_add32 = uct_rc_verbs_ep_atomic_add32,
.ep_atomic_fadd32 = uct_rc_verbs_ep_atomic_fadd32,
.ep_atomic_swap32 = uct_rc_verbs_ep_atomic_swap32,
.ep_atomic_cswap32 = uct_rc_verbs_ep_atomic_cswap32,
.ep_pending_add = uct_rc_ep_pending_add,
.ep_pending_purge = uct_rc_ep_pending_purge,
.ep_flush = uct_rc_verbs_ep_flush
},
.arm_tx_cq = uct_ib_iface_arm_tx_cq,
.arm_rx_cq = uct_ib_iface_arm_rx_cq,
.handle_failure = uct_rc_verbs_handle_failure
},
.fc_ctrl = uct_rc_verbs_ep_fc_ctrl,
.fc_handler = uct_rc_iface_fc_handler
};
static ucs_status_t uct_rc_verbs_query_resources(uct_md_h md,
uct_tl_resource_desc_t **resources_p,
unsigned *num_resources_p)
{
uct_ib_md_t *ib_md = ucs_derived_of(md, uct_ib_md_t);
return uct_ib_device_query_tl_resources(&ib_md->dev, "rc",
(ib_md->eth_pause ? 0 : UCT_IB_DEVICE_FLAG_LINK_IB),
resources_p, num_resources_p);
}
UCT_TL_COMPONENT_DEFINE(uct_rc_verbs_tl,
uct_rc_verbs_query_resources,
uct_rc_verbs_iface_t,
"rc",
"RC_VERBS_",
uct_rc_verbs_iface_config_table,
uct_rc_verbs_iface_config_t);
UCT_MD_REGISTER_TL(&uct_ib_mdc, &uct_rc_verbs_tl);
<file_sep>/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2017. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#include "tag_match.inl"
ucs_status_t ucp_tag_match_init(ucp_tag_match_t *tm)
{
ucs_queue_head_init(&tm->expected);
ucs_queue_head_init(&tm->unexpected);
return UCS_OK;
}
void ucp_tag_match_cleanup(ucp_tag_match_t *tm)
{
}
int ucp_tag_unexp_is_empty(ucp_tag_match_t *tm)
{
return ucs_queue_is_empty(&tm->unexpected);
}
void ucp_tag_exp_remove(ucp_tag_match_t *tm, ucp_request_t *req)
{
ucs_queue_iter_t iter;
ucp_request_t *qreq;
ucs_queue_for_each_safe(qreq, iter, &tm->expected, recv.queue) {
if (qreq == req) {
ucs_queue_del_iter(&tm->expected, iter);
return;
}
}
ucs_bug("expected request not found");
}
<file_sep>/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2017. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifndef UCP_TAG_MATCH_H_
#define UCP_TAG_MATCH_H_
#include <ucp/api/ucp_def.h>
#include <ucp/core/ucp_types.h>
#include <ucs/datastruct/queue_types.h>
#include <ucs/sys/compiler_def.h>
/**
* Tag-match header
*/
typedef struct {
ucp_tag_t tag;
} UCS_S_PACKED ucp_tag_hdr_t;
/**
* Tag-matching context
*/
typedef struct ucp_tag_match {
ucs_queue_head_t expected; /* Expected requests */
ucs_queue_head_t unexpected; /* Unexpected received descriptors */
} ucp_tag_match_t;
ucs_status_t ucp_tag_match_init(ucp_tag_match_t *tm);
void ucp_tag_match_cleanup(ucp_tag_match_t *tm);
void ucp_tag_exp_remove(ucp_tag_match_t *tm, ucp_request_t *req);
int ucp_tag_unexp_is_empty(ucp_tag_match_t *tm);
#endif
| 7a0d1ae494763bf7e61f948ded8530ac2ff2abe7 | [
"C",
"C++"
] | 5 | C | shssf/ucx | e720af3986f4301b066d6adbcc928ed307fb7409 | 8c6af41dd4c38842f54585d27560c6a14aa19123 |
refs/heads/main | <repo_name>bbissm/Cooking-with-React<file_sep>/src/components/RecipeEdit.js
import React, { useContext } from 'react';
import Input from "@material-tailwind/react/Input";
import Textarea from "@material-tailwind/react/Textarea"
import Button from "@material-tailwind/react/Button"
import RecipeIngredientEdit from './RecipeIngredientEdit'
import {RecipeContext} from "./App";
import uuidv4 from 'uuid/dist/v4'
function RecipeEdit({recipe}) {
const {handleRecipeChange,handleRecipeSelect} = useContext(RecipeContext)
function handleChange(changes) {
handleRecipeChange(recipe.id, {...recipe, ...changes})
}
function handleIngredientChange(id, ingredient) {
const newIngredients = [...recipe.ingredients]
const index = newIngredients.findIndex(i => i.id === id)
newIngredients[index] = ingredient
handleChange({ingredients: newIngredients})
}
function handleIngredientAdd() {
const newIngredient = {
id: uuidv4(),
name: '',
amount: ''
}
handleChange({ingredients: [...recipe.ingredients, newIngredient]})
}
function handleIngredientDelete(id) {
handleChange({ingredients: recipe.ingredients.filter(i => i.id !== id)})
}
return (
<div className="w-full">
<div className="md:fixed md:w-1/2 md:pr-8">
<button className="text-6xl flex ml-auto"
onClick={() => handleRecipeSelect(undefined)
}>
×
</button>
<div className="space-y-4">
<Input
type="text"
color="pink"
size="regular"
outline={true}
placeholder="Name"
value={recipe.name}
onChange={e => handleChange({name: e.target.value})}
/>
<Input
type="text"
color="pink"
size="regular"
outline={true}
placeholder="Image"
value={recipe.image}
onChange={e => handleChange({image: e.target.value})}
/>
<Input
type="text"
color="pink"
size="regular"
outline={true}
placeholder="Cook Time"
value={recipe.cookTime}
onChange={e => handleChange({cookTime: e.target.value})}
/>
<Input
type="number"
color="pink"
size="regular"
outline={true}
placeholder="Servings"
value={recipe.servings}
onChange={e => handleChange({servings: parseInt(e.target.value)})}
/>
<Textarea
type="text"
color="pink"
size="regular"
outline={true}
placeholder="Instructions"
value={recipe.instructions}
onChange={e => handleChange({instructions: e.target.value})}
/>
<div className="ingredients">
<div className="flex">
<div className="flex-1">Name</div>
<div className="flex-1">Amount</div>
<div></div>
</div>
{recipe.ingredients.map(ingredient => (
<RecipeIngredientEdit
key={ingredient.id}
handleIngredientChange={handleIngredientChange}
handleIngredientDelete={handleIngredientDelete}
ingredient={ingredient}
/>
))}
<Button
className="mx-auto my-12"
onClick={() => handleIngredientAdd()
}>
Add Ingredient
</Button>
</div>
</div>
</div>
</div>
);
}
export default RecipeEdit;<file_sep>/src/components/SearchBar.js
import React, {useContext} from 'react';
import NavbarInput from "@material-tailwind/react/NavbarInput";
import NavbarCollapse from "@material-tailwind/react/NavbarCollapse";
import {RecipeContext} from "./App";
function SearchBar(props) {
const {handleSearch} = useContext(RecipeContext)
return (
<div>
<NavbarInput type="text" placeholder="Search here" onChange={(e) => handleSearch(e.target.value)} />
</div>
);
}
export default SearchBar;<file_sep>/src/components/IngrendientList.js
import React from 'react';
import Ingredient from "./Ingredient";
function IngrendientList({ingredients}) {
const ingriedientElements = ingredients.map(ingredient => {
return <Ingredient key ={ingredient.id} {...ingredient}/>
})
return (
<ul className="list-disc">
{ingriedientElements}
</ul>
);
}
export default IngrendientList;<file_sep>/src/components/Ingredient.js
import React from 'react';
function Ingredient({name,amount}) {
return (
<>
<li><span>{name}</span><span>{amount}</span></li>
</>
);
}
export default Ingredient;<file_sep>/src/components/RecipeIngredientEdit.js
import React from 'react';
import Input from "@material-tailwind/react/Input";
function RecipeIngredientEdit(props) {
const {
ingredient,
handleIngredientChange,
handleIngredientDelete
} = props
function handleChange(changes) {
handleIngredientChange(ingredient.id, {...ingredient, ...changes})
}
return (
<div className="flex space-x-10">
<Input
type="text"
color="pink"
size="regular"
value={ingredient.name}
onChange={(e) => handleChange({name: e.target.value})}
/>
<Input
type="text"
color="pink"
size="regular"
value={ingredient.amount}
onChange={(e) => handleChange({amount: e.target.value})}
/>
<span
className="text-red-500 text-5xl"
onClick={() => handleIngredientDelete(ingredient.id)}
>
×
</span>
</div>
);
}
export default RecipeIngredientEdit;<file_sep>/README.md
# Cooking-with-React
PSD to Code PSD to Code
Demo --> https://bbissm.github.io/Cooking-with-React/
Dont add tailwind.config.js will cause problems in production build | 9c05c9f7025318d9fb473c6287df0453784618b0 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | bbissm/Cooking-with-React | 3a4f944246fc16ecfbd0ee67cb49eda7a6b237f0 | 46a8f26e6b93b69dcc95f1355d1b94f22991234e |
refs/heads/master | <file_sep>Rails.application.routes.draw do
apipie
root 'welcome#index'
devise_for :users, :controllers => {sessions: 'sessions'}
resources :users, only: [:index]
resources :students
resources :admins, only: [:index, :show, :new, :create, :destroy, :update]
end
<file_sep>class WelcomeController < ApplicationController
api :GET, "", "List welcome"
def index
end
end
<file_sep>// # Place all the behaviors and hooks related to the matching controller here.
// # All this logic will automatically be available in application.js.
// # You can use CoffeeScript in this file: http://coffeescript.org/
"use strict"
// Model
var Person = Backbone.Model.extend({
});
// Collection
var PeopleCollection = Backbone.Collection.extend({
model: Person,
initialize: function (options) {
this.url = "http://yardbook.herokuapp.com/users.json"
},
parse: function(response) {
return response.results;
}
});
// create an instance of PeopleCollection
var people = new PeopleCollection();
people.fetch();<file_sep>require 'rails_helper'
describe UsersController, :type => :controller do
describe "GET index" do
it "shows all users" do
users = create_list(:user, 2)
get :index, format: :json
expect(response).to be_success
data = JSON.parse(response.body)
expect(data).not_to be_empty
expect(data['users'].first['fname']).to eq users.first.fname
end
end
#
# it 'GET #show' do
# #
# end
#
# describe 'POST #create' do
# before {@user_attributes = attributes_for(:user)}
# it 'succeeds when all attributes are set' do
# #
# end
#
#
# it 'fails when a required field is missing' do
# #
# end
# end
#
# describe 'PATCH #update' do
# before {@user = create(:user)}
# it 'succeeds when valid data are changed' do
# #
# end
#
# it 'fails when valid data are changed' do
# #
# end
# end
#
# it 'DELETE #destroy' do
# #
# end
end
<file_sep>require 'rails_helper'
describe SessionsController, :type => :controller do
before :each do
@user = create(:user)
@request.env['devise.mapping'] = Devise.mappings[:user]
end
def login_status(user)
post :create, user: { email: user.email, password: <PASSWORD> }, format: :json
data = JSON.parse(response.body)
data['success'] && data['current_user'] == user.id
end
it 'successfully logs in a user' do
expect(login_status(@user)).to eq true
end
it 'rejects incorrect passwords' do
@user.password = '<PASSWORD>'
expect(login_status(@user)).to eq false
end
it 'rejects incorrect emails' do
@user.email = 'not_email'
expect(login_status(@user)).to eq false
end
it 'successfully logs out a user' do
expect(login_status(@user)).to eq true
get :destroy, format: :json
data = JSON.parse(response.body)
expect(data['log_out']).to eq true
end
end
| 16dc354c7c9766d06c6fc8eb1ba0d217432020a6 | [
"JavaScript",
"Ruby"
] | 5 | Ruby | tylerberry4/yardbook | 7eb31956b1c712cf64e5460b035e47dc4e35cf80 | 87f6be1ee035c6e30db0305ce5084f994d430e4b |
refs/heads/master | <file_sep>import java.awt.Color;
import java.awt.Graphics;
public class Bullet extends Circle{
static int RADIUS = 3;
private double rotation;
public Bullet(Point center, double rotation) {
super(center, RADIUS); // define RADIUS in Bullet class
this.rotation = rotation;
}
@Override
public void paint(Graphics brush, Color color) {
brush.setColor(color);
brush.fillOval((int) center.x, (int) center.y, radius, radius);
}
@Override
public void move() {
center.x += 5 * Math.cos(Math.toRadians(rotation));
center.y += 5 * Math.sin(Math.toRadians(rotation));
}
public Boolean outOfBounds() {
Boolean test = false;
if(this.center.x > 800.0 || this.center.x < 0.0 ) {
test = true;
}
if(this.center.y > 600.0 || this.center.y < 0.0) {
test = true;
}
return test;
}
public Point getCenter() {
Point p = new Point(center.x, center.y);
return p;
}
}
<file_sep>public class Point implements Cloneable {
double x,y;
public Point(double inX, double inY) { x = inX; y = inY; }
public Point clone() {
return new Point(x, y);
}
}
<file_sep>/**
* A representation of a ship.
*/
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
public class Ship extends Polygon implements KeyListener {
public static final int SHIP_WIDTH = 40;
public static final int SHIP_HEIGHT = 25;
private boolean forward;
private boolean right;
private boolean left;
private boolean shoot;
ArrayList<Bullet> bullets= new ArrayList <Bullet>();
public Ship(Point[] inShape, Point inPosition, double inRotation) {
super(inShape, inPosition, inRotation);
}
// Create paint method to paint a ship
public void paint(Graphics brush, Color color) {
Point[] points = getPoints();
int[] xPoints = new int[points.length];
int[] yPoints = new int[points.length];
int nPoints = points.length;
for(int i = 0; i < nPoints; ++i) {
xPoints[i] = (int) points[i].x;
yPoints[i] = (int) points[i].y;
}
brush.setColor(color);
brush.fillPolygon(xPoints, yPoints, nPoints);
}
public void move() {
// Check forward movement
if(forward) {
position.x += 3 * Math.cos(Math.toRadians(rotation));
position.y += 3 * Math.sin(Math.toRadians(rotation));
// This code was developed in milestone 2
if(position.x > Asteroids.SCREEN_WIDTH) {
position.x -= Asteroids.SCREEN_WIDTH;
} else if(position.x < 0) {
position.x += Asteroids.SCREEN_WIDTH;
}
if(position.y > Asteroids.SCREEN_HEIGHT) {
position.y -= Asteroids.SCREEN_HEIGHT;
} else if(position.y < 0) {
position.y += Asteroids.SCREEN_HEIGHT;
}
}
// The polygon class has a rotate() method that needs
// to be called if they are moving right or left
// Check rotation to right
if(right) {
rotate(2);
}
// Check rotation to left
if(left) {
rotate(-2);
}
if(shoot) {
Point [] points= getPoints();
Point center= points[3];
bullets.add(new Bullet(center, rotation));
shoot=false;
}
}
public ArrayList<Bullet> getBullets() {
return bullets;
}
/**
* Following methods set appropriate boolean values when
* arrow keys are pressed.
*/
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
forward = true;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
}
if(e.getKeyCode()== KeyEvent.VK_SPACE) {
shoot= true;
}
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
forward = false;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
left = false;
}
if(e.getKeyCode()== KeyEvent.VK_SPACE) {
shoot=false;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
}
| b6ff165b75f9325bff4142b6656d942ba3572214 | [
"Java"
] | 3 | Java | Mikkelkw/SpaceGame | d819ce806c323acfdaf6fb4e345d255207c72df2 | a3c79ad50648ea98025bf6b8adb591e2542becd7 |
refs/heads/master | <file_sep>package com.ubuntu_labs.covid_19app;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class StatsAdapter extends RecyclerView.Adapter<StatsAdapter.MyViewHolder> {
List<StatsJava> statsJavaList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView confirmed, recovered, deaths, country;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
confirmed = itemView.findViewById(R.id.confirmedStat);
recovered = itemView.findViewById(R.id.recoveredStat);
deaths = itemView.findViewById(R.id.deathStat);
country = itemView.findViewById(R.id.countryStat);
}
}
public StatsAdapter(List<StatsJava> statsJavaList) {
this.statsJavaList = statsJavaList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.stats_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
StatsJava data = statsJavaList.get(position);
holder.country.setText(data.getCountry());
holder.recovered.setText(data.getRecovered());
holder.deaths.setText(data.getDeaths());
holder.confirmed.setText(data.getConfirmed());
}
@Override
public int getItemCount() {
return statsJavaList.size();
}
}
<file_sep># Covid-19 Stats Tracker Android App
A Covid-19 Android App using Android Studio
| 7b536b1c48ad56c524abf5a0fd7fae0524847f44 | [
"Markdown",
"Java"
] | 2 | Java | official-ulabs/Covid-19-Stats-Tracker-Android-App | 5ea10da284776f0d3b769eabc07ddf072b0d8dda | c379b06abc3b9b088fe396825c397cae0a567af7 |
refs/heads/main | <file_sep>import React, { useEffect, useState } from "react";
import User from "./User";
import { getUserVideos } from "../modules/videoManager";
const UserList = () => {
const [users, setUser] = useState([]);
const getUser = () => {
getUserVideos().then(users => setUser(users));
};
useEffect(() => {
getUser()
}, []);
return (
<div className="container">
<div className="row justify-content-center">
{users.map((user) => (
<User user={user} key={user.id} />
))}
</div>
</div>
);
};
export default UserList;
<file_sep>import React, { useEffect, useState } from "react";
import {useHistory} from "react-router-dom";
import { getAllVideos, searchVideos } from "../modules/videoManager";
const VideoSearch = ({setVideos}) => {
return (
<>
Search:
<input type="text" className="tipsearch" onKeyUp={(event) =>
searchVideos(event.target.value, true).then(v => setVideos(v))} placeholder="Search for a post" />
</>
);
};
export default VideoSearch;<file_sep>import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import User from "./User";
import { getUserById } from "../modules/videoManager";
const UserDetails = () => {
const [user, setUser] = useState();
const { id } = useParams();
useEffect(() => {
getUserById(id).then(setUser);
}, []);
if (!user) {
return null;
}
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-sm-12 col-lg-6">
<User user={user} />
</div>
</div>
</div>
);
};
export default UserDetails; | fc2ddbd24d40c469d0c4d40d3c01001f3a55c41e | [
"JavaScript"
] | 3 | JavaScript | sxiong0519/Streamish | ca147a9858b7b30603e98ae49ee2504b56797a7a | ae7fb1e162752eb3beed8831e9b05102c23f6fe5 |
refs/heads/master | <file_sep>Feedbag
=======
Feedbag is Ruby's favorite auto-discovery tool/library!
### Quick synopsis
>> require "feedbag"
=> true
>> Feedbag.find "damog.net/blog"
=> ["http://damog.net/blog/index.rss", "http://damog.net/blog/tags/feed", "http://damog.net/blog/tags/rfeed"]
>> Feedbag.feed? "perl.org"
=> false
>> Feedbag.feed?("http://jobs.perl.org/rss/standard.rss")
=> true
### Installation
$ gem install feedbag
Or just grab feedbag.rb and use it on your own project:
$ wget http://github.com/damog/feedbag/raw/master/lib/feedbag.rb
You can also use the command line tool for quick queries, if you install the gem:
$ feedbag http://rubygems.org/profiles/damog
== http://rubygems.org/profiles/damog:
- http://feeds.feedburner.com/gemcutter-latest
### Why should you use it?
- Because it only uses [Nokogiri](http://nokogiri.org/) as dependency.
- Because it follows modern feed filename conventions (like those ones used by WordPress blogs, or Blogger, etc).
- Because it's a single file you can embed easily in your application.
- Because it's faster than rfeedfinder.
### Author
[<NAME>](http://damog.net/) <[<EMAIL>](mailto:<EMAIL>)>.
### Donations

[Superfeedr](http://superfeedr.com) has kindly financially [supported](https://github.com/damog/feedbag/issues/9) the development of Feedbag.
### Copyright
This is free software. See [COPYING](https://raw.githubusercontent.com/damog/feedbag/master/COPYING) for more information.
<file_sep>require 'test_helper'
class FeedbagTest < Test::Unit::TestCase
context "Feedbag.feed? should know that an RSS url is a feed" do
setup do
@rss_url = 'http://example.com/rss/'
Feedbag.stubs(:find).with(@rss_url).returns([@rss_url])
end
should "return true" do
assert Feedbag.feed?(@rss_url)
end
end
context "Feedbag.feed? should know that an RSS url with parameters is a feed" do
setup do
@rss_url = "http://example.com/data?format=rss"
Feedbag.stubs(:find).with(@rss_url).returns([@rss_url])
end
should "return true" do
assert Feedbag.feed?(@rss_url)
end
end
context "Feedbag find should discover feeds containing atom:link" do
setup do
@feeds = ['http://jenniferlynch.wordpress.com/feed', 'http://lurenbijdeburen.wordpress.com/feed']
end
should "find atom feed" do
@feeds.each do |url|
assert_equal [url], Feedbag.find(url)
end
end
end
end
| a0ca7520dcab72f56f78ee5ecd79b6ef0b01a707 | [
"Markdown",
"Ruby"
] | 2 | Markdown | boram/feedbag | a35b11bdbdf6924a2f808a3e63ef74af5d83e34f | e023a4e1f2cb58532f3335294e48eb6e6ae45936 |
refs/heads/master | <repo_name>Blackcool70/User_Manager<file_sep>/src/main/java/com/usrmngr/client/ui/controllers/ClientMainViewController.java
package com.usrmngr.client.ui.controllers;
import com.usrmngr.client.core.model.Connectors.ADConnector;
import com.usrmngr.client.core.model.Connectors.LDAPConfig;
import com.usrmngr.client.core.model.FXNodeContainer;
import com.usrmngr.client.core.model.User;
import com.usrmngr.util.Alert.AlertMaker;
import com.usrmngr.util.Dialog.DialogMaker;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Pair;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;
import static com.usrmngr.Main.APP_CONFIG_PATH;
public class ClientMainViewController implements Initializable {
private JSONArray data;
private User selectedUser;
@FXML
public VBox leftPane, centerPane;
public GridPane bottomPane;
@FXML
TitledPane basicInfoDropdown, contactInfoDropdown, passwordDropdown;
@FXML
public Label userCount, DN;
@FXML
public ListView<User> userList;
@FXML
public PasswordField password_entry, password_confirm_entry;
@FXML
MenuItem preferencesMenu, configurationsMenu;
private FXNodeContainer allNodes; //todo find better way to get a hold of all the textfields programmatically
private ArrayList<TitledPane> panes;
private ADConnector adConnector;
private LDAPConfig config;
private Pair<String, String> credentials;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
// initAdConnection();
initController();
//loadUserList();
loadDefaultView();
}
private void initAdConnection() {
loadConfigs();
connectToAD(); // will connect or quit
authenticateToAD();
}
private void authenticateToAD() {
credentials = new Pair<>("cn=Administrator,ou=users,ou=company,dc=lab,dc=net","<PASSWORD>!");
//credentials = getCredentials();
adConnector.authenticate(credentials.getKey(), credentials.getValue());//will clean up
}
private void loadConfigs() {
this.config = new LDAPConfig();
try {
this.config.load(APP_CONFIG_PATH);
} catch (IOException e) {
configMenuSelected();
try {
this.config.load(APP_CONFIG_PATH);
} catch (IOException ex) {
AlertMaker.showSimpleAlert("Config", "Failed to load config. Aborting.");
Platform.exit();
System.exit(1);
}
}
}
private void initController() {
allNodes = new FXNodeContainer();
allNodes.addItem((Parent) basicInfoDropdown.getContent());
allNodes.addItem((Parent) contactInfoDropdown.getContent());
panes = new ArrayList<>();
panes.add(basicInfoDropdown);
panes.add(contactInfoDropdown);
panes.add(passwordDropdown);
//action for when a user gets double clicked on the list
userList.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2
) {
selectedUser = userList.getSelectionModel().getSelectedItem();
selectedUser = new User(adConnector.getADUser(selectedUser.getAttribute("cn")));
loadUser(selectedUser);
}
});
}
private void connectToAD() {
adConnector = new ADConnector(this.config);
adConnector.connect();
while (!adConnector.isConnected()) {
if (DialogMaker.showConfirmatoinDialog("Unable to connect, check configuration.")) {
configMenuSelected();
adConnector.connect();
} else {
Platform.exit();
System.exit(0);
}
}
}
private Pair<String, String> getCredentials() {
boolean quit;
Optional<Pair<String, String>> input;
while (true) {
input = DialogMaker.showLoginDialog();
if (input.isEmpty()) {
quit = DialogMaker.showConfirmatoinDialog("Not providing credentials will terminate the application.");
if (quit) {
Platform.exit();
System.exit(0);
}
} else {
Pair<String, String> candaceCred = input.get();
adConnector.connect();
adConnector.authenticate(candaceCred.getKey(), candaceCred.getValue());
if (adConnector.isAuthenticated()) {
break;
} else {
AlertMaker.showSimpleAlert("Alert", "Invalid Credentials, try again.");
}
}
}
return input.get();
}
private void loadDefaultView() {
loadUser(selectedUser);
setAllFieldsDisabled(true);
setMenuDisabled(false);
setUserSectionDisabled(false);
setSaveDisabled(true);
setPasswordDisabled(true);
}
private void disableEdit(boolean disabled) {
setAllFieldsDisabled(disabled);
setSaveDisabled(disabled);
setMenuDisabled(!disabled);
}
//gets full details for the selected user from datasource
private void loadUser(User selectedUser) {
if (selectedUser == null) return;
DN.setText(selectedUser.getAttribute("DN"));
allNodes.getTextFields().forEach(textField ->
textField.setText(selectedUser.getAttribute(textField.getId())));
}
// loads a list of users fetched from source with enough information to be able to query for details on select.
private void loadUserList() {
ObservableList<User> displayableUsers = FXCollections.observableArrayList();
data = getDataFromSource();
try {
for (int i = 0; i < data.length(); i++) {
displayableUsers.add(new User(data.getJSONObject(i)));
}
} catch (JSONException e) {
AlertMaker.showErrorMessage("Fatal Error",e.getMessage());
Platform.exit();
System.exit(1);
}
userCount.setText(String.format("Users: %d", data.length()));
userList.setItems(displayableUsers);
}
private JSONArray getDataFromSource() {
adConnector.authenticate(credentials.getKey(), credentials.getValue());
return adConnector.getAllADUsers("displayName","cn");
}
@FXML
public void editButtonClicked() {
if (selectedUser == null) return;
disableEdit(false);
setPasswordDisabled(true);
}
private void setPasswordDisabled(boolean disabled) {
passwordDropdown.getContent().setMouseTransparent(disabled);
passwordDropdown.setExpanded(!disabled);
}
@FXML
public void addButtonClicked() {
disableEdit(false);
setAllDropdownExpanded(true);
clearAllTextFields();
DN.setText("");
selectedUser = null;
}
private void setSaveDisabled(boolean disabled) {
this.bottomPane.setDisable(disabled);
}
private void clearAllTextFields() {
allNodes.clearTextFields();
}
@FXML
public void cancelButtonClicked() {
if (DialogMaker.showConfirmatoinDialog("Changes will be lost.")) {
clearAllTextFields();
loadDefaultView();
}
}
@FXML
public void saveButtonClicked() {
setMenuDisabled(false);
//do the save
AlertMaker.showSimpleAlert("Save","Save successful.");
loadDefaultView();
loadUser(selectedUser);
}
@FXML
public void passwordResetButtonClicked() {
if (selectedUser == null) return;
setMenuDisabled(true);
setUserSectionDisabled(false);
setPasswordDisabled(false);
setSaveDisabled(false);
}
@FXML
public void deleteButtonClicked() {
if (selectedUser == null) return;
setMenuDisabled(true);
setUserSectionDisabled(false);
setMenuDisabled(true);
setSaveDisabled(false);
}
private void setUserSectionDisabled(boolean disabled) {
basicInfoDropdown.setMouseTransparent(disabled);
basicInfoDropdown.setExpanded(true);
}
private void setMenuDisabled(boolean disabled) {
leftPane.setDisable(disabled);
}
private void setAllDropdownExpanded(boolean expanded) {
panes.forEach(pane -> pane.setExpanded(expanded));
}
private void setAllFieldsDisabled(boolean disabled) {
panes.forEach(pane -> pane.getContent().setMouseTransparent(disabled));
}
public void configMenuSelected() {
String configViewFXML = "/client/fxml/ConfigView.fxml";
String windowTitle = "Configurations";
try {
openChildWindow(windowTitle, configViewFXML);
} catch (IOException e) {
AlertMaker.showSimpleAlert(windowTitle, "Unable to open " + windowTitle + " window.");
e.printStackTrace();
}
}
public void openChildWindow(String title, String fxml) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource(fxml));
Scene config = new Scene(root);
Stage configWindow = new Stage();
// prevents the parent window from being modified before configs are closed.
configWindow.initModality(Modality.WINDOW_MODAL);
configWindow.initOwner(root.getScene().getWindow());
configWindow.setTitle(title);
configWindow.setScene(config);
configWindow.setResizable(false);
configWindow.showAndWait();
}
}
<file_sep>/src/main/java/com/usrmngr/client/core/model/User.java
package com.usrmngr.client.core.model;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class User {
private HashMap<String, String> user;
public User(JSONObject jsonObject) {
this.user = new HashMap<>();
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
try {
user.put(key.toLowerCase(), jsonObject.getString(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String[] getAttributes() {
ArrayList<String> arrayList = new ArrayList<>(user.size());
Collections.addAll(arrayList, user.keySet().toArray(new String[0]));
return arrayList.toArray(new String[user.size()]);
}
public String getAttribute(String string) {
return user.getOrDefault(string.toLowerCase(), "");
}
private void setAttribute(String key) {
setAttribute(key.toLowerCase(), "");
}
private void setAttribute(String key, String value) {
this.user.put(key.toLowerCase(), value);
}
public JSONObject toJSON() {
JSONObject jsonObject = new JSONObject();
try {
String key;
String value;
for (Map.Entry<String, String> attribute : user.entrySet()) {
key = attribute.getKey();
value = attribute.getValue();
jsonObject.put(key, value);
}
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
@Override
public String toString() {
String dn = this.getAttribute("displayName");
String cn = this.getAttribute("cn");
return dn.isEmpty() ? cn : dn;
}
public static void main(String[] args) {
User user = null;
String DATA_PATH = "src/main/resources/samples/MOCK_DATA.json";
JSONArray data = null;
try {
data = new JSONArray();
} catch (JSONException e) {
e.printStackTrace();
}
try {
assert data != null;
user = new User(data.getJSONObject(0));
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(user);
}
}
<file_sep>/src/main/java/com/usrmngr/client/ui/controllers/ConfigViewController.java
package com.usrmngr.client.ui.controllers;
import com.usrmngr.client.core.model.Connectors.LDAPConfig;
import com.usrmngr.util.Alert.AlertMaker;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;
import static com.usrmngr.Main.APP_CONFIG_PATH;
public class ConfigViewController implements Initializable {
@FXML
private GridPane propGrid;
@FXML
private Button saveButton, cancelButton;
private LDAPConfig config;
private TextField[] textFields;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
saveButton.setOnMouseClicked(e -> onSaveClicked());
cancelButton.setOnMouseClicked(e -> onCancelClicked());
config = new LDAPConfig();
try {
config.load(APP_CONFIG_PATH);
} catch (IOException ignored) {
}
if(config.size() == 0)
loadDefault();
displayConfig(config);
}
private void loadDefault() {
config.setServer("localhost");
config.setPort(389);
config.setBaseDN("dc=company,dc=com");
}
private void onCancelClicked() {
// get a handle to the stage
Stage stage = (Stage) cancelButton.getScene().getWindow();
stage.close();
}
private void displayConfig(LDAPConfig config) {
if (config == null) config = new LDAPConfig();
int i = 0;
propGrid.addRow(i);
propGrid.addColumn(i);
Set<String> keys = config.stringPropertyNames();
textFields = new TextField[keys.size()];
for (String key : keys) {
textFields[i] = new TextField(config.getProperty(key));
textFields[i].setId(key);
propGrid.add(new Label(key), 0, i);
propGrid.add(textFields[i],1,i);
++i;
}
}
private void onSaveClicked() {
for (TextField textField : textFields) {
config.put(textField.getId(), textField.getText());
}
try {
config.save(APP_CONFIG_PATH);
AlertMaker.showSimpleAlert("Configuration","Saved");
} catch (IOException e) {
AlertMaker.showSimpleAlert("Configuration","Failed to save config, try again.");
}
}
private static String getPropertiesPath() {
return APP_CONFIG_PATH;
}
}
| f390d2042a425fe32a8ea857e90fe693509a9f59 | [
"Java"
] | 3 | Java | Blackcool70/User_Manager | b69c9a0293f10cca1c7909349999b4a2d3e842a8 | 37c6fa22a52b28c6805edb768cf2fb18b31bb6bc |
refs/heads/master | <file_sep>import vk
from config import VK_ACCESS_TOKEN
def create_api():
session = vk.Session(access_token=VK_ACCESS_TOKEN)
api = vk.API(session)
return api
def get_user_id(api, user_nick):
user_info = api.users.get(user_ids=user_nick)
return user_info[0]['uid']
def get_online_friends(api, user_id):
all_friends = api.friends.get(user_id=user_id, fields='online,photo_200_orig')
online_friends = filter_friends_online(all_friends)
return online_friends
def filter_friends_online(all_friends):
return [friend for friend in all_friends if friend['online'] == 1]
<file_sep>Flask==0.12
itsdangerous==0.24
Jinja2==2.9.5
MarkupSafe==1.0
vk==2.0.2
Werkzeug==0.12.1
gunicorn==19.7.1
Flask-WTF==0.14.2<file_sep># Online friends finder
### What is it?
There is site for find online users from friendlist of chosen user of [VK](https://vk.com).
### How to install?
* Clone this repo
* Install requirements using `pip`: `pip install -r requirements.txt`
* You should have **bower** installed to your PC. [How to install bower](https://bower.io/#install-bower)
* Install bower requirements using `bower update`
* Create `config.py` in root project directory. It should contain all config for Flask project. There is my config:
```
CSRF_ENABLED = True
SECRET_KEY = 'your-secret-random-string-here'
VK_ACCESS_TOKEN = 'vk-app-api-key-here'
```
* Run webserver using command `python index.py`
* Click on the link in terminal to open site in browser
* Let't use it ;)
<file_sep>from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class SearchForm(FlaskForm):
id = StringField('id', validators=[DataRequired(message='User ID or nickname is required!')])
<file_sep>import os
CSRF_ENABLED = True
SECRET_KEY = os.environ["SECRET_KEY"]
VK_ACCESS_TOKEN = os.environ["VK_ACCESS_TOKEN"]<file_sep>from flask import Flask, render_template, request
from helpers import vk_api
from models.forms.search_form import SearchForm
app = Flask(__name__)
app.config.from_object('config')
@app.route('/', methods=["GET"])
def index():
return render_template('index.html')
@app.route('/friends', methods=["GET"])
def friends():
search_form = SearchForm(request.args)
title = 'Enter ID of user you want to explore'
friends = {}
error = None
if search_form.validate():
user_nick = search_form.id.data
try:
api = vk_api.create_api()
user_id = vk_api.get_user_id(api, user_nick)
print(user_id)
friends = vk_api.get_online_friends(api, user_id)
if len(friends) == 0:
title = 'There is no friends'
else:
title = 'I find this friends online'
title += ' in friendlist of user with ID %d' % user_id
except BaseException as catched_error:
title = 'Alarm! An error occurred!'
error = catched_error
return render_template(
'friendlist.html',
friends=friends,
error=error,
title=title,
search_form=search_form
)
if __name__ == '__main__':
app.run()
| 3b26a176dd20e6a42df5772ef4246859dea6e5bd | [
"Markdown",
"Python",
"Text"
] | 6 | Python | poalrom/hw4 | 6fbd5b4e177a12f5da15b8179ca5a21a4dbcdc72 | 15dc7956856e774df50165965f68c8a76aa9d464 |
refs/heads/master | <repo_name>elmoremh/Amanita-Population-Genomics<file_sep>/run_GATK_extract_SNPs_Indels_12-11-17.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 3-00:00 # Runtime in minutes
#SBATCH -p general # Partition to submit to
#SBATCH --mem=20000
#SBATCH -o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/GATK_extract_SNPs_indels_12-11-17_%j.out # Standard out goes to this file
#SBATCH -e /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/GATK_extract_SNPs_indels_12-11-17_%j.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
#run from /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf
module load GATK/3.5-fasrc01
module load jdk/1.8.0_45-fasrc01
java -Xmx16g -jar ~/sw/GenomeAnalysisTK.jar \
-T SelectVariants \
-R /n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.fa \
-V /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/joint_calls_12-1-17.vcf \
-selectType SNP \
-o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf
java -Xmx16g -jar ~/sw/GenomeAnalysisTK.jar \
-T SelectVariants \
-R /n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.fa \
-V /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/joint_calls_12-1-17.vcf \
-selectType INDEL \
-o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_indels_12-11-17.vcf<file_sep>/README.md
# Amanita-Population-Genomics
Scripts used for everything from trimming reads to GATK variant calling and phasing variants. All done in connection with dissertation and the AmanitaBASE project.
<file_sep>/aggregate_fastqc.sh
# Run this script in a directory containing zip files from fastqc. It aggregates images of each type in individual folders
# So looking across data is quick.
zips=`ls *.zip`
for i in $zips; do
unzip -o $i &>/dev/null;
done
fastq_folders=${zips/.zip/}
rm -rf fq_aggregated # Remove aggregate folder if present
mkdir fq_aggregated
# Rename Files within each using folder name.
for folder in $fastq_folders; do
folder=${folder%.*}
img_files=`ls ${folder}/Images/*png`;
for img in $img_files; do
img_name=$(basename "$img");
img_name=${img_name%.*}
new_name=${folder};
mkdir -p fq_aggregated/${img_name};
mv $img fq_aggregated/${img_name}/${folder/_fastqc/}.png;
done;
done;
# Concatenate Summaries
for folder in $fastq_folders; do
folder=${folder%.*}
cat ${folder}/summary.txt >> fq_aggregated/summary.txt
done;
# Concatenate Statistics
for folder in $fastq_folders; do
folder=${folder%.*}
head -n 10 ${folder}/fastqc_data.txt | tail -n 7 | awk -v f=${folder/_fastqc/} '{ print $0 "\t" f }' >> fq_aggregated/statistics.txt
rm -rf ${folder}
done<file_sep>/submit_dedup_11-8-17-test.sh
#!/bin/bash
sbatch ~/Scripts/run_dedup_11-8-17.sh 10004 AGCGATAG-ATAGAGGC<file_sep>/submit_GATK_haplotypecaller_11-17-17.sh
#!/bin/bash
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10003
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10004
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10007
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10016
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10018
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10019
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10169
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10170
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10171
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10175
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10277
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10350
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10354
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10355
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10356
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10380
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10384
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10502
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10503
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10504
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10505
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10506
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10508
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10509
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10510
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10511
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10512
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10513
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10707
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10708
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10709
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10710
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10711
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10712
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10713
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10715
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10716
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10717
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10718
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10719
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10720
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10721
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10801
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10802
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10220
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10220
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10221
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10222
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10223
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10224
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10225
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10226
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10227
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10228
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10229
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10230
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10231
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10232
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10233
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10237
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10238
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10239
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10240
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10241
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10280
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10281
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10282
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10283
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10287
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10288
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10292
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10293
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10294
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10295
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10298
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10299
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10300
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10301
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10303
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10304
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10306
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10309
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10326
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10327
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10328
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10329
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10330
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10331
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10334
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10347
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10348
sleep 1
sleep 1
sbatch ~/Scripts/run_GATK_haplotypecaller_11-17-17.sh 10349<file_sep>/vcf_info_12-13-17.sh
#!/bin/bash
#SBATCH -p general
#SBATCH -n 1
#SBATCH -N 1
#SBATCH --mem 4000
#SBATCH -t 6:00:00
#SBATCH -J vcfINFO
#SBATCH -o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/vcfINFO_%j.out
#SBATCH -e /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/vcfINFO_%j.err
module load vcftools/0.1.14-fasrc01
#extract a variety of summary stats from each interval file for each specified species
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_MQ --get-INFO MQ
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_DP --get-INFO DP
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_RPRS --get-INFO ReadPosRankSum
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_BQRS --get-INFO BaseQRankSum
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_MQRS --get-INFO MQRankSum
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_QD --get-INFO QD
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_MLEAC --get-INFO MLEAC
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_MLEAF --get-INFO MLEAF
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_CRS --get-INFO ClippingRankSum
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_ExH --get-INFO ExcessHet
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_SOR --get-INFO SOR
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_missing --missing-indv
vcftools --vcf /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_snps_12-11-17.vcf --out /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/SNP_stats_FS --get-INFO FS
<file_sep>/run_GATK_indels_default_filter_12-11-17.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 3-00:00 # Runtime in minutes
#SBATCH -p general # Partition to submit to
#SBATCH --mem=20000
#SBATCH -o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/GATK_SNPs_default_filter_12-11-17_%j.out # Standard out goes to this file
#SBATCH -e /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/GATK_SNPs_default_filter_12-11-17_%j.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
#run from /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering
module load GATK/3.5-fasrc01
module load jdk/1.8.0_45-fasrc01
java -Xmx16g -jar ~/sw/GenomeAnalysisTK.jar \
-T VariantFiltration \
-R /n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.fa \
-V /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf/AmanitaBASE_raw_indels_12-11-17.vcf \
--filterExpression "QD < 2.0 || FS > 200.0 || ReadPosRankSum < -20.0" \
--filterName "default_parameters" \
-o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/filtering/AmanitaBASE_indels_default_filter_12-11-17.vcf
<file_sep>/run_whatshap_1-30-19.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 24:00:00 # Runtime in minutes #Tim suggested 72 hours but I just have to see...
#SBATCH -p general # Partition to submit to
#SBATCH --mem=16G
#SBATCH -o whatshap_1-30-19_%j.out # Standard out goes to this file
#SBATCH -e whatshap_1-30-19_%j.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
### run from /n/home15/elmoremh/regal_mhelmore/phasing
SAMPLE=$1
source activate whatshap
whatshap phase -o phased/${SAMPLE}_phased.vcf AmanitaBASE_SNPs_default_filter_12-11-17.vcf bams/${SAMPLE}.dedup.bam
<file_sep>/picard_dict_10-23-17.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 200 # Runtime in minutes
#SBATCH -p general # Partition to submit to
#SBATCH --mem=16000
#SBATCH -o picard_dict_10-23-17.out # Standard out goes to this file
#SBATCH -e picard_dict_10-23-17.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
module load picard/2.9.0-fasrc01
java -jar /n/home15/elmoremh/sw/broadinstitute-picard-b0ac123/src/main/java/picard/sam/CreateSequenceDictionary.java \
R= /n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.fa \
O= /n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.dict
<file_sep>/submit_sort-index-sum_11-9-17.sh
#!/bin/bash
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10003
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10004
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10007
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10016
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10018
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10019
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10169
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10170
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10171
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10175
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10277
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10350
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10354
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10355
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10356
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10380
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10384
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10502
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10503
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10504
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10505
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10506
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10508
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10509
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10510
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10511
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10512
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10513
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10707
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10708
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10709
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10710
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10711
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10712
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10713
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10715
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10716
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10717
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10718
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10719
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10720
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10721
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10801
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10802
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10220
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10220
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10221
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10222
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10223
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10224
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10225
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10226
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10227
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10228
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10229
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10230
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10231
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10232
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10233
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10237
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10238
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10239
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10240
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10241
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10280
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10281
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10282
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10283
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10287
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10288
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10292
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10293
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10294
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10295
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10298
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10299
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10300
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10301
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10303
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10304
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10306
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10309
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10326
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10327
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10328
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10329
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10330
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10331
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10334
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10347
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10348
sleep 1
sleep 1
sbatch ~/Scripts/run_sort-index-sum_11-9-17.sh 10349<file_sep>/run_sort-index-sum_11-9-17.sh
#!/bin/bash
#SBATCH -p serial_requeue
#SBATCH -n 2
#SBATCH -N 1
#SBATCH --mem 16000
#SBATCH -t 4:00:00
#SBATCH -o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/sort_index_sum_%j.out
#SBATCH -e /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/sort_index_sum_%j.err
SAMPLE=$1
module load jdk/1.8.0_45-fasrc01
module load java/1.8.0_45-fasrc01
java -Xmx8g -XX:ParallelGCThreads=1 -jar ~/sw/picard.jar SortSam \
I=/n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/bams/${SAMPLE}.dedup.bam \
O=${SAMPLE}.dedup.sorted.bam \
SORT_ORDER=coordinate
java -Xmx8g -XX:ParallelGCThreads=1 -jar ~/sw/picard.jar BuildBamIndex \
I=/n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/bams/${SAMPLE}.dedup.sorted.bam
java -Xmx8g -XX:ParallelGCThreads=1 -jar ~/sw/picard.jar CollectAlignmentSummaryMetrics \
I=/n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/bams/${SAMPLE}.dedup.sorted.bam \
R=/n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.fa \
METRIC_ACCUMULATION_LEVEL=SAMPLE \
METRIC_ACCUMULATION_LEVEL=READ_GROUP \
O=/n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/metrics/${SAMPLE}.alignment_metrics.txt
java -Xmx8g -XX:ParallelGCThreads=1 -jar ~/sw/picard.jar ValidateSamFile \
I=/n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/bams/${SAMPLE}.dedup.sorted.bam \
O=/n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/metrics/${SAMPLE}.validate.txt MODE=SUMMARY<file_sep>/separate_SNPs_indels_12-7-17.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 5:00:00 # Runtime in minutes
#SBATCH -p general # Partition to submit to
#SBATCH --mem=16000
#SBATCH -o separate_SNPs_indels_12-7-17_%j.out # Standard out goes to this file
#SBATCH -e separate_SNPs_indels_12-7-17_%j.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
#run from /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/vcf
module load vcftools/0.1.14-fasrc01
vcftools --vcf input_file.vcf --remove-indels --recode --recode-INFO-all --out SNPs_only<file_sep>/run_genotypeGVCFs_12-1-17.sh
#!/bin/bash
#SBATCH -p general
#SBATCH -n 2
#SBATCH -N 1
#SBATCH --mem 14000
#SBATCH -t 4-00:00
#SBATCH -J genotypeGVCF
#SBATCH -o /n/regal/haig_lab/mhelmore/alignment_array/GATK/logs/genotypeGVCF_12-1-17_%j.out
#SBATCH -e /n/regal/haig_lab/mhelmore/alignment_array/GATK/logs/genotypeGVCF_12-1-17_%j.err
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sentcd log
module load java/1.8.0_45-fasrc01
module load jdk/1.8.0_45-fasrc01
java -Xmx12g -XX:ParallelGCThreads=1 -jar ~/sw/GenomeAnalysisTK.jar \
-T GenotypeGVCFs \
-R /n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.fa \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10004.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10007.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10016.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10018.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10019.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10169.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10170.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10171.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10175.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10221.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10222.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10223.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10224.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10225.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10226.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10227.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10228.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10229.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10230.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10231.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10232.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10233.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10237.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10238.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10239.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10240.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10241.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10277.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10280.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10281.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10282.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10283.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10287.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10288.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10292.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10293.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10294.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10295.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10298.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10299.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10300.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10301.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10303.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10304.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10306.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10309.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10326.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10327.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10328.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10329.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10330.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10331.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10334.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10347.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10348.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10349.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10350.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10354.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10355.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10356.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10380.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10384.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10502.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10503.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10504.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10505.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10506.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10508.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10509.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10510.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10511.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10512.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10513.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10707.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10708.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10709.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10710.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10711.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10712.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10713.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10715.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10716.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10717.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10718.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10719.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10720.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10721.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10801.raw_variants.g.vcf \
--variant /n/regal/haig_lab/mhelmore/alignment_array/GATK/gvcf/10802.raw_variants.g.vcf \
-o /n/regal/haig_lab/mhelmore/alignment_array/GATK/vcf/joint_calls_12-1-17vcf/<file_sep>/run_GATK_haplotypecaller_11-14-17.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 2-00:00 # Runtime in minutes
#SBATCH -p general # Partition to submit to
#SBATCH --mem=20000
#SBATCH -o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/GATK_haplotypecaller_11-9-17_%j.out # Standard out goes to this file
#SBATCH -e /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/logs/GATK_haplotypecaller_11-9-17_%j.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
module load GATK/3.5-fasrc01
module load jdk/1.8.0_45-fasrc01
SAMPLE=$1
java -Xmx16g -jar ~/sw/GenomeAnalysisTK.jar \
-T HaplotypeCaller \
-R /n/home15/elmoremh/haig_lab_elmoremh/FINAL_ASSEMBLIES/10511_Aphal_PT_AllpathsLG.LINKS.jelly.pilon.fa \
-I /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/bams/${SAMPLE}.dedup.sorted.bam \
--genotyping_mode DISCOVERY \
--emitRefConfidence GVCF \
-o /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/gvcf/${SAMPLE}.raw_variants.g.vcf
<file_sep>/CompareStats.py
import os
import sys
def getStats(path):
for pathname, dirnames, filenames in os.walk(path):
for filename in ( os.path.join(pathname, x) for x in filenames ):
stat = os.stat(filename)
yield filename[len(path):], stat.st_mtime, stat.st_size
sys.exit(tuple(getStats(sys.argv[1])) != tuple(getStats(sys.argv[2])))<file_sep>/whatshap_1-31-19.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 72:00:00 # Runtime in minutes #Tim suggested 72 hours but I just have to see...
#SBATCH -p general # Partition to submit to
#SBATCH --mem=16G
#SBATCH -o whatshap_1-31-19_%j.out # Standard out goes to this file
#SBATCH -e whatshap_1-31-19_%j.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
source activate whatshap
### run from /n/home15/elmoremh/regal_mhelmore/phasing
echo "using 10511.dedup.bam"
whatshap phase -o phased/10511_phased.vcf AmanitaBASE_SNPs_default_filter_12-11-17.vcf bams/10511.dedup.bam
<file_sep>/run_collect_sample_metrics.sh
#!/bin/bash
#SBATCH -n 1 # Number of cores requested
#SBATCH -t 1:00:00 # Runtime in minutes
#SBATCH -p general # Partition to submit to
#SBATCH --mem=16000
#SBATCH -o collect_sample_metrics_12-11-17_%j.out # Standard out goes to this file
#SBATCH -e collect_sample_metrics_12-11-17_%j.err # Standard err goes to this filehostname
#SBATCH --mail-type=ALL # Type of email notification- BEGIN,END,FAIL,ALL
#SBATCH --mail-user=<EMAIL> # Email to which notifications will be sent
#run from /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/metrics
#collect_sample_metrics.py written in python 2
module load python/2.7.13-fasrc01
module load Anaconda/4.3.0-fasrc01
python ~/Scripts/03.2_collect_sample_metrics_holly.py -f /n/home15/elmoremh/regal_mhelmore/alignment_array/GATK/metrics \
-s ~/Scripts/samples.txt -a all_sample.alignment_metrics.txt -d all_sample.dedup.metrics.txt | 8c26c74031a14119b42d5956377aabd650c37543 | [
"Markdown",
"Python",
"Shell"
] | 17 | Shell | elmoremh/Amanita-Population-Genomics | 2fc7e01c0eca86a04afb45b1fcb8c8095b4cb2a5 | 63fab9fa7d8e74319080d4629170221e91eed9d0 |
refs/heads/main | <file_sep>import './view.css';
const View = ({ taskName, taskDate, action, index}) => {
return (
<div className="viewCard">
<div className="viewCardContent">
<div className="viewCardProp">
<h3>{taskName}</h3>
<p>{taskDate}</p>
</div>
<button onClick={() => action(index)}>X</button>
</div>
</div>
);
}
export default View; | cc0b683467a1f4304fba69a865bd91b0fda083c0 | [
"JavaScript"
] | 1 | JavaScript | 5thDimensionalVader/todo-react | 2b711c544ac57822541cb21644921fca7bd24215 | ef2083645ad9d4e174b63402734edf930c954812 |
refs/heads/master | <file_sep>var char1 = new Character("<NAME>");
char1.giveMyselfStats();
console.log(char1);
//get a chest ready
var starting_chest = new NoobChest();
//have character pick out some gear
char1.pickOutSomeGear(starting_chest);
console.log(char1);<file_sep># Rock Paper Scissors
- Create a game with two players (You and a Computer)
- Have the computer by random choose between rock, paper, or scissors
- Create three clickable cards with images representing these options
- Rock > Scissors, Paper > Rock, Scissors > Paper
- Winner is determined by Best-of-five rounds<file_sep># practice-projects
A repo containing a range of mini Javascript projects
<file_sep>function Character(name) {
var self = this;
this.name = name;
this.headSlot = null;
this.chestSlot = null;
this.handSlot = null;
this.legSlot = null;
this.neckSlot = null;
this.ringSlot = null;
this.mainHand = null;
this.offHand = null;
this.giveMyselfStats = function () {
self.strength = rollDice(3,6);
self.dexterity = rollDice(3,6);
self.intelligence = rollDice(3,6);
self.charisma = rollDice(3,6);
self.constitution = rollDice(3,6);
self.willpower = rollDice(3,6);
};
this.giveMyselfAName = function () {
//TODO: do this
};
this.pickOutSomeGear = function (armory) {
self.headSlot = armory.headwear_compartment[easyRand(0,armory.headwear_compartment.length-1)];
self.chestSlot = armory.chestwear_compartment[easyRand(0,armory.chestwear_compartment.length-1)];
self.mainHand = armory.weapons_compartment[easyRand(0,armory.weapons_compartment.length-1)];
if (self.mainHand.isTwoHanded){
self.offHand = self.mainHand;
} else {
self.offHand = armory.shields_compartment[easyRand(0,armory.shields_compartment.length-1)]
}
}
}<file_sep>function Headwear(){
}
function Chestwear(){
}
function Glove(){
}
function Weapon(){
}
function Shield() {
}
//////////Headwear
var sturdy_helmet = new Headwear();
sturdy_helmet.armor = 1;
var mage_crown = new Headwear();
mage_crown.intelligence = 1;
var thief_bandana = new Headwear();
thief_bandana.dexterity = 1;
//////////Chestwear
var chainmail_breastplate = new Chestwear();
chainmail_breastplate.armor = 2;
var mage_robe = new Chestwear();
mage_robe.intelligence = 2;
var sneak_tunic = new Chestwear();
sneak_tunic.dexterity = 2;
/////////Weapons
var giant_greatsword = new Weapon();
giant_greatsword.isTwoHanded = true;
var little_stabby_sword = new Weapon();
///////Sheilds
var iron_buckler = new Shield();
| bab18072f0786b87b9b46aebb60c12acd093576c | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | MattGeller/practice-projects | 226a107dcb5ce4f4505fc4db5c63d73920f47058 | b3427b56167184c0c57fac1626a73d9a9f94ed3c |
refs/heads/master | <repo_name>uk-gov-mirror/ministryofjustice.pfs-hub-fe<file_sep>/src/templates/text.js
import React from 'react'
import Layout from '../components/Layout'
export default ({ pageContext: { content, title, subtitle } }) => (
<>
<Layout>
<div className="govuk-width-container">
<main className="govuk-main-wrapper">
<div className="govuk-grid-row govuk-!-margin-bottom-9">
<div className="govuk-grid-column-two-thirds">
<h1 id="title" className="govuk-heading-xl govuk-!-margin-bottom-6 govuk-!-margin-top-3">{title}</h1>
<p id="stand-first" className="govuk-body-l">{subtitle}</p>
<div id="body" className="gov-uk-dynamic-content" dangerouslySetInnerHTML={{__html: content}}></div>
</div>
</div>
</main>
</div>
</Layout>
</>
)
<file_sep>/gatsby-node.js
const CopyPlugin = require('copy-webpack-plugin');
const axios = require('axios');
const get = endpoint => axios.get(`https://drupal.digital-hub-stage.hmpps.dsd.io/v1/api${endpoint}`);
const getData = ids =>
Promise.all(
ids.map(async id => {
const { data } = await get(`/content/${id}`);
return { ...data };
})
);
exports.createPages = async ({ actions: { createPage } }) => {
const data = await getData(['4391']);
// Create a page that lists all Pokémon.
createPage({
path: `/content/4391`,
component: require.resolve('./src/templates/text.js'),
context: {
title: data[0].title,
subtitle: data[0].stand_first,
content: data[0].description.value,
}
});
};
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
plugins: [
new CopyPlugin([
{
from: "node_modules/govuk-frontend/govuk/assets",
to: './assets'
}
]),
],
})
}
<file_sep>/src/components/Layout.js
import React from 'react'
import { Helmet } from 'react-helmet'
import PropTypes from 'prop-types'
import Clock from './Clock'
import PageNavigation from '../components/PageNavigation'
import '../assets/scss/index.scss'
import contentHubImage from '../assets/images/icons/content-hub.png'
const Layout = ({ blueBar, pageNavigation, children }) => {
return (
<>
<Helmet>
<body className="govuk-template__body" />
</Helmet>
<a href="#main-content" className="govuk-skip-link">Skip to main content</a>
<header className="govuk-header top-bar-container" data-module="header">
<div className="govuk-width-container govuk-body top-bar">
<h1 className="govuk-heading-m">
<img className="hub-logo" src={contentHubImage} alt="logo" />
<a href="/">Content Hub <span>HMP Wayland</span></a>
</h1>
<Clock />
</div>
</header>
{blueBar &&
<div className="govuk-width-container">
<hr className="govuk-section-break govuk-search-section-break--visible" />
</div>
}
{pageNavigation &&
<PageNavigation />
}
{children}
<footer className="govuk-footer" role="contentinfo">
<div className="govuk-width-container ">
<div className="govuk-footer__meta">
<div className="govuk-footer__meta-item govuk-footer__meta-item--grow">
<svg role="presentation" focusable="false" className="govuk-footer__licence-logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 483.2 195.7" height="17" width="41">
<path fill="currentColor" d="M421.5 142.8V.1l-50.7 32.3v161.1h112.4v-50.7zm-122.3-9.6A47.12 47.12 0 0 1 221 97.8c0-26 21.1-47.1 47.1-47.1 16.7 0 31.4 8.7 39.7 21.8l42.7-27.2A97.63 97.63 0 0 0 268.1 0c-36.5 0-68.3 20.1-85.1 49.7A98 98 0 0 0 97.8 0C43.9 0 0 43.9 0 97.8s43.9 97.8 97.8 97.8c36.5 0 68.3-20.1 85.1-49.7a97.76 97.76 0 0 0 149.6 25.4l19.4 22.2h3v-87.8h-80l24.3 27.5zM97.8 145c-26 0-47.1-21.1-47.1-47.1s21.1-47.1 47.1-47.1 47.2 21 47.2 47S123.8 145 97.8 145"></path>
</svg>
<span className="govuk-footer__licence-description">
All content is available under the Open Government Licence v3.0, except where otherwise stated
</span>
</div>
<div className="govuk-footer__meta-item govuk-footer__copyright-logo">© Crown copyright</div>
</div>
</div>
</footer>
</>
)
}
Layout.defaultProps = {
blueBar: false,
pageNavigation: true,
}
Layout.propTypes = {
blueBar: PropTypes.bool,
pageNavigation: PropTypes.bool,
children: PropTypes.node.isRequired,
}
export default Layout
<file_sep>/src/components/Clock.js
import React from 'react'
import { format } from 'date-fns'
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = this.getNewDate(new Date())
}
getNewDate(dateObject) {
return {
dateString: format(dateObject, 'iiii d LLLL'),
timeString: `${format(dateObject, 'h:mm')}${format(dateObject, 'a').toLowerCase()}`,
}
}
tick() {
this.setState(this.getNewDate(new Date()));
}
UNSAFE_componentWillMount() {
this.timerId = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
render() {
return (
<div className="top-bar-time">
<span>{this.state.dateString}</span>
<span>{this.state.timeString}</span>
</div>
);
}
}
export default Clock
<file_sep>/src/components/PopularTopics.js
import React from 'react'
const PopularTopics = () => {
const popularTopics = [
{
title: 'Visits',
url: '/content/4203',
},
{
title: 'IEP',
url: '/content/4204',
},
{
title: 'Games',
url: '/content/3621',
},
{
title: 'Inspiration',
url: '/content/3659',
},
{
title: 'Music & talk',
url: '/content/3662',
},
{
title: 'PSIs & PSOs',
url: '/tags/796',
},
{
title: 'Facilities list & catalogues',
url: ''//getFacilitiesListFor(establishmentId),
},
{
title: 'Healthy mind & body',
url: '/content/3657',
},
{
title: 'Money & debt',
url: '/content/4201',
},
]
return (
<div className="popular-topics">
<h3 className="govuk-heading-s">Popular topics</h3>
<ul>
{popularTopics.map(topic => {
return <li key={topic.title}><a href={topic.url} className="govuk-link">{topic.title}</a></li>
})}
</ul>
</div>
)
}
export default PopularTopics
<file_sep>/src/pages/index.js
import React from 'react'
import Layout from '../components/Layout'
import PopularTopics from '../components/PopularTopics'
import Searchbox from '../components/Searchbox'
import MediaPlayer from '../components/MediaPlayer'
const videoJsOptions = {
autoplay: false,
controls: true,
responsive: true,
sources: [{
src: 'https://drupal.digital-hub-stage.hmpps.dsd.io/sites/default/files/videos/2019-10/Nathan%27s%20Story.mp4',
type: 'video/mp4'
}]
}
export default () => {
return (
<>
<Layout blueBar pageNavigation={false}>
<div className="govuk-width-container home-navigation govuk-!-margin-top-3">
<div className="home-navigation__actions">
<div>
<div className="govuk-clearfix home-navigation__search">
<Searchbox large />
</div>
<a href="/topics" role="button" draggable="false" className="govuk-button govuk-button--start" data-module="govuk-button">
Browse all topics
<svg className="govuk-button__start-icon" xmlns="http://www.w3.org/2000/svg" width="17.5" height="19" viewBox="0 0 33 40" role="presentation" focusable="false">
<path fill="currentColor" d="M0 0h13l20 20-20 20H0l20-20z" />
</svg>
</a>
</div>
<PopularTopics />
</div>
<MediaPlayer { ...videoJsOptions } />
</div>
</Layout>
</>
)
}
<file_sep>/src/components/PageNavigation.js
import React from 'react'
import Searchbox from '../components/Searchbox'
class PageNavigation extends React.Component {
goBack(e) {
e.preventDefault();
window.history.go(-1);
}
goForwards(e) {
e.preventDefault();
window.history.go(1);
}
render() {
return (
<div className="page-navigation">
<nav className="govuk-width-container govuk-body">
<a href="/" className="govuk-link">Homepage</a>
<a href="/" className="govuk-link" id="go-back" onClick={this.goBack}>Back</a>
<a href="/" className="govuk-link" id="go-forwards" onClick={this.goForwards}>Forward</a>
<div>
<Searchbox />
</div>
</nav>
</div>
)
}
}
export default PageNavigation
| 850f4253b0b181f04c6f8fce6abd29f407e0f22a | [
"JavaScript"
] | 7 | JavaScript | uk-gov-mirror/ministryofjustice.pfs-hub-fe | b14841126d995dd207437a32ce538ac4232c0fa3 | b770bf42bad232b39e52f25737ee6940e3482bd8 |
refs/heads/master | <file_sep># Hebrew Text for Watchy
A bit hacky implementation of RTL Hebrew text watchface for [Watchy](https://watchy.sqfmi.com/).

## Creating new fonts
1. Download a ttf file
2. Place it in fontUtils
3. Update file name and desired size in `genGlyphs.sh`
4. All glyph image files will be created
5. Open `font-creator.html` in a web browser
6. Load all glyphs, adjust codes range, adjust `Identifier/Prefix`
7. Click `Generate code`
8. Copy generated code nto a new `*.h` file
9. Import the new file into the sketch and use normally
<file_sep>#!/bin/bash
# Generate bitmap glyphs from given font for supplied char code range
# Make sure the TTF file is in the same library
# example:
# > ./genGlyphs.sh FrankRuhlLibre-Bold 40
#
# To manually generate single glyphs use this command:
# convert -background none -fill black -font FrankRuhlLibre-Regular.ttf -pointsize 50 label:"ת" -colorspace gray -depth 1 154.png
fontFile="$1.ttf"
fontSize=$2
outDir="$1_$2pt"
mkdir -p $outDir
# First latin
for i in $(seq 32 127);
do convert -background white -fill black -font $fontFile -pointsize $fontSize label:"$(printf \\$(printf '%03o' $[$i]))" -colorspace gray -depth 1 $outDir/${i}.png
done;
# Now Hebrew
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"א" -colorspace gray -depth 1 $outDir/128.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ב" -colorspace gray -depth 1 $outDir/129.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ג" -colorspace gray -depth 1 $outDir/130.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ד" -colorspace gray -depth 1 $outDir/131.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ה" -colorspace gray -depth 1 $outDir/132.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ו" -colorspace gray -depth 1 $outDir/133.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ז" -colorspace gray -depth 1 $outDir/134.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ח" -colorspace gray -depth 1 $outDir/135.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ט" -colorspace gray -depth 1 $outDir/136.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"י" -colorspace gray -depth 1 $outDir/137.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ך" -colorspace gray -depth 1 $outDir/138.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"כ" -colorspace gray -depth 1 $outDir/139.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ל" -colorspace gray -depth 1 $outDir/140.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ם" -colorspace gray -depth 1 $outDir/141.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"מ" -colorspace gray -depth 1 $outDir/142.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ן" -colorspace gray -depth 1 $outDir/143.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"נ" -colorspace gray -depth 1 $outDir/144.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ס" -colorspace gray -depth 1 $outDir/145.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ע" -colorspace gray -depth 1 $outDir/146.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ף" -colorspace gray -depth 1 $outDir/147.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"פ" -colorspace gray -depth 1 $outDir/148.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ץ" -colorspace gray -depth 1 $outDir/149.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"צ" -colorspace gray -depth 1 $outDir/150.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ק" -colorspace gray -depth 1 $outDir/151.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ר" -colorspace gray -depth 1 $outDir/152.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ש" -colorspace gray -depth 1 $outDir/153.png
convert -background white -fill black -font $fontFile -pointsize $fontSize label:"ת" -colorspace gray -depth 1 $outDir/154.png
<file_sep>#include <Watchy.h> //include the Watchy library
#include <Fonts/FreeSerifBold9pt7b.h>
//#include "FrankRuhlLibre_Regular40pt8b.h"
//#include "FrankRuhlLibre_Bold40pt8b.h"
#include "Assistant_Regular40pt8b.h"
#include "Assistant_Bold40pt8b.h"
#include "HebrewAsciiCodes.h"
#define TWELVE_HOURS true
#define MAX_CHARS 20
#define MARGIN_X 8
#define MARGIN_TOP 6
#define Y_ADVANCE 45
#define MARK_CHANCE 3
// sync once every 6 hours
#define NTP_SYNC_INTERVAL 6 * 60
RTC_DATA_ATTR int ntpSyncCounter = 0;
#define MARKS_COUNT 7
char *marks [MARKS_COUNT] = {"!", "?", ".", "...", ":", ",", "-"};
char * getRandomMark (int maxIdx = MARKS_COUNT) {
if (random(MARK_CHANCE) == 0) {
return marks[random(min(maxIdx, MARKS_COUNT))];
}
return "";
}
void addMark(char * line1, char * line2, int maxIdx = 999) {
if (strlen(line2) == 0) {
char temp[MAX_CHARS];
strcpy(temp, getRandomMark(maxIdx));
strcat(temp, line1);
strcpy(line1, temp);
} else {
char temp[MAX_CHARS];
strcpy(temp, getRandomMark(maxIdx));
strcat(temp, line2);
strcpy(line2, temp);
}
}
class WatchFace : public Watchy { //inherit and extend Watchy class
public:
void drawWatchFace() { //override this method to customize how the watch face looks
uint16_t lines = 0;
// words
char zero[] = {SAMEKH, PE, ALEPH, 0};
char one[] = {TAV, HET, ALEPH, 0};
char two[] = {MEM_FIN, YOD, YOD, TAV, SHIN, 0};
char three[] = {SHIN, VAV, LAMED, SHIN, 0};
char four[] = {AYIN, BET, RESH, ALEPH, 0};
char five[] = {SHIN, MEM, HET, 0};
char six[] = {SHIN, SHIN, 0};
char seven[] = {AYIN, BET, SHIN, 0};
char eight[] = {HEH, NUN, VAV, MEM, SHIN, 0};
char nine[] = {AYIN, SHIN, TAV, 0};
char ten[] = {RESH, SHIN, AYIN, 0};
char twenty[] = {MEM_FIN, YOD, RESH, SHIN, AYIN, 0};
char thirty[] = {MEM_FIN, YOD, SHIN, VAV, LAMED, SHIN, 0};
char forty[] = {MEM_FIN, YOD, AYIN, BET, RESH, ALEPH, 0};
char fifty[] = {MEM_FIN, YOD, SHIN, YOD, MEM, HET, 0};
char sixty[] = {MEM_FIN, YOD, SHIN, YOD, SHIN, 0};
char seventy[] = {MEM_FIN, YOD, AYIN, BET, SHIN, 0};
char eighty[] = {MEM_FIN, YOD, NUN, VAV, MEM, SHIN, 0};
char ninety[] = {MEM_FIN, YOD, AYIN, SHIN, TAV, 0};
char twoOf[] = {YOD, TAV, SHIN, 0};
char teen[] = {HEH, RESH, SHIN, AYIN, 0};
char plus[] = {VAV, 0};
char midnight[] = {TAV, VAV, TSADI, HET, 0};
char minutes[] = {TAV, VAV, QOF, DALET, 0};
char aMinute[] = {HEH, QOF, DALET, VAV, 0};
char quarter[] = {AYIN, BET, RESH, VAV, 0};
char half[] = {YOD, TSADI, HET, VAV, 0};
char exactly[] = {QOF, VAV, YOD, DALET, BET, 0};
// word arrays
const char *units [11] = {zero, one, two, three, four, five, six, seven, eight, nine, ten};
const char *tens [10] = {zero, ten, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety};
const char *unitsMinutes [11] = {zero, one, twoOf, three, four, five, six, seven, eight, nine, ten};
// Full refresh every 10 minutes
if (currentTime.Minute % 10 == 1) {
//showWatchFace(false);
}
char hrLine1[MAX_CHARS] = "";
char hrLine2[MAX_CHARS] = "";
char mnLine1[MAX_CHARS] = "";
char mnLine2[MAX_CHARS] = "";
// HOURS
if (currentTime.Hour == 0) {
strcpy(hrLine1, midnight); // Midnight
} else {
uint8_t normHour;
if (TWELVE_HOURS && currentTime.Hour > 12) {
normHour = currentTime.Hour % 12;
} else {
normHour = currentTime.Hour;
}
if (normHour < 11) {
strcpy(hrLine1, units[normHour]);
} else if (normHour < 20) {
strcpy(hrLine1, units[normHour - 10]);
strcpy(hrLine2, teen); //teen
} else {
strcpy(hrLine1, tens[normHour / 10]);
if (normHour % 10 > 0) {
strcpy(hrLine2, units[normHour % 10]);
strcat(hrLine2, plus); // and
}
}
}
addMark(hrLine1, hrLine2);
// MINUTES
// special cases
if (currentTime.Minute == 0) {
strcpy(mnLine1, exactly); // exactly
} else if (currentTime.Minute == 1) {
strcpy(mnLine1, aMinute); // and a minute
} else if (currentTime.Minute == 15 && currentTime.Hour % 3 == 0) {
strcpy(mnLine1, quarter); // and a quarter
} else if (currentTime.Minute == 30 && currentTime.Hour % 2 == 0) {
strcpy(mnLine1, half); // and a half
// Other cases
} else if (currentTime.Minute < 11) {
strcpy(mnLine1, unitsMinutes[currentTime.Minute]);
strcat(mnLine1, plus); // and
strcpy(mnLine2, minutes); // minutes
} else if (currentTime.Minute < 20) {
strcpy(mnLine1, units[currentTime.Minute - 10]);
strcat(mnLine1, plus);
strcpy(mnLine2, teen); //teen
} else {
if (currentTime.Minute % 10 > 0) {
strcpy(mnLine1, tens[currentTime.Minute / 10]);
strcpy(mnLine2, units[currentTime.Minute % 10]);
strcat(mnLine2, plus); // and
} else {
strcpy(mnLine1, tens[currentTime.Minute / 10]);
strcat(mnLine1, plus); // and
strcpy(mnLine2, minutes); // minutes
}
}
addMark(mnLine1, mnLine2, 5);
//drawbg
display.fillScreen(GxEPD_WHITE);
display.setTextColor(GxEPD_BLACK);
display.setTextWrap(false);
// Tests
//display.drawBitmap(175, 150, epd_bitmap_aleph, 25, 50, GxEPD_BLACK); //test image
//display.setFont(&frankRuhl_Font);
//display.setCursor(100, 200 - 5);
//display.print("~abaruthk");
//char str[20] = {129, 'A', 'C', 67, 0, 0};
//display.print(str);
//drawtime
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(hrLine1, 0, 0, &x1, &y1, &w, &h);
// HOURS
lines += 1;
//display.setFont(&FrankRuhlLibre_Regular40pt8b);
display.setFont(&Assistant_Regular40pt_Font);
display.getTextBounds(hrLine1, 0, 0, &x1, &y1, &w, &h);
display.setCursor(display.width() - MARGIN_X - w, lines * Y_ADVANCE + MARGIN_TOP);
display.print(hrLine1);
if (strlen(hrLine2) > 0) {
lines += 1;
display.getTextBounds(hrLine2, 0, 0, &x1, &y1, &w, &h);
display.setCursor(display.width() - MARGIN_X - w, lines * Y_ADVANCE + MARGIN_TOP);
display.print(hrLine2);
}
// MINUTES
lines += 1;
//display.setFont(&FrankRuhlLibre_Bold40pt8b);
display.setFont(&Assistant_Bold40pt_Font);
display.getTextBounds(mnLine1, 0, 0, &x1, &y1, &w, &h);
display.setCursor(display.width() - MARGIN_X - w, lines * Y_ADVANCE + MARGIN_TOP);
display.print(mnLine1);
if (strlen(mnLine2) > 0) {
lines += 1;
display.getTextBounds(mnLine2, 0, 0, &x1, &y1, &w, &h);
display.setCursor(display.width() - MARGIN_X - w, lines * Y_ADVANCE + MARGIN_TOP);
display.print(mnLine2);
}
// VOLTAGE
int vBatRounded = (int)(100 * getBatteryVoltage());
display.setFont(&FreeSerifBold9pt7b);
display.setCursor(4, display.height() - 4);
display.print(vBatRounded);
// NTP_SYNC
if (ntpSyncCounter >= NTP_SYNC_INTERVAL) {
syncNTP();
ntpSyncCounter = 0;
} else {
ntpSyncCounter++;
}
}
};
WatchFace m; //instantiate your watchface
void setup() {
m.init(); //call init in setup
randomSeed(m.getBatteryVoltage());
}
void loop() {
// this should never run, Watchy deep sleeps after init();
}
<file_sep>// Constants with Hebrew ascii codes (DOS PC 8-bit ascii)
#define ALEPH 128
#define BET 129
#define GIMEL 130
#define DALET 131
#define HEH 132
#define VAV 133
#define ZAYIN 134
#define HET 135
#define TET 136
#define YOD 137
#define KAF_FIN 138
#define HAF 139
#define LAMED 140
#define MEM_FIN 141
#define MEM 142
#define NUN_FIN 143
#define NUN 144
#define SAMEKH 145
#define AYIN 146
#define PE_FIN 147
#define PE 148
#define TSADI_FIN 149
#define TSADI 150
#define QOF 151
#define RESH 152
#define SHIN 153
#define TAV 154 | 8b36a6ed6e4ded4459f5caaf9e43212bf840288c | [
"Markdown",
"C",
"C++",
"Shell"
] | 4 | Markdown | giladaya/hebrew-text-for-watchy | 4bfdda97b6aa72cde3ebdda1e6d157ff794328d8 | 71d650526e58505455804cfcfe637344b22b729b |
refs/heads/master | <file_sep># crypto
Various odds and ends. Simple functions to complete homework problems for my Cryptography class at University of Pittsburgh.
<file_sep>import math
def blumMicali(g, x, p):
new = pow(g, x, p)
if (new < (p-1)/2):
print 1
else:
print 0
return new
def main():
p = 7919
g = 7
x = 5
for i in range(10):
x = blumMicali(g, x, p)
main()
<file_sep>import math as math
import fractions as fractions
n = input('Enter n: ')
for i in range (2, 100):
x = (2**(math.factorial(i)) - 1) % n
y = fractions.gcd(x, n)
print "2^"+str(i)+"! - 1 mod "+str(n)+" = "+str(x)+"\tgcd("+str(x)+","+str(n)+") = "+str(y)
<file_sep>from math import sqrt; from itertools import count, islice
def main():
myList=[14770,10518,17841,12469,19231,18014,15784,19557,10526,11621,10749,11921,15530,13479,12876,16272,19294,13346,10960,12663,17039,12933,14659,12051,17402,18999,16866,16021,11099,14798,18628,16344,10382,11298,12316,13052,10047,13013,16370,15085]
for x in myList:
print x, isPrime(x)
def isPrime(n):
return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
main()
<file_sep>import math as math
import fractions as fractions
# Factorization via a difference of squares
def is_square(apositiveint):
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
if x in seen: return False
seen.add(x)
return True
def main():
n = input('Enter n: ')
for i in range (1, 100):
if (is_square(n+i**2)):
print str(n)+" + "+str(i)+"^2 = "+str(n+i**2)+" is a square!"
else:
print str(n)+" + "+str(i)+"^2 = "+str(n+i**2)+" is NOT a square!"
main()
<file_sep>#Baby Step Giant Step DLP problem y = a**x mod n
#Example 70 = 2**x mod 131
import math
def baby_step_giant_step(y, a, n):
s = int(math.ceil(math.sqrt(n)))
A = [y * math.pow(a, r, n) % n for r in xrange(s)]
for t in xrange(1,s+1):
value = math.pow(a, t*s, n)
if value in A:
return (t * s - A.index(value)) % n
print baby_step_giant_step(2213, 640, 3571)
<file_sep>import math as math
import fractions as fractions
# Calculating the entropy of a random variable
def main():
monthProb = [0.0798,0.0748,0.0836,0.0773,0.0833,0.0840,0.0863,0.0909,0.0878,0.0861,0.0825,0.0835]
daysInMonthProb = [31.0,28.0,31.0,30.0,31.0,30.0,31.0,31.0,30.0,31.0,30.0,31.0]
englishLetterProb = [0.1311, 0.1047,0.0815,0.08,0.0710,0.0683,0.0635,0.0610,0.0526,0.0379,0.0339,0.0292,0.0276,0.0254,0.0246,0.0199,0.0198,0.0198,0.0154,0.0144,0.0092,0.0042,0.0017,0.0013,0.0012,0.0008]
entropySum = 0
for x in monthProb:
entropySum += (-x)*math.log(x,2)
print "Sum of entropy using table of birth probabilities: ", entropySum
entropySum = 0
for y in daysInMonthProb:
entropySum += (-(y/365.0))*math.log((y/365.0),2)
print "Sum of entropy for birth probabilities using # of days in each month: ", entropySum
entropySum = 0
for z in englishLetterProb:
entropySum += (-z)*math.log(z,2)
print "Entropy of English Language: ", entropySum
main()
| dd02a68582f36c85f3fff8cee62a3d18fb40f996 | [
"Markdown",
"Python"
] | 7 | Markdown | amdi/crypto | 76de1e1e0c7c561fe75b3538fd7fc5e055f94625 | 3c874d6e0fd45c3810fa6285217ec5a1639607d5 |
refs/heads/master | <file_sep>package com.example.jalaljankhan.artisanapp.FirebaseHandler.Services;
import android.content.Intent;
import com.example.jalaljankhan.artisanapp.GahakCallActivity;
import com.example.jalaljankhan.artisanapp.Utils.Messages;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.gson.Gson;
import java.util.Objects;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
LatLng gahakLocation = new Gson().fromJson(Objects.requireNonNull(remoteMessage.getNotification()).getBody(),LatLng.class);
Intent intent = new Intent(getBaseContext(), GahakCallActivity.class);
intent.putExtra("lat",gahakLocation.latitude);
intent.putExtra("lng",gahakLocation.longitude);
intent.putExtra("gahakcall",remoteMessage.getNotification().getTitle());
startActivity(intent);
}
}
<file_sep>package com.example.jalaljankhan.artisanapp.FirebaseHandler.Models;
public class Karigar extends Users {
public Karigar(String fullName, String phoneNumber, String homeAddress, String city){
super(fullName,phoneNumber,homeAddress,city);
}
public String getFullName() {
return super.getFullName();
}
public void setFullName(String mFullName) {
super.setFullName(mFullName);
}
public String getPhoneNumber() {
return super.getPhoneNumber();
}
public void setPhoneNumber(String mPhoneNumber) {
super.setPhoneNumber(mPhoneNumber);
}
public String getHomeAddress() {
return super.getHomeAddress();
}
public void setHomeAddress(String mHomeAddress) {
super.setHomeAddress(mHomeAddress);
}
public String getCity() {
return super.getCity();
}
public void setCity(String mCity) {
super.setCity(mCity);
}
}
<file_sep>package com.example.jalaljankhan.artisanapp.FirebaseHandler.Models;
public class Tokens {
private String mFreshToken;
public Tokens(){
}
public Tokens(String freshToken){
setToken(freshToken);
}
public void setToken(String freshToken){
mFreshToken = freshToken;
}
public String getToken(){
return mFreshToken;
}
}
<file_sep>package com.example.jalaljankhan.artisanapp;
import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapDropDown;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.example.jalaljankhan.artisanapp.FirebaseHandler.Models.Karigar;
import com.example.jalaljankhan.artisanapp.Utils.FieldUtils;
import com.example.jalaljankhan.artisanapp.Utils.Messages;
import com.example.jalaljankhan.artisanapp.Utils.StorageUtils;
import com.google.firebase.auth.FirebaseAuth;
import java.util.List;
import java.util.Objects;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
public class AccountInfoActivity extends AppCompatActivity
implements View.OnClickListener, EasyPermissions.PermissionCallbacks {
// Widgets
private BootstrapEditText mFullName, mHomeAddress;
private BootstrapDropDown mCities;
private ImageButton mProfilePictureImageButton;
private BootstrapButton mOKButton;
// Local Variables
private final int CAPTURE_REQUEST_CODE = 3336;
private static final int PERMISSION_REQUEST_CODE = 123;
private static final String PERMISSION_REQUIRED = "Permission is required to proceed";
private String mCityStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_info);
initWidets();
clickOnWidgets();
}
// initialize views
private void initWidets() {
mProfilePictureImageButton = findViewById(R.id.info_profile_image_btn);
mFullName = findViewById(R.id.info_fullname_edit_text);
mHomeAddress = findViewById(R.id.info_home_address_edit_text);
mCities = findViewById(R.id.info_cities_dropdown);
mOKButton = findViewById(R.id.info_okBtn);
}
// When click triggers on widgets
private void clickOnWidgets() {
mProfilePictureImageButton.setOnClickListener(this);
mOKButton.setOnClickListener(this);
mCities.setOnDropDownItemClickListener(new BootstrapDropDown.OnDropDownItemClickListener() {
@Override
public void onItemClick(ViewGroup parent, View v, int itemId) {
String[] cities = mCities.getDropdownData();
mCityStr = cities[itemId];
mCities.setText(mCityStr);
Messages.toastMessage(AccountInfoActivity.this, mCityStr);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.info_profile_image_btn:{
openCamera();
break;
}
case R.id.info_okBtn:{
extractValues();
switchToActivity();
break;
}
default:
break;
}//switch ends
}
private void switchToActivity() {
Intent intent = new Intent(AccountInfoActivity.this,SkillActivity.class);
startActivity(intent);
}
// Opens Camera & Capture image
@AfterPermissionGranted(123)
private void openCamera() {
String[] params = {Manifest.permission.CAMERA};
if(EasyPermissions.hasPermissions(this,params)){
Messages.toastMessage(this,"Opening Camera");
captureImage();
}else{
EasyPermissions.requestPermissions(this,PERMISSION_REQUIRED,PERMISSION_REQUEST_CODE,params);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE){
Messages.toastMessage(AccountInfoActivity.this,"Camera is ready to use");
captureImage();
}
if(requestCode == CAPTURE_REQUEST_CODE){
Messages.toastMessage(AccountInfoActivity.this,"Capture_Request_Code Successful");
Bitmap bitmap = (Bitmap) Objects.requireNonNull(Objects.requireNonNull(data).getExtras()).get("data");
mProfilePictureImageButton.setImageBitmap(bitmap);
}
}
}
// Runtime permission
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
Messages.toastMessage(this,"Camera Permission Granted");
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
if(EasyPermissions.somePermissionPermanentlyDenied(this, perms)){
new AppSettingsDialog.Builder(this).build().show();
}
}
// Captures Image using camera intent
private void captureImage() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
if(cameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(cameraIntent, CAPTURE_REQUEST_CODE);
}
}
// Extract entered values
private void extractValues() {
String fullNameStr, phoneNumberStr, homeAddressStr;
if(!FieldUtils.allFieldsEmpty(mFullName,mHomeAddress)){
fullNameStr = mFullName.getText().toString().trim();
homeAddressStr = mHomeAddress.getText().toString().trim();
phoneNumberStr = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getPhoneNumber();
StorageUtils.karigarRef = new Karigar(fullNameStr,phoneNumberStr,homeAddressStr,mCityStr);
}
}
}
<file_sep>package com.example.jalaljankhan.artisanapp;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import com.example.jalaljankhan.artisanapp.Fragments.ElectricianSkillFragment;
import com.example.jalaljankhan.artisanapp.Fragments.PlumberSkillFragment;
import com.example.jalaljankhan.artisanapp.Utils.FragmentUtils;
import com.example.jalaljankhan.artisanapp.Utils.Messages;
import com.example.jalaljankhan.artisanapp.Utils.StorageUtils;
public class SkillActivity extends AppCompatActivity {
// Fragment References
private ElectricianSkillFragment mElectricianSkillFragment;
private PlumberSkillFragment mPlumberSkillFragment;
// Views
private BottomNavigationView mBottomNavigationView;
private TextView mSkillTitleTextView;
// Local Variables
private String mKarigarType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skill);
init();
initObject();
addDefaultFragment();
registerListener();
}
private void init() {
mBottomNavigationView = findViewById(R.id.skill_navigation_view);
mSkillTitleTextView = findViewById(R.id.skill_textview);
}
// initialize custom references
private void initObject() {
mElectricianSkillFragment = new ElectricianSkillFragment();
mPlumberSkillFragment = new PlumberSkillFragment();
}
private void addDefaultFragment() {
mKarigarType = "Electrician Skills";
mSkillTitleTextView.setText(mKarigarType);
FragmentUtils.addFragment(SkillActivity.this,R.id.skill_fragment_container,mElectricianSkillFragment);
}
// setting listener event for Bottom Navigation View's items selection
private void registerListener() {
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
boolean flag = false;
switch (menuItem.getItemId()){
case R.id.electrician_skill_action:{
StorageUtils.karigarType = "Electrician";
mKarigarType = "Electrician Skills";
mSkillTitleTextView.setText(mKarigarType);
FragmentUtils.removeAllFragments(SkillActivity.this);
FragmentUtils.replaceFragment(SkillActivity.this,R.id.skill_fragment_container,mElectricianSkillFragment);
flag = true;
break;
}
case R.id.plumber_skill_action:{
StorageUtils.karigarType = "Plumber";
mKarigarType = "Plumber Skills";
mSkillTitleTextView.setText(mKarigarType);
FragmentUtils.removeAllFragments(SkillActivity.this);
FragmentUtils.replaceFragment(SkillActivity.this,R.id.skill_fragment_container,mPlumberSkillFragment);
flag = true;
break;
}
default:
break;
}// switch ends
return flag;
}
});
}
}
| 9cf8ca7ebcf522282c5d976a84cbe44a27803326 | [
"Java"
] | 5 | Java | JalalJanKhan3336/ArtisanApp | 7cd7c6b6446044e3f7d2c9ffbdf27c35ab7e4bee | c9e6c18c1fbff5630979636168db1c476d6d3adf |
refs/heads/master | <repo_name>TJKeast/VentureOnline<file_sep>/client/js/classes/Sprite.js
class Sprite {
constructor(spriteSheet, startX, startY, frames, frameChangeFrequency, isLoopFrames) {
this.id = Sprite.nextID++;
this.spritesheet = spriteSheet.image;
this.width = spriteSheet.size;
this.height = spriteSheet.size;
this.startX = startX * this.width;
this.startY = startY * this.height;
//Animated frames
this.currentFrame = 0;
this.nextFrame = 1;
this.lastFrameChange = new Date().getTime();
this.frames = (frames == null) ? 0 : frames; //Frames = number of frames above the current sprite (x, y) to use as animations frames
this.frameChangeFrequency = frameChangeFrequency == null ? 0 : frameChangeFrequency; //Time (ms) between frame changes
this.isLoopFrames = isLoopFrames == null ? false : isLoopFrames; //When on the last frame: go backwards or start from the first frame
this.preRenderedFrames = {};
}
//@Deprecated
//Render a sprite
render(ctx, x, y) {
this.update();
this.renderSize(ctx, x, y, 64, 64);
}
//Render a sprite at a specific size
renderSize(ctx, x, y, width, height) {
this.update();
ctx.drawImage(this.spritesheet, this.startX, this.startY - this.height * this.currentFrame, this.width, this.height, x, y, width, height);
}
//Render a sprite at a specific size with an outline
renderSizeLined(ctx, x, y, width, height) {
this.update();
if(this.preRenderedFrames[this.currentFrame] == null) {
let newCanvasCtx = this.getNewCanvasObject(this.getNewCanvasObject(width, height));
this.renderSize(newCanvasCtx, 0, 0, width, height);
this.applyOutline(newCanvasCtx, width, height);
this.preRenderedFrames[this.currentFrame] = newCanvasCtx;
}
ctx.drawImage( this.preRenderedFrames[this.currentFrame].canvas, x, y);
}
//Render a specific frame at a specific size
renderFrameSize(ctx, x, y, width, height, frameIndex) {
this.update();
ctx.drawImage(this.spritesheet, this.startX, this.startY - this.height * frameIndex, this.width, this.height, x, y, width, height);
}
//Outline the shape of a sprite
applyOutline(ctx, width, height) {
for(let y = 0; y < width; y++) {
for(let x = 0; x < height; x++) {
let c = ctx.getImageData(x, y, 1, 1).data;
let cUp = ctx.getImageData(x, y - 1, 1, 1).data;
let cDown = ctx.getImageData(x, y + 1, 1, 1).data;
let cLeft = ctx.getImageData(x - 1, y, 1, 1).data;
let cRight = ctx.getImageData(x + 1, y, 1, 1).data;
if(!Sprite.isVoidPixel(c) && (Sprite.isVoidPixel(cUp) || Sprite.isVoidPixel(cDown) || Sprite.isVoidPixel(cLeft) || Sprite.isVoidPixel(cRight))) {
ctx.fillStyle = "rgba("+0+","+0+","+0+","+1+")";
ctx.fillRect(x, y, 1, 1);
}
}
}
}
//Get a new canvas object to pre-render a sprite onto
getNewCanvasObject(width, height) {
let newCanvas = $('<canvas/>', {"class": "pixelCanvas"});
let newCanvasCtx = newCanvas[0].getContext('2d');
newCanvas.css({'width': width, 'height': height});
newCanvas.attr('width', width);
newCanvas.attr('height', height);
newCanvasCtx.mozImageSmoothingEnabled = false;
newCanvasCtx.webkitImageSmoothingEnabled = false;
newCanvasCtx.msImageSmoothingEnabled = false;
newCanvasCtx.imageSmoothingEnabled = false;
return newCanvasCtx;
}
//Update animation frames
update() {
if(this.frames > 0) {
if(new Date().getTime() - this.lastFrameChange > this.frameChangeFrequency) {
this.lastFrameChange = new Date().getTime();
this.changeFrame();
}
}
}
//Change the current frame
changeFrame() {
if(this.currentFrame == this.frames && this.isLoopFrames) {
this.nextFrame = -1;
} else if(this.currentFrame == this.frames) {
this.currentFrame = 0;
return;
} else if(this.currentFrame == 0) {
this.nextFrame = 1;
}
this.currentFrame += this.nextFrame;
}
}
Sprite.nextID = 0;
//Check if a pixel in the sprite is void
Sprite.isVoidPixel = function(c) {
if(c[0] == 0 && c[1] == 0 && c[2] == 0 && c[3] == 0) return true;
return false;
}<file_sep>/modules/classes/entities/EntityManager.js
require('../../utils.js')();
require('./Mob.js')();
require('./Item.js')();
module.exports = function() {
this.EntityManager = class {
static addPlayer(p) {
EntityManager.playerList[getNextAvailableArrayIndex(EntityManager.playerList, 200)] = p;
}
static updateAllPlayers() {
let pack = [];
for(let i in EntityManager.playerList) {
let player = EntityManager.playerList[i];
player.update();
//Update spawn timer
if(EntityManager.spawnTimer > EntityManager.spawnTime) {
EntityManager.spawnEntitiesNearPoint(player, getRandomInt(3, 5));
}
//Add updated player to pack
pack[player.id] = {
id: player.id,
name: player.name,
spriteName: player.spriteName,
x: player.x,
y: player.y,
stats: player.stats,
mapId: player.map.id,
healthEffects: player.healthEffects,
equipment: player.equipment,
type: player.type,
faction: player.faction
};
}
if(EntityManager.spawnTimer > EntityManager.spawnTime) {
EntityManager.spawnTimer = 0;
EntityManager.spawnTime = 20 * getRandomInt(10, 15);
}
return pack;
}
static addEntity(e) {
EntityManager.entityList.push(e);
}
static updateAllEntities() {
let pack = [];
for(let i in EntityManager.entityList) {
let e = EntityManager.entityList[i];
e.update();
//Delete entity if inactive
if(!e.isActive) {
EntityManager.entityList.splice(i, 1);
continue;
}
//Add updated entity to pack
pack.push({
id: e.id,
name: e.name,
x: e.x,
y: e.y,
stats: e.stats,
spriteName: e.spriteName,
mapId: e.map.id,
healthEffects: e.healthEffects,
type: e.type,
faction: e.faction
});
}
return pack;
}
static addItem(i) {
EntityManager.itemList.push(i);
}
static updateAllItems() {
let pack = [];
for(let i in EntityManager.itemList) {
//Update item
let item = EntityManager.itemList[i];
item.update();
//Delete item if inactive
if(!item.isActive) {
EntityManager.itemList.splice(i, 1);
continue;
}
//Add updated item to pack
pack.push({
name: item.name,
x: item.x,
y: item.y,
mapId: item.mapId
});
}
return pack;
}
static updateEntityManager() {
EntityManager.spawnTimer++;
EntityManager.playerGameState = EntityManager.updateAllPlayers();
EntityManager.entityGameState = EntityManager.updateAllEntities();
EntityManager.itemGameState = EntityManager.updateAllItems();
}
static spawnEntitiesNearPoint(point, spawnLimit) {
let spawnRadius = 10, spawnAmount = 0;
let startX = point.x - 64 * spawnRadius, startY = point.x - 64 * spawnRadius;
let endX = point.x + 64 * spawnRadius, endY = point.x + 64 * spawnRadius;
for(let y = startY; y < endY; y+= 64) {
for(let x = startX; x < endX; x+= 64) {
if(spawnAmount >= spawnLimit) return;
if(getRandomInt(0, 100) < 5) {
let spawnX = x + 64 * 2;
let spawnY = y + 64 * 2;
let newEntity = ResourceManager.getRandomEntity(null);
let e = new Mob(newEntity, point.map, spawnX, spawnY);
if(distanceBetweenPoints(point, e) < 64 * 7) continue;
e.target = point;
EntityManager.addEntity(e);
spawnAmount++;
}
}
}
}
};
EntityManager.nextID = 0;
EntityManager.spawnTimer = 0;
EntityManager.spawnTime = 1;
EntityManager.playerList = [];
EntityManager.entityList = [];
EntityManager.itemList = [];
EntityManager.playerGameState = [];
EntityManager.entityGameState = [];
EntityManager.itemGameState = [];
};
<file_sep>/modules/classes/entities/StaticEntity.js
require('./Entity.js')();
module.exports = function() {
this.StaticEntity = class extends Entity {
constructor(spriteName, map, x, y, name, stats) {
super(EntityManager.nextID++, spriteName, map, x, y, name, stats);
this.type = "static";
}
update() {
super.update();
}
die() {
}
}
};<file_sep>/client/js/routes.js
page.base('/');
page('/', function() { route(["navbar", "play", "ui/mapEditor"]); });
page('play', function() { route(["navbar", "play", "ui/mapEditor"]); });
page('info', function() { route(["navbar", "play", "ui/mapEditor"]); });
page('*', function() { route(["navbar", "play", "ui/mapEditor"]); });
page();
//Processes a route request for a list of views.
function route(views) {
render(views);
}
//Renders an array of views to a DOM target.
//Renders each view by file name in the order they are set in the array.
function render(views) {
let viewFolder = "/resources/views/";
let appTarget = "body";
$(appTarget).empty();
for(i in views) {
let url = viewFolder + views[i] + ".html";
$(appTarget)
.append($("<div>")
.load(url));
}
}
<file_sep>/modules/classes/entities/Item.js
module.exports = function() {
this.Item = class {
constructor(name, x, y, mapID) {
this.id = Item.nextID++;
this.name = name;
this.x = x;
this.y = y;
this.mapId = mapID;
this.lifetime = 20 * 120;
this.timer = 0;
this.isActive = true;
}
update() {
this.timer++;
if(this.timer >= this.lifetime) this.isActive = false;
}
};
Item.nextID = 0;
};<file_sep>/modules/classes/entities/Creature.js
require('./Entity.js')();
require('./Projectile')();
module.exports = function() {
this.Creature = class extends Entity {
constructor(id, spriteName, map, x, y, name, stats) {
super(id, spriteName, map, x, y, name, stats);
this.primaryAttackCooldown = 20 * 2;
this.primaryAttackTimer = 0;
}
update() {
super.update();
}
shootProjectile(angle) {
let angleIncrement = 15;
angle = angle - Math.floor(this.attackProj.number_of_projectiles / 2) * angleIncrement;
for(let i = 0; i < this.attackProj.number_of_projectiles; i++) {
let p = new Projectile(this, angle, this.attackProj.sprite, this.map, this.x, this.y, this.attackProj.multihit,
this.attackProj.damage_min, this.attackProj.damage_max, this.attackProj.moveSpeed, this.attackProj.lifetime);
EntityManager.addEntity(p);
angle += angleIncrement;
}
}
shootAtLocation(point) {
this.shootProjectile(getAngle(this, point));
}
moveToPosition(point, followDistance) {
followDistance *= 64;
if(distanceBetweenPoints(this, {x: point.x, y: point.y}) < followDistance) return;
if(point.x < this.x) this.spdX = -this.stats.moveSpeed;
else if(point.x > this.x) this.spdX = this.stats.moveSpeed;
else this.spdX = 0;
if(point.y < this.y) this.spdY = -this.stats.moveSpeed;
else if(point.y > this.y) this.spdY = this.stats.moveSpeed;
else this.spdY = 0;
}
}
};<file_sep>/modules/classes/entities/Entity.js
module.exports = function() {
this.Entity = class {
constructor(id, spriteName, map, x, y, name, stats) {
this.id = id;
this.name = name != null ? name : "Unknown";
this.x = x;
this.y = y;
this.spdX = 0;
this.spdY = 0;
this.spriteName = spriteName;
this.map = map;
this.isActive = true;
this.timer = 0;
this.healthEffects = [];
this.bounds = {x: 16, y: 16, width: 40, height: 48};
this.timers = {regen: new Date().getTime()};
this.t = new Date();
this.nowTime = this.t.getTime();
this.type = "default";
this.faction = null;
this.stats = stats != null ? stats : {
"attack": 1, //Damage multiplier
"maxHp": 1000, //Maximum hitpoints
"currentHp": 1000, //Current hitpoints
"regenHp": 50, //Hitpoints regenrated per second
"moveSpeed": 10, //Movespeed in pixels per second
"defence": 10, //Damage reduction multiplier
"dexterity": 9
};
}
update() {
this.timer++;
this.nowTime = new Date().getTime();
this.updatePosition();
this.updateHealthEffects();
if(!(this instanceof Projectile)) {
this.updateHealth();
}
}
updatePosition() {
this.moveX();
this.moveY();
}
moveX() {
if(this.spdX > 0) { //Moving right
let xOffset = parseInt((this.x + this.spdX + this.bounds.width) / 64);
if(!this.isCollision(xOffset, parseInt((this.y + this.bounds.y + this.bounds.height) / 64))
&& !this.isCollision(xOffset, parseInt((this.y + this.bounds.y) / 64))) {
this.x += this.spdX;
} else {
this.x = xOffset * 64 - this.bounds.x - this.bounds.width - 1;
this.onMapCollision();
}
} else if(this.spdX < 0) { //Moving left
let xOffset = parseInt((this.x + this.spdX + this.bounds.x) / 64);
if(!this.isCollision(xOffset, parseInt((this.y + this.bounds.y) / 64))
&& !this.isCollision(xOffset, parseInt((this.y + this.bounds.y + this.bounds.height) / 64))) {
this.x += this.spdX;
} else {
this.x = xOffset * 64 + 64 - this.bounds.x;
this.onMapCollision();
}
}
}
moveY() {
if(this.spdY < 0) { //Moving up
let yOffset = parseInt((this.y + this.spdY + this.bounds.y) / 64);
if(!this.isCollision(parseInt((this.x + this.bounds.x) / 64), yOffset)
&& !this.isCollision(parseInt((this.x + this.bounds.x + this.bounds.width) / 64), yOffset)) {
this.y += this.spdY;
} else {
this.y = yOffset * 64 + 64 - this.bounds.y;
this.onMapCollision();
}
} else if(this.spdY > 0) { //Moving down
let yOffset = parseInt((this.y + this.spdY + this.bounds.y + this.bounds.height) / 64);
if(!this.isCollision(parseInt((this.x + this.bounds.x) / 64), yOffset)
&& !this.isCollision(parseInt((this.x + this.bounds.x + this.bounds.width) / 64), yOffset)) {
this.y += this.spdY;
} else {
this.y = yOffset * 64 - this.bounds.y - this.bounds.height - 1;
this.onMapCollision();
}
}
}
isCollision(x, y) {
//If the current tile is null or solid return true
if(ResourceManager.tileList[this.map.tiles[y * this.map.width + x]].isSolid ||
ResourceManager.tileList[this.map.tiles[y * this.map.width + x]] == null) return true;
return false;
}
//Behaviour when a projectile collides with a solid map tile
onMapCollision() {
if(this instanceof Projectile) this.isActive = false;
}
setTileLocation(x, y) {
this.x = parseInt(x) * 64;
this.y = parseInt(y) * 64;
}
updateHealth() {
let frequency = this instanceof Player ? 200 : 1000; //ms
let updateAmount = frequency / 1000 * this.stats.regenHp;
if(this.nowTime - this.timers.regen > frequency) {
this.timers.regen = this.nowTime;
this.addHealth(updateAmount, false);
}
}
addHealth(amount, showEffect) {
amount = parseInt(amount);
let newHp = this.stats.currentHp + amount;
if(newHp <= 0) {
this.stats.currentHp = 0;
this.die();
} else if(newHp >= this.stats.maxHp) {
this.stats.currentHp = this.stats.maxHp;
return;
} else {
this.stats.currentHp = newHp;
}
if(showEffect || showEffect == null) {
this.addHealthEffect(Math.abs(amount), amount >= 0 ? "green" : "red");
}
}
die() {
this.dropItem();
this.isActive = false;
}
dropItem() {
EntityManager.addItem(new Item(ResourceManager.getRandomItem().name, this.x + getRandomInt(-32, 32), this.y + getRandomInt(-32, 32), this.map.id));
}
addHealthEffect(text, type) {
this.healthEffects.push({text: text, color: type, timer: 0});
}
updateHealthEffects() {
let lifetime = 20 * 2;
for(let i in this.healthEffects) {
let fx = this.healthEffects[i];
if(fx == undefined) continue;
fx.timer++;
if(fx.timer > lifetime) delete this.healthEffects[i];
}
}
};
};
<file_sep>/modules/enums/Result.js
module.exports = function() {
this.Result = class {
}
Result.Success = "success";
Result.Failure = "failure";
Result.Pending = "pending";
Result.Error = "error";
};<file_sep>/client/js/classes/Client.js
class Client {
constructor() {
this.id = null;
this.map = null;
this.backupMap = null;
this.player = null;
this.debugOn = true;
}
//Set the players map and make a backup for map editor
setMap(map) {
this.map = map;
this.backupMap = JSON.parse(JSON.stringify(map));
}
}<file_sep>/client/js/managers/utils.js
//Escape html in a string
function escapeHtml (string) {
let entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
function distanceBetweenPoints(point1, point2) {
if(point1 == null || point2 == null) return 0;
return Math.abs(Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2)));
}
function getHpBarColor(currentHp, maxHp) {
let hpPercent = currentHp / maxHp * 100;
if(hpPercent < 25) return "rgb(255, 0, 0, 1)";
if(hpPercent < 50) return "rgb(255, 200, 0, 0.8)";
if(hpPercent <= 100) return "rgba(0, 255, 0, 0.8)";
return "rgba(255, 255, 255, 255, 1)";
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //Min is inclusive, max in exclusive
};
//Search a playerlist and return the ID of the player that matches the given username
function getPlayerIndexById(playerList, searchId) {
for(let i in playerList) {
if(playerList[i] == null) continue;
if(playerList[i].id === searchId) return i;
}
return null;
};
function getCenter(point, size) {
return {x: parseInt(point.x + size / 2), y: parseInt(point.y + size / 2)};
}
//Temp
function getAngle(p1x, p1y, p2x, p2y) {
let deltaY = p1y - p2y;
let deltaX = p2x - p1x;
let inRads = Math.atan2(deltaY, deltaX);
if (inRads < 0)
inRads = Math.abs(inRads);
else
inRads = 2 * Math.PI - inRads;
return inRads * 180 / Math.PI ;
}
const numberFormat = (num) => {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}<file_sep>/modules/classes/entities/Player.js
let fs = require('fs');
require('./EntityManager')();
require('../../utils.js')();
require('./Creature.js')();
require('../Equiment.js')();
require('../CommandManager.js')();
module.exports = function() {
this.Player = class extends Creature {
constructor(username, spriteName, map) {
super(EntityManager.nextID++, spriteName, map, (map.width / 2) * 64, (map.height / 2) * 64, username);
//META
this.faction = username;
//MOVEMENT
this.pressingRight = false;
this.pressingLeft = false;
this.pressingUp = false;
this.pressingDown = false;
this.pressingAttack = false;
this.mouseAngle = 0;
//STATS
this.equipment = new Equipment();
this.stats = {
"attack": 1,
"maxHp": 1000,
"currentHp": 1000,
"regenHp": 100,
"moveSpeed": 20,
"defence": 10,
"dexterity": 20
};
}
update() {
super.update();
this.equipment.update();
this.updateSpd();
if(this.pressingAttack && this.equipment.attack1Timer >= this.equipment.weapon1.fire_rate) {
this.shootProjectile(this.equipment.weapon1.attack1, this.mouseAngle);
this.equipment.attack1Timer = 0;
}
}
updateSpd() {
//Update x axis movement
if(this.pressingRight) this.spdX = this.stats.moveSpeed;
else if(this.pressingLeft) this.spdX = -this.stats.moveSpeed;
else this.spdX = 0;
//Update y axis movement
if(this.pressingUp) this.spdY = -this.stats.moveSpeed;
else if(this.pressingDown) this.spdY = this.stats.moveSpeed;
else this.spdY = 0;
//Reduce movement distance when travelling diagonally
if((this.pressingDown || this.pressingUp) && (this.pressingLeft || this.pressingRight)) {
this.spdX = parseInt(this.spdX * 0.75);
this.spdY = parseInt(this.spdY * 0.75);
}
}
shootProjectile(attack, angle) {
if(attack == undefined) {
return;
}
let angleIncrement = 15;
angle = angle - Math.floor(attack.number_of_projectiles / 2) * angleIncrement;
for(let i = 0; i < attack.number_of_projectiles; i++) {
let p = new Projectile(this, angle, attack.sprite, this.map, this.x, this.y, attack.multihit, attack.damage_min, attack.damage_max, attack.speed, attack.lifetime);
EntityManager.addEntity(p);
angle += angleIncrement;
}
}
//Change a players map
changeMap(serverCache, map) {
serverCache.socketList[this.socketId].emit('changeMap', {map: map});
if(this.map.id != map.id) this.setTileLocation((this.map.width / 2), (this.map.height / 2));
this.map = map;
}
die() {
serverMessage("DEATH", "[PLAYER: " + this.name + "] died.");
this.respawn();
}
respawn() {
this.x = this.x + getRandomInt(-4, 4) * 64;
this.y = this.y + getRandomInt(-4, 4) * 64;
this.stats.currentHp = this.stats.maxHp;
}
};
Player.onConnect = function(serverCache, socket, username) {
//Create player and add to list
let player = null;
let cachedPlayer = getPlayerByUsername(serverCache.playerCache, username);
if(cachedPlayer != null) {
player = cachedPlayer;
} else {
player = new Player(username, 'playerDefault', Map.getMapByName('Limbo'));
serverCache.playerCache.push(player);
}
player.socketId = socket.id;
EntityManager.addPlayer(player);
sendMessageToClients(serverCache.socketList, player.name + ' has joined the server.', 'info');
sendMessageToClients([socket], 'Welcome to Venture. Type /help for help.', 'info');
//Listen for input events
socket.on('keyPress', function(data) {
if(data.inputId === 'left') player.pressingLeft = data.state;
if(data.inputId === 'right') player.pressingRight = data.state;
if(data.inputId === 'up') player.pressingUp = data.state;
if(data.inputId === 'down') player.pressingDown = data.state;
if(data.inputId === 'attack') player.pressingAttack = data.state;
if(data.inputId === 'mouseAngle') player.mouseAngle = data.state;
});
//Listen for new messages from clients
socket.on('sendMessageToServer', function(data) {
if (data[0] === '/') processServerCommand(serverCache, {'socketList': serverCache.socketList, 'playerList': EntityManager.playerList, 'args': data.split(' '), 'senderSocketId': socket.id});
else sendMessageToClients(serverCache.socketList, data, 'default', player.name, player.map.name);
});
//Listen for map changes
socket.on('sendNewMapToServer', function(data) {
let newMap = new Map({id: data.map.id, name: data.map.name, width: data.map.width, height: data.map.height,
tiles: data.map.tiles, objects:data.map.objects, isPVP: false});
//Update map of all players on the edited map
if(data.pushToServer) {
for (let i in EntityManager.playerList) {
if (EntityManager.playerList[i].map.id == data.map.id) EntityManager.playerList[i].changeMap(serverCache, newMap);
}
}
//Update server saved version of map
Map.mapList[newMap.id] = newMap;
//Save map to text file on server
fs.writeFile('./data/maps/' + data.fileName + '.ven', JSON.stringify(newMap), function(err) {
if(err) {
return serverMessage("ERROR", err);
} else {
return serverMessage("INFO", "Success - file was saved to: " + './data/maps/' + data.fileName + '.ven')
}
});
});
};
Player.onDisconnect = function(serverCache, socket) {
let player = EntityManager.playerList[socket.id];
if(player != undefined) {//If client never signed in
sendMessageToClients(serverCache.socketList, player.name + ' has left the server.', 'info');
}
delete EntityManager.playerList[socket.id];
};
};
<file_sep>/modules/enums/ServerState.js
module.exports = function() {
this.ServerState = class {
}
ServerState.Offline = "offline";
ServerState.Loading = "loading";
ServerState.Ready = "ready";
};<file_sep>/client/js/classes/GameCamera.js
const TILE_WIDTH = 64;
const TILE_HEIGHT = 64;
class GameCamera {
constructor(xOffset, yOffset) {
this.xOffset = xOffset;
this.yOffset = yOffset;
}
move(xAmount, yAmount) {
this.xOffset += xAmount;
this.yOffset += yAmount;
}
setPosition(x, y, screenWidth, screenHeight) {
this.xOffset = x - screenWidth / 2 + 32;
this.yOffset = y - screenHeight / 2 + 32;
}
}<file_sep>/modules/classes/entities/Mob.js
require('../../utils.js')();
require('./Creature.js')();
module.exports = function() {
this.Mob = class extends Creature {
constructor(newEntityTemplate, map, x, y) {
super(EntityManager.nextID++, newEntityTemplate.spriteName, map, x, y, newEntityTemplate.name, newEntityTemplate.stats);
this.target = findNearestPoint(EntityManager.playerList, this.x, this.y);
this.distanceToTarget = null;
this.lifeTime = 20 * 60 * 10;
this.attackProj = newEntityTemplate.projectiles[0];
this.type = newEntityTemplate.type;
this.chaseDistance = newEntityTemplate.chaseDistance;
}
update() {
super.update();
//Kill of entity after lifetime is over
if(this.timer > this.lifeTime) {
this.isActive = false;
return;
}
//Find a target
if(this.target == undefined) {
this.target = findNearestPoint(EntityManager.playerList, this.x, this.y);
}
//Find new target if it is too far away
this.distanceToTarget = distanceBetweenPoints(this, this.target);
if(this.distanceToTarget > 64 * 15) this.target = findNearestPoint(EntityManager.playerList, this.x, this.y);
//Update movement
this.spdX = 0;
this.spdY = 0;
this.selectAction();
}
selectAction() {
//Attack
this.primaryAttackTimer++;
if(this.primaryAttackTimer > this.primaryAttackCooldown) {
if(this.target != undefined) {
super.shootAtLocation(this.target);
this.primaryAttackTimer = 0;
}
}
if(this.target != undefined) {
this.moveToPosition(this.target, this.chaseDistance);
}
}
idleMove() {
this.spdX = Math.random() < 0.5 ? this.stats.moveSpeed : -this.this.stats.moveSpeed;
}
};
};
<file_sep>/client/js/classes/ResourceManager.js
class ResourceManager {
constructor() {
}
static getSpriteByID(searchID) {
for(let i in this.sprites) if(this.sprites[i].id === searchID) return this.sprites[i];
return this.sprites[0];
}
static getSpriteByName(searchName) {
return ResourceManager.sprites[searchName] == undefined ? ResourceManager.sprites.tileDarkWater : ResourceManager.sprites[searchName];
}
static getItemByName(searchName) {
for(let i in ResourceManager.itemList)
if(ResourceManager.itemList[i].name.toString().toLowerCase() === searchName.toString().toLowerCase()) return ResourceManager.itemList[i];
return null;
}
static getEntityByName(searchName) {
for(let i in ResourceManager.entityList)
if(ResourceManager.entityList[i].name.toString().toLowerCase() === searchName.toString().toLowerCase()) return ResourceManager.entityList[i];
return null;
}
static santityCheck() {
let src = ResourceManager.sprites;
let result = [];
for (var key in src) {
if (src.hasOwnProperty(key)) {
for (var key2 in src) {
if (src.hasOwnProperty(key2)) {
if(src[key].width == src[key2].width &&
src[key].startX == src[key2].startX && src[key].startY == src[key2].startY
&& key != key2) {
result.push({key1:key, key2: key2})
break;
}
}
}
}
}
if(result.length > 0) {
console.log("Resource Manager Sanity Check - FAILURE - " + result.length + " conflicts found:");
for (var i in result) {
console.log("Sprite conflict: " + result[i].key1 + " -> " + result[i].key2);
}
}
}
}
ResourceManager.itemList = [];
ResourceManager.tileList = [];
ResourceManager.objectList = [];
ResourceManager.entityList = [];
//Images
ResourceManager.images = {
'spritesheet_64x64': new Image(1600, 1600), //Load 64x64 spritesheet
'spritesheet_16x16': new Image(1600, 1600), //Load 16x16 spritesheet
'spritesheet_8x8': new Image(800, 800), //Load 8x8 spritesheet
'turnipGuy': new Image(64, 64)
};
let root = "../../../resources/";
ResourceManager.images['spritesheet_64x64'].src = root + 'img/spritesheet_64x64.png';
ResourceManager.images['spritesheet_16x16'].src = root + 'img/spritesheet_16x16.png';
ResourceManager.images['spritesheet_8x8'].src = root + 'img/spritesheet_8x8.png';
ResourceManager.images['turnipGuy'].src = root + 'img/turnipguy.png';
//Spritesheets
let ss64 = {"image": ResourceManager.images['spritesheet_64x64'], size: 64};
let ss16 = {"image": ResourceManager.images['spritesheet_16x16'], size: 16};
let ss8 = {"image": ResourceManager.images['spritesheet_8x8'], size: 8};
ResourceManager.sprites = {
//Animated
animLightWater: new Sprite(ss16, 0, 784 / 16, 3, 50, false),
animDarkWater: new Sprite(ss16, 1, 784 / 16, 3, 50, false),
animCampFire: new Sprite(ss16, 2, 784 / 16, 3, 100, true),
//Creatures
//Player
playerDefault: new Sprite(ss64, 0, 0),
//Mobs
mobPrisonGuard: new Sprite(ss64, 10, 2),
petDog: new Sprite(ss64, 10, 2),
mobCube: new Sprite(ss64, 10, 4),
mobDarkInsect: new Sprite(ss8, 0, 99, 1, 300, true),
mobGreenSpider: new Sprite(ss8, 1, 99, 2, 200, false),
//Tiles
//Grass
tileDarkGrass: new Sprite(ss16, 1, 0),
tileDarkGrassLight: new Sprite(ss16, 1, 1),
tileLightGrass: new Sprite(ss16, 2, 0),
//Building
tileStoneFloor: new Sprite(ss64, 3, 0),
tileBrickWall: new Sprite(ss64, 3, 1),
tilePlanksFloor: new Sprite(ss64, 3, 2),
tileMarbleFloor: new Sprite(ss16, 3, 0),
//Water
tileDarkWater: new Sprite(ss16, 0, 1),
tileLightWater: new Sprite(ss16, 0, 0),
tileLightWaterRocks: new Sprite(ss64, 4, 2),
tileBeachSand: new Sprite(ss64, 4, 3),
//Desert
tileDesertSand: new Sprite(ss64, 5, 0),
tileDesertSandCactus: new Sprite(ss64, 5, 1),
tileDesertSandPond: new Sprite(ss64, 5, 2),
tileDesertSkull: new Sprite(ss64, 5, 3),
tileDesertBones: new Sprite(ss64, 5, 4),
//Snow
tileSnow: new Sprite(ss16, 2, 1),
tileIce: new Sprite(ss8, 0, 0),
//Entities
//Farming
farmDirt: new Sprite(ss64, 6, 0),
farmDirtRaked: new Sprite(ss64, 6, 1),
farmDirtSeeds: new Sprite(ss64, 6, 2),
farmDirtTomatoes: new Sprite(ss64, 6, 3),
farmDirtCorn: new Sprite(ss64, 6, 4),
farmDirtBlueberries: new Sprite(ss64, 6, 5),
farmDirtPotatoes: new Sprite(ss64, 6, 6),
farmTree: new Sprite(ss64, 6, 7),
farmTreeCut: new Sprite(ss64, 6, 8),
farmTreeApples: new Sprite(ss64, 6, 9),
//Objects
objRoundTreeLarge: new Sprite(ss64, 7, 8),
objWillowTreeLarge: new Sprite(ss8, 1, 1),
objMushroomLarge: new Sprite(ss8, 1, 0),
objRoundBushSmall: new Sprite(ss8, 1, 2),
objWildBushSmall: new Sprite(ss8, 1, 3),
objDeadTreeSmall: new Sprite(ss8, 1, 4),
objPineTreeLarge: new Sprite(ss8, 1, 6),
objCactus: new Sprite(ss8, 1, 5),
objPond: new Sprite(ss8, 2, 1),
objBigFlowers: new Sprite(ss8, 2, 2),
objBrownChest: new Sprite(ss8, 2, 5),
objBigRock: new Sprite(ss8, 2, 6),
objSmallRocks: new Sprite(ss8, 2, 7),
objSmallFlowers: new Sprite(ss8, 2, 3), //fixme
objTree: new Sprite(ss8, 3, 7),
objPondLeaves: new Sprite(ss8, 3, 1),
objSmallFlowersWhite: new Sprite(ss8, 3, 2),
objBlossomTreeLargePink: new Sprite(ss8, 3, 3),
objWillowTreeLargeLight: new Sprite(ss8, 3, 4),
objBlossomTreeLargeGreen: new Sprite(ss8, 3, 5),
objRoundTreeSnow: new Sprite(ss8, 3, 6),
objBlossomTreeLargeBlue: new Sprite(ss8, 3, 8),
objSnowman: new Sprite(ss16, 0, 2),
objDeadTreeLargeSnow: new Sprite(ss64, 0, 3),
//Items
//Weapons
bowWooden: new Sprite(ss64, 13, 0),
staffCorn: new Sprite(ss64, 14, 0),
armorCloth: new Sprite(ss64, 16, 0),
//Consumables
itemCorn: new Sprite(ss64, 17, 0),
itemTomato: new Sprite(ss64, 17, 1),
itemBlueberry: new Sprite(ss64, 17, 2),
itemPotato: new Sprite(ss64, 17, 3),
//Spells
spellCorn: new Sprite(ss64, 18, 0),
//Projectiles
projBlueBall: new Sprite(ss64, 21, 0),
projDarkBall: new Sprite(ss64, 21, 1)
};
ResourceManager.santityCheck();<file_sep>/server.js
require('./modules/classes/ResourceManager.js')();
require('./modules/classes/entities/EntityManager.js')();
require('./modules/classes/world/Map.js')();
require('./modules/classes/entities/Player.js')();
require('./modules/enums/ServerState.js')();
let serverRoutes = require('./modules/serverRoutes.js');
//Initialise server and express routing
let express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
//Load server cache object to control data and settings
let serverCache = {};
serverCache.config = require("./config.json")["config"];
serverCache.serverState = ServerState.Loading;
serverCache.config.debugOn = process.env.PORT !== undefined ? false : true; //Prod or dev environment
serverCache.config.portNum = process.env.PORT !== undefined ? process.env.PORT : serverCache.config.port;
serverCache.config.startupDelay = process.env.PORT !== undefined ? serverCache.config.startupDelay : 0;
//Listen for connection events
app.set('json spaces', 2);
app.use(express.static(__dirname + '/client'));
server.listen(serverCache.config.portNum);
serverRoutes(__dirname, app, serverCache);
//Load resources
ResourceManager.init(serverCache);
Map.mapList = [];
serverCache.socketList = [];
serverCache.playerList = EntityManager.playerList;
serverCache.playerCache = [];
//Load maps
openConnections();
setTimeout(function () {
serverCache.serverState = ServerState.Ready;
Map.mapList = [
new Map({fileName: 'limbo'}),
new Map({fileName: 'desert'}),
new Map({fileName: 'test'}),
new Map({fileName: 'arctic'}),
new Map({fileName: 'randomisland'})
];
}, serverCache.config.startupDelay);
function openConnections() {
serverMessage("INFO", serverCache.config.name + " server started listening on port " + serverCache.config.portNum + ".");
io.sockets.on('connection', function(socket) {
//Deny client connection if too many clients connected
if(getArrayIndexesInUse(serverCache.socketList) + 1 > serverCache.config.maxConnections) {
serverMessage("WARN", "denied client connection. Active connections: " + serverCache.socketList.length);
return;
}
//Add socket to list
socket.id = getNextAvailableArrayIndex(serverCache.socketList, serverCache.config.maxConnections);
serverCache.socketList[socket.id] = socket;
serverMessage("INFO", "[CLIENT " + socket.id + "] connected to the server. ");
//Listen for sign in attempts
socket.on('signIn', function(data) {
//Deny player sign in if too many players or server not ready.
if(getArrayIndexesInUse(serverCache.playerList) + 1 > serverCache.config.maxPlayers || serverCache.serverState !== ServerState.Ready) {
serverMessage("ALERT", " denied client sign-in on [SLOT " + socket.id + "].");
return;
}
//Give default username if empty
if(data.username === '') return;
//Authenticate user
if(true) {
//Start player connect events
Player.onConnect(serverCache, socket, data.username);
let player = getPlayerByUsername(serverCache.playerList, data.username);
//Send sign in result and init pack
socket.emit('signInResponse', {success: true});
socket.emit('initPack', {socketID: socket.id, playerId: player.id, map: player.map,
resources: {
itemList: ResourceManager.itemList,
tileList: ResourceManager.tileList,
objectList: ResourceManager.objectList,
entityList: ResourceManager.entityList
}
});
//Notify the server of new sign in
serverMessage("INFO", "[CLIENT: " + player.id + "] signed in as [PLAYER: '" + data.username + "'].");
} else {
//Send failed sing in response
socket.emit('signInResponse', {success: false});
}
});
//Remove client if disconnected (client sends disconnect automatically)
socket.on('disconnect', function() {
serverMessage("INFO", "[CLIENT: " + socket.id + "] disconnected from the server.");
Player.onDisconnect(serverCache, socket);
delete serverCache.socketList[socket.id];
});
});
}
//Client update loop
setInterval(function() {
EntityManager.updateEntityManager();
//Load package data
let pack = {
players: EntityManager.playerGameState,
entities: EntityManager.entityGameState,
items: EntityManager.itemList
};
//Send package data to all clients
for(let i in EntityManager.playerList) {
let socket = serverCache.socketList[i];
if(socket == undefined) continue;
socket.emit('update', pack);
}
}, 1000 / serverCache.config.tickRate);
<file_sep>/client/js/events/navEvents.js
(function() {
updatePlayerCount();
setInterval(function() {
updatePlayerCount();
}, 30 * 1000);
function updatePlayerCount() {
$.ajax({url: "/api/info", success: function(res){
$("#navPlayerCount").html(res.playersOnline);
}});
}
})();<file_sep>/modules/classes/world/Map.js
let fs = require('fs');
require('../../utils.js')();
module.exports = function() {
this.Map = class {
constructor(params) {
if(params == undefined) return;
this.id = Map.nextID++;
//Load map from file
if(params.fileName != null) {
fs.readFile('./data/maps/' + params.fileName + '.ven', (err, data) => {
if (err) {
serverMessage("ERROR", err);
return;
}
//Populate object with map data
data = JSON.parse(data);
this.name = data.name;
this.width = data.width;
this.height = data.height;
this.tiles = data.tiles;
this.objects = Map.generateMapObjects(this.tiles);
});
} else {
this.name = params.name;
this.width = params.width;
this.height = params.height;
this.tiles = params.tiles === undefined ? Map.generateNewBlankMap(this.width, this.height, params.tileSeedID) : params.tiles;
this.objects = params.objects === undefined ? Map.generateMapObjects(this.tiles) : params.objects;
}
}
//Generate new map with same tiles
static generateNewBlankMap(width, height, tileSeedID) {
let tileMap = [];
for (let i = 0; i < width * height; i++) {
tileMap.push(tileSeedID);
}
return tileMap;
}
//Generate map objects
static generateMapObjects(tileList) {
let objectMap = [];
for(let i = 0; i < tileList.length; i++) {
if(getRandomInt(0, 100) < 50
&& !ResourceManager.tileList[tileList[i]].isSolid) {
let newObj = ResourceManager.getRandomObject(null);
if(!arrayContainsArrayItem(newObj.regions, ResourceManager.tileList[tileList[i]].regions)) {
objectMap.push(null);
continue;
}
objectMap.push({id: newObj.id,
xOffset: getRandomInt(-32, 32),
yOffset: getRandomInt(-32, 32)});
} else {
objectMap.push(null);
}
}
return objectMap;
}
static getMapByName(searchName) {
for(let i in Map.mapList) {
let map = Map.mapList[i];
if(map.name.toString().toLowerCase() === searchName.toString().toLowerCase()) return map;
}
return false;
}
static getMapListString() {
let mapListString = '';
for(let i = 0; i < Map.mapList.length; i++) {
mapListString += Map.mapList[i].name;
if(i < Map.mapList.length - 1) mapListString += ', ';
}
return mapListString;
}
};
Map.nextID = 0;
};<file_sep>/README.md
# VentureOnline
A 2D multiplayer RPG game written using JavaScript/NodeJS.<br>
<h2>Testing Server: <a href="http://venture-env-1.ap-southeast-2.elasticbeanstalk.com">Sydney, AU</a></h2>
<h2>Backlog: <a href="https://trello.com/b/unN0cddD">Trello Link</a></h2>
<img src="client/resources/img/TestRun2.gif" alt="Venture demo gif">
| ff704724604354e13a3b134140f9e4e5a5758d1d | [
"JavaScript",
"Markdown"
] | 19 | JavaScript | TJKeast/VentureOnline | dd4b19d9bd3eabcabd513c7fa47ec04363a94df1 | b60897ff3b20e5c286579f1bcc863a74848d717e |
refs/heads/master | <repo_name>dominiquems/Rosalind<file_sep>/Tests/test_dna_to_rna.py
from unittest import TestCase
from Scripts.dna_to_rna import convert_dna_to_rna
class TestDnaToRna(TestCase):
# Test general functionality
def test_covert_dna_to_rna_correct(self):
outcome = convert_dna_to_rna("ACGTTCTACCT")
self.assertEqual(outcome, "ACGUUCUACCU", "Supposed to to be ACGUUCUACCU")
# Test short sequences
def test_covert_dna_to_rna_short(self):
outcome = convert_dna_to_rna("AT")
self.assertEqual(outcome, "AU", "Supposed to to be AU")
# Test if ValueError is raised if spaces are included
def test_convert_dna_to_rna_spaces(self):
with self.assertRaises(ValueError):
convert_dna_to_rna("ACGTTC TA CCT ")
# Test is ValueError is raised if invalid characters are included
def test_convert_dna_to_rna_unknown_char(self):
with self.assertRaises(ValueError):
convert_dna_to_rna("ACTGKK8Z")
# Test is ValueError is raised if an empty string is given
def test_convert_dna_to_rna_unknown_empty(self):
with self.assertRaises(ValueError):
convert_dna_to_rna("")
<file_sep>/Scripts/genome_assembly_ss.py
"""
Script to create a superstring using substrings
Author: <NAME>
Date: 26/09/2020
"""
# imports
from gc_content import parse_fasta
from overlap_graphs import is_similar_sequence
from sys import argv
# functions
def find_overlap(fastas: dict) -> str:
"""
Assemble fasta sequences with overlapping ends
:param fastas: dict, contains header: NDA sequence
:return: string, assembled sequence
"""
sequences = list(fastas.values())
while len(sequences) > 1:
for query_seq in sequences:
hit_found = False
for target_seq in sequences:
if is_similar_sequence(query_seq, target_seq):
continue
alignment = align_sequences(query_seq, target_seq)
if alignment[0]:
sequences.remove(query_seq)
sequences.remove(target_seq)
sequences.insert(0, alignment[1])
hit_found = True
break
if hit_found:
break
return sequences[0]
def align_sequences(query_seq: str, target_seq: str) -> tuple:
"""
Try to align a sequence against another sequence
The query and target represent a DNA sequence. Expanding substrings
of the target are compared against the query in stepwise fashion. When
an overlap of at least 10 characters is found, a hit is returned.
In case the entire query has been covered and no hit has been found,
the alignment is stopped.
:param query_seq: str, DNA sequence of the query
:param target_seq: str, DNA sequence of the target to be aligned
:return: tuple, bool (found a hit or not) and if so, the aligned sequence
"""
main_pos = len(query_seq) # position of the alignment between query and target
position = 0 # length of the substring of the query and target
while main_pos >= 0:
if query_seq[main_pos:(main_pos + len(target_seq))] == target_seq[:position] and position >= 10:
return True, query_seq + target_seq[position:]
position += 1 # increase size of the substrings each iteration by 1
main_pos -= 1 # decrease the position of the query each iteration by 1
return False, None
if __name__ == "__main__":
fasta_dict = parse_fasta(argv[1])
assembly = find_overlap(fasta_dict)
with open('answer_file', 'w') as writer:
writer.write(assembly.upper())
<file_sep>/Scripts/reverse_complement.py
"""
Script to produce the reverse complement of a DNA sequence
Author: <NAME>
Date: 22/09/2020
"""
# imports
from dna_to_rna import write_output
from nucleotide_count import parse_string
from sys import argv
# functions
def get_reverse_complement(dna_str: str) -> str:
"""
:param dna_str: str, a DNA sequence
:return: str, reverse complement of the DNA sequence
"""
complement_dna = []
for nucleotide in dna_str:
if nucleotide == 'a':
complement_dna.append('t')
elif nucleotide == 't':
complement_dna.append('a')
elif nucleotide == 'c':
complement_dna.append('g')
else:
complement_dna.append('c')
return ''.join(complement_dna).upper()[::-1]
if __name__ == "__main__":
dna_string = parse_string(argv[1])
complement = get_reverse_complement(dna_string)
write_output(complement, "complementary_dna.txt")
<file_sep>/Scripts/mendel_probability.py
"""
Script to calculate the probability of an individual having a Dominant allele
Author: <NAME>
Date: 03/10/2020
"""
# imports
from sys import argv
# functions
def parse_numbers(text_file: str) -> list:
"""
Parse the number of individuals with specific alleles
Three numbers are given in a file on the same line (k m n). The
number k represents homozygous dominant organisms, m represents
heterozygous organisms and n represents homozygous recessive organisms
The numbers are parsed from the first line of the file and returned
in a tuple (in order: k, m, n)
:param text_file: str, name of the text file
:return: list, number of organisms with a specific allele
"""
with open(text_file, 'r') as lines:
for line in lines:
if line.strip() == '':
continue
else:
return [int(number) for number in line.split(' ')]
def dominant_probability(individuals: list) -> float:
"""
Calculate the probability of an individual having a dominant allele
Based on the number of homozygous dominant individuals (k), the number of
heterozygous organisms (m) and the number of homozygous recessive
organisms (n) from the input, the probability is calculated that an
organism has at least one dominant allele
:param individuals: list, number of organisms with a specific allele
:return: float, probability of an organism having a dominant allele
"""
total = sum(individuals)
h_dom, het, h_rec = individuals[0], individuals[1], individuals[2]
probabilities = []
# AA * AA
probabilities.append(h_dom / total * (h_dom - 1) / (total - 1))
# AA * Aa
probabilities.append(h_dom / total * (het / (total - 1)))
# AA * aa
probabilities.append(h_dom / total * (h_rec / (total - 1)))
# Aa * AA
probabilities.append(het / total * (h_dom / (total - 1)))
# Aa * Aa
probabilities.append((het / total * (het - 1) / (total - 1)) * 0.75)
# Aa * aa
probabilities.append(het / total * (h_rec / (total - 1)) * 0.50)
# aa * AA
probabilities.append(h_rec / total * (h_dom / (total - 1)))
# aa * Aa
probabilities.append(h_rec / total * (het / (total - 1)) * 0.5)
return sum(probabilities)
if __name__ == "__main__":
numbers = parse_numbers(argv[1])
print(dominant_probability(numbers))
<file_sep>/Scripts/enumerating_kmers.py
"""
Script to find all strings of length n that can be found from the alphabet
Author: <NAME>
Date: 28/09/2020
"""
# imports
from sys import argv
# functions
def parse_symbols_int(text_file: str) -> tuple:
"""
Parse 1 - 10 symbols and an integer indicating the length of combinations
Text file must contain 1 - 10 symbols (separated by spaced) on the first
line and an integer on the second line. The integer indicates the length
of the combinations that are made with the symbols. For example, a length
of 2 with symbols A and T will lead to AA, AT, TA and TT.
:param text_file: str, name of the text file with symbols and an integer
:return: tuple, a list with symbols and an integer
"""
with open(text_file, 'r') as lines:
for line in lines:
if len(line.strip()) > 1:
symbols = line.strip().split(' ')
elif line.strip().isdigit():
integer = int(line.strip())
return symbols, integer
def find_combinations(integer: int, symbol_list: list) -> list:
"""
Find all permutations of length x (integer)
Based on a given integer, identify all possible combinations that can be
made based with the symbols, given a certain length.
:param integer: int, maximum length of each combination
:param symbol_list: list, all symbols to be considered
:return: list, all permutations that are possible
"""
length = 1
permutations = [[number] for number in range(1, len(symbol_list) + 1)]
while length < integer:
temp_list = []
for perm in permutations:
for i in range(1, len(symbols) + 1):
temp_list.append(perm + [i])
permutations = temp_list
length += 1
return permutations
def integers_to_symbols(permutations: list, symbol_list: list) -> list:
"""
Translate the combinatory numbers to given symbols
:param permutations: list, sub lists with numerical combinations
:param symbol_list: list, symbols to be combined
:return: list, symbolic combinations
"""
symb_combos = []
for sublist in permutations:
symb_combos.append([symbol_list[integer - 1] for integer in sublist])
return sorted(symb_combos)
def report_combinations(combinational_list: list):
"""
Write all combinations from a given symbol list to a file
:param combinational_list: list, symbolic combinations
"""
with open("answer_file", 'w') as writer:
for combo in combinational_list:
print(combo)
writer.write(f"{''.join(combo)}\n")
if __name__ == "__main__":
symbols, length_int = parse_symbols_int(argv[1])
combinations = find_combinations(length_int, symbols)
symbolic_combinations = integers_to_symbols(combinations, symbols)
report_combinations(symbolic_combinations)
<file_sep>/Scripts/point_mutation_identification.py
"""
Identify point mutations and report the hamming distance
Author: <NAME>
Date: 27/09/2020
"""
# imports
from nucleotide_count import is_valid_sequence
from sys import argv
# functions
def parse_dna_seq(text_file: str) -> list:
"""
Parse one or more DNA sequences in a list
:param text_file: str, name of the file with DNA sequences
:return: list, contains DNA sequences
"""
sequences = []
with open(text_file, 'r') as lines:
for line in lines:
sequences.append(line.strip())
return sequences
def identify_mutations(sequences: list) -> int:
"""
Identify the count of point mutations between two sequences
:param sequences: list, contains two sequences (strings)
:return: int, the hamming distance between the two sequences
"""
hamming_distance = 0
for char_1, char_2 in zip(sequences[0], sequences[1]):
if char_1 != char_2:
hamming_distance += 1
return hamming_distance
if __name__ == "__main__":
dna_sequences = parse_dna_seq(argv[1])
for sequence in dna_sequences:
if not is_valid_sequence(sequence):
raise ValueError("Invalid characters in sequence")
print(identify_mutations(dna_sequences))
<file_sep>/Scripts/overlap_graphs.py
"""
Script to find nodes that are adjacent to each other
Author: <NAME>
Date: 25/09/2020
"""
# imports
from sys import argv
from gc_content import parse_fasta
# functions
def find_overlap(fasta_dict: dict) -> list:
"""
Find overlap between two sequences
:param fasta_dict: dict, contains header: sequence
:return: list, contains headers of sequences with overlap of 3
"""
overlap_headers = []
for query_header, query_sequence in fasta_dict.items():
for target_header, target_sequence in fasta_dict.items():
if is_similar_sequence(query_sequence, target_sequence):
continue
else:
if target_sequence[-3:] == query_sequence[0:3]:
overlap_headers.append([target_header, query_header])
return overlap_headers
def is_similar_sequence(seq_1: str, seq_2:str) -> bool:
"""
Check if two sequences are identical
:param seq_1: str, sequence
:param seq_2: str, sequence
:return: bool, 1 if sequences are equal and false otherwise
"""
if seq_1 == seq_2:
return True
else:
return False
if __name__ == "__main__":
fasta_dict = parse_fasta(argv[1])
for header_hit in find_overlap(fasta_dict):
print(' '.join(header_hit))
<file_sep>/Scripts/dna_motif.py
"""
Script to find a substring in a string
Author: <NAME>
Date: 25/09/2020
"""
# imports
from nucleotide_count import is_valid_sequence
from sys import argv
# functions
def parse_strings(text_file: str) -> tuple:
"""
Parse a string and a substring from a text file
:param text_file: str, name of the text file
:return: tuple, contains a string and a substring
"""
with open(text_file, 'r') as lines:
string_list = lines.readlines()
string = string_list[0].strip().lower()
substring = string_list[1].strip().lower()
return string, substring
def substring_compare_string(string: str, substring: str):
"""
Determine positions where the substring is contained in the string
:param string: str, a string
:param substring: str, a substring
:return: list, contains the start position of the substring in the string
"""
start_pos_substring = []
for i in range(len(string)):
if string[i:i + len(substring)] == substring:
start_pos_substring.append(str(i + 1))
return start_pos_substring
if __name__ == "__main__":
dna_string, dna_substring = parse_strings(argv[1])
if is_valid_sequence(dna_string) and is_valid_sequence(dna_substring):
start_pos_list = substring_compare_string(dna_string, dna_substring)
print(' '.join(start_pos_list))<file_sep>/Scripts/translate_rna.py
"""
Script to translate an RNA sequence to a protein
Author: <NAME>
Date: 29/09/2020
"""
# imports
from codons import amino_acids
from nucleotide_count import parse_string
from sys import argv
# functions
def rna_to_protein(rna_string: str) -> str:
"""
Convert an RNA sequence into an amino acid sequence
:param rna_string: str, RNA sequence
:return: str, amino acid sequence
"""
aa_list = []
position = 0
while position + 4 < len(rna_string):
codon = rna_string[position:position + 3].upper()
if codon == '_':
break
aa_list.append(amino_acids[codon])
position += 3
return ''.join(aa_list)
def report_protein(aa_sequence: str):
"""
Write the amino acid sequence to a file
:param aa_sequence: str, amino acid sequence
"""
with open("answer_file.txt", 'w') as writer:
writer.write(aa_sequence)
if __name__ == "__main__":
rna_str = parse_string(argv[1])
report_protein(rna_to_protein(rna_str))
<file_sep>/Scripts/enumerating_gene_orders.py
"""
Script to report the number of permutations and all of those
Author: <NAME>
Date: 28/09/2020
"""
# imports
from sys import argv
# functions
def parse_int(text_file: str) -> int:
"""
Parse a single integer from a text file
:param text_file: str, name of file with an integer
:return: int, integer
"""
with open(text_file, 'r') as lines:
for line in lines:
return int(line.strip())
def find_combinations(integer: int) -> list:
"""
Find all permutations of length x (integer)
Based on a given integer, identify all possible combinations that can be
made based on the numbers between 1 and the integer. Calling the function
with 3 as integer, this results in a total of six different combinations:
3 * 2 * 1 = 6. Each combination of numbers is reported as list of lists
:param integer: int, maximum length of each combination
:return: list, all permutations that are possible
"""
length = 1
# create a separate list for each unique element
permutations = [[number] for number in range(1, integer + 1)]
while length < integer:
temp_list = []
for perm in permutations:
for i in range(1, integer + 1):
if i not in perm:
temp_list.append(perm + [i])
permutations = temp_list
length += 1
return permutations
def report_combinations(permutations: list):
"""
Report different combinations of integers and write output to a file
:param permutations: list, contains all permutations that are possible
"""
with open("answer_file", 'w') as writer:
writer.write(f"{len(permutations)}\n")
for permutation in permutations:
writer.write(f"{' '.join([str(numb) for numb in permutation])}\n")
if __name__ == "__main__":
permutation_int = parse_int(argv[1])
combinations = [str(i) for i in range(1, permutation_int + 1)]
report_combinations(find_combinations(5))
<file_sep>/Scripts/gc_content.py
"""
Compute the GC content and report the sequence with the highest content
Author: <NAME>
"""
# imports
from sys import argv
# functions
def parse_fasta(file_name: str) -> dict:
"""
Parse a fasta file into a dictionary
:param file_name: str, name of the fasta file
:return: dict, contains fasta header: DNA sequence
"""
with open(file_name, 'r') as lines:
fasta_dict = {}
for line in lines:
if line.startswith('>'):
current_header = line.strip('>').strip()
fasta_dict[current_header] = []
else:
fasta_dict[current_header].append(line.strip().lower())
for header, seq in fasta_dict.items():
fasta_dict[header] = ''.join(seq)
return fasta_dict
def calculate_gc_content(fasta_dict: dict) -> list:
"""
Calculate the GC percentage for every fasta sequence
:param fasta_dict:
:return: list, contains tuple with fasta header, GC perc
"""
gc_perc_list = []
for header, seq in fasta_dict.items():
gc_perc_list.append((header, (seq.count('c') + seq.count('g'))
/ len(seq) * 100))
return gc_perc_list
def highest_gc_perc(gc_perc_list: list):
"""
Reports the header of the sequence with the largest GC percentage
:param gc_perc_list: list, contains tuple with fasta header, GC perc
"""
highest_gc_fasta = sorted(gc_perc_list, key=lambda tup: tup[1])[-1]
print("{}\n{:.6f}".format(highest_gc_fasta[0], highest_gc_fasta[1]))
if __name__ == "__main__":
fasta_seqs = parse_fasta(argv[1])
gc_perc_list = calculate_gc_content(fasta_seqs)
highest_gc_perc(gc_perc_list)
<file_sep>/Scripts/error_correction.py
"""
Correct an erogenous nucleotide in a reads
Author: <NAME>
Date: 27/09/2020
"""
# imports
from gc_content import parse_fasta
from overlap_graphs import is_similar_sequence
from point_mutation_identification import identify_mutations
from reverse_complement import get_reverse_complement
from sys import argv
# functions
def check_pairs(fastas: dict) -> tuple:
"""
Check whether at least two pairs are present
:param fastas: dict, contains header: sequence
:return: tuple, contains two lists: (1) error reads and (2) all reads
"""
pairs = {}
for seq in fastas.values():
reverse_comp = get_reverse_complement(seq).lower()
if seq in pairs:
pairs[seq].append(seq)
elif reverse_comp in pairs:
pairs[reverse_comp].append(seq)
else:
pairs[seq] = []
correct_reads = [seq_1 for seq_1, seq_2 in pairs.items() if len(seq_2) > 0]
error_reads = [seq_1 for seq_1, seq_2 in pairs.items() if seq_2 == []]
return error_reads, correct_reads
def find_mate(error_reads: list, reads: list) -> dict:
"""
Determine hamming distance for reads that can be mates
The reads with an error are compared to all other reads as well as their
reverse complements. For the pairs, the hamming distance is calculated
and saved into a dictionary.
:param error_reads: list, contains reads with an error
:param reads: list, contains all reads
:return: dict, contains error reads and other reads with hamming distance
"""
scores = {error_read: {} for error_read in error_reads}
for error_read in error_reads:
for read in reads:
if is_similar_sequence(error_read, read):
continue
else:
reverse_complement = get_reverse_complement(read).lower()
norm_hamming_dist = identify_mutations([error_read, read])
revc_hamming_dist = identify_mutations([error_read, reverse_complement])
scores[error_read].update({read: norm_hamming_dist})
scores[error_read].update({reverse_complement: revc_hamming_dist})
return scores
def report_fixes(scores: dict) -> None:
"""
Writes a file with fixed reads
:param scores: dict, contains dict with alternatives and hamming distance
"""
writer = open("answer_file", 'w')
for (error_read, fixed_reads) in scores.items():
best_seen = False
for k, v in fixed_reads.items():
if v == 1:
writer.write(f'{error_read.upper()}->{k.upper()}\n')
best_seen = True
if not best_seen:
raise ValueError("A read contains multiple mistakes")
if __name__ == "__main__":
fasta_dict = parse_fasta(argv[1])
error_read_list, read_list = check_pairs(fasta_dict)
score_dict = find_mate(error_read_list, read_list)
report_fixes(score_dict)
<file_sep>/Scripts/kmer_composition.py
"""
Script to determine the k-mer composition of a DNA sequence
Author: <NAME>
Date: 28/09/2020
"""
# imports
from gc_content import parse_fasta
from sys import argv
# functions
def create_kmers(sequence: str, kmer_size: int) -> list:
"""
Create a list with k-mers of a specified size from a DNA sequence
:param sequence: str, a DNA sequence
:param kmer_size: int, the k-mer size
:return: list, contains k-mers
"""
kmers = []
for position in range(len(sequence)):
if position + kmer_size <= len(sequence):
kmers.append(sequence[position:position + kmer_size])
return kmers
def find_combinations(integer: int) -> list:
"""
Find all permutations of length x (integer)
Based on a given integer, identify all possible combinations that can be
made based on the numbers between 1 and the integer. Calling the function
with 3 as integer, this results in a total of six different combinations:
3 * 2 * 1 = 6. Each combination of numbers is reported as list of lists
:param integer: int, maximum length of each combination
:return: list, all permutations that are possible
"""
length = 1
# create a separate list for each unique element
permutations = [[number] for number in range(1, integer + 1)]
while length < integer:
temp_list = []
for perm in permutations:
for i in range(1, integer + 1):
temp_list.append(perm + [i])
permutations = temp_list
length += 1
return permutations
def generate_kmer_combinations(combinations: list) -> dict:
bases = ['a', 't', 'c', 'g']
kmer_collection = {}
for combination in combinations:
temp_sequence = []
for integer in combination:
temp_sequence.append(bases[integer - 1])
kmer_collection[''.join(temp_sequence)] = 0
return kmer_collection
def kmer_occurrence(kmers: list, kmer_combinations: dict) -> dict:
"""
Count the occurrence of each kmer in a string
:param kmers: list, a collection of k-mers
:param kmer_combinations: dict, all possible combinations of kmers
:return: dict, the occurrence of each k-mer in the string
"""
for kmer in kmers:
if kmer in kmer_combinations:
kmer_combinations[kmer] += 1
return kmer_combinations
def report_occurrence(kmer_occurrence: dict):
"""
Report the occurrence of each k-mer in lexicographical order
:param kmer_occurrence: dict, the occurrence of each k-mer
"""
sorted_kmers = {kmer: count for kmer, count in sorted(kmer_occurrence.items(), key=lambda item: item[0])}
with open("answer_file.txt", 'w') as writer:
writer.write(' '.join(str(count) for count in list(sorted_kmers.values())))
if __name__ == "__main__":
dna_seq = argv[1]
fasta_dict = parse_fasta(dna_seq)
fasta_string = list(fasta_dict.values())[0]
kmer_list = create_kmers(fasta_string, 4)
integer_combinations = find_combinations(4)
kmer_counts = kmer_occurrence(kmer_list, generate_kmer_combinations(integer_combinations))
report_occurrence(kmer_counts)
<file_sep>/Scripts/nucleotide_count.py
"""
Script to count the number of nucleotides in a single DNA string.
Author: <NAME>
Date: 21/09/2020
"""
# imports
import re
from sys import argv
# functions
def parse_string(text_file: str) -> str:
"""
Parse a DNA string from a text file
:param text_file: str, name for file with a DNA string
:return: str, contains letters A, C, G and T only
"""
with open(text_file) as dna_strings:
for dna_str in dna_strings:
if is_valid_sequence(dna_str.strip()):
return dna_str.strip().lower()
def count_nucleotides(dna_str: str) -> dict:
"""
Count the number of A, C, G and T nucleotides of a string
:param dna_str: str, sequence of a DNA segment
:return: dict, contains the nucleotide: count
"""
nucleotide_dict = {'a': 0, 'c': 0, 'g': 0, 't': 0}
for nucleotide in dna_str:
nucleotide_dict[nucleotide] += 1
return nucleotide_dict
def report_nucleotide_count(nucleotide_count: dict):
"""
Reports the count of nucleotides from a dictionary
:param nucleotide_count: dict, contains count of each nucleotide
"""
print(f"{nucleotide_count['a']} {nucleotide_count['c']} "
f"{nucleotide_count['g']} {nucleotide_count['t']}")
def is_valid_sequence(dna_str: str) -> bool:
"""
Checks if the DNA segment only contains valid chars (A, C, G, T)
:param dna_str: str, sequence of a DNA segment
:return: bool, True if the DNA sequence is valid
"""
# pattern only matches to DNA nucleotides A, C, G and T
pattern = re.compile(r'^[*ACGTUacgtu]+$', re.IGNORECASE)
if re.match(pattern, dna_str):
return True
else:
return False
if __name__ == "__main__":
dna_string = parse_string(argv[1])
nucl_count = count_nucleotides(dna_string)
report_nucleotide_count(nucl_count)
<file_sep>/Scripts/dna_to_rna.py
"""
Script to convert a DNA string to an RNA string
Author: <NAME>
Date: 22/09/2020
"""
# imports
from nucleotide_count import is_valid_sequence
from nucleotide_count import parse_string
from sys import argv
def convert_dna_to_rna(dna_str: str) -> str:
"""
Convert a DNA sequence into an RNA sequence
:param dna_str: str, sequence of a DNA sequence
:return: str, sequence of a corresponding RNA segment
"""
if not is_valid_sequence(dna_str):
raise ValueError("Unknown characters in DNA string")
nucleotide_list = ['u' if nucleotide.lower() == 't' else
nucleotide.lower() for nucleotide in dna_str]
return ''.join(nucleotide_list).upper()
def write_output(rna_str: str, output_name: str):
"""
Write converted RNA sequence to a text file
:param rna_str: str, RNA sequence
:param output_name: str, name for the output file
"""
with open(output_name, 'w') as writer:
writer.write(rna_str)
if __name__ == "__main__":
dna_string = parse_string(argv[1])
rna_string = convert_dna_to_rna(dna_string)
write_output(rna_string, "dna_to_rna_output")
<file_sep>/Scripts/rna_splicing.py
"""
Script to excise intronic sequences from DNA and translate it to a protein
Author: <NAME>
Date: 29/09/2020
"""
# imports
from dna_to_rna import convert_dna_to_rna
from gc_content import parse_fasta
from translate_rna import rna_to_protein
from translate_rna import report_protein
from sys import argv
# functions
def extract_headers(text_file: str) -> list:
"""
Extract all headers from a text file with fasta sequences
:param text_file: str, name of the file with fasta sequences
:return: list, all headers corresponding to the fasta sequences
"""
headers = []
with open(text_file, 'r') as lines:
for line in lines:
if line.startswith('>'):
headers.append(line.strip('>').strip())
return headers
def excise_introns(sequence: str, introns: list) -> str:
"""
Excise intronic subs sequences from the main DNA sequence
:param sequence: str, main sequence
:param introns: list, to be excised intronic sequences
:return: str, DNA sequences without intronic sequences
"""
intron_cords = []
for intron in introns:
for i in range(len(sequence)):
if intron == sequence[i:i + len(intron)]:
intron_cords.append((i, i + len(intron)))
intron_cords = sorted(intron_cords)
exons = []
for pos, cords in enumerate(intron_cords):
if pos == 0:
exons.append(sequence[:cords[0]])
else:
exons.append(sequence[intron_cords[pos - 1][1]:cords[0]])
exons.append(sequence[intron_cords[-1][1]:])
return ''.join(exons)
if __name__ == "__main__":
fasta_list = extract_headers(argv[1])
fasta_seqs = parse_fasta(argv[1])
main_seq = fasta_seqs[fasta_list[0]]
substrings = [fasta_seqs[header] for header in fasta_list[1:]]
excised_sequence = excise_introns(main_seq, substrings)
rna_seq = convert_dna_to_rna(excised_sequence.lower())
report_protein(rna_to_protein(rna_seq))
| a26022d9985c730f2272307ed99d4ce5a03acd9a | [
"Python"
] | 16 | Python | dominiquems/Rosalind | 81753eb86a05427e58af9fb980daa4eaa8535ed8 | e7839d90eeef1dbfc7a225e5ce15b18303a83b1e |
refs/heads/master | <file_sep>var express = require('express');
var app = express();
var multer = require('multer')
var cors = require('cors');
app.use(cors());
const path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'upload')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
//var upload = multer({ storage: storage }).single('file')
var upload = multer({ storage: storage }).array('file')
app.post('/upload',function(req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err)
} else if (err) {
return res.status(500).json(err)
}
return res.status(200).send(req.file)
})
});
//Serve static assets in production.
if (process.env.NODE_ENV==='production') {
// set static folder
app.use(express.static('build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'))
});
}
const PORT = process.env.PORT || 4000;
app.listen(PORT,()=>console.log(`Server started on port ${PORT}`));
<file_sep># fileupload-react-node
react-file-upload in node js
| cc99cfcef90cbbd61e265e432bd43f0e9b10c131 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | manojmoktandev/fileupload-react-node | fc8a006ff8bb2a604120567b741800a2cf66c580 | cf25c897d28d1d20982cb5944c53ffe632f65ba0 |
refs/heads/master | <repo_name>Maygriev/Eventos<file_sep>/eventos/index.php
<?php
require_once "../autoload.php";
require_once "../src/bones/header.php";
?>
<div class="row">
<div class="col">
<h1 class="text-center">Eventos</h1>
</div>
</div>
<hr/>
<div class="row">
<div class="col">
<div class="form-group row">
<label for="searchBar" class="col-2 col-form-label">Busca: </label>
<div class="col-10">
<input type="password" class="form-control" id="searchBar" placeholder="Insira sua Busca">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<table class="table">
<thead>
<tr>
<th scope="col">Nome</th>
<th scope="col">Período</th>
<th scope="col">Ano</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">SECITEX</td>
<td>XX/XX a XX/XX</td>
<td>2019</td>
</tr>
<tr>
<td scope="row">EXPOTEC</td>
<td>XX/XX a XX/XX</td>
<td>2019</td>
</tr>
<tr>
<td scope="row">SITADS</td>
<td>XX/XX a XX/XX</td>
<td>2019</td>
</tr>
</tbody>
</table>
</div>
</div>
<?php
require_once "../src/bones/footer.php";
?><file_sep>/README.md
# Eventos
Sistema de Gerenciamento de Eventos
<file_sep>/inscricoes/index.php
<?php
require_once "../autoload.php";
require_once "../src/bones/header.php";
?>
<div class="row">
<div class="col">
<h1 class="text-center">Minhas Inscrições</h1>
</div>
</div>
<hr/>
<div class="row justify-content-center">
<div class="col">
<div class="card">
<div class="card-body">
<h5 class="card-title">Minhas Inscrições</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-body">
<h5 class="card-title">Inscrições Abertas</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</div>
<?php
require_once "../src/bones/footer.php";
?> | 813e06bc0917d32baabc1f3c41390d8570cddc3f | [
"Markdown",
"PHP"
] | 3 | PHP | Maygriev/Eventos | 995ad7f01727bbc56b4baa7fa2ef9f6a92226554 | 83d4951424b7e0adecefaf3325dcbb5c9a4cfc20 |
refs/heads/master | <file_sep>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.04.23 at 07:12:03 PM MST
//
package beans.response;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{http://bioontology.org/bioportal/classBeanSchema#}fullId" minOccurs="0"/>
* <element ref="{http://bioontology.org/bioportal/classBeanSchema#}id" minOccurs="0"/>
* <element ref="{http://bioontology.org/bioportal/classBeanSchema#}label" minOccurs="0"/>
* <element ref="{http://bioontology.org/bioportal/classBeanSchema#}relations" minOccurs="0"/>
* <element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"fullIdOrIdOrLabel"
})
@XmlRootElement(name = "classBean")
public class ClassBean {
/*@XmlElementRefs({
@XmlElementRef(name = "fullId", namespace = "http://bioontology.org/bioportal/classBeanSchema#", type = JAXBElement.class),
@XmlElementRef(name = "label", namespace = "http://bioontology.org/bioportal/classBeanSchema#", type = JAXBElement.class),
@XmlElementRef(name = "type", namespace = "http://bioontology.org/bioportal/classBeanSchema#", type = JAXBElement.class),
@XmlElementRef(name = "relations", namespace = "http://bioontology.org/bioportal/classBeanSchema#", type = Relations.class),
@XmlElementRef(name = "id", namespace = "http://bioontology.org/bioportal/classBeanSchema#", type = JAXBElement.class)
})*/
@XmlElementRefs({
@XmlElementRef(name = "fullId", namespace = "", type = JAXBElement.class),
@XmlElementRef(name = "label", namespace = "", type = JAXBElement.class),
@XmlElementRef(name = "type", namespace = "", type = JAXBElement.class),
@XmlElementRef(name = "relations", namespace = "", type = Relations.class),
@XmlElementRef(name = "id", namespace = "", type = JAXBElement.class)
})
protected List<Object> fullIdOrIdOrLabel;
/**
* Gets the value of the fullIdOrIdOrLabel property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the fullIdOrIdOrLabel property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFullIdOrIdOrLabel().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link Relations }
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*
*/
public List<Object> getFullIdOrIdOrLabel() {
if (fullIdOrIdOrLabel == null) {
fullIdOrIdOrLabel = new ArrayList<Object>();
}
return this.fullIdOrIdOrLabel;
}
}
<file_sep>package client;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.xml.bind.JAXBElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import db.ProvisionalTermDAO;
import beans.ProvisionalTerm;
import beans.response.Success;
public class TermsToOntologiesClient {
private BioPortalClient bioPortalClient;
private Logger logger;
public TermsToOntologiesClient() throws Exception {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties properties = new Properties();
properties.load(loader.getResourceAsStream("config.properties"));
String url = properties.getProperty("bioportalUrl");
String userId = properties.getProperty("bioportalUserId");
String apiKey = properties.getProperty("bioportalApiKey");
bioPortalClient = new BioPortalClient(url, userId, apiKey);
logger = LoggerFactory.getLogger(this.getClass());
}
/**
* @param provisionalTerm
* @return temporary id given to the provided provisionalTerm
* @throws Exception
*/
public String sendTerm(ProvisionalTerm provisionalTerm) throws Exception {
Success success = bioPortalClient.createProvisionalTerm(provisionalTerm);
String temporaryId = getIdFromSuccessfulCreate(success, "id");
provisionalTerm.setTemporaryid(temporaryId);
ProvisionalTermDAO.getInstance().addAwaitingAdoption(provisionalTerm);
return temporaryId;
}
/**
* @return Map<Temporary ID, Permanent ID> of newly discovered adoptions
* @throws Exception
*/
public Map<String, String> checkTermAdoptions() throws Exception {
Map<String, String> result = new HashMap<String, String>();
List<ProvisionalTerm> allProvisionalTermsAwaitingAdoption = ProvisionalTermDAO.getInstance().getAllAwaitingAdoption();
for(ProvisionalTerm provisionalTerm : allProvisionalTermsAwaitingAdoption) {
Success success = bioPortalClient.getProvisionalTerm(provisionalTerm.getTemporaryid());
String permanentId = getIdFromSuccessfulCreate(success, "id");
String temporaryId = getIdFromSuccessfulCreate(success, "fullId");
if(permanentId.equals(temporaryId))
continue;
else {
provisionalTerm.setPermanentid(permanentId);
ProvisionalTermDAO.getInstance().deleteAwaitingAdoption(provisionalTerm);
ProvisionalTermDAO.getInstance().storeAdopted(provisionalTerm);
result.put(temporaryId, permanentId);
}
}
return result;
}
private String getIdFromSuccessfulCreate(Success createSuccess, String idName) {
List<Object> fullIdOrIdOrLabel = createSuccess.getData().getClassBean().getFullIdOrIdOrLabel();
for(Object object : fullIdOrIdOrLabel) {
if(object instanceof JAXBElement) {
JAXBElement<String> possibleIdElement = (JAXBElement<String>)object;
if(possibleIdElement.getName().toString().equals(idName)) {
return possibleIdElement.getValue();
}
}
}
return null;
}
}
<file_sep>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.2-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.04.23 at 07:12:03 PM MST
//
package beans.response;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element ref="{http://bioontology.org/bioportal/classBeanSchema#}list" minOccurs="0"/>
* <element ref="{http://bioontology.org/bioportal/classBeanSchema#}classBean" minOccurs="0"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
})
@XmlRootElement(name = "data")
public class Data {
protected List list;
protected ClassBean classBean;
/**
* Gets the value of the list property.
*
* @return
* possible object is
* {@link List }
*
*/
public List getList() {
return list;
}
/**
* Sets the value of the list property.
*
* @param value
* allowed object is
* {@link List }
*
*/
public void setList(List value) {
this.list = value;
}
/**
* Gets the value of the classBean property.
*
* @return
* possible object is
* {@link ClassBean }
*
*/
public ClassBean getClassBean() {
return classBean;
}
/**
* Sets the value of the classBean property.
*
* @param value
* allowed object is
* {@link ClassBean }
*
*/
public void setClassBean(ClassBean value) {
this.classBean = value;
}
}
<file_sep>package beans;
public class ProvisionalTerm {
private String temporaryid;
private String permanentid;
private String superclass;
private String submittedby;
private String definition;
private String ontologyids;
private String preferredname;
private String synonyms;
public ProvisionalTerm() { }
public ProvisionalTerm(String temporaryid, String permanentid, String superclass,
String submittedby, String definition, String ontologyids,
String preferredname, String synonyms) {
this.temporaryid = temporaryid;
this.permanentid = permanentid;
this.superclass = superclass;
this.submittedby = submittedby;
this.definition = definition;
this.ontologyids = ontologyids;
this.preferredname = preferredname;
this.synonyms = synonyms;
}
public String getPermanentid() {
return permanentid;
}
public void setPermanentid(String permanentid) {
this.permanentid = permanentid;
}
public String getSuperclass() {
return superclass;
}
public void setSuperclass(String superclass) {
this.superclass = superclass;
}
public String getSubmittedby() {
return submittedby;
}
public void setSubmittedby(String submittedby) {
this.submittedby = submittedby;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public String getOntologyids() {
return ontologyids;
}
public void setOntologyids(String ontologyids) {
this.ontologyids = ontologyids;
}
public String getPreferredname() {
return preferredname;
}
public void setPreferredname(String preferredname) {
this.preferredname = preferredname;
}
public boolean hasPermanentId() {
return this.permanentid != null;
}
public boolean hasSuperClass() {
return this.superclass != null;
}
public boolean hasSubmittedBy() {
return this.submittedby != null;
}
public boolean hasDefinition() {
return this.definition != null;
}
public boolean hasOntologyIds() {
return this.ontologyids != null;
}
public boolean hasPreferredName() {
return this.preferredname != null;
}
public String getSynonyms() {
return this.synonyms;
}
public boolean hasSynonyms() {
return this.synonyms != null;
}
public boolean hasTemporaryId() {
return this.temporaryid != null;
}
public String getTemporaryid() {
return temporaryid;
}
public void setTemporaryid(String temporaryid) {
this.temporaryid = temporaryid;
}
public void setSynonyms(String synonyms) {
this.synonyms = synonyms;
}
}
<file_sep>package db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import beans.ProvisionalTerm;
public class ProvisionalTermDAO extends AbstractDAO {
private static ProvisionalTermDAO instance;
private ProvisionalTermDAO() throws Exception { }
public static ProvisionalTermDAO getInstance() throws Exception {
if(instance == null)
instance = new ProvisionalTermDAO();
return instance;
}
public void addAwaitingAdoption(ProvisionalTerm provisionalTerm) throws SQLException {
this.openConnection();
createTableIfNecessary("awaitingadoption");
this.storeProvisionalTerm("awaitingadoption", provisionalTerm);
this.closeConnection();
}
public List<ProvisionalTerm> getAllAwaitingAdoption() throws SQLException {
this.openConnection();
List<ProvisionalTerm> result = this.getAll("awaitingAdoption");
this.closeConnection();
return result;
}
public void storeAdopted(ProvisionalTerm provisionalTerm) throws SQLException {
this.openConnection();
createTableIfNecessary("adopted");
storeProvisionalTerm("adopted", provisionalTerm);
this.closeConnection();
}
public void deleteAwaitingAdoption(ProvisionalTerm provisionalTerm) throws SQLException {
this.openConnection();
this.executeSQL("DELETE FROM awaitingadoption WHERE temporaryId='" + provisionalTerm.getTemporaryid() + "'");
this.closeConnection();
}
private void storeProvisionalTerm(String tableName, ProvisionalTerm provisionalTerm) throws SQLException {
PreparedStatement preparedStatement = this.prepareStatement("INSERT INTO " + tableName + " (`temporaryId`, `permanentId`, `superClass`, " +
"`submittedby`, `definition`, `ontologyids`, `preferredname`, `synonyms`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
preparedStatement.setString(1, provisionalTerm.getTemporaryid());
preparedStatement.setString(2, provisionalTerm.getPermanentid());
preparedStatement.setString(3, provisionalTerm.getSuperclass());
preparedStatement.setString(4, provisionalTerm.getSubmittedby());
preparedStatement.setString(5, provisionalTerm.getDefinition());
preparedStatement.setString(6, provisionalTerm.getOntologyids());
preparedStatement.setString(7, provisionalTerm.getPreferredname());
preparedStatement.setString(8, provisionalTerm.getSynonyms());
preparedStatement.executeUpdate();
}
private void createTableIfNecessary(String tableName) throws SQLException {
this.executeSQL("CREATE TABLE IF NOT EXISTS " + tableName + "(" +
" `temporaryId` varchar(100) NOT NULL, " +
" `permanentId` varchar(100) DEFAULT NULL, " +
" `superClass` varchar(100) DEFAULT NULL, " +
" `submittedBy` varchar(100) DEFAULT NULL, " +
" `definition` text, " +
" `ontologyIds` varchar(100) DEFAULT NULL, " +
" `preferredName` varchar(100) DEFAULT NULL, " +
" `synonyms` varchar(100) DEFAULT NULL, " +
" PRIMARY KEY (`temporaryId`))");
}
public List<ProvisionalTerm> getAll(String tableName) throws SQLException {
List<ProvisionalTerm> result = new ArrayList<ProvisionalTerm>();
PreparedStatement preparedStatement = this.executeSQL("SELECT * FROM " + tableName);
ResultSet resultSet = preparedStatement.getResultSet();
while(resultSet.next()) {
result.add(new ProvisionalTerm(resultSet.getString("temporaryId"),
resultSet.getString("permanentId"),
resultSet.getString("superClass"),
resultSet.getString("submittedBy"),
resultSet.getString("definition"),
resultSet.getString("ontologyIds"),
resultSet.getString("preferredName"),
resultSet.getString("synonyms")
));
}
return result;
}
public static void main(String[] args) {
ProvisionalTerm provisionalTerm = new ProvisionalTerm();
provisionalTerm.setTemporaryid("tempId");
provisionalTerm.setDefinition("def");
provisionalTerm.setPreferredname("name");
provisionalTerm.setSubmittedby("submittedby");
try {
ProvisionalTermDAO.getInstance().addAwaitingAdoption(provisionalTerm);
List<ProvisionalTerm> all = ProvisionalTermDAO.getInstance().getAllAwaitingAdoption();
ProvisionalTermDAO.getInstance().storeAdopted(provisionalTerm);
ProvisionalTermDAO.getInstance().deleteAwaitingAdoption(provisionalTerm);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| fde343f35cfa818845d865d430d66f1a7e87739e | [
"Java"
] | 5 | Java | hongcui/TermsToOntologies | 7aca1286ab9484c808280a6e8d91d3dcd05a58c4 | af3af6de425854789d9281d8f950a9bb3063796f |
refs/heads/master | <file_sep>#!/usr/bin/env python
import time
import os
import unittest
import logging
import unittest.mock
import microgear
import microgear.client as client
from unittest.mock import MagicMock
import subprocess
#from testfixtures import LogCapture
#import threading
connect_timeout = 4
message_timeout = 4
class TestResettoken(unittest.TestCase):
def setUp(self):
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.helperGearname = "helper"
self.message = 'hello'
self.topic = '/firstTopic'
self.expectedMessage = str(self.message.encode('utf-8')) #convert to bytes
self.expectedMsgTopic = "/" + self.appid + "/gearname/" + self.gearname
self.expectedTopic = "/" + self.appid + self.topic
self.received = False
#clear microgear.cache file
cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "w")
print(cache_file)
cache_file.write("")
cache_file.close()
receiver_file = open(os.path.join(os.getcwd()+"/receiver.txt"), "w")
print(receiver_file)
receiver_file.write("")
receiver_file.close()
def tearDown(self):
#delete receive txt
os.remove(os.path.join(os.getcwd()+"/receiver.txt"))
#fail
# def testCode8Case3(self):
# """resettoken twice"""
# self.assertTrue(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
# self.assertIsNone(microgear.gearkey)
# self.assertIsNone(microgear.gearsecret)
# self.assertIsNone(microgear.appid)
# client.create(self.gearkey, self.gearsecret, self.appid)
# client.on_connect = MagicMock()
# client.resettoken()
# time.sleep(2)
# self.assertFalse(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
# # client.resettoken()
# # time.sleep(2)
# # self.assertFalse(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
# client.connect()
# time.sleep(connect_timeout)
# self.assertTrue(client.on_connect.called)
# self.assertEqual(client.on_connect.call_count, 1)
# self.assertTrue(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
def testCode8Case2(self):
"""resettoken when have microgear.cache while microgear is offline"""
self.assertTrue(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
self.assertIsNone(microgear.gearkey)
self.assertIsNone(microgear.gearsecret)
self.assertIsNone(microgear.appid)
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.resettoken()
self.assertFalse(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.assertEqual(client.on_connect.call_count, 1)
self.assertTrue(os.path.isfile(os.path.join(os.getcwd()+"/microgear.cache")))
# def main():
# pass
# #suite = unittest.TestSuite()
# #suite.addTest(TestChat("testCode4Case2"))
# #runner = unittest.TextTestRunner()
# #runner.run(suite)
# print(os.path.join(os.getcwd(),"microgear.cache"))
# unittest.main()
# if __name__ == '__main__':
# main() <file_sep>import microgear.client as client
import time
import os
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testPython"
if(os.path.isfile(os.path.join(os.getcwd(),"microgear.cache"))):
cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "w")
print(cache_file)
cache_file.write("")
cache_file.close()
time.sleep(6)
client.create(gearkey,gearsecret,appid,{'debugmode': True})
def connection():
print("Now I am connected with netpie")
def subscription(topic,message):
print(topic+" "+message)
client.unsubscribe("/secondTopic")
# client.chat("mainPython","Hey guy."+str(int(time.time())))
# client.setalias("doraemon2")
client.subscribe("/firstTopic")
print("shoud")
client.on_connect = connection
client.on_message = subscription
# client.subscribe("/mails")
# client.subscribe("/firstTopic")
client.connect(False)
#client.chat("","Hello world."+str(int(time.time())))
#need delay
while(True):
pass
print("end")
#os.remove(os.path.join(os.getcwd()+"/receiver.txt"))
#print(os.path.join(os.getcwd()))
#cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "r").read()
#print(cache_file)
#cache_file.write("")
#cache_file.close()<file_sep>import microgear.client as client
import time
def testChat():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
origin = "oriA"
destination = "destX"
client.create(gearkey , gearsecret, appid, {'debugmode': True})
client.setname(origin)
client.connect()
def receive_message(topic, message):
print topic + " " + message
while True:
client.chat(destination,"Hello world.")
time.sleep(3)
testChat()<file_sep>import microgear.client as client
import time
def testChat():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
gear_name = "not receiver"
client.create(gearkey , gearsecret, appid, {'debugmode': True})
client.setname(gear_name)
client.connect()
def receive_message(topic, message):
print topic + " " + message
while True:
client.chat("not receiver", "hello")
time.sleep(3)
client.on_message = receive_message
testChat()<file_sep>echo "start"
date +%Y%m%d%H%M%S
echo "
"
python3 helping.py &
ps
python3 unitTestPython.py
ps<file_sep>import microgear
import microgear.client as client
import time
import sys
import os
import os.path
if(os.path.isfile(os.path.join(os.getcwd(),"microgear.cache"))):
cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "w")
print(cache_file)
cache_file.write("")
cache_file.close()
time.sleep(6)
def helper(createx=[], setaliasx=[], chatx=[], publishx=[], subscribex=[]):
print(createx, setaliasx,chatx,publishx,subscribex)
message = "hello"
received = False
if(len(createx) > 0):
print(microgear.gearkey)
client.create(createx[0],createx[1],createx[2],{'debugmode': True})
def on_connected():
print("connect")
def on_disconnected():
print("disconnected")
def on_message(topic, message):
print("message")
time.sleep(2)
ack = open(os.path.join(os.getcwd(),"../receiver.txt"), "w")
print(ack)
ack.write(message)
ack.close()
def on_present(gearkey):
print("present")
def on_absent(gearkey):
print("absent")
def on_warning(msg):
print("reject")
def on_info(msg):
print("info")
def on_error(msg):
print("error")
client.on_connect = on_connected
client.on_disconnect = on_disconnected
client.on_message = on_message
client.on_present = on_present
client.on_absent = on_absent
client.on_warning = on_warning
client.on_info = on_info
client.on_error = on_error
if(len(setaliasx) > 0):
client.setalias(setaliasx[0])
if(len(subscribex) > 0):
client.subscribe(subscribex[0])
client.resettoken()
client.connect(False)
if(len(chatx) > 0):
while True:
client.chat(chatx[0], message)
print('chitchat')
time.sleep(2)
if(len(publishx) > 0) :
while True:
client.publish(publishx[0], message)
print('pubpush')
time.sleep(2)
print("in helper file")
print(os.path.join(os.getcwd(),"microgear.cache"))
while True:
pass
def code(x):
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testPython"
gearkey2 = "<KEY>"
gearsecret2 = "<KEY>"
appid2 = "testPythonHelper"
gearname = "mainPython"
helperGearname = "helper"
topic = "/firstTopic"
emptyStr = ""
invalidTopic = "firstTopic"
if(x == 11):
#create in different appkey and setalias to helperGearname
helper(createx=[gearkey2, gearsecret2, appid2], setaliasx=[helperGearname])
if(x == 12):
#create in different appkey and setalias to gearname
helper(createx=[gearkey2, gearsecret2, appid2], setaliasx=[gearname])
#create in same appkey and setalias to helperGearname
elif(x == 31):
helper(createx=[gearkey, gearsecret, appid], setaliasx=[helperGearname])
#create in same appkey and setalias to topic name
elif(x == 32):
helper(createx=[gearkey, gearsecret, appid], setaliasx=[topic])
#create in same appkey and setalias to gearname
elif(x == 33):
helper(createx=[gearkey, gearsecret, appid], setaliasx=[gearname])
#create in same appkey and setalias to empty str
elif(x == 34):
helper(createx=[gearkey, gearsecret, appid], setaliasx=[emptyStr])
#create in same appkey and chat to gearname
elif(x == 4):
helper(createx=[gearkey, gearsecret, appid], chatx=[gearname])
#create in same appkey and publish topic
elif(x == 51):
helper(createx=[gearkey, gearsecret, appid], publishx=[topic])
#create in same appkey and publish to empty topic
elif(x == 52):
helper(createx=[gearkey, gearsecret, appid], publishx=[emptyStr])
#create in same appkey and publish to invalid topic - no slash
elif(x == 53):
helper(createx=[gearkey, gearsecret, appid], publishx=[invalidTopic])
#create in same appkey and subscribe to topic
elif(x == 61):
helper(createx=[gearkey, gearsecret, appid], subscribex=[topic])
#create in same appkey and subscribe invalid topic - no slash
elif(x == 63):
helper(createx=[gearkey, gearsecret, appid], subscribex=[invalidTopic])
print(sys.argv)
code(int(sys.argv[1]))
# x = int(sys.argv[1])
<file_sep>import microgear.client as client
import time
import os
# if not (os.path.isfile(os.path.join(os.getcwd(),"microgear.cache"))):
# cache_file = open(os.path.join(os.getcwd(),"microgear.cache"), "w")
# print(cache_file)
# cache_file.write("")
# cache_file.close()
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testPython"
# gearkey = "<KEY>"
# gearsecret = "<KEY>"
# appid = "testPythonHelper"
client.create(gearkey,gearsecret,appid,{'debugmode': True})
def connection():
print("Now I am connected with netpie")
def subscription(topic,message):
print(topic+" "+message)
# client.publish("mainPython","Hey guy."+str(int(time.time())))
# client.setalias("doraemon2")
client.on_connect = connection
client.on_message = subscription
# client.subscribe("/firstTopic")
print('resettoken')
client.resettoken()
client.resettoken()
time.sleep(3)
client.connect(False)
# while(True):
# client.chat("firstTopic","Hello world.")
# print("pub")
# time.sleep(3)
# #need delay
print("end")
#os.remove(os.path.join(os.getcwd()+"/receiver.txt"))
#print(os.path.join(os.getcwd()))
#cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "r").read()
#print(cache_file)
#cache_file.write("")
#cache_file.close()<file_sep>import microgear.client as client
import time
import os
def testChat():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
origin = "oriA"
destination = "destX"
client.create(gearkey , gearsecret, appid, {'debugmode': True})
bf = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
print(bf)
client.resettoken()
af = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
print(af)
testChat()<file_sep>#general case - blue sky scenario
#requirement: connect for the first time
import microgear.client as client
import time
import unittest
#class TestMicrogearInPython(unittest.TestCase):
#def testGear(self):
#self.failUnless()
#def main():
#unittest.main()
#if __name__ == '__main__':
#main()
def testCreateNetPie1():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
return gearkey, gearsecret, appid
def testCreateNetPie21():
gearkey = ""
gearsecret = "<KEY>"
appid = "p107microgear"
#gearkey = "<KEY>"
#gearsecret = ""
#appid = "p107microgear"
#gearkey = "<KEY>"
#gearsecret = "<KEY>"
#appid = ""
return gearkey, gearsecret, appid
def testCreateNetPie22():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgeAR"
return gearkey, gearsecret, appid
def testCreateNetPie231():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
#gearkey = "<KEY>"
#gearsecret = "<KEY>"
#appid = "p107microgear"
#gearkey = "<KEY>"
#gearsecret = "<KEY>"
#appid = "p107microge"
return gearkey, gearsecret, appid
def testCreateNetPie232():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
#gearkey = "<KEY>"
#gearsecret = "<KEY>"
#appid = "p107microgear"
#gearkey = "<KEY>"
#gearsecret = "<KEY>"
#appid = "p107microgearrr"
return gearkey, gearsecret, appid
def testCreateNetPieDebug():
gearkey, gearsecret, appid = testCreateNetPie1();
client.create(gearkey, gearsecret, appid, {'debugmode' : False})
client.connect()
print("Sleep for 20 seconds")
time.sleep(100)
def testCreateNetPieLabel():
gearkey, gearsecret, appid = testCreateNetPie1();
client.create(gearkey, gearsecret, appid, {'label' : "Microgear Python"})
client.setname('logg')
client.connect()
print("Sleep for 90 seconds")
time.sleep(90)
def testCreateNetPieScopeName():
gearkey, gearsecret, appid = testCreateNetPie1();
client.create(gearkey, gearsecret, appid, {'debugmode' : True, 'scope' : "name:logger"})
client.setname('logg')
client.connect()
print("Sleep for 90 seconds")
time.sleep(90)
def testCreateNetPieScopeChat():
gearkey, gearsecret, appid = testCreateNetPie1();
client.create(gearkey, gearsecret, appid, {'debugmode' : True, 'scope' : "chat:java ja"})
client.setname('Python ja')
client.connect()
def receive_message(topic, message):
print topic + " " + message
while(True):
client.chat('Html ka', "Hello html")
time.sleep(3)
client.on_message = receive_message
def testCreateNetPieScopeW():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
client.create(gearkey , gearsecret, appid, {'debugmode': True,'scope': "r:/LetsShare" })
client.create(gearkey , gearsecret, appid, {'debugmode': True,'scope': "w:/LetsShare" })
client.setname("Python ja")
client.connect()
def receive_message(topic, message):
print topic + " " + message
while True:
client.publish("/StopsShare","Happy New Year!")
time.sleep(3)
client.on_message = receive_message
def testCreateNetPieScopeR():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "p107microgear"
client.create(gearkey , gearsecret, appid, {'debugmode': True, 'scope': "r:/LetsShare,w:/LetsShare"})
client.setname("Python ja")
#client.subscribe("/LetsShare")
client.subscribe("/LetsPlay")
client.connect()
def receive_message(topic, message):
print topic + " " + message
while True:
time.sleep(3)
client.on_message = receive_message
def testCreateNetPieConnection():
gearkey, gearsecret, appid = testCreateNetPie1();
client.create(gearkey, gearsecret, appid, {'debugmode' : False})
def on_connection():
print "I am connected"
client.on_connect = on_connection
print(client.on_connect == 0)
client.connect()
print("Sleep for 100 seconds")
time.sleep(100)
testCreateNetPieConnection()<file_sep>#!/usr/bin/env python
import time
import os
import unittest
import logging
import unittest.mock
import microgear
import microgear.client as client
from unittest.mock import MagicMock
import subprocess
#from testfixtures import LogCapture
#import threading
connect_timeout = 4
message_timeout = 4
class TestChat(unittest.TestCase):
def setUp(self):
print('setUp')
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.helperGearname = "helper"
self.message = 'hello'
self.topic = '/firstTopic'
self.expectedMessage = str(self.message.encode('utf-8')) #convert to bytes
self.expectedMsgTopic = "/" + self.appid + "/gearname/" + self.gearname
self.expectedTopic = "/" + self.appid + self.topic
self.received = False
self.connected = False
# #clear microgear.cache file
# cache_file = open(microgear_cache, "w")
# print(cache_file)
# cache_file.write("")
# cache_file.close()
r_file = open(receiver_file, "w")
print(r_file)
r_file.write("")
r_file.close()
# receiver_file = open(os.path.join(os.getcwd()+"/receiver.txt"), "w")
# print(receiver_file)
# receiver_file.write("")
# receiver_file.close()
imp.reload(client)
imp.reload(microgear)
def tearDown(self):
#delete receive txt
print('tearDown')
os.remove(os.path.join(os.getcwd()+"/receiver.txt"))
if(self.connected):
microgear.mqtt_client.disconnect()
def testCode4Case1(self):
"""chat with itself"""
print('Code4Case1')
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_message = MagicMock()
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
client.chat(self.gearname, self.message)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_once_with(self.expectedMsgTopic, self.expectedMessage)
#require helper 31
def testCode4Case2(self):
"""chat with other microgear in same appid"""
try:
print('Code4Case2')
print("run helper...")
code = str(31)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print("run main...")
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
client.chat(self.helperGearname, self.message)
time.sleep(message_timeout)
r_file = open(receiver_file, "r")
received_message = r_file.read()
r_file.close()
if(received_message == self.message):
self.received = True
self.assertTrue(self.received)
p.kill()
#if fails due to assertion error
except Exception as e:
print("fail")
raise Exception(e.args)
#helper 11
def testCode4Case3(self):
"""chat with other microgear in different appid"""
try:
print('Code4Case3')
print("run helper...")
code = str(11)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print("run main...")
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
client.chat(self.helperGearname, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 33
def testCode4Case5(self):
"""chat to microgear which shares the same name as itself"""
try:
print('Code4Case5')
print("run helper...")
code = str(33)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print("run main...")
self.helperGearname = self.gearname
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
client.chat(self.helperGearname, self.message)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_once_with(self.expectedMsgTopic, self.expectedMessage)
r_file = open(receiver_file, "r")
received_message = r_file.read()
r_file.close()
if(received_message == self.message):
self.received = True
self.assertTrue(self.received)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 12
def testCode4Case6(self):
"""chat with other microgear which shares the same gearname in different appid"""
try:
print('Code4Case6')
print("run helper...")
code = str(12)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print("run main...")
self.helperGearname = self.gearname
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
client.chat(self.helperGearname, self.message)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_once_with(self.expectedMsgTopic, self.expectedMessage)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 32
def testCode4Case8(self):
"""chat to microgear which has gearname similar to topic"""
try:
print('Code4Case8')
print("run helper...")
code = str(32)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print("run main...")
self.gearname = '/firstTopic'
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
client.chat(self.helperGearname, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 34
def testCode4Case9(self):
"""chat with other microgear which has empty string as gearname"""
try:
print('Code4Case9')
print("run helper...")
code = str(34)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print("run main...")
self.helperGearname = ""
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
print(self.helperGearname, "empty")
client.chat(self.helperGearname, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 61
def testCode4Case10(self):
"""chat to topic which has subscriber"""
try:
print('Code4Case10')
print("run helper...")
code = str(61)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print("run main...")
self.gearname = '/firstTopic'
client.create(self.gearkey, self.gearsecret, self.appid)
client.setalias(self.gearname)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
client.chat(self.helperGearname, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
class TestSubscribe(unittest.TestCase):
def setUp(self):
print('setUp')
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.helperGearname = "helper"
self.message = 'hello'
self.topic = '/firstTopic'
self.expectedMessage = str(self.message.encode('utf-8')) #convert to bytes
self.expectedMsgTopic = "/" + self.appid + "/gearname/" + self.gearname
self.expectedTopic = "/" + self.appid + self.topic
self.received = False
self.connected = False
#clear microgear.cache file
cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "w")
print(cache_file)
cache_file.write("")
cache_file.close()
receiver_file = open(os.path.join(os.getcwd()+"/receiver.txt"), "w")
print(receiver_file)
receiver_file.write("")
receiver_file.close()
imp.reload(client)
imp.reload(microgear)
def tearDown(self):
#delete receive txt
print('tearDown')
os.remove(os.path.join(os.getcwd()+"/receiver.txt"))
if(self.connected):
microgear.mqtt_client.disconnect()
#helper 51
def testCode5Case1(self):
"""subscribe one topic"""
try:
print('Code5Case1')
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
client.create(self.gearkey, self.gearsecret, self.appid)
client.subscribe(self.topic)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 51
def testCode5Case2(self):
"""subscribe same topic twice"""
try:
print('Code5Case2')
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
client.create(self.gearkey, self.gearsecret, self.appid)
client.subscribe(self.topic)
client.subscribe(self.topic)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 51
def testCode5Case3(self):
"""subscribe same topic twice"""
try:
print('Code5Case3')
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
client.create(self.gearkey, self.gearsecret, self.appid)
client.subscribe(self.topic)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
connected = True
self.assertEqual(client.on_connect.call_count, 1)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
#unsubscribe after receive message
client.unsubscribe(self.topic)
client.on_message.reset_mock() #reset count recorded by mock
self.assertFalse(client.on_message.called)
time.sleep(message_timeout)
self.assertFalse(client.on_message.called) #should not receive message now
client.subscribe(self.topic) #subscribe again
time.sleep(message_timeout)
self.assertTrue(client.on_message.called) #should receive message
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
def testCode5Case4(self):
"""subscribe the topic that it publishes"""
print('Code5Case4')
client.create(self.gearkey, self.gearsecret, self.appid)
client.subscribe(self.topic)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
client.publish(self.topic, self.message)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
## fail
# #helper 51
# def testCode5Case5x1(self):
# """subscribe empty topic"""
# try:
# print('Code5Case5x1')
# print("run helper...")
# code = str(51)
# args = ['python', 'helper.py', code]
# p = subprocess.Popen(args, cwd=(helper_dir))
# time.sleep(connect_worst_timeout)
# self.topic = ""
# client.create(self.gearkey, self.gearsecret, self.appid)
# client.subscribe(self.topic)
# client.on_connect = MagicMock()
# client.on_message = MagicMock()
# client.connect()
# time.sleep(connect_timeout)
# self.assertTrue(client.on_connect.called)
# self.connected = True
# # self.assertEqual(client.on_connect.call_count, 1)
# time.sleep(message_timeout)
# self.assertFalse(client.on_message.called)
# p.kill()
# #if fails due to assertion error
# except Exception as e:
# p.kill()
# raise Exception(e.args)
# # fail
# # helper 52
# def testCode5Case5x2(self):
# """subscribe empty topic"""
# try:
# print('Code5Case5x1')
# print("run helper...")
# code = str(52)
# args = ['python', 'helper.py', code]
# p = subprocess.Popen(args, cwd=(helper_dir))
# time.sleep(connect_worst_timeout)
# self.topic = ""
# client.create(self.gearkey, self.gearsecret, self.appid)
# client.subscribe(self.topic)
# client.on_connect = MagicMock()
# client.on_message = MagicMock()
# client.connect()
# time.sleep(connect_timeout)
# self.assertTrue(client.on_connect.called)
# self.connected = True
# self.assertEqual(client.on_connect.call_count, 1)
# time.sleep(message_timeout)
# self.assertFalse(client.on_message.called)
# p.kill()
# except Exception as e:
# p.kill()
# raise Exception(e.args)
# fail #TODO not sure why
# #helper 51 should publish topic
# def testCode5Case6x1(self):
# """subscribe invalid topic - no slash"""
# try:
# print('Code5Case6x1')
# print("run helper...")
# code = str(51)
# args = ['python', 'helper.py', code]
# p = subprocess.Popen(args, cwd=(helper_dir))
# time.sleep(connect_worst_timeout)
# self.topic = "firstTopic"
# client.create(self.gearkey, self.gearsecret, self.appid)
# client.subscribe(self.topic)
# client.on_connect = MagicMock()
# client.on_message = MagicMock()
# client.connect()
# time.sleep(connect_timeout)
# self.assertTrue(client.on_connect.called)
# self.connected = True
# self.assertEqual(client.on_connect.call_count, 1)
# time.sleep(message_timeout)
# self.assertFalse(client.on_message.called)
# p.kill()
# #if fails due to assertion error
# except Exception as e:
# p.kill()
# raise Exception(e.args)
#helper 53 should publish invalid topic
def testCode5Case6x2(self):
"""subscribe invalid topic - no slash"""
try:
print('Code5Case6x2')
print("run helper...")
code = str(53)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
self.topic = "firstTopic"
client.create(self.gearkey, self.gearsecret, self.appid)
client.subscribe(self.topic)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
time.sleep(message_timeout)
self.assertFalse(client.on_message.called)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
print('setUp')
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.helperGearname = "helper"
self.message = 'hello'
self.topic = '/firstTopic'
self.expectedMessage = str(self.message.encode('utf-8')) #convert to bytes
self.expectedMsgTopic = "/" + self.appid + "/gearname/" + self.gearname
self.expectedTopic = "/" + self.appid + self.topic
self.received = False
self.connected = False
#clear microgear.cache file
cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "w")
print(cache_file)
cache_file.write("")
cache_file.close()
receiver_file = open(os.path.join(os.getcwd()+"/receiver.txt"), "w")
print(receiver_file)
receiver_file.write("")
receiver_file.close()
imp.reload(client)
imp.reload(microgear)
def tearDown(self):
#delete receive txt
print('tearDown')
os.remove(os.path.join(os.getcwd()+"/receiver.txt"))
if(self.connected):
microgear.mqtt_client.disconnect()
#helper 51
def testCode6Case1(self):
"""unsubscribe the subscribed topic"""
print('Code6Case1')
try:
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
client.subscribe(self.topic)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.unsubscribe(self.topic)
client.on_message.reset_mock()
self.assertFalse(client.on_message.called)
time.sleep(message_timeout)
self.assertFalse(client.on_message.called)
p.kill()
#if fails due to assertion error
except Exception as e:
p.kill()
raise Exception(e.args)
# helper 51
def testCode6Case2(self):
"""unsubscribe the topic before subscribe"""
print('Code6Case2')
print(microgear.gearkey)
try:
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print(microgear.gearkey)
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
self.assertFalse(client.on_message.called)
client.unsubscribe(self.topic)
self.assertFalse(client.on_message.called)
client.subscribe(self.topic)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 51
def testCode6Case3(self):
"""unsubscribe the same topic twice"""
print(microgear.gearkey)
try:
print('Code6Case3')
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
print(microgear.gearkey)
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.on_message = MagicMock()
self.assertFalse(client.on_connect.called)
self.assertFalse(client.on_message.called)
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
self.assertFalse(client.on_message.called)
client.subscribe(self.topic)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
client.on_message.reset_mock()
self.assertFalse(client.on_message.called)
client.unsubscribe(self.topic)
time.sleep(connect_timeout)
self.assertFalse(client.on_message.called)
client.unsubscribe(self.topic)
time.sleep(connect_timeout)
self.assertFalse(client.on_message.called)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 51 to publish topic
def testCode6Case4x1(self):
"""unsubscribe the empty topic"""
print('Code6Case4x1')
try:
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
self.emptyStr = ""
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
self.assertFalse(client.on_message.called)
client.subscribe(self.topic)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
client.on_message.reset_mock()
self.assertFalse(client.on_message.called)
client.unsubscribe(self.emptyStr)
time.sleep(connect_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
#fail due to subscribe to empty string fail
#helper 52 to publish empty string topic
# def testCode6Case4x2(self):
# """unsubscribe the empty topic"""
# try:
# print("run helper...")
# code = str(52)
# args = ['python', 'helper.py', code]
# p = subprocess.Popen(args, cwd=(helper_dir))
# time.sleep(connect_worst_timeout)
# self.topic = ""
# client.create(self.gearkey, self.gearsecret, self.appid)
# client.on_connect = MagicMock()
# client.on_message = MagicMock()
# client.connect()
# time.sleep(connect_timeout)
# self.assertTrue(client.on_connect.called)
# self.connected = True
# self.assertEqual(client.on_connect.call_count, 1)
# self.assertFalse(client.on_message.called)
# client.subscribe(self.topic)
# time.sleep(message_timeout)
# self.assertTrue(client.on_message.called)
# client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
# client.on_message.reset_mock()
# self.assertFalse(client.on_message.called)
# client.unsubscribe(self.topic)
# time.sleep(connect_timeout)
# self.assertTrue(client.on_message.called)
# client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
# p.kill()
# except Exception as e:
# p.kill()
# raise Exception(e.args)
#helper 51
def testCode6Case5x1(self):
"""unsubscribe the invalid topic - no slash"""
try:
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
self.invalidStr = "firstTopic"
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
self.assertFalse(client.on_message.called)
client.subscribe(self.topic)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
client.on_message.reset_mock()
self.assertFalse(client.on_message.called)
client.unsubscribe(self.invalidStr)
time.sleep(connect_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 51
def testCode6Case6(self):
"""unsubscribe the topic that is not subscribed"""
try:
print("run helper...")
code = str(51)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
self.anotherTopic = "/secondTopic"
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.on_message = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
self.assertFalse(client.on_message.called)
client.subscribe(self.topic)
time.sleep(message_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
client.on_message.reset_mock()
self.assertFalse(client.on_message.called)
client.unsubscribe(self.anotherTopic)
time.sleep(connect_timeout)
self.assertTrue(client.on_message.called)
client.on_message.assert_called_with(self.expectedTopic, self.expectedMessage)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
class TestPublish(unittest.TestCase):
def setUp(self):
print('setUp')
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.helperGearname = "helper"
self.message = 'hello'
self.topic = '/firstTopic'
self.expectedMessage = str(self.message.encode('utf-8')) #convert to bytes
self.expectedMsgTopic = "/" + self.appid + "/gearname/" + self.gearname
self.expectedTopic = "/" + self.appid + self.topic
self.received = False
self.connected = False
#clear microgear.cache file
cache_file = open(os.path.join(os.getcwd()+"/microgear.cache"), "w")
print(cache_file)
cache_file.write("")
cache_file.close()
receiver_file = open(os.path.join(os.getcwd()+"/receiver.txt"), "w")
print(receiver_file)
receiver_file.write("")
receiver_file.close()
imp.reload(client)
imp.reload(microgear)
def tearDown(self):
#delete receive txt
print('tearDown')
os.remove(os.path.join(os.getcwd()+"/receiver.txt"))
if(self.connected):
microgear.mqtt_client.disconnect()
#helper 61
def testCode7Case1(self):
"""publish topic after some microgear subscribe that topic"""
try:
print("run helper...")
code = str(61)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
client.publish(self.topic, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
print(received_message)
print('received')
if(received_message == self.message):
self.received = True
self.assertTrue(self.received)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 61
def testCode7Case3(self):
"""publish topic that has no subscriber"""
try:
print("run helper...")
code = str(61)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
self.anotherTopic = "/secondTopic"
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
client.publish(self.anotherTopic, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
#fail due to subscribe empty topic fail
#helper 61
def testCode7Case4(self):
"""publish empty string topic"""
try:
print("run helper...")
code = str(61)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
self.anotherTopic = "/secondTopic"
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
client.publish(self.anotherTopic, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
#helper 61
def testCode7Case5(self):
"""publish invalid topic - no slash"""
try:
print("run helper...")
code = str(61)
args = ['python', 'helper.py', code]
p = subprocess.Popen(args, cwd=(helper_dir))
time.sleep(connect_worst_timeout)
self.invalidTopic = "firstTopic"
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.connected = True
self.assertEqual(client.on_connect.call_count, 1)
client.publish(self.invalidTopic, self.message)
time.sleep(message_timeout)
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "r")
received_message = receiver_file.read()
receiver_file.close()
if(received_message == self.message):
self.received = True
self.assertFalse(self.received)
self.assertTrue(client.on_connect.call_count > 1)
p.kill()
except Exception as e:
p.kill()
raise Exception(e.args)
def main():
#suite = unittest.TestSuite()
#suite.addTest(TestChat("testCode4Case2"))
#runner = unittest.TextTestRunner()
#runner.run(suite)
unittest.main()
if __name__ == '__main__':
main() <file_sep>import microgear.client as client
import time
import microgear
import unittest
import logging
import os
from testfixtures import LogCapture
from testfixtures import *
import threading
import six
def connectTo():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testNo3"
client.create(gearkey, gearsecret, appid, {'debugmode': "True"})
def on_connected():
print("connect")
def on_closed():
print("close")
def on_rejected():
print("reject")
def on_error():
print("error")
def on_message():
print("message")
def on_present():
print("present")
def on_absent():
print("absent")
client.on_connect = on_connected
#client.on_error = on_error
client.on_present = on_present
client.on_absent = on_absent
client.on_rejected = on_rejected
client.on_closed = on_closed
client.on_message = on_message
logs = LogCapture()
client.connect()
print(logs)
logs.check(('root', 'DEBUG', 'Check stored token.'))
def testAlias():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testNo3"
client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'alias': "Python"})
client.connect()
while True:
pass
def testScopeChat():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testNo3"
client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'scope': "chat:receiver"})
client.setname("sender")
client.connect()
def receive_message(topic, message):
print topic + " " + message
while True:
client.chat("not receiver","How are you?")
time.sleep(3)
def testtest():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testNo3"
if(os.path.isfile("microgear.cache")):
f = open((os.getcwd() + "/microgear.cache"), 'r')
print(f.readlines())
f.close()
else:
print("yes1")
client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'scope': "chat:receiver"})
client.setname("sender")
if(os.path.isfile("microgear.cache")):
f = open((os.getcwd() + "/microgear.cache"), 'r')
print(f.readlines())
f.close()
else:
print("yes2")
client.connect()
f = open((os.getcwd() + "/microgear.cache"), 'r')
print(f.readlines())
f.close()
client.resettoken()
if(os.path.isfile("microgear.cache")):
f = open((os.getcwd() + "/microgear.cache"), 'r')
print(f.readlines())
f.close()
else:
print("yes3")
def testCreateTwo():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testNo3"
client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'alias': "Nobita"})
client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'alias': "Doraemon"})
client.connect()
time.sleep(5)
print("Next")
client.connect()
time.sleep(5)
print("done")
def test():
gearkey = "<KEY>"
gearsecret = "<KEY>"
appid = "testNo3"
client.create(gearkey, gearsecret, appid, {'debugmode': "True", 'alias': "Nobita"})
client.connect()
time.sleep(40)
#def testChat2():
#gearkey = "ExhoyeQoTyJS5Ac"
#gearsecret = "<KEY>"
#appid = "p107microgear"
#client.create(gearkey , gearsecret, appid, {'debugmode': True})
#client.setname("Python ja")
#client.connect()
#def receive_message(topic, message):
#print topic + " " + message
#while True:
#client.chat("Html ka","How are you?")
#time.sleep(3)
#client.on_message = receive_message
#print(os.path.isfile("microgear.cache"))
#if(os.path.isfile("microgear.cache")):
#os.remove("microgear.cache")
#print(os.path.isfile("microgear.cache"))
test()<file_sep>
#class TestCreate(unittest.TestCase):
#def setUp(self):
#self.gearkey = "<KEY>"
#self.gearsecret = "<KEY>"
#self.appid = "testPython"
#def tearDown(self):
#fo = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
#print("Name ", fo)
#fo.close()
#print("done")
##def testConnectWithValidInput(self):
##client.on_connect = MagicMock()
##self.connected = False
##def on_connected():
##self.connected = True
##client.on_connect = on_connected
##client.create(self.gearkey, self.gearsecret, self.appid, {'debugmode': "True"})
##client.connect()
##timeout = time.time() + 30.0
##if(time.time() > timeout or self.connected):
##self.assertTrue(self.connected)
#@unittest.skip("")
#def testCode1Case1(self):
#"""create microgear with valid gearkey, gearsecret, and appid"""
#self.assertIsNone(microgear.gearkey)
#self.assertIsNone(microgear.gearsecret)
#self.assertIsNone(microgear.appid)
#client.create(self.gearkey, self.gearsecret, self.appid)
#self.assertEqual(self.gearkey, microgear.gearkey)
#self.assertEqual(self.gearsecret, microgear.gearsecret)
#self.assertEqual(self.appid, microgear.appid)
#client.on_connect = MagicMock()
#client.connect()
#time.sleep(5)
#self.assertTrue(client.on_connect.called)
#self.assertEqual(client.on_connect.call_count, 1)
#@unittest.skip("")
#def testCode1Case2(self):
#"""create microgear with invalid gearkey"""
#self.assertIsNone(microgear.gearkey)
#self.assertIsNone(microgear.gearsecret)
#self.assertIsNone(microgear.appid)
#self.gearkey = ""
#client.create(self.gearkey, self.gearsecret, self.appid)
#self.assertEqual(self.gearkey, microgear.gearkey)
#self.assertEqual(self.gearsecret, microgear.gearsecret)
#self.assertEqual(self.appid, microgear.appid)
#client.on_connect = MagicMock()
#client.on_error = MagicMock()
#self.assertFalse(client.on_connect.called)
#client.connect()
#time.sleep(5)
#self.assertFalse(client.on_connect.called)
#self.assertTrue(client.on_error.called)
<EMAIL>("")
#def testCode1Case3(self):
#"""create microgear with invalid gearsecret"""
#self.assertIsNone(microgear.gearkey)
#self.assertIsNone(microgear.gearsecret)
#self.assertIsNone(microgear.appid)
#self.gearsecret = ""
#client.create(self.gearkey, self.gearsecret, self.appid)
#self.assertEqual(self.gearkey, microgear.gearkey)
#self.assertEqual(self.gearsecret, microgear.gearsecret)
#self.assertEqual(self.appid, microgear.appid)
#client.on_connect = MagicMock()
#client.on_error = MagicMock()
#self.assertFalse(client.on_connect.called)
#client.connect()
#time.sleep(connect_timeout)
#self.assertFalse(client.on_connect.called)
#self.assertTrue(client.on_error.called)
class TestConnect(unittest.TestCase):
def setUp(self):
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.message = "hello"
def tearDown(self):
fo = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
print("Name ", fo)
fo.close()
print("done")
class TestSetalias(unittest.TestCase):
def setUp(self):
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.message = "hello"
def tearDown(self):
fo = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
print("Name ", fo)
fo.close()
print("done")
class TestPublish(unittest.TestCase):
def setUp(self):
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.message = "hello"
self.topic = '/firstTopic'
def tearDown(self):
fo = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
print("Name ", fo)
fo.close()
print("done")
@unittest.skip("")
def testCode1Case1(self):
#write file TODO
receiver_file = open(os.path.join(os.getcwd(),"receiver.txt"), "w")
self.assertIsNone(microgear.gearkey)
self.assertIsNone(microgear.gearsecret)
self.assertIsNone(microgear.appid)
client.create(self.gearkey, self.gearsecret, self.appid)
client.on_connect = MagicMock()
client.connect()
time.sleep(connect_timeout)
self.assertTrue(client.on_connect.called)
self.assertEqual(client.on_connect.call_count, 1)
client.publish(self.topic, self.message)
time.sleep(message_timeout)
#watch file
class TestResettoken(unittest.TestCase):
def setUp(self):
self.gearkey = "<KEY>"
self.gearsecret = "<KEY>"
self.appid = "testPython"
self.gearname = "mainPython"
self.message = "hello"
def tearDown(self):
fo = open(os.path.join(os.getcwd(),"microgear.cache"), "rb")
print("Name ", fo)
fo.close()
print("done")
| 9067eb6000c9049de2c66dfbd23ce6017ff3c156 | [
"Python",
"Shell"
] | 12 | Python | kki32/microgearlib_test_python | 6fc8398486a49bbac109d67d99df132e3335068a | ffcdd5e1e129cd9edece702a5744fcf64dcd9181 |
refs/heads/master | <file_sep># coding: utf-8
from pizzas import PizzaVegetarienne
from pizzas import PizzaFromage
class PizzaFactory:
def obtenir(self, type_pizza):
"""Implémentation du patron méthode factory.
la fonction obtenir esr responsable de l'instanciation de la bonne pizza
en fonction de la valeur passée en paramètre.
:param type_pizza: le type de pizza à instancier
"""
pizza = None
if type_pizza == "vegetarienne":
pizza = PizzaVegetarienne()
elif type_pizza == "fromage":
pizza = PizzaFromage()
else:
raise NotImplementedError
return pizza
<file_sep># coding: utf-8
"""
Abstraction d'une pizza et les différents type concrêts de pizzas.
"""
class Pizza:
""" Classe abstraite d'une pizza.
:param nom: la nom de la pizza.
"""
nom = ""
def preparer(self):
print ("... Preparer ...")
def cuire(self):
print ("... Cuisson ...")
def decouper(self):
print("... Découper ...")
def mettre_en_carton(self):
print("... Mise en carton ...")
def __str__(self):
return "Ma {nom} est prête!".format(nom=self.nom)
class PizzaVegetarienne(Pizza):
def __init__(self):
self.nom = "Pizza vegetarienne"
class PizzaFromage(Pizza):
def __init__(self):
self.nom = "Pizza aux trois fromages"
<file_sep># coding: utf-8
from commands import NoCommand
class Remote:
"""
A programmable remote control that can handle 10 on slots and 10 off slots.
"""
COMMAND_NUMBER = 10
def __init__(self):
self.slots = [NoCommand() for i in range(0, Remote.COMMAND_NUMBER)]
def set_command(self, index, command):
self.slots[index] = command
def press_on(self, index):
self.slots[index].execute_on()
def press_off(self, index):
self.slots[index].execute_off()
def __str__(self):
state = "Remote state\n"
for index, command in enumerate(self.slots):
state += "#{index} - {command}\n".format(
index=index, command=command
)
return state
def __repr__(self):
return self.__str__()
<file_sep># coding: utf-8
""" Créons des magasins de notre franchise à différents endroits de la planètes.
Nos pizzas disponibles sont les suivantes :
- Pizza végétarienne
- Pizza reine
- Pizza calzone
Nous avons trois restaurants situés :
- NYC, USA
- Paris, FRA
"""
from pizza_store_factory import NycStore
from pizza_store_factory import ParisStore
def main():
# NYC - style
nyc_store = NycStore()
nyc_store.welcomeMessage()
veggie_nyc = nyc_store.commanderPizza("vegetarienne")
print(veggie_nyc)
calzone_nyc = nyc_store.commanderPizza("calzone")
print(calzone_nyc)
reine_nyc = nyc_store.commanderPizza("reine")
print(reine_nyc)
# Paris - style
paris_store = ParisStore()
paris_store.welcomeMessage()
veggie_paris = paris_store.commanderPizza("vegetarienne")
print(veggie_paris)
calzone_paris = paris_store.commanderPizza("calzone")
print(calzone_paris)
reine_paris = paris_store.commanderPizza("reine")
print(reine_paris)
if __name__ == "__main__":
main()<file_sep># coding: utf-8
"""
We use an adapater class (object adaptater) to translate from the duck
interface (quack, fly) to the turkey interface (gobble, fly).
"""
class Duck:
def quack(self):
raise NotImplementedError()
def fly(self):
raise NotImplementedError()
class Turkey:
def gobble(self):
print("GLOUGLOU GLOUGLOU")
def fly(self):
print("Turkey flying")
class Turkey_adaptater(Duck):
def __init__(self, turkey):
self.turkey = turkey
def quack(self):
self.turkey.gobble()
def fly(self):
for i in range(5):
self.turkey.fly()
<file_sep># coding: utf-8
class Boisson(object):
"""Interface générique représentant une boisson (chaude ou froide).
"""
description = "Boisson inconnue"
def prix(self):
""" Retourne le prix de la boisson
:returns: le prix de la boisson
"""
raise NotImplementedError
class CafeNoir(Boisson):
"""Un cafe noir bien chaud
"""
def __init__(self):
self.description = "Cafe noir"
def prix(self):
return 1.5
<file_sep># coding: utf-8
"""
Objects/lib API that knows how to handle a request.
"""
class Light:
def lights_on(self):
print("** Lights : ON")
def lights_off(self):
print("** Lights: OFF")
class GarageDoor:
def open_door(self):
print("** Garage door: OPEN")
def close_door(self):
print("** Garage door: CLOSED")
<file_sep># coding: utf-8
from quack_comportement import Queuk
from quack_comportement import Quick
from vole_comportement import VoleAiles
from vole_comportement import VoleNon
class Canard(object):
"""Un cannard peut faire quack, voler et nager."""
vole_comportement = None
quack_comportement = None
def vole(self):
"""Methode abstraite pour effectuer un vol"""
self.vole_comportement.vole()
def quack(self):
"""Méthode abstraite pour faire un "Quaaack"""
self.quack_comportement.quack()
def nage(self):
"""Un canard sait nager"""
print("Je nage...")
class ColVert(Canard):
def __init__(self):
self.vole_comportement = VoleAiles()
self.quack_comportement = Quick()
class Poule(Canard):
def __init__(self):
self.vole_comportement = VoleNon()
self.quack_comportement = Queuk()
<file_sep># coding: utf-8
from boisson import Boisson
class CondimentDecorateur(Boisson):
"""Classe représentant un condiment abstrait décorateur qui peut être
ajouté à n'importe quel Boisson.
Il référence une Boisson pour utiliser la *composition*
Il hérite de Boisson pour respecter l'interface de Boisson.
"""
def __init__(self, sur_boisson):
self.boisson = sur_boisson
def description(self):
return " + {description_boisson}" \
.format(description_boisson=self.boisson.description)
class Chantilly(CondimentDecorateur):
""" Une boule de chantilly par dessus hummmm...
"""
description = "Chantilly"
def prix(self):
return .99 + self.boisson.prix()
<file_sep># coding: utf-8
"""
Abstract factory pattern: Provides an interface for creating families of related
or depedent objects without specifying their concrete classes.
"""
from pizza_ingredients_factory import AllemagnePizzaIngredientFactory
from pizza_ingredients_factory import NYCPizzaIngregientFactory
def main():
""" Different pizza store locations
delivering different versions of the same pizzas.
"""
Allemagne_pif = AllemagnePizzaIngredientFactory()
print(Allemagne_pif)
print(Allemagne_pif.creerPate())
print(Allemagne_pif.creerSauce())
print(Allemagne_pif.creerIngredients())
print("-"*50)
NYC_pif = NYCPizzaIngregientFactory()
print(NYC_pif)
print(NYC_pif.creerPate())
print(NYC_pif.creerSauce())
print(NYC_pif.creerIngredients())
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
""" Gestion d'un home cinéma à l'aide du pattern facade.
Notre sous-système correspond à tous les éléments nous permettant d'intéragir
avec un device, amplifieur, TV, sono, magnetoscope, lecteur DVD.
Le pattern facade nous permet d'unifié l'utilisation de tous ces appareils au
sein d'une seule interface qui simplifie l'utilisation et la gestion.
Facade design pattern: provides a unified interface to a set of interfaces in a
subsystem. Facade defines a higher level of interface that makes the subsystem
easier to use.
"""
def main():
"""
"""
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
"""
What if our system which knows how to handles ducks and chicken, would like to
manage turkeys (which has totally diffrent interfaces.
They gobble instead of quacking.
They fly really wierdly (they need 5 fly for one duck fly).
Plus the Turkey implementation is not ours to decide. It is a read-only vendor
class.
Adaptateur pattern: Converts the interface of a class into another interface
the client expects. Adaptateur let's classes work together that couldn't
otherwise because of incompatible interfaces.
"""
from duck_to_turkey import Turkey
from duck_to_turkey import Turkey_adaptater
def main():
turkey = Turkey()
adapt_turkey = Turkey_adaptater(turkey)
adapt_turkey.quack()
adapt_turkey.fly()
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
"""
Strategies for flying.
"""
class VoleComportement(object):
""" Interface décrivant les méthodes pour qu'un canard puisse voler.
"""
def vole(self):
""" Les vols concrêts doivent implémenter.
"""
raise NotImplementedError()
class VoleAiles(VoleComportement):
"""Un canard qui vole avec les ailes"""
def vole(self):
print("je vole avec mes ailes, très haut et très loin !!")
class VoleNon(VoleComportement):
""" Des canards qui malheureusement ne volent pas """
def vole(self):
print("je ne vole pas. :'(")
<file_sep># coding: utf-8
""" Un ensemble d'appareils avec lesquels nous pouvons intéragir.
"""
class Amplifier:
pass
class Tuner:
pass
class CDPlayer:
pass
class DVDPlayer:
pass
class Screen:
pass
class Projector:
pass
class TheaterLights:
pass
class PopcornMachine:
pass
<file_sep># coding: utf-8
"""
Nos implémentations de magasin.
"""
from pizza_ingredients_factory import NycPizzaIngregientFactory
from pizza_ingredients_factory import ParisPizzaIngredientFactory
from pizzas import Vegetarienne
from pizzas import Reine
from pizzas import Calzone
class PizzaStore:
name = None
def commanderPizza(self, pizza_type):
print(" * (" + self.name + ") Ordering pizza : " + pizza_type)
pizza = self.creerPizza(pizza_type)
pizza.preparer()
pizza.enfourner()
pizza.couper()
pizza.mettre_en_boite()
return pizza
def welcomeMessage(self):
print("-"*50)
print("Bienvenue à PIZZA dot {name}".format(name=self.name))
print("-"*50)
def creerPizza(self, pizza_type):
ingredient_factory = self.creerIngredientFactory()
if pizza_type == "vegetarienne":
return Vegetarienne(ingredient_factory)
elif pizza_type == "reine":
return Reine(ingredient_factory)
elif pizza_type == "calzone":
return Calzone(ingredient_factory)
else:
raise ValueError("Unsupported pizza type")
def creerIngredientFactory(self):
raise NotImplementedError()
class NycStore(PizzaStore):
name = "NYC"
def creerIngredientFactory(self):
return NycPizzaIngregientFactory()
class ParisStore(PizzaStore):
name = "Paris"
def creerIngredientFactory(self):
return ParisPizzaIngredientFactory()
<file_sep># coding: utf-8
"""
Strategies for quacking.
"""
class Quack(object):
""" Interface quack"""
def quack(self):
"""Méthode abstraite"""
raise NotImplementedError()
class Queuk(Quack):
def quack(self):
print("queuuueuck")
class Quick(Quack):
"""Le comportement est quick"""
def quack(self):
print("Quiiiiiiiiiiick")
<file_sep># coding: utf-8
"""
Implementation of the command design pattern : Encapsulate requests in objects.
a remote control that can has inputs to send On actions and Off actions.
It has 10 of each and they are able to control Lights or GarageDoor.
Command pattern: Encapsulates a request as an object, thereby letting you
parametize clients with diffrents requests, queue or log requests, and support
undoable operations.
"""
from vendors import Light
from vendors import GarageDoor
from commands import LightCommand
from commands import GarageDoorCommand
from remote import Remote
def main():
""" A remote control that is programmed to control the light in button 0
and the garage door in the button 6
"""
print("Initialization of the remote")
remote = Remote()
print(remote)
# Programming button 1 to control lights
light = Light()
light_command = LightCommand(light)
remote.set_command(0, light_command)
print(remote)
# Programming button 1 to control garage door
garage_door = GarageDoor()
garage_command = GarageDoorCommand(garage_door)
remote.set_command(6, garage_command)
print(remote)
print("Testing possible actions")
remote.press_on(0)
remote.press_off(0)
remote.press_on(6)
remote.press_off(6)
remote.press_on(1)
remote.press_off(1)
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
"""Implémentation du patron de conception methode factory
Le but est de crééer et de préparer des pizzas de différents types
à l'aide d'une factory.
Factory method pattern: Provides an interface for creating an object, but let
sublasses decide which class to instanciate. Factory method let's a class defer
instanciation to the subclasses.
"""
from magasin_pizza import MagasinPizza
def main():
print("Bienvenue dans mon Pizza Store")
mon_magasin = MagasinPizza()
print("Un client demande une pizza vegetarienne !")
vegetarienne = mon_magasin.commander("vegetarienne")
print(vegetarienne)
print("Un client demande une pizza au fromage !")
fromage = mon_magasin.commander("fromage")
print(fromage)
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
""" Nos fabriques abstraites dont l'objectif est de mettre à dispositions tous
les ingrédients nécessaires à la confection d'une pizza (création de sauce,
de pate etc.).
En centralisant les méthodes de créations dans une classe, on se laisse la
possibilité de générer des types d'ingrédients ensemble.
"""
from ingredients import PateFine
from ingredients import PateEpaisse
from ingredients import SauceTomate
from ingredients import SauceFlamekuche
from ingredients import Champignons
from ingredients import Jambon
from ingredients import Lardons
from ingredients import Oignons
class PizzaIngredientFactory(object):
name = None
def creerPate(self):
raise NotImplementedError()
def creerSauce(self):
raise NotImplementedError()
def creerFromage(self):
raise NotImplementedError()
def creerIngredients(self):
raise NotImplementedError()
def __str__(self):
return self.__repr__()
def __repr__(self):
return "Fournisseur officiel de la région {fournisseur}" \
.format(fournisseur=self.name)
class NycPizzaIngregientFactory(PizzaIngredientFactory):
""" Des pizzas qui ressemblent à la pizza reine. """
def __init__(self):
self.name = "New York City"
def creerPate(self):
return PateFine()
def creerSauce(self):
return SauceTomate()
def creerIngredientsVegetarienne(self):
return [Champignons()]
def creerIngredientsReine(self):
return [Jambon(), Champignons(), Oignons()]
def creerIngredientsCalzone(self):
return [Champignons(), Oignons()] # oeufs
class ParisPizzaIngredientFactory(PizzaIngredientFactory):
""" Des pizzas qui ressemblent à une pizza flamekuche.
"""
def __init__(self):
self.name = "Paris"
def creerPate(self):
return PateEpaisse()
def creerSauce(self):
return SauceFlamekuche()
def creerIngredientsVegetarienne(self):
return [Champignons()]
def creerIngredientsReine(self):
return [Jambon(), Oignons(), Lardons()]
def creerIngredientsCalzone(self):
return [Oignons()]
<file_sep># coding: utf-8
""" Liste des ingrédients nécessaires à la préparation d'une pizza.
Une pate (fine ou epaisse), une sauce (ici tomate ou crême fraîche) et des
ingrédients par dessus.
Ce sont les produits de nos fabriques abstraites.
"""
class Pate(object):
name = None
def __repr__(self):
return "Pate : {name}".format(name=self.name)
def __str__(self):
return self.__repr__()
class PateFine(Pate):
def __init__(self):
self.name = "Fine"
class PateEpaisse(Pate):
def __init__(self):
self.name = "Double"
class Sauce(object):
name = None
def __repr__(self):
return "Sauce : {name}".format(name=self.name)
def __str__(self):
return self.__repr__()
class SauceTomate(Sauce):
def __init__(self):
self.name = "Tomate"
class SauceFlamekuche(Sauce):
def __init__(self):
self.name = "Blanche Flamekuche"
class Ingredient(object):
name = None
def __repr__(self):
return "Ingredient : {name}".format(name=self.name)
def __str__(self):
return self.__repr__()
class Champignons(Ingredient):
def __init__(self):
self.name = "Champignon"
class Lardons(Ingredient):
def __init__(self):
self.name = "Lardons"
class Jambon(Ingredient):
def __init__(self):
self.name = "Jambon blanc"
class Oignons(Ingredient):
def __init__(self):
self.name = "Oignons"
<file_sep># coding: utf-8
from abc import ABCMeta
from abc import abstractmethod
class Command:
__metaclass__ = ABCMeta
@abstractmethod
def execute_on(self):
return NotImplemented
@abstractmethod
def execute_off(self):
return NotImplemented
class LightCommand(Command):
""" Lights command
:param light: reference to a light handler to open close door.
:type light: `Vendor.Light`
"""
def __init__(self, light_lib_handler):
self.light = light_lib_handler
def execute_on(self):
self.light.lights_on()
def execute_off(self):
self.light.lights_off()
def __str__(self):
return "Lights command"
def __repr__(self):
return self.__str__()
class GarageDoorCommand(Command):
""" Garage door command.
:param garage_door: reference to a garage handler to open close door.
:type garage: `Vendor.GarageDoor`
"""
def __init__(self, garage_door_handler):
self.garage_door = garage_door_handler
def execute_on(self):
self.garage_door.open_door()
def execute_off(self):
self.garage_door.close_door()
def __str__(self):
return "Garage door command"
def __repr__(self):
return self.__str__()
class NoCommand(Command):
""" The No command command does nothing.
just avoids to test for null in the remote so it's convenient.
"""
def execute_on(self):
print("** No command: Does nothing. Button not programmed yet.")
def execute_off(self):
print("** No command: Does nothing. Button not programmed yet.")
def __str__(self):
return "No command"
def __repr__(self):
return self.__str__()
<file_sep># coding: utf-8
"""
Strategy pattern: Defines a family of algorithm, encapsulates each one and make
then interchangeable. Strategy let's the algorithm vary independently from the
clients that use it.
"""
from canard import ColVert
from canard import Poule
from vole_comportement import VoleAiles
from quack_comportement import Queuk
def main():
""" Une bascoure, des poules et des canards
"""
c1 = ColVert()
c1.vole()
c1.quack()
poule = Poule()
poule.vole()
poule.quack()
pouleMutante = Poule()
pouleMutante.vole_comportement = VoleAiles()
pouleMutante.vole()
pouleMutante.quack_comportement = Queuk()
pouleMutante.quack()
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
from boisson import CafeNoir
from condiment_decorateur import Chantilly
"""
Decorator pattern: The decorator pattern attaches additionnal responsibilities
to an object dynamically. Decorators provide flexible alternative to subclassing
for extending functionnality.
"""
def main():
""" Implémentation du patron de conception décorateur
Des cafés et des condiments.
"""
my_cafe = CafeNoir()
my_cafe_chantilly = Chantilly(CafeNoir())
print("prix de mon cafe : {prix}".format(prix=str(my_cafe.prix())))
print("prix de mon cafe chantilly : {prix}"
.format(prix=str(my_cafe_chantilly.prix())))
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
""" Nos pizzas disponibles sont les suivantes :
- Pizza végétarienne
- Pizza reine
- Pizza calzone
Nous avons trois restaurants situés :
- NYC, USA
- Paris, FRA
"""
class Pizza(object):
def __init__(self, ingredient_factory):
self.name = None
self.pate = None
self.sauce = None
self.ingredients = []
self.ingredient_factory = ingredient_factory
def preparer(self):
raise NotImplementedError()
def couper(self):
print("Decoupage de la pizza")
def enfourner(self):
print("Fast baking 12 minuts")
def mettre_en_boite(self):
print("Mise en boite, Emballé c'est pesé")
def __repr__(self):
repre = "Pizza " + self.name + " prête ! \n"
repre += "Pate : " + str(self.pate) + "\n"
repre += "sauce : " + str(self.sauce) + "\n"
repre += "Ingredients : " + str(self.ingredients) + "\n"
return repre
def __str__(self):
return self.__repr__()
class Vegetarienne(Pizza):
def __init__(self, igf):
super(Vegetarienne, self).__init__(igf)
self.name = "Vegetarienne"
def preparer(self):
self.pate = self.ingredient_factory.creerPate()
self.sauce = self.ingredient_factory.creerSauce()
self.ingredients = \
self.ingredient_factory.creerIngredientsVegetarienne()
class Reine(Pizza):
def __init__(self, igf):
super(Reine, self).__init__(igf)
self.name = "Reine"
def preparer(self):
self.pate = self.ingredient_factory.creerPate()
self.sauce = self.ingredient_factory.creerSauce()
self.ingredients = self.ingredient_factory.creerIngredientsReine()
class Calzone(Pizza):
def __init__(self, igf):
super(Calzone, self).__init__(igf)
self.name = "Calzone"
def preparer(self):
self.pate = self.ingredient_factory.creerPate()
self.sauce = self.ingredient_factory.creerSauce()
self.ingredients = self.ingredient_factory.creerIngredientsCalzone()
<file_sep># coding: utf-8
from pizza_factory import PizzaFactory
class MagasinPizza:
""" Un magasin de pizza qui prépare des pizzas peu importe le type
Il se fournit en pizza à l'aide d'une factory qui se charge de
l'instanciation de la bonne pizza en fonction de ce que le client demande.
:param fournisseur_pizza: Factory à la quelle est déléguée l'instanciation.
"""
def __init__(self):
self.fournisseur_pizza = PizzaFactory()
super(MagasinPizza, self).__init__()
def commander(self, type_pizza):
pizza = self.fournisseur_pizza.obtenir(type_pizza)
pizza.preparer()
pizza.cuire()
pizza.decouper()
pizza.mettre_en_carton()
return pizza
| 41f39afa64b88f4f2dffcea6d641f11260a39a79 | [
"Python"
] | 25 | Python | SamirBoulil/patrons_de_conceptions | 7b17fa2c4a2208113f8abcb973afb0418fb9cced | c4c9ad5e65a52608ea6e265639dd860ec4ce7c60 |
refs/heads/master | <repo_name>ecosia/mbt<file_sep>/ISSUE_TEMPLATE.md
**Do you want to report a bug?**
If you just want to ask a question, ignore this template and just go ahead.
**Which mbt command are you having troubles with?**
**What's the current behaviour?**
**What's the expected behaviour?**
**Environment**
- mbt version:
- os:
- arch:
<file_sep>/Makefile
default: install
.PHONY: install
install: build_libgit2
go install ./...
.PHONY: build_libgit2
build_libgit2:
./scripts/build_libgit2.sh
.PHONY: build
build: clean
./scripts/build.sh
.PHONY: clean
clean:
rm -rf build
.PHONY: restore
restore:
go get -t
go get github.com/stretchr/testify
.PHONY: test
test: build_libgit2
go test -covermode=count ./e
go test -covermode=count ./lib
go test -covermode=count ./cmd
go test -covermode=count ./trie
go test -covermode=count ./intercept
go test -covermode=count ./graph
go test -covermode=count ./utils
go test -covermode=count .
.PHONY: showcover
showcover:
go tool cover -html=coverage.out
.PHONY: doc
doc:
go run ./scripts/gendoc.go
.PHONY: lint
lint:
gofmt -s -w **/*.go
<file_sep>/intercept/interceptor_test.go
/*
Copyright 2018 MBT Authors.
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 intercept
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
type Target interface {
F1() int
F2(int) int
F3(int, int) int
}
type TestTarget struct {
}
func (t *TestTarget) F1() int {
return 42
}
func (t *TestTarget) F2(i int) int {
return i
}
func (t *TestTarget) F3(i int, j int) int {
return i + j
}
func (t *TestTarget) F4() (int, error) {
return 42, nil
}
func (t *TestTarget) F5() (*TestTarget, error) {
return nil, errors.New("doh")
}
func TestSingleReturn(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
assert.Equal(t, 42, i.Call("F1")[0].(int))
}
func TestSpecificReturn(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
i.Config("F1").Return(24)
assert.Equal(t, 24, i.Call("F1")[0].(int))
}
func TestSpecificDo(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
i.Config("F1").Do(func(args ...interface{}) []interface{} {
return []interface{}{24}
})
assert.Equal(t, 24, i.Call("F1")[0].(int))
}
func TestSingleInput(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
assert.Equal(t, 42, i.Call("F2", 42)[0].(int))
}
func TestMultipleInput(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
assert.Equal(t, 42, i.Call("F3", 21, 21)[0].(int))
}
func TestInterfaceDispatch(t *testing.T) {
var target Target
target = &TestTarget{}
i := NewInterceptor(target)
assert.Equal(t, 42, i.Call("F1")[0].(int))
}
func TestMultipleConfigurationsOfSameMethod(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
i.Config("F1").Return(24)
i.Config("F1").Return(32)
assert.Equal(t, 32, i.Call("F1")[0].(int))
}
func TestNullConfigCalls(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
i.Config("F1")
assert.Equal(t, 42, i.Call("F1")[0].(int))
}
func TestInvalidMethod(t *testing.T) {
defer func() {
if r := recover(); r == nil {
assert.Fail(t, "should panic")
}
}()
target := &TestTarget{}
i := NewInterceptor(target)
i.Config("Foo").Return(42)
i.Call("Foo")
}
func TestErrors(t *testing.T) {
target := &TestTarget{}
i := NewInterceptor(target)
assert.Nil(t, i.Call("F5")[0].(*TestTarget))
}
<file_sep>/lib/res.go
/*
Copyright 2018 MBT Authors.
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 lib
const (
msgInvalidSha = "Invalid commit sha '%v'"
msgCommitShaNotFound = "Failed to find commit sha '%v'"
msgFailedOpenRepo = "Failed to open a git repository in dir - '%v'"
msgFailedTemplatePath = "Failed to read the template in file '%v'"
msgFailedReadFile = "Failed to read file '%v'"
msgFailedLocalPath = "Failed to read the path '%v'"
msgFailedTemplateParse = "Failed to parse the template"
msgFailedBuild = "Failed to build module '%v'"
msgTemplateNotFound = "Specified template %v is not found in git tree %v"
msgFailedSpecParse = "Failed to parse the spec file"
msgFailedBranchLookup = "Failed to find the branch '%v'"
msgFailedTreeWalk = "Failed to walk to the tree object '%v'"
msgFailedTreeLoad = "Failed to read commit tree '%v'"
msgFileDependencyNotFound = "Failed to find the file dependency %v in module %v in %v - File dependencies are case sensitive"
msgFailedRestorationOfOldReference = "Restoration of reference %v failed %v"
msgSuccessfulRestorationOfOldReference = "Successfully restored reference %v"
msgSuccessfulCheckout = "Successfully checked out commit %v"
msgDirtyWorkingDir = "Dirty working dir"
msgDetachedHead = "Head is currently detached"
)
<file_sep>/lib/apply_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/mbtproject/mbt/e"
"github.com/stretchr/testify/assert"
)
type TC struct {
Template string
Expected string
}
func TestApplyBranch(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("template.tmpl", `
{{- range $i, $mod := .Modules}}
{{- $mod.Name }},
{{- end}}
`))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
output := new(bytes.Buffer)
check(t, NewWorld(t, ".tmp/repo").System.ApplyBranch("template.tmpl", "feature", output))
assert.Equal(t, "app-a,app-b,\n", output.String())
}
func TestApplyCommit(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("template.tmpl", `
{{- range $i, $mod := .Modules}}
{{- $mod.Name }},
{{- end}}
`))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
output := new(bytes.Buffer)
check(t, NewWorld(t, ".tmp/repo").System.ApplyCommit(repo.LastCommit.String(), "template.tmpl", output))
assert.Equal(t, "app-a,app-b,\n", output.String())
}
func TestApplyHead(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("template.tmpl", `
{{- range $i, $mod := .Modules}}
{{- $mod.Name }},
{{- end}}
`))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
output := new(bytes.Buffer)
check(t, NewWorld(t, ".tmp/repo").System.ApplyHead("template.tmpl", output))
assert.Equal(t, "app-a,app-b,\n", output.String())
}
func TestApplyLocal(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("template.tmpl", `
{{- range $i, $mod := .Modules}}
{{- $mod.Name }},
{{- end}}
`))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
output := new(bytes.Buffer)
check(t, NewWorld(t, ".tmp/repo").System.ApplyLocal("template.tmpl", output))
assert.Equal(t, "app-a,app-b,\n", output.String())
}
func TestIncorrectTemplatePath(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("template.tmpl", `
{{- range $i, $mod := .Modules}}
{{- $mod.Name }},
{{- end}}
`))
check(t, repo.Commit("first"))
output := new(bytes.Buffer)
err := NewWorld(t, ".tmp/repo").System.ApplyCommit(repo.LastCommit.String(), "foo/template.tmpl", output)
assert.EqualError(t, err, fmt.Sprintf(msgTemplateNotFound, "foo/template.tmpl", repo.LastCommit.String()))
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
assert.Equal(t, "", output.String())
}
func TestBadTemplate(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("template.tmpl", `{{range $i, $mod := .Modules}}`))
check(t, repo.Commit("first"))
output := new(bytes.Buffer)
err := NewWorld(t, ".tmp/repo").System.ApplyCommit(repo.LastCommit.String(), "template.tmpl", output)
assert.EqualError(t, err, msgFailedTemplateParse)
assert.EqualError(t, (err.(*e.E)).InnerError(), "template: template:1: unexpected EOF")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
assert.Equal(t, "", output.String())
}
func TestEnvironmentVariables(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("template.tmpl", "{{.Env.EXTERNAL_VALUE}}"))
check(t, repo.Commit("first"))
os.Setenv("EXTERNAL_VALUE", "FOO")
output := new(bytes.Buffer)
check(t, NewWorld(t, ".tmp/repo").System.ApplyCommit(repo.LastCommit.String(), "template.tmpl", output))
assert.Equal(t, "FOO", output.String())
}
func TestCustomTemplateFuncs(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Properties: map[string]interface{}{
"tags": []string{"a", "b", "c"},
"numbers": []int{1, 2, 3},
"nested": map[string]interface{}{
"tags": []string{"a", "b", "c"},
},
"empty": []int{},
"foo": "bar",
"map": map[string]interface{}{
"a": 1,
"b": "foo",
"c": "bar",
},
},
}))
cases := []TC{
{Template: `{{- if contains (property (module "app-a") "tags") "a"}}yes{{- end}}`, Expected: "yes"},
{Template: `{{- if contains (property (module "app-b") "tags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "dags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "tags") "d"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "numbers") "1"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "numbers") 1}}yes{{- end}}`, Expected: "yes"},
{Template: `{{- if contains (property (module "app-a") "empty") 1}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "nested.tags") "a"}}yes{{- end}}`, Expected: "yes"},
{Template: `{{- if contains (property (module "app-a") "nested.bags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "tags.tags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "nested.") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "nested") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- propertyOr (module "app-a") "foo" "car"}}`, Expected: "bar"},
{Template: `{{- propertyOr (module "app-a") "foo.bar" "car"}}`, Expected: "car"},
{Template: `{{- propertyOr (module "app-b") "foo" "car"}}`, Expected: "car"},
{Template: `{{- join (property (module "app-a") "tags") "%v" "-"}}`, Expected: "a-b-c"},
{Template: `{{- join (property (module "app-b") "tags") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "numbers") "%v" "-"}}`, Expected: "1-2-3"},
{Template: `{{- join (property (module "app-a") "empty") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "bar") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "foo") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "") "%v" "-"}}`, Expected: ""},
{Template: `{{- range $i, $e := (kvplist (property (module "app-a") "map"))}}{{if $i}},{{end}}{{$i}}-{{$e.Key}}-{{$e.Value}}{{end}}`, Expected: "0-a-1,1-b-foo,2-c-bar"},
{Template: `{{- range $i, $e := (kvplist (property (module "app-a") "invalid"))}}{{if $i}},{{end}}{{$i}}-{{$e.Key}}-{{$e.Value}}{{end}}`, Expected: ""},
{Template: `{{- add 1 1}}`, Expected: "2"},
{Template: `{{- sub 2 1}}`, Expected: "1"},
{Template: `{{- mul 2 2}}`, Expected: "4"},
{Template: `{{- div 4 2}}`, Expected: "2"},
{Template: `{{- if ishead (property (module "app-a") "tags") "a"}}yes{{end}}`, Expected: "yes"},
{Template: `{{- if ishead (property (module "app-a") "tags") "b"}}yes{{end}}`, Expected: ""},
{Template: `{{- if ishead (property (module "app-a") "nil") "b"}}yes{{end}}`, Expected: ""},
{Template: `{{- if istail (property (module "app-a") "tags") "c"}}yes{{end}}`, Expected: "yes"},
{Template: `{{- if istail (property (module "app-a") "tags") "b"}}yes{{end}}`, Expected: ""},
{Template: `{{- if istail (property (module "app-a") "nil") "b"}}yes{{end}}`, Expected: ""},
{Template: `{{- head (property (module "app-a") "tags") }}`, Expected: "a"},
{Template: `{{- head (property (module "app-a") "nil") }}`, Expected: ""},
{Template: `{{- head (property (module "app-a") "empty") }}`, Expected: ""},
{Template: `{{- tail (property (module "app-a") "tags") }}`, Expected: "c"},
{Template: `{{- tail (property (module "app-a") "nil") }}`, Expected: ""},
{Template: `{{- tail (property (module "app-a") "empty") }}`, Expected: ""},
}
for _, c := range cases {
check(t, repo.WriteContent("template.tmpl", c.Template))
check(t, repo.Commit("Update"))
output := new(bytes.Buffer)
err := NewWorld(t, ".tmp/repo").System.ApplyCommit(repo.LastCommit.String(), "template.tmpl", output)
check(t, err)
assert.Equal(t, c.Expected, output.String(), "Failed test case %s", c.Template)
}
}
func TestCustomTemplateFuncsForModulesWithoutProperties(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{Name: "app-a"}))
cases := []TC{
{Template: `{{- if contains (property (module "app-a") "tags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-b") "tags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "dags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "tags") "d"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "numbers") "1"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "numbers") 1}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "empty") 1}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "nested.tags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "nested.bags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "tags.tags") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "nested.") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- if contains (property (module "app-a") "nested") "a"}}yes{{- end}}`, Expected: ""},
{Template: `{{- propertyOr (module "app-a") "foo" "car"}}`, Expected: "car"},
{Template: `{{- propertyOr (module "app-a") "foo.bar" "car"}}`, Expected: "car"},
{Template: `{{- propertyOr (module "app-b") "foo" "car"}}`, Expected: "car"},
{Template: `{{- join (property (module "app-a") "tags") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-b") "tags") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "numbers") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "empty") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "bar") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "foo") "%v" "-"}}`, Expected: ""},
{Template: `{{- join (property (module "app-a") "") "%v" "-"}}`, Expected: ""},
}
for _, c := range cases {
check(t, repo.WriteContent("template.tmpl", c.Template))
check(t, repo.Commit("Update"))
output := new(bytes.Buffer)
err := NewWorld(t, ".tmp/repo").System.ApplyCommit(repo.LastCommit.String(), "template.tmpl", output)
check(t, err)
assert.Equal(t, c.Expected, output.String(), "Failed test case %s", c.Template)
}
}
func TestApplyBranchForFailedBranchResolution(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("BranchCommit").Return(nil, errors.New("doh"))
output := new(bytes.Buffer)
assert.EqualError(t, w.System.ApplyBranch("template.tmpl", "master", output), "doh")
}
func TestApplyCommitForFailedCommitResolution(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("GetCommit").Return(nil, errors.New("doh"))
output := new(bytes.Buffer)
assert.EqualError(t, w.System.ApplyCommit("abc", "template.tmpl", output), "doh")
}
func TestApplyHeadForFailedBranchResolution(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("CurrentBranch").Return("", errors.New("doh"))
output := new(bytes.Buffer)
assert.EqualError(t, w.System.ApplyHead("template.tmpl", output), "doh")
}
func TestApplyLocalForWrongTemplatePath(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
repo.InitModule("app-a")
w := NewWorld(t, ".tmp/repo")
absTemplatePath, err := filepath.Abs(".tmp/repo/template.tmpl")
check(t, err)
err = w.System.ApplyLocal("template.tmpl", new(bytes.Buffer))
assert.EqualError(t, err, fmt.Sprintf(msgFailedReadFile, absTemplatePath))
assert.Error(t, (err.(*e.E)).InnerError())
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestApplyLocalForManifestBuildFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("template.tmpl", "{{.Sha}}"))
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByWorkspace").Return(nil, errors.New("doh"))
assert.EqualError(t, w.System.ApplyLocal("template.tmpl", new(bytes.Buffer)), "doh")
}
func TestApplyForManifestBuildFailureForCommit(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
repo.InitModule("app-a")
check(t, repo.WriteContent("template.tmpl", "{{.Sha}}"))
repo.Commit("first")
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByCommit").Return(nil, errors.New("doh"))
assert.EqualError(t, w.System.ApplyBranch("template.tmpl", "master", new(bytes.Buffer)), "doh")
}
func TestResolvePropertyForAnEmptySource(t *testing.T) {
assert.Equal(t, "a", resolveProperty(nil, []string{"a"}, "a"))
}
func TestTheOrderOfModulesList(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-b"))
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("app-c"))
check(t, repo.WriteContent("template.tmpl", `
{{- range $i, $mod := .ModulesList}}
{{- $mod.Name }},
{{- end}}
`))
check(t, repo.Commit("first"))
output := new(bytes.Buffer)
check(t, NewWorld(t, ".tmp/repo").System.ApplyHead("template.tmpl", output))
assert.Equal(t, "app-a,app-b,app-c,\n", output.String())
}
func TestTheOrderOfOrderedModulesList(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{Name: "app-a", Dependencies: []string{"app-b"}}))
check(t, repo.InitModuleWithOptions("app-b", &Spec{Name: "app-b", Dependencies: []string{"app-c"}}))
check(t, repo.InitModule("app-c"))
check(t, repo.WriteContent("template.tmpl", `
{{- range $i, $mod := .OrderedModules}}
{{- $mod.Name }},
{{- end}}
`))
check(t, repo.Commit("first"))
output := new(bytes.Buffer)
check(t, NewWorld(t, ".tmp/repo").System.ApplyHead("template.tmpl", output))
assert.Equal(t, "app-c,app-b,app-a,\n", output.String())
}
<file_sep>/scripts/upload_git.sh
#!/bin/bash
#
# Upload binary artifacts when a new release is made.
#
set -e
# Ensure that the GITHUB_TOKEN secret is included
if [[ -z "$GITHUB_TOKEN" ]]; then
echo "Set the GITHUB_TOKEN env variable."
exit 1
fi
# Ensure that there is a pattern specified.
if [[ -z "$1" ]]; then
echo "Missing file (pattern) to upload."
exit 1
fi
#
# In the past we invoked a build-script to generate the artifacts
# prior to uploading.
#
# Now we no longer do so, they must exist before they are uploaded.
#
# Test for them here.
#
# Have we found any artifacts?
found=
for file in $*; do
if [ -e "$file" ]; then
found=1
fi
done
#
# Abort if missing.
#
if [ -z "${found}" ]; then
echo "*****************************************************************"
echo " "
echo " Artifacts are missing, and this action no longer invokes the "
echo " legacy-build script."
echo " "
echo " Please see the README.md file for github-action-publish-binaries"
echo " which demonstrates how to build AND upload artifacts."
echo " "
echo "*****************************************************************"
exit 1
fi
# Prepare the headers for our curl-command.
AUTH_HEADER="Authorization: token ${GITHUB_TOKEN}"
# Create the correct Upload URL.
RELEASE_ID=$(jq --raw-output '.release.id' "$GITHUB_EVENT_PATH")
# For each matching file..
for file in $*; do
echo "Processing file ${file}"
if [ ! -e "$file" ]; then
echo "***************************"
echo " file not found - skipping."
echo "***************************"
continue
fi
if [ ! -s "$file" ]; then
echo "**************************"
echo " file is empty - skipping."
echo "**************************"
continue
fi
FILENAME=$(basename "${file}")
UPLOAD_URL="https://uploads.github.com/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=${FILENAME}"
echo "Upload URL is ${UPLOAD_URL}"
# Generate a temporary file.
tmp=$(mktemp)
# Upload the artifact - capturing HTTP response-code in our output file.
response=$(curl \
-sSL \
-XPOST \
-H "${AUTH_HEADER}" \
--upload-file "${file}" \
--header "Content-Type:application/octet-stream" \
--write-out "%{http_code}" \
--output $tmp \
"${UPLOAD_URL}")
# If the curl-command returned a non-zero response we must abort
if [ "$?" -ne 0 ]; then
echo "**********************************"
echo " curl command did not return zero."
echo " Aborting"
echo "**********************************"
cat $tmp
rm $tmp
exit 1
fi
# If upload is not successful, we must abort
if [ $response -ge 400 ]; then
echo "***************************"
echo " upload was not successful."
echo " Aborting"
echo " HTTP status is $response"
echo "**********************************"
cat $tmp
rm $tmp
exit 1
fi
# Show pretty output, since we already have jq
cat $tmp | jq .
rm $tmp
done<file_sep>/docs/mbt_run-in_diff.md
## mbt run-in diff
### Synopsis
```
mbt run-in diff --from <sha> --to <sha> [flags]
```
### Options
```
--from string From commit
-h, --help help for diff
--to string To commit
```
### Options inherited from parent commands
```
-m, --command string Command to execute
--debug Enable debug output
--fail-fast Fail fast on command failure
--in string Path to repo
```
### SEE ALSO
* [mbt run-in](mbt_run-in.md) - Run user defined command
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/docs/mbt_build.md
## mbt build
Run build command
### Synopsis
`mbt build branch [name] [--content] [--name <name>] [--fuzzy]`<br>
Build modules in a branch. Assume master if branch name is not specified.
Build just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt build commit <commit> [--content] [--name <name>] [--fuzzy]`<br>
Build modules in a commit. Full commit sha is required.
Build just the modules modified in the commit when `--content` flag is used.
Build just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt build diff --from <commit> --to <commit>`<br>
Build modules changed between `from` and `to` commits.
In this mode, mbt works out the merge base between `from` and `to` and
evaluates the modules changed between the merge base and `to`.
`mbt build head [--content] [--name <name>] [--fuzzy]`<br>
Build modules in current head.
Build just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt build pr --src <name> --dst <name>`<br>
Build modules changed between `--src` and `--dst` branches.
In this mode, mbt works out the merge base between `--src` and `--dst` and
evaluates the modules changed between the merge base and `--src`.
`mbt build local [--all] [--content] [--name <name>] [--fuzzy]`<br>
Build modules modified in current workspace. All modules in the workspace are
built if `--all` option is specified.
Build just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
### Build Environment
When executing build, following environment variables are initialised and can be
used by the command being executed.
- `MBT_MODULE_NAME` Name of the module
- `MBT_MODULE_PATH` Relative path to the module directory
- `MBT_MODULE_VERSION` Module version
- `MBT_BUILD_COMMIT` Git commit SHA of the commit being built
- `MBT_REPO_PATH` Absolute path to the repository directory
In addition to the variables listed above, module properties are also populated
in the form of `MBT_MODULE_PROPERTY_XXX` where `XXX` denotes the key.
### Options
```
-h, --help help for build
```
### Options inherited from parent commands
```
--debug Enable debug output
--in string Path to repo
```
### SEE ALSO
* [mbt](mbt.md) - mbt - The most flexible build orchestration tool for monorepo
* [mbt build branch](mbt_build_branch.md) -
* [mbt build commit](mbt_build_commit.md) -
* [mbt build diff](mbt_build_diff.md) -
* [mbt build head](mbt_build_head.md) -
* [mbt build local](mbt_build_local.md) -
* [mbt build pr](mbt_build_pr.md) -
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/lib/manifest_builder.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"path/filepath"
)
// NewManifestBuilder creates a new ManifestBuilder
func NewManifestBuilder(repo Repo, reducer Reducer, discover Discover, log Log) ManifestBuilder {
return &stdManifestBuilder{Repo: repo, Discover: discover, Log: log, Reducer: reducer}
}
type stdManifestBuilder struct {
Log Log
Repo Repo
Discover Discover
Reducer Reducer
}
type manifestBuilder func() (*Manifest, error)
func peerDependencies(reduced, allModules []*Module) []*Module {
peerDeps := map[*Module]bool{}
for _, reducedModule := range reduced {
if len(reducedModule.metadata.spec.PeerDependencies) == 0 {
continue
}
for _, peer := range reducedModule.metadata.spec.PeerDependencies {
for _, module := range allModules {
if peer == module.Name() {
peerDeps[module] = true
}
}
}
}
peers := []*Module{}
for dep := range peerDeps {
peers = append(peers, dep)
}
return peers
}
func (b *stdManifestBuilder) ByDiff(from, to Commit) (*Manifest, error) {
return b.runManifestBuilder(func() (*Manifest, error) {
mods, err := b.Discover.ModulesInCommit(to)
if err != nil {
return nil, err
}
deltas, err := b.Repo.DiffMergeBase(from, to)
if err != nil {
return nil, err
}
reduced, err := b.Reducer.Reduce(mods, deltas)
if err != nil {
return nil, err
}
reduced, err = reduced.expandRequiredByDependencies()
if err != nil {
return nil, err
}
peerDeps := peerDependencies(reduced, mods)
for _, dep := range peerDeps {
exists := false
for _, existing := range reduced {
if dep == existing {
exists = true
break
}
}
if exists {
continue
}
reduced = append(reduced, dep)
}
return b.buildManifest(reduced, to.ID())
})
}
func (b *stdManifestBuilder) ByPr(src, dst string) (*Manifest, error) {
return b.runManifestBuilder(func() (*Manifest, error) {
from, err := b.Repo.BranchCommit(dst)
if err != nil {
return nil, err
}
to, err := b.Repo.BranchCommit(src)
if err != nil {
return nil, err
}
return b.ByDiff(from, to)
})
}
func (b *stdManifestBuilder) ByCommit(sha Commit) (*Manifest, error) {
return b.runManifestBuilder(func() (*Manifest, error) {
mods, err := b.Discover.ModulesInCommit(sha)
if err != nil {
return nil, err
}
return b.buildManifest(mods, sha.ID())
})
}
func (b *stdManifestBuilder) ByCommitContent(sha Commit) (*Manifest, error) {
return b.runManifestBuilder(func() (*Manifest, error) {
mods, err := b.Discover.ModulesInCommit(sha)
if err != nil {
return nil, err
}
diff, err := b.Repo.Changes(sha)
if err != nil {
return nil, err
}
if len(diff) > 0 {
mods, err = b.Reducer.Reduce(mods, diff)
if err != nil {
return nil, err
}
mods, err = mods.expandRequiredByDependencies()
if err != nil {
return nil, err
}
}
return b.buildManifest(mods, sha.ID())
})
}
func (b *stdManifestBuilder) ByBranch(name string) (*Manifest, error) {
return b.runManifestBuilder(func() (*Manifest, error) {
c, err := b.Repo.BranchCommit(name)
if err != nil {
return nil, err
}
return b.ByCommit(c)
})
}
func (b *stdManifestBuilder) ByCurrentBranch() (*Manifest, error) {
return b.runManifestBuilder(func() (*Manifest, error) {
n, err := b.Repo.CurrentBranch()
if err != nil {
return nil, err
}
return b.ByBranch(n)
})
}
func (b *stdManifestBuilder) ByWorkspace() (*Manifest, error) {
mods, err := b.Discover.ModulesInWorkspace()
if err != nil {
return nil, err
}
return b.buildManifest(mods, "local")
}
func (b *stdManifestBuilder) ByWorkspaceChanges() (*Manifest, error) {
mods, err := b.Discover.ModulesInWorkspace()
if err != nil {
return nil, err
}
deltas, err := b.Repo.DiffWorkspace()
if err != nil {
return nil, err
}
mods, err = b.Reducer.Reduce(mods, deltas)
if err != nil {
return nil, err
}
mods, err = mods.expandRequiredByDependencies()
if err != nil {
return nil, err
}
return b.buildManifest(mods, "local")
}
func (b *stdManifestBuilder) runManifestBuilder(builder manifestBuilder) (*Manifest, error) {
empty, err := b.Repo.IsEmpty()
if err != nil {
return nil, err
}
if empty {
return b.buildManifest(Modules{}, "")
}
return builder()
}
func (b *stdManifestBuilder) buildManifest(modules Modules, sha string) (*Manifest, error) {
repoPath := b.Repo.Path()
if !filepath.IsAbs(repoPath) {
var err error
repoPath, err = filepath.Abs(repoPath)
if err != nil {
return nil, err
}
}
return &Manifest{Dir: repoPath, Modules: modules, Sha: sha}, nil
}
<file_sep>/docs/mbt_build_pr.md
## mbt build pr
### Synopsis
```
mbt build pr --src <branch> --dst <branch> [flags]
```
### Options
```
--dst string Destination branch
-h, --help help for pr
--src string Source branch
```
### Options inherited from parent commands
```
--debug Enable debug output
--in string Path to repo
```
### SEE ALSO
* [mbt build](mbt_build.md) - Run build command
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/lib/benchmarks_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"testing"
)
func benchmarkReduceToDiff(modulesCount, deltaCount int, b *testing.B) {
clean()
defer clean()
repo := NewTestRepoForBench(b, ".tmp/repo")
for i := 0; i < modulesCount; i++ {
err := repo.InitModule(fmt.Sprintf("app-%v", i))
if err != nil {
b.Fatalf("%v", err)
}
}
err := repo.Commit("first")
if err != nil {
b.Fatalf("%v", err)
}
c1 := repo.LastCommit
for i := 0; i < deltaCount; i++ {
err = repo.WriteContent(fmt.Sprintf("content/file-%v", i), "sample content")
if err != nil {
b.Fatalf("%v", err)
}
}
repo.Commit("second")
c2 := repo.LastCommit
world := NewBenchmarkWorld(b, ".tmp/repo")
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err = world.System.ManifestByDiff(c1.String(), c2.String())
if err != nil {
b.Fatalf("%v", err)
}
}
b.StopTimer()
}
func BenchmarkReduceToDiff10(b *testing.B) {
benchmarkReduceToDiff(10, 10, b)
}
func BenchmarkReduceToDiff100(b *testing.B) {
benchmarkReduceToDiff(100, 100, b)
}
func BenchmarkReduceToDiff1000(b *testing.B) {
benchmarkReduceToDiff(1000, 1000, b)
}
func BenchmarkReduceToDiff10000(b *testing.B) {
benchmarkReduceToDiff(10000, 10000, b)
}
<file_sep>/lib/workspace_manager.go
/*
Copyright 2018 MBT Authors.
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 lib
import "github.com/mbtproject/mbt/e"
type stdWorkspaceManager struct {
Log Log
Repo Repo
}
func (w *stdWorkspaceManager) CheckoutAndRun(commit string, fn func() (interface{}, error)) (interface{}, error) {
err := w.Repo.EnsureSafeWorkspace()
if err != nil {
return nil, err
}
c, err := w.Repo.GetCommit(commit)
if err != nil {
return nil, err
}
oldReference, err := w.Repo.Checkout(c)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
w.Log.Infof(msgSuccessfulCheckout, commit)
defer w.restore(oldReference)
return fn()
}
func (w *stdWorkspaceManager) restore(oldReference Reference) {
err := w.Repo.CheckoutReference(oldReference)
if err != nil {
w.Log.Errorf(msgFailedRestorationOfOldReference, oldReference.Name(), err)
} else {
w.Log.Infof(msgSuccessfulRestorationOfOldReference, oldReference.Name())
}
}
// NewWorkspaceManager creates a new workspace manager.
func NewWorkspaceManager(log Log, repo Repo) WorkspaceManager {
return &stdWorkspaceManager{Log: log, Repo: repo}
}
<file_sep>/lib/discover.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"crypto/sha1"
"encoding/hex"
"io"
"io/ioutil"
"path/filepath"
"strings"
yaml "github.com/go-yaml/yaml"
"github.com/mbtproject/mbt/e"
"github.com/mbtproject/mbt/graph"
)
// moduleMetadata represents the information about modules
// found during discovery phase.
type moduleMetadata struct {
dir string
hash string
spec *Spec
dependentFileHashes map[string]string
}
// moduleMetadataSet is an array of ModuleMetadata extracted from the repository.
type moduleMetadataSet []*moduleMetadata
type stdDiscover struct {
Repo Repo
Log Log
}
const configFileName = ".mbt.yml"
// NewDiscover creates an instance of standard discover implementation.
func NewDiscover(repo Repo, l Log) Discover {
return &stdDiscover{Repo: repo, Log: l}
}
func (d *stdDiscover) ModulesInCommit(commit Commit) (Modules, error) {
repo := d.Repo
metadataSet := moduleMetadataSet{}
err := repo.WalkBlobs(commit, func(b Blob) error {
if b.Name() == configFileName {
var (
hash string
err error
)
p := strings.TrimRight(b.Path(), "/")
if p != "" {
// We are not on the root, take the git sha for parent tree object.
hash, err = repo.EntryID(commit, p)
if err != nil {
return err
}
} else {
// We are on the root, take the commit sha.
hash = commit.ID()
}
contents, err := repo.BlobContents(b)
if err != nil {
return err
}
spec, err := newSpec(contents)
if err != nil {
return e.Wrapf(ErrClassUser, err, "error while parsing the spec at %v", b)
}
// Discover the hashes for file dependencies of this module
dependentFileHashes := make(map[string]string)
for _, f := range spec.FileDependencies {
fh, err := repo.EntryID(commit, f)
if err != nil {
return e.Wrapf(ErrClassUser, err, msgFileDependencyNotFound, f, spec.Name, p)
}
dependentFileHashes[f] = fh
}
metadataSet = append(metadataSet, newModuleMetadata(p, hash, spec, dependentFileHashes))
}
return nil
})
if err != nil {
return nil, err
}
return toModules(metadataSet)
}
func (d *stdDiscover) ModulesInWorkspace() (Modules, error) {
metadataSet := moduleMetadataSet{}
absRepoPath, err := filepath.Abs(d.Repo.Path())
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
configFiles, err := d.Repo.FindAllFilesInWorkspace([]string{configFileName, "/**/" + configFileName})
if err != nil {
return nil, err
}
for _, entry := range configFiles {
if filepath.Base(entry) != configFileName {
// Fast path directories that matched path spec
// e.g. .mbt.yml/abc/foo
continue
}
path := filepath.Join(absRepoPath, entry)
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, e.Wrapf(ErrClassInternal, err, "error whilst reading file contents at path %s", path)
}
spec, err := newSpec(contents)
if err != nil {
return nil, e.Wrapf(ErrClassUser, err, "error whilst parsing spec at %s", path)
}
// Sanitize the module path
dir := filepath.ToSlash(filepath.Dir(entry))
if dir == "." {
dir = ""
} else {
dir = strings.TrimRight(dir, "/")
}
hash := "local"
metadataSet = append(metadataSet, newModuleMetadata(dir, hash, spec, nil))
}
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return toModules(metadataSet)
}
func newModuleMetadata(dir string, hash string, spec *Spec, dependentFileHashes map[string]string) *moduleMetadata {
/*
Normalise the module dir. We always use paths
relative to the module root. Root is represented
as an empty string.
*/
if dir == "." {
dir = ""
}
if dependentFileHashes == nil {
dependentFileHashes = make(map[string]string)
}
return &moduleMetadata{
dir: dir,
hash: hash,
spec: spec,
dependentFileHashes: dependentFileHashes,
}
}
func newSpec(content []byte) (*Spec, error) {
a := &Spec{
Properties: make(map[string]interface{}),
Build: make(map[string]*Cmd),
}
err := yaml.Unmarshal(content, a)
if err != nil {
return nil, err
}
a.Properties, err = transformProps(a.Properties)
if err != nil {
return nil, err
}
return a, nil
}
// toModules transforms an moduleMetadataSet to Modules structure
// while establishing the dependency links.
func toModules(a moduleMetadataSet) (Modules, error) {
// Step 1
// Index moduleMetadata by the module name and use it to
// create a ModuleMetadataProvider that we can use with TopSort fn.
m := make(map[string]*moduleMetadata)
nodes := make([]interface{}, 0, len(a))
for _, meta := range a {
if conflict, ok := m[meta.spec.Name]; ok {
return nil, e.NewErrorf(ErrClassUser, "Module name '%s' in directory '%s' conflicts with the module in '%s' directory", meta.spec.Name, meta.dir, conflict.dir)
}
m[meta.spec.Name] = meta
nodes = append(nodes, meta)
}
provider := newModuleMetadataProvider(m)
// Step 2
// Topological sort
sortedNodes, err := graph.TopSort(provider, nodes...)
if err != nil {
if cycleErr, ok := err.(*graph.CycleError); ok {
var pathStr string
for i, v := range cycleErr.Path {
if i > 0 {
pathStr = pathStr + " -> "
}
pathStr = pathStr + v.(*moduleMetadata).spec.Name
}
return nil, e.NewErrorf(ErrClassUser, "Could not produce the module graph due to a cyclic dependency in path: %s", pathStr)
}
return nil, e.Wrap(ErrClassInternal, err)
}
// Step 3
// Now that we have the topologically sorted moduleMetadataNodes
// create Module instances with dependency links.
mModules := make(map[string]*Module)
modules := make(Modules, len(sortedNodes))
i := 0
for _, n := range sortedNodes {
metadata := n.(*moduleMetadata)
spec := metadata.spec
deps := Modules{}
for _, d := range spec.Dependencies {
if depMod, ok := mModules[d]; ok {
deps = append(deps, depMod)
} else {
panic("topsort is inconsistent")
}
}
mod := newModule(metadata, deps)
modules[i] = mod
i++
mModules[mod.Name()] = mod
}
return calculateVersion(modules), nil
}
// calculateVersion takes the topologically sorted Modules and
// initialises their version field.
func calculateVersion(topSorted Modules) Modules {
for _, a := range topSorted {
if a.Hash() == "local" {
a.version = "local"
} else {
if len(a.Requires()) == 0 && len(a.FileDependencies()) == 0 {
// Fast path for modules without any dependencies
a.version = a.Hash()
} else {
// This module has dependencies.
// Version is created by combining the hashes of the module
// content, its file dependencies and the hashes of the dependencies.
h := sha1.New()
io.WriteString(h, a.Hash())
// Consider the version of all dependencies to compute the version of
// current module.
// It is unnecessary to traverse the entire dependency graph
// here because we are processing the list of modules in topological
// order. Therefore, version of a dependency would already contain
// the version of its dependencies.
for _, r := range a.Requires() {
io.WriteString(h, r.Version())
}
for _, f := range a.FileDependencies() {
io.WriteString(h, a.metadata.dependentFileHashes[f])
}
a.version = hex.EncodeToString(h.Sum(nil))
}
}
}
return topSorted
}
// moduleMetadataNodeProvider is an auxiliary type used to build the dependency
// graph. Acts as an implementation of graph.NodeProvider interface (We use graph
// library for topological sort).
type moduleMetadataNodeProvider struct {
set map[string]*moduleMetadata
}
func newModuleMetadataProvider(set map[string]*moduleMetadata) *moduleMetadataNodeProvider {
return &moduleMetadataNodeProvider{set}
}
func (n *moduleMetadataNodeProvider) ID(vertex interface{}) interface{} {
return vertex.(*moduleMetadata).spec.Name
}
func (n *moduleMetadataNodeProvider) ChildCount(vertex interface{}) int {
return len(vertex.(*moduleMetadata).spec.Dependencies)
}
func (n *moduleMetadataNodeProvider) Child(vertex interface{}, index int) (interface{}, error) {
spec := vertex.(*moduleMetadata).spec
d := spec.Dependencies[index]
if s, ok := n.set[d]; ok {
return s, nil
}
return nil, e.NewErrorf(ErrClassUser, "dependency not found %s -> %s", spec.Name, d)
}
<file_sep>/docs/mbt_describe.md
## mbt describe
Describe repository manifest
### Synopsis
`mbt describe branch [name] [--content] [--name <name>] [--fuzzy] [--graph] [--json]`<br>
Describe modules in a branch. Assume master if branch name is not specified.
Describe just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt describe commit <commit> [--content] [--name <name>] [--fuzzy] [--graph] [--json]`<br>
Describe modules in a commit. Full commit sha is required.
Describe just the modules modified in the commit when `--content` flag is used.
Describe just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt describe diff --from <commit> --to <commit> [--graph] [--json]`<br>
Describe modules changed between `from` and `to` commits.
In this mode, mbt works out the merge base between `from` and `to` and
evaluates the modules changed between the merge base and `to`.
`mbt describe head [--content] [--name <name>] [--fuzzy] [--graph] [--json]`<br>
Describe modules in current head.
Describe just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt describe pr --src <name> --dst <name> [--graph] [--json]`<br>
Describe modules changed between `--src` and `--dst` branches.
In this mode, mbt works out the merge base between `--src` and `--dst` and
evaluates the modules changed between the merge base and `--src`.
`mbt describe local [--all] [--content] [--name <name>] [--fuzzy] [--graph] [--json]`<br>
Describe modules modified in current workspace. All modules in the workspace are
described if `--all` option is specified.
Describe just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
### Output Formats
Use `--graph` option to output the manifest in graphviz dot format. This can
be useful to visualise build dependencies.
Use `--json` option to output the manifest in json format.
### Options
```
--graph Format output as dot graph
-h, --help help for describe
--json Format output as json
```
### Options inherited from parent commands
```
--debug Enable debug output
--in string Path to repo
```
### SEE ALSO
* [mbt](mbt.md) - mbt - The most flexible build orchestration tool for monorepo
* [mbt describe branch](mbt_describe_branch.md) -
* [mbt describe commit](mbt_describe_commit.md) -
* [mbt describe diff](mbt_describe_diff.md) -
* [mbt describe head](mbt_describe_head.md) -
* [mbt describe intersection](mbt_describe_intersection.md) -
* [mbt describe local](mbt_describe_local.md) -
* [mbt describe pr](mbt_describe_pr.md) -
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/lib/transform_props_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"testing"
"github.com/mbtproject/mbt/e"
"github.com/stretchr/testify/assert"
)
func TestFlatMap(t *testing.T) {
i := make(map[string]interface{})
i["a"] = 10
i["b"] = "foo"
o, err := transformProps(i)
check(t, err)
assert.Equal(t, 10, o["a"])
assert.Equal(t, "foo", o["b"])
}
func TestNestedMap(t *testing.T) {
i := make(map[string]interface{})
n := make(map[interface{}]interface{})
n["a"] = "foo"
i["a"] = n
o, err := transformProps(i)
check(t, err)
assert.Equal(t, "foo", o["a"].(map[string]interface{})["a"])
}
func TestNonStringKey(t *testing.T) {
i := make(map[string]interface{})
n := make(map[interface{}]interface{})
n[42] = "foo"
i["a"] = n
o, err := transformProps(i)
assert.EqualError(t, err, "Key is not a string 42")
assert.Equal(t, ErrClassInternal, (err.(*e.E)).Class())
assert.Nil(t, o)
}
<file_sep>/scripts/build_libgit2.sh
#!/bin/sh
set -e
DIR=$(pwd)
LIBGIT2_PATH=$DIR/libgit2
mkdir -p $LIBGIT2_PATH
cd $LIBGIT2_PATH &&
mkdir -p install/lib &&
mkdir -p build &&
cd build &&
cmake -DTHREADSAFE=ON \
-DBUILD_CLAR=OFF \
-DBUILD_SHARED_LIBS=OFF \
-DCMAKE_C_FLAGS=-fPIC \
-DCMAKE_BUILD_TYPE="RelWithDebInfo" \
-DCMAKE_INSTALL_PREFIX=../install \
-DUSE_SSH=OFF \
-DCURL=OFF \
.. &&
cmake --build . &&
make -j2 install &&
cd $DIR
<file_sep>/graph/top_sort.go
/*
Copyright 2018 MBT Authors.
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 graph
import (
"errors"
)
type tState int
const (
stateNew = iota
stateOpen
stateClosed
)
// NodeProvider is the interface between the vertices stored in the graph
// and various graph functions.
// This interface enables the consumers of graph functions to adopt their
// data structures for graph related operations without converting to
// a strict format beforehand.
type NodeProvider interface {
// ID returns an identifier that can be used to uniquely identify
// the vertex. This identifier is used internally to determine if
// two nodes are same.
ID(vertex interface{}) interface{}
// ChildCount returns the number of children this vertex has.
ChildCount(vertex interface{}) int
// Child returns the child vertex at index in vertex.
Child(vertex interface{}, index int) (interface{}, error)
}
// CycleError occurs when a cyclic reference is detected in a directed
// acyclic graph.
type CycleError struct {
Path []interface{}
}
func (e *CycleError) Error() string {
return "not a dag"
}
// TopSort performs a topological sort of the provided graph.
// Returns an array containing the sorted graph or an
// error if the provided graph is not a directed acyclic graph (DAG).
func TopSort(nodeProvider NodeProvider, graph ...interface{}) ([]interface{}, error) {
if nodeProvider == nil {
return nil, errors.New("nodeProvider should be a valid reference")
}
traversalState := make(map[interface{}]tState)
results := make([]interface{}, 0)
for _, node := range graph {
err := dfsVisit(nodeProvider, node, traversalState, &results, make([]interface{}, 0))
if err != nil {
return nil, err
}
}
return results, nil
}
func dfsVisit(nodeProvider NodeProvider, node interface{}, traversalState map[interface{}]tState, sorted *[]interface{}, path []interface{}) error {
id := nodeProvider.ID(node)
if traversalState[id] == stateOpen {
return &CycleError{Path: append(path, node)}
}
if traversalState[id] == stateClosed {
return nil
}
traversalState[id] = stateOpen
path = append(path, node)
for i := 0; i < nodeProvider.ChildCount(node); i++ {
c, err := nodeProvider.Child(node, i)
if err != nil {
return err
}
err = dfsVisit(nodeProvider, c, traversalState, sorted, path)
if err != nil {
return err
}
}
traversalState[id] = stateClosed
*sorted = append(*sorted, node)
return nil
}
<file_sep>/go.mod
module github.com/mbtproject/mbt
go 1.15
require (
github.com/cpuguy83/go-md2man v1.0.7
github.com/davecgh/go-spew v1.1.1
github.com/go-yaml/yaml v2.1.0+incompatible
github.com/inconshreveable/mousetrap v1.0.0
github.com/libgit2/git2go/v28 v28.8.6
github.com/pmezard/go-difflib v1.0.0
github.com/russross/blackfriday v0.0.0-20170728175326-4048872b16cc
github.com/sirupsen/logrus v1.7.0
github.com/spf13/cobra v1.1.1
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.3.0
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
golang.org/x/sys v0.0.0-20210112091331-59c308dcf3cc
gopkg.in/yaml.v2 v2.2.8
)
<file_sep>/cmd/apply.go
/*
Copyright 2018 MBT Authors.
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 cmd
import (
"errors"
"io"
"os"
"github.com/spf13/cobra"
)
var (
out string
)
func init() {
applyCmd.PersistentFlags().StringVar(&to, "to", "", "Template to apply")
applyCmd.PersistentFlags().StringVar(&out, "out", "", "Output path")
applyCmd.AddCommand(applyBranchCmd)
applyCmd.AddCommand(applyCommitCmd)
applyCmd.AddCommand(applyHeadCmd)
applyCmd.AddCommand(applyLocal)
RootCmd.AddCommand(applyCmd)
}
var applyCmd = &cobra.Command{
Use: "apply",
Short: docText("apply-summary"),
Long: docText("apply"),
}
var applyBranchCmd = &cobra.Command{
Use: "branch <branch>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
branch := "master"
if len(args) > 0 {
branch = args[0]
}
return applyCore(func(to string, output io.Writer) error {
return system.ApplyBranch(to, branch, output)
})
}),
}
var applyCommitCmd = &cobra.Command{
Use: "commit <sha>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("requires the commit sha")
}
commit := args[0]
return applyCore(func(to string, output io.Writer) error {
return system.ApplyCommit(commit, to, output)
})
}),
}
var applyHeadCmd = &cobra.Command{
Use: "head",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
return applyCore(func(to string, output io.Writer) error {
return system.ApplyHead(to, output)
})
}),
}
var applyLocal = &cobra.Command{
Use: "local",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
return applyCore(func(to string, output io.Writer) error {
return system.ApplyLocal(to, output)
})
}),
}
type applyFunc func(to string, output io.Writer) error
func applyCore(f applyFunc) error {
if to == "" {
return errors.New("requires the path to template, specify --to argument")
}
output, err := getOutput(out)
if err != nil {
return err
}
return f(to, output)
}
func getOutput(out string) (io.Writer, error) {
if out == "" {
return os.Stdout, nil
}
return os.Create(out)
}
<file_sep>/utils/strings_test.go
/*
Copyright 2018 MBT Authors.
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 utils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsSubsequence(t *testing.T) {
assert.True(t, IsSubsequence("barry", "barry", false))
assert.True(t, IsSubsequence("barry", "arr", false))
assert.True(t, IsSubsequence("barry", "ary", false))
assert.True(t, IsSubsequence("barray allen", "aal", false))
assert.True(t, IsSubsequence("abc", "", false))
assert.True(t, IsSubsequence("", "", false))
assert.False(t, IsSubsequence("barray", "yr", false))
assert.False(t, IsSubsequence("barry", "barray a", false))
assert.False(t, IsSubsequence("barry", "bR", false))
assert.False(t, IsSubsequence("", "abc", false))
assert.True(t, IsSubsequence("barry", "barry", true))
assert.True(t, IsSubsequence("barry", "arr", true))
assert.True(t, IsSubsequence("barry", "ary", true))
assert.True(t, IsSubsequence("barray allen", "aal", true))
assert.True(t, IsSubsequence("abc", "", true))
assert.True(t, IsSubsequence("", "", true))
assert.True(t, IsSubsequence("barry", "bR", true))
assert.False(t, IsSubsequence("barray", "yr", true))
assert.False(t, IsSubsequence("barry", "barray a", true))
assert.False(t, IsSubsequence("", "abc", true))
}
<file_sep>/lib/system.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"io"
"os"
)
// This file defines the interfaces and types that make up MBT system.
// Other source files basically contain the implementations of one
// or more of these components.
/** GIT Integration **/
// Blob stored in git.
type Blob interface {
// ID of the blob.
ID() string
// Name of the blob.
Name() string
// Path (relative) to the blob.
Path() string
//String returns a printable id.
String() string
}
// DiffDelta is a single delta in a git diff.
type DiffDelta struct {
// NewFile path of the delta
NewFile string
// OldFile path of the delta
OldFile string
}
// BlobWalkCallback used for discovering blobs in a commit tree.
type BlobWalkCallback func(Blob) error
// Commit in the repo.
// All commit based APIs in Repo interface accepts this interface.
// It gives the implementations the ability to optimise the access to commits.
// For example, a libgit2 based Repo implementation we use by default caches the access to commit tree.
type Commit interface {
ID() string
String() string
}
// Reference to a tree in the repository.
// For example, if you consider a git repository
// this could be pointing to a branch, tag or commit.
type Reference interface {
Name() string
SymbolicName() string
}
// Repo defines the set of interactions with the git repository.
type Repo interface {
// GetCommit returns the commit object for the specified SHA.
GetCommit(sha string) (Commit, error)
// Path of the repository.
Path() string
// Diff gets the diff between two commits.
Diff(a, b Commit) ([]*DiffDelta, error)
// DiffMergeBase gets the diff between the merge base of from and to and, to.
// In other words, diff contains the deltas of changes occurred in 'to' commit tree
// since it diverged from 'from' commit tree.
DiffMergeBase(from, to Commit) ([]*DiffDelta, error)
// DiffWorkspace gets the changes in current workspace.
// This should include untracked changes.
DiffWorkspace() ([]*DiffDelta, error)
// Changes returns a an array of DiffDelta objects representing the changes
// in the specified commit.
// Return an empty array if the specified commit is the first commit
// in the repo.
Changes(c Commit) ([]*DiffDelta, error)
// WalkBlobs invokes the callback for each blob reachable from the commit tree.
WalkBlobs(a Commit, callback BlobWalkCallback) error
// BlobContents of specified blob.
BlobContents(blob Blob) ([]byte, error)
// BlobContentsByPath gets the blob contents from a specific git tree.
BlobContentsFromTree(commit Commit, path string) ([]byte, error)
// EntryID of a git object in path.
// ID is resolved from the commit tree of the specified commit.
EntryID(commit Commit, path string) (string, error)
// BranchCommit returns the last commit for the specified branch.
BranchCommit(name string) (Commit, error)
// CurrentBranch returns the name of current branch.
CurrentBranch() (string, error)
// CurrentBranchCommit returns the last commit for the current branch.
CurrentBranchCommit() (Commit, error)
// IsEmpty informs if the current repository is empty or not.
IsEmpty() (bool, error)
// FindAllFilesInWorkspace returns all files in repository matching given pathSpec, including untracked files.
FindAllFilesInWorkspace(pathSpec []string) ([]string, error)
// EnsureSafeWorkspace returns an error workspace is in a safe state
// for operations requiring a checkout.
// For example, in git repositories we consider uncommitted changes or
// a detached head is an unsafe state.
EnsureSafeWorkspace() error
// Checkout specified commit into workspace.
// Also returns a reference to the previous tree pointed by current workspace.
Checkout(commit Commit) (Reference, error)
// CheckoutReference checks out the specified reference into workspace.
CheckoutReference(Reference) error
// MergeBase returns the merge base of two commits.
MergeBase(a, b Commit) (Commit, error)
}
/** Module Discovery **/
// Cmd represents the structure of a command appears in .mbt.yml.
type Cmd struct {
Cmd string
Args []string `yaml:",flow"`
}
// UserCmd represents the structure of a user defined command in .mbt.yml
type UserCmd struct {
Cmd string
Args []string `yaml:",flow"`
OS []string `yaml:"os"`
}
// Spec represents the structure of .mbt.yml contents.
type Spec struct {
Name string `yaml:"name"`
Build map[string]*Cmd `yaml:"build"`
Commands map[string]*UserCmd `yaml:"commands"`
Properties map[string]interface{} `yaml:"properties"`
Dependencies []string `yaml:"dependencies"`
FileDependencies []string `yaml:"fileDependencies"`
PeerDependencies []string `yaml:"peerDependencies"`
}
// Module represents a single module in the repository.
type Module struct {
metadata *moduleMetadata
version string
requires Modules
requiredBy Modules
}
// Modules is an array of Module.
type Modules []*Module
// Discover module metadata for various conditions
type Discover interface {
// ModulesInCommit walks the git tree at a specific commit looking for
// directories with .mbt.yml file. Returns discovered Modules.
ModulesInCommit(commit Commit) (Modules, error)
// ModulesInWorkspace walks current workspace looking for
// directories with .mbt.yml file. Returns discovered Modules.
ModulesInWorkspace() (Modules, error)
}
// Reducer reduces a given modules set to impacted set from a diff delta
type Reducer interface {
Reduce(modules Modules, deltas []*DiffDelta) (Modules, error)
}
// Manifest represents a collection modules in the repository.
type Manifest struct {
Dir string
Sha string
Modules Modules
}
// ManifestBuilder builds Manifest for various conditions
type ManifestBuilder interface {
// ByDiff creates the manifest for diff between two commits
ByDiff(from, to Commit) (*Manifest, error)
// ByPr creates the manifest for diff between two branches
ByPr(src, dst string) (*Manifest, error)
// ByCommit creates the manifest for the specified commit
ByCommit(sha Commit) (*Manifest, error)
// ByCommitContent creates the manifest for the content of the
// specified commit.
ByCommitContent(sha Commit) (*Manifest, error)
// ByBranch creates the manifest for the specified branch
ByBranch(name string) (*Manifest, error)
// ByCurrentBranch creates the manifest for the current branch
ByCurrentBranch() (*Manifest, error)
// ByWorkspace creates the manifest for the current workspace
ByWorkspace() (*Manifest, error)
// ByWorkspaceChanges creates the manifest for the changes in workspace
ByWorkspaceChanges() (*Manifest, error)
}
/** Workspace Management **/
// WorkspaceManager contains various functions to manipulate workspace.
type WorkspaceManager interface {
// CheckoutAndRun checks out the given commit and executes the specified function.
// Returns an error if current workspace is dirty.
// Otherwise returns the output from fn.
CheckoutAndRun(commit string, fn func() (interface{}, error)) (interface{}, error)
}
/** Process Manager **/
// ProcessManager manages the execution of build and user defined commands.
type ProcessManager interface {
// Exec runs an external command in the context of a module in a manifest.
// Following actions are performed prior to executing the command:
// - Current working directory of the target process is set to module path
// - Initialises important information in the target process environment
Exec(manifest *Manifest, module *Module, options *CmdOptions, command string, args ...string) error
}
/** Build **/
// CmdStage is an enum to indicate various stages of a command.
type CmdStage = int
// BuildSummary is a summary of a successful build.
type BuildSummary struct {
// Manifest used to trigger the build
Manifest *Manifest
// Completed list of the modules built. This list does not
// include the modules that were skipped due to
// the unavailability of a build command for the
// host platform.
Completed []*BuildResult
// Skipped modules due to the unavailability of a build command for
// the host platform
Skipped []*Module
}
// BuildResult is summary for a single module build
type BuildResult struct {
// Module of the build result
Module *Module
}
const (
// CmdStageBeforeBuild is the stage before executing module build command
CmdStageBeforeBuild = iota
// CmdStageAfterBuild is the stage after executing the module build command
CmdStageAfterBuild
// CmdStageSkipBuild is when module building is skipped due to lack of matching building command
CmdStageSkipBuild
// CmdStageFailedBuild is when module command is failed
CmdStageFailedBuild
)
// CmdStageCallback is the callback function used to notify various build stages
type CmdStageCallback func(mod *Module, s CmdStage, err error)
/** Main MBT System **/
// FilterOptions describe how to filter the modules in a manifest
type FilterOptions struct {
Name string
Fuzzy bool
Dependents bool
}
// CmdOptions defines various options required by methods executing
// user defined commands.
type CmdOptions struct {
Stdin io.Reader
Stdout, Stderr io.Writer
Callback CmdStageCallback
FailFast bool
}
// CmdFailure contains the failures occurred while running a user defined command.
type CmdFailure struct {
Module *Module
Err error
}
// RunResult is the result of running a user defined command.
type RunResult struct {
Manifest *Manifest
Completed []*Module
Skipped []*Module
Failures []*CmdFailure
}
// System is the interface used by users to invoke the core functionality
// of this package
type System interface {
// ApplyBranch applies the manifest of specified branch over a template.
// Template is retrieved from the commit tree of last commit of that branch.
ApplyBranch(templatePath, branch string, output io.Writer) error
// ApplyCommit applies the manifest of specified commit over a template.
// Template is retrieved from the commit tree of the specified commit.
ApplyCommit(sha, templatePath string, output io.Writer) error
// ApplyHead applies the manifest of current branch over a template.
// Template is retrieved from the commit tree of last commit current branch.
ApplyHead(templatePath string, output io.Writer) error
// ApplyLocal applies the manifest of local workspace.
// Template is retrieved from the current workspace.
ApplyLocal(templatePath string, output io.Writer) error
// BuildBranch builds the specified branch.
// This function accepts FilterOptions to specify which modules to be built
// within that branch.
BuildBranch(name string, filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error)
// BuildPr builds changes in 'src' branch since it diverged from 'dst' branch.
BuildPr(src, dst string, options *CmdOptions) (*BuildSummary, error)
// Build builds changes between two commits
BuildDiff(from, to string, options *CmdOptions) (*BuildSummary, error)
// BuildCurrentBranch builds the current branch.
// This function accepts FilterOptions to specify which modules to be built
// within that branch.
BuildCurrentBranch(filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error)
// BuildCommit builds specified commit.
// This function accepts FilterOptions to specify which modules to be built
// within that branch.
BuildCommit(commit string, filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error)
// BuildCommitChanges builds the changes in specified commit
BuildCommitContent(commit string, options *CmdOptions) (*BuildSummary, error)
// BuildWorkspace builds the current workspace.
// This function accepts FilterOptions to specify which modules to be built
// within that branch.
BuildWorkspace(filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error)
// BuildWorkspace builds changes in current workspace.
BuildWorkspaceChanges(options *CmdOptions) (*BuildSummary, error)
// IntersectionByCommit returns the manifest of intersection of modules modified
// between two commits.
// If we consider M as the merge base of first and second commits,
// intersection contains the modules that have been changed
// between M and first and M and second.
IntersectionByCommit(first, second string) (Modules, error)
// IntersectionByBranch returns the manifest of intersection of modules modified
// between two branches.
// If we consider M as the merge base of first and second branches,
// intersection contains the modules that have been changed
// between M and first and M and second.
IntersectionByBranch(first, second string) (Modules, error)
// ManifestByDiff creates the manifest for diff between two commits
ManifestByDiff(from, to string) (*Manifest, error)
// ManifestByPr creates the manifest for diff between two branches
ManifestByPr(src, dst string) (*Manifest, error)
// ManifestByCommit creates the manifest for the specified commit
ManifestByCommit(sha string) (*Manifest, error)
// ManifestByCommitContent creates the manifest for the content in specified commit
ManifestByCommitContent(sha string) (*Manifest, error)
// ByBranch creates the manifest for the specified branch
ManifestByBranch(name string) (*Manifest, error)
// ByCurrentBranch creates the manifest for the current branch
ManifestByCurrentBranch() (*Manifest, error)
// ByWorkspace creates the manifest for the current workspace
ManifestByWorkspace() (*Manifest, error)
// ByWorkspaceChanges creates the manifest for the changes in workspace
ManifestByWorkspaceChanges() (*Manifest, error)
// RunInBranch runs a command in a branch.
// This function accepts FilterOptions to specify a subset of modules.
RunInBranch(command, name string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error)
// RunInPr runs a command in modules that have been changed in
// 'src' branch since it diverged from 'dst' branch.
RunInPr(command, src, dst string, options *CmdOptions) (*RunResult, error)
// RunInDiff runs a command in modules that have been changed in 'from'
// commit since it diverged from 'to' commit.
RunInDiff(command, from, to string, options *CmdOptions) (*RunResult, error)
// RunInCurrentBranch runs a command in modules in the current branch.
// This function accepts FilterOptions to filter the modules included in this
// operation.
RunInCurrentBranch(command string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error)
// RunInCommit runs a command in all modules in a commit.
// This function accepts FilterOptions to filter the modules included in this
// operation.
RunInCommit(command, commit string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error)
// RunInCommitContent runs a command in modules modified in a commit.
RunInCommitContent(command, commit string, options *CmdOptions) (*RunResult, error)
// RunInWorkspace runs a command in all modules in workspace.
// This function accepts FilterOptions to filter the modules included in this
// operation.
RunInWorkspace(command string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error)
// RunInWorkspaceChanges runs a command in modules modified in workspace.
RunInWorkspaceChanges(command string, options *CmdOptions) (*RunResult, error)
}
type stdSystem struct {
Repo Repo
Log Log
MB ManifestBuilder
Discover Discover
Reducer Reducer
WorkspaceManager WorkspaceManager
ProcessManager ProcessManager
}
// NewSystem creates a new instance of core mbt system
func NewSystem(path string, logLevel int) (System, error) {
log := NewStdLog(logLevel)
repo, err := NewLibgitRepo(path, log)
if err != nil {
return nil, err
}
discover := NewDiscover(repo, log)
reducer := NewReducer(log)
mb := NewManifestBuilder(repo, reducer, discover, log)
wm := NewWorkspaceManager(log, repo)
pm := NewProcessManager(log)
return initSystem(log, repo, mb, discover, reducer, wm, pm), nil
}
// NoFilter is built-in filter that represents no filtering
var NoFilter = &FilterOptions{}
// FuzzyFilter is a helper to create a fuzzy match FilterOptions
func FuzzyFilter(name string) *FilterOptions {
return &FilterOptions{Name: name, Fuzzy: true}
}
// ExactMatchFilter is a helper to create an exact match FilterOptions
func ExactMatchFilter(name string) *FilterOptions {
return &FilterOptions{Name: name}
}
// FuzzyDependentsFilter is a helper to create a fuzzy match FilterOptions
func FuzzyDependentsFilter(name string) *FilterOptions {
return &FilterOptions{Name: name, Fuzzy: true, Dependents: true}
}
// ExactMatchDependentsFilter is a helper to create an exact match FilterOptions
func ExactMatchDependentsFilter(name string) *FilterOptions {
return &FilterOptions{Name: name, Dependents: true}
}
func initSystem(log Log, repo Repo, mb ManifestBuilder, discover Discover, reducer Reducer, workspaceManager WorkspaceManager, processManager ProcessManager) System {
return &stdSystem{
Log: log,
Repo: repo,
MB: mb,
Discover: discover,
Reducer: reducer,
WorkspaceManager: workspaceManager,
ProcessManager: processManager,
}
}
func (s *stdSystem) ManifestBuilder() ManifestBuilder {
return s.MB
}
// CmdOptionsWithStdIO creates an instance of CmdOptions with
// its streams pointing to std io streams.
func CmdOptionsWithStdIO(callback CmdStageCallback) *CmdOptions {
return &CmdOptions{
Callback: callback,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
}
<file_sep>/docs/mbt_build_diff.md
## mbt build diff
### Synopsis
```
mbt build diff --from <sha> --to <sha> [flags]
```
### Options
```
--from string From commit
-h, --help help for diff
--to string To commit
```
### Options inherited from parent commands
```
--debug Enable debug output
--in string Path to repo
```
### SEE ALSO
* [mbt build](mbt_build.md) - Run build command
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/docs/mbt_apply_local.md
## mbt apply local
### Synopsis
```
mbt apply local [flags]
```
### Options
```
-h, --help help for local
```
### Options inherited from parent commands
```
--debug Enable debug output
--in string Path to repo
--out string Output path
--to string Template to apply
```
### SEE ALSO
* [mbt apply](mbt_apply.md) - Apply repository manifest over a go template
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/lib/intersection_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIntersectionWithElements(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature-a"))
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
second := repo.LastCommit
check(t, repo.SwitchToBranch("master"))
check(t, repo.SwitchToBranch("feature-b"))
check(t, repo.WriteContent("app-a/bar", "hello"))
check(t, repo.WriteContent("app-b/foo", "hello"))
check(t, repo.Commit("third"))
third := repo.LastCommit
mods, err := NewWorld(t, ".tmp/repo").System.IntersectionByCommit(second.String(), third.String())
check(t, err)
assert.Len(t, mods, 1)
assert.Equal(t, "app-a", mods[0].Name())
// This operation should be commutative
mods, err = NewWorld(t, ".tmp/repo").System.IntersectionByCommit(third.String(), second.String())
check(t, err)
assert.Len(t, mods, 1)
assert.Equal(t, "app-a", mods[0].Name())
}
func TestIntersectionWithoutElements(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature-a"))
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
second := repo.LastCommit
check(t, repo.SwitchToBranch("master"))
check(t, repo.SwitchToBranch("feature-b"))
check(t, repo.WriteContent("app-b/foo", "hello"))
check(t, repo.Commit("third"))
third := repo.LastCommit
mods, err := NewWorld(t, ".tmp/repo").System.IntersectionByCommit(second.String(), third.String())
check(t, err)
assert.Len(t, mods, 0)
// This operation should be commutative
mods, err = NewWorld(t, ".tmp/repo").System.IntersectionByCommit(third.String(), second.String())
check(t, err)
assert.Len(t, mods, 0)
}
func TestIntersectionByBranchWithElements(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature-a"))
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.SwitchToBranch("feature-b"))
check(t, repo.WriteContent("app-a/bar", "hello"))
check(t, repo.WriteContent("app-b/foo", "hello"))
check(t, repo.Commit("third"))
mods, err := NewWorld(t, ".tmp/repo").System.IntersectionByBranch("feature-a", "feature-b")
check(t, err)
assert.Len(t, mods, 1)
assert.Equal(t, "app-a", mods[0].Name())
// This operation should be commutative
mods, err = NewWorld(t, ".tmp/repo").System.IntersectionByBranch("feature-b", "feature-a")
check(t, err)
assert.Len(t, mods, 1)
assert.Equal(t, "app-a", mods[0].Name())
}
func TestIntersectionWithDependencies(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{Name: "app-a", Dependencies: []string{"app-c"}}))
check(t, repo.InitModule("app-b"))
check(t, repo.InitModuleWithOptions("app-c", &Spec{Name: "app-c"}))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature-a"))
check(t, repo.WriteContent("app-c/foo", "hello"))
check(t, repo.Commit("second"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.SwitchToBranch("feature-b"))
check(t, repo.WriteContent("app-a/bar", "hello"))
check(t, repo.Commit("third"))
mods, err := NewWorld(t, ".tmp/repo").System.IntersectionByBranch("feature-a", "feature-b")
check(t, err)
assert.Len(t, mods, 1)
assert.Equal(t, "app-c", mods[0].Name())
// This operation should be commutative
mods, err = NewWorld(t, ".tmp/repo").System.IntersectionByBranch("feature-b", "feature-a")
check(t, err)
assert.Len(t, mods, 1)
assert.Equal(t, "app-c", mods[0].Name())
}
func TestIntersctionOfTwoChangesWithSharedDependency(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{Name: "app-a", Dependencies: []string{"app-c"}}))
check(t, repo.InitModuleWithOptions("app-b", &Spec{Name: "app-b", Dependencies: []string{"app-c"}}))
check(t, repo.InitModuleWithOptions("app-c", &Spec{Name: "app-c"}))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature-a"))
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.SwitchToBranch("feature-b"))
check(t, repo.WriteContent("app-b/bar", "hello"))
check(t, repo.Commit("third"))
mods, err := NewWorld(t, ".tmp/repo").System.IntersectionByBranch("feature-a", "feature-b")
check(t, err)
assert.Len(t, mods, 0)
// This operation should be commutative
mods, err = NewWorld(t, ".tmp/repo").System.IntersectionByBranch("feature-b", "feature-a")
check(t, err)
assert.Len(t, mods, 0)
}
<file_sep>/lib/discover_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"os"
"testing"
"github.com/mbtproject/mbt/e"
"github.com/stretchr/testify/assert"
)
func TestDependencyLinks(t *testing.T) {
a := newModuleMetadata("app-a", "a", &Spec{Name: "app-a", Dependencies: []string{"app-b"}}, nil)
b := newModuleMetadata("app-b", "b", &Spec{Name: "app-b", Dependencies: []string{"app-c"}}, nil)
c := newModuleMetadata("app-c", "c", &Spec{Name: "app-c"}, nil)
s := moduleMetadataSet{a, b, c}
mods, err := toModules(s)
check(t, err)
m := mods.indexByName()
assert.Len(t, mods, 3)
assert.Equal(t, m["app-b"], m["app-a"].Requires()[0])
assert.Equal(t, m["app-c"], m["app-b"].Requires()[0])
assert.Equal(t, 0, len(m["app-c"].Requires()))
assert.Equal(t, m["app-b"], m["app-c"].RequiredBy()[0])
assert.Equal(t, m["app-a"], m["app-b"].RequiredBy()[0])
}
func TestVersionCalculation(t *testing.T) {
a := newModuleMetadata("app-a", "a", &Spec{Name: "app-a", Dependencies: []string{"app-b"}}, nil)
b := newModuleMetadata("app-b", "b", &Spec{Name: "app-b"}, nil)
s := moduleMetadataSet{a, b}
mods, err := toModules(s)
check(t, err)
m := mods.indexByName()
assert.Equal(t, "b", m["app-b"].Version())
assert.Equal(t, "da23614e02469a0d7c7bd1bdab5c9c474b1904dc", m["app-a"].Version())
}
func TestMalformedSpec(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/.mbt.yml", "blah:blah\nblah::"))
check(t, repo.Commit("first"))
world := NewWorld(t, ".tmp/repo")
lc, err := world.Repo.GetCommit(repo.LastCommit.String())
check(t, err)
metadata, err := world.Discover.ModulesInCommit(lc)
assert.Nil(t, metadata)
assert.EqualError(t, err, "error while parsing the spec at app-a/.mbt.yml")
assert.EqualError(t, (err.(*e.E).InnerError()), "yaml: line 1: mapping values are not allowed in this context")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestMissingBlobs(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
world := NewWorld(t, ".tmp/repo")
lc, err := world.Repo.GetCommit(repo.LastCommit.String())
check(t, err)
check(t, os.RemoveAll(".tmp/repo/.git/objects"))
check(t, os.Mkdir(".tmp/repo/.git/objects", 0755))
metadata, err := world.Discover.ModulesInCommit(lc)
assert.Nil(t, metadata)
assert.EqualError(t, err, fmt.Sprintf(msgFailedTreeLoad, repo.LastCommit.String()))
assert.EqualError(t, (err.(*e.E)).InnerError(), fmt.Sprintf("object not found - no match for id (215e27aae62c4e89fd047f07b9ca3708283c3657)"))
assert.Equal(t, ErrClassInternal, (err.(*e.E)).Class())
}
func TestMissingTreeObject(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
world := NewWorld(t, ".tmp/repo")
lc, err := world.Repo.GetCommit(repo.LastCommit.String())
check(t, err)
check(t, os.RemoveAll(".tmp/repo/.git/objects/6c"))
metadata, err := world.Discover.ModulesInCommit(lc)
treeID := "215e27aae62c4e89fd047f07b9ca3708283c3657"
assert.Nil(t, metadata)
assert.EqualError(t, err, fmt.Sprintf(msgFailedTreeWalk, treeID))
assert.EqualError(t, (err.(*e.E)).InnerError(), "object not found - no match for id (6c1d6fb334240894b1ec130a6009264a0cf8351b)")
assert.Equal(t, ErrClassInternal, (err.(*e.E)).Class())
}
func TestMissingDependencies(t *testing.T) {
s := moduleMetadataSet{&moduleMetadata{
dir: "app-a",
hash: "a",
spec: &Spec{
Name: "app-a",
Dependencies: []string{"app-b"},
},
}}
mods, err := toModules(s)
assert.Nil(t, mods)
assert.EqualError(t, err, "dependency not found app-a -> app-b")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestModuleNameConflicts(t *testing.T) {
s := moduleMetadataSet{
&moduleMetadata{
dir: "app-a",
hash: "a",
spec: &Spec{Name: "app-a"},
},
&moduleMetadata{
dir: "app-b",
hash: "a",
spec: &Spec{Name: "app-a"},
},
}
mods, err := toModules(s)
assert.Nil(t, mods)
assert.EqualError(t, err, "Module name 'app-a' in directory 'app-b' conflicts with the module in 'app-a' directory")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestDirectoryEntriesCalledMbtYml(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent(".mbt.yml/foo", "blah"))
check(t, repo.Commit("first"))
world := NewWorld(t, ".tmp/repo")
lc, err := world.Repo.GetCommit(repo.LastCommit.String())
check(t, err)
modules, err := world.Discover.ModulesInCommit(lc)
check(t, err)
assert.Len(t, modules, 1)
assert.Equal(t, "app-a", modules[0].Name())
}
func TestVersionChangeOnFileDependencyChange(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
FileDependencies: []string{"foo.txt"},
}))
check(t, repo.WriteContent("foo.txt", "hello"))
check(t, repo.Commit("first"))
world := NewWorld(t, ".tmp/repo")
c1, err := world.Repo.GetCommit(repo.LastCommit.String())
check(t, err)
m1, err := world.Discover.ModulesInCommit(c1)
check(t, err)
check(t, repo.AppendContent("foo.txt", "world"))
check(t, repo.Commit("second"))
c2, err := world.Repo.GetCommit(repo.LastCommit.String())
check(t, err)
m2, err := world.Discover.ModulesInCommit(c2)
check(t, err)
assert.NotEqual(t, m2[0].Version(), m1[0].Version())
}
<file_sep>/docs/mbt_describe_pr.md
## mbt describe pr
### Synopsis
```
mbt describe pr --src <branch> --dst <branch> [flags]
```
### Options
```
--dst string Destination branch
-h, --help help for pr
--src string Source branch
```
### Options inherited from parent commands
```
--debug Enable debug output
--graph Format output as dot graph
--in string Path to repo
--json Format output as json
```
### SEE ALSO
* [mbt describe](mbt_describe.md) - Describe repository manifest
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/CHANGELOG.md
## 0.22.0
- [f2489cd](https://github.com/mbtproject/mbt/commit/f2489cd) [build] Upgraded go tool-chain
## 0.21.0
- [6c9f0d4](https://github.com/mbtproject/mbt/commit/6c9f0d4) [feat] Fail fast option for user defined commands
- [f53f196](https://github.com/mbtproject/mbt/commit/f53f196) [a4ab9ae](https://github.com/mbtproject/mbt/commit/a4ab9ae) [a9903c4](https://github.com/mbtproject/mbt/commit/a9903c4) [feat] Default build command
## 0.20.1
- [e3a0fbb](https://github.com/mbtproject/mbt/commit/e3a0fbb) [f855765](https://github.com/mbtproject/mbt/commit/f855765) [perf] Faster discovery of local modules
## 0.20.0
- [398b10e](https://github.com/mbtproject/mbt/commit/398b10e) [2af9407](https://github.com/mbtproject/mbt/commit/2af9407) Feature: Additional environment values
## 0.19.0
- [529068f](https://github.com/mbtproject/mbt/commit/529068f) Feature: Make a sorted modules list available for templates
## 0.18.0
- [9ed7c00](https://github.com/mbtproject/mbt/commit/9ed7c00) Feature: New template helpers
## 0.17.1
- [24e3039](https://github.com/mbtproject/mbt/commit/24e3039) Fix: Support builds when head is detached
## 0.17.0
- [97855c3](https://github.com/mbtproject/mbt/commit/97855c3) Fix: Version is written to stdout instead of stderr
- [aecdcd3](https://github.com/mbtproject/mbt/commit/aecdcd3) Feature: Template helper to convert a map to a list
- [d8b898a](https://github.com/mbtproject/mbt/commit/d8b898a) Fix: Prevent build|run-in commands when head is detached
- [ff5d22a](https://github.com/mbtproject/mbt/commit/ff5d22a) Feature: Execute user defined commands in modules
## 0.16.0
### Breaking Changes
This version includes significant breaking changes. Click through to the
commit messages for more information.
- [cdcc122](https://github.com/mbtproject/mbt/commit/cdcc122) Fix: Consider file dependencies when calculating the version
- [c52b91b](https://github.com/mbtproject/mbt/commit/c52b91b) Feature: Filter modules during commands based on git tree
## 0.15.1
- [3f20eee](https://github.com/mbtproject/mbt/commit/3f20eee) Fix: Update head during checkout operations
- [0760617](https://github.com/mbtproject/mbt/commit/0760617) Fix: Detect local changes on root
- [60792ab](https://github.com/mbtproject/mbt/commit/60792ab) Fix: Handle root module changes correctly
## 0.15.0
- [b02aaad](https://github.com/mbtproject/mbt/commit/b02aaad) Feature: Filter modules during local build/describe
- [7c0f5b0](https://github.com/mbtproject/mbt/commit/7c0f5b0) Feature: Run mbt command from anywhere
- [78c1b44](https://github.com/mbtproject/mbt/commit/78c1b44) Feature: Improved cyclic error message
- [25e3ae6](https://github.com/mbtproject/mbt/commit/25e3ae6) Feature: Display a build summary
- [884819e](https://github.com/mbtproject/mbt/commit/884819e) Feature: Display an empty list when no modules to describe.
- [b0796b0](https://github.com/mbtproject/mbt/commit/b0796b0) Feature: Build/Describe content of a commit
<file_sep>/lib/system_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"os"
"testing"
"github.com/mbtproject/mbt/e"
"github.com/stretchr/testify/assert"
)
func TestNewSystemForNonGitRepo(t *testing.T) {
clean()
check(t, os.MkdirAll(".tmp/repo", 0755))
repo, err := NewSystem(".tmp/repo", LogLevelNormal)
assert.EqualError(t, err, fmt.Sprintf(msgFailedOpenRepo, ".tmp/repo"))
assert.EqualError(t, (err.(*e.E)).InnerError(), "could not find repository from '.tmp/repo'")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
assert.Nil(t, repo)
}
<file_sep>/lib/transform_props.go
/*
Copyright 2018 MBT Authors.
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 lib
import "github.com/mbtproject/mbt/e"
// transformProps is a helper function to convert all map[interface{}]interface{}
// to map[string]interface{}.
// Background:
// This operation is required due to what seems to be an anomaly in yaml
// library (https://github.com/go-yaml/yaml/issues/286)
// Due to this behavior, if we serialise the output of yaml.Unmarshal to
// with json.Marshal, it blows-up for scenarios with nested maps.
// This function is used to normalise the the whole tree before
// we use it.
func transformProps(p map[string]interface{}) (map[string]interface{}, error) {
for k, v := range p {
nv, err := transformIfRequired(v)
if err != nil {
return nil, err
}
p[k] = nv
}
return p, nil
}
func transformIfRequired(v interface{}) (interface{}, error) {
if c, ok := v.(map[interface{}]interface{}); ok {
return transformMaps(c)
} else if c, ok := v.([]interface{}); ok {
a := make([]interface{}, len(c))
for i, v := range c {
e, err := transformIfRequired(v)
if err != nil {
return nil, err
}
a[i] = e
}
return a, nil
}
return v, nil
}
func transformMaps(m map[interface{}]interface{}) (map[string]interface{}, error) {
newMap := make(map[string]interface{})
for k, v := range m {
sk, ok := k.(string)
if !ok {
return nil, e.NewErrorf(ErrClassInternal, "Key is not a string %v", k)
}
nv, err := transformIfRequired(v)
if err != nil {
return nil, err
}
newMap[sk] = nv
}
return newMap, nil
}
<file_sep>/docs/mbt_run-in.md
## mbt run-in
Run user defined command
### Synopsis
`mbt run-in branch [name] [--content] [--name <name>] [--fuzzy]`<br>
Run user defined command in modules in a branch. Assume master if branch name is not specified.
Consider just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt run-in commit <commit> [--content] [--name <name>] [--fuzzy]`<br>
Run user defined command in modules in a commit. Full commit sha is required.
Consider just the modules modified in the commit when `--content` flag is used.
Consider just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt run-in diff --from <commit> --to <commit>`<br>
Run user defined command in modules changed between `from` and `to` commits.
In this mode, mbt works out the merge base between `from` and `to` and
evaluates the modules changed between the merge base and `to`.
`mbt run-in head [--content] [--name <name>] [--fuzzy]`<br>
Run user defined command in modules in current head.
Consider just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
`mbt run-in pr --src <name> --dst <name>`<br>
Run user defined command in modules changed between `--src` and `--dst` branches.
In this mode, mbt works out the merge base between `--src` and `--dst` and
evaluates the modules changed between the merge base and `--src`.
`mbt run-in local [--all] [--content] [--name <name>] [--fuzzy]`<br>
Run user defined command in modules modified in current workspace. All modules in the workspace are
considered if `--all` option is specified.
Consider just the modules matching the `--name` filter if specified.
Default `--name` filter is a prefix match. You can change this to a subsequence
match by using `--fuzzy` option.
### Execution Environment
When executing a command, following environment variables are initialised and can be
used by the command being executed.
`MBT_MODULE_NAME` Name of the module
`MBT_MODULE_VERSION` Module version
`MBT_BUILD_COMMIT` Git commit SHA of the commit being built
In addition to the variables listed above, module properties are also populated
in the form of `MBT_MODULE_PROPERTY_XXX` where `XXX` denotes the key.
### Options
```
-m, --command string Command to execute
--fail-fast Fail fast on command failure
-h, --help help for run-in
```
### Options inherited from parent commands
```
--debug Enable debug output
--in string Path to repo
```
### SEE ALSO
* [mbt](mbt.md) - mbt - The most flexible build orchestration tool for monorepo
* [mbt run-in branch](mbt_run-in_branch.md) -
* [mbt run-in commit](mbt_run-in_commit.md) -
* [mbt run-in diff](mbt_run-in_diff.md) -
* [mbt run-in head](mbt_run-in_head.md) -
* [mbt run-in local](mbt_run-in_local.md) -
* [mbt run-in pr](mbt_run-in_pr.md) -
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/lib/manifest.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"strings"
"github.com/mbtproject/mbt/utils"
)
func (s *stdSystem) ManifestByDiff(from, to string) (*Manifest, error) {
f, err := s.Repo.GetCommit(from)
if err != nil {
return nil, err
}
t, err := s.Repo.GetCommit(to)
if err != nil {
return nil, err
}
return s.MB.ByDiff(f, t)
}
func (s *stdSystem) ManifestByPr(src, dst string) (*Manifest, error) {
return s.MB.ByPr(src, dst)
}
func (s *stdSystem) ManifestByCommit(sha string) (*Manifest, error) {
c, err := s.Repo.GetCommit(sha)
if err != nil {
return nil, err
}
return s.MB.ByCommit(c)
}
func (s *stdSystem) ManifestByCommitContent(sha string) (*Manifest, error) {
c, err := s.Repo.GetCommit(sha)
if err != nil {
return nil, err
}
return s.MB.ByCommitContent(c)
}
func (s *stdSystem) ManifestByBranch(name string) (*Manifest, error) {
return s.MB.ByBranch(name)
}
func (s *stdSystem) ManifestByCurrentBranch() (*Manifest, error) {
return s.MB.ByCurrentBranch()
}
func (s *stdSystem) ManifestByWorkspace() (*Manifest, error) {
return s.MB.ByWorkspace()
}
func (s *stdSystem) ManifestByWorkspaceChanges() (*Manifest, error) {
return s.MB.ByWorkspaceChanges()
}
// FilterByName reduces the modules in a Manifest to the
// ones that are matching the terms specified in filter.
// Multiple terms can be specified as a comma separated
// string.
// If fuzzy argument is true, comparison is a case insensitive
// subsequence comparison. Otherwise, it's a case insensitive
// exact match.
func (m *Manifest) FilterByName(filterOptions *FilterOptions) *Manifest {
filteredModules := make(Modules, 0)
filter := strings.ToLower(filterOptions.Name)
filters := strings.Split(filter, ",")
for _, m := range m.Modules {
lowerModuleName := strings.ToLower(m.Name())
match := matches(lowerModuleName, filters, filterOptions.Fuzzy)
if match {
filteredModules = append(filteredModules, m)
}
}
return &Manifest{Dir: m.Dir, Modules: filteredModules, Sha: m.Sha}
}
// ApplyFilters will filter the modules in the manifest to the ones that
// matches the specified filter. If filter is not specified, original
// manifest is returned.
func (m *Manifest) ApplyFilters(filterOptions *FilterOptions) (*Manifest, error) {
if filterOptions == nil {
panic("filterOptions cannot be nil")
}
if filterOptions.Name != "" {
m = m.FilterByName(filterOptions)
}
if filterOptions.Dependents {
var err error
m.Modules, err = m.Modules.expandRequiredByDependencies()
if err != nil {
return nil, err
}
}
return m, nil
}
func matches(value string, filters []string, fuzzy bool) bool {
match := false
for _, f := range filters {
if fuzzy {
match = utils.IsSubsequence(value, f, true)
} else {
match = value == f
}
if match {
break
}
}
return match
}
<file_sep>/lib/build.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"runtime"
git "github.com/libgit2/git2go/v28"
"github.com/mbtproject/mbt/e"
)
var defaultCheckoutOptions = &git.CheckoutOpts{
Strategy: git.CheckoutSafe,
}
func (s *stdSystem) BuildBranch(name string, filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByBranch(name)
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.checkoutAndBuildManifest(m, options)
}
func (s *stdSystem) BuildPr(src, dst string, options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByPr(src, dst)
if err != nil {
return nil, err
}
return s.checkoutAndBuildManifest(m, options)
}
func (s *stdSystem) BuildDiff(from, to string, options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByDiff(from, to)
if err != nil {
return nil, err
}
return s.checkoutAndBuildManifest(m, options)
}
func (s *stdSystem) BuildCurrentBranch(filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByCurrentBranch()
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.checkoutAndBuildManifest(m, options)
}
func (s *stdSystem) BuildCommit(commit string, filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByCommit(commit)
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.checkoutAndBuildManifest(m, options)
}
func (s *stdSystem) BuildCommitContent(commit string, options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByCommitContent(commit)
if err != nil {
return nil, err
}
return s.checkoutAndBuildManifest(m, options)
}
func (s *stdSystem) BuildWorkspace(filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByWorkspace()
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.buildManifest(m, options)
}
func (s *stdSystem) BuildWorkspaceChanges(options *CmdOptions) (*BuildSummary, error) {
m, err := s.ManifestByWorkspaceChanges()
if err != nil {
return nil, err
}
return s.buildManifest(m, options)
}
func (s *stdSystem) checkoutAndBuildManifest(m *Manifest, options *CmdOptions) (*BuildSummary, error) {
r, err := s.WorkspaceManager.CheckoutAndRun(m.Sha, func() (interface{}, error) {
return s.buildManifest(m, options)
})
if err != nil {
return nil, err
}
return r.(*BuildSummary), nil
}
func (s *stdSystem) buildManifest(m *Manifest, options *CmdOptions) (*BuildSummary, error) {
completed := make([]*BuildResult, 0)
skipped := make([]*Module, 0)
for _, a := range m.Modules {
cmd, ok := s.canBuildHere(a)
if !ok {
skipped = append(skipped, a)
options.Callback(a, CmdStageSkipBuild, nil)
continue
}
options.Callback(a, CmdStageBeforeBuild, nil)
err := s.execBuild(cmd, m, a, options)
if err != nil {
return nil, err
}
options.Callback(a, CmdStageAfterBuild, nil)
completed = append(completed, &BuildResult{Module: a})
}
return &BuildSummary{Manifest: m, Completed: completed, Skipped: skipped}, nil
}
func (s *stdSystem) execBuild(buildCmd *Cmd, manifest *Manifest, module *Module, options *CmdOptions) error {
err := s.ProcessManager.Exec(manifest, module, options, buildCmd.Cmd, buildCmd.Args...)
if err != nil {
return e.Wrapf(ErrClassUser, err, msgFailedBuild, module.Name())
}
return nil
}
func (s *stdSystem) canBuildHere(mod *Module) (*Cmd, bool) {
c, ok := mod.Build()[runtime.GOOS]
if !ok {
c, ok = mod.Build()["default"]
}
return c, ok
}
<file_sep>/e/e_test.go
/*
Copyright 2018 MBT Authors.
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 e
import (
"errors"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
)
const (
ErrClassInternal = iota
ErrClassUser
)
func TestSimpleError(t *testing.T) {
e := NewError(ErrClassInternal, "a")
assert.EqualError(t, e, "a")
}
func TestSimpleErrorWithFormat(t *testing.T) {
e := NewErrorf(ErrClassInternal, "a%s", "b")
assert.EqualError(t, e, "ab")
}
func TestWrappedErrorWithMessage(t *testing.T) {
i := errors.New("a")
e := Wrapf(ErrClassInternal, i, "b")
assert.EqualError(t, e, "b")
assert.EqualError(t, e.InnerError(), "a")
}
func TestWrappedError(t *testing.T) {
e := Wrap(ErrClassInternal, errors.New("a"))
assert.EqualError(t, e, "a")
}
func TestStack(t *testing.T) {
ptr, _, _, ok := runtime.Caller(0)
assert.True(t, ok)
frames := runtime.CallersFrames([]uintptr{ptr})
f, _ := frames.Next()
e := Wrap(ErrClassInternal, errors.New("b"))
assert.Equal(t, f.Function, e.Stack()[1].Function)
}
func TestExtendedInfo(t *testing.T) {
err := NewError(ErrClassInternal, "blah")
assert.Contains(t, err.WithExtendedInfo().Error(), "call stack")
}
func WrappingAnE(t *testing.T) {
a := Wrap(ErrClassInternal, errors.New("a"))
assert.Equal(t, a, Wrap(ErrClassInternal, a))
assert.Equal(t, a, Wrap(ErrClassUser, a))
}
<file_sep>/lib/run_in_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"bytes"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCmdExecution(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello"}},
},
})
w := NewWorld(t, ".tmp/repo")
// Test new workspace
buff := new(bytes.Buffer)
result, err := w.System.RunInWorkspace("echo", NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "hello\n", buff.String())
// Test new workspace diff
buff = new(bytes.Buffer)
result, err = w.System.RunInWorkspaceChanges("echo", stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "hello\n", buff.String())
}
func TestRunInDirtyWorkingDir(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello"}},
},
})
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInCurrentBranch("echo", NoFilter, stdTestCmdOptions(buff))
assert.Nil(t, result)
assert.EqualError(t, err, msgDirtyWorkingDir)
}
func TestRunInBranch(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-master"}},
},
})
r.Commit("first")
r.SwitchToBranch("feature")
r.Remove("app-a")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-feature"}},
},
})
r.Commit("second")
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInBranch("echo", "master", NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "hello-master\n", buff.String())
buff = new(bytes.Buffer)
result, err = w.System.RunInBranch("echo", "feature", NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "hello-feature\n", buff.String())
}
func TestRunInPr(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-app-a"}},
},
})
r.Commit("first")
r.SwitchToBranch("feature")
r.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-app-b"}},
},
})
r.Commit("second")
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInPr("echo", "feature", "master", stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-b", result.Completed[0].Name())
assert.Equal(t, "hello-app-b\n", buff.String())
buff = new(bytes.Buffer)
result, err = w.System.RunInPr("echo", "master", "feature", stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 0)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "", buff.String())
}
func TestRunInDiff(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-app-a"}},
},
})
r.Commit("first")
c1 := r.LastCommit
r.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-app-b"}},
},
})
r.Commit("second")
c2 := r.LastCommit
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInDiff("echo", c1.String(), c2.String(), stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-b", result.Completed[0].Name())
assert.Equal(t, "hello-app-b\n", buff.String())
buff = new(bytes.Buffer)
result, err = w.System.RunInDiff("echo", c2.String(), c1.String(), stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 0)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "", buff.String())
}
func TestRunInCurrentBranch(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello"}},
},
})
r.Commit("first")
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInCurrentBranch("echo", NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "hello\n", buff.String())
}
func TestRunInCommit(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-c1"}},
},
})
r.Commit("first")
c1 := r.LastCommit
r.Remove("app-a")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-c2"}},
},
})
r.Commit("second")
c2 := r.LastCommit
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInCommit("echo", c1.String(), NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "hello-c1\n", buff.String())
buff = new(bytes.Buffer)
result, err = w.System.RunInCommit("echo", c2.String(), NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "hello-c2\n", buff.String())
}
func TestRunInCommitContent(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-app-a"}},
},
})
r.Commit("first")
r.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"hello-app-b"}},
},
})
r.Commit("second")
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInCommitContent("echo", r.LastCommit.String(), stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "app-b", result.Completed[0].Name())
assert.Equal(t, "hello-app-b\n", buff.String())
}
func TestOSConstraints(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("unix-app", &Spec{
Name: "unix-app",
Commands: map[string]*UserCmd{
"echo": {Cmd: "./script.sh", OS: []string{"linux", "darwin"}},
},
})
r.WriteShellScript("unix-app/script.sh", "echo hello-unix-app")
r.InitModuleWithOptions("windows-app", &Spec{
Name: "windows-app",
Commands: map[string]*UserCmd{
"echo": {Cmd: "powershell", Args: []string{"-ExecutionPolicy", "Bypass", "-File", ".\\script.ps1"}, OS: []string{"windows"}},
},
})
r.WritePowershellScript("windows-app/script.ps1", "echo hello-windows-app")
r.Commit("first")
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInCurrentBranch("echo", NoFilter, stdTestCmdOptions(buff))
check(t, err)
switch runtime.GOOS {
case "linux", "darwin":
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 1)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "unix-app", result.Completed[0].Name())
assert.Equal(t, "windows-app", result.Skipped[0].Name())
assert.Equal(t, "hello-unix-app\n", buff.String())
case "windows":
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 1)
assert.Len(t, result.Failures, 0)
assert.Equal(t, "windows-app", result.Completed[0].Name())
assert.Equal(t, "unix-app", result.Skipped[0].Name())
assert.Equal(t, "hello-windows-app\r\n", buff.String())
}
}
func TestFailingCommands(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"app-a"}},
},
})
r.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Commands: map[string]*UserCmd{
"echo": {Cmd: "bad_command", Args: []string{"app-b"}},
},
})
r.InitModuleWithOptions("app-c", &Spec{
Name: "app-c",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"app-c"}},
},
})
r.Commit("first")
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
result, err := w.System.RunInCurrentBranch("echo", NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Len(t, result.Completed, 2)
assert.Len(t, result.Skipped, 0)
assert.Len(t, result.Failures, 1)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "app-c", result.Completed[1].Name())
assert.Equal(t, "app-b", result.Failures[0].Module.Name())
assert.Equal(t, "app-a\napp-c\n", buff.String())
}
func TestFailFast(t *testing.T) {
clean()
r := NewTestRepo(t, ".tmp/repo")
r.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"app-a"}},
},
})
r.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Commands: map[string]*UserCmd{
"echo": {Cmd: "bad_command", Args: []string{"app-b"}},
},
})
r.InitModuleWithOptions("app-c", &Spec{
Name: "app-c",
Commands: map[string]*UserCmd{
"echo": {Cmd: "echo", Args: []string{"app-c"}},
},
})
r.Commit("first")
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
options := stdTestCmdOptions(buff)
options.FailFast = true
result, err := w.System.RunInCurrentBranch("echo", NoFilter, options)
check(t, err)
assert.Len(t, result.Completed, 1)
assert.Len(t, result.Skipped, 1)
assert.Len(t, result.Failures, 1)
assert.Equal(t, "app-a", result.Completed[0].Name())
assert.Equal(t, "app-b", result.Failures[0].Module.Name())
assert.Equal(t, "app-c", result.Skipped[0].Name())
assert.Equal(t, "app-a\n", buff.String())
}
<file_sep>/scripts/import_libgit2.sh
#!/bin/sh
#
# Use this utility to import libgit2 sources into the directory.
#
set -e
DIR="$(pwd)"
LIBGIT2_PATH="$DIR/libgit2"
LIBGIT2_VERSION="v0.28.5"
if [ -d $LIBGIT2_PATH ]; then
rm -rf $LIBGIT2_PATH
fi
git clone https://github.com/libgit2/libgit2.git $LIBGIT2_PATH
cd $LIBGIT2_PATH
git checkout $LIBGIT2_VERSION
cd $DIR
rm -rf $LIBGIT2_PATH/.git<file_sep>/docs/mbt_apply.md
## mbt apply
Apply repository manifest over a go template
### Synopsis
`mbt apply branch [name] --to <path>`<br>
Apply the manifest of the tip of the branch to a template.
Template path should be relative to the repository root and must be available
in the commit tree. Assume master if name is not specified.
`mbt apply commit <commit> --to <path>`<br>
Apply the manifest of a commit to a template.
Template path should be relative to the repository root and must be available
in the commit tree.
`mbt apply head --to <path>`<br>
Apply the manifest of current head to a template.
Template path should be relative to the repository root and must be available
in the commit tree.
`mbt apply local --to <path>`<br>
Apply the manifest of local workspace to a template.
Template path should be relative to the repository root and must be available
in the workspace.
### Template Helpers
Following helper functions are available when writing templates.
`module <name>`<br>
Find the specified module from modules set discovered in the repo.
`property <module> <name>`<br>
Find the specified property in the given module. Standard dot notation can be used to access nested properties (e.g. `a.b.c`).
`propertyOr <module> <name> <default>`<br>
Find specified property in the given module or return the designated default value.
`contains <array> <item>`<br>
Return true if the given item is present in the array.
`join <array> <format> <separator>`<br>
Format each item in the array according the format specified and then join them with the specified separator.
`kvplist <map>`<br>
Take a map of `map[string]interface{}` and return the items in the map as a list of key/value pairs sorted by the key. They can be accessed via `.Key` and `.Value` properties.
`add <int> <int>`<br>
Add two integers.
`sub <int> <int>`<br>
Subtract two integers.
`mul <int> <int>`{br}
Multiply two integers.
`div <int> <int>`<br>
Divide two integers.
`head <array|slice>`<br>
Select the first item in an array/slice. Return `""` if the input is `nil` or an empty array/slice.
`tail <array|slice>`<br>
Select the last item in an array/slice. Return `""` if the input is `nil` or an empty array/slice.
`ishead <array> <value>`<br>
Return true if the specified value is the head of the array/slice.
`istail <array> <value>`<br>
Return true if the specified value is the tail of the array/slice.
These functions can be pipelined to simplify complex template expressions. Below is an example of emitting the word "foo"
when module "app-a" has the value "a" in it's tags property.
### Options
```
-h, --help help for apply
--out string Output path
--to string Template to apply
```
### Options inherited from parent commands
```
--debug Enable debug output
--in string Path to repo
```
### SEE ALSO
* [mbt](mbt.md) - mbt - The most flexible build orchestration tool for monorepo
* [mbt apply branch](mbt_apply_branch.md) -
* [mbt apply commit](mbt_apply_commit.md) -
* [mbt apply head](mbt_apply_head.md) -
* [mbt apply local](mbt_apply_local.md) -
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/intercept/interceptor.go
/*
Copyright 2018 MBT Authors.
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 intercept
import (
"fmt"
"reflect"
)
// Config is the configuration of an intercepted functions behavior.
type Config interface {
// Return configures specific return value(s).
Return(...interface{}) Config
// Do configure a specific behavior for a function.
Do(func(...interface{}) []interface{}) Config
}
type stdConfig struct {
impl func(...interface{}) []interface{}
}
func (c *stdConfig) Return(values ...interface{}) Config {
c.impl = func(...interface{}) []interface{} {
return values
}
return c
}
func (c *stdConfig) Do(impl func(...interface{}) []interface{}) Config {
c.impl = impl
return c
}
// Interceptor provides the means for intercepting.
type Interceptor struct {
config map[string]*stdConfig
target interface{}
}
// NewInterceptor creates an interceptor for the specified target.
func NewInterceptor(target interface{}) *Interceptor {
return &Interceptor{
config: make(map[string]*stdConfig),
target: target,
}
}
// Config returns a configuration object for the specified function.
// Config can be used to manipulate the behavior of the target function.
func (i *Interceptor) Config(name string) Config {
m := resolveMethod(name, i.target)
if config, ok := i.config[name]; ok {
return config
}
config := &stdConfig{
impl: func(args ...interface{}) []interface{} {
return invokeTarget(i.target, m, name, args...)
},
}
i.config[name] = config
return config
}
// Call invokes the configured target and returns the returns the results.
func (i *Interceptor) Call(name string, args ...interface{}) []interface{} {
m := resolveMethod(name, i.target)
if config, ok := i.config[name]; ok {
return config.impl(args...)
}
return invokeTarget(i.target, m, name, args...)
}
func resolveMethod(name string, target interface{}) reflect.Value {
tv := reflect.ValueOf(target)
m := tv.MethodByName(name)
if !m.IsValid() {
panic(fmt.Errorf("method not found %s", name))
}
return m
}
func invokeTarget(target interface{}, method reflect.Value, name string, args ...interface{}) []interface{} {
in := make([]reflect.Value, 0, len(args))
for _, v := range args {
in = append(in, reflect.ValueOf(v))
}
ov := method.Call(in)
out := make([]interface{}, 0, len(ov))
for _, v := range ov {
out = append(out, v.Interface())
}
return out
}
<file_sep>/cmd/build.go
/*
Copyright 2018 MBT Authors.
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 cmd
import (
"errors"
"github.com/sirupsen/logrus"
"github.com/mbtproject/mbt/lib"
"github.com/spf13/cobra"
)
func init() {
buildPr.Flags().StringVar(&src, "src", "", "Source branch")
buildPr.Flags().StringVar(&dst, "dst", "", "Destination branch")
buildDiff.Flags().StringVar(&from, "from", "", "From commit")
buildDiff.Flags().StringVar(&to, "to", "", "To commit")
buildLocal.Flags().BoolVarP(&all, "all", "a", false, "All modules")
buildLocal.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
buildLocal.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
buildCommit.Flags().BoolVarP(&content, "content", "c", false, "Build the modules impacted by the content of the commit")
buildCommit.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
buildCommit.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
buildBranch.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
buildBranch.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
buildHead.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
buildHead.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
buildCommand.AddCommand(buildBranch)
buildCommand.AddCommand(buildPr)
buildCommand.AddCommand(buildDiff)
buildCommand.AddCommand(buildHead)
buildCommand.AddCommand(buildCommit)
buildCommand.AddCommand(buildLocal)
RootCmd.AddCommand(buildCommand)
}
var buildHead = &cobra.Command{
Use: "head",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
return summarise(system.BuildCurrentBranch(&lib.FilterOptions{Name: name, Fuzzy: fuzzy}, lib.CmdOptionsWithStdIO(buildStageCB)))
}),
}
var buildBranch = &cobra.Command{
Use: "branch <branch>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
branch := "master"
if len(args) > 0 {
branch = args[0]
}
return summarise(system.BuildBranch(branch, &lib.FilterOptions{Name: name, Fuzzy: fuzzy}, lib.CmdOptionsWithStdIO(buildStageCB)))
}),
}
var buildPr = &cobra.Command{
Use: "pr --src <branch> --dst <branch>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if src == "" {
return errors.New("requires source")
}
if dst == "" {
return errors.New("requires dest")
}
return summarise(system.BuildPr(src, dst, lib.CmdOptionsWithStdIO(buildStageCB)))
}),
}
var buildDiff = &cobra.Command{
Use: "diff --from <sha> --to <sha>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if from == "" {
return errors.New("requires from commit")
}
if to == "" {
return errors.New("requires to commit")
}
return summarise(system.BuildDiff(from, to, lib.CmdOptionsWithStdIO(buildStageCB)))
}),
}
var buildCommit = &cobra.Command{
Use: "commit <sha>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("requires the commit sha")
}
commit := args[0]
if content {
return summarise(system.BuildCommitContent(commit, lib.CmdOptionsWithStdIO(buildStageCB)))
}
return summarise(system.BuildCommit(commit, &lib.FilterOptions{Name: name, Fuzzy: fuzzy}, lib.CmdOptionsWithStdIO(buildStageCB)))
}),
}
var buildLocal = &cobra.Command{
Use: "local [--all]",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if all || name != "" {
return summarise(system.BuildWorkspace(&lib.FilterOptions{Name: name, Fuzzy: fuzzy}, lib.CmdOptionsWithStdIO(buildStageCB)))
}
return summarise(system.BuildWorkspaceChanges(lib.CmdOptionsWithStdIO(buildStageCB)))
}),
}
func buildStageCB(a *lib.Module, s lib.CmdStage, err error) {
switch s {
case lib.CmdStageBeforeBuild:
logrus.Infof("BUILD %s in %s for %s", a.Name(), a.Path(), a.Version())
case lib.CmdStageSkipBuild:
logrus.Infof("SKIP %s in %s for %s", a.Name(), a.Path(), a.Version())
}
}
func summarise(summary *lib.BuildSummary, err error) error {
if err == nil {
logrus.Infof("Modules: %v Built: %v Skipped: %v",
len(summary.Manifest.Modules),
len(summary.Completed),
len(summary.Skipped))
logrus.Infof("Build finished for commit %v", summary.Manifest.Sha)
}
return err
}
var buildCommand = &cobra.Command{
Use: "build",
Short: docText("build-summary"),
Long: docText("build"),
}
<file_sep>/lib/build_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"testing"
git "github.com/libgit2/git2go/v28"
"github.com/mbtproject/mbt/e"
"github.com/stretchr/testify/assert"
)
//noinspection GoUnusedParameter
func noopCb(a *Module, s CmdStage, err error) {}
func stdTestCmdOptions(buff *bytes.Buffer) *CmdOptions {
var stdout io.Writer = buff
var stderr io.Writer = buff
if buff == nil {
stdout = os.Stdout
stderr = os.Stderr
}
return &CmdOptions{Callback: noopCb, Stdin: os.Stdin, Stdout: stdout, Stderr: stderr}
}
func TestBuildExecution(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo app-a built"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host \"app-a built\""))
check(t, repo.Commit("first"))
stages := make([]CmdStage, 0)
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildCurrentBranch(NoFilter, &CmdOptions{
Callback: func(a *Module, s CmdStage, err error) {
stages = append(stages, s)
},
Stdin: os.Stdin,
Stdout: stdout,
Stderr: stderr,
})
check(t, err)
assert.Equal(t, "app-a built\n", stdout.String())
assert.EqualValues(t, []CmdStage{CmdStageBeforeBuild, CmdStageAfterBuild}, stages)
}
func TestBuildDirExecution(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo app-a built"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host \"app-a built\""))
check(t, repo.Commit("first"))
stages := make([]CmdStage, 0)
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildWorkspace(NoFilter, &CmdOptions{
Callback: func(a *Module, s CmdStage, err error) {
stages = append(stages, s)
},
Stdin: os.Stdin,
Stdout: stdout,
Stderr: stderr,
})
check(t, err)
assert.Equal(t, "app-a built\n", stdout.String())
assert.EqualValues(t, []CmdStage{CmdStageBeforeBuild, CmdStageAfterBuild}, stages)
}
func TestBuildSkip(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
switch runtime.GOOS {
case "linux", "darwin":
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Build: map[string]*Cmd{"windows": {"powershell", []string{"-ExecutionPolicy", "Bypass", "-File", ".\\build.ps1"}}},
}))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
case "windows":
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Build: map[string]*Cmd{"darwin": {"./build.sh", []string{}}},
}))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
}
check(t, repo.Commit("first"))
skipped := make([]string, 0)
other := make([]string, 0)
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildCurrentBranch(NoFilter, &CmdOptions{
Callback: func(a *Module, s CmdStage, err error) {
if s == CmdStageSkipBuild {
skipped = append(skipped, a.Name())
} else {
other = append(other, a.Name())
}
},
Stdin: os.Stdin,
Stdout: buff,
Stderr: buff,
})
check(t, err)
assert.EqualValues(t, []string{"app-a"}, skipped)
assert.EqualValues(t, []string{}, other)
}
func TestBuildBranch(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
check(t, repo.Commit("second"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildBranch("master", NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-a\n", buff.String())
buff = new(bytes.Buffer)
_, err = NewWorld(t, ".tmp/repo").System.BuildBranch("feature", NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-a\nbuilt app-b\n", buff.String())
}
func TestBuildDiff(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
check(t, repo.SwitchToBranch("feature"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildDiff(c1.String(), c2.String(), stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-b\n", buff.String())
buff = new(bytes.Buffer)
_, err = NewWorld(t, ".tmp/repo").System.BuildDiff(c2.String(), c1.String(), stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "", buff.String())
}
func TestBuildPr(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
check(t, repo.Commit("second"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildPr("feature", "master", stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-b\n", buff.String())
buff = new(bytes.Buffer)
_, err = NewWorld(t, ".tmp/repo").System.BuildPr("master", "feature", stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "", buff.String())
}
func TestBuildWorkspaceWithNameFilter(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildWorkspace(&FilterOptions{Name: "app-a", Fuzzy: true}, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-a\n", buff.String())
}
func TestBuildWorkspaceWithMultipleNameFilters(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
check(t, repo.InitModule("app-c"))
check(t, repo.WriteShellScript("app-c/build.sh", "echo built app-c"))
check(t, repo.WritePowershellScript("app-c/build.ps1", "write-host built app-c"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildWorkspace(&FilterOptions{Name: "app-a,app-c", Fuzzy: true}, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-a\nbuilt app-c\n", buff.String())
}
func TestBuildWorkspaceWithNameFiltersMatchingSameModule(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildWorkspace(&FilterOptions{Name: "app-a,app-a", Fuzzy: true}, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-a\n", buff.String())
}
func TestBuildWorkspaceWithNameFilterThatDoesNotMatchAnyModule(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildWorkspace(&FilterOptions{Name: "app-c", Fuzzy: true}, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "", buff.String())
}
func TestBuildWorkspace(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildWorkspace(NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-a\nbuilt app-b\n", buff.String())
}
func TestBuildWorkspaceChanges(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildWorkspaceChanges(stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-b\n", buff.String())
}
func TestBuildBranchForManifestFailure(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByBranch").Return(nil, errors.New("doh"))
_, err := w.System.BuildBranch("master", NoFilter, stdTestCmdOptions(nil))
assert.EqualError(t, err, "doh")
}
func TestBuildPrForManifestFailure(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByPr").Return(nil, errors.New("doh"))
_, err := w.System.BuildPr("feature", "master", stdTestCmdOptions(nil))
assert.EqualError(t, err, "doh")
}
func TestBuildDiffForManifestFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
c := repo.LastCommit.String()
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByDiff").Return(nil, errors.New("doh"))
_, err := w.System.BuildDiff(c, c, stdTestCmdOptions(nil))
assert.EqualError(t, err, "doh")
}
func TestBuildCurrentBranchManifestFailure(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByCurrentBranch").Return(nil, errors.New("doh"))
_, err := w.System.BuildCurrentBranch(NoFilter, stdTestCmdOptions(nil))
assert.EqualError(t, err, "doh")
}
func TestBuildCommitForManifestFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
c := repo.LastCommit.String()
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByCommit").Return(nil, errors.New("doh"))
_, err := w.System.BuildCommit(c, NoFilter, stdTestCmdOptions(nil))
assert.EqualError(t, err, "doh")
}
func TestBuildWorkspaceForManifestFailure(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByWorkspace").Return(nil, errors.New("doh"))
_, err := w.System.BuildWorkspace(NoFilter, stdTestCmdOptions(nil))
assert.EqualError(t, err, "doh")
}
func TestBuildWorkspaceChangesForManifestFailure(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByWorkspaceChanges").Return(nil, errors.New("doh"))
_, err := w.System.BuildWorkspaceChanges(stdTestCmdOptions(nil))
assert.EqualError(t, err, "doh")
}
func TestDirtyWorkingDir(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/foo", "a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.WriteContent("app-a/foo", "b"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildCurrentBranch(NoFilter, stdTestCmdOptions(buff))
assert.Error(t, err)
assert.Equal(t, msgDirtyWorkingDir, err.Error())
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestBuildEnvironment(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Build: map[string]*Cmd{
"linux": {Cmd: "./build.sh"},
"darwin": {Cmd: "./build.sh"},
"windows": {Cmd: "powershell", Args: []string{"-ExecutionPolicy", "Bypass", "-File", ".\\build.ps1"}},
},
Properties: map[string]interface{}{"foo": "bar"},
}))
check(t, repo.WriteShellScript("app-a/build.sh", "echo $MBT_BUILD_COMMIT-$MBT_MODULE_VERSION-$MBT_MODULE_NAME-$MBT_MODULE_PATH-$MBT_REPO_PATH-$MBT_MODULE_PROPERTY_FOO"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host $Env:MBT_BUILD_COMMIT-$Env:MBT_MODULE_VERSION-$Env:MBT_MODULE_NAME-$Env:MBT_MODULE_PATH-$Env:MBT_REPO_PATH-$Env:MBT_MODULE_PROPERTY_FOO"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByCurrentBranch()
check(t, err)
buff := new(bytes.Buffer)
_, err = NewWorld(t, ".tmp/repo").System.BuildCurrentBranch(NoFilter, stdTestCmdOptions(buff))
check(t, err)
expectedRepoPath, err := filepath.Abs(".tmp/repo")
check(t, err)
out := buff.String()
assert.Equal(t, fmt.Sprintf("%s-%s-%s-%s-%s-%s\n", m.Sha, m.Modules[0].Version(), m.Modules[0].Name(), m.Modules[0].Path(), expectedRepoPath, m.Modules[0].Properties()["foo"]), out)
}
func TestDefaultBuild(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Build: map[string]*Cmd{"default": {Cmd: "echo", Args: []string{"hello"}}},
}))
check(t, repo.Commit("first"))
_, err := NewWorld(t, ".tmp/repo").System.ManifestByCurrentBranch()
check(t, err)
buff := new(bytes.Buffer)
_, err = NewWorld(t, ".tmp/repo").System.BuildCurrentBranch(NoFilter, stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "hello\n", buff.String())
}
func TestDefaultBuildOverride(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Build: map[string]*Cmd{
"default": {Cmd: "doh"},
"windows": {Cmd: "powershell", Args: []string{"-ExecutionPolicy", "Bypass", "-File", ".\\build.ps1"}},
"darwin": {Cmd: "./build.sh"},
"linux": {Cmd: "./build.sh"},
},
}))
check(t, repo.WriteShellScript("app-a/build.sh", "echo foo"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host bar"))
check(t, repo.Commit("first"))
_, err := NewWorld(t, ".tmp/repo").System.ManifestByCurrentBranch()
check(t, err)
buff := new(bytes.Buffer)
_, err = NewWorld(t, ".tmp/repo").System.BuildCurrentBranch(NoFilter, stdTestCmdOptions(buff))
check(t, err)
out := buff.String()
if runtime.GOOS == "windows" {
assert.Equal(t, "bar\n", out)
} else {
assert.Equal(t, "foo\n", out)
}
}
func TestBuildEnvironmentForAbsPath(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Build: map[string]*Cmd{
"linux": {Cmd: "./build.sh"},
"darwin": {Cmd: "./build.sh"},
"windows": {Cmd: "powershell", Args: []string{"-ExecutionPolicy", "Bypass", "-File", ".\\build.ps1"}},
},
Properties: map[string]interface{}{"foo": "bar"},
}))
check(t, repo.WriteShellScript("app-a/build.sh", "echo $MBT_BUILD_COMMIT-$MBT_MODULE_VERSION-$MBT_MODULE_NAME-$MBT_MODULE_PATH-$MBT_REPO_PATH-$MBT_MODULE_PROPERTY_FOO"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host $Env:MBT_BUILD_COMMIT-$Env:MBT_MODULE_VERSION-$Env:MBT_MODULE_NAME-$Env:MBT_MODULE_PATH-$Env:MBT_REPO_PATH-$Env:MBT_MODULE_PROPERTY_FOO"))
check(t, repo.Commit("first"))
expectedRepoPath, err := filepath.Abs(".tmp/repo")
check(t, err)
m, err := NewWorld(t, expectedRepoPath).System.ManifestByCurrentBranch()
check(t, err)
buff := new(bytes.Buffer)
_, err = NewWorld(t, ".tmp/repo").System.BuildCurrentBranch(NoFilter, stdTestCmdOptions(buff))
check(t, err)
out := buff.String()
assert.Equal(t, fmt.Sprintf("%s-%s-%s-%s-%s-%s\n", m.Sha, m.Modules[0].Version(), m.Modules[0].Name(), m.Modules[0].Path(), expectedRepoPath, m.Modules[0].Properties()["foo"]), out)
}
func TestBadSha(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
_, err := NewWorld(t, ".tmp/repo").System.BuildCommit("a", NoFilter, stdTestCmdOptions(nil))
assert.EqualError(t, err, fmt.Sprintf(msgInvalidSha, "a"))
assert.EqualError(t, (err.(*e.E)).InnerError(), "encoding/hex: odd length hex string")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestMissingSha(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
sha := "22221c5e56794a2af5f59f94512df4c669c77a49"
_, err := NewWorld(t, ".tmp/repo").System.BuildCommit(sha, NoFilter, stdTestCmdOptions(nil))
assert.EqualError(t, err, fmt.Sprintf(msgCommitShaNotFound, sha))
assert.EqualError(t, (err.(*e.E)).InnerError(), "object not found - no match for id (22221c5e56794a2af5f59f94512df4c669c77a49)")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestBuildCommitContent(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.WriteShellScript("app-b/build.sh", "echo built app-b"))
check(t, repo.WritePowershellScript("app-b/build.ps1", "write-host built app-b"))
check(t, repo.Commit("second"))
buff := new(bytes.Buffer)
_, err := NewWorld(t, ".tmp/repo").System.BuildCommitContent(repo.LastCommit.String(), stdTestCmdOptions(buff))
check(t, err)
assert.Equal(t, "built app-b\n", buff.String())
}
func TestBuildCommitContentForManifestFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.ManifestBuilder.Interceptor.Config("ByCommitContent").Return((*Manifest)(nil), errors.New("doh"))
buff := new(bytes.Buffer)
_, err := w.System.BuildCommitContent(repo.LastCommit.String(), stdTestCmdOptions(buff))
assert.EqualError(t, err, "doh")
}
func TestRestorationOfPristineWorkspace(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.WriteContent("app-a/foo", "bar1"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.AppendContent("app-a/foo", "bar2"))
check(t, repo.AppendContent("app-a/foo2", "bar1"))
check(t, repo.Commit("second"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.AppendContent("app-a/foo", "bar3"))
check(t, repo.AppendContent("app-a/foo2", "bar2"))
check(t, repo.Commit("third"))
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
_, err := w.System.BuildBranch("feature", NoFilter, stdTestCmdOptions(buff))
check(t, err)
status, err := repo.Repo.StatusList(&git.StatusOptions{
Flags: git.StatusOptIncludeUntracked,
})
check(t, err)
statusEntriesCount, err := status.EntryCount()
check(t, err)
assert.Equal(t, 0, statusEntriesCount)
head, err := repo.Repo.Head()
check(t, err)
assert.Equal(t, "refs/heads/master", head.Name())
}
func TestBuildingDetachedHead(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "echo built app-a"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "write-host built app-a"))
check(t, repo.WriteContent("app-a/foo", "bar1"))
check(t, repo.Commit("first"))
first := repo.LastCommit
check(t, repo.SwitchToBranch("feature"))
check(t, repo.AppendContent("app-a/foo", "bar2"))
check(t, repo.AppendContent("app-a/foo2", "bar1"))
check(t, repo.Commit("second"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.AppendContent("app-a/foo", "bar3"))
check(t, repo.AppendContent("app-a/foo2", "bar2"))
check(t, repo.Commit("third"))
check(t, repo.CheckoutAndDetach(first.String()))
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
_, err := w.System.BuildBranch("feature", NoFilter, stdTestCmdOptions(buff))
check(t, err)
status, err := repo.Repo.StatusList(&git.StatusOptions{
Flags: git.StatusOptIncludeUntracked,
})
check(t, err)
statusEntriesCount, err := status.EntryCount()
check(t, err)
assert.Equal(t, 0, statusEntriesCount)
detached, err := repo.Repo.IsHeadDetached()
check(t, err)
assert.True(t, detached)
}
func TestRestorationOnBuildFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteShellScript("app-a/build.sh", "exit 1"))
check(t, repo.WritePowershellScript("app-a/build.ps1", "throw \"foo\""))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.AppendContent("app-a/foo", "bar2"))
check(t, repo.AppendContent("app-a/foo2", "bar1"))
check(t, repo.Commit("second"))
w := NewWorld(t, ".tmp/repo")
buff := new(bytes.Buffer)
_, err := w.System.BuildBranch("feature", NoFilter, stdTestCmdOptions(buff))
assert.EqualError(t, err, fmt.Sprintf(msgFailedBuild, "app-a"))
idx, err := repo.Repo.Index()
check(t, err)
diff, err := repo.Repo.DiffIndexToWorkdir(idx, &git.DiffOptions{
Flags: git.DiffIncludeUntracked | git.DiffRecurseUntracked,
})
check(t, err)
numDeltas, err := diff.NumDeltas()
check(t, err)
assert.Equal(t, 0, numDeltas)
}
<file_sep>/lib/module.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"github.com/mbtproject/mbt/e"
"github.com/mbtproject/mbt/graph"
)
// Name returns the name of the module.
func (a *Module) Name() string {
return a.metadata.spec.Name
}
// Path returns the relative path to module.
func (a *Module) Path() string {
return a.metadata.dir
}
// Build returns the build configuration for the module.
func (a *Module) Build() map[string]*Cmd {
return a.metadata.spec.Build
}
// Commands returns a list of user defined commands in the spec.
func (a *Module) Commands() map[string]*UserCmd {
return a.metadata.spec.Commands
}
// Properties returns the custom properties in the configuration.
func (a *Module) Properties() map[string]interface{} {
return a.metadata.spec.Properties
}
// Requires returns an array of modules required by this module.
func (a *Module) Requires() Modules {
return a.requires
}
// RequiredBy returns an array of modules requires this module.
func (a *Module) RequiredBy() Modules {
return a.requiredBy
}
// Version returns the content based version SHA for the module.
func (a *Module) Version() string {
return a.version
}
// Hash for the content of this module.
func (a *Module) Hash() string {
return a.metadata.hash
}
// FileDependencies returns the list of file dependencies this module has.
func (a *Module) FileDependencies() []string {
return a.metadata.spec.FileDependencies
}
type requiredByNodeProvider struct{}
func (p *requiredByNodeProvider) ID(vertex interface{}) interface{} {
return vertex.(*Module).Name()
}
func (p *requiredByNodeProvider) ChildCount(vertex interface{}) int {
return len(vertex.(*Module).RequiredBy())
}
func (p *requiredByNodeProvider) Child(vertex interface{}, index int) (interface{}, error) {
return vertex.(*Module).RequiredBy()[index], nil
}
type requiresNodeProvider struct{}
func (p *requiresNodeProvider) ID(vertex interface{}) interface{} {
return vertex.(*Module).Name()
}
func (p *requiresNodeProvider) ChildCount(vertex interface{}) int {
return len(vertex.(*Module).Requires())
}
func (p *requiresNodeProvider) Child(vertex interface{}, index int) (interface{}, error) {
return vertex.(*Module).Requires()[index], nil
}
func newModule(metadata *moduleMetadata, requires Modules) *Module {
mod := &Module{
requires: Modules{},
requiredBy: Modules{},
metadata: metadata,
}
if requires != nil {
mod.requires = requires
}
for _, d := range requires {
d.requiredBy = append(d.requiredBy, mod)
}
return mod
}
func (l Modules) indexByName() map[string]*Module {
q := make(map[string]*Module)
for _, a := range l {
q[a.Name()] = a
}
return q
}
func (l Modules) indexByPath() map[string]*Module {
q := make(map[string]*Module)
for _, a := range l {
q[a.Path()] = a
}
return q
}
// expandRequiredByDependencies takes a list of Modules and
// returns a new list of Modules including the ones in their
// requiredBy (see below) dependency chain.
// requiredBy dependency
// Module dependencies are described in two forms requires and requiredBy.
// If A needs B, then, A requires B and B is requiredBy A.
func (l Modules) expandRequiredByDependencies() (Modules, error) {
// Step 1
// Create the new list with all nodes
g := make([]interface{}, 0, len(l))
for _, a := range l {
g = append(g, a)
}
// Step 2
// Top sort it by requiredBy chain.
allItems, err := graph.TopSort(&requiredByNodeProvider{}, g...)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
// Step 3
// Copy resulting array in the reverse order
// because we top sorted by requiredBy chain.
r := make([]*Module, len(allItems))
i := len(allItems) - 1
for _, ele := range allItems {
r[i] = ele.(*Module)
i--
}
return r, nil
}
// expandRequiresDependencies takes a list of Modules and
// returns a new list of Modules including the ones in their
// requires (see below) dependency chain.
// requires dependency
// Module dependencies are described in two forms requires and requiredBy.
// If A needs B, then, A requires B and B is requiredBy A.
func (l Modules) expandRequiresDependencies() (Modules, error) {
g := make([]interface{}, 0, len(l))
for _, a := range l {
g = append(g, a)
}
items, err := graph.TopSort(&requiresNodeProvider{}, g...)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
r := make([]*Module, len(items))
i := 0
for _, ele := range items {
r[i] = ele.(*Module)
i++
}
return r, nil
}
<file_sep>/lib/mbt_error.go
/*
Copyright 2018 MBT Authors.
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 lib
const (
// ErrClassNone Not specified
ErrClassNone = iota
// ErrClassUser is a user error that can be corrected
ErrClassUser
// ErrClassInternal is an internal error potentially due to a bug
ErrClassInternal
)
<file_sep>/e/e.go
/*
Copyright 2018 MBT Authors.
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 e
import (
"fmt"
"runtime"
"strings"
)
// E is a container for errors.
// In addition to the standard error message, it also contains the
// stack trace and a few other important attributes.
type E struct {
message string
innerError error
class int
stack []runtime.Frame
showExtendedInfo bool
}
func (e *E) Error() string {
s := e.message
if s == "" && e.innerError != nil {
s = e.innerError.Error()
}
if e.showExtendedInfo {
innerErr := ""
if e.innerError != nil {
innerErr = e.innerError.Error()
}
stack := make([]string, 0, len(e.stack))
for _, f := range e.stack {
stack = append(stack, fmt.Sprintf("%s %s(%v)", f.Function, f.File, f.Line))
}
return fmt.Sprintf(`%s
inner error: %s
call stack:
%s
`, s, innerErr, strings.Join(stack, "\n"))
}
return s
}
// InnerError returns the inner error wrapped in this error if there's one.
func (e *E) InnerError() error {
return e.innerError
}
// Class returns the class of this error.
func (e *E) Class() int {
return e.class
}
// Stack returns the callstack (up to 32 frames) indicating where the
// error occurred
func (e *E) Stack() []runtime.Frame {
return e.stack
}
// WithExtendedInfo returns a new instance of E which prints the
// additional details such as callstack.
func (e *E) WithExtendedInfo() *E {
return &E{
class: e.class,
innerError: e.innerError,
message: e.message,
showExtendedInfo: true,
stack: e.stack,
}
}
// NewError creates a new E
func NewError(klass int, message string) *E {
return newE(klass, nil, message)
}
// NewErrorf creates a new E with an interpolated message
func NewErrorf(klass int, message string, args ...interface{}) *E {
return newE(klass, nil, message, args...)
}
// Wrap creates a new E that wraps another error
func Wrap(klass int, innerError error) *E {
if wrapped, ok := innerError.(*E); ok {
return wrapped
}
return newE(klass, innerError, "")
}
// Wrapf creates a new wrapped E with an interpolated message
func Wrapf(klass int, innerError error, message string, args ...interface{}) *E {
return newE(klass, innerError, message, args...)
}
// Failf panics with a wrapped E containing an interpolated message
func Failf(klass int, innerError error, message string, args ...interface{}) {
panic(Wrapf(klass, innerError, message, args...))
}
func newE(klass int, innerError error, message string, args ...interface{}) *E {
m := fmt.Sprintf(message, args...)
pc := make([]uintptr, 32 /*limit the number of frames to 32 max*/)
n := runtime.Callers(2, pc)
frames := make([]runtime.Frame, 0, n)
rframes := runtime.CallersFrames(pc[:n])
for {
f, more := rframes.Next()
frames = append(frames, f)
if !more {
break
}
}
return &E{class: klass, message: m, innerError: innerError, stack: frames}
}
<file_sep>/cmd/doc.go
/*
Copyright 2018 MBT Authors.
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 cmd
import (
"bytes"
"fmt"
"os"
"text/template"
)
var templates = map[string]string{
"main-summary": `mbt - The most flexible build orchestration tool for monorepo`,
"main": `mbt is a build orchestration utility for monorepo.
In mbt, we use the term {{c "module"}} to identify an independently buildable unit of code.
A collection of modules stored in a repository is called a manifest.
You can turn any directory into a module by placing a spec file called {{c ".mbt.yml"}}.
Spec file is written in {{c "yaml" }} following the schema specified below.
{{c "" }}
name: Unique module name (required)
build: Dictionary of build commands specific to a platform (optional)
default: (optional)
cmd: Default command to run when os specific command is not found (required)
args: Array of arguments to default build command (optional)
linux|darwin|windows:
cmd: Operating system specific command name (required)
args: Array of arguments (optional)
dependencies: An array of modules that this module's build depend on (optional)
fileDependencies: An array of file names that this module's build depend on (optional)
commands: Optional dictionary of custom commands (optional)
name:
cmd: Command name (required)
args: Array of arguments (optional)
os: Array of os identifiers where this command should run (optional)
properties: Custom dictionary to hold any module specific information (optional)
{{c ""}}
{{h2 "Build Command"}}
Build command is operating system specific. When executing {{c "mbt build xxx" }}
commands, it skips the modules that do not specify a build command for the operating
system build is running on.
Full list of operating systems names that can be used can be
found {{link "here" "https://golang.org/doc/install/source#environment"}}
When the command is applicable for multiple operating systems, you could list it as
the default command. Operating system specific commands take precedence.
{{h2 "Dependencies"}}
{{ c "mbt"}} comes with a set of primitives to manage build dependencies. Current build
tools do a good job in managing dependencies between source files/projects.
GNU {{c "make" }} for example does a great job in deciding what parts require building.
{{c "mbt"}} dependencies work one level above that type of tooling to manage build
relationship between two independent modules.
{{h2 "Module Dependencies"}}
One advantage of a single repo is that you can share code between multiple modules
more effectively. Building this type of dependencies requires some thought. mbt provides
an easy way to define dependencies between modules and automatically builds the impacted modules
in topological order.
Dependencies are defined in {{c ".mbt.yml" }} file under 'dependencies' property.
It accepts an array of module names.
For example, {{ c "module-a" }} could define a dependency on {{c "module-b" }},
so that any time {{c "module-b"}} is changed, build command for {{c "module-a" }} is also executed.
An example of where this could be useful is, shared libraries. Shared library
could be developed independently of its consumers. However, all consumers
are automatically built whenever the shared library is modified.
{{h2 "File Dependencies"}}
File dependencies are useful in situations where a module should be built
when a file(s) stored outside the module directory is modified. For instance,
a build script that is used to build multiple modules could define a file
dependency in order to trigger the build whenever there's a change in build.
File dependencies should specify the path of the file relative to the root
of the repository.
{{h2 "Module Version"}}
For each module stored within a repository, {{c "mbt"}} generates a unique
stable version string. It is calculated based on three source attributes in
module.
- Content stored within the module directory
- Versions of dependent modules
- Content of file dependencies
As a result, version of a module is changed only when any of those attributes
are changed making it a safe attribute to use for tagging the
build artifacts (i.e. tar balls, container images).
{{h2 "Document Generation"}}
{{ c "mbt" }} has a powerful feature that exposes the module state inferred from
the repository to a template engine. This could be quite useful for generating
documents out of that information. For example, you may have several modules
packaged as docker containers. By using this feature, you could generate a
Kubernetes deployment specification for all of them as of a particular commit
sha.
See {{c "apply"}} command for more details.
`,
"apply-summary": `Apply repository manifest over a go template`,
"apply": `{{cli "Apply repository manifest over a go template\n" }}
{{c "mbt apply branch [name] --to <path>"}}{{br}}
Apply the manifest of the tip of the branch to a template.
Template path should be relative to the repository root and must be available
in the commit tree. Assume master if name is not specified.
{{c "mbt apply commit <commit> --to <path>"}}{{br}}
Apply the manifest of a commit to a template.
Template path should be relative to the repository root and must be available
in the commit tree.
{{c "mbt apply head --to <path>"}}{{br}}
Apply the manifest of current head to a template.
Template path should be relative to the repository root and must be available
in the commit tree.
{{c "mbt apply local --to <path>"}}{{br}}
Apply the manifest of local workspace to a template.
Template path should be relative to the repository root and must be available
in the workspace.
{{h2 "Template Helpers"}}
Following helper functions are available when writing templates.
{{ c "module <name>" }}{{br}}
Find the specified module from modules set discovered in the repo.
{{ c "property <module> <name>" }}{{br}}
Find the specified property in the given module. Standard dot notation can be used to access nested properties (e.g. {{ c "a.b.c" }}).
{{ c "propertyOr <module> <name> <default>" }}{{br}}
Find specified property in the given module or return the designated default value.
{{ c "contains <array> <item>" }}{{br}}
Return true if the given item is present in the array.
{{ c "join <array> <format> <separator>" }}{{br}}
Format each item in the array according the format specified and then join them with the specified separator.
{{ c "kvplist <map>" }}{{br}}
Take a map of {{ c "map[string]interface{}" }} and return the items in the map as a list of key/value pairs sorted by the key. They can be accessed via {{ c ".Key" }} and {{ c ".Value" }} properties.
{{ c "add <int> <int>" }}{{br}}
Add two integers.
{{ c "sub <int> <int>" }}{{br}}
Subtract two integers.
{{ c "mul <int> <int>" }}{br}
Multiply two integers.
{{ c "div <int> <int>" }}{{br}}
Divide two integers.
{{ c "head <array|slice>" }}{{br}}
Select the first item in an array/slice. Return {{ c "\"\"" }} if the input is {{ c "nil" }} or an empty array/slice.
{{ c "tail <array|slice>" }}{{br}}
Select the last item in an array/slice. Return {{ c "\"\"" }} if the input is {{ c "nil" }} or an empty array/slice.
{{ c "ishead <array> <value>" }}{{br}}
Return true if the specified value is the head of the array/slice.
{{ c "istail <array> <value>" }}{{br}}
Return true if the specified value is the tail of the array/slice.
These functions can be pipelined to simplify complex template expressions. Below is an example of emitting the word "foo"
when module "app-a" has the value "a" in it's tags property.
`,
"build-summary": `Run build command`,
"build": `{{cli "Run build command \n"}}
{{c "mbt build branch [name] [--content] [--name <name>] [--fuzzy]"}}{{br}}
Build modules in a branch. Assume master if branch name is not specified.
Build just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt build commit <commit> [--content] [--name <name>] [--fuzzy]"}}{{br}}
Build modules in a commit. Full commit sha is required.
Build just the modules modified in the commit when {{c "--content"}} flag is used.
Build just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt build diff --from <commit> --to <commit>"}}{{br}}
Build modules changed between {{c "from"}} and {{c "to"}} commits.
In this mode, mbt works out the merge base between {{c "from"}} and {{c "to"}} and
evaluates the modules changed between the merge base and {{c "to"}}.
{{c "mbt build head [--content] [--name <name>] [--fuzzy]"}}{{br}}
Build modules in current head.
Build just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt build pr --src <name> --dst <name>"}}{{br}}
Build modules changed between {{c "--src"}} and {{c "--dst"}} branches.
In this mode, mbt works out the merge base between {{c "--src"}} and {{c "--dst"}} and
evaluates the modules changed between the merge base and {{c "--src"}}.
{{c "mbt build local [--all] [--content] [--name <name>] [--fuzzy]"}}{{br}}
Build modules modified in current workspace. All modules in the workspace are
built if {{c "--all"}} option is specified.
Build just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{h2 "Build Environment"}}
When executing build, following environment variables are initialised and can be
used by the command being executed.
- {{c "MBT_MODULE_NAME"}} Name of the module
- {{c "MBT_MODULE_PATH"}} Relative path to the module directory
- {{c "MBT_MODULE_VERSION"}} Module version
- {{c "MBT_BUILD_COMMIT"}} Git commit SHA of the commit being built
- {{c "MBT_REPO_PATH"}} Absolute path to the repository directory
In addition to the variables listed above, module properties are also populated
in the form of {{c "MBT_MODULE_PROPERTY_XXX"}} where {{c "XXX"}} denotes the key.
`,
"describe-summary": `Describe repository manifest`,
"describe": `{{cli "Describe repository manifest \n"}}
{{c "mbt describe branch [name] [--content] [--name <name>] [--fuzzy] [--graph] [--json]"}}{{br}}
Describe modules in a branch. Assume master if branch name is not specified.
Describe just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt describe commit <commit> [--content] [--name <name>] [--fuzzy] [--graph] [--json]"}}{{br}}
Describe modules in a commit. Full commit sha is required.
Describe just the modules modified in the commit when {{c "--content"}} flag is used.
Describe just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt describe diff --from <commit> --to <commit> [--graph] [--json]"}}{{br}}
Describe modules changed between {{c "from"}} and {{c "to"}} commits.
In this mode, mbt works out the merge base between {{c "from"}} and {{c "to"}} and
evaluates the modules changed between the merge base and {{c "to"}}.
{{c "mbt describe head [--content] [--name <name>] [--fuzzy] [--graph] [--json]"}}{{br}}
Describe modules in current head.
Describe just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt describe pr --src <name> --dst <name> [--graph] [--json]"}}{{br}}
Describe modules changed between {{c "--src"}} and {{c "--dst"}} branches.
In this mode, mbt works out the merge base between {{c "--src"}} and {{c "--dst"}} and
evaluates the modules changed between the merge base and {{c "--src"}}.
{{c "mbt describe local [--all] [--content] [--name <name>] [--fuzzy] [--graph] [--json]"}}{{br}}
Describe modules modified in current workspace. All modules in the workspace are
described if {{c "--all"}} option is specified.
Describe just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{h2 "Output Formats"}}
Use {{c "--graph"}} option to output the manifest in graphviz dot format. This can
be useful to visualise build dependencies.
Use {{c "--json"}} option to output the manifest in json format.
`,
"run-in-summary": `Run user defined command`,
"run-in": `{{cli "Run user defined command \n"}}
{{c "mbt run-in branch [name] [--content] [--name <name>] [--fuzzy]"}}{{br}}
Run user defined command in modules in a branch. Assume master if branch name is not specified.
Consider just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt run-in commit <commit> [--content] [--name <name>] [--fuzzy]"}}{{br}}
Run user defined command in modules in a commit. Full commit sha is required.
Consider just the modules modified in the commit when {{c "--content"}} flag is used.
Consider just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt run-in diff --from <commit> --to <commit>"}}{{br}}
Run user defined command in modules changed between {{c "from"}} and {{c "to"}} commits.
In this mode, mbt works out the merge base between {{c "from"}} and {{c "to"}} and
evaluates the modules changed between the merge base and {{c "to"}}.
{{c "mbt run-in head [--content] [--name <name>] [--fuzzy]"}}{{br}}
Run user defined command in modules in current head.
Consider just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{c "mbt run-in pr --src <name> --dst <name>"}}{{br}}
Run user defined command in modules changed between {{c "--src"}} and {{c "--dst"}} branches.
In this mode, mbt works out the merge base between {{c "--src"}} and {{c "--dst"}} and
evaluates the modules changed between the merge base and {{c "--src"}}.
{{c "mbt run-in local [--all] [--content] [--name <name>] [--fuzzy]"}}{{br}}
Run user defined command in modules modified in current workspace. All modules in the workspace are
considered if {{c "--all"}} option is specified.
Consider just the modules matching the {{c "--name"}} filter if specified.
Default {{c "--name"}} filter is a prefix match. You can change this to a subsequence
match by using {{c "--fuzzy"}} option.
{{h2 "Execution Environment"}}
When executing a command, following environment variables are initialised and can be
used by the command being executed.
{{c "MBT_MODULE_NAME"}} Name of the module
{{c "MBT_MODULE_VERSION"}} Module version
{{c "MBT_BUILD_COMMIT"}} Git commit SHA of the commit being built
In addition to the variables listed above, module properties are also populated
in the form of {{c "MBT_MODULE_PROPERTY_XXX"}} where {{c "XXX"}} denotes the key.
`,
}
func docText(name string) string {
templateString, ok := templates[name]
if !ok {
panic("template not found")
}
t := template.New(name)
t, err := augmentWithTemplateFuncs(t).Parse(templateString)
if err != nil {
panic(err)
}
return generateHelpText(t)
}
func augmentWithTemplateFuncs(t *template.Template) *template.Template {
heading := func(s string, level int) string {
if os.Getenv("MBT_DOC_GEN_MARKDOWN") == "1" {
prefix := ""
switch level {
case 1:
prefix = "##"
case 2:
prefix = "###"
default:
prefix = "####"
}
return fmt.Sprintf("%s %s\n", prefix, s)
}
line := ""
for i := 0; i < len(s); i++ {
line = line + "="
}
return fmt.Sprintf("%s\n%s", s, line)
}
return t.Funcs(template.FuncMap{
"c": func(s string) string {
if os.Getenv("MBT_DOC_GEN_MARKDOWN") != "1" {
return s
}
if s == "" {
return "```"
}
return fmt.Sprintf("`%s`", s)
},
"link": func(text, link string) string {
if os.Getenv("MBT_DOC_GEN_MARKDOWN") != "1" {
return fmt.Sprintf("%s %s", text, link)
}
return fmt.Sprintf("[%s](%s)", text, link)
},
"h1": func(s string) string {
return heading(s, 1)
},
"h2": func(s string) string {
return heading(s, 2)
},
"h3": func(s string) string {
return heading(s, 3)
},
"br": func() string {
if os.Getenv("MBT_DOC_GEN_MARKDOWN") == "1" {
return "<br>"
}
return ""
},
"cli": func(s string) string {
if os.Getenv("MBT_DOC_GEN_MARKDOWN") == "1" {
return ""
}
return s
},
})
}
func generateHelpText(t *template.Template) string {
buff := new(bytes.Buffer)
err := t.Execute(buff, nil)
if err != nil {
panic(err)
}
return buff.String()
}
<file_sep>/lib/dot_serializer.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"strings"
)
// SerializeAsDot converts specified modules into a dot graph
// that can be used for visualization with gv package.
func (mods Modules) SerializeAsDot() string {
paths := []string{}
for _, m := range mods {
if len(m.Requires()) == 0 {
paths = append(paths, fmt.Sprintf("\"%s\"", m.Name()))
} else {
for _, r := range m.Requires() {
paths = append(paths, fmt.Sprintf("\"%s\" -> \"%s\"", m.Name(), r.Name()))
}
}
}
return fmt.Sprintf(`digraph mbt {
node [shape=box fillcolor=powderblue style=filled fontcolor=black];
%s
}`, strings.Join(paths, "\n "))
}
// GroupedSerializeAsDot converts specified modules into a dot graph
// that can be used for visualization with gv package.
//
// This variant groups impacted modules in red, while plotting
// the rest of the graph in powderblue
func (mods Modules) GroupedSerializeAsDot() string {
auxiliaryPaths := []string{}
impactedPaths := []string{}
for _, m := range mods {
impactedPaths = append(impactedPaths, fmt.Sprintf("\"%s\"", m.Name()))
for _, r := range m.Requires() {
auxiliaryPaths = append(auxiliaryPaths, fmt.Sprintf("\"%s\" -> \"%s\"", m.Name(), r.Name()))
}
}
return fmt.Sprintf(`digraph mbt {
node [shape=box fillcolor=red style=filled fontcolor=black];
%s
node [shape=box fillcolor=powderblue style=filled fontcolor=black];
%s
}`, strings.Join(impactedPaths, "\n "), strings.Join(auxiliaryPaths, "\n "))
}
<file_sep>/scripts/gendoc.go
// +build ignore
package main
import (
"os"
"path"
"github.com/mbtproject/mbt/cmd"
"github.com/spf13/cobra/doc"
)
func main() {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
err = os.RemoveAll(path.Join(wd, "docs"))
if err != nil {
panic(err)
}
err = os.Mkdir(path.Join(wd, "docs"), 0755)
if err != nil {
panic(err)
}
err = doc.GenMarkdownTree(cmd.RootCmd, path.Join(wd, "docs"))
if err != nil {
panic(err)
}
err = os.Link(path.Join(wd, "docs", "mbt.md"), path.Join(wd, "docs", "index.md"))
if err != nil {
panic(err)
}
}
<file_sep>/lib/run_in.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"runtime"
"github.com/mbtproject/mbt/e"
)
func (s *stdSystem) RunInBranch(command, name string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByBranch(name)
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.checkoutAndRunManifest(command, m, options)
}
func (s *stdSystem) RunInPr(command, src, dst string, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByPr(src, dst)
if err != nil {
return nil, err
}
return s.checkoutAndRunManifest(command, m, options)
}
func (s *stdSystem) RunInDiff(command, from, to string, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByDiff(from, to)
if err != nil {
return nil, err
}
return s.checkoutAndRunManifest(command, m, options)
}
func (s *stdSystem) RunInCurrentBranch(command string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByCurrentBranch()
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.checkoutAndRunManifest(command, m, options)
}
func (s *stdSystem) RunInCommit(command, commit string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByCommit(commit)
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.checkoutAndRunManifest(command, m, options)
}
func (s *stdSystem) RunInCommitContent(command, commit string, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByCommitContent(commit)
if err != nil {
return nil, err
}
return s.checkoutAndRunManifest(command, m, options)
}
func (s *stdSystem) RunInWorkspace(command string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByWorkspace()
if err != nil {
return nil, err
}
m, err = m.ApplyFilters(filterOptions)
if err != nil {
return nil, err
}
return s.runManifest(command, m, options)
}
func (s *stdSystem) RunInWorkspaceChanges(command string, options *CmdOptions) (*RunResult, error) {
m, err := s.ManifestByWorkspaceChanges()
if err != nil {
return nil, err
}
return s.runManifest(command, m, options)
}
func (s *stdSystem) checkoutAndRunManifest(command string, m *Manifest, options *CmdOptions) (*RunResult, error) {
r, err := s.WorkspaceManager.CheckoutAndRun(m.Sha, func() (interface{}, error) {
return s.runManifest(command, m, options)
})
if err != nil {
return nil, err
}
return r.(*RunResult), nil
}
func (s *stdSystem) runManifest(command string, m *Manifest, options *CmdOptions) (*RunResult, error) {
completed := make([]*Module, 0)
skipped := make([]*Module, 0)
failed := make([]*CmdFailure, 0)
var err error
for _, a := range m.Modules {
cmd, canRun := s.canRunHere(command, a)
if !canRun || (err != nil && options.FailFast) {
skipped = append(skipped, a)
options.Callback(a, CmdStageSkipBuild, nil)
continue
}
options.Callback(a, CmdStageBeforeBuild, nil)
err = s.execCommand(cmd, m, a, options)
if err != nil {
failed = append(failed, &CmdFailure{Err: err, Module: a})
options.Callback(a, CmdStageFailedBuild, err)
} else {
completed = append(completed, a)
options.Callback(a, CmdStageAfterBuild, nil)
}
}
return &RunResult{Manifest: m, Failures: failed, Completed: completed, Skipped: skipped}, nil
}
func (s *stdSystem) execCommand(command *UserCmd, manifest *Manifest, module *Module, options *CmdOptions) error {
err := s.ProcessManager.Exec(manifest, module, options, command.Cmd, command.Args...)
if err != nil {
return e.Wrap(ErrClassUser, err)
}
return nil
}
func (s *stdSystem) canRunHere(command string, mod *Module) (*UserCmd, bool) {
c, ok := mod.Commands()[command]
if !ok {
return nil, false
}
if len(c.OS) == 0 {
return c, true
}
for _, os := range c.OS {
if os == runtime.GOOS {
return c, true
}
}
return nil, false
}
<file_sep>/lib/utils.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"os"
"path/filepath"
)
// GitRepoRoot returns path to a git repo reachable from
// the specified directory.
// If the specified directory itself is not a git repo,
// this function searches for it in the parent directory
// path.
func GitRepoRoot(dir string) (string, error) {
dir, err := filepath.Abs(dir)
if err != nil {
return "", err
}
root, err := filepath.Abs("/")
if err != nil {
return "", err
}
for {
test := filepath.Join(dir, ".git")
fi, err := os.Stat(test)
if err == nil && fi.IsDir() {
return dir, nil
}
if err != nil && !os.IsNotExist(err) {
return "", err
}
if dir == root {
return dir, nil
}
dir = filepath.Dir(dir)
}
}
<file_sep>/README.md

# mbt
>> The most flexible build orchestration tool for monorepo
[Documentation](https://mbtproject.github.io/mbt/) | [Twitter](https://twitter.com/mbtproject)
[](https://travis-ci.org/mbtproject/mbt)
[](https://ci.appveyor.com/project/mbtproject/mbt)
[](https://goreportcard.com/report/github.com/mbtproject/mbt)
[](https://coveralls.io/github/mbtproject/mbt)
## Features
- Differential Builds
- Content Based Versioning
- Build Dependency Management
- Dependency Visualisation
- Template Driven Deployments
## Status
mbt is production ready. We try our best to maintain semver.
Visit [Github issues](https://github.com/mbtproject/mbt/issues) for support.
## Install
```sh
curl -L -o /usr/local/bin/mbt [get the url for your target from the links below]
chmod +x /usr/local/bin/mbt
```
## Releases
### Stable
|OS |Download|
|-----------------|--------|
|darwin x86_64 |[](https://github.com/mbtproject/mbt/releases/latest/download/mbt_darwin_x86_64)|
|linux x86_64 |[](https://bintray.com/buddyspike/bin/mbt_linux_x86_64/_latestVersion)|
|windows |[](https://bintray.com/buddyspike/bin/mbt_windows_x86/_latestVersion)|
### Dev Channel
|OS |Download|
|-----------------|--------|
|darwin x86_64 |[](https://bintray.com/buddyspike/bin/mbt_dev_darwin_x86_64/_latestVersion)|
|linux x86_64 |[](https://bintray.com/buddyspike/bin/mbt_dev_linux_x86_64/_latestVersion)|
|windows |[](https://bintray.com/buddyspike/bin/mbt_dev_windows_x86/_latestVersion)|
## Building Locally
### Linux/OSX
- You need `cmake` and `pkg-config` (latest of course is preferred)
- Get the code `go get github.com/mbtproject/mbt`
- Change to source directory `cd $GOPATH/src/github.com/mbtproject/mbt`
If you haven't set `$GOPATH`, change it to `~/go` which is the default place used by `go get`.
See [this](https://golang.org/cmd/go/#hdr-GOPATH_environment_variable) for more information about `$GOPATH`
- Run `make build` to build and run all unit tests
- Run `make install` to install the binary in `$GOPATH/bin`
Make sure `$GOPATH/bin` is in your path in order to execute the binary
### Windows
Local builds on Windows is not currently supported.
However, the specifics can be found in our CI scripts (`appveyor.yml` and `build_win.bat`)
## Demo
[](https://asciinema.org/a/KJxXNgrTs9KZbVV4GYNN5DScC)
## Credits
`mbt` is powered by these awesome libraries
- [git2go](https://github.com/libgit2/git2go)
- [libgit2](https://github.com/libgit2/libgit2)
- [yaml](https://github.com/go-yaml/yaml)
- [cobra](https://github.com/spf13/cobra)
- [logrus](https://github.com/sirupsen/logrus)
Icons made by <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a>
<file_sep>/cmd/build_handler.go
/*
Copyright 2018 MBT Authors.
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 cmd
import (
"fmt"
"github.com/mbtproject/mbt/e"
"github.com/mbtproject/mbt/lib"
"github.com/spf13/cobra"
)
type handlerFunc func(command *cobra.Command, args []string) error
func buildHandler(handler handlerFunc) handlerFunc {
return func(command *cobra.Command, args []string) error {
err := handler(command, args)
if err == nil {
return nil
}
if ee, ok := err.(*e.E); ok {
if ee.Class() == lib.ErrClassInternal {
return fmt.Errorf(`An unexpected error occurred. See below for more details.
For support, create a new issue at https://github.com/mbtproject/mbt/issues
%v`, ee.WithExtendedInfo())
} else if debug {
return ee.WithExtendedInfo()
}
}
return err
}
}
<file_sep>/lib/intersection.go
/*
Copyright 2018 MBT Authors.
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 lib
func (s *stdSystem) IntersectionByCommit(first, second string) (Modules, error) {
c1, err := s.Repo.GetCommit(first)
if err != nil {
return nil, err
}
c2, err := s.Repo.GetCommit(second)
if err != nil {
return nil, err
}
return s.intersectionCore(c1, c2)
}
func (s *stdSystem) IntersectionByBranch(first, second string) (Modules, error) {
fc, err := s.Repo.BranchCommit(first)
if err != nil {
return nil, err
}
sc, err := s.Repo.BranchCommit(second)
if err != nil {
return nil, err
}
return s.intersectionCore(fc, sc)
}
func (s *stdSystem) intersectionCore(first, second Commit) (Modules, error) {
repo := s.Repo
discover := s.Discover
reducer := s.Reducer
base, err := repo.MergeBase(first, second)
if err != nil {
return nil, err
}
modules, err := discover.ModulesInCommit(first)
if err != nil {
return nil, err
}
diff, err := repo.Diff(first, base)
if err != nil {
return nil, err
}
firstSet, err := reducer.Reduce(modules, diff)
if err != nil {
return nil, err
}
firstSetWithDeps, err := firstSet.expandRequiresDependencies()
if err != nil {
return nil, err
}
modules, err = discover.ModulesInCommit(second)
if err != nil {
return nil, err
}
diff, err = repo.Diff(second, base)
if err != nil {
return nil, err
}
secondSet, err := reducer.Reduce(modules, diff)
if err != nil {
return nil, err
}
secondSetWithDeps, err := secondSet.expandRequiresDependencies()
if err != nil {
return nil, err
}
intersection := make(map[string]*Module)
firstMap := firstSet.indexByName()
secondMap := secondSet.indexByName()
merge := func(changesWithDependencies Modules, otherChanges map[string]*Module, intersection map[string]*Module) {
for _, mod := range changesWithDependencies {
if _, ok := otherChanges[mod.Name()]; ok {
intersection[mod.Name()] = mod
}
}
}
merge(firstSetWithDeps, secondMap, intersection)
merge(secondSetWithDeps, firstMap, intersection)
result := make([]*Module, len(intersection))
i := 0
for _, v := range intersection {
result[i] = v
i++
}
return result, nil
}
<file_sep>/cmd/root.go
/*
Copyright 2018 MBT Authors.
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 cmd
import (
"os"
"github.com/mbtproject/mbt/e"
"github.com/mbtproject/mbt/lib"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// Flags available to all commands.
var (
in string
src string
dst string
from string
to string
first string
second string
kind string
name string
command string
all bool
debug bool
content bool
fuzzy bool
failFast bool
system lib.System
)
func init() {
RootCmd.PersistentFlags().StringVar(&in, "in", "", "Path to repo")
RootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "Enable debug output")
}
// RootCmd is the main command.
var RootCmd = &cobra.Command{
Use: "mbt",
Short: docText("main-summary"),
Long: docText("main"),
SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if cmd.Use == "version" {
return nil
}
if in == "" {
cwd, err := os.Getwd()
if err != nil {
return err
}
in, err = lib.GitRepoRoot(cwd)
if err != nil {
return err
}
}
parent := cmd.Parent()
if parent != nil && parent.Name() == "run-in" && command == "" {
return e.NewError(lib.ErrClassUser, "--command (-m) is not specified")
}
if parent != nil && parent.Name() == "describe" && dependents && name == "" {
return e.NewError(lib.ErrClassUser, "--dependents flag can only be specified with the --name (-n) flag")
}
level := lib.LogLevelNormal
if debug {
logrus.SetLevel(logrus.DebugLevel)
level = lib.LogLevelDebug
}
var err error
system, err = lib.NewSystem(in, level)
return err
},
}
<file_sep>/lib/manifest_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"errors"
"fmt"
"path/filepath"
"testing"
"github.com/mbtproject/mbt/e"
"github.com/stretchr/testify/assert"
)
func TestSingleModDir(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
err := repo.InitModule("app-a")
check(t, err)
err = repo.Commit("first")
check(t, err)
m, err := NewWorld(t, ".tmp/repo").System.ManifestByBranch("master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestNonModContent(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
err := repo.InitModule("app-a")
check(t, err)
err = repo.WriteContent("content/index.html", "hello")
check(t, err)
err = repo.Commit("first")
check(t, err)
m, err := NewWorld(t, ".tmp/repo").System.ManifestByBranch("master")
check(t, err)
assert.Len(t, m.Modules, 1)
}
func TestNestedAppDir(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("a/b/c/app-a"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByBranch("master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "a/b/c/app-a", m.Modules[0].Path())
}
func TestModsDirInModDir(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("app-a/app-b"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByBranch("master")
check(t, err)
assert.Len(t, m.Modules, 2)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "app-a", m.Modules[0].Path())
assert.Equal(t, "app-b", m.Modules[1].Name())
assert.Equal(t, "app-a/app-b", m.Modules[1].Path())
}
func TestEmptyRepo(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByBranch("master")
check(t, err)
assert.Len(t, m.Modules, 0)
}
func TestDiffingTwoBranches(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
masterTip := repo.LastCommit
check(t, repo.SwitchToBranch("feature"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
featureTip := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByPr("feature", "master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, featureTip.String(), m.Sha)
assert.Equal(t, "app-b", m.Modules[0].Name())
m, err = NewWorld(t, ".tmp/repo").System.ManifestByPr("master", "feature")
check(t, err)
assert.Len(t, m.Modules, 0)
assert.Equal(t, masterTip.String(), m.Sha)
}
func TestDiffingTwoProgressedBranches(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.InitModule("app-c"))
check(t, repo.Commit("third"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByPr("feature", "master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-b", m.Modules[0].Name())
m, err = NewWorld(t, ".tmp/repo").System.ManifestByPr("master", "feature")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-c", m.Modules[0].Name())
}
func TestDiffingWithMultipleChangesToSameMod(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.WriteContent("app-a/file1", "hello"))
check(t, repo.Commit("second"))
check(t, repo.WriteContent("app-a/file2", "world"))
check(t, repo.Commit("third"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByPr("feature", "master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestDiffingForDeletes(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/file1", "hello world"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.Remove("app-a/file1"))
check(t, repo.Commit("second"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByPr("feature", "master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestDiffingForRenames(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/file1", "hello world"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.Rename("app-a/file1", "app-a/file2"))
check(t, repo.Commit("second"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByPr("feature", "master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestModuleOnRoot(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("", &Spec{Name: "root-app"}))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByBranch("master")
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "root-app", m.Modules[0].Name())
assert.Equal(t, "", m.Modules[0].Path())
assert.Equal(t, repo.LastCommit.String(), m.Modules[0].Version())
}
func TestModuleOnRootWhenDiffing(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
// Test a change in the root dir
check(t, repo.InitModuleWithOptions("", &Spec{Name: "root-app"}))
check(t, repo.Commit("first"))
first := repo.LastCommit.String()
check(t, repo.WriteContent("foo", "bar"))
check(t, repo.Commit("second"))
second := repo.LastCommit.String()
world := NewWorld(t, ".tmp/repo")
m, err := world.System.ManifestByDiff(first, second)
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "root-app", m.Modules[0].Name())
assert.Equal(t, "", m.Modules[0].Path())
assert.Equal(t, second, m.Modules[0].Version())
// Test a change in a nested dir
check(t, repo.WriteContent("dir/foo", "bar"))
check(t, repo.Commit("third"))
third := repo.LastCommit.String()
m, err = world.System.ManifestByDiff(second, third)
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "root-app", m.Modules[0].Name())
assert.Equal(t, "", m.Modules[0].Path())
assert.Equal(t, third, m.Modules[0].Version())
// Test an empty diff
m, err = world.System.ManifestByDiff(third, third)
check(t, err)
assert.Len(t, m.Modules, 0)
}
func TestNestedModules(t *testing.T) {
/*
Nesting modules is a rare scenario.
Although it could be useful to implement common build logic
for a sub tree.
Current expectation is, if a file changes in a path
where modules are nested, all impacted modules should
be returned in manifest.
Consider the following repo structure
/
|_ .mbt.yml (root module)
|_ foo.txt
|_ mod-a
|_ .mbt.yml
|_ bar.txt
Change to foo.txt should return just root module in the manifest.
Change to bar.txt on the other hand should return both root module
and mod-a.
*/
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("", &Spec{Name: "root-app"}))
check(t, repo.Commit("first"))
first := repo.LastCommit.String()
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("second"))
second := repo.LastCommit.String()
world := NewWorld(t, ".tmp/repo")
m, err := world.System.ManifestByDiff(first, second)
check(t, err)
assert.Len(t, m.Modules, 2)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "app-a", m.Modules[0].Path())
assert.NotEqual(t, second, m.Modules[0].Version())
assert.Equal(t, "root-app", m.Modules[1].Name())
assert.Equal(t, "", m.Modules[1].Path())
assert.Equal(t, second, m.Modules[1].Version())
}
func TestManifestByDiff(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1.String(), c2.String())
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
m, err = NewWorld(t, ".tmp/repo").System.ManifestByDiff(c2.String(), c1.String())
check(t, err)
assert.Len(t, m.Modules, 0)
}
func TestManifestByHead(t *testing.T) {
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByCurrentBranch()
check(t, err)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestManifestByLocalDirForUpdates(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/test.txt", "test contents"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspaceChanges()
check(t, err)
expectedPath, err := filepath.Abs(".tmp/repo")
check(t, err)
assert.Equal(t, "local", m.Sha)
assert.Equal(t, expectedPath, m.Dir)
// currently no modules changed locally
assert.Equal(t, 0, len(m.Modules))
// change the file, expect 1 module to be returned
check(t, repo.WriteContent("app-a/test.txt", "amended contents"))
m, err = NewWorld(t, ".tmp/repo").System.ManifestByWorkspaceChanges()
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "local", m.Modules[0].Version())
}
func TestManifestByLocalDirForAddition(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/test.txt", "test contents"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspaceChanges()
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-b", m.Modules[0].Name())
assert.Equal(t, "local", m.Modules[0].Version())
}
func TestManifestByLocalDirForConversion(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("app-a/test.txt", "test contents"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-a"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspaceChanges()
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestManifestByLocalDirForNestedModules(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("README.md", "test contents"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("src/app-a"))
check(t, repo.WriteContent("src/app-a/test.txt", "test contents"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspaceChanges()
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestManifestByLocalDirForAnEmptyRepo(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspaceChanges()
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "local", m.Modules[0].Version())
}
func TestManifestByLocalForFilesEndingWithSpecFileName(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("dummy/interesting.mbt.yml", "hello"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspace()
check(t, err)
assert.Len(t, m.Modules, 0)
}
func TestManifestByLocalForDirsEndingWithSpecFileName(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent(".mbt.yml/hello", "world"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspace()
check(t, err)
assert.Len(t, m.Modules, 0)
}
func TestVersionOfLocalDirManifest(t *testing.T) {
// All modules should have the fixed version string "local" as
// for manifest derived from local directory.
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/test.txt", "test contents"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspace()
check(t, err)
expectedPath, err := filepath.Abs(".tmp/repo")
check(t, err)
assert.Equal(t, "local", m.Sha)
assert.Equal(t, expectedPath, m.Dir)
assert.Equal(t, 2, len(m.Modules))
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "local", m.Modules[0].Version())
assert.Equal(t, "app-b", m.Modules[1].Name())
assert.Equal(t, "local", m.Modules[1].Version())
}
func TestLocalDependencyChange(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.InitModuleWithOptions("app-c", &Spec{
Name: "app-c",
Dependencies: []string{"app-b"},
}))
check(t, repo.InitModuleWithOptions("app-d", &Spec{
Name: "app-d",
Dependencies: []string{"app-c"},
}))
check(t, repo.Commit("first"))
check(t, repo.WriteContent("app-b/foo", "bar"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByWorkspaceChanges()
check(t, err)
assert.Equal(t, 3, len(m.Modules))
assert.Equal(t, "app-b", m.Modules[0].Name())
assert.Equal(t, "local", m.Modules[0].Version())
assert.Equal(t, "app-c", m.Modules[1].Name())
assert.Equal(t, "local", m.Modules[1].Version())
assert.Equal(t, "app-d", m.Modules[2].Name())
assert.Equal(t, "local", m.Modules[2].Version())
}
func TestDependencyChange(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1.String(), c2.String())
check(t, err)
assert.Len(t, m.Modules, 2)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "app-b", m.Modules[1].Name())
}
func TestIndirectDependencyChange(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.InitModuleWithOptions("app-c", &Spec{
Name: "app-c",
Dependencies: []string{"app-b"},
}))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1.String(), c2.String())
check(t, err)
assert.Len(t, m.Modules, 3)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "app-b", m.Modules[1].Name())
assert.Equal(t, "app-c", m.Modules[2].Name())
}
func TestDiffOfDependentChange(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
check(t, repo.WriteContent("app-b/foo", "hello"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1.String(), c2.String())
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-b", m.Modules[0].Name())
}
func TestVersionOfIndependentModules(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
m1, err := NewWorld(t, ".tmp/repo").System.ManifestByCommit(c1.String())
check(t, err)
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m2, err := NewWorld(t, ".tmp/repo").System.ManifestByCommit(c2.String())
check(t, err)
assert.Equal(t, m1.Modules[1].Version(), m2.Modules[1].Version())
assert.NotEqual(t, m1.Modules[0].Version(), m2.Modules[0].Version())
}
func TestVersionOfDependentModules(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
m1, err := NewWorld(t, ".tmp/repo").System.ManifestByCommit(c1.String())
check(t, err)
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m2, err := NewWorld(t, ".tmp/repo").System.ManifestByCommit(c2.String())
check(t, err)
assert.NotEqual(t, m1.Modules[0].Version(), m2.Modules[0].Version())
assert.NotEqual(t, m1.Modules[1].Version(), m2.Modules[1].Version())
}
func TestVersionOfIndirectlyDependentModules(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.InitModuleWithOptions("app-c", &Spec{
Name: "app-c",
Dependencies: []string{"app-b"},
}))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
m1, err := NewWorld(t, ".tmp/repo").System.ManifestByCommit(c1.String())
check(t, err)
check(t, repo.WriteContent("app-a/foo", "hello"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m2, err := NewWorld(t, ".tmp/repo").System.ManifestByCommit(c2.String())
check(t, err)
assert.NotEqual(t, m1.Modules[0].Version(), m2.Modules[0].Version())
assert.NotEqual(t, m1.Modules[1].Version(), m2.Modules[1].Version())
assert.NotEqual(t, m1.Modules[2].Version(), m2.Modules[2].Version())
}
func TestChangeToFileDependency(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("shared/file", "a"))
check(t, repo.InitModule("app-a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
FileDependencies: []string{"shared/file"},
}))
check(t, repo.Commit("first"))
c1 := repo.LastCommit.String()
check(t, repo.WriteContent("shared/file", "b"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit.String()
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1, c2)
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-b", m.Modules[0].Name())
}
func TestFileDependencyInADependentModule(t *testing.T) {
/*
Edge case: It does not make sense to have a file dependency to a file
in a module that you already have a dependency on. We test the correct
behavior nevertheless.
*/
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/file", "a"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
FileDependencies: []string{"app-a/file"},
}))
check(t, repo.Commit("first"))
c1 := repo.LastCommit.String()
check(t, repo.WriteContent("app-a/file", "b"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit.String()
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1, c2)
check(t, err)
assert.Len(t, m.Modules, 2)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "app-b", m.Modules[1].Name())
}
func TestDependentOfAModuleWithFileDependency(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("shared/file", "a"))
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
FileDependencies: []string{"shared/file"},
}))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-a"},
}))
check(t, repo.InitModule("app-c"))
check(t, repo.Commit("first"))
c1 := repo.LastCommit.String()
check(t, repo.WriteContent("shared/file", "b"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit.String()
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1, c2)
check(t, err)
assert.Len(t, m.Modules, 2)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "app-b", m.Modules[1].Name())
}
func TestManifestBySha(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByCommit(c1.String())
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, c1.String(), m.Sha)
assert.Equal(t, "app-a", m.Modules[0].Name())
m, err = NewWorld(t, ".tmp/repo").System.ManifestByCommit(c2.String())
check(t, err)
assert.Len(t, m.Modules, 2)
assert.Equal(t, c2.String(), m.Sha)
assert.Equal(t, "app-a", m.Modules[0].Name())
assert.Equal(t, "app-b", m.Modules[1].Name())
}
func TestOrderOfModules(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Dependencies: []string{"app-b"},
}))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-c"},
}))
check(t, repo.InitModule("app-c"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByBranch("master")
check(t, err)
assert.Len(t, m.Modules, 3)
assert.Equal(t, "app-c", m.Modules[0].Name())
assert.Equal(t, "app-b", m.Modules[1].Name())
assert.Equal(t, "app-a", m.Modules[2].Name())
}
func TestAppsWithSamePrefix(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-aa"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("second"))
c1 := repo.LastCommit
check(t, repo.WriteContent("app-aa/foo", "bar"))
check(t, repo.Commit("third"))
c2 := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1.String(), c2.String())
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-aa", m.Modules[0].Name())
}
func TestDiffingForCaseSensitivityOfModulePath(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("App-A"))
check(t, repo.Commit("first"))
c1 := repo.LastCommit
check(t, repo.WriteContent("App-A/foo", "bar"))
check(t, repo.Commit("second"))
c2 := repo.LastCommit
m, err := NewWorld(t, ".tmp/repo").System.ManifestByDiff(c1.String(), c2.String())
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "App-A", m.Modules[0].Name())
}
func TestCaseSensitivityOfFileDependency(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("App-A", &Spec{
Name: "App-A",
FileDependencies: []string{"Dir1/Foo.js"},
}))
check(t, repo.WriteContent("dir/foo.js", "console.log('foo');"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").System.ManifestByCurrentBranch()
assert.Nil(t, m)
assert.EqualError(t, err, fmt.Sprintf(msgFileDependencyNotFound, "Dir1/Foo.js", "App-A", "App-A"))
}
func TestByDiffForDiscoverFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Discover.Interceptor.Config("ModulesInCommit").Return(Modules(nil), errors.New("doh"))
_, err := w.System.ManifestByDiff(repo.LastCommit.String(), repo.LastCommit.String())
assert.EqualError(t, err, "doh")
}
func TestByDiffForMergeBaseFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("DiffMergeBase").Return([]*DiffDelta(nil), errors.New("doh"))
_, err := w.System.ManifestByDiff(repo.LastCommit.String(), repo.LastCommit.String())
assert.EqualError(t, err, "doh")
}
func TestByDiffForReduceFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Reducer.Interceptor.Config("Reduce").Return(Modules(nil), errors.New("doh"))
_, err := w.System.ManifestByDiff(repo.LastCommit.String(), repo.LastCommit.String())
assert.EqualError(t, err, "doh")
}
func TestByPrForInvalidSrcBranch(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
_, err := w.System.ManifestByPr("master", "feature")
assert.EqualError(t, err, fmt.Sprintf(msgFailedBranchLookup, "feature"))
}
func TestByPrForInvalidDstBranch(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
_, err := w.System.ManifestByPr("feature", "master")
assert.EqualError(t, err, fmt.Sprintf(msgFailedBranchLookup, "feature"))
}
func TestByCommitForDiscoverFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Discover.Interceptor.Config("ModulesInCommit").Return(Commit(nil), errors.New("doh"))
_, err := w.System.ManifestByCommit(repo.LastCommit.String())
assert.EqualError(t, err, "doh")
}
func TestByBranchForInvalidBranch(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
_, err := w.System.ManifestByBranch("feature")
assert.EqualError(t, err, fmt.Sprintf(msgFailedBranchLookup, "feature"))
}
func TestByCurrentBranchForResolutionFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("CurrentBranch").Return("", errors.New("doh"))
_, err := w.System.ManifestByCurrentBranch()
assert.EqualError(t, err, "doh")
}
func TestByWorkspaceForDiscoverFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Discover.Interceptor.Config("ModulesInWorkspace").Return((Modules)(nil), errors.New("doh"))
_, err := w.System.ManifestByWorkspace()
assert.EqualError(t, err, "doh")
}
func TestByWorkspaceChangesForDiscoverFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Discover.Interceptor.Config("ModulesInWorkspace").Return((Modules)(nil), errors.New("doh"))
_, err := w.System.ManifestByWorkspaceChanges()
assert.EqualError(t, err, "doh")
}
func TestByWorkspaceChangesForDiffFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("DiffWorkspace").Return([]*DiffDelta(nil), errors.New("doh"))
_, err := w.System.ManifestByWorkspaceChanges()
assert.EqualError(t, err, "doh")
}
func TestByWorkspaceChangesForReduceFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Reducer.Interceptor.Config("Reduce").Return((Modules)(nil), errors.New("doh"))
_, err := w.System.ManifestByWorkspaceChanges()
assert.EqualError(t, err, "doh")
}
func TestByXxxForEmptyRepoEvaluationFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("IsEmpty").Return(false, errors.New("doh"))
_, err := w.System.ManifestByCurrentBranch()
assert.EqualError(t, err, "doh")
}
func TestByCommitContentForFirstCommit(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
m, err := w.System.ManifestByCommitContent(repo.LastCommit.String())
check(t, err)
assert.Equal(t, repo.LastCommit.String(), m.Sha)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-a", m.Modules[0].Name())
}
func TestByCommitContentForCommitWithParent(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("second"))
w := NewWorld(t, ".tmp/repo")
m, err := w.System.ManifestByCommitContent(repo.LastCommit.String())
check(t, err)
assert.Equal(t, repo.LastCommit.String(), m.Sha)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "app-b", m.Modules[0].Name())
}
func TestByCommitContentForDiscoverFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
w.Discover.Interceptor.Config("ModulesInCommit").Return(Modules(nil), errors.New("doh"))
m, err := w.System.ManifestByCommitContent(repo.LastCommit.String())
assert.Nil(t, m)
assert.EqualError(t, err, "doh")
}
func TestByCommitContentForRepoFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
repo.InitModule("app-a")
repo.Commit("first")
w := NewWorld(t, ".tmp/repo")
w.Repo.Interceptor.Config("Changes").Return([]*DiffDelta(nil), errors.New("doh"))
m, err := w.System.ManifestByCommitContent(repo.LastCommit.String())
assert.Nil(t, m)
assert.EqualError(t, err, "doh")
}
func TestByCommitContentForReducerFailure(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
repo.InitModule("app-a")
repo.Commit("first")
repo.InitModule("app-b")
repo.Commit("second")
w := NewWorld(t, ".tmp/repo")
w.Reducer.Interceptor.Config("Reduce").Return(Modules(nil), errors.New("doh"))
m, err := w.System.ManifestByCommitContent(repo.LastCommit.String())
assert.Nil(t, m)
assert.EqualError(t, err, "doh")
}
func TestCircularDependencyInCommit(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{Name: "app-a", Dependencies: []string{"app-b"}}))
check(t, repo.InitModuleWithOptions("app-b", &Spec{Name: "app-b", Dependencies: []string{"app-a"}}))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
m, err := w.System.ManifestByCommit(repo.LastCommit.String())
assert.Nil(t, m)
assert.EqualError(t, err, "Could not produce the module graph due to a cyclic dependency in path: app-a -> app-b -> app-a")
}
func TestCircularDependencyInWorkspace(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("app-a", &Spec{Name: "app-a", Dependencies: []string{"app-b"}}))
check(t, repo.InitModuleWithOptions("app-b", &Spec{Name: "app-b", Dependencies: []string{"app-a"}}))
check(t, repo.Commit("first"))
w := NewWorld(t, ".tmp/repo")
m, err := w.System.ManifestByWorkspace()
assert.Nil(t, m)
assert.EqualError(t, err, "Could not produce the module graph due to a cyclic dependency in path: app-a -> app-b -> app-a")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestManifestByWorkspaceChangesForRootModule(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModuleWithOptions("", &Spec{Name: "root"}))
w := NewWorld(t, ".tmp/repo")
m, err := w.System.ManifestByWorkspaceChanges()
check(t, err)
assert.Len(t, m.Modules, 1)
assert.Equal(t, "root", m.Modules[0].Name())
}
func TestApplyFilter(t *testing.T) {
appA := &Module{metadata: &moduleMetadata{spec: &Spec{Name: "app-a"}}}
appB := &Module{
metadata: &moduleMetadata{spec: &Spec{Name: "app-b", Dependencies: []string{"app-a"}}},
requiredBy: Modules{appA},
}
appAa := &Module{metadata: &moduleMetadata{spec: &Spec{Name: "app-aa"}}}
m := &Manifest{Modules: []*Module{appA, appB, appAa}}
m1, err := m.ApplyFilters(NoFilter)
check(t, err)
assert.Equal(t, m, m1)
m1, err = m.ApplyFilters(ExactMatchFilter("app"))
check(t, err)
assert.Len(t, m1.Modules, 0)
m1, err = m.ApplyFilters(ExactMatchFilter("app-a"))
check(t, err)
assert.Len(t, m1.Modules, 1)
assert.Equal(t, "app-a", m1.Modules[0].Name())
m1, err = m.ApplyFilters(FuzzyFilter("app-a"))
check(t, err)
assert.Len(t, m1.Modules, 2)
assert.Equal(t, "app-a", m1.Modules[0].Name())
assert.Equal(t, "app-aa", m1.Modules[1].Name())
m1, err = m.ApplyFilters(ExactMatchDependentsFilter("app-b"))
check(t, err)
assert.Len(t, m1.Modules, 2)
assert.Equal(t, "app-b", m1.Modules[0].Name())
assert.Equal(t, "app-a", m1.Modules[1].Name())
m1, err = m.ApplyFilters(FuzzyDependentsFilter("app-b"))
check(t, err)
assert.Len(t, m1.Modules, 2)
assert.Equal(t, "app-b", m1.Modules[0].Name())
assert.Equal(t, "app-a", m1.Modules[1].Name())
}
<file_sep>/docs/mbt_run-in_local.md
## mbt run-in local
### Synopsis
```
mbt run-in local [--all] [flags]
```
### Options
```
-a, --all All modules
-f, --fuzzy Use fuzzy match when filtering
-h, --help help for local
-n, --name string Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.
```
### Options inherited from parent commands
```
-m, --command string Command to execute
--debug Enable debug output
--fail-fast Fail fast on command failure
--in string Path to repo
```
### SEE ALSO
* [mbt run-in](mbt_run-in.md) - Run user defined command
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/docs/mbt_describe_diff.md
## mbt describe diff
### Synopsis
```
mbt describe diff --from <commit> --to <commit> [flags]
```
### Options
```
--from string From commit
-h, --help help for diff
--to string To commit
```
### Options inherited from parent commands
```
--debug Enable debug output
--graph Format output as dot graph
--in string Path to repo
--json Format output as json
```
### SEE ALSO
* [mbt describe](mbt_describe.md) - Describe repository manifest
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/cmd/describe.go
/*
Copyright 2018 MBT Authors.
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 cmd
import (
"encoding/json"
"errors"
"fmt"
"os"
"text/tabwriter"
"github.com/mbtproject/mbt/lib"
"github.com/spf13/cobra"
)
var (
toJSON bool
toGraph bool
dependents bool
)
func init() {
describePrCmd.Flags().StringVar(&src, "src", "", "Source branch")
describePrCmd.Flags().StringVar(&dst, "dst", "", "Destination branch")
describeIntersectionCmd.Flags().StringVar(&kind, "kind", "", "Kind of input for first and second args (available options are 'branch' and 'commit')")
describeIntersectionCmd.Flags().StringVar(&first, "first", "", "First item")
describeIntersectionCmd.Flags().StringVar(&second, "second", "", "Second item")
describeDiffCmd.Flags().StringVar(&from, "from", "", "From commit")
describeDiffCmd.Flags().StringVar(&to, "to", "", "To commit")
describeLocalCmd.Flags().BoolVarP(&all, "all", "a", false, "Describe all")
describeCommitCmd.Flags().BoolVarP(&content, "content", "c", false, "Describe the modules impacted by the changes in commit")
describeCmd.PersistentFlags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
describeCmd.PersistentFlags().StringVarP(&name, "name", "n", "", "Describe modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
describeCmd.PersistentFlags().BoolVar(&toJSON, "json", false, "Format output as json")
describeCmd.PersistentFlags().BoolVar(&toGraph, "graph", false, "Format output as dot graph")
describeCmd.PersistentFlags().BoolVar(&dependents, "dependents", false, "Output dependents on potential change")
describeCmd.AddCommand(describeCommitCmd)
describeCmd.AddCommand(describeBranchCmd)
describeCmd.AddCommand(describeHeadCmd)
describeCmd.AddCommand(describeLocalCmd)
describeCmd.AddCommand(describePrCmd)
describeCmd.AddCommand(describeIntersectionCmd)
describeCmd.AddCommand(describeDiffCmd)
RootCmd.AddCommand(describeCmd)
}
var describeCmd = &cobra.Command{
Use: "describe",
Short: docText("describe-summary"),
Long: docText("describe"),
}
var describeBranchCmd = &cobra.Command{
Use: "branch <branch>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
branch := "master"
if len(args) > 0 {
branch = args[0]
}
m, err := system.ManifestByBranch(branch)
if err != nil {
return err
}
m, err = m.ApplyFilters(&lib.FilterOptions{Name: name, Fuzzy: fuzzy, Dependents: dependents})
if err != nil {
return err
}
return output(m.Modules)
}),
}
var describeHeadCmd = &cobra.Command{
Use: "head",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
m, err := system.ManifestByCurrentBranch()
if err != nil {
return err
}
m, err = m.ApplyFilters(&lib.FilterOptions{Name: name, Fuzzy: fuzzy, Dependents: dependents})
if err != nil {
return err
}
return output(m.Modules)
}),
}
var describeLocalCmd = &cobra.Command{
Use: "local",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
var (
m *lib.Manifest
err error
)
if all {
m, err = system.ManifestByWorkspace()
if err != nil {
return err
}
m, err = m.ApplyFilters(&lib.FilterOptions{Name: name, Fuzzy: fuzzy, Dependents: dependents})
} else {
m, err = system.ManifestByWorkspaceChanges()
}
if err != nil {
return err
}
return output(m.Modules)
}),
}
var describePrCmd = &cobra.Command{
Use: "pr --src <branch> --dst <branch>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if src == "" {
return errors.New("requires source")
}
if dst == "" {
return errors.New("requires dest")
}
m, err := system.ManifestByPr(src, dst)
if err != nil {
return err
}
m, err = m.ApplyFilters(&lib.FilterOptions{Name: name, Fuzzy: fuzzy, Dependents: dependents})
if err != nil {
return err
}
return output(m.Modules)
}),
}
var describeCommitCmd = &cobra.Command{
Use: "commit <sha>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("requires the commit sha")
}
commit := args[0]
var (
m *lib.Manifest
err error
)
if content {
m, err = system.ManifestByCommitContent(commit)
} else {
m, err = system.ManifestByCommit(commit)
}
if err != nil {
return err
}
m, err = m.ApplyFilters(&lib.FilterOptions{Name: name, Fuzzy: fuzzy, Dependents: dependents})
if err != nil {
return err
}
return output(m.Modules)
}),
}
var describeIntersectionCmd = &cobra.Command{
Use: "intersection --kind <branch|commit> --first <first> --second <second>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if kind == "" {
return errors.New("requires the kind argument")
}
if first == "" {
return errors.New("requires the first argument")
}
if second == "" {
return errors.New("requires the second argument")
}
var mods lib.Modules
var err error
switch kind {
case "branch":
mods, err = system.IntersectionByBranch(first, second)
case "commit":
mods, err = system.IntersectionByCommit(first, second)
default:
err = errors.New("not a valid kind - available options are 'branch' and 'commit'")
}
if err != nil {
return err
}
return output(mods)
}),
}
var describeDiffCmd = &cobra.Command{
Use: "diff --from <commit> --to <commit>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if from == "" {
return errors.New("requires from commit")
}
if to == "" {
return errors.New("requires to commit")
}
m, err := system.ManifestByDiff(from, to)
if err != nil {
return err
}
m, err = m.ApplyFilters(&lib.FilterOptions{Name: name, Fuzzy: fuzzy, Dependents: dependents})
if err != nil {
return err
}
return output(m.Modules)
}),
}
const columnWidth = 30
func output(mods lib.Modules) error {
if toJSON {
m := make(map[string]map[string]interface{})
for _, a := range mods {
v := make(map[string]interface{})
v["Name"] = a.Name()
v["Path"] = a.Path()
v["Version"] = a.Version()
v["Properties"] = a.Properties()
m[a.Name()] = v
}
buff, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
fmt.Println(string(buff))
} else if toGraph {
if dependents {
fmt.Println(mods.GroupedSerializeAsDot())
} else {
fmt.Println(mods.SerializeAsDot())
}
} else {
w := tabwriter.NewWriter(os.Stdout, 0, 4, 4, ' ', 0)
fmt.Fprintf(w, "Name\tPATH\tVERSION\n")
for _, a := range mods {
fmt.Fprintf(w, "%s\t%s\t%s\n", a.Name(), a.Path(), a.Version())
}
if err := w.Flush(); err != nil {
panic(err)
}
}
return nil
}
<file_sep>/lib/dot_serializer_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGraph(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
// Create indirect dependency graph
check(t, repo.InitModule("lib-a"))
check(t, repo.InitModuleWithOptions("lib-b", &Spec{
Name: "lib-b",
Dependencies: []string{"lib-a"},
}))
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Dependencies: []string{"lib-b"},
}))
// Create an isolated node
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").ManifestBuilder.ByCurrentBranch()
check(t, err)
s := m.Modules.SerializeAsDot()
assert.Equal(t, `digraph mbt {
node [shape=box fillcolor=powderblue style=filled fontcolor=black];
"lib-a"
"lib-b" -> "lib-a"
"app-a" -> "lib-b"
"app-b"
}`, s)
}
func TestGroupedGraph(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
// Create indirect dependency graph
check(t, repo.InitModule("lib-a"))
check(t, repo.InitModuleWithOptions("lib-b", &Spec{
Name: "lib-b",
Dependencies: []string{"lib-a"},
}))
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Dependencies: []string{"lib-b"},
}))
// Create an isolated node
check(t, repo.InitModule("app-b"))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").ManifestBuilder.ByCurrentBranch()
check(t, err)
filterOptions := ExactMatchDependentsFilter("lib-b")
m, err = m.ApplyFilters(filterOptions)
check(t, err)
mods := m.Modules
s := mods.GroupedSerializeAsDot()
assert.Equal(t, `digraph mbt {
node [shape=box fillcolor=red style=filled fontcolor=black];
"lib-b"
"app-a"
node [shape=box fillcolor=powderblue style=filled fontcolor=black];
"lib-b" -> "lib-a"
"app-a" -> "lib-b"
}`, s)
}
func TestSerializeAsDotOfAnEmptyRepo(t *testing.T) {
clean()
_, err := createTestRepository(".tmp/repo")
check(t, err)
m, err := NewWorld(t, ".tmp/repo").ManifestBuilder.ByCurrentBranch()
check(t, err)
s := m.Modules.SerializeAsDot()
assert.Equal(t, `digraph mbt {
node [shape=box fillcolor=powderblue style=filled fontcolor=black];
}`, s)
}
func TestTransitiveDependencies(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-c"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-c"},
}))
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Dependencies: []string{"app-b"},
}))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").ManifestBuilder.ByCurrentBranch()
check(t, err)
s := m.Modules.SerializeAsDot()
assert.Equal(t, `digraph mbt {
node [shape=box fillcolor=powderblue style=filled fontcolor=black];
"app-c"
"app-b" -> "app-c"
"app-a" -> "app-b"
}`, s)
}
func TestTransitiveDependenciesWithFiltering(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-c"))
check(t, repo.InitModuleWithOptions("app-b", &Spec{
Name: "app-b",
Dependencies: []string{"app-c"},
}))
check(t, repo.InitModuleWithOptions("app-a", &Spec{
Name: "app-a",
Dependencies: []string{"app-b"},
}))
check(t, repo.Commit("first"))
m, err := NewWorld(t, ".tmp/repo").ManifestBuilder.ByCurrentBranch()
check(t, err)
m, err = m.ApplyFilters(&FilterOptions{Name: "app-a"})
check(t, err)
s := m.Modules.SerializeAsDot()
// Should only include filtered modules in the graph
assert.Equal(t, `digraph mbt {
node [shape=box fillcolor=powderblue style=filled fontcolor=black];
"app-a" -> "app-b"
}`, s)
}
<file_sep>/lib/apply.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"text/template"
"github.com/mbtproject/mbt/e"
)
// TemplateData is the data passed into template.
type TemplateData struct {
Args map[string]interface{}
Sha string
Env map[string]string
Modules map[string]*Module
ModulesList []*Module
OrderedModules []*Module
}
// KVP is a key value pair.
type KVP struct {
Key string
Value interface{}
}
type kvpSoter []*KVP
func (a kvpSoter) Len() int {
return len(a)
}
func (a kvpSoter) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a kvpSoter) Less(i, j int) bool {
return a[i].Key < a[j].Key
}
type modulesByNameSorter []*Module
func (m modulesByNameSorter) Len() int {
return len(m)
}
func (m modulesByNameSorter) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m modulesByNameSorter) Less(i, j int) bool {
return m[i].Name() < m[j].Name()
}
func (s *stdSystem) ApplyBranch(templatePath, branch string, output io.Writer) error {
commit, err := s.Repo.BranchCommit(branch)
if err != nil {
return err
}
return s.applyCore(commit, templatePath, output)
}
func (s *stdSystem) ApplyCommit(commit string, templatePath string, output io.Writer) error {
c, err := s.Repo.GetCommit(commit)
if err != nil {
return err
}
return s.applyCore(c, templatePath, output)
}
// ApplyHead applies the repository manifest to specified template.
func (s *stdSystem) ApplyHead(templatePath string, output io.Writer) error {
branch, err := s.Repo.CurrentBranch()
if err != nil {
return err
}
return s.ApplyBranch(templatePath, branch, output)
}
func (s *stdSystem) ApplyLocal(templatePath string, output io.Writer) error {
absDir, err := filepath.Abs(s.Repo.Path())
if err != nil {
return e.Wrapf(ErrClassUser, err, msgFailedLocalPath, s.Repo.Path())
}
absTemplatePath := filepath.Join(absDir, templatePath)
c, err := ioutil.ReadFile(absTemplatePath)
if err != nil {
return e.Wrapf(ErrClassUser, err, msgFailedReadFile, absTemplatePath)
}
m, err := s.ManifestBuilder().ByWorkspace()
if err != nil {
return err
}
return processTemplate(c, m, output)
}
func (s *stdSystem) applyCore(commit Commit, templatePath string, output io.Writer) error {
b, err := s.Repo.BlobContentsFromTree(commit, templatePath)
if err != nil {
return e.Wrapf(ErrClassUser, err, msgTemplateNotFound, templatePath, commit)
}
m, err := s.MB.ByCommit(commit)
if err != nil {
return err
}
return processTemplate(b, m, output)
}
func processTemplate(buffer []byte, m *Manifest, output io.Writer) error {
modulesIndex := m.Modules.indexByName()
sortedModules := make(modulesByNameSorter, len(m.Modules))
copy(sortedModules, m.Modules)
sort.Sort(sortedModules)
temp, err := template.New("template").Funcs(template.FuncMap{
"module": func(n string) *Module {
return modulesIndex[n]
},
"property": func(m *Module, n string) interface{} {
if m == nil {
return nil
}
return resolveProperty(m.Properties(), strings.Split(n, "."), nil)
},
"propertyOr": func(m *Module, n string, def interface{}) interface{} {
if m == nil {
return def
}
return resolveProperty(m.Properties(), strings.Split(n, "."), def)
},
"contains": func(container interface{}, item interface{}) bool {
if container == nil {
return false
}
a, ok := container.([]interface{})
if !ok {
return false
}
for _, w := range a {
if w == item {
return true
}
}
return false
},
"join": func(container interface{}, format string, sep string) string {
if container == nil {
return ""
}
a, ok := container.([]interface{})
if !ok {
return ""
}
strs := make([]string, 0, len(a))
for _, i := range a {
strs = append(strs, fmt.Sprintf(format, i))
}
return strings.Join(strs, sep)
},
"kvplist": func(m map[string]interface{}) []*KVP {
l := make([]*KVP, 0, len(m))
for k, v := range m {
l = append(l, &KVP{Key: k, Value: v})
}
sort.Sort(kvpSoter(l))
return l
},
"add": func(a, b int) int {
return a + b
},
"sub": func(a, b int) int {
return a - b
},
"mul": func(a, b int) int {
return a * b
},
"div": func(a, b int) int {
return a / b
},
"istail": func(array, value interface{}) bool {
if array == nil {
return false
}
t := reflect.TypeOf(array)
if t.Kind() != reflect.Array && t.Kind() != reflect.Slice {
panic(fmt.Sprintf("istail function requires an array/slice as input %d", t.Kind()))
}
arrayVal := reflect.ValueOf(array)
if arrayVal.Len() == 0 {
return false
}
v := arrayVal.Index(arrayVal.Len() - 1).Interface()
return v == value
},
"ishead": func(array, value interface{}) bool {
if array == nil {
return false
}
t := reflect.TypeOf(array)
if t.Kind() != reflect.Array && t.Kind() != reflect.Slice {
panic(fmt.Sprintf("ishead function requires an array/slice as input %d", t.Kind()))
}
arrayVal := reflect.ValueOf(array)
if arrayVal.Len() == 0 {
return false
}
v := arrayVal.Index(0).Interface()
return v == value
},
"head": func(array interface{}) interface{} {
if array == nil {
return ""
}
t := reflect.TypeOf(array)
if t.Kind() != reflect.Array && t.Kind() != reflect.Slice {
panic(fmt.Sprintf("head function requires an array/slice as input %d", t.Kind()))
}
arrayVal := reflect.ValueOf(array)
if arrayVal.Len() == 0 {
return ""
}
return arrayVal.Index(0).Interface()
},
"tail": func(array interface{}) interface{} {
if array == nil {
return ""
}
t := reflect.TypeOf(array)
if t.Kind() != reflect.Array && t.Kind() != reflect.Slice {
panic(fmt.Sprintf("tail function requires an array/slice as input %d", t.Kind()))
}
arrayVal := reflect.ValueOf(array)
if arrayVal.Len() == 0 {
return ""
}
return arrayVal.Index(arrayVal.Len() - 1).Interface()
},
}).Parse(string(buffer))
if err != nil {
return e.Wrapf(ErrClassUser, err, msgFailedTemplateParse)
}
data := &TemplateData{
Sha: m.Sha,
Env: getEnvMap(),
Modules: m.Modules.indexByName(),
ModulesList: sortedModules,
OrderedModules: m.Modules,
}
return temp.Execute(output, data)
}
func resolveProperty(in interface{}, path []string, def interface{}) interface{} {
if in == nil || len(path) == 0 {
return def
}
if currentMap, ok := in.(map[string]interface{}); ok {
v, ok := currentMap[path[0]]
if !ok {
return def
}
rest := path[1:]
if len(rest) > 0 {
return resolveProperty(v, rest, def)
}
return v
}
return def
}
func getEnvMap() map[string]string {
m := make(map[string]string)
for _, v := range os.Environ() {
p := strings.Split(v, "=")
m[p[0]] = p[1]
}
return m
}
<file_sep>/docs/mbt_describe_intersection.md
## mbt describe intersection
### Synopsis
```
mbt describe intersection --kind <branch|commit> --first <first> --second <second> [flags]
```
### Options
```
--first string First item
-h, --help help for intersection
--kind string Kind of input for first and second args (available options are 'branch' and 'commit')
--second string Second item
```
### Options inherited from parent commands
```
--debug Enable debug output
--graph Format output as dot graph
--in string Path to repo
--json Format output as json
```
### SEE ALSO
* [mbt describe](mbt_describe.md) - Describe repository manifest
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/lib/repo.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
git "github.com/libgit2/git2go/v28"
"github.com/mbtproject/mbt/e"
)
type libgitBlob struct {
path string
commit *libgitCommit
entry *git.TreeEntry
}
func (b *libgitBlob) ID() string {
return b.entry.Id.String()
}
func (b *libgitBlob) Name() string {
return b.entry.Name
}
func (b *libgitBlob) Path() string {
return b.path
}
func (b *libgitBlob) String() string {
return fmt.Sprintf("%s%s", b.Path(), b.Name())
}
type libgitCommit struct {
commit *git.Commit
tree *git.Tree
}
func (c *libgitCommit) ID() string {
return c.commit.Id().String()
}
func (c *libgitCommit) String() string {
return c.ID()
}
type libgitReference struct {
reference *git.Reference
symbolicName string
}
func (r *libgitReference) Name() string {
return r.reference.Name()
}
func (r *libgitReference) SymbolicName() string {
return r.symbolicName
}
type libgitRepo struct {
path string
Repo *git.Repository
Log Log
}
func (c *libgitCommit) Tree() (*git.Tree, error) {
if c.tree == nil {
tree, err := c.commit.Tree()
if err != nil {
return nil, e.Wrapf(ErrClassInternal, err, msgFailedTreeLoad, c.commit.Id())
}
c.tree = tree
}
return c.tree, nil
}
// NewLibgitRepo creates a libgit2 repo instance
func NewLibgitRepo(path string, log Log) (Repo, error) {
repo, err := git.OpenRepository(path)
if err != nil {
return nil, e.Wrapf(ErrClassUser, err, msgFailedOpenRepo, path)
}
return &libgitRepo{
path: path,
Repo: repo,
Log: log,
}, nil
}
func (r *libgitRepo) GetCommit(commitSha string) (Commit, error) {
commitOid, err := git.NewOid(commitSha)
if err != nil {
return nil, e.Wrapf(ErrClassUser, err, msgInvalidSha, commitSha)
}
commit, err := r.Repo.LookupCommit(commitOid)
if err != nil {
return nil, e.Wrapf(ErrClassUser, err, msgCommitShaNotFound, commitSha)
}
return &libgitCommit{commit: commit}, nil
}
func (r *libgitRepo) Path() string {
return r.path
}
func (r *libgitRepo) Diff(a, b Commit) ([]*DiffDelta, error) {
diff, err := diff(r.Repo, a, b)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return deltas(diff)
}
func (r *libgitRepo) DiffMergeBase(from, to Commit) ([]*DiffDelta, error) {
bc, err := r.MergeBase(from, to)
if err != nil {
return nil, err
}
diff, err := diff(r.Repo, bc, to)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return deltas(diff)
}
func (r *libgitRepo) DiffWorkspace() ([]*DiffDelta, error) {
index, err := r.Repo.Index()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
// Diff flags below are essential to get a list of
// untracked files (including the ones inside new directories)
// in the diff.
// Without git.DiffRecurseUntracked option, if a new file is added inside
// a new directory, we only get the path to the directory.
// This option is same as running git status -uall
diff, err := r.Repo.DiffIndexToWorkdir(index, &git.DiffOptions{
Flags: git.DiffIncludeUntracked | git.DiffRecurseUntracked,
})
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return deltas(diff)
}
func (r *libgitRepo) Changes(c Commit) ([]*DiffDelta, error) {
commit := c.(*libgitCommit).commit
repo := r.Repo
t1, err := c.(*libgitCommit).Tree()
if err != nil {
return nil, err
}
np := commit.ParentCount()
r.Log.Debug("Commit %v has %v parents", commit, np)
if np == 0 {
return []*DiffDelta{}, nil
}
p := commit.Parent(0)
r.Log.Debug("Changes are based on parent %v", p)
t2, err := p.Tree()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
d, err := repo.DiffTreeToTree(t1, t2, &git.DiffOptions{})
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return deltas(d)
}
func (r *libgitRepo) WalkBlobs(commit Commit, callback BlobWalkCallback) error {
tree, err := commit.(*libgitCommit).Tree()
if err != nil {
return err
}
var (
walkErr error
)
err = tree.Walk(func(path string, entry *git.TreeEntry) int {
if entry.Type == git.ObjectBlob {
b := &libgitBlob{
entry: entry,
path: path,
commit: commit.(*libgitCommit),
}
walkErr = callback(b)
if walkErr != nil {
return -1
}
}
return 0
})
if walkErr != nil {
return walkErr
}
if err != nil {
return e.Wrapf(ErrClassInternal, err, msgFailedTreeWalk, tree.Id())
}
return nil
}
func (r *libgitRepo) BlobContents(blob Blob) ([]byte, error) {
bl, err := r.Repo.LookupBlob(blob.(*libgitBlob).entry.Id)
if err != nil {
return nil, e.Wrapf(ErrClassInternal, err, "error while fetching the blob object for %s%s", blob.Path(), blob.Name())
}
return bl.Contents(), nil
}
func (r *libgitRepo) EntryID(commit Commit, path string) (string, error) {
tree, err := commit.(*libgitCommit).Tree()
if err != nil {
return "", err
}
entry, err := tree.EntryByPath(path)
if err != nil {
return "", e.Wrapf(ErrClassInternal, err, "error while fetching the tree entry for %s", path)
}
return entry.Id.String(), nil
}
func (r *libgitRepo) BranchCommit(name string) (Commit, error) {
repo := r.Repo
ref, err := repo.References.Dwim(name)
if err != nil {
return nil, e.Wrapf(ErrClassUser, err, msgFailedBranchLookup, name)
}
return r.GetCommit(ref.Target().String())
}
func (r *libgitRepo) CurrentBranch() (string, error) {
head, err := r.Repo.Head()
if err != nil {
return "", e.Wrap(ErrClassInternal, err)
}
name, err := head.Branch().Name()
if err != nil {
return "", e.Wrap(ErrClassInternal, err)
}
return name, nil
}
func (r *libgitRepo) CurrentBranchCommit() (Commit, error) {
b, err := r.CurrentBranch()
if err != nil {
return nil, err
}
return r.BranchCommit(b)
}
func (r *libgitRepo) IsEmpty() (bool, error) {
empty, err := r.Repo.IsEmpty()
if err != nil {
return false, e.Wrap(ErrClassInternal, err)
}
return empty, nil
}
func (r *libgitRepo) FindAllFilesInWorkspace(pathSpec []string) ([]string, error) {
var configPaths []string
status, err := r.Repo.StatusList(&git.StatusOptions{
Flags: git.StatusOptIncludeUntracked | git.StatusOptIncludeUnmodified | git.StatusOptRecurseUntrackedDirs,
Pathspec: pathSpec,
})
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
defer status.Free()
count, err := status.EntryCount()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
r.Log.Debug("Discovered %v files matching the filter", count)
if count > 0 {
for c := 0; c < count; c++ {
entry, err := status.ByIndex(c)
if err != nil {
r.Log.Debug("Error while getting the change at index %v - %v", c, err)
continue
}
if entry.Status != git.StatusWtDeleted {
path := entry.IndexToWorkdir.NewFile.Path
if path == "" {
path = entry.HeadToIndex.NewFile.Path
}
r.Log.Debug("Matching file detected: %v", path)
configPaths = append(configPaths, path)
}
}
}
return configPaths, nil
}
func (r *libgitRepo) EnsureSafeWorkspace() error {
status, err := r.Repo.StatusList(&git.StatusOptions{
Flags: git.StatusOptIncludeUntracked,
})
if err != nil {
return e.Wrap(ErrClassInternal, err)
}
defer status.Free()
count, err := status.EntryCount()
if err != nil {
return e.Wrap(ErrClassInternal, err)
}
if count > 0 {
r.Log.Debug("Workspace has %v changes", count)
r.Log.Debug("Begin tracing all changes")
for c := 0; c < count; c++ {
entry, err := status.ByIndex(c)
if err != nil {
r.Log.Debug("Error while getting the change at index %v - %v", c, err)
continue
}
r.Log.Debug("%v", entry.IndexToWorkdir.NewFile)
}
r.Log.Debug("End tracing all changes")
return e.NewError(ErrClassUser, msgDirtyWorkingDir)
}
return nil
}
func (r *libgitRepo) BlobContentsFromTree(commit Commit, path string) ([]byte, error) {
t, err := commit.(*libgitCommit).Tree()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
item, err := t.EntryByPath(path)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
blob, err := r.Repo.LookupBlob(item.Id)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return blob.Contents(), nil
}
func (r *libgitRepo) readHeadReference() (Reference, error) {
ref, err := r.Repo.Head()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
reference := &libgitReference{reference: ref}
detached, err := r.Repo.IsHeadDetached()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
if !detached {
reference.symbolicName = ref.Name()
}
return reference, nil
}
func (r *libgitRepo) Checkout(commit Commit) (Reference, error) {
reference, err := r.readHeadReference()
if err != nil {
return nil, err
}
gitCommit := commit.(*libgitCommit)
tree, err := gitCommit.Tree()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
options := &git.CheckoutOpts{
Strategy: git.CheckoutSafe,
}
err = r.Repo.CheckoutTree(tree, options)
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
err = r.Repo.SetHeadDetached(gitCommit.commit.Id())
if err != nil {
return reference, e.Wrap(ErrClassInternal, err)
}
return reference, nil
}
func (r *libgitRepo) CheckoutReference(reference Reference) error {
gitRef := (reference.(*libgitReference)).reference
target := gitRef.Target()
commit, err := r.Repo.LookupCommit(target)
if err != nil {
return err
}
tree, err := commit.Tree()
if err != nil {
return err
}
err = r.Repo.CheckoutTree(tree, &git.CheckoutOpts{Strategy: git.CheckoutForce})
if err != nil {
return e.Wrap(ErrClassInternal, err)
}
if reference.SymbolicName() != "" {
err = r.Repo.SetHead(reference.SymbolicName())
} else {
err = r.Repo.SetHeadDetached(commit.Id())
}
if err != nil {
return e.Wrap(ErrClassInternal, err)
}
return nil
}
func (r *libgitRepo) MergeBase(a, b Commit) (Commit, error) {
bid, err := r.Repo.MergeBase(a.(*libgitCommit).commit.Id(), b.(*libgitCommit).commit.Id())
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return r.GetCommit(bid.String())
}
func diff(repo *git.Repository, ca, cb Commit) (*git.Diff, error) {
t1, err := ca.(*libgitCommit).Tree()
if err != nil {
return nil, err
}
t2, err := cb.(*libgitCommit).Tree()
if err != nil {
return nil, err
}
diff, err := repo.DiffTreeToTree(t1, t2, &git.DiffOptions{})
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
return diff, nil
}
func deltas(diff *git.Diff) ([]*DiffDelta, error) {
count, err := diff.NumDeltas()
if err != nil {
return nil, e.Wrap(ErrClassInternal, err)
}
deltas := make([]*DiffDelta, 0, count)
err = diff.ForEach(func(delta git.DiffDelta, num float64) (git.DiffForEachHunkCallback, error) {
deltas = append(deltas, &DiffDelta{
OldFile: delta.OldFile.Path,
NewFile: delta.NewFile.Path,
})
return nil, nil
}, git.DiffDetailFiles)
return deltas, err
}
<file_sep>/scripts/build.sh
#!/bin/bash
set -e
# Utility functions
lint() {
paths=$@
for path in "${paths[@]}"
do
r=$(gofmt -s -d $path)
if [ ! -z "$r" ]; then
echo "ERROR: Linting failed. Review errors and try running gofmt -s -w $path"
echo $r
exit 1
fi
done
}
DIR=$(pwd)
LIBGIT2_PATH=$DIR/libgit2
OS=$(uname -s | awk '{print tolower($0)}')
ARCH=$(uname -m)
# Restore build dependencies
go get golang.org/x/tools/cmd/cover
go get github.com/mattn/goveralls
# Build libgit2
./scripts/build_libgit2.sh
# Set environment so to static link libgit2 when building git2go
export PKG_CONFIG_PATH="$LIBGIT2_PATH/build"
export CGO_LDFLAGS="$(pkg-config --libs --static $LIBGIT2_PATH/build/libgit2.pc)"
# All preparation is done at this point.
# Move on to building mbt
cd $DIR
OUT="mbt_${OS}_${ARCH}"
VERSION=$VERSION
if [ -z $VERSION ]; then
OUT="mbt_dev_${OS}_${ARCH}"
if [ ! -z $TRAVIS_COMMIT ]; then
VERSION="dev-$(echo $TRAVIS_COMMIT | head -c8)"
go run scripts/update_version.go -custom "$VERSION"
else
VERSION="dev-$(git rev-parse HEAD | head -c8)"
fi
fi
make restore
# Run linter
lint *.go ./e ./dtrace ./trie ./intercept ./lib
# Run tests
go test ./e -v -covermode=count
go test ./dtrace -v -covermode=count
go test ./trie -v -covermode=count
go test ./intercept -v -covermode=count
go test ./graph -v -covermode=count
go test ./utils -v -covermode=count
go test ./lib -v -covermode=count -coverprofile=coverage.out
if [ ! -z $COVERALLS_TOKEN ] && [ -f ./coverage.out ]; then
$HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN
fi
go build -o "build/${OUT}"
shasum -a 1 -p "build/${OUT}" | cut -d ' ' -f 1 > "build/${OUT}.sha1"
# Run go vet (this should happen after the build)
go vet ./*.go
go vet ./e ./dtrace ./trie ./intercept ./lib ./graph
echo "testing the bin"
"./build/${OUT}" version
if [ ! -z $PUBLISH_TOKEN ]; then
echo "publishing $OUT"
curl \
-ubuddyspike:$PUBLISH_TOKEN \
-X POST \
-H "Content-Type: application/json" \
-d "{\"name\": \"$VERSION\", \"description\": \"$VERSION\", \"published\": true}" \
"https://api.bintray.com/packages/buddyspike/bin/$OUT/versions"
curl \
-ubuddyspike:$PUBLISH_TOKEN \
--progress-bar \
-T "build/$OUT" \
-H "X-Bintray-Package:$OUT" \
-H "X-Bintray-Version:$VERSION" \
"https://api.bintray.com/content/buddyspike/bin/$OUT/$VERSION/$VERSION/$OUT?publish=1"
fi
<file_sep>/lib/log.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"github.com/mbtproject/mbt/dtrace"
"github.com/sirupsen/logrus"
)
// Log used to write system events
type Log interface {
Info(args ...interface{})
Infof(format string, args ...interface{})
Warn(args ...interface{})
Warnf(format string, args ...interface{})
Error(error)
Errorf(format string, args ...interface{})
Debug(format string, args ...interface{})
}
const (
// LogLevelNormal logs info and above
LogLevelNormal = iota
// LogLevelDebug logs debug and above
LogLevelDebug
)
type stdLog struct {
level int
}
// NewStdLog creates a standared logger
func NewStdLog(level int) Log {
return &stdLog{
level: level,
}
}
func (l *stdLog) Info(args ...interface{}) {
logrus.Info(args...)
}
func (l *stdLog) Infof(format string, args ...interface{}) {
logrus.Infof(format, args...)
}
func (l *stdLog) Warn(args ...interface{}) {
logrus.Warn(args...)
}
func (l *stdLog) Warnf(format string, args ...interface{}) {
logrus.Warnf(format, args...)
}
func (l *stdLog) Error(err error) {
logrus.Error(err)
}
func (l *stdLog) Errorf(format string, args ...interface{}) {
logrus.Errorf(format, args...)
}
func (l *stdLog) Debug(format string, args ...interface{}) {
if l.level != LogLevelDebug {
return
}
dtrace.Printf(format, args...)
}
<file_sep>/docs/mbt_run-in_pr.md
## mbt run-in pr
### Synopsis
```
mbt run-in pr --src <branch> --dst <branch> [flags]
```
### Options
```
--dst string Destination branch
-h, --help help for pr
--src string Source branch
```
### Options inherited from parent commands
```
-m, --command string Command to execute
--debug Enable debug output
--fail-fast Fail fast on command failure
--in string Path to repo
```
### SEE ALSO
* [mbt run-in](mbt_run-in.md) - Run user defined command
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/docs/index.md
## mbt
mbt - The most flexible build orchestration tool for monorepo
### Synopsis
mbt is a build orchestration utility for monorepo.
In mbt, we use the term `module` to identify an independently buildable unit of code.
A collection of modules stored in a repository is called a manifest.
You can turn any directory into a module by placing a spec file called `.mbt.yml`.
Spec file is written in `yaml` following the schema specified below.
```
name: Unique module name (required)
build: Dictionary of build commands specific to a platform (optional)
default: (optional)
cmd: Default command to run when os specific command is not found (required)
args: Array of arguments to default build command (optional)
linux|darwin|windows:
cmd: Operating system specific command name (required)
args: Array of arguments (optional)
dependencies: An array of modules that this module's build depend on (optional)
fileDependencies: An array of file names that this module's build depend on (optional)
commands: Optional dictionary of custom commands (optional)
name: Custom command name (required)
cmd: Command name (required)
args: Array of arguments (optional)
os: Array of os identifiers where this command should run (optional)
properties: Custom dictionary to hold any module specific information (optional)
```
### Build Command
Build command is operating system specific. When executing `mbt build xxx`
commands, it skips the modules that do not specify a build command for the operating
system build is running on.
Full list of operating systems names that can be used can be
found [here](https://golang.org/doc/install/source#environment)
When the command is applicable for multiple operating systems, you could list it as
the default command. Operating system specific commands take precedence.
### Dependencies
`mbt` comes with a set of primitives to manage build dependencies. Current build
tools do a good job in managing dependencies between source files/projects.
GNU `make` for example does a great job in deciding what parts require building.
`mbt` dependencies work one level above that type of tooling to manage build
relationship between two independent modules.
### Module Dependencies
One advantage of a single repo is that you can share code between multiple modules
more effectively. Building this type of dependencies requires some thought. mbt provides
an easy way to define dependencies between modules and automatically builds the impacted modules
in topological order.
Dependencies are defined in `.mbt.yml` file under 'dependencies' property.
It accepts an array of module names.
For example, `module-a` could define a dependency on `module-b`,
so that any time `module-b` is changed, build command for `module-a` is also executed.
An example of where this could be useful is, shared libraries. Shared library
could be developed independently of its consumers. However, all consumers
are automatically built whenever the shared library is modified.
### File Dependencies
File dependencies are useful in situations where a module should be built
when a file(s) stored outside the module directory is modified. For instance,
a build script that is used to build multiple modules could define a file
dependency in order to trigger the build whenever there's a change in build.
File dependencies should specify the path of the file relative to the root
of the repository.
### Module Version
For each module stored within a repository, `mbt` generates a unique
stable version string. It is calculated based on three source attributes in
module.
- Content stored within the module directory
- Versions of dependent modules
- Content of file dependencies
As a result, version of a module is changed only when any of those attributes
are changed making it a safe attribute to use for tagging the
build artifacts (i.e. tar balls, container images).
### Document Generation
`mbt` has a powerful feature that exposes the module state inferred from
the repository to a template engine. This could be quite useful for generating
documents out of that information. For example, you may have several modules
packaged as docker containers. By using this feature, you could generate a
Kubernetes deployment specification for all of them as of a particular commit
sha.
See `apply` command for more details.
### Options
```
--debug Enable debug output
-h, --help help for mbt
--in string Path to repo
```
### SEE ALSO
* [mbt apply](mbt_apply.md) - Apply repository manifest over a go template
* [mbt build](mbt_build.md) - Run build command
* [mbt describe](mbt_describe.md) - Describe repository manifest
* [mbt run-in](mbt_run-in.md) - Run user defined command
* [mbt version](mbt_version.md) - Show mbt version
###### Auto generated by spf13/cobra on 9-Jul-2018
<file_sep>/lib/repo_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"testing"
"github.com/mbtproject/mbt/e"
"github.com/stretchr/testify/assert"
)
func TestInvalidBranch(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
_, err := NewWorld(t, ".tmp/repo").Repo.BranchCommit("foo")
assert.EqualError(t, err, fmt.Sprintf(msgFailedBranchLookup, "foo"))
assert.EqualError(t, (err.(*e.E)).InnerError(), "no reference found for shorthand 'foo'")
assert.Equal(t, ErrClassUser, (err.(*e.E)).Class())
}
func TestBranchName(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
commit, err := NewWorld(t, ".tmp/repo").Repo.BranchCommit("feature")
check(t, err)
assert.Equal(t, repo.LastCommit.String(), commit.ID())
}
func TestDiffByIndex(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/test.txt", "test contents"))
check(t, repo.Commit("first"))
check(t, repo.WriteContent("app-a/test.txt", "amend contents"))
diff, err := NewWorld(t, ".tmp/repo").Repo.DiffWorkspace()
check(t, err)
assert.Len(t, diff, 1)
}
func TestDirtyWorkspaceForUntracked(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/foo", "a"))
err := NewWorld(t, ".tmp/repo").Repo.EnsureSafeWorkspace()
assert.EqualError(t, err, msgDirtyWorkingDir)
}
func TestDirtyWorkspaceForUpdates(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/foo", "a"))
check(t, repo.Commit("first"))
check(t, repo.WriteContent("app-a/foo", "b"))
err := NewWorld(t, ".tmp/repo").Repo.EnsureSafeWorkspace()
assert.EqualError(t, err, msgDirtyWorkingDir)
}
func TestDirtyWorkspaceForRenames(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.WriteContent("app-a/foo", "a"))
check(t, repo.Commit("first"))
check(t, repo.Rename("app-a/foo", "app-a/bar"))
err := NewWorld(t, ".tmp/repo").Repo.EnsureSafeWorkspace()
assert.EqualError(t, err, msgDirtyWorkingDir)
}
func TestChangesOfFirstCommit(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("readme.md", "hello"))
check(t, repo.Commit("first"))
r := NewWorld(t, ".tmp/repo").Repo
commit, err := r.GetCommit(repo.LastCommit.String())
check(t, err)
d, err := r.Changes(commit)
check(t, err)
assert.Empty(t, d)
}
func TestChangesOfCommitWithOneParent(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("readme.md", "hello"))
check(t, repo.Commit("first"))
check(t, repo.WriteContent("contributing.md", "hello"))
check(t, repo.Commit("second"))
r := NewWorld(t, ".tmp/repo").Repo
commit, err := r.GetCommit(repo.LastCommit.String())
check(t, err)
d, err := r.Changes(commit)
check(t, err)
assert.Len(t, d, 1)
assert.Equal(t, "contributing.md", d[0].NewFile)
}
func TestChangesOfCommitWithMultipleParents(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("readme.md", "hello"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature"))
check(t, repo.WriteContent("foo", "hello"))
check(t, repo.Commit("second"))
check(t, repo.WriteContent("bar", "hello"))
check(t, repo.Commit("third"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.WriteContent("index.md", "hello"))
check(t, repo.Commit("fourth"))
mergeCommitID, err := repo.SimpleMerge("feature", "master")
check(t, err)
check(t, repo.SwitchToBranch("master"))
r := NewWorld(t, ".tmp/repo").Repo
mergeCommit, err := r.GetCommit(mergeCommitID.String())
check(t, err)
delta, err := r.Changes(mergeCommit)
check(t, err)
assert.Len(t, delta, 2)
assert.Equal(t, "bar", delta[0].NewFile)
assert.Equal(t, "foo", delta[1].NewFile)
}
func TestChangesOfCommitWhereOneParentIsAMergeCommit(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("readme.md", "hello"))
check(t, repo.Commit("first"))
check(t, repo.SwitchToBranch("feature-b"))
check(t, repo.SwitchToBranch("feature-a"))
check(t, repo.WriteContent("foo", "hello"))
check(t, repo.Commit("second"))
check(t, repo.WriteContent("bar", "hello"))
check(t, repo.Commit("third"))
check(t, repo.SwitchToBranch("master"))
check(t, repo.WriteContent("index.md", "hello"))
check(t, repo.Commit("fourth"))
check(t, repo.SwitchToBranch("feature-b"))
check(t, repo.WriteContent("car", "hello"))
check(t, repo.Commit("fifth"))
_, err := repo.SimpleMerge("feature-a", "master")
check(t, err)
mergeCommitID, err := repo.SimpleMerge("feature-b", "master")
check(t, err)
check(t, repo.SwitchToBranch("master"))
r := NewWorld(t, ".tmp/repo").Repo
mergeCommit, err := r.GetCommit(mergeCommitID.String())
check(t, err)
delta, err := r.Changes(mergeCommit)
check(t, err)
assert.Len(t, delta, 1)
assert.Equal(t, "car", delta[0].NewFile)
}
func TestGitIgnoreRulesInSafeWorkspace(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("readme.md", "hello"))
check(t, repo.WriteContent(".gitignore", "!*.[Cc]ache/"))
check(t, repo.WriteContent("subdir/.gitignore", ".cache/"))
check(t, repo.Commit("first"))
check(t, repo.WriteContent("subdir/.cache/foo", "hello"))
w := NewWorld(t, ".tmp/repo")
check(t, w.Repo.EnsureSafeWorkspace())
}
<file_sep>/scripts/update_version.go
// +build ignore
package main
import (
"flag"
"fmt"
"io/ioutil"
"regexp"
"strconv"
"strings"
)
var (
major, minor, patch bool
custom string
)
func nextReleaseVersion(currentMajor, currentMinor, currentPatch string) (string, error) {
majorVersion, err := strconv.ParseInt(currentMajor, 10, 32)
if err != nil {
return "", err
}
minorVersion, err := strconv.ParseInt(currentMinor, 10, 32)
if err != nil {
return "", err
}
patchLevel, err := strconv.ParseInt(currentPatch, 10, 32)
if err != nil {
return "", err
}
if major {
majorVersion++
minorVersion = 0
patchLevel = 0
} else if minor {
minorVersion++
patchLevel = 0
} else if patch {
patchLevel++
}
return fmt.Sprintf("%v.%v.%v", majorVersion, minorVersion, patchLevel), nil
}
func main() {
flag.BoolVar(&major, "major", false, "Update major version")
flag.BoolVar(&minor, "minor", false, "Update minor version")
flag.BoolVar(&patch, "patch", false, "Update patch")
flag.StringVar(&custom, "custom", "", "Use a custom version")
flag.Parse()
contentBytes, err := ioutil.ReadFile("cmd/version.go")
if err != nil {
panic(err)
}
content := string(contentBytes)
versionPattern := regexp.MustCompile(`"(?P<Major>\d*?)\.(?P<Minor>\d*?)\.(?P<Patch>\d*?)"`)
match := versionPattern.FindStringSubmatch(content)
if len(match) != 4 {
panic("Unable to find the version string in source")
}
currentVersion := match[0]
// Use the custom version if specified, otherwise calculate the next
// release version.
nextVersion := custom
if custom == "" {
nextVersion, err = nextReleaseVersion(match[1], match[2], match[3])
if err != nil {
panic(err)
}
}
quotedNextVersion := fmt.Sprintf(`"%s"`, nextVersion)
newContent := strings.Replace(content, currentVersion, quotedNextVersion, 1)
err = ioutil.WriteFile("cmd/version.go", []byte(newContent), 0644)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", nextVersion)
}
<file_sep>/lib/utils_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
var (
repoDir, rootDir string
)
func init() {
var err error
repoDir, err = filepath.Abs(".tmp/repo")
if err != nil {
panic(err)
}
rootDir, err = filepath.Abs("/")
if err != nil {
panic(err)
}
}
func TestGitRepoRootForPathWithoutAGitRepo(t *testing.T) {
path, err := GitRepoRoot("/tmp/this/does/not/exist")
assert.NoError(t, err)
assert.Equal(t, rootDir, path)
}
func TestGitRepoRootForRepoDir(t *testing.T) {
clean()
NewTestRepo(t, ".tmp/repo")
path, err := GitRepoRoot(".tmp/repo")
assert.NoError(t, err)
assert.Equal(t, repoDir, path)
}
func TestGitRepoRootForChildDir(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
check(t, repo.InitModule("a/b/c/app-b"))
path, err := GitRepoRoot(".tmp/repo/app-a")
assert.NoError(t, err)
assert.Equal(t, repoDir, path)
path, err = GitRepoRoot(".tmp/repo/a/b/c/app-b")
assert.NoError(t, err)
assert.Equal(t, repoDir, path)
}
func TestGitRepoRootForConflictingFileName(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.WriteContent("a/b/.git", "hello"))
path, err := GitRepoRoot(".tmp/repo/a/b")
assert.NoError(t, err)
assert.Equal(t, repoDir, path)
}
func TestGitRepoRootForAbsPath(t *testing.T) {
clean()
repo := NewTestRepo(t, ".tmp/repo")
check(t, repo.InitModule("app-a"))
abs, err := filepath.Abs(".tmp/repo")
check(t, err)
path, err := GitRepoRoot(filepath.Join(abs, "app-a"))
assert.NoError(t, err)
assert.Equal(t, repoDir, path)
}
<file_sep>/dtrace/dtrace.go
/*
Copyright 2018 MBT Authors.
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 dtrace
import (
"fmt"
"path/filepath"
"runtime"
"github.com/sirupsen/logrus"
)
// Printf writes a debug entry to the log
func Printf(format string, args ...interface{}) {
var (
function, file string
line int
)
pc, _, _, ok := runtime.Caller(1)
if ok {
pcs := []uintptr{pc}
frames := runtime.CallersFrames(pcs)
frame, _ := frames.Next()
function = frame.Function
file = filepath.Base(frame.File)
line = frame.Line
}
logrus.Debugf(fmt.Sprintf("%s (@%s %s,%v)", format, function, file, line), args...)
}
<file_sep>/lib/reducer.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"strings"
"github.com/mbtproject/mbt/trie"
)
type stdReducer struct {
Log Log
}
// NewReducer creates a new reducer
func NewReducer(log Log) Reducer {
return &stdReducer{Log: log}
}
func (r *stdReducer) Reduce(modules Modules, deltas []*DiffDelta) (Modules, error) {
t := trie.NewTrie()
filtered := make(Modules, 0)
for _, d := range deltas {
// Current comparison is case insensitive. This is problematic
// for case sensitive file systems.
// Perhaps we can read core.ignorecase configuration value
// in git and adjust accordingly.
nfp := strings.ToLower(d.NewFile)
r.Log.Debug("Index change %s", nfp)
t.Add(nfp, nfp)
}
for _, m := range modules {
mp := m.Path()
if mp == "" {
// Fast path for the root module if there's one.
// Root module should match any change.
if len(deltas) > 0 {
filtered = append(filtered, m)
}
continue
}
// Append / to the end of module path to make sure
// we restrict the search exactly for that path.
// for example, change in path a/bb should not
// match a module in a/b
mp = strings.ToLower(fmt.Sprintf("%s/", m.Path()))
r.Log.Debug("Filter by module path %s", mp)
if t.ContainsPrefix(mp) {
filtered = append(filtered, m)
} else {
for _, p := range m.FileDependencies() {
fdp := strings.ToLower(p)
r.Log.Debug("Filter by file dependency path %s", fdp)
if t.ContainsPrefix(fdp) {
filtered = append(filtered, m)
}
}
}
}
return filtered, nil
}
<file_sep>/lib/mbt_test.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"io"
"io/ioutil"
"os"
"path"
"testing"
"time"
yaml "github.com/go-yaml/yaml"
git "github.com/libgit2/git2go/v28"
"github.com/mbtproject/mbt/e"
"github.com/mbtproject/mbt/intercept"
)
type TestRepository struct {
Dir string
Repo *git.Repository
LastCommit *git.Oid
CurrentBranch string
}
func (r *TestRepository) InitModule(p string) error {
return r.InitModuleWithOptions(p, &Spec{
Name: path.Base(p),
Build: map[string]*Cmd{
"darwin": {"./build.sh", []string{}},
"linux": {"./build.sh", []string{}},
"windows": {"powershell", []string{"-ExecutionPolicy", "Bypass", "-File", ".\\build.ps1"}},
},
Properties: map[string]interface{}{"foo": "bar", "jar": "car"},
})
}
func (r *TestRepository) InitModuleWithOptions(p string, mod *Spec) error {
modDir := path.Join(r.Dir, p)
err := os.MkdirAll(modDir, 0755)
if err != nil {
return err
}
buff, err := yaml.Marshal(mod)
if err != nil {
return err
}
err = ioutil.WriteFile(path.Join(modDir, ".mbt.yml"), buff, 0644)
if err != nil {
return err
}
return nil
}
func (r *TestRepository) WriteContent(file, content string) error {
fpath := path.Join(r.Dir, file)
dir := path.Dir(fpath)
if dir != "" {
err := os.MkdirAll(dir, 0755)
if err != nil {
return err
}
}
return ioutil.WriteFile(fpath, []byte(content), 0744)
}
func (r *TestRepository) AppendContent(file, content string) error {
fpath := path.Join(r.Dir, file)
dir := path.Dir(fpath)
if dir != "" {
err := os.MkdirAll(dir, 0755)
if err != nil {
return err
}
}
fd, err := os.OpenFile(fpath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0744)
if err != nil {
return err
}
defer fd.Close()
_, err = fd.WriteString(content)
return err
}
func (r *TestRepository) Commit(message string) error {
idx, err := r.Repo.Index()
if err != nil {
return err
}
err = idx.AddAll([]string{"."}, git.IndexAddCheckPathspec, func(p string, f string) int {
return 0
})
if err != nil {
return err
}
err = idx.Write()
if err != nil {
return err
}
oid, err := idx.WriteTree()
if err != nil {
return err
}
tree, err := r.Repo.LookupTree(oid)
if err != nil {
return err
}
sig := &git.Signature{
Email: "<EMAIL>",
Name: "alice",
When: time.Now(),
}
parents := []*git.Commit{}
isEmpty, err := r.Repo.IsEmpty()
if err != nil {
return nil
}
if !isEmpty {
currentBranch, err := r.Repo.Head()
if err != nil {
return err
}
bc, err := r.Repo.LookupCommit(currentBranch.Target())
if err != nil {
return err
}
parents = append(parents, bc)
}
r.LastCommit, err = r.Repo.CreateCommit("HEAD", sig, sig, message, tree, parents...)
if err != nil {
return err
}
return nil
}
func (r *TestRepository) SwitchToBranch(name string) error {
branch, err := r.Repo.LookupBranch(name, git.BranchAll)
if err != nil {
head, err := r.Repo.Head()
if err != nil {
return err
}
hc, err := r.Repo.LookupCommit(head.Target())
if err != nil {
return err
}
branch, err = r.Repo.CreateBranch(name, hc, false)
if err != nil {
return err
}
}
commit, err := r.Repo.LookupCommit(branch.Target())
if err != nil {
return err
}
tree, err := commit.Tree()
if err != nil {
return err
}
err = r.Repo.CheckoutTree(tree, &git.CheckoutOpts{
Strategy: git.CheckoutForce,
})
if err != nil {
return err
}
return r.Repo.SetHead(fmt.Sprintf("refs/heads/%s", name))
}
func (r *TestRepository) CheckoutAndDetach(commit string) error {
oid, err := git.NewOid(commit)
if err != nil {
return err
}
gitCommit, err := r.Repo.LookupCommit(oid)
if err != nil {
return err
}
tree, err := gitCommit.Tree()
if err != nil {
return err
}
err = r.Repo.CheckoutTree(tree, &git.CheckoutOpts{Strategy: git.CheckoutForce})
if err != nil {
return err
}
return r.Repo.SetHeadDetached(oid)
}
func (r *TestRepository) SimpleMerge(src, dst string) (*git.Oid, error) {
srcRef, err := r.Repo.References.Dwim(src)
if err != nil {
return nil, err
}
srcCommit, err := r.Repo.LookupCommit(srcRef.Target())
if err != nil {
return nil, err
}
dstRef, err := r.Repo.References.Dwim(dst)
if err != nil {
return nil, err
}
dstCommit, err := r.Repo.LookupCommit(dstRef.Target())
if err != nil {
return nil, err
}
index, err := r.Repo.MergeCommits(dstCommit, srcCommit, nil)
if err != nil {
return nil, err
}
treeID, err := index.WriteTreeTo(r.Repo)
if err != nil {
return nil, err
}
mergeTree, err := r.Repo.LookupTree(treeID)
if err != nil {
return nil, err
}
sig := &git.Signature{
Email: "<EMAIL>",
Name: "alice",
When: time.Now(),
}
head, err := r.Repo.CreateCommit(dstRef.Name(), sig, sig, "Merged", mergeTree, dstCommit, srcCommit)
if err != nil {
return nil, err
}
err = r.Repo.CheckoutHead(&git.CheckoutOpts{Strategy: git.CheckoutForce})
if err != nil {
return nil, err
}
return head, err
}
func (r *TestRepository) Remove(p string) error {
return os.RemoveAll(path.Join(r.Dir, p))
}
func (r *TestRepository) Rename(old, new string) error {
return os.Rename(path.Join(r.Dir, old), path.Join(r.Dir, new))
}
func (r *TestRepository) WritePowershellScript(p, content string) error {
return r.WriteContent(p, content)
}
func (r *TestRepository) WriteShellScript(p, content string) error {
return r.WriteContent(p, fmt.Sprintf("#!/bin/sh\n%s", content))
}
func createTestRepository(dir string) (*TestRepository, error) {
err := os.MkdirAll(dir, 0755)
if err != nil {
return nil, err
}
repo, err := git.InitRepository(dir, false)
if err != nil {
return nil, err
}
return &TestRepository{dir, repo, nil, "master"}, nil
}
func NewTestRepoForBench(b *testing.B, dir string) *TestRepository {
repo, err := createTestRepository(dir)
if err != nil {
b.Fatalf("%v", err)
}
return repo
}
func NewTestRepo(t *testing.T, dir string) *TestRepository {
repo, err := createTestRepository(dir)
check(t, err)
return repo
}
func clean() {
os.RemoveAll(".tmp")
}
func check(t *testing.T, err error) {
if err != nil {
ee, ok := err.(*e.E)
if ok {
err = ee.WithExtendedInfo()
}
t.Fatal(err)
}
}
type World struct {
Log Log
Repo *TestRepo
Discover *TestDiscover
Reducer *TestReducer
ManifestBuilder *TestManifestBuilder
WorkspaceManager *TestWorkspaceManager
ProcessManager *TestProcessManager
System *TestSystem
}
/* sXxx methods below are used to safely convert interface{} to an interface type */
func sErr(e interface{}) error {
if e == nil {
return nil
}
return e.(error)
}
func sBlob(e interface{}) Blob {
if e == nil {
return nil
}
return e.(Blob)
}
func sCommit(e interface{}) Commit {
if e == nil {
return nil
}
return e.(Commit)
}
func sManifest(e interface{}) *Manifest {
if e == nil {
return nil
}
return e.(*Manifest)
}
func sModules(e interface{}) Modules {
if e == nil {
return nil
}
return e.(Modules)
}
func sBuildSummary(e interface{}) *BuildSummary {
if e == nil {
return nil
}
return e.(*BuildSummary)
}
func sRunResult(e interface{}) *RunResult {
if e == nil {
return nil
}
return e.(*RunResult)
}
func sReference(e interface{}) Reference {
if e == nil {
return nil
}
return e.(Reference)
}
type TestRepo struct {
Interceptor *intercept.Interceptor
}
func (r *TestRepo) GetCommit(sha string) (Commit, error) {
ret := r.Interceptor.Call("GetCommit", sha)
return sCommit(ret[0]), sErr(ret[1])
}
func (r *TestRepo) Path() string {
ret := r.Interceptor.Call("Path")
return ret[0].(string)
}
func (r *TestRepo) Diff(a, b Commit) ([]*DiffDelta, error) {
ret := r.Interceptor.Call("Diff", a, b)
return ret[0].([]*DiffDelta), sErr(ret[1])
}
func (r *TestRepo) DiffMergeBase(from, to Commit) ([]*DiffDelta, error) {
ret := r.Interceptor.Call("DiffMergeBase", from, to)
return ret[0].([]*DiffDelta), sErr(ret[1])
}
func (r *TestRepo) DiffWorkspace() ([]*DiffDelta, error) {
ret := r.Interceptor.Call("DiffWorkspace")
return ret[0].([]*DiffDelta), sErr(ret[1])
}
func (r *TestRepo) Changes(c Commit) ([]*DiffDelta, error) {
ret := r.Interceptor.Call("Changes", c)
return ret[0].([]*DiffDelta), sErr(ret[1])
}
func (r *TestRepo) WalkBlobs(a Commit, callback BlobWalkCallback) error {
ret := r.Interceptor.Call("WalkBlobs", a, callback)
return sErr(ret[0])
}
func (r *TestRepo) BlobContents(blob Blob) ([]byte, error) {
ret := r.Interceptor.Call("BlobContents", blob)
return ret[0].([]byte), sErr(ret[1])
}
func (r *TestRepo) BlobContentsFromTree(commit Commit, path string) ([]byte, error) {
ret := r.Interceptor.Call("BlobContentsFromTree", commit, path)
return ret[0].([]byte), sErr(ret[1])
}
func (r *TestRepo) EntryID(commit Commit, path string) (string, error) {
ret := r.Interceptor.Call("EntryID", commit, path)
return ret[0].(string), sErr(ret[1])
}
func (r *TestRepo) BranchCommit(name string) (Commit, error) {
ret := r.Interceptor.Call("BranchCommit", name)
return sCommit(ret[0]), sErr(ret[1])
}
func (r *TestRepo) CurrentBranch() (string, error) {
ret := r.Interceptor.Call("CurrentBranch")
return ret[0].(string), sErr(ret[1])
}
func (r *TestRepo) CurrentBranchCommit() (Commit, error) {
ret := r.Interceptor.Call("CurrentBranchCommit")
return sCommit(ret[0]), sErr(ret[1])
}
func (r *TestRepo) IsEmpty() (bool, error) {
ret := r.Interceptor.Call("IsEmpty")
return ret[0].(bool), sErr(ret[1])
}
func (r *TestRepo) FindAllFilesInWorkspace(pathSpec []string) ([]string, error) {
ret := r.Interceptor.Call("FindAllFilesInWorkspace", pathSpec)
return ret[0].([]string), sErr(ret[1])
}
func (r *TestRepo) EnsureSafeWorkspace() error {
ret := r.Interceptor.Call("EnsureSafeWorkspace")
return sErr(ret[0])
}
func (r *TestRepo) Checkout(commit Commit) (Reference, error) {
ret := r.Interceptor.Call("Checkout", commit)
return sReference(ret[0]), sErr(ret[1])
}
func (r *TestRepo) CheckoutReference(reference Reference) error {
ret := r.Interceptor.Call("CheckoutReference", reference)
return sErr(ret[0])
}
func (r *TestRepo) MergeBase(a, b Commit) (Commit, error) {
ret := r.Interceptor.Call("MergeBase", a, b)
return sCommit(ret[0]), sErr(ret[1])
}
type TestManifestBuilder struct {
Interceptor *intercept.Interceptor
}
func (b *TestManifestBuilder) ByDiff(from, to Commit) (*Manifest, error) {
ret := b.Interceptor.Call("ByDiff", from, to)
return sManifest(ret[0]), sErr(ret[1])
}
func (b *TestManifestBuilder) ByPr(src, dst string) (*Manifest, error) {
ret := b.Interceptor.Call("ByPr", src, dst)
return sManifest(ret[0]), sErr(ret[1])
}
func (b *TestManifestBuilder) ByCommit(sha Commit) (*Manifest, error) {
ret := b.Interceptor.Call("ByCommit", sha)
return sManifest(ret[0]), sErr(ret[1])
}
func (b *TestManifestBuilder) ByCommitContent(sha Commit) (*Manifest, error) {
ret := b.Interceptor.Call("ByCommitContent", sha)
return sManifest(ret[0]), sErr(ret[1])
}
func (b *TestManifestBuilder) ByBranch(name string) (*Manifest, error) {
ret := b.Interceptor.Call("ByBranch", name)
return sManifest(ret[0]), sErr(ret[1])
}
func (b *TestManifestBuilder) ByCurrentBranch() (*Manifest, error) {
ret := b.Interceptor.Call("ByCurrentBranch")
return sManifest(ret[0]), sErr(ret[1])
}
func (b *TestManifestBuilder) ByWorkspace() (*Manifest, error) {
ret := b.Interceptor.Call("ByWorkspace")
return sManifest(ret[0]), sErr(ret[1])
}
func (b *TestManifestBuilder) ByWorkspaceChanges() (*Manifest, error) {
ret := b.Interceptor.Call("ByWorkspaceChanges")
return sManifest(ret[0]), sErr(ret[1])
}
type TestSystem struct {
Interceptor *intercept.Interceptor
}
func (s *TestSystem) ApplyBranch(templatePath, branch string, output io.Writer) error {
ret := s.Interceptor.Call("ApplyBranch", templatePath, branch, output)
return sErr(ret[0])
}
func (s *TestSystem) ApplyCommit(sha, templatePath string, output io.Writer) error {
ret := s.Interceptor.Call("ApplyCommit", sha, templatePath, output)
return sErr(ret[0])
}
func (s *TestSystem) ApplyHead(templatePath string, output io.Writer) error {
ret := s.Interceptor.Call("ApplyHead", templatePath, output)
return sErr(ret[0])
}
func (s *TestSystem) ApplyLocal(templatePath string, output io.Writer) error {
ret := s.Interceptor.Call("ApplyLocal", templatePath, output)
return sErr(ret[0])
}
func (s *TestSystem) BuildBranch(name string, filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildBranch", name, filterOptions, options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) BuildPr(src, dst string, options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildPr", src, dst, options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) BuildDiff(from, to string, options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildDiff", from, to, options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) BuildCurrentBranch(filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildCurrentBranch", filterOptions, options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) BuildCommit(commit string, filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildCommit", commit, filterOptions, options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) BuildCommitContent(commit string, options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildCommitContent", commit, options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) BuildWorkspace(filterOptions *FilterOptions, options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildWorkspace", filterOptions, options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) BuildWorkspaceChanges(options *CmdOptions) (*BuildSummary, error) {
ret := s.Interceptor.Call("BuildWorkspaceChanges", options)
return sBuildSummary(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInBranch(command, name string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInBranch", command, name, filterOptions, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInPr(command, src, dst string, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInPr", command, src, dst, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInDiff(command, from, to string, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInDiff", command, from, to, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInCurrentBranch(command string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInCurrentBranch", command, filterOptions, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInCommit(command, commit string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInCommit", command, commit, filterOptions, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInCommitContent(command, commit string, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInCommitContent", command, commit, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInWorkspace(command string, filterOptions *FilterOptions, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInWorkspace", command, filterOptions, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) RunInWorkspaceChanges(command string, options *CmdOptions) (*RunResult, error) {
ret := s.Interceptor.Call("RunInWorkspaceChanges", command, options)
return sRunResult(ret[0]), sErr(ret[1])
}
func (s *TestSystem) IntersectionByCommit(first, second string) (Modules, error) {
ret := s.Interceptor.Call("IntersectionByCommit", first, second)
return sModules(ret[0]), sErr(ret[1])
}
func (s *TestSystem) IntersectionByBranch(first, second string) (Modules, error) {
ret := s.Interceptor.Call("IntersectionByBranch", first, second)
return sModules(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByDiff(from, to string) (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByDiff", from, to)
return sManifest(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByPr(src, dst string) (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByPr", src, dst)
return sManifest(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByCommit(sha string) (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByCommit", sha)
return sManifest(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByCommitContent(sha string) (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByCommitContent", sha)
return sManifest(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByBranch(name string) (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByBranch", name)
return sManifest(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByCurrentBranch() (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByCurrentBranch")
return sManifest(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByWorkspace() (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByWorkspace")
return sManifest(ret[0]), sErr(ret[1])
}
func (s *TestSystem) ManifestByWorkspaceChanges() (*Manifest, error) {
ret := s.Interceptor.Call("ManifestByWorkspaceChanges")
return sManifest(ret[0]), sErr(ret[1])
}
type TestDiscover struct {
Interceptor *intercept.Interceptor
}
func (d *TestDiscover) ModulesInCommit(commit Commit) (Modules, error) {
ret := d.Interceptor.Call("ModulesInCommit", commit)
return sModules(ret[0]), sErr(ret[1])
}
func (d *TestDiscover) ModulesInWorkspace() (Modules, error) {
ret := d.Interceptor.Call("ModulesInWorkspace")
return sModules(ret[0]), sErr(ret[1])
}
type TestReducer struct {
Interceptor *intercept.Interceptor
}
func (r *TestReducer) Reduce(modules Modules, deltas []*DiffDelta) (Modules, error) {
ret := r.Interceptor.Call("Reduce", modules, deltas)
return sModules(ret[0]), sErr(ret[1])
}
type TestWorkspaceManager struct {
Interceptor *intercept.Interceptor
}
func (w *TestWorkspaceManager) CheckoutAndRun(commit string, fn func() (interface{}, error)) (interface{}, error) {
ret := w.Interceptor.Call("CheckoutAndRun", commit, fn)
return ret[0], sErr(ret[1])
}
type TestProcessManager struct {
Interceptor *intercept.Interceptor
}
func (p *TestProcessManager) Exec(manifest *Manifest, module *Module, options *CmdOptions, command string, args ...string) error {
rest := []interface{}{manifest, module, options, command}
for _, a := range args {
rest = append(rest, a)
}
ret := p.Interceptor.Call("Exec", rest...)
return sErr(ret[0])
}
func buildWorld(repo string, failureCallback func(error)) *World {
log := NewStdLog(LogLevelNormal)
libgitRepo, err := NewLibgitRepo(repo, log)
if err != nil {
failureCallback(err)
return nil
}
r := &TestRepo{Interceptor: intercept.NewInterceptor(libgitRepo)}
discover := &TestDiscover{Interceptor: intercept.NewInterceptor(NewDiscover(r, log))}
reducer := &TestReducer{Interceptor: intercept.NewInterceptor(NewReducer(log))}
mb := &TestManifestBuilder{Interceptor: intercept.NewInterceptor(NewManifestBuilder(r, reducer, discover, log))}
wm := &TestWorkspaceManager{Interceptor: intercept.NewInterceptor(NewWorkspaceManager(log, r))}
pm := &TestProcessManager{Interceptor: intercept.NewInterceptor(NewProcessManager(log))}
return &World{
Log: log,
Repo: r,
Discover: discover,
Reducer: reducer,
ManifestBuilder: mb,
WorkspaceManager: wm,
ProcessManager: pm,
System: &TestSystem{Interceptor: intercept.NewInterceptor(initSystem(log, r, mb, discover, reducer, wm, pm))},
}
}
func NewWorld(t *testing.T, repo string) *World {
return buildWorld(repo, func(err error) { check(t, err) })
}
func NewBenchmarkWorld(b *testing.B, repo string) *World {
return buildWorld(repo, func(err error) { b.Fatal(err) })
}
<file_sep>/trie/trie_test.go
/*
Copyright 2018 MBT Authors.
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 trie
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestEmptyTrie(t *testing.T) {
i := NewTrie()
m := i.Match("abc")
assert.False(t, m.Success)
assert.False(t, m.IsCompleteMatch)
assert.Equal(t, "", m.NearestPrefix)
assert.Nil(t, m.Value)
}
func TestFindingEmptyString(t *testing.T) {
i := NewTrie()
i.Add("abc", 42)
m := i.Match("")
assert.True(t, m.Success)
assert.True(t, m.IsCompleteMatch)
assert.Equal(t, "", m.NearestPrefix)
assert.Nil(t, m.Value)
}
func TestAddingEmptyString(t *testing.T) {
i := NewTrie()
i.Add("", 42)
m := i.Match("")
assert.True(t, m.Success)
assert.True(t, m.IsCompleteMatch)
assert.Equal(t, "", m.NearestPrefix)
assert.Equal(t, 42, m.Value)
m = i.Match("a")
assert.False(t, m.Success)
assert.False(t, m.IsCompleteMatch)
assert.Equal(t, "", m.NearestPrefix)
assert.Nil(t, m.Value)
}
func TestSimpleMatch(t *testing.T) {
i := NewTrie()
i.Add("a", 42)
m := i.Match("a")
assert.True(t, m.Success)
assert.True(t, m.IsCompleteMatch)
assert.Equal(t, "a", m.NearestPrefix)
assert.Equal(t, 42, m.Value)
}
func TestAddingSameKeyTwice(t *testing.T) {
i := NewTrie()
i.Add("abc", 42)
i.Add("abc", 43)
m := i.Match("abc")
assert.True(t, m.Success)
assert.True(t, m.IsCompleteMatch)
assert.Equal(t, "abc", m.NearestPrefix)
// Last one should win
assert.Equal(t, 43, m.Value)
}
func TestPrefix(t *testing.T) {
i := NewTrie()
i.Add("aa", 42)
i.Add("aabb", 43)
m := i.Match("aa")
assert.True(t, m.Success)
assert.True(t, m.IsCompleteMatch)
assert.Equal(t, "aa", m.NearestPrefix)
assert.Equal(t, 42, m.Value)
m = i.Match("aab")
assert.True(t, m.Success)
assert.False(t, m.IsCompleteMatch)
assert.Equal(t, "aab", m.NearestPrefix)
assert.Nil(t, m.Value)
m = i.Match("aabb")
assert.True(t, m.Success)
assert.True(t, m.IsCompleteMatch)
assert.Equal(t, "aabb", m.NearestPrefix)
assert.Equal(t, 43, m.Value)
m = i.Match("ab")
assert.False(t, m.Success)
assert.False(t, m.IsCompleteMatch)
assert.Equal(t, "a", m.NearestPrefix)
assert.Nil(t, m.Value)
}
func TestUnsuccessfulMatch(t *testing.T) {
i := NewTrie()
i.Add("abc", 42)
m := i.Match("def")
assert.False(t, m.Success)
assert.False(t, m.IsCompleteMatch)
assert.Equal(t, "", m.NearestPrefix)
assert.Nil(t, m.Value)
}
func TestUnicodeEntries(t *testing.T) {
i := NewTrie()
i.Add("😄🍓💩👠", 42)
m := i.Match("😄🍓")
assert.True(t, m.Success)
assert.False(t, m.IsCompleteMatch)
assert.Equal(t, "😄🍓", m.NearestPrefix)
assert.Nil(t, m.Value)
m = i.Match("😄🍓💩👠")
assert.True(t, m.Success)
assert.True(t, m.IsCompleteMatch)
assert.Equal(t, "😄🍓💩👠", m.NearestPrefix)
assert.Equal(t, 42, m.Value)
m = i.Match("🍓💩")
assert.False(t, m.Success)
assert.False(t, m.IsCompleteMatch)
assert.Equal(t, "", m.NearestPrefix)
assert.Nil(t, m.Value)
}
func TestFind(t *testing.T) {
i := NewTrie()
i.Add("aba", 42)
i.Add("abb", 43)
v, ok := i.Find("aba")
assert.True(t, ok)
assert.Equal(t, 42, v)
v, ok = i.Find("abb")
assert.True(t, ok)
assert.Equal(t, 43, v)
v, ok = i.Find("ab")
assert.False(t, ok)
assert.Nil(t, v)
v, ok = i.Find("")
assert.True(t, ok)
assert.Nil(t, v)
v, ok = i.Find("def")
assert.False(t, ok)
assert.Nil(t, v)
i.Add("", 42)
v, ok = i.Find("")
assert.True(t, ok)
assert.Equal(t, 42, v)
}
func TestContainsPrefix(t *testing.T) {
i := NewTrie()
i.Add("aba", 42)
assert.True(t, i.ContainsPrefix("aba"))
assert.True(t, i.ContainsPrefix("ab"))
assert.True(t, i.ContainsPrefix(""))
assert.False(t, i.ContainsPrefix("abc"))
assert.False(t, i.ContainsPrefix("def"))
}
func TestContainsProperPrefix(t *testing.T) {
i := NewTrie()
i.Add("aba", 42)
assert.True(t, i.ContainsProperPrefix("ab"))
assert.False(t, i.ContainsProperPrefix(""))
assert.False(t, i.ContainsProperPrefix("aba"))
assert.False(t, i.ContainsProperPrefix("def"))
assert.False(t, i.ContainsProperPrefix("ba"))
}
<file_sep>/utils/strings.go
/*
Copyright 2018 MBT Authors.
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 utils
import (
"strings"
)
// IsSubsequence takes two strings and returns true
// if the second string is a subsequence of the first.
// If ignoreCase is set, the comparison will be
// case insensitive.
// https://en.wikipedia.org/wiki/Subsequence
func IsSubsequence(input, target string, ignoreCase bool) bool {
if ignoreCase {
input = strings.ToLower(input)
target = strings.ToLower(target)
}
idx := 0
targetArray := []rune(target)
for _, r := range input {
if len(targetArray) > idx && targetArray[idx] == r {
idx++
}
}
return idx == len(targetArray)
}
<file_sep>/trie/trie.go
/*
Copyright 2018 MBT Authors.
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 trie
// Trie is a representation of Prefix Trie data structure.
type Trie struct {
root *node
}
// Match is a result of looking up a value in a Trie.
type Match struct {
// Indicates whether this is a successful match or not.
Success bool
// Indicates whether the input matches a complete entry or not.
IsCompleteMatch bool
// For successful results (i.e. Success = true), this field has
// the same value as string being searched for.
// For unsuccessful results (i.e. Success = false), it contains
// the closest matching prefix.
NearestPrefix string
// For complete matches, we also return the value stored in that node.
Value interface{}
}
type node struct {
prefix string
isCompleteMatch bool
children map[rune]*node
value interface{}
}
// NewTrie creates a new instance of Trie.
func NewTrie() *Trie {
return &Trie{
root: &node{
prefix: "",
isCompleteMatch: true,
children: make(map[rune]*node),
},
}
}
// Add creates a new entry in Trie.
func (t *Trie) Add(key string, value interface{}) *Trie {
addOne(t.root, []rune(key), value)
return t
}
// Match searches the specified key in Trie.
func (t *Trie) Match(key string) *Match {
return findCore([]rune(key), t.root)
}
// ContainsPrefix returns true if trie contains the specified key
// with or without a value.
func (t *Trie) ContainsPrefix(key string) bool {
m := t.Match(key)
return m.Success
}
// ContainsProperPrefix returns true if specified key is a
// proper prefix of an entry in the trie. A proper prefix of a key is
// a string that is not an exact match. For example if you store
// key "aba", both "a" and "ab" are proper prefixes but "aba" is not.
// In this implementation, empty string is not considered as a
// proper prefix unless a call to .Add is made with an empty string.
func (t *Trie) ContainsProperPrefix(key string) bool {
m := t.Match(key)
return m.Success && !m.IsCompleteMatch
}
// Find returns the value specified with a given key.
// If the key is not found or a partial match, it returns
// an additional boolean value indicating the failure.
// Empty string will always return true but value may be null
// unless a call to .Add is made with an empty string and a non nil value.
func (t *Trie) Find(key string) (interface{}, bool) {
m := t.Match(key)
return m.Value, m.IsCompleteMatch
}
func addOne(to *node, from []rune, value interface{}) {
if len(from) == 0 {
to.isCompleteMatch = true
to.value = value
return
}
head := from[0]
next, ok := to.children[head]
if !ok {
next = &node{
prefix: to.prefix + string(head),
children: make(map[rune]*node),
}
to.children[head] = next
}
addOne(next, from[1:], value)
}
func findCore(target []rune, in *node) *Match {
if len(target) == 0 {
return &Match{
Success: true,
IsCompleteMatch: in.isCompleteMatch,
NearestPrefix: in.prefix,
Value: in.value,
}
}
head := target[0]
if n, ok := in.children[head]; ok {
return findCore(target[1:], n)
}
return &Match{
Success: false,
NearestPrefix: in.prefix,
}
}
<file_sep>/graph/top_sort_test.go
/*
Copyright 2018 MBT Authors.
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 graph
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
type node struct {
name string
children []*node
}
type testNodeProvider struct {
childError error
}
func (n *testNodeProvider) ID(vertex interface{}) interface{} {
return vertex.(*node).name
}
func (n *testNodeProvider) ChildCount(vertex interface{}) int {
return len(vertex.(*node).children)
}
func (n *testNodeProvider) Child(vertex interface{}, index int) (interface{}, error) {
if n.childError != nil {
return nil, n.childError
}
return vertex.(*node).children[index], nil
}
func newNode(name string) *node {
return &node{
name: name,
children: []*node{},
}
}
func TestNoDependency(t *testing.T) {
n := newNode("a")
s, _ := TopSort(&testNodeProvider{}, n)
assert.Equal(t, 1, len(s))
assert.Equal(t, n, s[0])
}
func TestSingleDependency(t *testing.T) {
a := newNode("a")
b := newNode("b")
a.children = []*node{b}
s, _ := TopSort(&testNodeProvider{}, a, b)
assert.Equal(t, 2, len(s))
assert.Equal(t, b, s[0])
assert.Equal(t, a, s[1])
}
func TestDiamondDependency(t *testing.T) {
a := newNode("a")
b := newNode("b")
c := newNode("c")
d := newNode("d")
b.children = []*node{d}
c.children = []*node{d}
a.children = []*node{b, c}
s, _ := TopSort(&testNodeProvider{}, a, b, c, d)
assert.Equal(t, 4, len(s))
assert.Equal(t, d, s[0])
assert.Equal(t, b, s[1])
assert.Equal(t, c, s[2])
assert.Equal(t, a, s[3])
}
func TestDirectCircularDependency(t *testing.T) {
a := newNode("a")
a.children = []*node{a}
s, err := TopSort(&testNodeProvider{}, a)
cErr := err.(*CycleError)
assert.EqualError(t, cErr, "not a dag")
assert.Equal(t, a, cErr.Path[0])
assert.Equal(t, a, cErr.Path[1])
assert.Nil(t, s)
}
func TestIndirectCircularDependency(t *testing.T) {
a := newNode("a")
b := newNode("b")
b.children = []*node{a}
a.children = []*node{b}
s, err := TopSort(&testNodeProvider{}, a, b)
cErr := err.(*CycleError)
assert.EqualError(t, cErr, "not a dag")
assert.Len(t, cErr.Path, 3)
assert.Equal(t, a, cErr.Path[0])
assert.Equal(t, b, cErr.Path[1])
assert.Equal(t, a, cErr.Path[2])
assert.Nil(t, s)
}
func TestIndirectCircularDependencyForDuplicatedRoots(t *testing.T) {
a := newNode("a")
b := newNode("b")
b.children = []*node{a}
a.children = []*node{b}
s, err := TopSort(&testNodeProvider{}, a, b, a, b)
cErr := err.(*CycleError)
assert.EqualError(t, cErr, "not a dag")
assert.Len(t, cErr.Path, 3)
assert.Equal(t, a, cErr.Path[0])
assert.Equal(t, b, cErr.Path[1])
assert.Equal(t, a, cErr.Path[2])
assert.Nil(t, s)
}
func TestCommonLinksFromDisjointNodes(t *testing.T) {
a := newNode("a")
b := newNode("b")
c := newNode("c")
a.children = []*node{c}
b.children = []*node{c}
s, _ := TopSort(&testNodeProvider{}, a, b)
assert.Equal(t, 3, len(s))
assert.Equal(t, c, s[0])
assert.Equal(t, a, s[1])
assert.Equal(t, b, s[2])
}
func TestIdentity(t *testing.T) {
a1 := newNode("a")
a2 := newNode("a")
s, _ := TopSort(&testNodeProvider{}, a1, a2)
assert.Equal(t, 1, len(s))
assert.Equal(t, a1, s[0])
}
func TestNilInput(t *testing.T) {
_, err := TopSort(nil)
assert.EqualError(t, err, "nodeProvider should be a valid reference")
}
func TestEmptyInput(t *testing.T) {
s, err := TopSort(&testNodeProvider{})
assert.NoError(t, err)
assert.Len(t, s, 0)
}
func TestGetChildrenError(t *testing.T) {
a := newNode("a")
b := newNode("b")
a.children = []*node{b}
_, err := TopSort(&testNodeProvider{childError: errors.New("foo")}, a)
assert.EqualError(t, err, "foo")
}
func TestComplexGraph(t *testing.T) {
/*
a -> [b, c, d]
b -> [c]
c -> [e]
d -> [c, g]
e -> []
f -> [c]
g -> [f]
*/
a := newNode("a")
b := newNode("b")
c := newNode("c")
d := newNode("d")
e := newNode("e")
f := newNode("f")
g := newNode("g")
a.children = []*node{b, c, d}
b.children = []*node{c}
c.children = []*node{e}
d.children = []*node{c, g}
f.children = []*node{c}
g.children = []*node{f}
s, err := TopSort(&testNodeProvider{}, a)
assert.Nil(t, err)
assert.Equal(t, 7, len(s))
assert.Equal(t, e, s[0])
assert.Equal(t, c, s[1])
assert.Equal(t, b, s[2])
assert.Equal(t, f, s[3])
assert.Equal(t, g, s[4])
assert.Equal(t, d, s[5])
assert.Equal(t, a, s[6])
}
func TestComplexCycle(t *testing.T) {
/*
a -> [b, c, d]
b -> [c]
c -> [e]
d -> [c, g]
e -> [f]
f -> [c]
g -> [f]
*/
a := newNode("a")
b := newNode("b")
c := newNode("c")
d := newNode("d")
e := newNode("e")
f := newNode("f")
g := newNode("g")
a.children = []*node{b, c, d}
b.children = []*node{c}
c.children = []*node{e}
d.children = []*node{c, g}
f.children = []*node{c}
g.children = []*node{f}
e.children = []*node{f}
s, err := TopSort(&testNodeProvider{}, a)
cErr := err.(*CycleError)
assert.Nil(t, s)
assert.EqualError(t, cErr, "not a dag")
assert.Len(t, cErr.Path, 6)
assert.Equal(t, a, cErr.Path[0])
assert.Equal(t, b, cErr.Path[1])
assert.Equal(t, c, cErr.Path[2])
assert.Equal(t, e, cErr.Path[3])
assert.Equal(t, f, cErr.Path[4])
assert.Equal(t, c, cErr.Path[5])
}
<file_sep>/CONTRIBUTING.md
## Contributing
We always welcome pull requests. This guide will help you to ensure that that your time is spent wisely.
If you are thinking of introduing a new feature or making a significant change to an existing behavior, discuss it
first with the maintainers by creating an issue.
### Process
- Fork and clone the repo
- Use a text editor with support for .editorconfig
- Implement the change
- Ensure a new test cases are added to cover new code
- Ensure you can run `make build` command without errors
- Commit and push your changes to your private fork. If you have multiple commits, squash them into one.
- Submit a PR
### Structure
mbt source is organised into a few go modules that resides in the repository root.
|Module |Description|
|-----|------|
|lib |This is the main implementation of mbt functionality |
|cmd |Cobra commands for CLI |
|dtrace |Utility for writing debug trace messages from other packages |
|e |go error implementation enriched with callsite info |
|fsutil |File IO utility |
|trie |Prefix trie implementation |
### Writing Code
- When you return an error from received from call to an external library, wrap it in an `E` using `e.Wrap` function. Use
the other `e.Xxx` methods if you want to enrich the error with more information.
<file_sep>/lib/process_manager.go
/*
Copyright 2018 MBT Authors.
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 lib
import (
"fmt"
"os"
"os/exec"
"path"
"strings"
)
type stdProcessManager struct {
Log Log
}
func (p *stdProcessManager) Exec(manifest *Manifest, module *Module, options *CmdOptions, command string, args ...string) error {
cmd := exec.Command(command)
cmd.Env = append(os.Environ(), p.setupModBuildEnvironment(manifest, module)...)
cmd.Dir = path.Join(manifest.Dir, module.Path())
cmd.Stdin = options.Stdin
cmd.Stdout = options.Stdout
cmd.Stderr = options.Stderr
cmd.Args = append(cmd.Args, args...)
return cmd.Run()
}
func (p *stdProcessManager) setupModBuildEnvironment(manifest *Manifest, mod *Module) []string {
r := []string{
fmt.Sprintf("MBT_BUILD_COMMIT=%s", manifest.Sha),
fmt.Sprintf("MBT_MODULE_VERSION=%s", mod.Version()),
fmt.Sprintf("MBT_MODULE_NAME=%s", mod.Name()),
fmt.Sprintf("MBT_MODULE_PATH=%s", mod.Path()),
fmt.Sprintf("MBT_REPO_PATH=%s", manifest.Dir),
}
for k, v := range mod.Properties() {
if value, ok := v.(string); ok {
r = append(r, fmt.Sprintf("MBT_MODULE_PROPERTY_%s=%s", strings.ToUpper(k), value))
}
}
return r
}
// NewProcessManager creates an instance of ProcessManager.
func NewProcessManager(log Log) ProcessManager {
return &stdProcessManager{Log: log}
}
<file_sep>/scripts/release.sh
#!/bin/sh
set -e
VERSION=$(go run ./scripts/update_version.go $1)
git add -A
git commit -S -m "Bump version - v$VERSION"
git tag -a $VERSION -m $VERSION --sign
git push origin master --tags
<file_sep>/cmd/run_in.go
/*
Copyright 2018 MBT Authors.
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 cmd
import (
"errors"
"github.com/sirupsen/logrus"
"github.com/mbtproject/mbt/e"
"github.com/mbtproject/mbt/lib"
"github.com/spf13/cobra"
)
func init() {
runIn.PersistentFlags().StringVarP(&command, "command", "m", "", "Command to execute")
runIn.PersistentFlags().BoolVarP(&failFast, "fail-fast", "", false, "Fail fast on command failure")
runInPr.Flags().StringVar(&src, "src", "", "Source branch")
runInPr.Flags().StringVar(&dst, "dst", "", "Destination branch")
runInDiff.Flags().StringVar(&from, "from", "", "From commit")
runInDiff.Flags().StringVar(&to, "to", "", "To commit")
runInLocal.Flags().BoolVarP(&all, "all", "a", false, "All modules")
runInLocal.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
runInLocal.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
runInCommit.Flags().BoolVarP(&content, "content", "c", false, "Build the modules impacted by the content of the commit")
runInCommit.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
runInCommit.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
runInBranch.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
runInBranch.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
runInHead.Flags().StringVarP(&name, "name", "n", "", "Build modules with a name that matches this value. Multiple names can be specified as a comma separated string.")
runInHead.Flags().BoolVarP(&fuzzy, "fuzzy", "f", false, "Use fuzzy match when filtering")
runIn.AddCommand(runInBranch)
runIn.AddCommand(runInPr)
runIn.AddCommand(runInDiff)
runIn.AddCommand(runInHead)
runIn.AddCommand(runInCommit)
runIn.AddCommand(runInLocal)
RootCmd.AddCommand(runIn)
}
var runInHead = &cobra.Command{
Use: "head",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
return summariseRun(system.RunInCurrentBranch(command, &lib.FilterOptions{Name: name, Fuzzy: fuzzy}, runInCmdOptions()))
}),
}
var runInBranch = &cobra.Command{
Use: "branch <branch>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
branch := "master"
if len(args) > 0 {
branch = args[0]
}
return summariseRun(system.RunInBranch(command, branch, &lib.FilterOptions{Name: name, Fuzzy: fuzzy}, runInCmdOptions()))
}),
}
var runInPr = &cobra.Command{
Use: "pr --src <branch> --dst <branch>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if src == "" {
return errors.New("requires source")
}
if dst == "" {
return errors.New("requires dest")
}
return summariseRun(system.RunInPr(command, src, dst, runInCmdOptions()))
}),
}
var runInDiff = &cobra.Command{
Use: "diff --from <sha> --to <sha>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if from == "" {
return errors.New("requires from commit")
}
if to == "" {
return errors.New("requires to commit")
}
return summariseRun(system.RunInDiff(command, from, to, runInCmdOptions()))
}),
}
var runInCommit = &cobra.Command{
Use: "commit <sha>",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("requires the commit sha")
}
commit := args[0]
if content {
return summariseRun(system.RunInCommitContent(command, commit, runInCmdOptions()))
}
return summariseRun(system.RunInCommit(command, commit, &lib.FilterOptions{Name: name, Fuzzy: fuzzy}, runInCmdOptions()))
}),
}
var runInLocal = &cobra.Command{
Use: "local [--all]",
RunE: buildHandler(func(cmd *cobra.Command, args []string) error {
if all || name != "" {
return summariseRun(system.RunInWorkspace(command, &lib.FilterOptions{Name: name, Fuzzy: fuzzy}, runInCmdOptions()))
}
return summariseRun(system.RunInWorkspaceChanges(command, runInCmdOptions()))
}),
}
func runCmdStageCB(a *lib.Module, s lib.CmdStage, err error) {
switch s {
case lib.CmdStageBeforeBuild:
logrus.Infof("RUN command %s in module %s (path: %s version: %s)", command, a.Name(), a.Path(), a.Version())
case lib.CmdStageSkipBuild:
logrus.Infof("SKIP %s in %s for %s", a.Name(), a.Path(), a.Version())
case lib.CmdStageFailedBuild:
logrus.Infof("Failed %s in %s for %s: %v", a.Name(), a.Path(), a.Version(), err)
}
}
func summariseRun(summary *lib.RunResult, err error) error {
if err == nil {
logrus.Infof("Modules: %v Success: %v Failed: %v Skipped: %v",
len(summary.Manifest.Modules),
len(summary.Completed),
len(summary.Failures),
len(summary.Skipped))
logrus.Infof("Build finished for commit %v", summary.Manifest.Sha)
if len(summary.Failures) > 0 && failFast {
return e.NewError(lib.ErrClassUser, "One or more commands failed to run")
}
}
return err
}
func runInCmdOptions() *lib.CmdOptions {
options := lib.CmdOptionsWithStdIO(runCmdStageCB)
options.FailFast = failFast
return options
}
var runIn = &cobra.Command{
Use: "run-in",
Short: docText("run-in-summary"),
Long: docText("run-in"),
}
| aba4a4e82d451e91344ec1ec825e2e8715a9592c | [
"Markdown",
"Makefile",
"Go",
"Go Module",
"Shell"
] | 77 | Markdown | ecosia/mbt | 3090625ea323bdb9505a6e4ddaef8784e208b684 | a61e9ffc3f47739f28e89f34dd2b7887d1020114 |
refs/heads/master | <repo_name>jpommerening/node-eval-stream<file_sep>/README.md
# eval-stream
> Evaluate streams of JavaScript code in a given context.
## Examples
Here, we read the body of an adding function from a simple
through-stream:
```js
var PassThrough = require('stream').PassThrough ||
require('readable-stream/passthrough');
var assert = require('assert');
var evalStream = require('eval-stream');
var ts = new PassThrough();
ts.pipe(evalStream({
a: 1,
b: 2
}, function (err, result) {
assert(!err);
assert.equal(result, 3);
}));
ts.write('return a + b;');
ts.end();
```
<file_sep>/index.js
var stream = require('readable-stream');
var inherits = require('inherits');
function EvalStream(context) {
if (!(this instanceof EvalStream)) {
return new EvalStream(context);
}
stream.Writable.call(this);
var buffer = [];
this._write = function(chunk, encoding, callback) {
buffer.push(chunk);
callback();
}
this.on('prefinish', function() {
var args = Object.keys(context);
var code = Buffer.concat(buffer);
var func = Function.apply(new Function(), args.concat([code]));
try {
this.emit('end', func.apply(this, args.map(function(arg) {
return context[arg];
})));
}
catch (err) {
this.emit('error', err);
}
}.bind(this));
};
inherits(EvalStream, stream.Writable);
function evalStream(context, callback) {
var stream = new EvalStream(context);
if (callback) {
stream.on('end', callback.bind(stream, null));
stream.on('error', callback);
}
return stream;
}
evalStream.EvalStream = EvalStream;
module.exports = evalStream;
| 3911a7a95182f21b54a6f43b54bf695341776a2c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jpommerening/node-eval-stream | e5d329d4490a9cea155a2996f4ce61ffaa643055 | 2c56adb4ca77ea7347cde6eddb611690775f7824 |
refs/heads/master | <repo_name>achary2303/BCBS<file_sep>/Apr 02 2019/streamsets_commithook/app/streamsets_commithook/streamsets_commithook/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello world..............")
def commithook(request):
return HttpResponse('Request received: <br>' +
'GET Parameters: <br>' +
'<br>'.join(param+'='+str(request.GET[param]) for param in sorted(request.GET)) +
'<br><br>' +
'Post Parameters: <br>' +
'<br>'.join(param+'='+str(request.POST[param]) for param in sorted(request.POST)) +
'<br><br>' +
"META: <br>" +
'<br>'.join(param+'='+str(request.META[param]) for param in sorted(request.META)) +
'<br><br>' +
''
)
<file_sep>/Apr 02 2019/streamsets_commithook/s2i/bin/run
#!/bin/bash -e
#
# S2I run script for the 'registry.access.redhat.com/rhscl/python-36-rhel7' image.
# The run script executes the server that runs your application.
#
# For more information see the documentation:
# https://github.com/openshift/source-to-image/blob/master/docs/builder_image.md
#
#exec asdf -p 8080
appHome="../app/streamsets_commithook"
echo "Starting Gunicorn..."
cd "$appHome/"
#exec /bin/bash -c "pwd ; ls -l"
exec gunicorn streamsets_commithook.wsgi:application --bind 0.0.0.0:8000 --workers 4
<file_sep>/tests.py
# pages/tests.py
from django.http import HttpRequest
from django.test import SimpleTestCase
#from django.urls import reverse
#from . import views
#from hash
class HomePageTests(SimpleTestCase):
def test_home_page_status_code(self):
response = selfs.client.get('/')
self.assertEqual(response.statuxs_code, 200)<file_sep>/Apr 02 2019/streamsets_commithook/Makefile
IMAGE_NAME = streamsets_commithook
.PHONY: build
build: docker-clean
#s2i create registry.access.redhat.com/rhscl/python-36-rhel7 streamsets_commithook <---- command used to start, but not correct
docker build -t $(IMAGE_NAME) .
s2i build app/streamsets_commithook registry.access.redhat.com/rhscl/python-36-rhel7 $(IMAGE_NAME) -s file://s2i/bin
.PHONY: docker-clean
docker-clean:
-docker rm $(IMAGE_NAME) --force
-docker rmi $(IMAGE_NAME) --force
<file_sep>/pygit .py
from github import Github
import pygit2
# using username and password establish connection to github
g = Github('<EMAIL>', '<PASSWORD>')
org = g.get_organization('BCBS')
#create the new repository
repo = org.create_repo("tk111", description = "New Project Initiation" )
#create some new files in the repo
repo.create_file("README.md", "init commit", 'General Info.')
#Clone the newly created repo
repoClone = pygit2.clone_repository(repo.git_url, '/home/ubuntu/Pygit/Test-repo')
#put the files in the repository here
#Commit it
repoClone.remotes.set_url("origin", repo.clone_url)
index = repoClone.index
index.add_all()
index.write()
author = pygit2.Signature("Keerthi", "<EMAIL>")
commiter = pygit2.Signature("Keerthi", "<EMAIL>")
tree = index.write_tree()
oid = repoClone.create_commit('refs/heads/master', author, commiter, "init commit",tree,[repoClone.head.get_object().hex])
remote = repoClone.remotes["origin"]
credentials = pygit2.UserPass('<EMAIL>', '<PASSWORD>')
remote.credentials = credentials
callbacks=pygit2.RemoteCallbacks(credentials=credentials)
remote.push(['refs/heads/master'],callbacks=callbacks)
curl https://bootstrap.pypa.io/get-pip.py -o
get-pip.py
python get-pip.py
git config --list --show-origin
git config --global user.name "keerthi"
git config --global user.email <EMAIL>
pip install xxx --disable-pip-version-check
sudo yum list | grep python3
https://linuxize.com/post/how-to-install-python-3-7-on-ubuntu-18-04/
sudo apt install python3-pip
Step1: install git (sudo apt-get instll git)
step 2: Python 3 Installation (https://linuxize.com/post/how-to-install-python-3-7-on-ubuntu-18-04/)
step 3: INstall pip ( sudo apt install python3-pip)
Step 4: INstall pygit2 (sudo pip3 install pygit2)
Step 5: Run Script (python3 script.py)
| 243a797683abdd906d6aa995274e0470c47f96e8 | [
"Python",
"Makefile",
"Shell"
] | 5 | Python | achary2303/BCBS | b30926adce7c20402f9210e0607661e21d954c00 | 2af3caf97a3aa09dbcd7fe1a8bed3f62375287a9 |
refs/heads/master | <repo_name>axel0070/plagiat<file_sep>/download.c
#include <stdio.h>
#include <tidy.h>
#include <stdlib.h>
#include <string.h>
#include <tidybuffio.h>
#include <curl/curl.h>
#include "minunit.h"
#include "uri_encode.h"
#include "minunit.h"
#include "def.h"
//Prototypes de fonctions
uint write_cb_dl(char *in, uint size, uint nmemb, TidyBuffer *out); //== Résultat Curl
void dumpNode_dl(TidyDoc doc, TidyNode tnod, int indent, char *memoryTemp); //==analyse des noeux XML ( HTML )
int download(bool isProxyNeeded,char *test[], char* url,int NbLine,int pos)
{
CURL *curl = NULL;
char curl_errbuf[CURL_ERROR_SIZE];
TidyDoc tdoc;
TidyBuffer docbuf = {0};
TidyBuffer tidy_errbuf = {0};
int err;
struct curl_slist *list = NULL;
char memoryTemp[10000];
//printf("new download start");
memoryTemp[0] = '\0';
curl = curl_easy_init();
int plagiat = 0;
/**Only on UTBM network.**/
if(isProxyNeeded)
{
curl_easy_setopt(curl, CURLOPT_PROXY, "http://proxy.utbm.fr:3128");
}
//printf("\nDow : %s",url);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errbuf);
//curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb_dl);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
tdoc = tidyCreate();
tidyOptSetBool(tdoc, TidyForceOutput, yes); /* try harder */
tidyOptSetInt(tdoc, TidyWrapLen, 4096);//http: //wpad.utbm.local/wpad.dat
tidySetErrorBuffer(tdoc, &tidy_errbuf);
tidyBufInit(&docbuf);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &docbuf);
err = curl_easy_perform(curl);
// printf("\nError ????%d",err);
if(!err) {
err = tidyParseBuffer(tdoc, &docbuf); /* parse the input */
if(err >= 0) {
err = tidyCleanAndRepair(tdoc); /* fix any problems */
if(err >= 0) {
err = tidyRunDiagnostics(tdoc); /* load tidy error buffer */
if(err >= 0) {
dumpNode_dl(tdoc, tidyGetRoot(tdoc), 0,memoryTemp); /* walk the tree */
/** There is error but not showing to the console because pointless**/
//fprintf(stderr, "%s\n", tidy_errbuf.bp); /* show errors */
}
}
}
}
else
{
//fprintf(stderr, "%s\n", curl_errbuf);
return 0;
}
//printf(fuckingData);
//printf("\nFinScanTidy");
for(int i =0; i < NbLine ; i++)
{
if(strstr(memoryTemp, test[i]) != NULL)
{
plagiat++;
}
}
tidyBufFree(&docbuf);
tidyBufFree(&tidy_errbuf);
tidyRelease(tdoc);
return plagiat;
}
/* curl write callback, to fill tidy's input buffer... */
uint write_cb_dl(char *in, uint size, uint nmemb, TidyBuffer *out)
{
uint r;
r = size * nmemb;
tidyBufAppend(out, in, r);
return r;
}
/* Traverse the document tree */
void dumpNode_dl(TidyDoc doc, TidyNode tnod, int indent, char *memoryTemp)
{
TidyNode child;
for(child = tidyGetChild(tnod); child; child = tidyGetNext(child) ) {
ctmbstr name = tidyNodeGetName(child);
if(!name) {
/* if it doesn't have a name, then it's probably text, cdata, etc... */
TidyBuffer buf;
tidyBufInit(&buf);
tidyNodeGetText(doc, child, &buf);
//printf("%*.*s\n", indent, indent, buf.bp?(char *)buf.bp:"");
char *out = buf.bp;
int len = strlen(out);
if(buf.bp)
{
for(int i =0 ; i < len; i++)
{
if(out[i] != 13 && out[i] != 10)
{
//printf("\ncrash? 1 len %d",len);
int len = strlen(memoryTemp);
if(len<9999)
{
memoryTemp[len] = out[i];
memoryTemp[len+1] = '\0';
}
//bigData = append_(bigData,out[i]);
//printf("\ncrash? 10");
}
}
}
tidyBufFree(&buf);
}
dumpNode_dl(doc, child, indent + 4,memoryTemp); /* recursive */
}
}
<file_sep>/ThreadScreen.h
#include "def.h"
//Fonctions
void screen();
void resetScreen();
void print(char *text,int x,int y, int color);
void initBorders();
void BordersTop();
void *functionThread1(int val);
void *functionThread2(int val);
void resetLeft();
void resetBottomRight();
void popup(char * msg,int select);
//for thread 3
void progressBar(int pos,int progress, char *filename);
void selectThreadPos(int pos);
void printResult(struct Data output);
<file_sep>/main.c
#include <stdio.h>
#include <stdlib.h>
/* Fichiers d'en-tête pour la librairie Curl.*/
#include <curl/curl.h>
/*Fichiers d'en-tête pour les fonctions relatives aux Threads.*/
#include <pthread.h>
/* Fichiers d'en-tête pour les appelles de fonctions */
#include "ThreadScreen.h"
#include "fileexplorer.h"
main()
{
int rc1; /* code d'erreur */
pthread_t thread1; /* Structure correspondant à un Thread */
/**Un thread est similaire à un processus car tous deux représentent l'exécution d'un ensemble
d'instructions du langage machine d'un processeur.
Du point de vue de l'utilisateur, ces exécutions semblent se dérouler en parallèle. Toutefois, là
où chaque processus possède sa propre mémoire virtuelle, les threads d'un même processus se partagent sa
mémoire virtuelle. Par contre, tous les threads possèdent leur propre pile d'exécution. **/
bool isProxyNeeded; /* Variable pouvant être "vrai" ou "faux" suivant le besoin */
CURLcode res; /* Code obtenu après une connection */
res = proxy_checker(); /* Connection internet Synchrome pour verifier si un proxy est nécéssaire */
switch ( res )
{
case CURLE_OK :
isProxyNeeded = false;
break;
case CURLE_COULDNT_CONNECT :
isProxyNeeded = true;
break;
default :
printf("\nErreur de connection (%d)",res);
printf("\nVeuillez vous référer à https://curl.haxx.se/libcurl/c/libcurl-errors.html pour plus d'information");
return res;
}
/* Création d'un thread pour la fonction "explore" */
if( (rc1=pthread_create( &thread1, NULL, &explore, isProxyNeeded)) )
{
printf("Thread creation failed: %d\n", rc1);
}
/** pthread_join() suspend l'exécution du thread appelant (Thread principal) jusqu'à ce que le thread identifié par thread1 achève son exécution**/
pthread_join( thread1, NULL);
/*Fin du processus*/
exit(EXIT_SUCCESS);
}
<file_sep>/phase_1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "def.h"
char ** decompo (FILE* fichier,int *MaxL,int pos)
{
int c;
int line = 0;
/*Variables declared as static inside a function are statically allocated,
thus keep their memory cell throughout all program execution, while having the
same scope of visibility as automatic local variables (auto and register),
meaning remain local to the function. Hence whatever values the function puts
into its static local variables during one call will still be present when the
function is called again.*/
static char* tab[5][MAX_LINE]; //static = super important
int nbMot=0;
int returnLine = 0;
/*Tout d'abord on initialise le tableau à la bonne position avec du vide
pour être sur de ne pas être embeter */
for(int init =0; init < MAX_LINE; init++)
{
tab[pos][init] = "";
}
while ((c = getc(fichier)) != EOF)
{
//Tableau ASCII : http://www.gecif.net/qcm/information/ascii_decimal.pdf
if (c==46 || c==33 || c==58 || c==59 || c==63 || (nbMot>8 && c==44) || (nbMot>10 && c==32))
{
tab[pos][line] = append_(tab[pos][line],c);
line++;
returnLine = 1;
nbMot=0;
}
else if (c==32)//Si c'est un espace
{
if(!returnLine)
{
tab[pos][line] = append_(tab[pos][line],c);
}
else
{
returnLine = 0;
}
nbMot++;
}
else if ((c!=32 || nbMot!=0) && c!=10)
{
tab[pos][line] = append_(tab[pos][line],c);
returnLine = 0;
}
}
//Pour debug et afficher le découpage
/*printf("\n-------FICHIER-DEBUT-------\n");
for(int j = 0; j <= line; j++)
{
printf("\n%d: %s",j,tab[pos][j]);
}
printf("\n-------FICHIER-FIN-------");*/
*MaxL = line;
//On retourne un tableau de char*
return tab[pos];
}
/*Cette fonction est appellé une fois que l'utilisateur à validé la selection*/
/*Le premier argument *path est le chemin d'acces du fichier*/
/*MaxL est l'adresse de la variable MaxL qui servira a receuillir le nombre de lignes*/
char ** phase_1(char *path,int *MaxL,int pos)
{
FILE* fichier = NULL;
fichier = fopen(path, "r");
char ** buffer[5] ; //On a ici 5 tableau a deux dimension
if(fichier == NULL)
{
system("CLS");
printf("No file in the directory");
exit(EXIT_FAILURE);
return;
}
if (fichier)
{
buffer[pos] =decompo(fichier,MaxL,pos);
}
fclose(fichier);
return buffer[pos];
}
<file_sep>/proxy_checker.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Fichiers d'en-tête pour la librairie Curl.*/
#include <curl/curl.h>
int proxy_checker()
{
/* Procedure basique de connection à un url donnée références : https://curl.haxx.se/libcurl/ */
CURL *curl_handle;
CURLcode res;
/*On met en place l'environnement libcurl avec curl_global_init()*/
curl_global_init(CURL_GLOBAL_ALL);
/*On initialise la variables CURL*/
curl_handle = curl_easy_init();
/*On spécifie l'url dans les paramètres*/
curl_easy_setopt(curl_handle, CURLOPT_URL, "https://www.google.fr/");
/*On demande à la librairie de travailler uniquement avec le Header de la conneciton*/
curl_easy_setopt(curl_handle, CURLOPT_NOBODY, 1);
//curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
//curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);
/*On ignore les vérifications SSL (trop compliqué et sources de nombreuses erreur) */
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
/*On lance la connection, et on récupère le code résultant*/
res = curl_easy_perform(curl_handle);
/*On nettoie l'environnement pour éviter les "memory leak" */
curl_easy_cleanup(curl_handle);
curl_global_cleanup();
return res;
}
<file_sep>/ThreadScreen.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <windows.h> /* for HANDLE type, and console functions */
#include <string.h>
#include <unistd.h> //Header file for Sleep().
#include <pthread.h> //Header file for Threads.
#include "ThreadScreen.h"
//Variables
HANDLE wHnd; /* write (output) handle */
static struct block map[WIDTH][HEIGHT];
int run = 1;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
/*Cette fonctions permet d'afficher sur la console,
les données stoqué dans le tableau a deux dimension map
Informations complémentaire :
=> https://stackoverflow.com/questions/38343232/outputs-in-console-with-writeconsoleoutputa
=> https://docs.microsoft.com/en-us/windows/console/writeconsoleoutput
=> http://cecilsunkure.blogspot.com/2011/11/windows-console-game-setting-up-window.html */
void screen()
{
int x, y;
SetConsoleTitle("Detecteur de Plagiat");
/* On définit les coordonnées des coins de la console
=> https://docs.microsoft.com/en-us/windows/console/small-rect-str */
SMALL_RECT windowSize = {0, 0, WIDTH - 1, HEIGHT - 1};
SMALL_RECT consoleWriteArea = {0, 0, WIDTH - 1, HEIGHT - 1};
/* Les structures COORD sont utilisés pour spécifié des positions sur l'écran.
=> https://docs.microsoft.com/en-us/windows/console/coord-str*/
COORD bufferSize = {WIDTH, HEIGHT};
COORD characterBufferSize = {WIDTH, HEIGHT};
COORD characterPosition = {0, 0};
/* On définit une structure CHAR_INFO qui contiendra toutes les données pour chaques caractères */
CHAR_INFO consoleBuffer[WIDTH * HEIGHT];
/* On récupère la sortie */
wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
/* On définit la taille de la fenetre */
SetConsoleWindowInfo(wHnd, TRUE, &windowSize);
/* On définit la taille de la fenetre virtuel (tempon) */
SetConsoleScreenBufferSize(wHnd, bufferSize);
for (y = 0; y < HEIGHT; y++)
{
for (x = 0; x < WIDTH; x++)
{
int color = map[x][y].color;
consoleBuffer[x + WIDTH * y].Char.AsciiChar = map[x][y].character;
consoleBuffer[x + WIDTH * y].Attributes = color;
}
}
/* On copie les données situé dans consoleBuffer pour les envoyées dans une zone rectangulaire de taille spécifié par
characterBufferSize et characterPosition situé dans la zone de la console indiqué par consoleWriteArea*/
WriteConsoleOutputA(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);
}
/*Cette fonction remplis le tableau map de caractère █ de couleur blanche*/
void resetScreen()
{
for(int x = 0 ; x < WIDTH; x++ )
{
for(int y=0; y < HEIGHT; y++)
{
map[x][y].color = 255;
map[x][y].character = 219;
}
}
}
/* Cette fonction affiche une fenetre sur la partie gauche de l'écran*/
void popup(char * msg,int select)
{
//Impression du font bleu de la fenetre
for(int x = WIDTH/2-strlen(msg)/2-3 - WIDTH/4; x < WIDTH/2+strlen(msg)/2+3- WIDTH/4; x++ )
{
for(int y= HEIGHT/2-5; y < HEIGHT/2+5; y++)
{
map[x][y].character = 219; //█
map[x][y].color = 51; //bleu
}
}
print("Scanner ?",WIDTH/2-strlen(msg)/2- WIDTH/4,HEIGHT/2-3,48); //Impression de text
print(msg,WIDTH/2-strlen(msg)/2- WIDTH/4,HEIGHT/2-2,48); //Impression du nom du fichier
//L'utilisateur peut choisir entre oui/non
if(select == 0)
{
print("Oui",WIDTH/2-5- WIDTH/4,HEIGHT/2 +1,32);
print("Non",WIDTH/2+2- WIDTH/4,HEIGHT/2 +1,48);
}
else
{
print("Oui",WIDTH/2-5- WIDTH/4,HEIGHT/2 +1,48);
print("Non",WIDTH/2+2- WIDTH/4,HEIGHT/2 +1,192);
}
}
void BordersTop()
{
for(int x = 0 ; x < WIDTH; x++ )
{
map[x][0].color = 119;
map[x][0].character = 219;
}
}
/*Ici on colorie les bordures*/
void initBorders()
{
for(int x = 0 ; x < WIDTH; x++ )
{
map[x][0].color = 119;
map[x][0].character = 219;
map[x][HEIGHT-1].color = 119;
map[x][HEIGHT-1].character = 219;
}
for(int y=0; y < HEIGHT; y++)
{
map[0][y].color = 119;
map[0][y].character = 219;
map[WIDTH-1][y].color = 119;
map[WIDTH-1][y].character = 219;
map[1][y].color = 119;
map[1][y].character = 219;
map[WIDTH-2][y].color = 119;
map[WIDTH-2][y].character = 219;
map[WIDTH/2][y].color = 119;
map[WIDTH/2][y].character = 219;
map[WIDTH/2 +1][y].color = 119;
map[WIDTH/2 +1][y].character = 219;
}
}
//On remet en blanc uniquement la partie de gauche
void resetLeft()
{
/**En effet durant le programme, la partie de gauche est tout le temps reset et remis au propre
la partie de droite est laissé tel quelles tout au long du programme **/
for(int i =2; i < WIDTH/2-1;i++)
{
for(int j = 0; j < HEIGHT -1; j++)
{
map[i][j].color = 255;
map[i][j].character = 219;
}
}
}
void resetBottomRight()
{
for(int i = WIDTH/2 + 2; i < WIDTH-2;i++)
{
map[i][HEIGHT/2].color = 119;
map[i][HEIGHT/2].character = 219;
}
for(int i = WIDTH/2 + 2; i < WIDTH-2;i++)
{
for(int j = HEIGHT/2+1; j < HEIGHT -1; j++)
{
map[i][j].color = 255;
map[i][j].character = 219;
}
}
}
void printResult(struct Data output)
{
int j = 0;
resetBottomRight();
print(output.filename,WIDTH/4 * 3 - strlen(output.filename),HEIGHT/2+1,248); //On imprime le nom du fichier préalablement scanné
while(j < 7 && j < output.nbResult) //Deux condition, la première
{
char str[1000];
//Ici plag correponds au pourcentage de plagiat dans le fichier.
float plag = (float) output.result[j].occurence/ (output.totalLine) * 100;
//On fait une jolie phrase pour chaque lien
sprintf(str, "%d%% pour %s",(int) plag, output.result[j].url);
if(strlen(str)>WIDTH/2-4)
{
str[WIDTH/2-4] = '\0';
str[WIDTH/2-5] = '.';
str[WIDTH/2-6] = '.';
}
//On définit une couleurs différences en fonctions du %
if((int)plag>50)
{
print(str,WIDTH/2+2,HEIGHT/2+3+2*j,244);
}
else if((int)plag>40)
{
print(str,WIDTH/2+2,HEIGHT/2+3+2*j,252);
}
else if((int)plag>30)
{
print(str,WIDTH/2+2,HEIGHT/2+3+2*j,246);
}
else if((int)plag>20)
{
print(str,WIDTH/2+2,HEIGHT/2+3+2*j,240);
}
else if((int)plag>10)
{
print(str,WIDTH/2+2,HEIGHT/2+3+2*j,241);
}
else
{
print(str,WIDTH/2+2,HEIGHT/2+3+2*j,242);
}
j++;
}
}
/*Imprime la barre de progrès*/
void progressBar(int pos,int progress, char *filename)
{
int start = WIDTH/2+WIDTH/8;
int end = WIDTH/2+3*WIDTH/8;
int dif = end - start;
int prog = progress*dif / 100;
int posH = HEIGHT/2/5 + 3*pos;
char str[10];
sprintf(str, "%d%%", progress);
print(str,start,posH -1,250);
print(filename,start+ 5,posH-1,250);
for(int i = start; i < start + prog;i++)
{
map[i][posH].color = 2;
map[i][posH].character = 219;
}
}
/*Cette fonction va imprimer a cote du temps de chargement
un barre bleu pour indiquer qu'elle est selectionné*/
void selectThreadPos(int pos)
{ //contour color 136
int color = 0;
int start = WIDTH/2+WIDTH/8;
int end = WIDTH/2+3*WIDTH/8;
int posH;
for(int w =0; w < 5; w++)
{
posH = HEIGHT/2/5 + 3*w;;
if(w ==pos)
{
color = 153;
}
else
{
color = 255;
}
map[start-4][posH].color = color;
map[start-4][posH].character = 219;
map[start-4][posH-1].color = color;
map[start-4][posH-1].character = 219;
}
}
/*Cette fonction va imprimer du text,
a l'emplacement donnée en x,y et de la bonne couleur*/
void print(char *text,int x,int y, int color)
{
for(int i =0; i<strlen(text);i++)
{
if(i > WIDTH-1)
{
return;
}
map[x+i][y].character = (unsigned char) text[i];
map[x+i][y].color = color;
}
}
<file_sep>/phase_2.c
#include <stdio.h>
#include <tidy.h>
#include <string.h>
#include <tidybuffio.h>
#include <curl/curl.h>
#include "minunit.h"
#include "uri_encode.h"
#include "phase_2.h"
#include "ThreadScreen.h"
//Variables globals.
struct Link link[5][MAX_LINK];
int gCounter = -1;
int NextLine = 0;
char memory[50000];
bool BIGERROR = false;
//int phase_2(char ** array,bool isProxyNeeded, int *MaxL)
void phase_2(void *vargp)
{
char *reel_var[MAX_LINE];
int j =0;
struct Data *data;
int pos = 0 ;
int totalLine =0;
data = vargp;
pos = (*data).pos;
totalLine = *(*data).MaxL;
(*data).totalLine = totalLine;
(*data).finish = false;
char filename[120] = "";
strcpy(filename,(*data).filename);
initLink(pos);
while( strlen(*((*data).array + j))>0 )
{
CURL *curl = NULL;
char curl_errbuf[CURL_ERROR_SIZE];
TidyDoc tdoc;
TidyBuffer docbuf = {0};
TidyBuffer tidy_errbuf = {0};
int err;
struct curl_slist *list = NULL;
float progress = (float)j/ totalLine *50;
reel_var[j] = *((*data).array + j);
//printf( "\n*(tab + %d) : %s", j, reel_var[j]);
progressBar(pos,(int) progress,filename);
//printf("\nProgress %f | pos %d",progress,pos);
char *uri = reel_var[j];
const size_t len = strlen(uri);
char buffer[ len * 3 + 1 ];
buffer[0] = '\0';
uri_encode(uri, len, buffer);
//printf("ENCODE: %s",buffer);
char *url_ = "https://www.google.com/search?q=";
for(int i =0; i < strlen(buffer);i++)
{
url_ = append_(url_,buffer[i]);
}
//This allow to avoid to be kicked from google.com
Sleep(200);
curl = curl_easy_init();
//printf("\ndata.isProxyNeeded: %d",(*data).isProxyNeeded);
/**Only on UTBM network.**/
if((*data).isProxyNeeded)
{
curl_easy_setopt(curl, CURLOPT_PROXY, "http://proxy.utbm.fr:3128");
}
//printf("\nURL: %s",url_);
curl_easy_setopt(curl, CURLOPT_URL, url_);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errbuf);
//curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
tdoc = tidyCreate();
tidyOptSetBool(tdoc, TidyForceOutput, yes); /* try harder */
tidyOptSetInt(tdoc, TidyWrapLen, 4096);//http: //wpad.utbm.local/wpad.dat
tidySetErrorBuffer(tdoc, &(tidy_errbuf));
tidyBufInit(&(docbuf));
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &(docbuf));
/**Simulate a real browser**/
curl_easy_setopt(curl, CURLOPT_COOKIESESSION, 1L);
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");
list = curl_slist_append(list, "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
list = curl_slist_append(list, "accept-language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7");
list = curl_slist_append(list, "cache-control: max-age=0");
list = curl_slist_append(list, "upgrade-insecure-requests: 1");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36");
err = curl_easy_perform(curl);
if(!err) {
err = tidyParseBuffer(tdoc, &(docbuf)); /* parse the input */
if(err >= 0) {
err = tidyCleanAndRepair(tdoc); /* fix any problems */
if(err >= 0) {
err = tidyRunDiagnostics(tdoc); /* load tidy error buffer */
if(err >= 0) {
dumpNode(tdoc, tidyGetRoot(tdoc), 0,pos); /* walk the tree */
/** There is error but not showing to the console because pointless**/
//fprintf(stderr, "%s\n", tidy_errbuf.bp); /* show errors */
}
}
}
}
else
{
fprintf(stderr, "%s\n", curl_errbuf);
}
//BOUCLE WHILE POUR CHAQUE PHRASE
j++;
/* clean-up */
curl_easy_cleanup(curl);
tidyBufFree(&docbuf);
tidyBufFree(&tidy_errbuf);
tidyRelease(tdoc);
}
progressBar(pos,50,filename);
//printf("\nFinish");
//listLink(pos);
//result();
//listLink(pos);
char *buffer = NULL;
int temp = 0;
int total = estimation(pos);
int positiveResult = 0;
while((buffer = result(pos)) != NULL)
{
if(strlen(buffer)>1)
{
float progress = (float)temp/ total *50+50;
int b = download((*data).isProxyNeeded,reel_var,buffer,j,pos);
if(b)
{
strcpy( (*data).result[positiveResult].url,buffer);
(*data).result[positiveResult].occurence = b;
positiveResult++;
(*data).nbResult = positiveResult;
}
Sleep(1000);
progressBar(pos,(int) progress,filename);
//printf("\n-------->Temp : %d",temp);
temp ++;
}
//download((*data).isProxyNeeded,reel_var,buffer,j,pos);
}
progressBar(pos,100,filename);
(*data).finish = true;
//result(pos);
//download(0,reel_var[0]);
//free(data);
//free(list);
//free(reel_var);
//printf("\nEnd");
//return err;
//initLink(pos);
//return 0;
}
/* curl write callback, to fill tidy's input buffer... */
uint write_cb(char *in, uint size, uint nmemb, TidyBuffer *out)
{
uint r;
r = size * nmemb;
tidyBufAppend(out, in, r);
return r;
}
/* Traverse the document tree */
void dumpNode(TidyDoc doc, TidyNode tnod, int indent,int pos) //Cette fonctions est appellé pour chaque ligne.
{
TidyNode child;
for(child = tidyGetChild(tnod); child; child = tidyGetNext(child) ) {
ctmbstr name = tidyNodeGetName(child);
if(name) {
/* if it has a name, then it's an HTML tag ... */
TidyAttr attr;
//printf("NAME:%*.*s%s ", indent, indent, "<", name);
//printf("%*.*s%s", indent, indent, "<", name);
/* walk the attribute list */
for(attr = tidyAttrFirst(child); attr; attr = tidyAttrNext(attr) ) {
if(strstr(tidyAttrName(attr),"class") != NULL && strstr(tidyAttrValue(attr),"g") != NULL && strlen(tidyAttrValue(attr)) < 3)
{
//printf("\nResult:|%s|%s|",tidyAttrName(attr),tidyAttrValue(attr)); //La on vient de passer la ligne class="g"
gCounter++;
}else if(gCounter>= 0 && strstr(tidyAttrName(attr),"class") != NULL && strstr(tidyAttrValue(attr),"r") != NULL && strlen(tidyAttrValue(attr)) < 3)
{
NextLine = 1;
/**
After the <class='r'> the <a> arrive and contain the href which is the link to the website.
**/
}
else if(NextLine>0)
{
char *link = tidyAttrValue(attr);
//link?printf("LINK=|%s|\n",link):printf(" ");
if(link)
{
if(strstr(link,"LC20lb"))
{
// system("CLS");
// printf("ERROR DETECTED THIS SHOULD NEVER HAPPEN RESTART THE PROGRAM");
//exit(-1);
}
else
{
//printf("\nLINK=|%s| pos %d",link,pos); //attention si il y a "sFZIhb" alors c'est un pdf.
addlink(link,pos);
NextLine = 0;
}
}
else
{
NextLine = 0;
}
}
}
//printf(">\n");
}
dumpNode(doc, child, indent + 4,pos); /* recursive */
}
}
void initLink(int pos)
{
for(int i =0; i < MAX_LINK; i++)
{
link[pos][i].occurence = 0;
strcpy(link[pos][i].url,"");
}
}
void addlink(char *url,int pos)
{
//printf("\nNew url pos %d : %s",pos,url);
for(int i =0; i < MAX_LINK; i++)
{
if(strcmp(url, link[pos][i].url)== 0)//return 0 si identique, sinon autres choses.
{
//printf("\n-Found inside- |%s|",url);
link[pos][i].occurence++;
return;
}
}
//La chaine n'est pas présente dans le tableau de structure. On l'ajoute
for(int i =0; i < MAX_LINK; i++)
{
if(strlen(link[pos][i].url) ==0)//return 0 si identique, sinon autres choses.
{
//printf("\n-ADDED-");
strcpy(link[pos][i].url,url);
//link[pos][i].url =url;
return;
}
}
}
/*Cete fonction compte le nombre de lien avec une occurence > 0
=> Elle renvoit combien de lien sont apparu au moins une fois*/
int estimation(int pos)
{
int count = 0;
for(int i =0; i < MAX_LINK; i++)
{
if(strlen(link[pos][i].url)>0)
{
if(link[pos][i].occurence)
{
count++;
}
}
}
return count;
}
/**La fonction résult renvoi l'url le plus occurente dans le tableau link[pos]
=> Elle renvoit le lien qui a été trouvé le plus de fois, et elle le suprime du tableau après**/
char *result(int pos)
{
int posMax = -1; //Correspondra à la position dans le tableau du lien le plus apparu
int valueMax = 0; //Corresponds à la valeur maximum ...
/*On scan tous les liens*/
for(int i =0; i < MAX_LINK; i++)
{
if(strlen(link[pos][i].url)>0) //Si le lien existe
{
if(link[pos][i].occurence) //Si le lien est apparu au moins une fois
{
if(valueMax<link[pos][i].occurence) //si la nouvelle occurence testé est meilleur que la précédente
{
posMax = i; //Alors maj index
valueMax = link[pos][i].occurence; //Update
}
}
}
}
//Maintenant, si posMax a été actualisé, c'est à dire, que dans tous les liens obtenu, au moins 1 est apparu plus d'une fois
if(posMax>=0)
{
link[pos][posMax].occurence = 0; //On reset
if(strstr(link[pos][posMax].url,".pdf") != NULL) //On verifie si ce ne serait pas un pdf.. histoire d'éviter les bugs
{
return ""; //on renvoit rien, car si on renvoit NULL le scan s'arrête.
}
return link[pos][posMax].url; //On renvoit la chaine de caracteres
}
return NULL;
}
<file_sep>/fileexplorer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
/*Fichiers d'en-tête pour les fonctions relatives aux fichiers.*/
#include <dirent.h>
#include <sys/stat.h>
/*Fichiers d'en-tête pour les fonctions relatives aux Threads.*/
#include <unistd.h>
#include <pthread.h>
/*Fichiers d'en-tête pour les fonctions relatives à la console.*/
#include <windows.h>
/* Fichiers d'en-tête pour les appelles de fonctions */
#include "def.h"
#include "fileexplorer.h"
#include "phase_2.h"
/**Variables globales**/
/*La variables runExplorer est utilisé pour la boucle principale*/
bool runExplorer = true;
/*La console est divisé en deux parties (Gauche / Droite )
l'utilisateur à l'aide des flèche peut passer de gauche à droite
lorsque l'explorateur de fichier est selectionné explorerSelect = true sinon false*/
bool explorerSelect = true;
/*A l'aide des flèches haut/bas l'utilisateur peut naviguer entres les fichiers et les dossier.
selectLine correspond à la ligne selectionné, l'indice est utilisé pour savoir
quel élement l'utilisateur à choisie lorsqu'il clique sur "ENTER" mais également, quels élements
doit être surligné */
int selectLine = 0;
/*maxLine est une variable utilisé pour indiquer, le nombre d'élement afficher sur la console.*/
int maxLine = 0;
/*Si le nombre de fichiers/dossiers dans le chemin d'accès spécifié dépasse le nombre de ligne de la console
l'utilisateur peut descendre avec les flèches pour "scroller" et afficher les autres fichiers,
scroll corresponds au décalage. */
int scroll = 0;
/*La variables pressedEnter est modifié lorsque l'utilisateur appuis sur Enter*/
bool pressedEnter = false;
/*la chaine de caractère workingDir est utilisé pour stocker la position dans laquel se situe l'explorateur*/
char workingDir[1000];
/*returnPath est la chaine de caractère ou se situe le chemin d'accès de l'élément séléctionné et validé*/
char returnPath[1000];
/*Cette structure est un objet correspondant à la fenêtre d'intéraction, demandant de validé ou non la selection*/
struct Validpop validpop;
/*variables similaire à selectLine elles corresponds à l'élement séléctionné sur la droite de la console*/
int selectPos = 0;
void explore(bool isProxyNeeded)
{
/*La variables pos correspond au nombre total de Thread d'analyse existant
Nous avons limité le nombre d'analyse à 5 donc 0 < pos < 5*/
int pos = 0;
/*La structure Data corresponds à l'ensemble des données nécéssaires, pour l'analyse.
chacun des indices du tableaux data correponds aux données d'un des fichiers à analyser.*/
struct Data data[5];
/*Cette fonction copie le chemin d'acces dans lequel est lancé l'executable dans workingDir*/
getcwd(workingDir, sizeof(workingDir));
/*Cette fonction initialise la console en l'effacant*/
resetScreen();
initBorders();
validpop.select = 0;
/*Boucle principal, elle permet d'actualiser en permanence la console*/
while(runExplorer)
{
if(validpop.Active)
{
/*Si la fenetre de la validation est active on "imprime" sur l'écran la fenetre */
popup(validpop.filePath,validpop.select);
}
else
{
resetLeft(); //On efface la partie de gauche
BordersTop(); //On imprime les bordures
tree(workingDir,pos); //On imprime les fichiers/dossiers
}
if(!explorerSelect)
{
selectThreadPos(selectPos);
if(pos > 0 && (data)[selectPos].finish)
{
print("Appuyer sur 'Entrer' pour selectionner",WIDTH/2+2,HEIGHT/2,112);
}
else if(pos >0)
{
print("Analyse en cours...",WIDTH/2+2,HEIGHT/2,112);
}
}
else
{
print("Appuyer sur 'Entrer' pour selectionner",2,HEIGHT-1,112);
}
/*Cette fonction actualise les modifications à l'écran*/
screen();
/*La fonction int kbhit(void); indique si une touche du clavier a été frappée et que,
par conséquent, un caractère est en attente d'être lu. Son appel renvoie 0 si aucun
caractère n'est en attente et une valeur non nulle autrement. La lecture proprement
dite est réalisée à l'aide de la fonction int getch(void);*/
if (_kbhit())
{
int value = getch();
if(!validpop.Active)
{
switch(value) {
case 72: //flèche du haut
if(explorerSelect)
{
if(scroll == selectLine && scroll>0)
{
scroll--;
selectLine--;
}
else if(selectLine != -1)
{
selectLine--;
}
}
else //Right side
{
resetBottomRight();
if(selectPos == 0 && pos >0)
{
selectPos = pos - 1;
}
else if(pos >0)
{
selectPos--;
}
initBorders();
}
break;
case 80: //flèche du bas
if(explorerSelect) //left side
{
if(selectLine == HEIGHT - 6 + scroll && selectLine<(maxLine-1))
{
scroll++;
selectLine++;
}
else if(selectLine<(maxLine-1))
{
selectLine++;
}
}
else //right side
{
resetBottomRight();
if(selectPos == pos -1 && pos >0)
{
selectPos = 0;
}
else if(pos >0)
{
selectPos++;
}
initBorders();
}
break;
case 13: //Bouton "enter"
pressedEnter = true;
if(!explorerSelect && pos > 0)
{
if((data)[selectPos].finish)
{
printResult((data)[selectPos]);
print("Appuyer sur 'o' pour ouvrir les liens",WIDTH/2+2,HEIGHT-1,112);
}
else
{
resetBottomRight();
print("Analyse en cours...",WIDTH/2+4,HEIGHT/2+4,122);
}
pressedEnter = false;
}
else if(selectLine == -1 && scroll ==0)
{
strcat(workingDir,"/..");
pressedEnter = false;
}
break;
case 77: //flèche droite
if(pos != 0)
{
explorerSelect = !explorerSelect;
if(explorerSelect)
{
selectThreadPos(-1);
}
initBorders();
resetBottomRight();
}
break;
case 75: //flèche gauche
if(pos != 0)
{
explorerSelect = !explorerSelect;
if(explorerSelect)
{
selectThreadPos(-1);
}
initBorders();
resetBottomRight();
}
break;
case 111: //bouton 'o' pour open
if((data)[selectPos].finish)
{
int sz = 0;
while(sz < 7 && sz < (data)[selectPos].nbResult) //Deux condition, la première
{
ShellExecute(0, 0, (data)[selectPos].result[sz].url, 0, 0 , SW_SHOW );
sz++;
}
}
break;
case 27: //Touche "echap"
runExplorer = false;
system("CLS");
printf("Program end");
exit(0);
break;
}
}
else /* Cas ou la fenetre de validation est active */
{
//Pressed right / left arrow switch
if(value ==77 || value ==75)
{
if(validpop.select == 1)
{
validpop.select =0;
}
else
{
validpop.select = 1;
}
}
//Pressed Escape or "No"
if(value == 27 || (validpop.select==1 && value ==13))
{
resetLeft();
validpop.Active = false;
validpop.filePath[0] = '\0';
}
//Pressed enter on "Yes"
if(validpop.select==0 && value ==13)
{
/**Ici l'utilisateur à validé la séléction
ainsi nous allons lancer l'analyse du fichier selectionné**/
int rc; //Code d'erreur relatif au threads
int MaxL=0; //Ceci est une variables temporaire.
pthread_t thread; //On déclare un thread.
/*Rappel data est un tableau de structure Data, elle sert a stoquer les informations
relative à chaque scan, elle est de dimension 5, 1 pour chaque scan (maximum 5)*/
(data)[pos].array = phase_1(returnPath,&MaxL,pos); //on recupère une liste de chaine de caractere, provenant de la phase 1
(data)[pos].isProxyNeeded = isProxyNeeded; //On précise si un proxy est nécéssaire
(data)[pos].MaxL = &MaxL; //On utilise notre variables temporaire pour la copie
(data)[pos].pos = pos; //On informe quels est la position du thread actuel
(data)[pos].finish = false; //On l'initialise
strcpy((data)[pos].filename,validpop.filePath); //On copie le NOM DU FICHIER
/*Lors de la création d'un thread, il est impossible d'envoyé plusieurs arguments,
on ne peut envoyer que une adresse indéfinit */
if( (rc=pthread_create( &thread, NULL, &phase_2, &(data[pos]) )) )
{
system("CLS");
printf("Une erreur est survenu lors de l'execution du programme: %d\n Merci de redemarrer le programme.", rc);
exit(EXIT_FAILURE);
}
else
{
/**On lance le thread en detaché c'est à dire, qu'il va s'executer en "parralle" du code actuel
Information complémentaire :
=> http://man7.org/linux/man-pages/man3/pthread_detach.3.html
=> https://stackoverflow.com/a/10598449/10160890 **/
pthread_detach(thread);
pos++;
}
//Une fois le nouveau thread servant pour l'analyse
//créée on continue, et on réinitialise l'explorateur.
resetLeft();
validpop.Active = false;
validpop.filePath[0] = '\0';
}
}
}
}
return;
}
void tree(char *basePath, int pos)
{
int i,line = 0;
char path[1000]; //Ceci est une variables temporaire pour faire des copies etc...
struct dirent *dp; //Cette variables sert pour chaque élément
DIR *dir = opendir(basePath); //On ouvre une directory
if (!dir) //On vérifie qu'elle existe
return;
print((*dir).dd_name,2,0,112); //On imprime en haut a gauche le chemin d'accès
/*on affiche tout en haut de l'explorateur une ligne d'indice -1 qui correspond à remonter*/
//Si la l'utilisateur à selectionner cette élément, et qu'il est entrain d'utiliser l'explorateur
if(selectLine == -1 && explorerSelect)
{
print("../",3,2,158); //On la surligne
}
else if(scroll == 0)
{
print("../",3,2,241); //On l'affiche normalement
}
/**Cette boucle va se réaliser, autant de fois qu'il y a d'élément dans le chemin donné**/
while ((dp = readdir(dir)) != NULL)
{
if(line>=scroll)
{
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
{
/**Ici on "fabrique" le chemin d'accès de chaque fichier
on récupère le chemin de dossier dans lequel on est, on
ajoute un / puis le nom de l'élement lu**/
strcpy(path, basePath);
strcat(path, "/");
strcat(path, dp->d_name);
/** Pour faire la différences entre un fichier et un dossier,
on essaye d'ouvrir l'élément, si c'est un dossier, on aura
un résultat, sinon on aura 0 **/
if(opendir(path))
{ //ALORS C'EST UN DOSSIER
/*Si l'utilisateur à appuyé sur enter ET
que la ligne actuel et la ligne selectionné
alors ouvrir le DOSSIER*/
if(pressedEnter && selectLine == line)
{
workingDir[0] = '\0';
selectLine = 0;
strcat(workingDir,path);
pressedEnter = false;
scroll = 0;
closedir(dir);
return;
}
if(line < HEIGHT - 4 + scroll)
{
//Si la ligne selectionné est la bonne ligne ET que l'utilisateur utilise l'explorateur.
if(selectLine == line && explorerSelect)
{
print(append_(dp->d_name,'/'),3,3+line-scroll,158); //On la surligne
}
else
{
print(append_(dp->d_name,'/'),3,3+line-scroll,241); //On l'affiche normalement
}
line++; //On incrémente le nombre de ligne
}
}
else
{//SINON C'EST UN FICHIER
/*Si l'utilisateur à appuyé sur enter ET
que la ligne actuel et la ligne selectionné
ET que la fenetre de validation n'est pas ouverte
alors ouvrir FENETRE DE VALIDATION*/
if(pressedEnter && selectLine == line && !validpop.Active)
{
//Si le nombre d'élément scanner est < 5
if(pos < 5)
{
strcpy(returnPath,path);
pressedEnter = false;
strcpy(validpop.filePath,dp->d_name); //on met dans la fenetre le nom du fichier
validpop.Active = true; //On ouvre la fenetre
}
else
{
pressedEnter = false;
}
}
/*Si la ligne ne dépasse pas la console*/
if(line < HEIGHT - 4 + scroll)
{
//Si la ligne selectionné est la bonne ligne ET que l'utilisateur utilise l'explorateur.
if(selectLine == line && explorerSelect)
{
print(dp->d_name,3,3+line-scroll,158); //On la surligne
}
else
{
print(dp->d_name,3,3+line-scroll,246); //On l'affiche normalement
}
int i = fsize(path); //On regarde quel taille fait un fichier
char str[20];
if(i > 100000000000)
{
i = i/100000000000;
sprintf(str, "%d To", i);
}
else if(i > 100000000)
{
i = i/100000000;
sprintf(str, "%d Go", i);
}
else if(i > 1000000)
{
i = i/1000000;
sprintf(str, "%d Mo", i);
}
else if(i>1000)
{
i = i/1000;
sprintf(str, "%d Ko", i);
}
else
{
sprintf(str, "%d O", i);
}
print(str,WIDTH/2 - 2 - strlen(str),3+line-scroll,248); //On imprime sur la console
line++; //On incrémente le nombre de ligne
}
}
}
}
else
{
line++;
}
}
maxLine = line; //On note le nombre de ligne affiché
closedir(dir);//On ferme le chemin d'acces
}
/* Explication
=> https://stackoverflow.com/a/238609/10160890 */
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
char* append_(const char *s, char c)
{
int len = strlen(s);
char buf[len+2];
strcpy(buf, s);
buf[len] = c;
buf[len + 1] = 0;
return strdup(buf); //La fonction strdup() renvoie un pointeur sur une nouvelle chaîne de caractères qui est dupliquée depuis s
}
<file_sep>/def.h
/**La console s'adaptera pour différentes valeurs noté ici
Attention, le programme à été fait pour ces valeurs données, des changements
dans ces défitions peuvent amener à des problèmes d'affichage. **/
#define WIDTH 150
#define HEIGHT 45
/**Le programme se reserve de limité le nombre de phrase maximum à scaner à 1000
pour des questions de stabilités, et de fluidité.**/
#define MAX_LINE 1000
/**Le programme limite le nombre de lien à 1000 question de mémoire**/
#define MAX_LINK 1000
/** Question de facilité et d'habitude, il est plus agréable de travailler avec des boolean**/
#define true 1
#define false 0
typedef int bool;
/**Structure relative à la console
On remplis la console de caractère dont on veut pouvoir changer : la couleur, et le type de caractère
ainsi on définit un structure qui sera utilisé dans un tableau a deux dimension pour correspondre
à la taille de la console**/
struct block
{
int color;
unsigned char character;
};
/**Cette structure correponds à la fenêtre de validation, qui peut être active ou non
elle a également, deux choix (oui / non ) qui auront une valeur correspondante dans select
comme information à afficher elle contient également, le nom du fichier.**/
struct Validpop
{
char filePath[120];
int select;
bool Active;
};
/**Dans la phase 2, on réalise des recherches succèssive sur google, les résultats seront stoquer dans
un tableau de structure Link, chaque url est stoquer une seule fois, et on lui attribut un entier indiquant
le nombre de fois qu'il est apparu**/
struct Link
{
int occurence;
char url[1000];
};
/**Cette structure est très importante, elle permet de faire la liason, entre différents threads. En effet,
lors du démarrage d'un nouveaux threads, un seul argument peut être envoyé à la fonction d'arrivé,
donc on creer une structure Data, qui contient toute les informations nécéssaire,
les différents processus pourront alors y acceder en simultané**/
struct Data
{
char ** array; //array of all sentences to scan.
bool isProxyNeeded;
int *MaxL; //Number of sentence to scan (useful to compute progress without strlen on array.
int totalLine;
int pos; //Position on the console (max = 5)
char filename[120];
bool finish;
struct Link result[100];
int nbResult;
};
<file_sep>/README.md
# Plagiat
This project was made for school. That's why the documentation is in french.
It uses differents library as LibCurl to analyse a text file and give a pourcentage of plagiat per url.
In the project instructions, we were limited to window console, that's why we are using it.
# Screenshots
<p align="center">
<b>Analyse and multithreading</b><br>
<img src="https://github.com/axel0070/plagiat/blob/master/Screenshots/1.PNG">
</p>
<p align="center">
<b>Result</b><br>
<img src="https://github.com/axel0070/plagiat/blob/master/Screenshots/2.PNG">
</p>
# Required elements
* Libcurl DDLs
https://curl.haxx.se/download.html
* OpenSSl DDLs
https://curl.haxx.se/windows/dl-7.64.1/
* Tidy DDL
http://binaries.html-tidy.org/
<file_sep>/fileexplorer.h
//Fonctions
void tree(char *basePath,int pos);
off_t fsize(const char *filename);
char* append_(const char *s, char c);
void explore(bool isProxyNeeded);
<file_sep>/phase_2.h
#include <stdio.h>
#include <tidy.h>
#include <string.h>
#include <tidybuffio.h>
#include <curl/curl.h>
//Prototypes de fonctions
uint write_cb(char *in, uint size, uint nmemb, TidyBuffer *out); //== Résultat Curl
void dumpNode(TidyDoc doc, TidyNode tnod, int indent,int pos); //==analyse des noeux XML ( HTML )
void addlink(char *url,int pos);
void initLink(int pos);
char *result(int pos);
void phase_2(void *vargp);
void listLink(int pos);
int estimation(int pos);
| a62434bacf779b398bb6fc21f0ba9a94fd80ee7c | [
"Markdown",
"C"
] | 12 | C | axel0070/plagiat | 9cc8c5fdbe73bdd1e97ef3ca637854c45f0e6b54 | 6af8ce55dc145e110963e49a9b2884b41e9277b9 |
refs/heads/master | <repo_name>bityob/notebooks<file_sep>/gcd.py
# https://www.hackerrank.com/contests/ieeextreme-challenges/challenges/play-with-gcd
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from functools import reduce
from collections import defaultdict
from pprint import pprint
from copy import *
try:
from math import gcd
except:
from fractions import gcd
inputs = """5
2 3 5 6 6
2
2
5
"""
inputs = """7
6 2 3 5 6 6 6
3
2
5
3
"""
# inputs = """3
# 2 4 8
# 1
# 2
# """
# with open("input01.txt", 'r') as reader:
# inputs = reader.read()
# func read for hackerrank
read = lambda: sys.stdin.readline().strip()
multiple = lambda l: reduce(lambda x, y: x*y, l)
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
def all_subsets(xs):
if not xs:
return [[]]
else:
x = xs.pop()
subsets = all_subsets(xs)
subsets_copy = deepcopy(subsets) # NB you need to use a deep copy here!
for s in subsets_copy:
s.append(x)
subsets.extend(subsets_copy)
return subsets
def calc_query(q, subsets, isold=False):
count = 0
for s in subsets:
if (len(s) == 0):
continue
all_multi_values = [multiple(l) for l in s]
curr_gcd = reduce(gcd, all_multi_values)
if curr_gcd == q:
if (isold):
count += 1
# for k in s:
# print balls_dict[q][k]
else:
count += sum(balls_dict[q][k] for k in s)
# print(curr_gcd, all_multi_values)
# if (not isold):
# pass
# count = (2 ** (count - 1)) / 2
return count
if __name__ == '__main__':
# Refresh strdin
sys.stdin = StringIO(inputs)
balls_num = int(read())
balls_list = [int(x) for x in read().split()]
query_num = int(read())
# old
old_balls_dict = defaultdict(list)
for b in balls_list:
# primes_of_ball = primes(b)
primes_of_ball = tuple(primes(b))
for p in primes_of_ball:
old_balls_dict[p].append(primes_of_ball)
balls_dict = defaultdict(lambda: defaultdict(int))
#
# example:
# {
# 2 : {
# (2,3) : 3, # key - set of primes, value - counter
# (2) : 4
# }
# }
for b in balls_list:
primes_of_ball = tuple(set(primes(b)))
for p in primes_of_ball:
balls_dict[p][primes_of_ball] += 1
for _ in [2]:#range(query_num)[:10]:
q = int(read())
print "(New) balls", dict(balls_dict[q])#.keys()
subsets = all_subsets(list(balls_dict[q].keys()))
# subsets = all_subsets(curr_balls)
print "(New) subsets", subsets
print "(New) subsets count", len(subsets)
count = calc_query(q, subsets)
print "(New) Query:", q, "Count:", count
print "(Old) balls", old_balls_dict[q]
subsets = all_subsets(old_balls_dict[q])
print "(Old) subsets", subsets
print "(Old) subsets count", len(subsets)
count = calc_query(q, subsets, isold=True)
print "(Old) Query:", q, "Count:", count
| 7116494f45b1cade14fa5dd6c2855305e6046b0c | [
"Python"
] | 1 | Python | bityob/notebooks | 6dc1f06959c873068742b010f8f87ed952914a7f | a495d8d0f6a176431e5e084586fceb71e63c886c |
refs/heads/main | <repo_name>lmcorbalan/cpk-address-test<file_sep>/.env.example
ACCOUNT_PK=private key of the account you want to find CPK address
INFURA_PROJECT_ID=infura project id
<file_sep>/index.ts
import { config as dotenvConfig } from 'dotenv';
import { resolve } from 'path';
dotenvConfig({ path: resolve(__dirname, './.env') });
import CPK, { EthersAdapter } from 'contract-proxy-kit';
import { ethers } from 'ethers';
const provider = new ethers.providers.JsonRpcProvider(`https://kovan.infura.io/v3/${process.env.INFURA_PROJECT_ID}`)
const PK = process.env.ACCOUNT_PK || ''
const wallet = new ethers.Wallet(PK, provider)
const ethLibAdapter = new EthersAdapter({ ethers, signer: wallet });
(function main() {
return CPK.create({ ethLibAdapter, isSafeApp: false });
})().then(cpk => {
console.log(`User address: ${wallet.address} - CPK address ${cpk.address}`)
})
<file_sep>/README.md
```bash
$ yarn install
```
Create an `.env` file based on `.env.example`
```bash
$ yarn start
```
| 68282f968db4c5005efed9dc89bc21b40ceb4042 | [
"Markdown",
"TypeScript",
"Shell"
] | 3 | Shell | lmcorbalan/cpk-address-test | 1f4f2469c4f8ceebc1ff05c4c94602f45956f20b | 989aab189098921e6ed98940eb7d6b6da1d4326a |
refs/heads/master | <repo_name>RafaelFernando12/Contro-de-estoque2.0<file_sep>/ControleEstoque2.0/src/InterfaceGrafica/MovimentaTelaConsultar.java
package InterfaceGrafica;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MovimentaTelaConsultar implements ActionListener {
TelaIniciaOpcoes tela;
public MovimentaTelaConsultar(TelaIniciaOpcoes telaIniciaOpcoes) {
this.tela = telaIniciaOpcoes;
}
public void actionPerformed(ActionEvent evento) {
String acao = evento.getActionCommand();
if ("Consultar".equals(acao)) {
TelaConsultar chamaTelaConsultar = new TelaConsultar();
chamaTelaConsultar.setVisible(true);
tela.fecha();
}
}
}
<file_sep>/ControleEstoque2.0/src/InterfaceGrafica/MovimentaTelaExcluir.java
package InterfaceGrafica;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MovimentaTelaExcluir implements ActionListener {
TelaIniciaOpcoes tela;
public MovimentaTelaExcluir(TelaIniciaOpcoes telaIniciaOpcoes) {
this.tela = telaIniciaOpcoes;
}
public void actionPerformed(ActionEvent evento) {
String acao = evento.getActionCommand();
if ("Excluir".equals(acao)) {
TelaExcluir chamaTelaExcluir = new TelaExcluir();
chamaTelaExcluir.setVisible(true);
tela.fecha();
}
}
}
<file_sep>/ControleEstoque2.0/src/InterfaceGrafica/TelaConsultar.java
package InterfaceGrafica;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import DAO.OperacoesMenuCadastrarDAO;
public class TelaConsultar extends JFrame {
private JPanel contentPane;
private JLabel rotuloMarca;
private JLabel rotuloModelo;
private JLabel rotuloNumeroCalcado;
private JTextField campoMarca;
private JTextField campoModelo;
private JTextField campoNumeroCalcado;
private static final long serialVersionUID = 1L;
public TelaConsultar() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.setSize(600, 400);
this.setTitle("Pesquisa de Produtos");
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
this.setLocationRelativeTo(null);
rotuloMarca = new JLabel("Marca");
rotuloMarca.setFont(new Font("Bitstream Vera Sans", Font.BOLD, 13));
rotuloMarca.setBounds(12, 4, 188, 15);
contentPane.add(rotuloMarca);
rotuloModelo = new JLabel("Modelo");
rotuloModelo.setFont(new Font("Bitstream Vera Sans", Font.BOLD, 13));
rotuloModelo.setBounds(12, 44, 188, 15);
contentPane.add(rotuloModelo);
rotuloNumeroCalcado = new JLabel("Número do Calçado");
rotuloNumeroCalcado.setFont(new Font("Bitstream Vera Sans", Font.BOLD, 13));
rotuloNumeroCalcado.setBounds(12, 84, 188, 15);
contentPane.add(rotuloNumeroCalcado);
campoMarca = new JTextField();
campoMarca.setToolTipText("Digite a marca do calçado que está buscando");
campoMarca.setBounds(180, 4, 320, 21);
contentPane.add(campoMarca);
campoMarca.setColumns(10);
campoModelo = new JTextField();
campoModelo.setToolTipText("Digite o modelo do calçado que está buscando");
campoModelo.setBounds(180, 44, 320, 21);
contentPane.add(campoModelo);
campoModelo.setColumns(10);
campoNumeroCalcado = new JTextField();
campoNumeroCalcado.setToolTipText("Digite o número do tamanha do calçado que está buscando");
campoNumeroCalcado.setBounds(180, 84, 320, 21);
contentPane.add(campoNumeroCalcado);
campoNumeroCalcado.setColumns(10);
JButton btnPesquisar = new JButton("Buscar");
// btnPesquisar.setIcon(new
// ImageIcon("/home/rafaelfernando/eclipse-workspace/ControleEstoque2.0/src/InterfaceGrafica/Imagens/rafa.png"));
btnPesquisar.setBounds(84, 301, 116, 25);
contentPane.add(btnPesquisar);
btnPesquisar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evento) {
String acao = evento.getActionCommand();
if ("Buscar".equals(acao)) {
if (campoMarca != null && campoModelo != null && campoNumeroCalcado != null
&& !campoMarca.getText().trim().isEmpty() && !campoModelo.getText().trim().isEmpty()
&& !campoNumeroCalcado.getText().trim().isEmpty()) {
String resultado;
OperacoesMenuCadastrarDAO buscaBanco = new OperacoesMenuCadastrarDAO();
String marca = campoMarca.getText();
String modelo = campoModelo.getText();
int numeroCalcado = Integer.parseInt(campoNumeroCalcado.getText());
resultado = buscaBanco.consultaProdutos(marca, modelo, numeroCalcado);
JOptionPane.showMessageDialog(null, resultado, "Produto Encontrado", JOptionPane.PLAIN_MESSAGE);
// entra o método que vai no banco e conecta e faz a pesquisa e retorna valores
int confirmacao = JOptionPane.showConfirmDialog(null, "Deseja realizar outra pesquisa ? ");
if (confirmacao == JOptionPane.YES_OPTION) {
fechaTelaConsultar();
TelaConsultar chamaTelaConsultar = new TelaConsultar();
chamaTelaConsultar.setVisible(true);
} else if (confirmacao == JOptionPane.NO_OPTION) {
TelaIniciaOpcoes tela = new TelaIniciaOpcoes();
tela.abre();
fechaTelaConsultar();
}
} else {
JOptionPane.showMessageDialog(null,
"O preechimento de todos campos são obrigatórios para realizar a busca.", "Alerta", 2);
}
}
}
});
JButton btnVoltar = new JButton("Voltar");
btnVoltar.setIcon(
new ImageIcon(TelaConsultar.class.getResource("/com/sun/javafx/scene/web/skin/Undo_16x16_JFX.png")));
btnVoltar.setBounds(222, 301, 116, 25);
contentPane.add(btnVoltar);
btnVoltar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evento) {
TelaIniciaOpcoes tela = new TelaIniciaOpcoes();
tela.abre();
fechaTelaConsultar();
}
});
JButton btnLimpar = new JButton("Limpar");
btnLimpar.setIcon(new ImageIcon(
"/home/rafaelfernando/eclipse-workspace/ControleEstoque2.0/src/InterfaceGrafica/Imagens/iconlimpar2.png"));
btnLimpar.setBounds(360, 301, 116, 25);
contentPane.add(btnLimpar);
btnLimpar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evento) {
campoMarca.setText("");
campoModelo.setText("");
campoNumeroCalcado.setText("");
}
});
}
public void fechaTelaConsultar() {
this.setVisible(false);
}
}
| bf3978dfbfbfb8e14c5a9e64bee0549ed2614944 | [
"Java"
] | 3 | Java | RafaelFernando12/Contro-de-estoque2.0 | 3448f500cbd6793d3e416ff63bbc7a81cfc026a6 | f606c5e40cc2abbeb1847a6cbba34dbefdc5fac7 |
refs/heads/master | <file_sep>/**
Copyright 2016 Siemens AG.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.siemens.industrialbenchmark.dynamics.goldstone;
import com.google.common.base.Preconditions;
/**
* Reward function for normalized, linearly biased Goldstone Potential
*
* @author <NAME>, <NAME>
*/
public class PenaltyFunction {
private final double phi;
private final double max_required_step;
private final DoubleFunction reward_function;
private final double optimum_radius;
private final double optimum_value;
/**
* generates the reward function for fixed phi
works ONLY WITH SCALAR inputs
* @param phi angle in radians
* @param max_required_step the max. required step by the optimal policy; must be positive
*/
public PenaltyFunction(double phi, double max_required_step) {
Preconditions.checkArgument(max_required_step > 0,
"max_required_step must be > 0, but was %s", max_required_step);
this.phi = phi;
this.max_required_step = max_required_step;
reward_function = reward_function_factory(phi, max_required_step);
optimum_radius = compute_optimal_radius(phi, max_required_step);
optimum_value = reward_function.apply(optimum_radius);
}
public double reward (double r) {
return reward_function.apply(r);
}
/**
* vectorized version of reward(double)
* @param r
* @return
*/
public double[] reward (double r[]) {
double ret[] = new double [r.length];
for (int i=0; i<r.length; i++) {
ret[i] = reward(r[i]);
}
return ret;
}
// ################################################################################### #
// # Radius Transformation #
// # --------------------------------------------------------------------------------- #
// # ################################################################################# #
private DoubleFunction transfer_function_factory(final double r0, double chi, double xi) {
final double exponent = chi / xi;
final double scaling = xi / Math.pow(chi, exponent);
return new DoubleFunction() {
@Override
public double apply(double value) {
return r0 + scaling * Math.pow(value, exponent);
}
};
}
private DoubleFunction rad_transformation_factory(double x0, double r0, double x1, double r1) {
Preconditions.checkArgument(
(x0<=0 && r0<=0 && x1<=0 && r1<=0) ||
(x0>=0 && r0>=0 && x1>=0 && r1>=0),
"x0, r0, x1, r1 must be either all positive or all negative, " +
"but was x0=%s, r0=%s, x1=%s, r1=%s", x0, r0, x1, r1);
x0 = Math.abs(x0);
r0 = Math.abs(r0);
x1 = Math.abs(x1);
r1 = Math.abs(r1);
Preconditions.checkArgument(x0>0 && r0>0,
"x0 and r0 must be positive, but was x0=%s and r0=%s", x0, r0);
Preconditions.checkArgument(x1>=x0 && r1>=r0,
"required: (x0, r0) < (x1, r1), but was x0=%s, r0=%s x1=%s, r1=%s", x0, r0, x1, r1);
final double rscaler = r0 / x0;
final double final_r0 = r0;
final double final_x0 = x0;
final double final_x1 = x1;
final double final_r1 = r1;
final DoubleFunction seg2_tsf =
transfer_function_factory(final_r0, final_x1-final_x0, final_r1-final_r0);
return new DoubleFunction() {
@Override
public double apply(double x) {
final double s = Math.signum(x);
x = Math.abs(x);
if (x<=final_x0) {
return s*rscaler*x;
}
if (x<final_x1){
return s*seg2_tsf.apply(x-final_x0);
}
return s*(x-final_x1+final_r1);
}
};
}
// # ################################################################################# #
// # Radius transforming NLGP #
// # --------------------------------------------------------------------------------- #
// # ################################################################################# #
/**
* """
Computes radius for the optimum (global minimum). Note that
for angles phi = 0, pi, 2pi, ... the Normalized Linear-biased
Goldstone Potential has two global minima.
Per convention, the desired sign of the return value is:
opt radius > 0 for phi in [0,pi)
opt radius < 0 for phi in [pi,2pi)
Explanation:
* for very small angles, where the sin(phi) is smaller than max_required_step
the opt of the reward landscape should be per definition at
max_required_step if phi in [0,pi)
-max_required_step if phi in [pi,2pi)
(max_required_step is assumed to be positive)
* for all cases phi != 0,pi,2pi
the sign is identical to the sign of the sin function
* but for phi = 0,pi,2pi the sig-function is zero and
provides no indication about the sign of the opt
"""
*
* @param phi
* @param max_required_step
* @return
*/
private double compute_optimal_radius (double phi, double max_required_step) {
phi = phi % (2*Math.PI);
double opt = Math.max(Math.abs(Math.sin(phi)), max_required_step);
if (phi>=Math.PI) {
opt *= -1;
}
return opt;
}
/**
Generates the reward function for fixed phi. Works ONLY WITH SCALAR inputs.
* @param p angle in Radians
* @param max_required_step the max. required step by the optimal policy; must be positive
* @return
*/
private DoubleFunction reward_function_factory(double phi, double max_required_step) {
final NLGP l = new NLGP();
final double pTmp = phi % (2*Math.PI);
final double p = pTmp < 0 ? pTmp+(2*Math.PI) : pTmp;
double opt_rad = compute_optimal_radius(p, max_required_step);
double r0 = l.global_minimum_radius(p);
final DoubleFunction tr = rad_transformation_factory(opt_rad, r0, Math.signum(opt_rad)*2, Math.signum(r0)*2);
return new DoubleFunction() {
@Override
public double apply(double r) {
return l.polar_nlgp(tr.apply(r), p);
}
};
}
public double getOptimumRadius() {
return optimum_radius;
}
public double getOptimumValue() {
return optimum_value;
}
public double getPhi() {
return this.phi;
}
public double getMaxRequiredStep() {
return this.max_required_step;
}
}
<file_sep>Industrial Benchmark:
=====================
Requires: Java 8 and Apache Maven 3.x
Documentation: The documentation is available online at: https://arxiv.org/abs/1610.03793
Source: <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. "Introduction to the
Industrial Benchmark". CoRR, arXiv:1610.03793 [cs.LG], pages 1-11. 2016.
Citing Industrial Benchmark:
============================
To cite Industrial Benchmark, please reference:
<NAME>, <NAME>, <NAME>, <NAME> and <NAME>. "Introduction to the
Industrial Benchmark". CoRR, arXiv:1610.03793 [cs.LG], pages 1-11. 2016.
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. "Batch Reinforcement
Learning on the Industrial Benchmark: First Experiences." Neural Networks (IJCNN), 2017
International Joint Conference on. IEEE, 2017. (accepted) (to be published)
<NAME>, <NAME>, <NAME>, and <NAME>. "Learning and
policy search in stochastic dynamical systems with bayesian neural networks." arXiv
preprint arXiv:1605.07127, 2016.
Inclusion as a dependency to your Java/Maven project:
=====================================================
<dependency>
<groupId>com.siemens.oss.industrialbenchmark</groupId>
<artifactId>industrialbenchmark</artifactId>
<version>1.1.1</version>
</dependency>
Compilation + Run:
==================
mvn clean package
java -jar industrialbenchmark-<VERSION>.jar <OPTIONAL_CONFIG_FILE>
E.g.: java -jar target/industrialbenchmark-<VERSION>-SNAPSHOT-jar-with-dependencies.jar src/main/resources/sim.properties
=> a random trajectory is generated
=> all observable state variables are written to file dyn-observable.csv.
=> all markov state variables are written to file dyn-markov.csv
Example main()-Function:
========================
An example usage of the industrial benchmark can be found in the class com.siemens.industrialbenchmark.ExampleMain.
This class is intented to be a template for data generation.
| 9490541df4dbab7639abb893c0f483ddaaae9b94 | [
"Java",
"Text"
] | 2 | Java | shehroze37-zz/industrialbenchmark | d4c826392771e8d281d0dcbd30c624d6ef31b97e | 3196a574f0d8a001af7e19c951e3cb28aca82d35 |
refs/heads/master | <repo_name>helunwencser/MusicClassification<file_sep>/dnn/DNN.py
from __future__ import print_function
import numpy as np
import tflearn
# Load CSV file, indicate that the first column represents labels
from tflearn.data_utils import load_csv
print('Load data...');
data, labels = load_csv('data.csv', target_column=13, categorical_labels=True, n_classes=10);
index = int(len(data)*0.8);
training_data = data[0:index];
training_label = labels[0:index];
test_data = data[index:];
test_label = labels[index:];
print('Building neural network...');
# Build neural network
net = tflearn.input_data(shape=[None, 13]);
net = tflearn.fully_connected(net, 32);
net = tflearn.fully_connected(net, 32);
net = tflearn.fully_connected(net, 32);
net = tflearn.fully_connected(net, 32);
net = tflearn.fully_connected(net, 10, activation='softmax');
net = tflearn.regression(net);
# Define model
model = tflearn.DNN(net);
print('Training model...');
# Start training (apply gradient descent algorithm)
model.fit(training_data, training_label, n_epoch=50, batch_size=1000, show_metric=True);
print('Saving model...');
model.save('./model/dnn_model');
print('Testing model...');
pred = model.predict(test_data);
count = float(0);
for idx, val in enumerate(pred):
label = test_label[idx];
if np.argmax(label) == np.argmax(val):
count += 1;
accuracy=count/len(test_label);
print('The accuracy of model is {}'.format(accuracy));<file_sep>/FeatureExtraction/extract_chroma_features.py
# https://github.com/tyiannak/pyAudioAnalysis/wiki
from pyAudioAnalysis import audioBasicIO
from pyAudioAnalysis import audioFeatureExtraction
import pandas as pd
import os
def extract_one(filename, folder):
'''
:param filename: path for the wav file
:param folder: output folder path of the csv file
:return:
'''
[Fs, x] = audioBasicIO.readAudioFile(filename)
F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 0.025*Fs, 0.010*Fs)
filename = filename.split('/')[-1]
output = os.path.join(folder, filename[:-3] + 'csv')
df = pd.DataFrame(data=F.T.astype(float))
if not os.path.exists(folder):
os.makedirs(folder)
df.to_csv(output, sep=',', header=False, float_format='%.5f', index=False)
def extract_allfile():
'''
extract 34 features for each audios for 10 genres and output csv file in the same folder structure feature.
:return:
'''
root_folder = '../wav/genres'
categories = os.listdir(root_folder)
output_root = '../features'
print categories
for cat in categories:
subfolder = os.path.join(root_folder,cat)
output_sub = os.path.join(output_root,cat)
for file in os.listdir(subfolder):
extract_one(os.path.join(subfolder, file),output_sub)
print cat
extract_allfile()<file_sep>/dnn/Validation.py
import numpy as np
import tflearn
import matlab.engine
import operator
import os
import re
# To use matlab.engine, please go to /Applications/MATLAB_R2016a.app/extern/engines/python/
# and run python setup.py install
# https://www.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html
type_to_class = {
0: 'blues',
1: 'classical',
2: 'country',
3: 'disco',
4: 'hiphop',
5: 'jazz',
6: 'metal',
7: 'pop',
8: 'reggae',
9: 'rock'
}
types = {'blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock'}
def featureExtraction(filename):
'''
Get the feature of audio file
:param filename: audio file name
:return: audio feature
'''
engine = matlab.engine.start_matlab()
return engine.featureExtractionForSingleFile(filename)
def load_model():
'''
Load model
:return: model
'''
# Build neural network
net = tflearn.input_data(shape=[None, 13])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 10, activation='softmax')
net = tflearn.regression(net)
# Define model
model = tflearn.DNN(net)
model.load('./model/dnn_model', False)
return model
def classify(model, file):
'''
Classify audio file
:param model: neural model
:param file: audio file
:return: audio file class
'''
pred = model.predict(featureExtraction(file))
dict = {};
for idx, val in enumerate(pred):
type = np.argmax(val);
dict[type] = dict.get(type, 0) + 1;
return type_to_class.get(max(dict.items(), key=operator.itemgetter(1))[0], 'no class found')
def main():
model = load_model();
correct_result = 0
directories = os.listdir('./data')
for directory in directories:
if directory in types:
print('Validating type: {}'.format(directory))
files = os.listdir('./data/{}'.format(directory))
for file in files:
if file.endswith('.au'):
index = int(re.findall('\d+', file)[0])
if index >= 80:
type = classify(model, './data/{0}/{1}'.format(directory, file))
print('\tValidating audio file: {0}/{1}, {2}'.format(directory, file, type))
if type == directory:
correct_result += 1
print('Correct: {}'.format(correct_result))
print('{0} files out of {1} are correctly classified.'.format(correct_result, 200))
print('The accuracy is {}.'.format(correct_result / float(200)))
if __name__ == "__main__":
main()
<file_sep>/baseline/validation.py
from __future__ import print_function
import tflearn
def build_load_model():
print('Building neural network...')
# Build neural network
net = tflearn.input_data(shape=[None, 13])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 10, activation='softmax')
net = tflearn.regression(net)
# Define model
model = tflearn.DNN(net)
model.load('model_{}/dnn_model'.format(30))
return model
def main():
model = build_load_model()
if __name__ == "__main__":
main()
<file_sep>/dnn/Classification.py
import numpy as np
import tflearn
import matlab.engine
import operator
import sys
# To use matlab.engine, please go to /Applications/MATLAB_R2016a.app/extern/engines/python/
# and run python setup.py install
# https://www.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html
def main():
filename = sys.argv[1];
engine = matlab.engine.start_matlab();
data = engine.featureExtractionForSingleFile(filename);
print('done');
print('Load data finished')
print('building neural network');
# Build neural network
net = tflearn.input_data(shape=[None, 13])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 10, activation='softmax')
net = tflearn.regression(net)
# Define model
model = tflearn.DNN(net)
print('start loading model')
model.load('./model/dnn_model', False);
print('predict...')
pred = model.predict(data)
type_to_class = {
0:'blues',
1:'classical',
2:'country',
3:'disco',
4:'hiphop',
5:'jazz',
6:'metal',
7:'pop',
8:'reggae',
9:'rock'
};
dict = {};
for idx, val in enumerate(pred):
type = np.argmax(val);
dict[type] = dict.get(type, 0) + 1;
print(dict)
print(type_to_class)
print(type_to_class.get(max(dict.items(), key=operator.itemgetter(1))[0], 'no class found'));
if __name__ == "__main__":
main()<file_sep>/README.md
# MusicClassification
##Music Classification
11-751, Fall 2016, Carnegie Mellon University
<NAME>, <NAME>, <NAME>
<file_sep>/baseline/sklearn_models.py
__author__ = 'zhengyiwang'
import numpy as np
import math
import time
from sklearn.svm import SVC
# load data
start = time.time()
filename="data.csv"
X = np.loadtxt(filename,delimiter=',')
print 'load finished took %d s' % (time.time() - start)
# split training and testing data
y = X[:,-1]
X = X[:,:-1]
m = X.shape[0]
split = int(math.floor(m*0.8))
X_tr=X[:split]
X_te=X[split:]
y_tr=y[:split]
y_te=y[split:]
print X_tr.shape, X_te.shape
# training data
start = time.time()
cfl = SVC(C=1.0, kernel='rbf', degree=2, gamma=0.001,
coef0=0.0, shrinking=True, probability=False,
tol=0.001, cache_size=200, class_weight=None,
verbose=True, max_iter=-1, decision_function_shape=None, random_state=None)
cfl.fit(X_tr,y_tr)
print 'train finished took %d s' % (time.time() - start)
y_p = cfl.predict(X_te)
accuracy = (y_p == y_te).sum()/float(len(y_te))
print 'accuracy =', accuracy
<file_sep>/baseline/DT_NN_vote.py
__author__ = 'zhengyiwang'
import numpy as np
import math
import time
import os
from collections import Counter
from validation import build_load_model
from sklearn.neighbors.nearest_centroid import NearestCentroid
# from sklearn.neural_network import MLPClassifie
# from sklearn.gaussian_process import GaussianProcessClassifier
# from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.neighbors import KNeighborsClassifier
# load data
start = time.time()
filename="data.csv"
X = np.loadtxt(filename,delimiter=',')
print 'load finished took %d s' % (time.time() - start)
# split training and testing data
y = X[:,-1]
X = X[:,:-1]
m = X.shape[0]
split = int(math.floor(m*0.8))
X_tr=X[:split]
X_te=X[split:int(split+split*0.4)]
y_tr=y[:split]
y_te=y[split:int(split+split*0.4)]
print X_tr.shape, X_te.shape
# training data
start = time.time()
clf = DecisionTreeClassifier(max_depth=10)
clf.fit(X_tr,y_tr)
print 'train finished took %d s' % (time.time() - start)
y_p =clf.predict(X_te)
accuracy = (y_p == y_te).sum()/float(len(y_te))
print 'testing accuracy =', accuracy
# validation dataset
root_folder = 'feature_txt'
categories = os.listdir(root_folder)
print categories
type_to_class = {
0: 'blues',
1: 'classical',
2: 'country',
3: 'disco',
4: 'hiphop',
5: 'jazz',
6: 'metal',
7: 'pop',
8: 'reggae',
9: 'rock'
}
count = 0
total = 0
model = build_load_model()
for cat in categories:
subfolder = os.path.join(root_folder,cat)
if not os.path.isdir(subfolder) or cat.startswith('.'):
continue
print cat + ':'
for file in os.listdir(subfolder):
if not file.startswith('.') and int(file[-6:-4]) >= 80:
X = np.loadtxt(os.path.join(subfolder, file),delimiter=',')
y_p =clf.predict(X)
# NN model loaded
y_nn = model.predict(X)
y_nn = [np.argmax(y) for y in y_nn]
counter = Counter(y_p) + Counter(y_nn)
genre = type_to_class[int(counter.most_common(1)[0][0])]
print file + '...'+ genre
total += 1
if genre == cat:
print "correct!"
count += 1
print "validation accuracy = " + str(count *1.0/total) | b0cb20af8ceea49059a92890bee6ef607fb5f44b | [
"Markdown",
"Python"
] | 8 | Python | helunwencser/MusicClassification | 9311fbfba4003ebc77fe76169e7d12d6c9f4e553 | ff508c0fa75b848e789cdb45cde8cb8fafb90892 |
refs/heads/master | <file_sep>import React from 'react';
import './List.css'
import Li from '../Li';
class List extends React.Component{
constructor(props) {
super(props);
this.state = {
input: '',
}
}
onChangeValue(valueChange) {
console.log(valueChange)
this.props.onChange(valueChange)
}
handleClickDel(index) {
this.props.onDel(index);
}
render() {
const {list} = this.props;
return (
<div className="List">
{list.map((item,index)=>{
return (
<Li
item={item}
key={index}
index = {index}
onChange={this.onChangeValue.bind(this)}
onDel={this.handleClickDel.bind(this)}
/>
)
})}
</div>
)
}
}
export default List;<file_sep>import React from 'react';
import {Input,Button} from 'antd';
class Li extends React.Component{
constructor(props) {
super(props);
this.state = {
isMod: false,
inputValue: this.props.item,
}
}
handleClickDel(index) {
this.props.onDel(index);
}
handleClickMod() {
this.setState({
isMod: true,
inputValue:this.props.item,
})
}
handleClickConfirm(index) {
const inputValue = this.state.inputValue;
this.props.onChange({inputValue,index})
this.setState({
isMod: false,
})
}
onChangeValue(e) {
this.setState({
inputValue: e.target.value,
})
}
render() {
const {index,item} = this.props;
return (
<div className="flex_li">
{
this.state.isMod === false
? <div>{item}</div>
: <Input value={this.state.inputValue} onChange={this.onChangeValue.bind(this)} style={{width:'400px'}} />
}
<div>
<Button onClick={this.handleClickDel.bind(this,index)}>删除</Button>
{
this.state.isMod === false
? <Button onClick={this.handleClickMod.bind(this,index)}>修改</Button>
: <Button onClick={this.handleClickConfirm.bind(this,index)}>确定</Button>
}
</div>
</div>
)
}
}
export default Li;<file_sep>import React from 'react';
import './App.css';
import InputCom from './components/InputCom/InputCom'
import List from './components/List/List';
import 'antd/dist/antd.css';
class Todolist extends React.Component{
constructor(props) {
super(props);
this.state = {
inputValue:'',
list:[],
mod:'',
}
}
handleInputChange(inputValue) {
this.setState({
inputValue:inputValue,
})
}
handleButtonSubmit() {
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
handleClickDel(index) {
const list = this.state.list;
list.splice(index,1);
this.setState({
list: list,
})
}
inputValueChange(valueChange) {
const list = this.state.list;
const index = valueChange.index
list[index] = valueChange.inputValue;
this.setState({
list: list,
})
}
handleButtonSearch() {
const inputValue = this.state.inputValue;
const list = this.state.list;
let arr = [];
list.forEach((item)=>{
if(item === inputValue){
arr.push(item)
}
})
this.setState({
list: arr
})
}
render() {
return (
<div className="App">
<InputCom
inputValue={this.state.inputValue}
onChange={this.handleInputChange.bind(this)}
onAdd={this.handleButtonSubmit.bind(this)}
onSearch={this.handleButtonSearch.bind(this)}
/>
<List
list={this.state.list}
onDel={this.handleClickDel.bind(this)}
onChange={this.inputValueChange.bind(this)}
/>
</div>
);
}
}
export default Todolist;
<file_sep>This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
### demo简介:
此demo是使用React脚手架(create-react-app),实现 “ 增删该查 ” 功能的小实例,看懂这个实例,你就已经基本掌握了react,后期再进行例如Redux等更复杂的技术学习。
### demo涉及的React技术点:
1.JSX
2.元素渲染
3.组件 & Props
4.State
5.事件处理
6.条件渲染
7.列表 & key
8.父子组件的状态管理
9.Ant Design React UI组件库
### 从git中拉取此demo后,你可以按照以下步鄹进行操作:
### `npm install`
下载依赖包
### `npm start`
启动程序,浏览器会自动打开3000或者3003端口(3003是我在package.json文件中设置的)
### 如果你喜欢这个demo,给个星星呗!
| f4f2d9198f09aaa2d442d25b59881e16ae0871cf | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | wdldans/react-demo-Create-Read-Update-Delete- | c450f6d36ef7856584370a9f55a8f03ca8dbb9ee | ad4bce6ec906ecdc431c21f5a6846a1c708ea6c4 |
refs/heads/master | <file_sep>import pandas as pd
import numpy as np
raw_data = {'student':['A','B','C','D','E'],
'score': [100, 96, 80, 105,156],
'height': [7, 4,9,5,3],
'trigger1' : [84,95,15,78,16],
'trigger2' : [99,110,30,93,31],
'trigger3' : [114,125,45,108,46]}
df = pd.DataFrame(raw_data)
print(df)
def text_df(df):
if (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return "Red"
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return "Yellow"
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return "Orange"
elif (df['height'] > 8):
return np.nan
df['Flag'] = df.apply(text_df, axis = 1)
df['t1Flag'] = df['trigger1'].apply(lambda x: 'True' if x >= 75 and x <=85 else 'False')
df['t2Flag'] = df['trigger2'].apply(lambda x: 'True' if x >= 90 else 'False')
print("______________________________________________________________________________")
print(df)
newDf= df[(df.t1Flag == "True") & (df.t2Flag == "True")]
print("______________________________________________________________________________")
print(newDf)
#alternate method of above logic to filterout the rows from datframe
"""
lis = ['A','D']
aDf = df[(df.trigger1 >= 75) & (df.trigger1<= 85) & (df.student.isin(lis))]
print(df)
"""
<file_sep>FROM python
MAINTAINER 'deepanshu'
RUN apt install python3 -y
RUN pip3 install pandas
RUN mkdir /dockertest
COPY dataframe_rows_filter.py /dockertest/dataframe_rows_filter.py
WORKDIR /dockerTest
CMD python3 /dockertest/dataframe_rows_filter.py
| 8862b19f8e75fe02c4ed84f4e6e6510d9bf1c8fd | [
"Python",
"Dockerfile"
] | 2 | Python | deepanshusamdani/docker25feb | 59019ceaf5085ce188dfdbee54ed8601c2b5a936 | 4e0e01aaf557e237b247b633b347ce54ceb2f7e5 |
refs/heads/master | <file_sep># recettes-webservice
RESTful Web Service for [Recettes Android App](https://github.com/hieumt2198/Recettes)
## Installation
* Download or clone this repository
* Go to downloaded folder
* Run command `npm install`
* Run command `node index.js`
## API
### User
* GET `/api/users/:userId`
* POST `/api/users`
### Recipe
* GET `/api/recipes`
* POST `/api/recipes`
* GET `/api/recipes/:id`
* PUT `/api/recipes/:id`
* DELETE `/api/recipes/:id`
* POST `/api/search/recipes`
### Ingredient
* GET `/api/ingredients`
* POST `/api/ingredients`
* GET `/api/ingredients/:id`
* PUT `/api/ingredients/:id`
* DELETE `/api/ingredients/:id`
* GET `/api/search/ingredients/:recipe_id`
### Tag
* GET `/api/tags`
* POST `/api/tags`
* GET `/api/tags/:id`
* PUT `/api/tags/:id`
* DELETE `/api/tags/:id`
* GET `/api/search/tags/:recipe_id`
### Comment
* GET `/api/comments`
* POST `/api/comments`
* GET `/api/comments/:id`
* PUT `/api/comments/:id`
* DELETE `/api/comments/:id`
* GET `/api/search/comments/:recipe_id`
<file_sep>// tagController.js
// Import tag model
Tag = require('./tagModel');
// Handle index actions
exports.index = function (req, res) {
Tag.get(function (err, tags) {
if (err) {
res.json({
status: "error",
message: err,
});
}
res.json({
status: "success",
message: "Tags retrieved successfully",
data: tags
});
});
};
// Handle create tag actions
exports.new = function (req, res) {
var tag = new Tag(req.body);
// save the tag and check for errors
tag.save(function (err) {
// if (err)
// res.json(err);
res.json({
message: 'New tag created!',
data: tag
});
});
};
// Handle view tag info
exports.view = function (req, res) {
Tag.findById(req.params.tag_id, function (err, tag) {
if (err)
res.send(err);
res.json({
message: 'Tag details loading..',
data: tag
});
});
};
// Handle update tag info
exports.update = function (req, res) {
Tag.findById(req.params.tag_id, function (err, tag) {
if (err)
res.send(err);tag.name = req.body.name ? req.body.name : tag.name;
// save the tag and check for errors
tag.save(function (err) {
if (err)
res.json(err);
res.json({
message: 'Tag Info updated',
data: tag
});
});
});
};
// Handle delete tag
exports.delete = function (req, res) {
Tag.remove({
_id: req.params.tag_id
}, function (err, tag) {
if (err)
res.send(err);res.json({
status: "success",
message: 'Tag deleted'
});
});
};<file_sep>// tagModel.js
var mongoose = require('mongoose');
// Setup schema
var tagSchema = mongoose.Schema({
name: {
type: String,
required: true
}
});
// Export Tag model
var Tag = module.exports = mongoose.model('tag', tagSchema);
module.exports.get = function (callback, limit) {
Tag.find(callback).limit(limit);
}<file_sep>// commentModel.js
var mongoose = require('mongoose');
// Setup schema
var commentSchema = mongoose.Schema({
content: String,
ownerId: String,
recipeId: String,
modifiedDate: {
type: Date,
default: Date.now
}
});
// Export Comment model
var Comment = module.exports = mongoose.model('comment', commentSchema);
module.exports.get = function (callback, limit) {
Comment.find(callback).limit(limit);
}<file_sep>// ingredientController.js
// Import ingredient model
Ingredient = require('./ingredientModel');
// Handle index actions
exports.index = function (req, res) {
Ingredient.get(function (err, ingredients) {
if (err) {
res.json({
status: "error",
message: err,
});
}
res.json({
status: "success",
message: "Ingredients retrieved successfully",
data: ingredients
});
});
};
// Handle create ingredient actions
exports.new = function (req, res) {
var ingredient = new Ingredient(req.body);
// save the ingredient and check for errors
ingredient.save(function (err) {
// if (err)
// res.json(err);
res.json({
message: 'New ingredient created!',
data: ingredient
});
});
};
// Handle view ingredient info
exports.view = function (req, res) {
Ingredient.findById(req.params.ingredient_id, function (err, ingredient) {
if (err)
res.send(err);
res.json({
message: 'Ingredient details loading..',
data: ingredient
});
});
};
// Handle update ingredient info
exports.update = function (req, res) {
Ingredient.findById(req.params.ingredient_id, function (err, ingredient) {
if (err)
res.send(err);
ingredient.name = req.body.name ? req.body.name : ingredient.name;
// save the ingredient and check for errors
ingredient.save(function (err) {
if (err)
res.json(err);
res.json({
message: 'Ingredient Info updated',
data: ingredient
});
});
});
};
// Handle delete ingredient
exports.delete = function (req, res) {
Ingredient.remove({
_id: req.params.ingredient_id
}, function (err, ingredient) {
if (err)
res.send(err);res.json({
status: "success",
message: 'Ingredient deleted'
});
});
};<file_sep>// Import express
let express = require('express');
// Import Body parser
let bodyParser = require('body-parser');
// Import Mongoose
let mongoose = require('mongoose');
// Initialise the app
let app = express();
// For image uploading
let multer = require('multer');
let path = require('path');
let crypto = require('crypto');
let fs = require('fs');
// Import routes
let apiRoutes = require("./api-routes");
// Configure bodyparser to handle post requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Connect to Mongoose and set connection variable
mongoose.connect('mongodb://ubal9vgh0u8v4hagerew:<EMAIL>:27017/b6zmtqgtmaxasfw', { useNewUrlParser: true});
var db = mongoose.connection;
// Added check for DB connection
if(!db)
console.log("Error connecting db")
else
console.log("Db connected successfully")
// Setup server port
var port = process.env.PORT || 8080;
// Send message for default URL
// app.get('/', (req, res) => res.send('Hello World with Express'));
// Use Api routes in the App
app.use('/api', apiRoutes);
// Image uploading
let form = "<!DOCTYPE HTML><html><body>" +
"<form method='post' action='/upload' enctype='multipart/form-data'>" +
"<input type='file' name='upload'/>" +
"<input type='submit' /></form>" +
"</body></html>";
app.get('/', function (req, res){
res.writeHead(200, {'Content-Type': 'text/html' });
res.end(form);
});
storage = multer.diskStorage({
destination: './uploads/',
filename: function(req, file, cb) {
return crypto.pseudoRandomBytes(16, function(err, raw) {
if (err) {
return cb(err);
}
return cb(null, "" + (raw.toString('hex')) + (path.extname(file.originalname)));
});
}
});
// Post files
app.post(
"/upload",
multer({
storage: storage
}).single('upload'), function(req, res) {
// res.redirect("/uploads/" + req.file.filename);
res.json({
status: "success",
filename: req.file.filename,
path: "/uploads/" + req.file.filename
});
}
);
app.get('/uploads/:upload', function (req, res){
file = req.params.upload;
var img = fs.readFileSync(__dirname + "/uploads/" + file);
res.writeHead(200, {'Content-Type': 'image/png' });
res.end(img, 'binary');
}
);
// Launch app to listen to specified port
app.listen(port, function () {
console.log("Running Recettes on port " + port);
});
<file_sep>// searchController.js
// Import recipe model
Recipe = require('./recipeModel');
// Import recipe model
Ingredient = require('./ingredientModel');
// Import comment model
Comment = require('./commentModel');
// Import tag model
Tag = require('./tagModel');
// Handle search
exports.getIngredientsByRecipeId = function (req, res) {
Recipe.findById(req.params.recipe_id, async function (err, recipe) {
if (err)
res.send(err);
ingredientIds = recipe["ingredientIds"];
ingredientArr = [];
for(var ingredientId of ingredientIds) {
ingredient = await Ingredient.findById(ingredientId);
ingredientArr.push(ingredient);
}
res.json({
status: "success",
message: "Searched for ingredients by recipe's id successfully",
data: ingredientArr
});
});
};
exports.getTagsByRecipeId = function (req, res) {
Recipe.findById(req.params.recipe_id, async function (err, recipe) {
if (err)
res.send(err);
tagIds = recipe["tagIds"];
tagArr = [];
for(var tagId of tagIds) {
tag = await Tag.findById(tagId);
tagArr.push(tag);
}
res.json({
status: "success",
message: "Searched for ingredients by recipe's id successfully",
data: tagArr
});
});
};
exports.getCommentsByRecipeId = function (req, res) {
Comment.find({ recipeId: req.params.recipe_id }, function (err, comments) {
if (err)
res.send(err);
res.json({
status: "success",
message: "Searched for comments by recipe's id successfully",
data: comments
});
});
};
exports.getRecipes = async function (req, res) {
result = [];
recipes = await Recipe.find({});
if(req.body["tagsId"]) {
tagIds = req.body["tagIds"];
for(tagId of tagIds) {
for(recipe of recipes) {
if(recipe["tagIds"].includes(tagId)) {
result.push(recipe);
}
}
}
}
if(req.body["ingredientIds"]) {
ingredientIds = req.body["ingredientIds"];
for(ingredientId of ingredientIds) {
for(recipe of recipes) {
if(recipe["ingredientIds"].includes(ingredientId)) {
result.push(recipe);
}
}
}
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
unique = result.filter(onlyUnique);
res.json({
status: "success",
message: "Search for recipes by [ingredientIds] and [tagIds] successfully!",
data: unique
});
};
<file_sep>// Filename: api-routes.js
// Initialize express router
let router = require('express').Router();
// Set default API response
router.get('/', function (req, res) {
res.json({
status: 'API Is Working',
message: 'Welcome to Recettes crafted with love!'
});
});
// Import recipe controller
var recipeController = require('./recipeController');
// Recipe routes
router.route('/recipes')
.get(recipeController.index)
.post(recipeController.new);
router.route('/recipes/:recipe_id')
.get(recipeController.view)
.patch(recipeController.update)
.put(recipeController.update)
.delete(recipeController.delete);
// Import tag controller
var tagController = require('./tagController');
// Tag routes
router.route('/tags')
.get(tagController.index)
.post(tagController.new);
router.route('/tags/:tag_id')
.get(tagController.view)
.patch(tagController.update)
.put(tagController.update)
.delete(tagController.delete);
// Import ingredient controller
var ingredientController = require('./ingredientController');
// Ingredient routes
router.route('/ingredients')
.get(ingredientController.index)
.post(ingredientController.new);
router.route('/ingredients/:ingredient_id')
.get(ingredientController.view)
.patch(ingredientController.update)
.put(ingredientController.update)
.delete(ingredientController.delete);
// Import comment controller
var commentController = require('./commentController');
// Comment routes
router.route('/comments')
.get(commentController.index)
.post(commentController.new);
router.route('/comments/:comment_id')
.get(commentController.view)
.patch(commentController.update)
.put(commentController.update)
.delete(commentController.delete);
// Import user controller
var userController = require('./userController');
// User routes
router.route('/users')
.get(userController.index)
.post(userController.new);
router.route('/users/:user_id')
.get(userController.view)
.patch(userController.update)
.put(userController.update)
.delete(userController.delete);
// Import search controller
var searchController = require('./searchController');
// Search routes
router.route('/search/ingredients/:recipe_id')
.get(searchController.getIngredientsByRecipeId);
router.route('/search/comments/:recipe_id')
.get(searchController.getCommentsByRecipeId);
router.route('/search/tags/:recipe_id')
.get(searchController.getTagsByRecipeId);
router.route('/search/recipes')
.post(searchController.getRecipes);
// Export API routes
module.exports = router;<file_sep>// recipeController.js
// Import recipe model
Recipe = require('./recipeModel');
// Handle index actions
exports.index = function (req, res) {
Recipe.get(function (err, recipes) {
if (err) {
res.json({
status: "error",
message: err,
});
}
res.json({
status: "success",
message: "Recipes retrieved successfully",
data: recipes
});
});
};
// Handle create recipe actions
exports.new = function (req, res) {
var recipe = new Recipe(req.body);
// save the recipe and check for errors
recipe.save(function (err) {
// if (err)
// res.json(err);
res.json({
message: 'New recipe created!',
data: recipe
});
});
};
// Handle view recipe info
exports.view = function (req, res) {
Recipe.findById(req.params.recipe_id, function (err, recipe) {
if (err)
res.send(err);
res.json({
message: 'Recipe details loading..',
data: recipe
});
});
};
// Handle update recipe info
exports.update = function (req, res) {
Recipe.findById(req.params.recipe_id, function (err, recipe) {
if (err)
res.send(err);
// TODO: update data
// save the recipe and check for errors
recipe.save(function (err) {
if (err)
res.json(err);
res.json({
message: 'Recipe Info updated',
data: recipe
});
});
});
};
// Handle delete recipe
exports.delete = function (req, res) {
Recipe.remove({
_id: req.params.recipe_id
}, function (err, recipe) {
if (err)
res.send(err);res.json({
status: "success",
message: 'Recipe deleted'
});
});
}; | 00ab6c2bc98d7925c45e49c03e80a89650b0184c | [
"Markdown",
"JavaScript"
] | 9 | Markdown | 9812h/recettes-webservice | 82d1aaacfd9c290d1f9aca08af7d89d1f3c13697 | 1b26b08063344e88fb7679da5bdbb73a8c1a884f |
refs/heads/master | <file_sep>FROM alpine:latest
MAINTAINER <NAME> <<EMAIL>>
RUN echo "@edge http://dl-4.alpinelinux.org/alpine/edge/main" >> /etc/apk/repositories
RUN apk --update upgrade && apk add bash ansible@edge
RUN mkdir -p /etc/ansible
COPY run.sh /usr/bin/run.sh
RUN chmod +x /usr/bin/run.sh
# CMD ["bash"]
ENTRYPOINT ["/usr/bin/run.sh"]
<file_sep>#!/usr/bin/env sh
case ${CMD} in
adhoc)
ansible "$@"
;;
playbook)
ansible-playbook "$@"
;;
esac
<file_sep># Docker Ansible
Simple docker container to run ansible
## Simple setup
```bash
docker run -e "CMD=adhoc" --rm -it -v ${PWD}/config/:/etc/ansible ansible all -m shell -a "ip a"
```
Setup the env variable CMD to adhoc to use adhoc commands as seen here:
http://docs.ansible.com/ansible/intro_adhoc.html
In order to use ansible-playbook set the CMD variable to playbook
## Notes
N/A
| 6fb65f85de19e7b3f74a75573843635ff922bbc8 | [
"Markdown",
"Dockerfile",
"Shell"
] | 3 | Dockerfile | Ytseboy/docker-ansible | d8183623c9d5201e134b90100cbc50f99780d41f | 6c73f2cece0a3ddf9362b402ba8bcdf5a3db4288 |
refs/heads/master | <file_sep>class BitcoinController < ApplicationController
def show
@bitcoin = Bitcoin.find(params[:id])
end
end
<file_sep>require 'nokogiri'
require 'open-uri'
class StartScrap
def initialize
doc = Nokogiri::HTML(open("https://coinmarketcap.com/all/views/all/"))
tabname = []
tabvalue = []
doc.css('a.currency-name-container.link-secondary').each do |element| tabname << element.text end
doc.css('a.price').each do |element| tabvalue << element.text end
myhash = Hash[tabname.zip(tabvalue)]
return myhash
end
def save
initialize.each do |key, v|
bitcoin = Bitcoin.new
bitcoin.name = key.downcase
bitcoin.value = v
bitcoin.save
end
end
def perform
save
end
end<file_sep>class HomeController < ApplicationController
#lors du premier lancement decommenter la ligne 5 pour pouvoir scrapper ensuite remettre en commentaire.merci
def index
if Bitcoin.first == nil
StartScrap.new.perform
end
@bitcoins = Bitcoin.all
puts params
end
def create
@bitcoin = Bitcoin.new
if Bitcoin.find_by(name: params[:recherche])
redirect_to bitcoin_path(Bitcoin.find_by(name: params[:recherche]).id)
else
redirect_to(root_path)
return
end
end
end
<file_sep># README
*links to my app heroku
https://serene-beach-79922.herokuapp.com/
| 4a48c97f084581ceb5e24757a70f046f5e90c370 | [
"Markdown",
"Ruby"
] | 4 | Ruby | abouadamwawawa/cryptoscrapp | 721b47e9b9be3532004f90ef9c9b29a9747d7d0d | 463394459f1533907c5be474882f64d3bbfecadb |
refs/heads/main | <file_sep>import _ from 'lodash'
import { Middleware, RouterParamContext } from '@koa/router'
export default (field: string, values: string[] | ((ctx: RouterParamContext) => string[])): Middleware => {
return async (ctx, next) => {
const name = ctx.params[field]
let supportedValues: string[]
if (typeof values === 'function') {
supportedValues = values(ctx)
} else {
supportedValues = values
}
if (_.isEmpty(supportedValues) || !_.includes(supportedValues, name)) {
return ctx.throw(404, `unsupported ${field}: ${name}`)
}
// go next
await next()
} // end Middleware
}
<file_sep>import _ from 'lodash'
import type { IConfig } from 'config'
import { NFTStorage } from 'nft.storage'
import { BaseService } from '@jadepool/types'
import type { JadePool } from '@jadepool/instance'
import Logger from '@jadepool/logger'
const logger = Logger.of('Service', 'Nft Storage')
class Service extends BaseService {
// constructor
constructor (services: any) {
super('nft.storage', services)
this._jadepool = services.jadepool as JadePool
}
/// Private members
/** jadepool instance */
private readonly _jadepool: JadePool
/** nft.storage instance */
private _storage?: NFTStorage
/// Accessors
get config (): IConfig { return this._jadepool.config as IConfig }
get storage (): NFTStorage {
if (this._storage === undefined) {
throw new Error('storage isn‘t initialized.')
}
return this._storage
}
/// Methods
/**
* 初始化
* @param opts
*/
async initialize (_opts: object): Promise<void> {
const endpoint: string = this.config.get('nftStorage.endpoint')
if (_.isEmpty(endpoint)) throw new Error('missing nft.storage endpoint config.')
const token: string = this.config.get('nftStorage.accessToken')
if (_.isEmpty(token) || token.length < 200) throw new Error('missing nft.storage token config.')
// create nft instance
this._storage = new NFTStorage({ token, endpoint })
logger.tag('Initialized').log(`endpoint=${endpoint}`)
}
/**
* 该Service的优雅退出函数
* @param signal 退出信号
*/
async onDestroy (_signal: number): Promise<void> {
// reset to undefined
this._storage = undefined
}
}
export = Service
<file_sep>import type { ArgsBuildTxMint, ResultTrxBuilt } from '@mintcraft/types'
import buildContractContext from './invoke-utils/build-contract-context'
/**
* method implement
* @param namespace
* @param args
*/
export = async (namespace: string, args: ArgsBuildTxMint): Promise<ResultTrxBuilt> => {
// build contract context
const { substrateSrv, api, contract } = await buildContractContext(namespace, args)
// contract parameters
const initialSupply = args.initialSupply ?? 1
const metadataUri = args.metadata
// We will use these values for the execution
const value = 0
const { gasConsumed, result } = await contract.query.create(args.creator, { value, gasLimit: -1 }, initialSupply, metadataUri)
// contract should implement create message
if (!result.isOk) {
throw new Error(`missing "create" message for contract ${args.contract}`)
}
// transaction body
const extrinsic = contract.tx.create({ value, gasLimit: gasConsumed }, initialSupply, metadataUri)
// return built rawtx
return await substrateSrv.buildUnsignedExtrinsic(api, args.creator, extrinsic)
}
<file_sep>import _ from 'lodash'
import Router from '@koa/router'
import { METHOD_NAMESPACE, PLATFORMS, PLATFORM_CHAINIDS } from '@mintcraft/types'
import supportedParams from '../../middlewares/supported-params'
import { buildHandler } from '../factory'
const platformRouter = new Router()
// send raw transcation data
.post('/send-trx', buildHandler('platform-send-transaction', METHOD_NAMESPACE.BLOCKCHAIN, {
// weither rawHex string or signed array
rawHex: { type: 'string', required: false },
signed: {
type: 'array',
required: false,
itemType: 'object',
rule: {
unsignedRawHex: { type: 'string', required: true },
signingPayload: { type: 'string', required: false },
signature: { type: 'string', required: true },
recoveryId: { type: 'number', required: false } // optional, ecdsa recovery id
}
}
}))
// platform call for more information (not to send transaction)
.post('/call', buildHandler('platform-general-call', METHOD_NAMESPACE.BLOCKCHAIN, {
method: { type: 'string', required: true },
params: { type: 'array', required: false, min: 0 }
}))
// get transaction basic infomation
.get('/tx/:txid', buildHandler('platform-query-transaction', METHOD_NAMESPACE.BLOCKCHAIN, {
'ref-block-number': { type: 'int', convertType: 'int', required: false, min: 1 },
'ref-block-hash': { type: 'string', required: false, empty: false }
}))
// platform summary info
.get('/', buildHandler('platform-query-info', METHOD_NAMESPACE.BLOCKCHAIN))
// export routers
const router = new Router()
.use('/:platform/:chainId',
supportedParams('platform', _.values(PLATFORMS)),
supportedParams('chainId', (ctx) => PLATFORM_CHAINIDS[ctx.params.platform]),
platformRouter.routes()
)
.get('/', buildHandler('list-all-platforms', METHOD_NAMESPACE.NULL))
export = router
<file_sep>import _ from 'lodash'
import axios from 'axios'
import {
ArgsEntityGetMetadata
} from '@mintcraft/types'
import jadepool from '@jadepool/instance'
import { toGatewayURL } from 'nft.storage'
import NFTStorageServ from '../services/nft.storage.service'
/**
* method implement
* @param namespace
* @param args
*/
export = async (namespace: string, args: ArgsEntityGetMetadata): Promise<any> => {
if (_.isEmpty(args.reference)) throw new Error('missing reference.')
// storage instance
const nftServ = jadepool.getService('nft.storage') as NFTStorageServ
const cid = args.reference
// Throws if the NFT was not found
const result = await nftServ.storage.check(cid)
if (result.cid !== cid) {
throw new Error(`Checked cid is ${result.cid} instead of ${cid}`)
}
// FIXME: add options to use custom gateway
const httpUrl = toGatewayURL(`ipfs://${cid}/metadata.json`)
// request metadata
const res = await axios.get(httpUrl.href, { responseType: 'json' })
if (res.status >= 200 && res.status < 300) {
const ret = res.data
// convert to gateway url
if (args.asGatewayUrl === true) {
if (typeof ret?.image === 'string') ret.image = toGatewayURL(ret.image)
const contentUrl = ret?.properties?.mintcraft?.content
if (typeof contentUrl === 'string') {
ret.properties.mintcraft.content = toGatewayURL(contentUrl)
}
}
return ret
}
throw new Error(`status - ${res.status}: ${res.statusText}`)
}
<file_sep>// const fs = require('fs')
// const path = require('path')
module.exports = {
logLevel: 'INFO',
endpoints: {
canvas: [
{
name: 'local',
url: 'ws://127.0.0.1:9944'
},
{
name: 'parity',
url: 'wss://canvas-rpc.parity.io'
}
]
},
contracts: [
// {
// name: '<name>',
// category: 'nft|token'
// symbol?: '<token symbol>',
// address: '<address>',
// abi: JSON.parse(fs.readFileSync(path.resolve(__dirname, './abis/metadata.json')))
// }
]
}
<file_sep>import type { ArgsQueryTrx, ResultQueryTrx } from '@mintcraft/types'
import buildContext from './invoke-utils/build-context'
/**
* method implement
* @param namespace
* @param args
*/
export = async (namespace: string, args: ArgsQueryTrx): Promise<ResultQueryTrx> => {
if (args.txid === undefined) throw new Error('missing required txid.')
if (args['ref-block-hash'] === undefined && args['ref-block-number'] === undefined) {
throw new Error('ref-block is required for query tx info')
}
// build contract context
const { substrateSrv, api } = await buildContext(namespace, args)
let blockHash: string
if (args['ref-block-number'] !== undefined) {
const hash = await substrateSrv.getBlockHash(api, args['ref-block-number'])
blockHash = hash.toHex()
} else if (args['ref-block-hash'] !== undefined) {
blockHash = args['ref-block-hash']
} else {
throw new Error('missing required block reference.')
}
// block info
const signedBlock = await substrateSrv.getBlock(api, blockHash)
if (signedBlock === undefined) {
throw new Error(`failed to find block[${blockHash}]`)
}
// find transaction
let foundTrxIdx: number = -1
const extrinsics = signedBlock.block.extrinsics
const foundTrx = extrinsics.find((extrinsic, idx) => {
if (extrinsic.hash.toString().toLowerCase() === args.txid.toLowerCase()) {
foundTrxIdx = idx
return true
} else {
return false
}
})
if (foundTrx === undefined) {
throw new Error(`failed to find transaction(${args.txid}) in block[${blockHash}]`)
}
// find events
const events = await substrateSrv.getBlockEvents(api, blockHash)
const trxEvents = events.filter(record => record.phase.asApplyExtrinsic.toNumber() === foundTrxIdx)
return {
txid: args.txid,
blockHash,
blockNumber: signedBlock.block.header.number.unwrap().toNumber(),
content: foundTrx.toHuman(),
receipt: {
events: trxEvents.map(one => one.toHuman())
}
}
}
<file_sep>import _ from 'lodash'
import type { ArgsWithContract } from '@mintcraft/types'
import { ContractPromise } from '@polkadot/api-contract'
import buildContext from './build-context'
export = async (namespace: string, args: ArgsWithContract) => {
if (_.isEmpty(args.contract)) throw new Error('invalid args: missing contract.')
const { substrateSrv, api } = await buildContext(namespace, args)
// get contract defination
const define = substrateSrv.ensureContractSupported(args.contract)
// get contract instance
const contract = new ContractPromise(api, define.abi, define.address)
// return all instances
return { substrateSrv, api, contract }
}
<file_sep>import { ParsedArgs } from './methods-shared'
// ------- consts -------
//
// ------- interface -------
//
export interface ArgsWithPlatform {
/** platform argument */
platform: string
/** platform chain id argument */
chainId: string
}
export interface ArgsWithContract extends ArgsWithPlatform {
/** contract address or name argument */
contract: string
}
export interface UnsignedData {
unsignedRawHex: string
signingPayload?: string
signatureOptions?: object
}
export interface SignedData {
unsignedRawHex: string
signingPayload?: string
signature: string
recoveryId?: number
}
export interface ResultTrxBuilt {
sender: string
transactions: UnsignedData[]
}
export interface ArgsBuildTxMint extends ParsedArgs, ArgsWithContract {
/** nft creator who own the nft at first */
creator: string
/** nft metadata url (now only support ipfs or swarm) */
metadata: string
/** nft initial supply (erc721 should be always 1) */
initialSupply?: number
}
export interface ArgsSendTrx extends ParsedArgs, ArgsWithPlatform {
rawHex?: string
signed?: SignedData[]
}
/**
* basic transaction data
*/
interface TrxBasics {
txid: string
blockHash?: string
blockNumber?: number
}
export interface ResultTrxSent extends TrxBasics { }
export interface ArgsQueryTrx extends ParsedArgs, ArgsWithPlatform {
txid: string
'ref-block-hash'?: string
'ref-block-number'?: number
}
export interface ResultQueryTrx extends TrxBasics {
content: any
receipt?: any
}
<file_sep>import _ from 'lodash'
import jadepool from '@jadepool/instance'
import type { ArgsWithPlatform } from '@mintcraft/types'
import SubstrateSrv from '../../services/substrate.service'
export = async (namespace: string, args: ArgsWithPlatform) => {
if (_.isEmpty(args.chainId)) throw new Error('invalid args: missing chain id.')
// get substrate instance
const substrateSrv = jadepool.getService('substrate') as SubstrateSrv
// get api promise
const api = await substrateSrv.getApiPromise(args.chainId)
// return all instances
return { substrateSrv, api }
}
<file_sep>import _ from 'lodash'
import type { IConfig } from 'config'
import { hexToU8a } from '@polkadot/util'
import { blake2AsHex } from '@polkadot/util-crypto'
import { ApiPromise, WsProvider } from '@polkadot/api'
import type { Signer, SignerResult } from '@polkadot/api/types'
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types'
import type { Vec } from '@polkadot/types'
import type { BlockHash, EventRecord, Header, SignedBlock } from '@polkadot/types/interfaces'
import type { AnyJson, SignerPayloadRaw, SignatureOptions, IExtrinsic } from '@polkadot/types/types'
import Logger from '@jadepool/logger'
import { BaseService } from '@jadepool/types'
import type { JadePool } from '@jadepool/instance'
import { PLATFORMS, PLATFORM_CHAINIDS, ResultTrxBuilt, ResultTrxSent, SignedData } from '@mintcraft/types'
const logger = Logger.of('Service', 'Substrate')
// local define
interface EndpointDefine {
name: string
url: string
}
interface ContractDefine {
name: string
category: 'nft' | 'token'
symbol?: string
address: string
abi: AnyJson
}
class Service extends BaseService {
// constructor
constructor (services: any) {
super('substrate', services)
this._jadepool = services.jadepool as JadePool
this._apis = new Map()
}
/// Private members
/** jadepool instance */
private readonly _jadepool: JadePool
/** api instance dictionary */
private readonly _apis: Map<string, ApiPromise|Promise<ApiPromise>>
/// Accessors
static get supportedChainIds (): string[] { return PLATFORM_CHAINIDS[PLATFORMS.SUBSTRATE_INK] }
get config (): IConfig { return this._jadepool.config as IConfig }
/// Life circles
/**
* 初始化
* @param opts
*/
async initialize (_opts: object): Promise<void> {
const endpoints = this.config.get('endpoints')
logger.tag('Initialized').log(`endpoints=${JSON.stringify(endpoints)}`)
}
/**
* 该Service的优雅退出函数
* @param signal 退出信号
*/
async onDestroy (_signal: number): Promise<void> {
// reset to undefined
// this._storage = undefined
}
/// Methods
/**
* get endpoints for specific chain
* @param chainId
*/
getEndpoints (chainId: string): EndpointDefine[] {
const endpoints = this.config.get(`endpoints.${chainId}`)
if (!_.isArray(endpoints) || endpoints.length === 0) throw new Error(`missing endpoints for ${chainId}`)
return endpoints
}
/**
* get supported contracts
* @param category contract type
*/
getSupportedContracts (category: 'nft' | 'token'): ContractDefine[] {
const contracts = this.config.get<ContractDefine[]>('contracts')
return contracts.filter(one => one.category === category)
}
/**
* ensure the contract and return it
*/
ensureContractSupported (contractOrNameOrSymbol: string): ContractDefine {
const inputName = _.trim(contractOrNameOrSymbol).toLowerCase()
const contracts = this.config.get<ContractDefine[]>('contracts')
const found = contracts.find(one => {
return one.name.toLowerCase() === inputName ||
one.address.toLowerCase() === inputName ||
(one.symbol !== undefined ? one.symbol.toLowerCase() === inputName : false)
})
if (found === undefined) {
throw new Error(`${contractOrNameOrSymbol} didn't find.`)
}
return found
}
/**
* get substrate api promise
* @param chainId
*/
async getApiPromise (chainId: string): Promise<ApiPromise> {
if (!_.includes(Service.supportedChainIds, chainId)) {
throw new Error('unsupported chain id.')
}
const api = this._apis.get(chainId)
if (api !== undefined) {
if (api instanceof Promise) {
return await api
} else {
return api
}
} else {
const endpoints = this.getEndpoints(chainId)
// FIXME pick accessable endpoin
const endpoint = endpoints[0]
const promise = ApiPromise.create({
provider: new WsProvider(endpoint.url)
}).then(createdApi => {
// 打印连接成功
createdApi.on('connected', () => {
logger.tag('Connected').log(`name=${endpoint.name},url=${endpoint.url}`)
})
// 断线则重设api
createdApi.on('disconnected', () => {
logger.tag('Disconnected').log(`name=${endpoint.name},url=${endpoint.url}`)
this._apis.delete(chainId)
})
this._apis.set(chainId, createdApi)
return createdApi
})
this._apis.set(chainId, promise)
return await promise
}
}
/**
* wrap timeout for promise
* @param promise
*/
private async _wrapPromiseRequest<T> (promise: Promise<T>): Promise<T> {
const timeout = 5000 // 5 seconds
return await new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('request timeout.'))
}, timeout)
promise.then(resolve).catch(reject).finally(() => {
clearTimeout(timeoutId)
})
})
}
/**
* get nonce
*/
async getAccountNextNonce (api: ApiPromise, address: string): Promise<number> {
const nonce = await this._wrapPromiseRequest(api.rpc.system.accountNextIndex(address))
return nonce.toNumber()
}
/**
* get block hash by block number
*/
async getBlockHash (api: ApiPromise, num: number): Promise<BlockHash> {
return await this._wrapPromiseRequest(api.rpc.chain.getBlockHash(num))
}
/**
* get block
*/
async getBlock (api: ApiPromise, hash?: number | string): Promise<SignedBlock> {
let signedBlock: SignedBlock
if (hash === undefined) {
signedBlock = await this._wrapPromiseRequest(api.rpc.chain.getBlock())
} else if (typeof hash === 'number') {
const hashStr = await this._wrapPromiseRequest(api.rpc.chain.getBlockHash(hash))
signedBlock = await this._wrapPromiseRequest(api.rpc.chain.getBlock(hashStr))
} else {
signedBlock = await this._wrapPromiseRequest(api.rpc.chain.getBlock(hash))
}
return signedBlock
}
/**
* block header
*/
async getBlockHeader (api: ApiPromise, hash?: number | string): Promise<Header> {
const signedBlock = await this.getBlock(api, hash)
return signedBlock.block.header
}
/**
* block events
*/
async getBlockEvents (api: ApiPromise, hash: string | BlockHash): Promise<Vec<EventRecord>> {
return await this._wrapPromiseRequest(api.query.system.events.at(hash))
}
/**
* build the extrinsic
*/
async buildUnsignedExtrinsic (api: ApiPromise, sender: string, extrinsic: SubmittableExtrinsic<'promise'>, mortalBlocks: number = 64): Promise<ResultTrxBuilt> {
const senderAddressNonce = await this.getAccountNextNonce(api, sender)
const header = await this.getBlockHeader(api)
// add signing data
const options: SignatureOptions = {
blockHash: header.hash,
era: api.registry.createType('ExtrinsicEra', {
current: header.number,
period: mortalBlocks // default mortal blocks is 64
}),
nonce: senderAddressNonce,
genesisHash: api.genesisHash,
runtimeVersion: api.runtimeVersion,
signedExtensions: api.registry.signedExtensions
}
// unsigned rawhex with faked sig
const unsignedRawHex = extrinsic.signFake(sender, options).toHex()
// hacking the payload
options.signer = new RawSigner()
const signedFaked = await extrinsic.signAsync(sender, options)
const signingPayload = signedFaked.signature.toHex()
return {
sender,
transactions: [
{ unsignedRawHex, signingPayload }
]
}
}
/**
* decode extrinsic with signature
* @param api
* @param unsignedRawHex should be the result of buildUnsignedExtrinsic method, which is the hex string with a fake signature
* @param signature signature hex
*/
decodeExtrinsic (api: ApiPromise, unsignedRawHex: string, signingData?: Partial<SignedData>): IExtrinsic {
if (!unsignedRawHex.startsWith('0x')) unsignedRawHex = '0x' + unsignedRawHex
const decodedExtrinsic = api.registry.createType('Extrinsic', hexToU8a(unsignedRawHex), { isSigned: true, version: api.extrinsicVersion })
// sender should be signer
const sender = decodedExtrinsic.signer
if (_.isEmpty(sender)) throw new Error('missing signer after parsing unsignedRawHex.')
// now replace the right signature into the extrinsic
if (signingData !== undefined) {
if (signingData.signature === undefined) throw new Error('missing signature.')
if (signingData.signingPayload === undefined) throw new Error('missing signing payload.')
// FIXME: we should ensure signature is signed by sender
// FIXME: we should ensure signingPayload is the payload for unsignedRawHex or create payload by unsignedRawHex
const payload = api.registry.createType('ExtrinsicPayload', hexToU8a(signingData.signingPayload), { version: api.extrinsicVersion })
decodedExtrinsic.addSignature(sender, signingData.signature, payload.toU8a())
}
return decodedExtrinsic
}
/**
* sumbit transaction to blockchain
*/
async sumbitTransaction (api: ApiPromise, extrinsic: IExtrinsic | string): Promise<ResultTrxSent> {
let decodedExtrinsic: IExtrinsic
if (typeof extrinsic === 'string') {
decodedExtrinsic = this.decodeExtrinsic(api, extrinsic)
} else {
decodedExtrinsic = extrinsic
}
return await this._wrapPromiseRequest(new Promise((resolve, reject) => {
api.rpc.author.submitAndWatchExtrinsic(decodedExtrinsic, async (status) => {
if (status.isInvalid) { return reject(new Error('invalid extrinsic')) }
if (status.isDropped) { return reject(new Error('dropped extrinsic')) }
if (!status.isFinalized && !status.isInBlock) return
// get block hash
const blockHash = status.isInBlock ? status.asInBlock : status.asFinalized
// get block number
const header = await api.rpc.chain.getHeader(blockHash)
// final return
resolve({
txid: decodedExtrinsic.hash.toHex(),
blockHash: blockHash.toHex(),
blockNumber: header.number.unwrap().toNumber()
})
}).catch(reject)
}))
}
}
/**
* Fake signer to expose payload hex
*/
class RawSigner implements Signer {
public async signRaw ({ data }: SignerPayloadRaw): Promise<SignerResult> {
return await new Promise((resolve, reject): void => {
const hashed = (data.length > (256 + 1) * 2)
? blake2AsHex(data)
: data
resolve({ id: 1, signature: hashed })
})
}
}
export = Service
<file_sep>import { pick } from 'lodash'
import jadepool from '@jadepool/instance'
import { ParsedArgs } from '@mintcraft/types'
import SubstrateSrv from '../services/substrate.service'
/**
* method implement
* @param namespace
* @param args
*/
export = async (namespace: string, args: ParsedArgs): Promise<any> => {
const substrateSrv = jadepool.getService('substrate') as SubstrateSrv
const contracts = substrateSrv.getSupportedContracts('token')
return contracts.map(one => pick(one, ['name', 'address', 'category', 'symbol']))
}
<file_sep>// import _ from 'lodash'
import type { ArgsSendTrx, ResultTrxSent } from '@mintcraft/types'
import buildContext from './invoke-utils/build-context'
/**
* method implement
* @param namespace
* @param args
*/
export = async (namespace: string, args: ArgsSendTrx): Promise<ResultTrxSent> => {
if (args.rawHex === undefined && args.signed === undefined) {
throw new Error('weither rawHex or signed array is required.')
}
// build contract context
const { substrateSrv, api } = await buildContext(namespace, args)
// directly send raw hex
let result: ResultTrxSent
if (args.rawHex !== undefined) {
result = await substrateSrv.sumbitTransaction(api, args.rawHex)
} else if (args.signed !== undefined && args.signed.length > 0) {
const data = args.signed[0]
if (data.unsignedRawHex === undefined) throw new Error('missing unsignedRawHex')
if (data.signature === undefined) throw new Error('missing signature')
const extrinsic = substrateSrv.decodeExtrinsic(api, data.unsignedRawHex, data)
result = await substrateSrv.sumbitTransaction(api, extrinsic)
} else {
throw new Error('invalid arguments.')
}
return result
}
<file_sep>
// ------- consts -------
//
export const SUPPORTED_MIME_TYPES = {
TEXT: 'text/plain',
JSON: 'application/json',
BINARY: 'application/octet-stream',
PDF: 'application/pdf',
IMAGE: 'image/*',
IMAGE_PNG: 'image/png',
IMAGE_GIF: 'image/gif',
IMAGE_JPEG: 'image/jpeg',
IMAGE_BMP: 'image/bmp',
IMAGE_ICON: 'image/x-icon',
AUDIO_MPEG: 'audio/mpeg',
AUDIO_WEBM: 'audio/webm',
AUDIO_OGG: 'audio/ogg',
AUDIO_WAV: 'audio/wav',
VIDEO_WEBM: 'video/webm',
VIDEO_OGG: 'video/ogg',
VIDEO_MP4: 'video/mp4'
}
| 1d8a9588fdb53e22bad4fe249ed9cae57117e637 | [
"JavaScript",
"TypeScript"
] | 14 | TypeScript | QueendomDAO/mintcraft-nft-gateway | d686e82af0801356a27514cc4df11e06de517441 | 66e96d0b00e3b085c7ca6428f27781a5e3ebc6a0 |
refs/heads/master | <file_sep><?php
/**
* Podcast Embedder plugin for Craft CMS 3.x
*
* Podcast fieldtype
*
* @link https://kurious.agency
* @copyright Copyright (c) 2019 Kurious Agency
*/
namespace kuriousagency\podcastembedder\variables;
use kuriousagency\podcastembedder\PodcastEmbedder;
use Craft;
use craft\helpers\Template;
/**
* @author Kurious Agency
* @package PodcastEmbedder
* @since 0.0.1
*/
class PodcastEmbedderVariable
{
// Public Methods
// =========================================================================
public function embed($url, $params = [])
{
return Template::raw(PodcastEmbedder::$plugin->service->embed($url, $params));
}
public function getEmbedUrl($url, $params = [])
{
return Template::raw(PodcastEmbedder::$plugin->service->getEmbedUrl($url, $params));
}
public function getThumbnail($url) {
return Template::raw(PodcastEmbedder::$plugin->service->getThumbnail($url));
}
public function getTitle($url) {
return Template::raw(PodcastEmbedder::$plugin->service->getInfo($url)->title);
}
public function getDescription($url) {
return Template::raw(PodcastEmbedder::$plugin->service->getInfo($url)->description);
}
public function getType($url) {
return Template::raw(PodcastEmbedder::$plugin->service->getInfo($url)->type);
}
public function getAspectRatio($url) {
return Template::raw(PodcastEmbedder::$plugin->service->getInfo($url)->aspectRatio);
}
public function getProviderName($url) {
return Template::raw(PodcastEmbedder::$plugin->service->getInfo($url)->providerName);
}
public function getPodcastId($url) {
return Template::raw(PodcastEmbedder::$plugin->service->getPodcastId($url));
}
}
<file_sep><?php
/**
* Podcast Embedder plugin for Craft CMS 3.x
*
* Podcast fieldtype
*
* @link https://kurious.agency
* @copyright Copyright (c) 2019 Kurious Agency
*/
namespace kuriousagency\podcastembedder\fields;
use kuriousagency\podcastembedder\PodcastEmbedder;
use kuriousagency\podcastembedder\assetbundles\podcastfield\PodcastFieldAsset;
use Craft;
use craft\base\ElementInterface;
use craft\base\Field;
use craft\helpers\Db;
use yii\db\Schema;
use craft\helpers\Json;
use craft\base\PreviewableFieldInterface;
use craft\helpers\UrlHelper;
/**
* @author Kurious Agency
* @package PodcastEmbedder
* @since 0.0.1
*/
class Podcast extends Field implements PreviewableFieldInterface
{
// Public Properties
// =========================================================================
// Static Methods
// =========================================================================
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('podcast-embedder', 'Podcast');
}
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public function rules()
{
$rules = parent::rules();
$rules = array_merge($rules, []);
return $rules;
}
/**
* @inheritdoc
*/
public function getContentColumnType(): string
{
return Schema::TYPE_TEXT;
}
/**
* @inheritdoc
*/
public function normalizeValue($value, ElementInterface $element = null)
{
return $value;
}
/**
* @inheritdoc
*/
public function serializeValue($value, ElementInterface $element = null)
{
return parent::serializeValue($value, $element);
}
/**
* @inheritdoc
*/
public function getSettingsHtml()
{
// Render the settings template
return Craft::$app->getView()->renderTemplate(
'podcast-embedder/_components/fields/settings',
[
'field' => $this,
]
);
}
/**
* @inheritdoc
*/
public function getInputHtml($value, ElementInterface $element = null): string
{
// Register our asset bundle
Craft::$app->getView()->registerAssetBundle(PodcastFieldAsset::class);
// Get our id and namespace
$id = Craft::$app->getView()->formatInputId($this->handle);
$namespacedId = Craft::$app->getView()->namespaceInputId($id);
$pluginSettings = PodcastEmbedder::getInstance()->getSettings();
$fieldSettings = $this->getSettings();
// Variables to pass down to our field JavaScript to let it namespace properly
$jsonVars = [
'id' => $id,
'name' => $this->handle,
'namespace' => $namespacedId,
'prefix' => Craft::$app->getView()->namespaceInputId(''),
'fieldSettings' => $fieldSettings,
'pluginSettings' => $pluginSettings,
'endpointUrl' => UrlHelper::actionUrl('podcast-embedder/podcast/parse'),
];
$jsonVars = Json::encode($jsonVars);
Craft::$app->getView()->registerJs("$('#{$namespacedId}-field').PodcastEmbedder(" . $jsonVars . ");");
// Render the input template
return Craft::$app->getView()->renderTemplate(
'podcast-embedder/_components/fields/input',
[
'name' => $this->handle,
'value' => $value,
'field' => $this,
'id' => $id,
'namespacedId' => $namespacedId,
'fieldSettings' => $fieldSettings,
'pluginSettings' => $pluginSettings,
]
);
}
}
<file_sep># Podcast Embedder plugin for Craft CMS 3.x
Creates a podcast fieldtype for the embed of Podbean or Libsyn podcast media players. A podcast can be embeded using a podcast's share url.
## Requirements
This plugin requires Craft CMS 3.0.0-beta.23 or later.
## Installation
To install the plugin, follow these instructions.
1. Open your terminal and go to your Craft project:
cd /path/to/project
2. Then tell Composer to load the plugin:
composer require kuriousagency/podcast-embedder
3. In the Control Panel, go to Settings → Plugins and click the “Install” button for Podcast Embedder.
## Podcast Embedder Overview
Podcasts hosted on either the podbean or libsyn services can be embedded in templates using the podcast embedder fieldtype.
## Configuring Podcast Embedder
Create a new field in Settings → Fields → New Field and select Podcast from the fieldtype dropdown.
## Using Podcast Embedder
To add a podcast to templates add the following twig code:
```
{{ craft.podcastEmbedder.embed(podcast) }}
```
### Available Twig Functions ###
+ craft.podcastEmbedder.embed()
+ craft.podcastEmbedder.getEmbedUrl()
+ craft.podcastEmbedder.getThumbnail()
+ craft.podcastEmbedder.getTitle()
+ craft.podcastEmbedder.getDescription()
+ craft.podcastEmbedder.getType()
+ craft.podcastEmbedder.getPodcastId()
## Podcast Embedder Roadmap
* Add more providers
Brought to you by [Kurious Agency](https://kurious.agency)
<file_sep><?php
/**
* Podcast Embedder plugin for Craft CMS 3.x
*
* Podcast fieldtype
*
* @link https://kurious.agency
* @copyright Copyright (c) 2019 Kurious Agency
*/
namespace kuriousagency\podcastembedder\services;
use kuriousagency\podcastembedder\PodcastEmbedder;
use Craft;
use craft\base\Component;
use DOMDocument;
use Embed\Embed;
/**
* @author Kurious Agency
* @package PodcastEmbedder
* @since 0.0.1
*/
class PodcastEmbedderService extends Component
{
// Public Methods
// =========================================================================
public function getInfo($url, $params=[])
{
$info = Embed::create($url, [
'choose_bigger_image' => true,
'parameters' => [],
]);
$this->{strtolower($info->providerName).'Format'}($info, $params);
return $info;
}
public function podbeanFormat(&$info, $params=[])
{
$url = $info->url;
preg_match('%(?:podbean.com\/media\/share\/pb-)(.+)%i', $url, $match);
if (!count($match)) {
return;
}
$info->id = $match[1];
$url = "https://www.podbean.com/media/player/$info->id-pb";
$query = [
'skin' => 1
];
if (isset($params['query']) && is_array($params['query'])) {
$query = array_merge($query, $params['query']);
}
$url .= '?'.http_build_query($query);
unset($params['query']);
$params = array_merge([
'frameborder' => 0,
'allowTransparency' => 1,
'width' => '100%',
], $params);
$paramString = '';
foreach ($params as $key => $param)
{
$paramString .= $key."='$param' ";
}
$iframe = "<iframe src='$url' $paramString></iframe>";
$info->embedUrl = $url;
$info->code = $iframe;
}
public function libsynFormat(&$info, $params=[])
{
//https://oembed.libsyn.com/embed?item_id=4737975
$url = $info->url;
preg_match('%(?:libsyn\.com\/embed\?item_id=)(.+)%i', $url, $match);
if (!count($match)) {
return;
}
$info->id = $match[1];
$url = "//html5-player.libsyn.com/embed/episode/id/$info->id/";
$query = [
'height' => 90,
'theme' => 'custom',
'thumbnail' => 'yes',
'direction' => 'backwards',
'render-playlist' => 'no',
];
if (isset($params['query']) && is_array($params['query'])) {
$query = array_merge($query, $params['query']);
}
$url .= http_build_query($query);
$url = str_replace('&', '/', $url);
$url = str_replace('=', '/', $url);
unset($params['query']);
//html5-player.libsyn.com/embed/episode/id/4737975/height/90/theme/custom/thumbnail/yes/direction/backward/render-playlist/no/custom-color/87A93A/
$params = array_merge([
'frameborder' => 0,
'allowTransparency' => 1,
'width' => '100%',
], $params);
$paramString = '';
foreach ($params as $key => $param)
{
$paramString .= $key."='$param' ";
}
$iframe = "<iframe src='$url' $paramString></iframe>";
$info->embedUrl = $url;
$info->code = $iframe;
}
public function embed($url, $params=[]) : string
{
$info = $this->getInfo($url);
return $info->code;
}
public function getEmbedUrl($url, $params=[])
{
$info = $this->getInfo($url);
return $info->embedUrl;
}
public function getPodcastId($url)
{
$info = $this->getInfo($url);
return $info->id;
}
public function getThumbnail($url)
{
$info = $this->getInfo($url);
return $info->image;
}
}
<file_sep><?php
/**
* Podcast Embedder plugin for Craft CMS 3.x
*
* Podcast fieldtype
*
* @link https://kurious.agency
* @copyright Copyright (c) 2019 Kurious Agency
*/
namespace kuriousagency\podcastembedder\controllers;
use kuriousagency\podcastembedder\PodcastEmbedder;
use Craft;
use craft\web\Controller;
/**
* @author Kurious Agency
* @package PodcastEmbedder
* @since 0.0.1
*/
class PodcastController extends Controller
{
// Protected Properties
// =========================================================================
/**
* @var bool|array Allows anonymous access to this controller's actions.
* The actions must be in 'kebab-case'
* @access protected
*/
protected $allowAnonymous = [];
// Public Methods
// =========================================================================
public function actionParse(): string
{
$url = Craft::$app->request->get('url');
return Craft::$app->getView()->renderTemplate(
'podcast-embedder/_components/fields/inputEmbed.twig',
[
'name' => Craft::$app->request->get('name'),
'value' => $url,
]
);
}
}
<file_sep>/**
* Podcast Embedder plugin for Craft CMS
*
* Podcast Field JS
*
* @author Kurious Agency
* @copyright Copyright (c) 2019 Kurious Agency
* @link https://kurious.agency
* @package PodcastEmbedder
* @since 0.0.1PodcastEmbedderPodcast
*/
(function($, window, document, undefined) {
var pluginName = 'PodcastEmbedder',
defaults = {};
// Plugin constructor
function Plugin(element, options) {
this.element = element;
this.$element = $(element);
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function(id) {
var _this = this;
this.id = id;
this.$url = this.$element.find('.podcast-embedder-url');
this.$preview = this.$element.find('.podcast-embedder-previewContainer');
this.$url.on('change', $.proxy(this.fetchPreview, this));
this.$url.on('keydown', $.proxy(this.handleKeydown, this));
this.$spinner = $('<div class="spinner hidden"/>').insertAfter(this.$url.parent());
$(function() {
/* -- _this.options gives us access to the $jsonVars that our FieldType passed down to us */
});
},
fetchPreview: function(event) {
var self = this;
var jxhr;
event.preventDefault();
this.$preview.addClass('is-loading');
//this.$embedDataInput.val(null);
this.$spinner.removeClass('hidden');
jxhr = $.get(this.options.endpointUrl, {
url: this.$url.val(),
name: this.options.name
});
jxhr.done(function(data, textStatus, jqXHR) {
//console.log(data);
self.$preview.html(data);
});
jxhr.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
jxhr.always(function() {
Craft.initUiElements(self.$preview);
self.$preview.removeClass('is-loading');
self.$spinner.addClass('hidden');
});
},
handleKeydown: function(event) {
if (event.keyCode === 13) {
event.preventDefault();
this.fetchPreview(event);
}
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
<file_sep># Podcast Embedder Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/).
## 0.0.3 - 2019-05-15
### Added
- Libsyn support
## 0.0.1 - 2019-05-13
### Added
- Initial release
| 14e45e77ec904540a0329bda43ea1a83b8a189b5 | [
"Markdown",
"JavaScript",
"PHP"
] | 7 | PHP | KuriousAgency/podcast-embedder | 9e9372f649dfddaf2c120749879058e111b86fba | 4758a2cba5348274b5b9a04ea044b20ac0fe1848 |
refs/heads/master | <file_sep>import * as actionTypes from '../actions/actionsTypes';
import { updateObject } from '../../shared/utility';
const initialState = {
user: {},
loading: false,
};
const fetchUserStart = ( state, action ) => {
return updateObject( state, { loading: true } );
};
const fetchUserSuccess = ( state, action ) => {
return updateObject( state, {
user: action.user,
loading: false
} );
};
const fetchUserFail = ( state, action ) => {
return updateObject( state, { loading: false } );
};
const reducer = ( state = initialState, action ) => {
switch ( action.type ) {
case actionTypes.FETCH_USER_START: return fetchUserStart( state, action );
case actionTypes.FETCH_USER_SUCCESS: return fetchUserSuccess( state, action );
case actionTypes.FETCH_USER_FAIL: return fetchUserFail( state, action );
default: return state;
}
};
export default reducer;
<file_sep>import React, { useEffect, useState } from 'react'
import Rightbar from "../../components/rightbar/Rightbar";
import LanguageIcon from '@material-ui/icons/Language';
import { PersonAdd } from '@material-ui/icons';
import "./userProfile.css"
import { useParams } from 'react-router';
import axios from '../../axios-users';
import Topbar from '../../components/topbar/Topbar';
export default function UserProfile({userdata}) {
const [userInfo, setuserInfo] = useState({
name: "",
designation: "",
email: "",
city: "",
state: "",
zip: "",
website: "",
friendCount: ""
})
const { id } = useParams()
useEffect(() => {
axios.get(`/${id}`).then(data => {
setuserInfo({
name: data.data.name,
designation: data.data.designation,
email: data.data.email,
city: data.data.city,
state: data.data.zip,
website: data.data.website,
friendCount: data.data.friends.length
})
}).catch(err => {
console.log(err)
})
}, [id])
const onAddFriendHandler = () => {
axios.put(`/${id}/addfriend`).then(data=>{
console.log(data)
}).catch(err=>{
console.log(err)
})
}
return (
<>
<Topbar data={userdata}/>
<div className="userContainer">
<div className="userProfile">
<div className="userBanner">
</div>
<div className="userProfileInfo">
<img src="" alt="" />
<h2>{userInfo.name}</h2>
<p>{userInfo.designation}</p>
<p>{userInfo.email}</p>
<ul className="userDetails">
<li className="userDetailsItem">{userInfo.city}</li>
<li className="userDetailsItem">{userInfo.state}</li>
<li className="userDetailsItem">{userInfo.zip}</li>
<li className="userDetailsItem">{userInfo.friendCount} friends</li>
</ul>
</div>
<div className="userProfileAction">
<button className="addFriend" onClick={() => onAddFriendHandler()}>
<span className="addFriendItem">
<PersonAdd /> <span>Add Friend</span>
</span>
</button>
<button className="visitWebsite">
<span className="visitWebsiteItem">
<a href={userInfo.website} target="_blank"> <LanguageIcon /><span>Visit Website</span>
</a>
</span>
</button>
</div>
</div>
<div className="suggestions">
<Rightbar />
</div>
</div>
</>
)
}
<file_sep>import React from 'react'
import "./login.css"
export default function Login() {
return (
<div className="login">
<div className="loginWrapper">
<div className="loginLeft">
<h3>Login with Google</h3>
<a href="http://localhost:5500/auth/google">login</a>
</div>
<div className="loginRight">
<h3>Login using email and password</h3>
<label htmlFor="email">Email</label>
<input type="email" />
<br />
<label htmlFor="email">Email</label>
<input type="email" />
</div>
</div>
</div>
)
}
<file_sep>import React,{useState, useEffect} from 'react'
import { Redirect, Route } from 'react-router';
import axios from '../axios-users';
function ProtectedRoute({component:Component,...rest}) {
const [isAuthenticated, setisAuthenticated] = useState(null)
const [user, setuser] = useState(null)
useEffect(() => {
axios.get("http://localhost:5500/api/auth/check").then(data=>{
if(data.status === 200){
// console.log(data)
setisAuthenticated(true)
setuser(data.data)
}else{
setisAuthenticated(false)
}
}).catch(err=>{
setisAuthenticated(false)
})
}, [isAuthenticated])
if(isAuthenticated===null){
return "loading";
}
console.log("protected",user)
return (
<Route {...rest} render={props=> isAuthenticated ? (
<Component {...props} userdata={user}/>
) : <Redirect to="/login"/> } />
)
}
export default ProtectedRoute
<file_sep>import "./topbar.css"
import { Person, Chat, Notifications } from '@material-ui/icons';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import Notification from "../notification/Notification";
export default function Topbar({ data }) {
console.log(data)
let friendRequests = data?.friendRequests?.incoming?.map((e, i) => (<Notification key={i} data={e} />))
//send friend request array on map to notification as props and there find that user
return (
<div className="topbarContainer">
<div className="topbarLeft">
<span className="logo">
<a href="/"> Buzz App</a>
</span>
</div>
<div className="topbarRight">
<div className="topbarIcons">
<div className="topbarIconItem">
<Person /><a href="/editprofile">{data && data.name || "user"}</a>
</div>
<div className="topbarIconItem">
<div className="dropdown">
<Notifications className="dropbtn" />
<div className="dropdown-content">
{friendRequests}
</div>
</div>
<span className="topbarIconBadge">{data && data.friendRequests.incoming.length || ""}</span>
</div>
<div className="topbarIconItem">
<Chat />
</div>
<div className="topbarIconItem">
<a href="http://localhost:5500/logout">
<ExitToAppIcon /> <span>Logout</span>
</a>
</div>
</div>
</div>
</div>
)
}<file_sep>import Home from "./pages/home/Home";
import UserProfile from "./pages/userProfile/UserProfile"
import { Redirect, Route, Switch } from 'react-router-dom';
import EditProfile from "./pages/editprofile/EditProfile";
import Login from "./pages/login/Login";
import ProtectedRoute from "./auth/ProtectedRoute";
function App() {
return (
<Switch>
<ProtectedRoute path="/" component={Home} exact />
<ProtectedRoute path="/userprofile/:id" component={UserProfile} />
<ProtectedRoute path="/editprofile" component={EditProfile} exact />
<Route path="/login" component={Login} exact />
<Redirect to="/" />
</Switch>
);
}
export default App;
<file_sep>import "./leftbar.css";
import { ExpandMore, Bookmark, Chat, Group, HelpOutline, PlayCircleFilledOutlined, RssFeed, School, WorkOutline, Event } from "@material-ui/icons";
export default function Leftbar({ data }) {
// console.log("leftbar",data)
return (
<div className="leftbar">
<div className="leftbarWrapper">
<div className="leftbarCard">
<div className="banner">
</div>
<ul className="profileInfo">
<li className="profileInfoItem">
<img src={data && data.profilePicture || ""} alt="" />
</li>
<li className="profileInfoItem">
{data && data.name || "user"}
</li>
<li className="profileInfoItem">
<p>Designation : {data && data.designation || ""}</p>
</li>
</ul>
<ul className="userInfo">
<li className="userInfoItem">
<h4>{data && data.friends?.length || ""}</h4>
<span>Friends</span>
</li>
<li className="userInfoItem">
<br></br>
<br></br>
</li>
<li className="userInfoItem">
<h4>2</h4>
<span>Posts</span>
</li>
</ul>
</div>
<div className="leftbarListWrapper">
<ul className="leftbarList">
<h4>Media</h4>
<li className="leftbarListItem">
<RssFeed className="leftbarIcon" />
<span className="leftbarListItemText">Feed</span>
</li>
<li className="leftbarListItem">
<Chat className="leftbarIcon" />
<span className="leftbarListItemText">Chats</span>
</li>
<li className="leftbarListItem">
<PlayCircleFilledOutlined className="leftbarIcon" />
<span className="leftbarListItemText">Videos</span>
</li>
<li className="leftbarListItem">
<ExpandMore className="leftbarIcon colored" />
<span className="leftbarListItemText colored">Show more</span>
</li>
</ul>
<ul className="leftbarList">
<h4>Related</h4>
<li className="leftbarListItem">
<Group className="leftbarIcon" />
<span className="leftbarListItemText">Groups</span>
</li>
<li className="leftbarListItem">
<Bookmark className="leftbarIcon" />
<span className="leftbarListItemText">Bookmarks</span>
</li>
<li className="leftbarListItem">
<HelpOutline className="leftbarIcon" />
<span className="leftbarListItemText">Questions</span>
</li>
<li className="leftbarListItem">
<ExpandMore className="leftbarIcon colored" />
<span className="leftbarListItemText colored">Show more</span>
</li>
</ul>
<ul className="leftbarList">
<h4>Find</h4>
<li className="leftbarListItem">
<WorkOutline className="leftbarIcon" />
<span className="leftbarListItemText">Jobs</span>
</li>
<li className="leftbarListItem">
<Event className="leftbarIcon" />
<span className="leftbarListItemText">Events</span>
</li>
<li className="leftbarListItem">
<School className="leftbarIcon" />
<span className="leftbarListItemText">Courses</span>
</li>
<li className="leftbarListItem">
<ExpandMore className="leftbarIcon colored" />
<span className="leftbarListItemText colored">Show more</span>
</li>
</ul>
</div>
</div>
</div>
)
}<file_sep>import Share from "../share/Share"
import "./feed.css"
import React, { useEffect, useState, Suspense, useContext } from "react";
import axios from "../../axios-posts";
import AdminPost from "../adminPost/AdminPost";
const Post = React.lazy(() => import("../post/Post"))
export default function Feed({ data }) {
const [posts, setposts] = useState([])
const [isFetching, setIsFetching] = useState(false);
const [page, setPage] = useState(1);
const [updatedPost, setupdatedPost] = useState(false)
const [isAdmin, setisAdmin] = useState(false)
const [adminView, setadminView] = useState(false)
useEffect(() => {
fetchData();
window.addEventListener('scroll', handleScroll);
return () => {
setposts([])
setIsFetching(false)
setPage(1)
setupdatedPost(false)
}
}, [])
const changeStateHandler = () => {
setupdatedPost(true)
}
const handleScroll = () => {
if (
Math.ceil(window.innerHeight + document.documentElement.scrollTop) !== document.documentElement.offsetHeight ||
isFetching
) {
return;
}
setIsFetching(true);
console.log(isFetching);
};
const fetchData = async () => {
axios.get(`/post/all?page=${page}`).then(data => {
console.log(data)
setPage(page + 1)
setposts(() => {
return [...posts, ...data.data]
})
}).catch(err => {
console.log(err)
})
}
useEffect(() => {
if (!isFetching) return;
fetchMoreListItems();
}, [isFetching]);
const fetchMoreListItems = () => {
fetchData();
setIsFetching(false);
};
useEffect(() => {
setisAdmin(data?.isAdmin)
}, [data])
let post =
posts?.map((e, i) => (
<Suspense key={i} fallback="loading...">
<Post key={i} data={e} />
</Suspense>
))
let adminPost = posts?.map((e, i) => (
<Suspense key={i} fallback="loading...">
<AdminPost key={i} data={e} />
</Suspense>
))
return (
<div className="feed">
<div className="feedWrapper">
<div className="switchWrapper">
<label className="switch">
<input type="checkbox" disabled={!isAdmin} onClick={() => (setadminView((p) => !p))} />
<span className="slider round">Admin</span>
</label>
</div>
<Share data={data} postUpdate={changeStateHandler} />
<div className="postFeeddWrapper">
{adminView && isAdmin ? adminPost : post}
</div>
</div>
</div>
)
}
| 1d9718bfc5574605674f95790a502ca8dc679d28 | [
"JavaScript"
] | 8 | JavaScript | shivam-gupta-ttn/buzz-app-react | dc4429eb3fe88f49e316440d18bfeb60f6a2f4d1 | 02d90b2712e689738bb5a812284cbb8874e20ccf |
refs/heads/master | <file_sep>def my_agent(obs, config):
# Your code here: Amend the agent!
import numpy as np
import random
# Gets board at next step if agent drops piece in selected column
def drop_piece(grid, col, piece, config):
next_grid = grid.copy()
for row in range(config.rows-1, -1, -1):
if next_grid[row][col] == 0:
break
next_grid[row][col] = piece
return next_grid
# Returns True if dropping piece in column results in game win
def check_winning_move(obs, config, col, piece):
# Convert the board to a 2D grid
grid = np.asarray(obs.board).reshape(config.rows, config.columns)
next_grid = drop_piece(grid, col, piece, config)
# horizontal
for row in range(config.rows):
for col in range(config.columns-(config.inarow-1)):
window = list(next_grid[row,col:col+config.inarow])
if window.count(piece) == config.inarow:
return True
# vertical
for row in range(config.rows-(config.inarow-1)):
for col in range(config.columns):
window = list(next_grid[row:row+config.inarow,col])
if window.count(piece) == config.inarow:
return True
# positive diagonal
for row in range(config.rows-(config.inarow-1)):
for col in range(config.columns-(config.inarow-1)):
window = list(next_grid[range(row, row+config.inarow), range(col, col+config.inarow)])
if window.count(piece) == config.inarow:
return True
# negative diagonal
for row in range(config.inarow-1, config.rows):
for col in range(config.columns-(config.inarow-1)):
window = list(next_grid[range(row, row-config.inarow, -1), range(col, col+config.inarow)])
if window.count(piece) == config.inarow:
return True
return False
# Helper function for score_move: calculates value of heuristic for grid
def get_heuristic(grid, mark, config):
A = 0
B = 1
C = 1e2
D = 1e3
E = 0
F = -1e2
G = -1e3
H = -1e5
num_one = count_windows(grid, 1, mark, config)
num_two = count_windows(grid, 2, mark, config)
num_three = count_windows(grid, 3, mark, config)
num_four = count_windows(grid, 4, mark, config)
num_one_opp = count_windows(grid, 1, mark%2+1, config)
num_two_opp = count_windows(grid, 2, mark%2+1, config)
num_three_opp = count_windows(grid, 3, mark%2+1, config)
num_four_opp = count_windows(grid, 4, mark%2+1, config)
score = num_one * A + num_two * B + num_three * C + num_four * D + num_one_opp * E + num_two_opp * F + num_three_opp * G + num_four_opp * H
return score
# Helper function for get_heuristic: checks if window satisfies heuristic conditions
def check_window(window, num_discs, piece, config):
return (window.count(piece) == num_discs and window.count(0) == config.inarow-num_discs)
# Helper function for get_heuristic: counts number of windows satisfying specified heuristic conditions
def count_windows(grid, num_discs, piece, config):
num_windows = 0
# horizontal
for row in range(config.rows):
for col in range(config.columns-(config.inarow-1)):
window = list(grid[row, col:col+config.inarow])
if check_window(window, num_discs, piece, config):
num_windows += 1
# vertical
for row in range(config.rows-(config.inarow-1)):
for col in range(config.columns):
window = list(grid[row:row+config.inarow, col])
if check_window(window, num_discs, piece, config):
num_windows += 1
# positive diagonal
for row in range(config.rows-(config.inarow-1)):
for col in range(config.columns-(config.inarow-1)):
window = list(grid[range(row, row+config.inarow), range(col, col+config.inarow)])
if check_window(window, num_discs, piece, config):
num_windows += 1
# negative diagonal
for row in range(config.inarow-1, config.rows):
for col in range(config.columns-(config.inarow-1)):
window = list(grid[range(row, row-config.inarow, -1), range(col, col+config.inarow)])
if check_window(window, num_discs, piece, config):
num_windows += 1
return num_windows
valid_moves = [col for col in range(config.columns) if obs.board[col] == 0]
for attempt in valid_moves:
if check_winning_move(obs, config, attempt, obs.mark):
return attempt
for attempt in valid_moves:
if check_winning_move(obs, config, attempt, obs.mark%2+1):
return attempt
heuristics = list()
for col in valid_moves:
temp = drop_piece(np.asarray(obs.board).reshape(config.rows, config.columns), col, obs.mark, config)
heuristics.append(get_heuristic(temp, obs.mark, config))
best_val = max(heuristics)
best_choices = list()
for i in range(len(heuristics)):
if heuristics[i] == best_val:
best_choices.append(valid_moves[i])
return random.choice(best_choices)
| f73ec34da2f3c2eaa9e63a7dacd062352de74fb1 | [
"Python"
] | 1 | Python | haydnkeung/Connect-X | 2beedc091fd7d09f8b9288256d7fee074ec04283 | 5abf4fd3059b57e11d73223e09b11737c9132e6b |
refs/heads/master | <file_sep><?php
function insert_data_return_id($table,$array)
{
$query=build_insert_query($table,$array);
return execute_query_and_return_id($query);
}
function insert_data($table,$array)
{
$query=build_insert_query($table,$array);
execute_query($query);
}
function insert_data_array($table,$array)
{
$query=build_insert_query($table,$array);
execute_query($query);
}
?><file_sep><?php
require('models/model_quizList.php');
$quizList=get_data('question');
$AnswerList=get_Answer('answer');
if(!empty($_POST['next']))
{
if (!isset($_COOKIE['Ind_Counter']) )
$_COOKIE['Ind_Counter'] = 0;
$_COOKIE['Ind_Counter']++;
setcookie('Ind_Counter', $_COOKIE['Ind_Counter']);
$a = $_COOKIE['Ind_Counter'];
$count = 0;
foreach ($_POST as $key => $value) {
++$count;
if ($count <= 1) {
$_SESSION['question'][] = array($key, $value);
}
}
}
if(!empty($_POST['button']))
{
foreach ($_SESSION['question'] as $id=>$resultArray)
{
$id_array[]=$resultArray[0];
$userUnswer[]=$resultArray[1];
$score=explode('?',$resultArray[1]);
$answerNameUser=array_shift($score);
$answerNameArray[]=$answerNameUser;
$score=array_pop($score);
$scoreArray[]=$score;
if($score=="1")
{
$totalScore[]=$score;
}
}
require('views/view_user_answer.php');
}
if(!empty($_REQUEST['come_back']))
{
unset($_COOKIE['Ind_Counter']);
setcookie('Ind_Counter', "", -1);
session_unset();
}
require('views/view_quizList.php');
?><file_sep><?php
require('models/model_quizList.php');
$quizList=get_data('question');
$AnswerList=get_Answer('answer');
require('views/view_user_answer.php');
?><file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1
-- Время создания: Апр 25 2020 г., 12:55
-- Версия сервера: 10.4.11-MariaDB
-- Версия PHP: 7.4.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `quiz`
--
-- --------------------------------------------------------
--
-- Структура таблицы `answer`
--
CREATE TABLE `answer` (
`answer_id` int(11) NOT NULL,
`question_id` int(11) NOT NULL,
`is_correct` int(11) NOT NULL,
`answer_name` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `answer`
--
INSERT INTO `answer` (`answer_id`, `question_id`, `is_correct`, `answer_name`) VALUES
(371, 215, 0, ' унітарною'),
(372, 215, 0, 'суверенною'),
(373, 215, 1, 'цілісною і недоторканою'),
(374, 215, 0, 'суверенною та невідчужуваною'),
(375, 216, 1, 'політичної, економічної та ідеологічної багатоманітності;'),
(376, 216, 1, ' соціального плюралізму та багатоукладності економіки;'),
(377, 216, 1, 'відсутності цензури і поваги до приватної власності;'),
(378, 216, 1, 'поваги до культури Українського народу та культури національних\r\nменшин.'),
(379, 217, 1, ' військові формування, організація і порядок діяльності яких визначаються\r\nзаконом;'),
(380, 217, 1, ' Збройні Сили України;'),
(381, 217, 1, ' Збройні Сили України і інші військові формування;'),
(382, 217, 1, ' Службу безпеки України і правоохоронні органи держави.'),
(383, 218, 1, 'на підставі, в межах повноважень та у спосіб, передбачені Конституцією та\r\nзаконами України;'),
(384, 218, 0, 'з дотриманням принципів поваги до основоположних прав і свобод людини\r\nта неухильного дотримання законності;'),
(385, 218, 0, 'на підставах, у межах повноважень та у спосіб, що не заборонені\r\nКонституцією та законами України;'),
(386, 218, 0, 'на принципах верховенства права.'),
(387, 219, 1, 'не допускаються;'),
(388, 219, 0, 'допускаються у визначених Конституцією випадках;'),
(389, 219, 0, 'допускаються на підставі рішення Конституційного Суду України; '),
(390, 219, 0, 'допускаються у разі погодження з керівником вищого рівня.'),
(391, 220, 0, 'не мають зворотної дії;'),
(392, 220, 0, 'мають зворотну дію;'),
(393, 220, 1, 'не мають зворотної дії, окрім випадків коли вони помякшують чи\r\nскасовують відповідальність особи;'),
(394, 220, 0, 'мають зворотну дію в умовах надзвичайного та воєнного стану.'),
(395, 221, 0, 'всі правові акти органів влади'),
(396, 221, 0, 'розпорядчі акти органів державного управління, що визначають права і\r\nобовязки громадян'),
(397, 221, 1, 'закони та інші нормативно-правові акти, що визначають права і обовязки\r\nгромадян'),
(398, 221, 0, ' всі підзаконні нормативно-правові акти'),
(399, 222, 0, 'може бути позбавлений державою громадянства і висланий за межі\r\nУкраїни'),
(400, 222, 0, 'може бути позбавлений громадянства'),
(401, 222, 1, 'не може бути позбавлений громадянства'),
(402, 222, 0, ' може бути позбавлений лише політичних прав і свобод'),
(403, 223, 0, ' піклування'),
(404, 223, 0, 'надання допомоги'),
(405, 223, 1, 'піклування та захист'),
(406, 223, 0, 'захист'),
(407, 224, 0, 'кожен'),
(408, 224, 0, 'людина та громадянин'),
(409, 224, 1, 'громадянин'),
(410, 224, 0, 'громадянин України, який останні пять років мешкає на території України'),
(411, 225, 1, 'кожному'),
(412, 225, 0, 'громадянам України та особам без громадянства, які на законних підставах\r\nперебувають на території України'),
(413, 225, 0, 'громадянам України'),
(414, 225, 0, 'громадянам України та іноземцям'),
(415, 226, 0, ' усі фізичні особи'),
(416, 226, 1, 'громадяни України'),
(417, 226, 0, 'громадяни України та особи без громадянства, які на законних підставах\r\nперебувають на території України'),
(418, 226, 0, ' іноземці, які проживають в Україні останні 10 років');
-- --------------------------------------------------------
--
-- Структура таблицы `question`
--
CREATE TABLE `question` (
`id` int(11) NOT NULL,
`name` varchar(200) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `question`
--
INSERT INTO `question` (`id`, `name`) VALUES
(215, '1. Якою є територія України в межах існуючого кордону?'),
(216, ' 2.На яких засадах ґрунтується суспільне життя в Україні?'),
(217, '3.На кого покладається оборона України, захист її суверенітету,\r\nтериторіальної цілісності і недоторканості?'),
(218, '4. Як зобовязані діяти органи державної влади та органи місцевого\r\nсамоврядування, їх посадові особи?'),
(219, '5. Чи допускаються звуження змісту та обсягу існуючих прав і свобод при\r\nприйнятті нових законів або внесенні змін до чинних законів?'),
(220, '6. Чи мають зворотну дію у часі закони та інші нормативно правові\r\nакти?'),
(221, '7. Які акти мають бути доведені до відома населення у порядку,\r\nвстановленому законом?'),
(222, '8. Чи може громадянин України за дії, що дискредитують державу, бути\r\nпозбавлений громадянства?'),
(223, '9. Що гарантується Україною своїм громадянам, які перебувають за її\r\nмежами?'),
(224, '10. Хто має конституційне право на користування рівним правом доступу\r\nдо державної служби'),
(225, '11. Кому гарантується право на свободу думки і слова, на вільне\r\nвираження своїх поглядів і переконань?'),
(226, '12. Хто має право на участь в управлінні державними справами?');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `answer`
--
ALTER TABLE `answer`
ADD PRIMARY KEY (`answer_id`);
--
-- Индексы таблицы `question`
--
ALTER TABLE `question`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `answer`
--
ALTER TABLE `answer`
MODIFY `answer_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=426;
--
-- AUTO_INCREMENT для таблицы `question`
--
ALTER TABLE `question`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=229;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
foreach($quizList as $key=>$questionList)
{
foreach ($id_array as $index => $userResponse)
{
if($userResponse==$questionList['id'])
{
?>
<h3 class='quizTitle'><?= $questionList['name']; ?></h3>
<?php
foreach($scoreArray as $date=>$val)
{
foreach($answerNameArray as $Namedate=>$NameVal)
{
if($date==$Namedate && $key== $Namedate && $val==0)
{
?>
<p class='resultOfquestion'><?= $NameVal; ?></p>
<p>Вірно:</p>
<?php
foreach ($AnswerList as $true_kye=>$true_value)
{
if($true_value['question_id']==$userResponse && $true_value['is_correct']==1)
{
?>
<p class='resultOfquestionCorrect'><?=$true_value['answer_name'];?></p>
<?php
}
}
}elseif ($date==$Namedate && $key== $Namedate && $val==1)
{
?>
<p class='resultOfquestionTrue'><?= $NameVal; ?></p>
<?php
}
}
}
}
}
}
if(is_array($totalScore))
{
?>
<div class='totalScore'>
<h3 class='totalScore'>Вірних відповідей <?=count($totalScore);?> із <?=count($quizList);?></h3>
</div>
<?php
}else
{
$totalScore=0;
?>
<div class='totalScore'>
<h3 class='totalScore'>Вірних відповідей <?=$totalScore;?> із <?=count($quizList);?></h3>
</div>
<?php
}
?>
<file_sep><?php
require('views/view_add_question.php');
require('core/function_add_question.php');
?><file_sep>
<?php
function execute_query($query)
{
$connection=mysqli_connect('localhost','root','','quiz');
$result=mysqli_query($connection,$query);
if ($result==false)
{
echo mysqli_error($connection);
}
mysqli_close($connection);
return $result;
}
function execute_select_query($query)
{
$result=execute_query($query);
if (mysqli_num_rows($result)>0){
while($row=mysqli_fetch_assoc($result))
{
$rows[]=$row;
}
return $rows;
}
else
{
return null;
}
}
function build_select_query($table,$where='',$what='')
{
$where_sql='';
if (!empty($where))
{
$and=' and ';
foreach($where as $key=>$value)
{
if ($value)
{
$where_sql.=" $key='$value' $and";
}
}
$where_sql=rtrim($where_sql,$and);
if (!empty($where_sql))
{
$where_sql=" WHERE ".$where_sql;
}
}
$what_sql='';
if (empty($what)){
$what_sql ='*';
}
return "SELECT $what_sql
FROM $table
";
}
function execute_query_and_return_id($query){
$connection=mysqli_connect('localhost','root','','quiz');
$result=mysqli_query($connection,$query);
if ($result==false){
echo mysqli_error($connection);
}
$new_id=mysqli_insert_id($connection);
mysqli_close($connection);
return $new_id;
}
function build_insert_query($table,$parameters){
$columns_sql ='';
$values_sql ='';
$coma =',';
foreach($parameters as $col=>$value)
{
if (!empty($value) || $value!=null)
{
if(is_array($value))
{
foreach($value as $co=>$val)
{
$key=$col;
$columns_sql.=$key.$coma ;
$values_sql.="'".$val."'".$coma ;
}
}else
{
$columns_sql.=$col.$coma ;
$values_sql.="'".$value."'".$coma ;
}
}
}
$columns_sql=rtrim($columns_sql,$coma);
$values_sql =rtrim($values_sql,$coma);
return "INSERT INTO $table ($columns_sql)
VALUES ($values_sql)";
}
function build_delete_query($table,$where=''){
$where_sql='';
if ($where){
$and=' and';
foreach($where as $key=>$value){
$where_sql.=" $key='$value' $and";
}
$where_sql =rtrim($where_sql,$and);
$where_sql=' WHERE '.$where_sql;
}
return "DELETE FROM $table $where_sql";
}
function build_update_query($id,$table,$parameters){
$columns_sql ='';
$values_sql ='';
$coma =',';
foreach($parameters as $col=>$value)
{
if (!empty($value) || $value!=null)
{
if(is_array($value))
{
foreach($value as $co=>$val)
{
$key=$col;
$columns_sql.=$key.$coma ;
$values_sql.="'".$val."'".$coma ;
}
}else
{
$columns_sql.=$col.$coma ;
$values_sql.="'".$value."'".$coma ;
}
}
}
$columns_sql=rtrim($columns_sql,$coma);
$values_sql =rtrim($values_sql,$coma);
return "UPDATE $table
SET $columns_sql=$values_sql
WHERE id=$id";
}
function build_update_condition_query($id_Answer,$id,$table,$parameters)
{
foreach($parameters as $col=>$value)
{
$question_id=$parameters['question_id'];
$is_correct=$parameters['is_correct'];
$answer_name=$parameters['answer_name'];
}
return "UPDATE $table
SET is_correct=$is_correct,answer_name='$answer_name'
WHERE answer_id=$id_Answer
";
}
?><file_sep><?php
session_start();
require('db_script.php');
function load_page()
{
$page=getPage();
routing($page);
}
function getPage()
{
$result= 'quizList';
$array=explode('/',$_SERVER['REQUEST_URI']);
$page=array_pop($array);
if($page != null)
{
$array=explode('?',$page);
$result=array_shift($array);
}
return $result;
}
function routing($page)
{
switch($page)
{
case "quizList":
$controller="controller_quizList.php";
break;
case "action_user_answer":
$controller="controller_action_user_answer.php";
break;
case "addQuestionToQuiz":
$controller="controller_add_question.php";
break;
case "delete_question":
$controller="controller_delete_question.php";
break;
case "edit_question":
$controller="controller_edit_question.php";
break;
case "action_edit_data":
$controller="controller_action_edit_data.php";
break;
case "action_sent_question.php":
$controller="controller_action_sent_question.php";
break;
case "pagination":
$controller="controller_pagination.php";
break;
}
require ("views/template_view.php");
}
?><file_sep><?php
require('models/model_quizList.php');
require('models/model_delete_question.php');
$questionId=$_GET['questionId'];
delete_data('question',['id'=>$questionId]);
delete_data('answer',['question_id'=>$questionId]);
header("Location:quizList");
?><file_sep><div class='add_question_content'>
<form class='add_question_form' action="action_edit_data" method="post" enctype='multipart/form-data' name="Form">
<input type='hidden' name='number' value="<?=$questionId;?>">
<?php
foreach($get_id_Answer as $id_Answer)
{
?>
<input type='hidden' name='arrayIdAnswer[]' value="<?=$id_Answer;?>">
<?php
}
?>
<p class='add_question_title'>Запитання:</p>
<textarea name="questionName"><?=$question_name;?></textarea>
<p class='add_question_title'>Відповідь:</p>
<div class='add_question_newAnswer editData'>
<?php
foreach($answer_name as $info)
{
?>
<div class='edit_question_fild'>
<textarea class='add_question_newAnswer_select' name="newAnswer[]"><?=$info;?></textarea>
<select name='correctAnswerArray[]'>
<option value="1"> вірна відповідь</option>
<option value="0"> не вірна відповідь</option>
</select>
</div>
<?php
}
?>
</div>
<br>
<div id="DynamicExtraFieldsContainer">
<div id="addDynamicField">
</div>
<div class="DynamicExtraField"></div>
</div>
<input type='submit' value='Зберегти' name='edit_question'>
</form>
</div>
<file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css2?family=Poiret+One&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght@700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="<KEY>
crossorigin="anonymous"></script>
<title>QUIZ</title>
</head>
<body>
<header class='header'>
<div class='title'>
<h1 class='h1'>
ІV. Питання на перевірку знання спеціального законодавства (законів
України «Про Кабінет Міністрів України», «Про центральні органи
виконавчої влади», «Про адміністративні послуги», «Про місцеві державні
адміністрації», «Про звернення громадян», «Про доступ до публічної
інформації», «Про засади запобігання та протидії дискримінації в Україні»,
«Про забезпечення рівних прав та можливостей жінок і чоловіків», Конвенції
про права осіб з інвалідністю, Бюджетного кодексу України та Податкового
кодексу України)
</h1>
</div>
</header>
<main class='main'>
<div class='quiz_content'>
<?php
include 'controllers/'.$controller;
?>
</div>
</main>
</body>
</html>
<file_sep><script>
$('#addDynamicExtraFieldButton').click(function(event) {
addDynamicExtraField();
return false;
});
function addDynamicExtraField() {
var div = $('<div/>', {
'class': 'DynamicExtraField'
}).appendTo($('#DynamicExtraFieldsContainer'));
var br = $('<br/>').appendTo(div);
var label = $('<label/>').appendTo(div);
var input = $('<input/>', {
value: 'Видалити',
type: 'button',
'class': 'DeleteDynamicExtraField'
}).appendTo(div);
input.click(function() {
$(this).parent().remove();
});
var br = $('<br/>').appendTo(div);
var textarea = $('<textarea/>', {
name: 'DynamicExtraField[]',
'class': 'add_choise_select'
}).appendTo(div);
var select = $('<select/>',{
name: 'correctAnswer[]',
'class': 'add_true_select'
}).prependTo(div);
var option = $('<option/>',{
value: "1"
}).html("вірна відповідь").appendTo(select);
var option = $('<option/>',{
value: "0"
}).html("не вірна відповідь").appendTo(select);
}
$('.DeleteDynamicExtraField').click(function(event) {
$(this).parent().remove();
return false;
});
</script>
<file_sep><?php
require('core/core.php');
load_page();
?><file_sep><?php
function edit_data($table,$where=null)
{
$query=build_edit_query($table,$where);
execute_query($query);
}
function update_data($id,$table,$array)
{
$query=build_update_query($id,$table,$array);
execute_query($query);
}
function update_data_condition($id_Answer,$id,$table,$array)
{
$query=build_update_condition_query($id_Answer,$id,$table,$array);
execute_query($query);
}
?><file_sep><?php
require('models/model_quizList.php');
require('models/model_edit_question.php');
require('core/function_add_question.php');
require('models/model_add_quizList.php');
$questionId=$_GET['questionId'];
$questionList=get_data('question');
$AnswerList=get_data('answer');
$count=0;
foreach($questionList as $key=>$value)
{
$count++;
foreach($value as $k=>$val)
{
if($val==$questionId)
{
$question_name=$value['name'];
}
}
}
foreach($AnswerList as $point=>$data)
{
if($questionId==$data['question_id'])
{
$answer_name[]=$data['answer_name'];
$get_id_Answer[]=$data['answer_id'];
}
}
require('views/views_edit_question.php');
?><file_sep><?php
require('models/model_edit_question.php');
require('models/model_quizList.php');
$questionName=$_REQUEST['questionName'];
$answer_name_array=$_REQUEST['newAnswer'];
$id_Answer=$_REQUEST['arrayIdAnswer'];
$is_correct_array=$_REQUEST['correctAnswerArray'];
$id=$_REQUEST['number'];
update_data($id,'question',['name'=>$questionName]);
foreach($answer_name_array as $key=>$answer)
{
$answerData="$answer";
foreach($is_correct_array as $k=>$is_correct)
{
foreach($id_Answer as $point=>$idAnswer)
{
if ($k==$key && $k==$point)
{
update_data_condition($idAnswer,$id,'answer',['question_id'=>$id,
'is_correct'=>$is_correct,
'answer_name'=>"$answerData"
]);
}
}
}
}
header("Location:quizList");
exit;
?><file_sep><?php
function get_data($table,$where=null,$what=null)
{
$query=build_select_query($table,$where,$what);
return execute_select_query($query);
};
function get_Answer(){
$query="SELECT answer_name,question_id,id,is_correct
FROM answer
JOIN question
ON answer.question_id=question.id";
return execute_select_query($query);
}
?><file_sep>
<?php
require('models/model_quizList.php');
require('models/model_add_quizList.php');
$quizList=get_data('question');
$answerList=get_data('answer');
require('views/view_add_question.php');
$questionName=$_POST['questionName'];
$answer_name_base=$_POST['newAnswer'];
$answer_name=$_POST['DynamicExtraField'];
$is_correct_base=$_POST['correctAnswerBase'];
$is_correct=$_POST['correctAnswer'];
$newId=insert_data_return_id('question',['name'=>$questionName]);
$number="$newId";
$insert_Answer_base=insert_data('answer',['answer_name'=>$answer_name_base,
'is_correct'=>$is_correct_base,
'question_id'=>$number
]);
$count=-1;
foreach($is_correct as $key=>$value)
{
$count++;
foreach($answer_name as $point=>$data)
{
if($point==$count)
{
insert_data('answer',['answer_name'=>$data,
'is_correct'=>$value,
'question_id'=>$number
]);
}
}
}
header('Location:addQuestionToQuiz');
exit;
?><file_sep><?php
function delete_data($table,$where=null){
$query=build_delete_query($table,$where);
execute_query($query);
}
?><file_sep><div class='addQuestion'>
<a class="addQuestion_title" href='addQuestionToQuiz'>
<h4 class="link_add_question"><u>Додати питання до вікторини</u> <b class="answerList">+<b></h4></a>
</div>
<?php
$_COOKIE['Ind_Counter']=$_COOKIE['Ind_Counter'];
if ($quizList != null)
{
?>
<?php
foreach ($quizList as $index_quiz=>$quiz)
{
$idQ = $quiz['id'];
extract($quiz);
if ($quiz['name'] != NULL) {
?>
<form method="POST" enctype="multipart/form-data" action="" >
<?php
if ( $_COOKIE['Ind_Counter']== $index_quiz) {
?>
<a class="link_style edit" href="edit_question?questionId=<?= $idQ; ?>">Корегувати</a>
<a class="link_style" href="delete_question?questionId=<?= $idQ; ?>">Видалити</a>
<legend class="question_Name"
style='font-weight:800;
padding-bottom:10px;
padding-top:10px'><?= $name; ?></legend>
<?php
if ($AnswerList != null) {
foreach ($AnswerList as $valueQuiz) {
if ($idQ == $valueQuiz['question_id']) {
extract($valueQuiz);
?>
<input type="radio"
id="<?= $id; ?>"
name="<?= $question_id; ?>"
value="<?= $answer_name; ?>?<?= $valueQuiz['is_correct']; ?>">
<label class="answerList" for="<?= $id; ?>"><?= $answer_name; ?></label><br>
<?php
}
}
}
?>
<br>
<hr>
<?php
}
}
}
?>
<input id="number_question" value="Наступне запитання" name='next' type=submit>
<?php
if($_COOKIE['Ind_Counter']>=count($quizList)){
?>
<input name="button" id='check_answer' class="check_answer" value="Переглянути результат" type=submit>
<script>
document.getElementById('number_question').style.display='none';
document.getElementById('check_answer').style.display='flex';</script>
<input type="submit" name="come_back" value="Повернутись на головну">
<?php
}
?>
</form>
<?php
}
?>
| b9f419b385bbb91353620b59d5b69069b5e20ea2 | [
"SQL",
"PHP"
] | 20 | PHP | Anzhela-Chernenko/quiz | 77b2d80d3c5ad223c4b3ca4430dace16ae99e99c | 4075c65cd9ec66ab5748bfa84e81e96f3bd4800a |
refs/heads/master | <file_sep>// TOKENを秘匿化 別のファイルに書き出し
mapboxgl.accessToken =
"<KEY>";
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/light-v10",
// 松本
center: [137.972, 36.238],
zoom: 14,
});
function filterBy(year) {
const filters = ["==", "year", year];
map.setFilter("earthquake-circles", filters);
map.setFilter("earthquake-labels", filters);
document.getElementById("year").textContent = year;
}
map.on("load", () => {
d3.json("./data/matsumoto.geojson", jsonCallback);
});
const minYear = 2014;
function jsonCallback(err, data) {
if (err) {
throw err;
}
// Create a year property value based on time
// used to filter against.
data.features = data.features.map((d) => {
d.properties.year = new Date(d.properties.time).getFullYear();
return d;
});
//
map.addSource("earthquakes", {
type: "geojson",
data: data,
});
map.addLayer({
id: "earthquake-circles",
type: "circle",
source: "earthquakes",
paint: {
"circle-color": [
"interpolate",
["linear"],
["get", "hoge"],
6,
"#a3f3e8",
8,
"#1139e9",
],
"circle-opacity": 0.75,
"circle-radius": [
"interpolate",
["linear"],
["get", "hoge"],
6,
20,
10,
60,
],
},
});
map.addLayer({
id: "earthquake-labels",
type: "symbol",
source: "earthquakes",
layout: {
// "text-field": ["concat", ["to-string", ["get", "mag"]], "m"],
// ["get", "XXX"]で特定のフィールドを取得
"text-field": ["to-string", ["get", "content"]],
// "text-field": "松本に幽閉",
"text-font": ["Open Sans Bold", "Arial Unicode MS Bold"],
"text-size": 12,
},
paint: {
"text-color": "rgba(0,0,0,0.5)",
},
});
// Set filter to first year to the slider
filterBy(minYear);
document.getElementById("slider").addEventListener("input", (e) => {
const year = parseInt(e.target.value, 10) + minYear;
filterBy(year);
});
}
| 2518cf4bc422276c715596d97c45228c89211a33 | [
"JavaScript"
] | 1 | JavaScript | iaoiui/mapbox_d3js | 5cd4a7133416986d45b003e2e47092de1c733e7e | 0df8dc6123e21de4561994fa0b794d9d67d72536 |
refs/heads/master | <file_sep><?php
/**
* Plugin Name: Mk Widget
* Plugin URI: http://www.mayankpatel104.blogspot.in/
* Description: MK Widget
* Version: 1.0
* Author: <NAME>
* Author URI: http://www.mayankpatel104.blogspot.in/
* License: A "mk-widget"
*/
// Creating the widget
class mk_widget extends WP_Widget
{
function __construct()
{
parent::__construct('mk_widget',__('MK Widget', 'mk_widget_domain'), array( 'description' => __( 'Sample Widget By Mayank Patel', 'mk_widget_description' ),));
}
public function widget($args,$instance)
{
$title = apply_filters('widget_title',$instance['title']);
echo $args['before_widget'];
if(!empty($title))
{
echo $args['before_title'] . $title . $args['after_title'];
}
echo __('Hello, World Frontend Side!','mk_widget_description');
echo $args['after_widget'];
}
public function form($instance)
{
if(isset($instance['title']))
{
$title = $instance['title'];
}
else
{
$title = __('New title','mk_widget_description');
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
public function update($new_instance,$old_instance)
{
$instance = array();
$instance['title'] = (!empty($new_instance['title']))?strip_tags($new_instance['title']):'';
return $instance;
}
}
function wpb_load_widget()
{
register_widget( 'mk_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );
?> | 1951a7ece8daa65d68ed52c262c53516e4b9566d | [
"PHP"
] | 1 | PHP | mayankpatel1004/mk_widget | bab7ddb0b3bbf6c8a2007f3558f360724b78fb32 | 78f2a11c7aef144829bce48bf337e76951f7a17a |
refs/heads/master | <file_sep>import React, { Component, PropTypes } from 'react';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';
/*
React Router provides singleton versions of history (browserHistory and hashHistory) that you can import
and use from anywhere in your application. However, if you prefer Redux style actions, the library also
provides a set of action creators and a middleware to capture them and redirect them to your history instance.
https://github.com/reactjs/react-router-redux
import { push } from 'react'router-redux';
*/
// Need to use for code to render on server side
@asyncConnect([{
promise: ({store: { /* dispatch, getState */} }) => {
const promises = [];
return Promise.all(promises);
}
}])
/*
Use @connect to load state from redux
import { connect } from 'react-redux';
@connect(
state => ({user: state.auth.user}),
{logout, pushState: push}
)
*/
export default class App extends Component {
static propTypes = {
children: PropTypes.object.isRequired
};
static contextTypes = {
store: PropTypes.object.isRequired
};
render() {
const styles = require('./App.scss');
return (
<div className={styles.app}>
<Helmet {...config.app.head}/>
<Navbar fixedTop>
<Navbar.Header>
<Navbar.Brand>
<IndexLink to="/" activeStyle={{color: '#33e0ff'}}>
<div className={styles.brand}/>
<span>{config.app.title}</span>
</IndexLink>
</Navbar.Brand>
<Navbar.Toggle/>
</Navbar.Header>
<Navbar.Collapse eventKey={0}>
<Nav navbar>
{ /* Add link items here. For each link remember to increment eventKey by 1. */ }
<LinkContainer to="/about">
<NavItem eventKey={1}>About Us</NavItem>
</LinkContainer>
</Nav>
</Navbar.Collapse>
</Navbar>
<div className={styles.appContent}>
{this.props.children}
</div>
</div>
);
}
}
<file_sep># React Redux Universal Hot Remodelled for MERN Stack



A scaffolding tool which makes it easy to build isomorphic apps using MERN, [MongoDB](https://www.mongodb.com) - [Express](http://expressjs.com) - [React](https://github.com/facebook/react) - [NodeJS](https://nodejs.org). By minimizing the setup time, you can quickly start developmenting a fresh app with proven technologies!
---
## About
This is a remodelled of <NAME>'s [React Redux Universal Hot Example](https://github.com/erikras/react-redux-universal-hot-example) meant to act as a boilerplate MERN project.
## Installation
```
npm install
```
## Useful commands
Running Dev Server:
```bash
npm run dev
```
Take it to Production:
```bash
npm run build
npm run start
```
Unit Testing:
```bash
npm run test
```
## Changes made to original React Redux Hot Example
### Major changes
- Removed API server
- Removed every other container/components except for App, About Me, and 404 page
### Minor changes
- Organized files similar to that of [MERN.io](http://mern.io/)
- Helmet title template is now '%s - title'
- Added a .env file to root folder to store node environment variables
<file_sep>/**
* Point of contact for component modules
*
* ie: export CounterButton from './CounterButton/CouterButton';
*
*/
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import {renderIntoDocument} from 'react-addons-test-utils';
import { expect} from 'chai';
import { Provider } from 'react-redux';
import { browserHistory } from 'react-router';
import createStore from 'redux/create';
import ApiClient from 'helpers/ApiClient';
const client = new ApiClient();
<file_sep>import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {reducer as reduxAsyncConnect} from 'redux-async-connect';
/*
multireducer is a utility to wrap many copies of a single Redux reducer into a single key-based reducer.
import multireducer from 'multireducer';
export default combineReducers({
multireducer: multireducer({
counter1: counter,
counter2: counter,
counter3: counter
})
});
*/
// Import reducers here
import {reducer as form} from 'redux-form';
export default combineReducers({
routing: routerReducer,
reduxAsyncConnect,
form
});
| bc1339889636cd3eaac2b65b471a486b1a91c5e1 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | chengsieuly/react-redux-universal-hot-remodelled | a3412fa85f4371944542a4ac52aca89356992077 | 3c8a74ea9b8fecbdb97d536c4e619a996f791376 |
refs/heads/master | <file_sep>(function (global) {
var DemoViewModel,
app = global.app = global.app || {};
DemoViewModel = kendo.data.ObservableObject.extend({
checkAvailable: function () {
if (!this.checkSimulator()) {
cordova.plugins.email.isAvailable(this.callback);
}
},
composeEmail: function () {
if (!this.checkSimulator()) {
cordova.plugins.email.open({
to: ['<EMAIL>'],
cc: ['<EMAIL>'],
bcc: ['<EMAIL>', '<EMAIL>'],
attachments: ['file://styles/images/logo.png', 'file://styles/images/logo2x.png'],
subject: 'EmailComposer plugin test',
body: '<h2>Hello!</h2>This is a nice <strong>HTML</strong> email with two attachments.',
isHtml: true
}, this.callback)
}
},
callback: function(msg) {
navigator.notification.alert(JSON.stringify(msg), null, 'EmailComposer callback', 'Close');
},
checkSimulator: function() {
if (window.navigator.simulator === true) {
alert('This plugin is not available in the simulator.');
return true;
} else if (window.cordova === undefined || window.cordova.plugins === undefined) {
alert('Plugin not found. Maybe you are running in AppBuilder Companion app which currently does not support this plugin.');
return true;
} else {
return false;
}
}
});
app.demoService = {
viewModel: new DemoViewModel()
};
})(window);
| 7838db7233708c4b499e4039440085a59708863c | [
"JavaScript"
] | 1 | JavaScript | Telerik-Verified-Plugins/EmailComposer-DemoApp | 1a8780d11ddb5606b16391ec8059644bcce078d0 | 50ca5a6a0e18f9b5c5e396aa88bf72c70d9d3bdc |
refs/heads/master | <repo_name>developerdesigner18/quotesbook<file_sep>/src/components/Signup.js
import { useState } from "react";
import { useHistory, Link as RouterLink } from "react-router-dom";
import { auth, db } from "../firebase/config";
import { useTranslation } from "react-i18next";
import { makeStyles } from "@material-ui/core/styles";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
import Grid from "@material-ui/core/Grid";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
import Typography from "@material-ui/core/Typography";
import Container from "@material-ui/core/Container";
const useStyles = makeStyles((theme) => ({
paper: {
// marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function Signup() {
const classes = useStyles();
const [fullName, setFullName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const history = useHistory();
// Signup with Email
const handleOnSignup = (e) => {
e.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((cred) => {
db.collection("users")
.doc(cred.user.uid)
.set({
displayName: fullName,
photoURL: cred.user.photoURL,
favoritedCount: 0,
starredCount: 0,
created: [],
createdCount: 0,
uid: cred.user.uid,
})
.then(() => {
cred.user
.updateProfile({ displayName: fullName })
.then(() => {
console.log("updated...");
history.push("/");
// Firebase onAuthStateChanged listener cannot be triggered by updateProfile method!
// So window reload is a temporary solution!
window.location.reload();
})
.catch((error) => console.log(error));
});
})
.catch((error) => alert(error.message));
};
const { t } = useTranslation();
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
{t("signUp")}
</Typography>
<form className={classes.form} noValidate>
<TextField
onChange={(e) => {
setFullName(e.target.value);
}}
variant="outlined"
margin="normal"
required
fullWidth
id="fullname"
label={t("fullName")}
name="fullname"
autoComplete="fullname"
autoFocus
/>
<TextField
onChange={(e) => {
setEmail(e.target.value);
}}
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label={t("emailAddress")}
name="email"
autoComplete="email"
autoFocus
/>
<TextField
onChange={(e) => {
setPassword(e.target.value);
}}
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label={t("password")}
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label={t("rememberMe")}
/>
<Button
onClick={handleOnSignup}
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
{t("signUp")}
</Button>
<Grid item>
<RouterLink
to="/signin"
variant="body2"
style={{ color: "inherit" }}
>
{t("alreadyHaveAnAccount")}? {t("signIn")}
</RouterLink>
</Grid>
</form>
</div>
</Container>
);
}
<file_sep>/src/components/FavoriteQuotes.js
import { useState, useEffect } from "react";
import { useParams, withRouter } from "react-router-dom";
import { db } from "../firebase/config";
import { useTranslation } from "react-i18next";
import Quote from "./Quote";
import { Typography } from "@material-ui/core";
const Quotes = ({ currentUser }) => {
const { authorId } = useParams();
const [user, setUser] = useState([]);
const [favoritedQuotes, setFavoritedQuotes] = useState([]);
const [quotes, setQuotes] = useState([]);
const filteredQuotes = quotes.filter((quote) =>
favoritedQuotes.includes(quote.id)
);
useEffect(() => {
// Get quoteId from author's favorit's collection
db.collection("favorites")
.where("uid", "==", authorId)
.onSnapshot((snap) => {
let data = [];
snap.forEach((doc) => {
data.push(doc.data().quoteId);
});
setFavoritedQuotes(data);
});
// Get all quotes
db.collection("quotes")
.orderBy("createdAt", "desc")
.onSnapshot((snap) => {
let data = [];
snap.docs.forEach((doc) => {
data.push({ ...doc.data(), id: doc.id });
});
setQuotes(data);
});
// Get user
db.collection("users")
.doc(authorId)
.get()
.then((doc) => {
if (doc.exists) {
setUser(doc.data());
}
})
.catch((error) => console.error(error));
}, [authorId]);
const { t } = useTranslation();
return !filteredQuotes.length ? (
<Typography>
{`${user.displayName} ${t("hasNotFavoritedAnyQuotesYet")}!`}
</Typography>
) : (
<div>
{filteredQuotes.map((doc) => (
<Quote
key={doc.id}
quoteId={doc.id}
quote={doc}
currentUser={currentUser}
quoteImage={doc.image}
quoteAudio={doc.audio}
topics={doc.topics}
favoritesCount={doc.favoritesCount}
starsCount={doc.starsCount}
quoteStars={doc.stars}
quoteCreatedAt={doc.createdAt}
/>
))}
</div>
);
};
export default withRouter(Quotes);
<file_sep>/src/components/Signin.js
import { useEffect, useState } from "react";
import { useHistory, Link as RouterLink } from "react-router-dom";
import { auth, db, facebookProvider, googleProvider } from "../firebase/config";
import { useTranslation } from "react-i18next";
import { makeStyles } from "@material-ui/core/styles";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
import Link from "@material-ui/core/Link";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import Container from "@material-ui/core/Container";
import FacebookIcon from "@material-ui/icons/Facebook";
import { MailOutline } from "@material-ui/icons";
const useStyles = makeStyles((theme) => ({
paper: {
// marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
cursor: "pointer",
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function Signin() {
const classes = useStyles();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const history = useHistory();
// Email Login
const handleOnSubmit = (e) => {
e.preventDefault();
auth.signInWithEmailAndPassword(email, password).then((cred) => {
history.push("/");
});
};
// Fetch existing users
const [existingUsers, setExistingUsers] = useState([]);
useEffect(() => {
db.collection("users")
.get()
.then((doc) => {
let data = [];
doc.forEach((doc) => {
data.push(doc.data());
});
setExistingUsers(data);
})
.catch((error) => {
console.log("Error getting document:", error);
});
}, []);
// Gmail Login
const handleLoginWithGmail = () => {
auth
.signInWithPopup(googleProvider)
.then((cred) => {
if (
existingUsers.find(
(existingUser) => existingUser.uid === cred.user.uid
)
) {
history.push("/");
} else {
db.collection("users")
.doc(cred.user.uid)
.set({
displayName: cred.user.displayName,
photoURL: cred.user.photoURL,
favoritedCount: 0,
starredCount: 0,
created: [],
createdCount: 0,
uid: cred.user.uid,
})
.then(() => {
history.push("/");
})
.catch((error) => console.log(error.message));
}
})
.catch((error) => console.log(error.message));
};
// Facebook Login
const handleLoginWithFacebook = () => {
auth
.signInWithPopup(facebookProvider)
.then((cred) => {
if (
existingUsers.find(
(existingUser) => existingUser.uid === cred.user.uid
)
) {
history.push("/");
} else {
db.collection("users")
.doc(cred.user.uid)
.set({
displayName: cred.user.displayName,
photoURL: cred.user.photoURL,
favorited: [],
favoritedCount: 0,
starred: [],
starredCount: 0,
created: [],
createdCount: 0,
uid: cred.user.uid,
})
.then(() => {
history.push("/");
})
.catch((error) => console.log(error.message));
}
})
.catch((error) => console.log(error.message));
};
const { t } = useTranslation();
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<div style={{ display: "flex", alignItems: "center" }}>
<Typography component="p">{t("signInWith")}</Typography>
<Avatar onClick={handleLoginWithGmail} className={classes.avatar}>
<MailOutline />
</Avatar>
<Avatar onClick={handleLoginWithFacebook} className={classes.avatar}>
<FacebookIcon />
</Avatar>
</div>
<Typography component="p" variant="h6">
{t("or")}
</Typography>
<form className={classes.form} noValidate>
<TextField
onChange={(e) => {
setEmail(e.target.value);
}}
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label={t("emailAddress")}
name="email"
autoComplete="email"
autoFocus
/>
<TextField
onChange={(e) => {
setPassword(e.target.value);
}}
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label={t("password")}
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label={t("rememberMe")}
/>
<Button
onClick={handleOnSubmit}
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
{t("signIn")}
</Button>
<Grid container>
<Grid item xs>
<Link href="/forgot-password" variant="body2">
{t("forgotPassword")}?
</Link>
</Grid>
<Grid item>
<RouterLink
to="/signup"
variant="body2"
style={{ color: "inherit" }}
>
{t("newToQuotesBook")}? {t("signUp")}
</RouterLink>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
<file_sep>/src/firebase/config.js
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/storage";
import "firebase/auth";
import "firebase/functions";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "quotesbook-ae596.firebaseapp.com",
projectId: "quotesbook-ae596",
storageBucket: "quotesbook-ae596.appspot.com",
messagingSenderId: "214540384599",
appId: "1:214540384599:web:05081abc20c5cb06d9e612",
measurementId: "G-0QCK80XEZ5",
};
// firebase.initializeApp(firebaseConfig);
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
// Firestore setting as per environment
// if (window.location.hostname === "localhost") {
// console.log("localhost detected");
// firebase.firestore().settings({
// host: "localhost:8080",
// ssl: false,
// });
// firebase.functions().useFunctionsEmulator("http://localhost:5001");
// }
} else {
firebase.app(); // if already initialized, use that one
}
const db = firebase.firestore();
const firebaseStorage = firebase.storage();
const auth = firebase.auth();
const functions = firebase.functions();
const googleProvider = new firebase.auth.GoogleAuthProvider();
const facebookProvider = new firebase.auth.FacebookAuthProvider();
const timeStamp = firebase.firestore.FieldValue.serverTimestamp();
const increment = firebase.firestore.FieldValue.increment(1);
const decrement = firebase.firestore.FieldValue.increment(-1);
export {
db,
firebaseStorage,
auth,
functions,
googleProvider,
facebookProvider,
timeStamp,
increment,
decrement,
};
// Fake collections for local emulators
// uid: 'fasfdaf948a96f',
// displayName: 'Prashant',
// photoURL: 'fasfafewer<PASSWORD>4f5s4',
// text: 'hello'
// favoritesCount: 2,
// starsCount: 3,
<file_sep>/src/components/GuestUser.js
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import { Divider, ListItem, ListItemText } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
maxWidth: 300,
},
bullet: {
display: "inline-block",
margin: "0 2px",
transform: "scale(0.8)",
},
title: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
// necessary for content to be below app bar
toolbar: theme.mixins.toolbar,
}));
export default function GuestUser() {
const classes = useStyles();
const { t } = useTranslation();
return (
<div>
<div className={classes.toolbar} />
<Divider />
<ListItem>
<ListItemText>
{t("youAreUnique")}. <br />
<Link to="/signin" style={{ color: "inherit" }}>
{t("signIn")}
</Link>{" "}
{t("toCreateYourAwesomeQuotes")}.
</ListItemText>
</ListItem>
<ListItem>
<Button variant="contained" color="primary" size="small">
{t("share")}
</Button>
</ListItem>
</div>
);
}
<file_sep>/src/config.js
const dev = {
app_url: "http://localhost:3000",
};
const prod = {
app_url: "http://localhost:3000",
};
const config = process.env.REACT_APP_STAGE === "dev" ? dev : prod;
export default config;
<file_sep>/src/components/TopicSelector.js
/* eslint-disable no-use-before-define */
import { useState } from "react";
import { useTranslation } from "react-i18next";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
const useStyles = makeStyles((theme) => ({
root: {
width: "100%",
"& > * + *": {
marginTop: theme.spacing(3),
},
},
}));
export default function TopicSelector({ loadTopics }) {
const classes = useStyles();
const [selectedTopics, setSelectedTopics] = useState("");
console.log("topics", selectedTopics);
loadTopics(selectedTopics);
const { t } = useTranslation();
return (
<div className={classes.root}>
<Autocomplete
size="small"
multiple
id="tags-standard"
options={topics}
getOptionDisabled={(options) =>
selectedTopics.length > 1 ? true : false
}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
label={t("topic")}
placeholder={t("selectUpTo2Topics")}
/>
)}
onChange={(e, val) => {
setSelectedTopics(val);
}}
/>
</div>
);
}
// Predefined topics by admin
const topics = ["Inspirational", "Positivity", "Motivational"];
<file_sep>/src/components/About.js
import { useTranslation } from "react-i18next";
// import { AuthorSkeleton } from "./Skeletons";
import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import { Button, Divider, Grid } from "@material-ui/core";
// const useStyles = makeStyles((theme) => ({
// // necessary for content to be below app bar
// toolbar: theme.mixins.toolbar,
// }));
export default function About() {
// const classes = useStyles();
const { t } = useTranslation();
// const array = ["About", "Contact", "Terms", "Privacy Policy", "Disclaimer"];
return (
<div style={{ position: "absolute", bottom: "80px" }}>
<Divider />
<Typography align="center" color="textSecondary" variant="subtitle1">
{t("quotesBook")}
</Typography>
<Grid container spacing={1} justifyContent="center">
{/* {array.map((gridItem) => (
<Grid item xs={4}>
<Button>{gridItem}</Button>
</Grid>
))} */}
<Grid item xs={4}>
<Button>About</Button>
</Grid>
<Grid item xs={4}>
<Button>Contact</Button>
</Grid>
<Grid item xs={4}>
<Button>Terms</Button>
</Grid>
<Grid item xs={7}>
<Button>Privacy Policy</Button>
</Grid>
<Grid item xs={5}>
<Button>Disclaimer</Button>
</Grid>
</Grid>
<Divider />
</div>
);
}
<file_sep>/src/components/Author.js
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { db } from "../firebase/config";
import { useTranslation } from "react-i18next";
import Quote from "./Quote";
import { Typography } from "@material-ui/core";
import { QuoteSkeleton } from "./Skeletons";
const Author = ({ currentUser, loadAuthorId }) => {
const { authorId } = useParams();
const [user, setUser] = useState(null);
const [quotes, setQuotes] = useState(null);
useEffect(() => {
// Load authorId to App component
authorId && loadAuthorId(authorId);
db.collection("users")
.doc(authorId)
.onSnapshot((user) => {
setUser(user.data());
});
db.collection("quotes")
.orderBy("createdAt", "desc")
.onSnapshot((quotes) => {
let data = [];
quotes.forEach((quote) => data.push({ ...quote.data(), id: quote.id }));
setQuotes(data.filter((quote) => quote.uid === authorId));
});
}, [authorId, loadAuthorId]);
const { t } = useTranslation();
return !user ? (
<div style={{ width: "100%" }}>
{[1, 2, 3, 4].map((skeleton) => (
<QuoteSkeleton key={skeleton} />
))}
</div>
) : !quotes?.length ? (
currentUser.uid ? (
<Typography align="center" gutterBottom>
{`
${user?.displayName?.split(" ")[0]}, ${t("youHaveNotCreatedAQuoteYet")}!
`}
</Typography>
) : (
<Typography align="center" gutterBottom>
{`
${user?.displayName.split(" ")[0]}, ${t("hasNotCreatedAQuoteYet")}
`}
</Typography>
)
) : (
<div style={{ width: "100%" }}>
{quotes.map((doc) => (
<Quote
key={doc.id}
currentUser={currentUser}
authorId={authorId}
quoteId={doc.id}
quote={doc}
quoteImage={doc.image}
quoteAudio={doc.audio}
topics={doc.topics}
favoritesCount={doc.favoritesCount}
starsCount={doc.starsCount}
quoteCreatedAt={doc.createdAt}
/>
))}
</div>
);
};
export default Author;
<file_sep>/src/components/Authors.js
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { CardActions, makeStyles } from "@material-ui/core";
import BorderColorIcon from "@material-ui/icons/BorderColor";
import {
Avatar,
Divider,
List,
ListItem,
ListItemAvatar,
ListItemText,
Typography,
} from "@material-ui/core";
import { db } from "../firebase/config";
import { Link } from "react-router-dom";
import { AuthorsSkeleton } from "./Skeletons";
const useStyles = makeStyles((theme) => ({
root: {
maxWidth: "56ch",
marginBottom: "10px",
background: "transparent",
},
}));
const Authors = () => {
const classes = useStyles();
const [users, setUsers] = useState();
useEffect(() => {
db.collection("users")
// .where("createdCount", ">", 0)
.orderBy("createdCount", "asc")
.onSnapshot((snap) => {
let data = [];
snap.forEach((snap) => {
data.push({ ...snap.data() });
});
setUsers(data);
});
}, []);
const { t } = useTranslation();
return (
<div>
{!users
? [1, 2, 3, 4].map((skeleton) => <AuthorsSkeleton />)
: users.map((user) => (
<Link
to={`/author/${user.uid}`}
style={{ color: "inherit", textDecoration: "none" }}
>
<List className={classes.root}>
<ListItem alignItems="flex-start">
<ListItemAvatar>
<Avatar alt={user.displayName} src={user.photoURL} />
</ListItemAvatar>
<ListItemText
primary={user.displayName}
secondary={
<>
{user.favoriteQuote && (
<>
<Typography
component="span"
variant="body2"
color="textPrimary"
>
{`${t("favoriteQuote")} >> `}
</Typography>
{user.favoriteQuote}
</>
)}
<CardActions style={{ paddingLeft: "0" }}>
<div
style={{
display: "flex",
alignItems: "center",
marginRight: "12px",
}}
>
<BorderColorIcon
style={{
fontSize: "18px",
marginRight: "10px",
}}
/>
<Typography>{user.createdCount}</Typography>
</div>
</CardActions>
</>
}
/>
</ListItem>
<Divider variant="inset" component="li" />
</List>
</Link>
))}
</div>
);
};
export default Authors;
<file_sep>/src/components/Topics.js
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { AuthorSkeleton } from "./Skeletons";
// import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import { Divider, List, ListItem } from "@material-ui/core";
import ListItemText from "@material-ui/core/ListItemText";
// const useStyles = makeStyles((theme) => ({
// necessary for content to be below app bar
// toolbar: theme.mixins.toolbar,
// }));
export default function Topics() {
// const classes = useStyles();
const { t } = useTranslation();
const topics = ["Inspirational", "Positivity", "Motivational"];
return (
<div>
<Divider />
<Typography align="center" color="textSecondary" variant="subtitle1">
{t("topics")}
</Typography>
{!topics.length ? (
[1, 2, 3, 4].map((skeleton) => <AuthorSkeleton key={skeleton} />)
) : (
<List>
{topics.map((topic) => (
<Link
to={`/quotes/${topic}`}
style={{ textDecoration: "none", color: "inherit" }}
>
<ListItem button className={listItem}>
<ListItemText primary={topic} />
</ListItem>
</Link>
))}
</List>
)}
<Divider />
</div>
);
}
<file_sep>/src/components/CreateQuote.js
import { useState } from "react";
import PostQuote from "./PostQuote";
import { useTranslation } from "react-i18next";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CreateIcon from "@material-ui/icons/Create";
import clsx from "clsx";
import {
Avatar,
CardHeader,
Collapse,
IconButton,
Typography,
} from "@material-ui/core";
import "./CreateQuote.css";
const useStyles = makeStyles((theme) => ({
icon: {
cursor: "pointer",
},
card: {
width: 445,
[theme.breakpoints.down("sm")]: {
maxWidth: 340,
},
marginBottom: "20px",
},
}));
export default function CreateQuote({ currentUser }) {
const classes = useStyles();
const [expanded, setExpanded] = useState(false);
const handleExpandClick = () => {
setExpanded(!expanded);
};
const loadExpansion = (data) => {
setExpanded(data);
};
const { t } = useTranslation();
return (
<div
style={{
display: "flex",
flexDirection: "column",
}}
>
<Card className={classes.card}>
<div className="createQuote">
<CardHeader
avatar={
<Avatar className={classes.avatar}>
{currentUser ? (
currentUser.photoURL ? (
<img
src={currentUser.photoURL}
alt={currentUser.displayName}
style={{
height: "100%",
width: "100%",
objectFit: "cover",
}}
/>
) : (
currentUser.displayName?.charAt(0)
)
) : (
"QB"
)}
</Avatar>
}
/>
<IconButton
className={clsx(classes.expand, {
[classes.expandOpen]: expanded,
})}
onClick={handleExpandClick}
aria-expanded={expanded}
aria-label="show more"
>
<Typography>{t("createQuote")}</Typography>
<CreateIcon />
</IconButton>
</div>
</Card>
<Collapse in={expanded} timeout="auto" unmountOnExit>
<PostQuote currentUser={currentUser} loadExpansion={loadExpansion} />
</Collapse>
</div>
);
}
<file_sep>/src/components/Skeletons.js
import { Avatar, Box, Typography } from "@material-ui/core";
import { Skeleton } from "@material-ui/lab";
export const QuoteSkeleton = () => {
return (
<div>
<Box display="flex" alignItems="center">
<Box margin={1}>
<Skeleton variant="circle">
<Avatar />
</Skeleton>
</Box>
<Box width="100%">
<Skeleton width="100%">
<Typography>
Lorem ipsum dolor sit consectetur adipisicing.
</Typography>
</Skeleton>
</Box>
</Box>
<Skeleton variant="rect" width="100%">
<div style={{ paddingTop: "57%" }} />
</Skeleton>
</div>
);
};
export const AuthorSkeleton = () => {
return (
<div>
<Box display="flex" alignItems="center">
<Box margin={1}>
<Skeleton variant="circle">
<Avatar />
</Skeleton>
</Box>
<Box margin={1} width="100%">
<Skeleton variant="text" width="100%">
<Typography>.</Typography>
</Skeleton>
</Box>
</Box>
</div>
);
};
export const AuthorsSkeleton = () => {
return (
<div style={{ margin: "40px 20px" }}>
<Box display="flex" alignItems="center">
<Box margin={1}>
<Skeleton variant="circle">
<Avatar />
</Skeleton>
</Box>
<Skeleton width="100%">
<Typography>.</Typography>
</Skeleton>
</Box>
<Box margin={1} width="100%">
<Skeleton width="100%">
<Typography variant="h6">.</Typography>
</Skeleton>
<Skeleton width="100%">
<Typography variant="subtitle1">
Lorem ipsum dolor sit amet consectetur, adipisicing elit.
Doloremque, ut.
</Typography>
</Skeleton>
</Box>
</div>
);
};
export const PhotoSkeleton = () => {
return (
<div>
<Skeleton variant="rect" width="100%">
<div style={{ paddingTop: "57%" }} />
</Skeleton>
</div>
);
};
export const ProfileStatusSkeleton = () => {
return (
<div>
<Box display="flex" alignItems="center">
<Box margin={1}>
<Skeleton variant="circle">
<Avatar />
</Skeleton>
</Box>
<Box margin={1} width="100%">
<Skeleton variant="text" width="80%">
<Typography>.</Typography>
</Skeleton>
</Box>
</Box>
<Box margin={1} display="flex">
<Box margin={1}>
<Skeleton variant="rect">
<Avatar variant="square" />
</Skeleton>
</Box>
<Box margin={1}>
<Skeleton variant="rect">
<Avatar variant="square" />
</Skeleton>
</Box>
</Box>
<Box margin={1}>
<Skeleton variant="text" width="90%">
<Typography>.</Typography>
</Skeleton>
</Box>
</div>
);
};
| 1aa9c4713f73c5da57ea6c0e3dc1c81351286aa8 | [
"JavaScript"
] | 13 | JavaScript | developerdesigner18/quotesbook | 920dcb3dd853871262af604d57ea9c29f5c44361 | dee7ee034af0d1397dbaec0d931f6051d5dc0bf3 |
refs/heads/master | <repo_name>matt-bernhardt/mitlib_self_quiz<file_sep>/src/Controller/QuizController.php
<?php
namespace Drupal\mitlib_self_quiz\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Defines HelloController class.
*/
class QuizController extends ControllerBase {
/**
* Display the custom quiz page.
*
* @return array
* Return markup array.
*/
public function content() {
$foo = [
'#type' => 'markup',
'#markup' => $this->t('Hello, updated custom quiz page!'),
];
$foo['#attached']['library'][] = 'mitlib_self_quiz/self_quiz';
print_r( $foo );
return $foo;
}
/**
* Display the markup.
*
* @return array
* Return markup array.
*/
public function settings() {
return [
'#type' => 'markup',
'#markup' => $this->t('Hello, Quiz settings page!'),
];
}
}
<file_sep>/js/self_quiz.js
/**
* @file
* Contains js for the accordion example.
*/
(function ($) {
'use strict';
console.log('self_quiz.js is ready...');
})(jQuery);
| 1319828c631c2eec202ee4f3c1ade0def2eaeb3c | [
"JavaScript",
"PHP"
] | 2 | PHP | matt-bernhardt/mitlib_self_quiz | 78f2c622f0f14ba4a8a6b95f3b35631c678f59b2 | 7272076d521e1795e9ae939a8f15674994da9220 |
refs/heads/master | <file_sep><?php
class SV_ThreadReplyBanner_DataWriter_ThreadBanner extends XenForo_DataWriter
{
const OPTION_THREAD = 'thread';
const OPTION_LOG_EDIT = 'logEdit';
const banner_length = 65536;
//const banner_length = 16777215;
protected function _getFields()
{
return [
'xf_thread_banner' => [
'thread_id' => ['type' => self::TYPE_UINT, 'required' => true],
'raw_text' => ['type' => self::TYPE_STRING, 'verification' => ['$this', '_verifyBannerText']],
'banner_state' => ['type' => self::TYPE_BOOLEAN, 'default' => 1],
'banner_user_id' => ['type' => self::TYPE_UINT, 'default' => XenForo_Visitor::getUserId()],
'banner_last_edit_date' => ['type' => self::TYPE_UINT, 'default' => 0],
'banner_last_edit_user_id' => ['type' => self::TYPE_UINT, 'default' => 0],
'banner_edit_count' => ['type' => self::TYPE_UINT_FORCED, 'default' => 0],
]
];
}
protected function _verifyBannerText(&$raw_text)
{
$raw_text = strval($raw_text);
if (strlen($raw_text) > self::banner_length)
{
$this->error(new XenForo_Phrase('please_enter_value_using_x_characters_or_fewer', ['count' => self::banner_length]));
return false;
}
return true;
}
protected function _getExistingData($data)
{
if (!$id = $this->_getExistingPrimaryKey($data, 'thread_id'))
{
return false;
}
return ['xf_thread_banner' => $this->_getThreadModel()->getRawThreadReplyBanner($id)];
}
protected function _getUpdateCondition($tableName)
{
return 'thread_id = ' . $this->_db->quote($this->getExisting('thread_id'));
}
protected function _getDefaultOptions()
{
$defaultOptions = parent::_getDefaultOptions();
$editHistory = XenForo_Application::getOptions()->editHistory;
$defaultOptions[self::OPTION_LOG_EDIT] = empty($editHistory['enabled']) ? false : $editHistory['enabled'];
$defaultOptions[self::OPTION_THREAD] = null;
return $defaultOptions;
}
protected function _preSave()
{
if ($this->isUpdate() && $this->isChanged('raw_text'))
{
if (!$this->isChanged('banner_last_edit_date'))
{
$this->set('banner_last_edit_date', XenForo_Application::$time);
if (!$this->isChanged('banner_last_edit_user_id'))
{
$this->set('banner_last_edit_user_id', XenForo_Visitor::getUserId());
}
}
if (!$this->isChanged('banner_edit_count'))
{
$this->set('banner_edit_count', $this->get('banner_edit_count') + 1);
}
}
if ($this->isChanged('banner_edit_count') && $this->get('banner_edit_count') == 0)
{
$this->set('banner_last_edit_date', 0);
}
if (!$this->get('banner_last_edit_date'))
{
$this->set('banner_last_edit_user_id', 0);
}
}
protected function _getThread()
{
$thread = $this->getOption(self::OPTION_THREAD);
if (empty($thread))
{
$thread = $this->_getThreadModel()->getThreadById($this->get('thread_id'));
$this->setOption(self::OPTION_THREAD, $thread);
}
return $thread;
}
protected function _postSave()
{
if ($this->isUpdate() && $this->isChanged('raw_text') && $this->getOption(self::OPTION_LOG_EDIT))
{
$this->_insertEditHistory();
}
$this->_db->query(
"UPDATE xf_thread
SET has_banner = ?
WHERE thread_id = ?",
[$this->get('banner_state'), $this->get('thread_id')]
);
$thread = $this->_getThread();
if ($this->isChanged('raw_text'))
{
XenForo_Model_Log::logModeratorAction('thread', $thread, 'replybanner', ['banner' => $this->get('raw_text')]);
}
if ($this->isChanged('banner_state') && !$this->get('banner_state'))
{
XenForo_Model_Log::logModeratorAction('thread', $thread, 'replybanner_deleted');
}
$this->_getThreadModel()->updateThreadBannerCache($this->get('thread_id'), $this->getMergedData());
}
protected function _postDelete()
{
$this->_db->query(
"UPDATE xf_thread
SET has_banner = 0
WHERE thread_id = ?",
[$this->get('thread_id')]
);
$thread = $this->_getThread();
XenForo_Model_Log::logModeratorAction('thread', $thread, 'replybanner_deleted');
$this->_getThreadModel()->updateThreadBannerCache($this->get('thread_id'), null);
}
protected function _insertEditHistory()
{
/** @var XenForo_DataWriter_EditHistory $historyDw */
$historyDw = XenForo_DataWriter::create('XenForo_DataWriter_EditHistory', XenForo_DataWriter::ERROR_SILENT);
$historyDw->bulkSet(
[
'content_type' => 'thread_banner',
'content_id' => $this->get('thread_id'),
'edit_user_id' => XenForo_Visitor::getUserId(),
'old_text' => $this->getExisting('raw_text')
]
);
$historyDw->save();
}
/**
* @return XenForo_Model|XenForo_Model_Thread|SV_ThreadReplyBanner_XenForo_Model_Thread
*/
protected function _getThreadModel()
{
return $this->getModelFromCache('XenForo_Model_Thread');
}
}
<file_sep><?php
class SV_ThreadReplyBanner_Installer
{
public static function install($existingAddOn, $addOnData)
{
$version = isset($existingAddOn['version_id']) ? $existingAddOn['version_id'] : 0;
$db = XenForo_Application::getDb();
$db->query(
"
CREATE TABLE IF NOT EXISTS xf_thread_banner (
thread_id INT UNSIGNED NOT NULL PRIMARY KEY,
raw_text MEDIUMTEXT,
banner_state TINYINT(3) NOT NULL DEFAULT 1,
banner_user_id INT NOT NULL DEFAULT 0,
banner_edit_count INT NOT NULL DEFAULT 0,
banner_last_edit_date INT NOT NULL DEFAULT 0,
banner_last_edit_user_id INT NOT NULL DEFAULT 0
) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci
"
);
SV_Utils_Install::addColumn('xf_thread', 'has_banner', 'TINYINT NOT NULL DEFAULT 0');
SV_Utils_Install::addColumn('xf_thread_banner', 'banner_state', 'TINYINT(3) NOT NULL DEFAULT 1');
SV_Utils_Install::addColumn('xf_thread_banner', 'banner_user_id', 'INT NOT NULL DEFAULT 0');
SV_Utils_Install::addColumn('xf_thread_banner', 'banner_edit_count', 'INT NOT NULL DEFAULT 0');
SV_Utils_Install::addColumn('xf_thread_banner', 'banner_last_edit_date', 'INT NOT NULL DEFAULT 0');
SV_Utils_Install::addColumn('xf_thread_banner', 'banner_last_edit_user_id', 'INT NOT NULL DEFAULT 0');
$db->query(
"
INSERT IGNORE INTO xf_content_type
(content_type, addon_id, fields)
VALUES
('thread_banner', 'SV_ThreadReplyBanner', '')
"
);
$db->query(
"
INSERT IGNORE INTO xf_content_type_field
(content_type, field_name, field_value)
VALUES
('thread_banner', 'edit_history_handler_class', 'SV_ThreadReplyBanner_EditHistoryHandler_ThreadBanner')
"
);
if ($version == 0)
{
$db->query(
"
INSERT IGNORE INTO xf_permission_entry (user_group_id, user_id, permission_group_id, permission_id, permission_value, permission_value_int)
SELECT DISTINCT user_group_id, user_id, convert(permission_group_id USING utf8), 'sv_replybanner_show', permission_value, permission_value_int
FROM xf_permission_entry
WHERE permission_group_id = 'forum' AND permission_id IN ('postReply')
"
);
$db->query(
"
INSERT IGNORE INTO xf_permission_entry (user_group_id, user_id, permission_group_id, permission_id, permission_value, permission_value_int)
SELECT DISTINCT user_group_id, user_id, convert(permission_group_id USING utf8), 'sv_replybanner_manage', permission_value, permission_value_int
FROM xf_permission_entry
WHERE permission_group_id = 'forum' AND permission_id IN ('warn','editAnyPost','deleteAnyPost')
"
);
}
if ($version < 1000402)
{
// clean-up orphaned thread banners.
$db->query(
'
DELETE
FROM xf_thread_banner
WHERE NOT EXISTS (SELECT thread_id FROM xf_thread)
'
);
}
}
public static function uninstall()
{
$db = XenForo_Application::get('db');
$db->query(
"
DROP TABLE IF EXISTS xf_thread_banner
"
);
$db->query(
"
DELETE FROM xf_permission_entry
WHERE permission_group_id = 'forum' AND permission_id IN ('sv_replybanner_show', 'sv_replybanner_manage')
"
);
$db->query(
"
DELETE
FROM xf_content_type
WHERE content_type = 'thread_banner'
"
);
$db->query(
"
DELETE
FROM xf_content_type_field
WHERE content_type = 'thread_banner'
"
);
$db->query(
"
DELETE FROM xf_edit_history
WHERE content_type = 'thread_banner'
"
);
SV_Utils_Install::dropColumn('xf_thread', 'has_banner');
}
}
<file_sep><?php
class SV_ThreadReplyBanner_XenForo_Model_Thread extends XFCP_SV_ThreadReplyBanner_XenForo_Model_Thread
{
/**
* @param int $threadId
* @return array
*/
public function getRawThreadReplyBanner($threadId)
{
return $this->_getDb()->fetchRow("SELECT * FROM xf_thread_banner WHERE thread_id = ?", $threadId);
}
/**
* @return XenForo_BbCode_Parser
*/
public function getThreadReplyBannerParser()
{
return XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Base'));
}
/**
* @param XenForo_BbCode_Parser $bbCodeParser
* @param array $banner
* @return string
*/
public function renderThreadReplyBanner(XenForo_BbCode_Parser $bbCodeParser, array $banner)
{
return $bbCodeParser->render($banner['raw_text']);
}
/**
* @param int $threadId
* @return string
*/
public function getThreadReplyBannerCacheId($threadId)
{
return 'thread_banner_' . $threadId;
}
/**
* @param $thread
* @param array|null $nodePermissions
* @param array|null $viewingUser
* @return null|string
*/
public function getThreadReplyBanner($thread, array $nodePermissions = null, array $viewingUser = null)
{
if (empty($thread['has_banner']))
{
return null;
}
$this->standardizeViewingUserReferenceForNode($thread['node_id'], $viewingUser, $nodePermissions);
if (!XenForo_Permission::hasContentPermission($nodePermissions, 'sv_replybanner_show') &&
!XenForo_Permission::hasContentPermission($nodePermissions, 'sv_replybanner_manage'))
{
return null;
}
if ($cacheObject = $this->_getCache(true))
{
$cacheId = $this->getThreadReplyBannerCacheId($thread['thread_id']);
if ($bannerText = $cacheObject->load($cacheId, true))
{
return $bannerText;
}
}
$bannerText = '';
$banner = $this->getRawThreadReplyBanner($thread['thread_id']);
if (!empty($banner['banner_state']))
{
$bbCodeParser = $this->getThreadReplyBannerParser();
$bannerText = $this->renderThreadReplyBanner($bbCodeParser, $banner);
if ($cacheObject)
{
$cacheObject->save($bannerText, $cacheId, [], 86400);
}
}
return $bannerText;
}
/**
* @param int $threadId
* @param array $banner
*/
public function updateThreadBannerCache($threadId, array $banner = null)
{
$cache = $this->_getCache();
if (!$cache)
{
return;
}
$cacheId = $this->getThreadReplyBannerCacheId($threadId);
if ($banner === null || empty($banner['banner_state']))
{
$cache->remove($cacheId);
}
else
{
$bbCodeParser = $this->getThreadReplyBannerParser();
$bannerText = $this->renderThreadReplyBanner($bbCodeParser, $banner);
$cache->save($bannerText, $cacheId, [], 86400);
}
}
/**
* @param array $thread
* @param array $forum
* @param string $errorPhraseKey
* @param array|null $nodePermissions
* @param array|null $viewingUser
* @return bool
* @throws XenForo_Exception
*/
public function canManageThreadReplyBanner(array $thread, array $forum, &$errorPhraseKey = '', array $nodePermissions = null, array $viewingUser = null)
{
$this->standardizeViewingUserReferenceForNode($thread['node_id'], $viewingUser, $nodePermissions);
return XenForo_Permission::hasContentPermission($nodePermissions, 'sv_replybanner_manage');
}
}
<file_sep><?php
class SV_ThreadReplyBanner_XenForo_ControllerPublic_Thread extends XFCP_SV_ThreadReplyBanner_XenForo_ControllerPublic_Thread
{
public function actionReplyBannerHistory()
{
$this->_request->setParam('content_type', 'thread_banner');
$this->_request->setParam('content_id', $this->_input->filterSingle('thread_id', XenForo_Input::UINT));
return $this->responseReroute(
'XenForo_ControllerPublic_EditHistory',
'index'
);
}
public function actionEdit()
{
$response = parent::actionEdit();
if ($response instanceof XenForo_ControllerResponse_View &&
!empty($response->params['thread']) &&
!empty($response->params['forum']))
{
/** @var SV_ThreadReplyBanner_XenForo_Model_Thread $threadModel */
$threadModel = $this->_getThreadModel();
if ($threadModel->canManageThreadReplyBanner($response->params['thread'], $response->params['forum']))
{
$response->params['canEditThreadReplyBanner'] = true;
$response->params['thread']['rawbanner'] = $threadModel->getRawThreadReplyBanner($response->params['thread']['thread_id']);
}
}
return $response;
}
public function actionSave()
{
SV_ThreadReplyBanner_Globals::$banner = [
'raw_text' => $this->_input->filterSingle('thread_reply_banner', XenForo_Input::STRING),
'banner_state' => $this->_input->filterSingle('thread_banner_state', XenForo_Input::BOOLEAN),
];
return parent::actionSave();
}
public function actionIndex()
{
$response = parent::actionIndex();
if ($response instanceof XenForo_ControllerResponse_View && !empty($response->params['thread']))
{
/** @var SV_ThreadReplyBanner_XenForo_Model_Thread $threadModel */
$threadModel = $this->_getThreadModel();
$response->params['thread']['banner'] = $threadModel->getThreadReplyBanner($response->params['thread']);
}
return $response;
}
public function actionAddReply()
{
$response = parent::actionAddReply();
if ($response instanceof XenForo_ControllerResponse_View && !empty($response->params['thread']))
{
/** @var SV_ThreadReplyBanner_XenForo_Model_Thread $threadModel */
$threadModel = $this->_getThreadModel();
$response->params['thread']['banner'] = $threadModel->getThreadReplyBanner($response->params['thread']);
}
return $response;
}
public function actionReply()
{
$response = parent::actionReply();
if ($response instanceof XenForo_ControllerResponse_View && !empty($response->params['thread']))
{
/** @var SV_ThreadReplyBanner_XenForo_Model_Thread $threadModel */
$threadModel = $this->_getThreadModel();
$response->params['thread']['banner'] = $threadModel->getThreadReplyBanner($response->params['thread']);
}
return $response;
}
}
<file_sep><?php
class XFCP_SV_ThreadReplyBanner_XenForo_ControllerPublic_Thread extends XenForo_ControllerPublic_Thread {}
class XFCP_SV_ThreadReplyBanner_XenForo_DataWriter_Discussion_Thread extends XenForo_DataWriter_Discussion_Thread {}
class XFCP_SV_ThreadReplyBanner_XenForo_Model_Thread extends XenForo_Model_Thread {}
<file_sep><?php
class SV_ThreadReplyBanner_EditHistoryHandler_ThreadBanner extends XenForo_EditHistoryHandler_Abstract
{
protected $_prefix = 'threads';
protected function _getContent($contentId, array $viewingUser)
{
$threadModel = $this->_getThreadModel();
$thread = $threadModel->getThreadById(
$contentId,
[
'join' => XenForo_Model_Thread::FETCH_FORUM |
XenForo_Model_Thread::FETCH_FORUM_OPTIONS |
XenForo_Model_Thread::FETCH_USER,
'permissionCombinationId' => $viewingUser['permission_combination_id']
]
);
if ($thread)
{
$thread['permissions'] = XenForo_Permission::unserializePermissions($thread['node_permission_cache']);
$thread['reply_banner'] = $threadModel->getRawThreadReplyBanner($contentId);
}
return $thread;
}
protected function _canViewHistoryAndContent(array $content, array $viewingUser)
{
$threadModel = $this->_getThreadModel();
return $threadModel->canViewThreadAndContainer($content, $content, $null, $content['permissions'], $viewingUser) &&
$threadModel->canManageThreadReplyBanner($content, $content, $null, $content['permissions'], $viewingUser);
}
protected function _canRevertContent(array $content, array $viewingUser)
{
$threadModel = $this->_getThreadModel();
return $threadModel->canManageThreadReplyBanner($content, $content, $null, $content['permissions'], $viewingUser);
}
public function getText(array $content)
{
//$bbCodeParser = $this->getThreadReplyBannerParser();
//$bannerText = $this->renderThreadReplyBanner($bbCodeParser, $content['reply_banner']);
return htmlspecialchars($content['reply_banner']['raw_text']);
}
public function getTitle(array $content)
{
//return new XenForo_Phrase('post_in_thread_x', array('title' => $content['title']));
return htmlspecialchars($content['title']); // TODO
}
public function getBreadcrumbs(array $content)
{
/* @var $nodeModel XenForo_Model_Node */
$nodeModel = XenForo_Model::create('XenForo_Model_Node');
$node = $nodeModel->getNodeById($content['node_id']);
if ($node)
{
$crumb = $nodeModel->getNodeBreadCrumbs($node);
$crumb[] = [
'href' => XenForo_Link::buildPublicLink('full:threads', $content),
'value' => $content['title']
];
return $crumb;
}
else
{
return [];
}
}
public function getNavigationTab()
{
return 'forums';
}
public function formatHistory($string, XenForo_View $view)
{
return htmlspecialchars($string);
}
public function revertToVersion(array $content, $revertCount, array $history, array $previous = null)
{
$banner = $content['reply_banner'];
/** @var SV_ThreadReplyBanner_DataWriter_ThreadBanner $dw */
$dw = XenForo_DataWriter::create('SV_ThreadReplyBanner_DataWriter_ThreadBanner', XenForo_DataWriter::ERROR_SILENT);
$dw->setExistingData($banner);
$dw->set('raw_text', $history['old_text']);
$dw->set('banner_edit_count', $dw->get('thread_title_edit_count') + 1);
if ($dw->get('banner_edit_count'))
{
$dw->set('banner_last_edit_date', $previous['edit_date']);
$dw->set('banner_last_edit_user_id', $previous['edit_user_id']);
}
return $dw->save();
}
protected $_threadModel = null;
/**
* @return SV_ThreadReplyBanner_XenForo_Model_Thread|XenForo_Model_Thread|XenForo_Model
* @throws XenForo_Exception
*/
protected function _getThreadModel()
{
if ($this->_threadModel === null)
{
$this->_threadModel = XenForo_Model::create('XenForo_Model_Thread');
}
return $this->_threadModel;
}
}
<file_sep><?php
class SV_ThreadReplyBanner_Listener
{
public static function load_class($class, array &$extend)
{
$extend[] = 'SV_ThreadReplyBanner_' . $class;
}
}
<file_sep>XenForo-ThreadReplyBanner
======================
Displayed per-thread banners above the editor for users.
- In both Quick Reply, and preview reply views.
- Only fetches the thread reply banner when viewing the thread.
- Text may be up to 65536 characters long, and supports bbcode.
- Supports caching rendered bbcode.
- Logs modifications of these banners to the Moderator Logs.
New Permission to control who can manage and see reply banners.
- View Thread Reply Banner - default - to users/groups who can reply.
- Manage Thread Reply Banner - default - to users/groups who can delete/edit all posts, or warn.
<file_sep><?php
class SV_ThreadReplyBanner_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_ThreadReplyBanner_XenForo_DataWriter_Discussion_Thread
{
/** @var SV_ThreadReplyBanner_DataWriter_ThreadBanner */
protected $bannerDw = null;
protected function _discussionPreSave()
{
parent::_discussionPreSave();
if (empty(SV_ThreadReplyBanner_Globals::$banner) || !$this->isUpdate())
{
return;
}
/** @var SV_ThreadReplyBanner_XenForo_Model_Thread $threadModel */
$threadModel = $this->_getThreadModel();
$thread = $this->getMergedData();
$forum = $this->_getForumData();
if (empty($forum) || !$threadModel->canManageThreadReplyBanner($thread, $forum))
{
return;
}
$banner = $threadModel->getRawThreadReplyBanner($this->get('thread_id'));
$this->bannerDw = XenForo_DataWriter::create('SV_ThreadReplyBanner_DataWriter_ThreadBanner', self::ERROR_SILENT);
$this->bannerDw->setOption(SV_ThreadReplyBanner_DataWriter_ThreadBanner::OPTION_THREAD, $this->getMergedData());
if ($banner)
{
$this->bannerDw->setExistingData($banner, true);
}
else
{
// do not insert the banner row
if (empty(SV_ThreadReplyBanner_Globals::$banner['raw_text']))
{
$this->bannerDw = null;
return;
}
$this->bannerDw->set('thread_id', $this->get('thread_id'));
}
$this->bannerDw->bulkSet(SV_ThreadReplyBanner_Globals::$banner);
$this->bannerDw->preSave();
$this->_errors += $this->bannerDw->getErrors();
}
protected function _postSaveAfterTransaction()
{
parent::_postSaveAfterTransaction();
if ($this->bannerDw && $this->bannerDw->hasChanges())
{
$this->bannerDw->save();
}
}
protected function _discussionPostDelete()
{
parent::_discussionPostDelete();
/** @var SV_ThreadReplyBanner_XenForo_Model_Thread $threadModel */
$threadModel = $this->_getThreadModel();
$banner = $threadModel->getRawThreadReplyBanner($this->get('thread_id'));
if ($banner)
{
/** @var SV_ThreadReplyBanner_DataWriter_ThreadBanner $dw */
$dw = XenForo_DataWriter::create('SV_ThreadReplyBanner_DataWriter_ThreadBanner', self::ERROR_SILENT);
$dw->setExistingData($this->get('thread_id'));
$dw->setOption(SV_ThreadReplyBanner_DataWriter_ThreadBanner::OPTION_THREAD, $this->getMergedData());
$dw->delete();
}
}
}
| 668ef462ff2fa3d919db96a48c362c6605d33160 | [
"Markdown",
"PHP"
] | 9 | PHP | Xon/XenForo-ThreadReplyBanner | f93e17fa1b4046e5fc74afa305171ccd72984ff9 | 70f5855461e3a186dee754cc8790f35bd55420df |
refs/heads/master | <file_sep>package method_drill;
public class Question11 {
//■ 引数列がクラスの参照(Person クラスを用いる例) 戻り値なし
//処理の内容: "こんにちは xx さん" というメッセージを出力する。
//xx には引数列で渡された Person オブジェクトの名前( name )を入れる。
//ヒント: Person クラスのインスタンス変数 name は private 修飾子が付いているので、
//直接参照できない。 getName メソッドを用いて取得する。
static void printMessage(Person person) {
String name = person.getName();
System.out.println("こんにちは" + name + "さん");
}
public static void main(String[] args) {
Person person = new Person("aaaa", 25);
printMessage(person);
}
}
<file_sep>package method_drill;
public class Question03 {
//戻り値なし 引数2
static void printMessage(String message, int count) {
//変数iが、引数countより小さいときはメッセージ出力(countより大きくなったら抜ける)
for (int i = 0; i < count; i++) {
System.out.println(message);
}
}
public static void main(String[] args) {
// Question03 のメソッドの動作検証
printMessage("Hello", 5);
}
}
<file_sep>package method_drill;
public class Question05 {
//戻り値boolean 引数あり
static boolean isEvenNumber(int value) {
//引数が偶数=true、 奇数=false を返す
if (value % 2 == 0) {
return true;
} else
return false;
}
public static void main(String[] args) {
// Question05 動作検証
boolean number = isEvenNumber(2000);
System.out.println(number);
}
}
<file_sep>package method_drill;
public class Question09 {
static String getLongestString(String[] array) {
//引数で受け取る配列の要素のうち、最も文字数の大きい文字列を返す。
//文字数が同じものが複数存在する場合は、配列の後ろの方の要素を優先する。
//引数の文字列を配列に入れる
//配列カウント
int count = 0;
//maxの文字数を格納
int max = 0;
for (int i = 0; i < array.length;) {
//文字列を入れる(比較用)
String character = array[i];
//文字数を比較して、max以上だったら文字数と配列の要素数を保持
if (max <= character.length()) {
max = character.length();
count = i;
}
++i;
}
//文字列を返す
return array[count];
}
public static void main(String[] args) {
// Question09 動作検証
String data[] = { "aa", "bb", "ccc", "d", "eee", "ff" };
//文字列の出力
String character = getLongestString(data);
System.out.println(character);
}
}
<file_sep>package method_drill;
public class Question04 {
//引数列なし、戻り値あり
static String getMessage() {
return "よろしくおねがいします";
}
public static void main(String[] args) {
// Question04 動作検証
String message = getMessage();
System.out.println(message);
}
}
<file_sep>package method_drill;
public class Question07 {
//引数列が複数、戻り値あり
static String getMessage(String name, boolean isKid) {
if (isKid == true) {
return "こんにちは。" + name + "ちゃん。";
}
return "こんにちは。" + name + "さん。";
}
public static void main(String[] args) {
//Question07 動作検証
String message = getMessage("山田", false);
System.out.println(message);
}
}
<file_sep>package method_drill;
public class Question01 {
//戻り値なし 引数あり
static void printMessage(String message) {
System.out.println(message);
}
public static void main(String[] args) {
// Question01 のメソッドの動作検証
printMessage("Hello");
}
}
| fb458e7dce8a9d9e3970af0d0e5c801c409ea25c | [
"Java"
] | 7 | Java | soejima-reona/MethodDrill2 | b8283cd50b89dc941b668032ceee1d693ada6941 | 84eb6d9b357cf4edc2a06b26f936d57d4032f6f6 |
refs/heads/master | <repo_name>ay-b/docker<file_sep>/balancer_plus_3_nginxs_demo.sh
#!/bin/sh
set -e
i=$1
if [ -z $1 ]; then
echo "Usage: $0 [number of nginx containers to launch]"
exit 1
fi
apk add docker
service docker start
rc-update add docker
docker run -d --name balancer -p 80:80 suncheez/nginx:balancer
for n in `seq 1 $1`;
do
echo Container: $n
docker run -d --name nginx$n suncheez/nginx:balancer
done<file_sep>/README.md
# docker
Docker images for various use
Use with caution<file_sep>/grav/rungrav.sh
#/bin/bash
yum update -y
yum upgrade -y
yum install epel-release -y
yum install docker docker-compose wget git -y
chkconfig docker on
service docker start
git clone ***
wget https://getgrav.org/download/core/grav-admin/1.3.1 -O grav.zip
unzip grav.zip
mv grav-admin/* html/
| 8a906ecb3c9212e56401f06fc292c0cfc0612f4d | [
"Markdown",
"Shell"
] | 3 | Shell | ay-b/docker | 45e0fe58b17066a2daa7ae50f84ecee12dcaac44 | 713a57e5d5bb5098ac4133a289d766e06eb96985 |
refs/heads/main | <repo_name>mikeriley131/gatsby-starter<file_sep>/src/components/header.jsx
import React from 'react';
import { Link } from 'gatsby';
import logo from '../images/pullingteethlogo.svg';
const Header = () => (
<header className="header" role="banner">
<div className="container">
<Link to="/">
<img
src={logo}
alt="Pulling Teeth logo"
loading="lazy"
width="1200"
height="368"
decoding="async"
/>
</Link>
</div>
</header>
);
export default Header;
<file_sep>/src/components/layout.jsx
import React, {Fragment} from 'react'
import PropTypes from 'prop-types'
import { StaticQuery, graphql } from 'gatsby'
import '../styles/main.scss'
import Header from './header'
const Layout = ({ children }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`}
render={data => (
<Fragment>
<a className="skip-link" href="#main">
skip to main content
</a>
<Header siteTitle={data.site.siteMetadata.title} />
<main className="main" id="main" role="main">
{children}
</main>
</Fragment>
)}
/>
)
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout;
<file_sep>/src/pages/index.jsx
import React from 'react';
// import { Link } from 'gatsby';
import Layout from '../components/layout';
import SEO from '../components/seo';
import stronethrowersShirtFront from '../images/pt-stonethrowers-shirt-front.png';
import stronethrowersShirtBack from '../images/pt-stonethrowers-shirt-back.png';
const IndexPage = () => (
<Layout>
<SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
<div className="container">
<h1 className="visuallyhidden">Pulling Teeth</h1>
<section>
<h2 className="h1">Stonethrowers shirt</h2>
<p>
We’re not a band, but if we can sell some shirts to benefit an
organization providing support to LGBTQ youth, we’re happy to do
so. Proceeds benefit{' '}
<a href="https://www.thetrevorproject.org/">the Trevor Project</a>.
Design by{' '}
<a href="https://www.instagram.com/onetricpony/"><NAME></a>.
</p>
<div className="flex-wrapper flex-wrapper--two">
<div>
<img
src={stronethrowersShirtFront}
alt="front view of black shirt with Pulling Teeth logo and text that reads 'What are you so afraid of?'"
loading="lazy"
width="600"
height="599"
decoding="async"
/>
</div>
<div>
<img
src={stronethrowersShirtBack}
alt="back view of black shirt with the lyrics to the song 'Stonethrowers'."
loading="lazy"
width="600"
height="599"
decoding="async"
/>
</div>
</div>
</section>
<section>
<h2 className="h1">Heretic Video</h2>
<iframe
width="1120"
height="630"
src="https://www.youtube.com/embed/9inzBm9Y-z0"
title="YouTube video player"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
/>
</section>
<section>
<h2 className="h1">Coming Soon</h2>
<ul>
<li>shirt gallery</li>
<li>flyer gallery</li>
<li>some other stuff</li>
</ul>
</section>
</div>
</Layout>
);
export default IndexPage;
<file_sep>/gatsby-config.js
module.exports = {
siteMetadata: {
title: `Pulling Teeth`,
description: `Archive of music, merch, flyers, and more for Pulling Teeth - Baltimore hardcore.`,
siteUrl: `https://pullingteethmd.com`,
socialImage: `ABSOLUTE PATH TO IMAGE IN STATIC FOLDER`,
},
plugins: [
`gatsby-plugin-remove-trailing-slashes`,
`gatsby-plugin-react-helmet`,
`gatsby-plugin-sass`,
`gatsby-plugin-sitemap`,
{
resolve: 'gatsby-plugin-web-font-loader',
options: {
google: {
families: ['Cinzel Decorative:700,900', 'PT Serif: 400, 400i, 700'],
},
// custom: {
// families: ['CUSTOMFONT1, CUSTOMFONT2'],
// urls: ['/fonts/fonts.css'],
// },
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Pulling Teeth - Baltimore Hardcore`,
short_name: `Pulling Teeth`,
start_url: `/`,
background_color: `#111111`,
theme_color: `HEX VALUE`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-plugin-accessibilityjs`,
options: {
injectStyles: false,
errorClassName: false,
},
},
// {
// resolve: `gatsby-plugin-google-tagmanager`,
// options: {
// id: 'GTM-ID-STRING',
// includeInDevelopment: true
// }
// }
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.app/offline
// 'gatsby-plugin-offline',
],
};
<file_sep>/TODO.md
- set up development environment
- update packages
- delete cache and git folders
- create git repo
- https://kbroman.org/github_tutorial/pages/init.html
- yarn install
- yarn start
- ensure site runs as expected
- add custom fonts
- complete gatsby-config file
- restart environment
- update variables.scss file
- add logo as SVG asset
- header component
- footer component
- homepage
- interior pages(s)
- add site content
- static and/or via WordPress API
- push to Pyrographic Netlify account for dev URL
- [WordPress] create a WP instance on client's host
- SSL required
- [WordPress] add plugins
- Advanced Custom Fields PRO
- All-in-One WP Migration
- All-in-One WP Migration Unlimited Extension
- Classic Editor
- Custom Post Type UI
- Deploy with NetlifyPress
- Duplicate Page
- UpdraftPlus - Backup/Restore
- WP Gatsby
- WP GraphQL
- WPGraphQL for Advanced Custom Fields
- [WordPress] add custom fields
- [WordPress] add content
- create interior page template(s) used in gatsby-node
- get content from WP API
- add schema.org metadata
- custom 404 page or redirect to homepage
- create sitemap
- gatsby-plugin-sitemap
- cross-browser testing
- Lighthouse audits
- accessibility
- performance
- manual accessibility audits
- interactive elements navigable via keyboard?
- hidden menus?
- overall audit
- https://sonarwhal.com/scanner
- google analytics scripts added
- remove unused boilerplate files and assets (images, icons, fonts, etc.)
- update gatsby-config file for launch
- favicon
- create Open Graph/Twitter Card image (1200px x 1200px)
- connect to any social media sites
- update README
- [WordPress] set up Updraft Plus backups
- final payment
- migrate to client's Netlify account
- DNS updates to client's domain
- launch
- create GitHub organization for client and migrate repo
- client documentation
- client video training session
- delete TODO
| 6129eb19b3430a4a709440157fbd2b4e722cada5 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | mikeriley131/gatsby-starter | 379a184a65f1846631ab9051e2a5cca500db9360 | c115a9368bb48315b181d62a3112f52bb36ac8e7 |
refs/heads/master | <repo_name>antonmenykhov/calc<file_sep>/public/data.php
<?php
require_once __DIR__ . '/SimpleXLSX.php';
function getBk6()
{
class A
{
}
;
if ($xlsx = SimpleXLSX::parse('table.xlsx')) {
$massiv = $xlsx->rows(0);
$currentArr = new A;
$currentVar = new A;
$currentCost = new A;
$fullArr = [];
for ($i=0; $i<=count($massiv); $i++) {
if ((($massiv[$i][1] === "Раздел") or ($i==count($massiv)))){
$oldArr = clone $currentArr;
array_push($fullArr, $oldArr );
$currentArr->name = $massiv[$i][0];
$currentArr->arr = [];
}elseif
(($massiv[$i][2] === "Варианты") or ($massiv[$i][2] === "Общее") or ($massiv[$i][2] === "Количество") or ($massiv[$i][2] === "Опции"))
{
$oldVar = clone $currentVar;
array_push($currentArr->arr, $oldVar);
$currentVar->name=$massiv[$i][1];
$currentVar->type=$massiv[$i][2];
$currentVar->arr = [];
}else{
$currentCost->name = $massiv[$i][1];
$currentCost->price = $massiv[$i][7];
$currentCost->number = $massiv[$i][5];
$oldCost = clone $currentCost;
array_push($currentVar->arr, $oldCost);
}
}
return $fullArr;
} else {
echo SimpleXLSX::parseError();
}
}
function getBk8()
{
class A
{
}
;
$vars = new A;
$kolvo = new A;
$names = new A;
if ($xlsx = SimpleXLSX::parse('table.xlsx')) {
$massiv = $xlsx->rows();
for ($i = 0; $i < count($massiv); $i++) {
$key = $massiv[$i][3];
$vars->$key = $massiv[$i][11];
$kolvo->$key = $massiv[$i][10];
$names->$key = $massiv[$i][2];
}
$all = array($vars, $kolvo, $names);
return $all;
} else {
echo SimpleXLSX::parseError();
}
}
echo json_encode(getBk6());
?> | 93b5f304670fb9ac42f87be7955cec2728232c6f | [
"PHP"
] | 1 | PHP | antonmenykhov/calc | 4df410cf5ea8ed594b0825c81e5e6647bb5ee907 | 2d362ea406367fac6596ee80c59ddd6ba1c83a89 |
refs/heads/master | <file_sep>
import tkinter as tk
import keyboard
import random as r
# window
SIZE = 500
# background + outline of the blocks
bgColor = "grey"
# volba viditelnosti animace gridu
wait = True
# pocet kostek podel jedne osy
# liche - at je spawn ve stredu
size = 19
# cim mensi tim rychlejsi, musi byt na deleni 10_000
speed = 2000
# Non variables - set once and leave untouched
block = SIZE / size
snake = []
count = 0
snakeColor = "green2"
c = tk.Canvas(width=SIZE, height=SIZE, background=bgColor)
c.pack()
# animace gridu... (ctvercovane pozadi)
for i in range(size):
if i % 2 == 0:
for j in range(size):
c.create_rectangle(block*j, block*i, block*(j+1), block*(i+1), fill="black", outline=bgColor)
if wait == True:
c.after(1)
c.update()
else:
for j in range(size-1, -1, -1):
c.create_rectangle(block*j, block*i, block*(j+1), block*(i+1), fill="black", outline=bgColor)
if wait == True:
c.after(1)
c.update()
# prodluz hada
def addToSnake(x, y):
global snake, block, size, bgColor, c, snakeColor
pos = [x, y]
x = block*(size//2) + block * x
y = block*(size//2) + block * y
snake.append([c.create_rectangle(x, y, x+block, y+block, fill=snakeColor, outline=bgColor), pos])
# vytvor jablko na nahodne pozici, jine nez na predchozi a v hadovi
# pokud je game-over zmeni se barva hada a vyresetuje se
def getApple(prev):
global snake, block, bgColor, c, size, snakeColor
ls = []
for i in range(len(snake)):
ls.append(snake[i][1])
x = r.randint(0-size//2, size//2)
y = r.randint(0-size//2, size//2)
while [x, y] in ls or [x, y] == prev:
x = r.randint(0-size//2, size//2)
y = r.randint(0-size//2, size//2)
if len(snake) >= (size**2)-1:
for i in range(len(snake)):
if not snake[i] == snake[-2]:
c.delete(snake[i][0])
snake = [snake[-2]]
if snakeColor == "blue2":
snakeColor = "green2"
elif snakeColor == "green2":
snakeColor = "blue2"
pos = [x, y]
x = block*(size//2) + block * x
y = block*(size//2) + block * y
return [c.create_rectangle(x, y, x+block, y+block, fill="red2", outline=bgColor), pos]
# get starting position - snake's head
addToSnake(0, 0)
# create the apple
apple = getApple([0, 0])
# cekani na start
stop = False
while not stop:
c.update()
if keyboard.is_pressed('escape'):
exit()
if keyboard.is_pressed('h'):
stop = True
if keyboard.is_pressed('j'):
stop = True
if keyboard.is_pressed('k'):
stop = True
if keyboard.is_pressed('l'):
stop = True
# game loop
while True:
# updating canvas and the count
c.update()
count += 1
if count >= 10000: count = 0
# close windows
if keyboard.is_pressed('escape'):
exit()
# get direction
if keyboard.is_pressed('h'):
direction = "left"
if keyboard.is_pressed('j'):
direction = "down"
if keyboard.is_pressed('k'):
direction = "up"
if keyboard.is_pressed('l'):
direction = "right"
# refresh
if count % speed == 0:
# pohyb
if direction == "left":
if not snake[-1][1][0] < 0-size//2+1:
addToSnake(snake[-1][1][0]-1, snake[-1][1][1])
else:
addToSnake(size//2, snake[-1][1][1])
elif direction == "down":
if not snake[-1][1][1] > size//2-1:
addToSnake(snake[-1][1][0], snake[-1][1][1]+1)
else:
addToSnake(snake[-1][1][0], 0-size//2)
elif direction == "up":
if not snake[-1][1][1] < 0-size//2+1:
addToSnake(snake[-1][1][0], snake[-1][1][1]-1)
else:
addToSnake(snake[-1][1][0], size//2)
elif direction == "right":
if not snake[-1][1][0] > size//2-1:
addToSnake(snake[-1][1][0]+1, snake[-1][1][1])
else:
addToSnake(0-size//2, snake[-1][1][1])
# formace listu souradnic vlastnich bunek
ls = []
for i in range(len(snake)-1):
ls.append(snake[i][1])
# kolize s jablkem - pridani delky (vlastne spis neubrani)
if snake[-1][1] == apple[1]:
c.delete(apple[0])
apple = getApple(apple[1])
else:
# probehne vzdy pokud nesni jablko - ubrani na delce
c.delete(snake[0][0])
del snake[0]
# kolize sam se sebou
if snake[-1][1] in ls:
for i in range(len(snake)):
if not snake[i] == snake[-2]:
c.delete(snake[i][0])
snake = [snake[-2]]
| bb5ffc279afc571c448e346021a33eb3cf7a8613 | [
"Python"
] | 1 | Python | vojtaborsky/snake | d35b6e4f90228d0b55a4ccda8e0a9206df5c3d9a | 9f6a191ca0ef02d2c11d6ab791cce46e8e691b87 |
refs/heads/master | <file_sep>/**
* listaEnlazada.h
*
* Descripción: Este es el archivo cabecera para listaEnlazada.c
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 27-04-2015.
*/
enum NivelDeComplejidad {basico, intermedio, avanzado};
typedef struct pregunta{
int codigo;
char area;
enum NivelDeComplejidad complejidad;
char strings[4][100];
int respuestaCorrecta;
} PREGUNTA;
typedef struct lista {
PREGUNTA preg;
struct lista *sig;
struct lista *ant;
} LISTA;
void insertar(LISTA **ultimo, PREGUNTA pregunta);
LISTA **buscar(LISTA **ultimo, int codigo);
int eliminar(LISTA **list, int codigo);
<file_sep>#!/bin/bash
find . -name $1 -print
#fin del script
<file_sep>/**
* Bases.c
*
* Descripción: Este archivo contiene las funciones y procedimientos principales
* para el manejo de las preguntas en las bases de datos.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 27-04-2015.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "listaEnlazada.h"
/*
* LeerArchivo es el procedimiento que abre el archivo, crea una pregunta, lee
* línea por línea y los datos los guarda en la pregunta, ésta se insera en
* alguna de las tres listas enlazadas que están en memoria y al acabarse el
* archivo, lo cierra.
* Argumentos: nombre, es un String que tiene el nombre del archivo.
* listas, es un apuntador al arreglo de listas enlazadas en memoria.
* Retorna: nada, se modifican directamente las listas enlazadas.
*/
void LeerArchivo(char nombre[], LISTA **listas){
FILE *filepointer;
PREGUNTA P;
filepointer = fopen(nombre,"r");
if(filepointer == NULL){
perror("Lo lamentamos");
printf("Vuelva a ejecutar el programa con el nombre del archivo correcto.\n");
printf("errno = %d\n",errno);
exit(1);
}
printf("Abriendo el archivo...\n");
printf("Leyendo los datos de la base de datos...\n");
while(
fscanf(filepointer,"%d %d %c \"%[^\"]\" \"%[^\"]\" \"%[^\"]\" \"%[^\"]\" %d ",&P.codigo,&P.complejidad,&P.area,P.strings[0],P.strings[1],P.strings[2],P.strings[3],&P.respuestaCorrecta) != EOF){
insertar(&listas[P.complejidad],P);
}
fclose(filepointer);
printf("Hemos terminado de leer el archivo.\n");
}
/*
* MostrarPregunta le muestra al usuario en consola los datos de la pregunta que
* se recibe de argumento.
* Argumentos: P, es la pregunta que se desea mostrar al usuario.
* Retorna: nada, sólo se imprime en pantalla los atributos de la pregunta.
*/
void mostrarPregunta(PREGUNTA P){
printf("\tCódigo: %d\n",P.codigo);
printf("\tÁrea: %c\n",P.area);
printf("\tNivel de complejidad: %d\n",P.complejidad);
printf("\tPregunta: %s\n",P.strings[0]);
printf("\tRespuesta1: %s\n",P.strings[1]);
printf("\tRespuesta2: %s\n",P.strings[2]);
printf("\tRespuesta3: %s\n",P.strings[3]);
printf("\tEntero correspondiente a la respuesta correcta: %d\n\n\n\n",P.respuestaCorrecta);
}
/*
* ConsultarComplejidad determina, para una complejidad dada, si hay elementos en
* la lista correspondiente a la misma. Si la lista tiene elementos, se llama
* al procedimiento de mostrarPregunta, en caso contrario, imprime en pantalla
* que la lista no tiene elementos de esa complejidad.
* Argumentos: listas, es un apuntador al arreglo de listas enlazadas en memoria.
* complejidad, es un String que tiene el nombre del archivo.
* Retorna: nada, en ambos casos, imprime un mensaje en pantalla.
*/
void ConsultarComplejidad(LISTA **listas, int complejidad){
LISTA *temp;
temp = listas[complejidad];
if (temp == NULL){
printf("No existen preguntas en la base de datos con nivel complejidad %d.\n",complejidad);
}
else{
printf("PREGUNTAS de complejidad %d \n",complejidad);
}
while (temp != NULL){
mostrarPregunta((temp)->preg);
temp = (temp)->ant;
}
}
/*
* EliminarPregunta es un procedimiento que se encarga de eliminar una pregunta
* de las listas en memoria, esto lo hace ejecutando la función eliminar. Si no
* existía la pregunta, imprime en pantalla un mensaje de error, en caso contrario,
* imprime en pantalla que la pregunta fue eliminada con éxito.
* Argumentos: código, entero que representa el código de la pregunta a eliminar.
* listas, es un apuntador al arreglo de listas enlazadas en memoria.
* Retorna: nada, las modificaciones las hace en memoria e imprime en pantalla
* si la pregunta fue removida exitosamente.
*/
void EliminarPregunta(int codigo, LISTA **listas){
int eliminado = 0;
int i = 0;
//Buscamos sobre las tres listas la pregunta.
while((i < 3) && eliminado == 0){
if (listas[i] != NULL)
eliminado = eliminar(&listas[i],codigo);
i++;
}
//Se imprime el mensaje al usuario.
if(eliminado == 0){
printf("En la base de datos no existe una pregunta con el código: %d\n",codigo);
}
else {
printf("La pregunta ha sido eliminada con exito.\n");
}
}
/*
* InsertarPregunta le pregunta al usuario los datos necesarios para añadir una
* pregunta a alguna de las listas enlazadas que están en memoria.
* Argumentos: listas, es un apuntador al arreglo de listas enlazadas en memoria.
* Retorna: nada, las modificaciones las hace en memoria.
*/
void InsertarPregunta(LISTA **listas){
PREGUNTA P;
int continuar;
do{
printf("A continuación, introduzca los atributos que se le piden.\n");
printf("\tCódigo: ");
scanf("%d",&P.codigo);
getchar();
printf("\n");
printf("\tÁrea(H,G,T,C ó L): ");
scanf("%c",&P.area);
printf("\n");
printf("\tNivel de complejidad(0, 1 ó 2): ");
scanf("%d",&(P.complejidad));
getchar();
printf("\n");
printf("\tPregunta: ");
scanf("%[^\n]",P.strings[0]);
getchar();
printf("\n");
printf("\tRespuesta1: ");
scanf("%[^\n]",P.strings[1]);
getchar();
printf("\n");
printf("\tRespuesta2: ");
scanf("%[^\n]",P.strings[2]);
getchar();
printf("\n");
printf("\tRespuesta3: ");
scanf("%[^\n]",P.strings[3]);
getchar();
printf("\n");
printf("\tEntero correspondiente a la respuesta correcta: ");
scanf("%d",&P.respuestaCorrecta);
getchar();
printf("\n");
printf("Los datos que introdujo son: \n\n");
mostrarPregunta(P);
printf("Escriba 0 si los datos son correctos o 1 si son incorrectos: ");
scanf("%d",&continuar);
getchar();
printf("\n\n");
if (!continuar){
insertar(&listas[P.complejidad],P);
}
} while (continuar);
printf("La pregunta se ha añadido correctamente.\n");
}
/*
* Salvar es la opción para pasar de memoria a disco los datos modificados en
* la sesión de trabajo, recibe el nombre del archivo y lo sobreescribe en disco
* en este archivo, imprime todas las preguntas que estban en las listas.
* Argumentos: nombre, es un String que tiene el nombre del archivo.
* listas, es un apuntador al arreglo de listas enlazadas en memoria.
* Retorna: nada, las modificaciones las hace en disco.
*/
void Salvar(char *nombre,LISTA **listas){
int i = 0;
FILE *fp;
LISTA *temp;
PREGUNTA p;
fp = fopen(nombre, "w");
if(fp == NULL){
perror("Lo lamentamos");
printf("errno = %d\n",errno);
exit(1);
}
printf("Abriendo el archivo...\n");
printf("Guardando los datos en la base de datos...\n");
for (i = 0; i < 3; i++){
temp = listas[i];
while (temp != NULL){
p = temp->preg;
fprintf(fp,"%d %d %c \"%s\" \"%s\" \"%s\" \"%s\" %d\n",p.codigo,p.complejidad,p.area,p.strings[0],p.strings[1],p.strings[2],p.strings[3],p.respuestaCorrecta);
temp = (temp)->ant;
}
}
fclose(fp);
printf("Hemos terminado de escribir en el archivo.\n");
}
<file_sep>#!/bin/bash
# USO: du_extendido
for i in *;do du -skh $i;done
#fin del script
<file_sep>//Archivos.
#include <stdio.h>
#include <stdlib.h>
/* La estructura es la siguiente:
1- Declaro un apuntador de tipo FILE.
2- Asociamos el nombre del archivo con fopen.
3- Traemos datos del disco a la RAM con fscanf.
4- Guardamos datos en disco usando fprintf.
5- cerramos el archivo.
*/
void main(){
//Se declara el apuntador de tipo FILE.
FILE *archivo;
//Lo asociamos con fopen.
archivo = fopen("numeros.txt","r+");
int datos;
int datos1[11];
int i = 0;
int dato = 11;
//Lo traemos a RAM usando fscanf.
//Si no sabemos la longitud total del archivo, iteramos hasta que se
//termine.
while(fscanf(archivo,"%d",&datos) != EOF){
printf("Todo es: %d\n",datos);
}
//Escribimos en el archivo.
fprintf(archivo,"%d",dato);
//Nos devolvemos al principio con una función de C.
rewind(archivo);
//Si sabemos cual es la longitud total del archivo pudiesemos usar esto.
for(i = 0;i <= 10;i++){
fscanf(archivo,"%d",&datos1[i]);
printf("En el arreglo es: %d\n",datos1[i]);
}
//Lo cerramos.
fclose(archivo);
}
<file_sep>/*
* mainHilos.c
*
* Descripción: Este archivo contiene el ciclo principal del proyecto usando
* hilos según la API POSIX.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 21-05-2015.
*/
//Inclumimos las librerías que necesitaremos.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "listaEnlazada.h"
#include <math.h>
#include <pthread.h>
typedef struct argumento{
int *primero;
int *ultimo;
}ARGUMENTO;
/*
* Variables globales necesarias para los hilos.
*/
char **lineas = NULL;
ARGUMENTO argumentoHilo;
LISTA **lista;
int lineasTotales;
int nodosTotales;
pthread_mutex_t listLock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t linesLock= PTHREAD_MUTEX_INITIALIZER;
/*
* mapHilos es una función que dada una linea, reconoce a una persona y su
* lista de amigos. Luego, hace un mapeo de essa persona con sus amigos y el
* resultado lo guarda en la lista enlazada. Esta función la hace un hilo HIJO,
* creado en el MAIN.
* Argumentos: entero, posicion de la lista a leer.
* Retorna: nada, hace modificaciones en memoria.
*/
void *mapHilos(void *entero){
char *savePtr = NULL;
char *temp, *temp2;
char *nombre;
char **amigos;
int nroDeAmigos = 0;
int contador;
int i,j;
LISTA **listaTemp = NULL;
int *casilla, tarea;
casilla = (int *)entero;
tarea = *casilla;
int l;
for(l = argumentoHilo.primero[tarea] ; l< argumentoHilo.ultimo[tarea];l++ ){
listaTemp = lista;
//COMIENZA LA SECCIÓN CRITICA
pthread_mutex_lock(&linesLock);
temp = strdup(lineas[l]);
temp2 = strdup(lineas[l]);
temp = strtok_r(temp, " ",&savePtr);
nombre = strdup(temp);
temp = strtok_r(NULL, " ",&savePtr);
nroDeAmigos = 0;
while((temp = strtok_r(NULL, " ",&savePtr))!=NULL){
nroDeAmigos++;
}
savePtr = NULL;
free(temp);
amigos = (char **)malloc(nroDeAmigos * sizeof(char **));
contador = 0;
temp2 = strtok_r(temp2," ",&savePtr);
temp2 = strtok_r(NULL," ",&savePtr);
while((temp2 = strtok_r(NULL," ",&savePtr)) != NULL){
amigos[contador] = strdup(temp2);
contador++;
}
free(temp2);
savePtr = NULL;
amigos[contador - 1] = strtok_r(amigos[contador - 1],"\n",&savePtr);
for(i = 0; i < nroDeAmigos; i++){
j = strcmp(nombre,amigos[i]);
listaTemp = buscar(lista,nombre,amigos[i]);
if(j <= 0){
listaTemp = buscar(lista,nombre,amigos[i]);
}else{
listaTemp = buscar(lista,amigos[i],nombre);
}
if(listaTemp == NULL){
if(j <= 0){
insertar(lista,nombre,amigos[i]);
}else{
insertar(lista,amigos[i],nombre);
}
(*lista)->nroAmigos[0] = nroDeAmigos;
(*lista)->nroAmigos[1] = 0;
(*lista)->nroAmigos[2] = 0;
(*lista)->amigos1 = (char **)malloc(nroDeAmigos * sizeof(char **));
for(contador =0; contador<(*lista)->nroAmigos[0];contador++){
(*lista)->amigos1[contador] = strdup(amigos[contador]);
}
nodosTotales++;
} else{
(*listaTemp)->nroAmigos[1] = nroDeAmigos;
//pedimos espacio para almacenar a los amigos
(*listaTemp)->amigos2 = (char **)malloc(contador * sizeof(char **));
for(contador =0; contador<(*listaTemp)->nroAmigos[1];contador++){
(*listaTemp)->amigos2[contador] = strdup(amigos[contador]);
}
}
printf("i = %d\n",i);
}
pthread_mutex_unlock(&linesLock);
}
pthread_exit(NULL);
}
void *reduceHilo(void *entero){
int *casilla, tarea;
casilla = (int *)entero;
tarea = *casilla;
int nroAmigosComunes; //numero de amigos en comun
LISTA **l;
l = lista;
printf("primero = %d; ultimo = %d \n",argumentoHilo.primero[tarea],argumentoHilo.ultimo[tarea]);
int i,j,k,n;
pthread_mutex_lock(&linesLock);
for(i = 0; i < argumentoHilo.primero[tarea]; i++){
if((*l)->ant != NULL)
*l = (*l)->ant;
}
for(k = argumentoHilo.primero[tarea]; k < argumentoHilo.ultimo[tarea]; k++){
nroAmigosComunes = 0;
if((*l)->nroAmigos[1] != 0){
for(i = 0; i < (*l)->nroAmigos[0]; i++){
for(j = 0; j < (*l)->nroAmigos[1]; j++){
if (!strcmp((*l)->amigos1[i],(*l)->amigos2[j] )){
nroAmigosComunes++;
}
}
}
n = 0;
(*l)->comunes = (char **)malloc(sizeof(char **) * nroAmigosComunes);
for(i = 0; i < (*l)->nroAmigos[0]; i++){
for(j = 0; j < (*l)->nroAmigos[1]; j++){
if (!strcmp((*l)->amigos1[i],(*l)->amigos2[j] )){
(*l)->comunes[n] = strdup((*l)->amigos1[i]);
n++;
}
}
}
(*l)->nroAmigos[2] = n;
}
if(((*l)->ant)!=NULL)
*l = (*l)->ant;
}
pthread_mutex_unlock(&linesLock);
}
/*
* main es el ciclo principal del programa, también, es el ciclo principal del
* proceso padre, aquí se generarán las llamadas a pthread_create necesarias para que
* los hijos hagan MAP y REDUCE.
* Argumentos: argc, es el contador de argumentos pasados por entrada estándar.
* argv, contiene los distintos argumentos pasados por entrada estándar.
* Retorna: 0 si termina con éxito, otro entero en cualquier otro caso.
*/
int main(int argc, char *argv[]){
clock_t comienzo;
clock_t final;
int nroHilos;
char *nombreArchivo;
char *salida;
//Verificamos que la entrada del usuario sea correcta y ajustamos las variables.
if(argc == 5){
nroHilos = atoi(argv[2]);
nombreArchivo = argv[3];
salida = argv[4];
}
else if (argc == 3){
nroHilos = 1;
nombreArchivo = argv[1];
salida = argv[2];
}
if (nroHilos == 0){
printf("El número de procesos debe ser positivo, ejecute el programa nuevamente.\n");
exit(1);
}
int contador = 0;
int i;
int nroLineas[nroHilos];//Nro de lineas a asignar a cada hilo
lineasTotales = 0;//Nro de lineas que contiene el archivo
int nroNodos = 0;
int residuo = 0;
LISTA **lTemp;
char *line = NULL;
size_t len = 0;
ssize_t read;
int status;
lineasTotales = 0;//Nro de lineas que contiene el archivo
FILE *filepointer;
pthread_t *TIDs = NULL;
filepointer = fopen(nombreArchivo,"r");
if(filepointer == NULL){
perror("Lo lamentamos");
printf("Vuelva a ejecutar el programa con el nombre del archivo correcto.\n");
printf("errno = %d\n",errno);
exit(1);
}
printf("Abriendo el archivo...\n");
printf("Leyendo los datos de la base de datos...\n");
//inicializamos el numero de lineas a asignar a cada hilo en 0
for(i= 0; i < nroHilos; i++ )
nroLineas[i] = 0;
i = 0;
//lectura y almacenado de lineas
//se determina cuantas y cuales lineas se le asignan a cada proceso
while ((read = getline(&line, &len, filepointer)) != -1) {
if(i == nroHilos)
i = 0;
//incrementamos contadores
nroLineas[i]++;
lineasTotales++;
i++;
}
//free(line);
rewind(filepointer);
//pedimos memoria para almacenar las lineas
//lineas = (char **)malloc(sizeof(char **)*4);
lineas = (char **)malloc(sizeof(char*) * lineasTotales);
i= 0;
//almacenamos las lineas
while ((read = getline(&line, &len, filepointer)) != -1) {
lineas[i] = strdup(line);
i++;
}
printf("Numero de lineas del archivo = %d\n",lineasTotales);
puts("El archivo contiene lo siguiente: \n");
for(i = 0; i<lineasTotales; i++)
puts(*(lineas+i));
int j;
lista = (LISTA **)malloc(sizeof(LISTA **) * lineasTotales);
*lista = NULL;
comienzo = clock();
TIDs = (pthread_t *)malloc(sizeof(pthread_t *) * nroHilos);
int primera = 0;
int ultima = 0;
int *icorrespondiente;
argumentoHilo.primero = (int *)malloc(sizeof(int *) * nroHilos);
argumentoHilo.ultimo = (int *)malloc(sizeof(int *) * nroHilos);
icorrespondiente = (int *)malloc(sizeof(int *) * nroHilos);
//mandamos a mapear
for (i = 0; i < nroHilos; i++){
primera = ultima;
ultima = ultima + nroLineas[i];
argumentoHilo.primero[i] = primera;
argumentoHilo.ultimo[i] = ultima;
icorrespondiente[i] = i;
printf("%d %d",argumentoHilo.primero[i],argumentoHilo.ultimo[i] );
status = pthread_create(&TIDs[i],NULL,mapHilos, (void *)&(icorrespondiente[i]));
if (status != 0){
perror("Error al crear el hilo:");
exit(1);
}
else
printf("Se ha creado un hilo con éxito \n");
}
int retorno = 0;
for (i=0;i < nroHilos; i++){
status = pthread_join(TIDs[i],(void *)&retorno);
if(status != 0)
printf("Ocurrió un error");
else
printf("éxito");
}
if(nodosTotales >= nroHilos){
nroNodos = nodosTotales / nroHilos;
residuo = nodosTotales % nroHilos;
} else{
residuo = nodosTotales;
}
puts("##########REDUCE################################");
//Mandamos a hacer reduce
for (i = 0; i < nroHilos; i++){
icorrespondiente[i] = i;
//asignamos primero y ultimo para el hijo
if (i != 0){
argumentoHilo.primero[i] = argumentoHilo.ultimo[i];
}else{
argumentoHilo.primero[i] = 0;
}
argumentoHilo.ultimo[i] = argumentoHilo.primero[i] + nroNodos;
if(residuo > i){
argumentoHilo.ultimo[i]++;
}else{
if(nroNodos == 0){
argumentoHilo.primero[i] = 0;
argumentoHilo.ultimo[i] = 0;
}
}
status = pthread_create(&TIDs[i],NULL,reduceHilo, (void *)&(icorrespondiente[i]));
if (status != 0){
perror("Error al crear el hilo:");
exit(1);
}
else
printf("Se ha creado un hilo con éxito \n");
}
retorno = 0;
for (i=0;i < nroHilos; i++){
status = pthread_join(TIDs[i],(void *)&retorno);
if(status != 0)
printf("Ocurrió un error");
else
printf("éxito");
}
puts("######PAPA GENERA ARCHIVO A PARTIR DE LA ESTRUCTURA###############");
filepointer = fopen(argv[3],"w");
lTemp = lista;
while((*lTemp) !=NULL){
printf("(%s %s) -> %d \n",(*lTemp)->nombre[0],(*lTemp)->nombre[1],(*lTemp)->nroAmigos[2]);
if ((*lTemp)->nroAmigos[2] != 0){
fprintf(filepointer,"(%s %s) ->",(*lTemp)->nombre[0],(*lTemp)->nombre[1]);
printf("(%s %s) ->",(*lTemp)->nombre[0],(*lTemp)->nombre[1]);
for(i=0;i < (*lTemp)->nroAmigos[2]; i++){
fprintf(filepointer," %s",(*lTemp)->comunes[i]);
printf(" %s",(*lTemp)->comunes[i]);
}
fprintf(filepointer,"\n");
printf("\n");
}
*lTemp = (*lTemp)->sig;
}
fprintf(filepointer," \n");
fclose(filepointer);
final = clock() -comienzo;
printf("La ejecución del programa tomo: %d unidades de tiempo.\n",(int)final);
exit(0);
}
<file_sep>default: main.o bases.o listaEnlazada.o
gcc -Wall -o preguntas main.o bases.o listaEnlazada.o
main.o: main.c bases.h listaEnlazada.h
gcc -c main.c
bases.o: bases.c bases.h listaEnlazada.h
gcc -c bases.c
listaEnlazada.o: listaEnlazada.c listaEnlazada.h
gcc -c listaEnlazada.c -o listaEnlazada.o
clean:
rm -f *.o
<file_sep>//ListaEnlazadaEnC.c
#include <stdio.h>
#include <stdlib.h>
//Se crea la estructura de la lista enlazada.
typedef struct listaenlazada{
int x;
int y;
struct listaenlazada *sigPunto;
} LinkedList;
/* La estructura es la siguiente:
1- Se crea la estructura de la lista.
2- Se pide la memoria que necesitaremos para el primero y crearemos un apuntador
que quede siempre en el ultimo.
3- Con el manejo de un temporal, iterativamente iremos añadiendo más elementos
a la lista enlazada.
4- Luego haremos printf de todos los elementos.
*/
void main(){
//Creamos la variable.
LinkedList *miLista;
LinkedList *aux;
int i;
//Se pide la memoria para la primera caja.
miLista = (LinkedList *)malloc(sizeof(LinkedList));
aux = miLista;
for(i = 0;i <= 20;i++){
//Asignamos los valores actuales.
aux->x = i;
aux->y = 20 - i;
aux->sigPunto = (LinkedList *)malloc(sizeof(LinkedList));
printf("Datos actuales: %d - %d\n",aux->x,aux->y);
aux = aux->sigPunto;
}
free(miLista);
free(aux);
}
<file_sep>/*
* funcionesAuxiliares.c
*
* Descripción: Este archivo contiene las funciones y procedimientos de
* operaciones auxiliares al programa principal, tales como inicialización de
* arreglos, escritura en PIPE, verificación de argumentos, entre otros.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 22-06-2015.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <dirent.h>
#include <fcntl.h>
/*
* leerArchivo abre, lee el contenido y cierra un archivo, además escribe en
* la salida estándar (que para el uso de esta función es el pipe entre los hijos
* y el padre) el contenido del mismo.
*
* Argumentos: nombre, ruta y nombre del archivo a abrir.
*
* Retorna: nada, escribe en el pipe el contenido del archivo al padre.
*/
void leerArchivo(char *nombre){
int fd = 0;
int charsRead; //número de carácteres leídos
off_t offset;
int nroChars; //número de carácteres que contiene el archivo
char *buffer;
int archivoprueba;
//Se abre el archivo.
fd = open(nombre, O_RDONLY);
//movemos el offset al final del archivo para determinar la
//cantidad de caracteres
offset = 0;
nroChars = lseek(fd, offset,SEEK_END);
//movemos el offset al inicio del archivo
lseek(fd, offset,SEEK_SET);
//pedimos memoria
buffer = (char *) malloc(sizeof( char)* nroChars);
//Se lee archivo.
charsRead = read(fd, buffer, nroChars);
//Se escribe en el pipe.
write(STDOUT_FILENO, buffer, charsRead);
free(buffer);
close(fd);
}
/*
* verificarConjunto es una función que determina, dado un arreglo, y un número
* aleatorio, si el mismo está en el arreglo.
*
* Argumentos: numero, entero a verificar si está en el conjunto.
* arreglo, arreglo de enteros donde buscar.
* tamano, entero que especifica el tamaño del arreglo.
*
* Retorna: 0 si no está en el conjunto, 1 si está en el conjunto.
*/
int verificarConjunto(int numero, int arreglo[], int tamano){
int i;
for(i = 0; i< tamano; i++){
if(numero == arreglo[i])
return 1;
}
return 0;
}
/*
* verificarArgumentos verifica que los argumentos de la entrada sean correctos.
*
* Argumentos: n, dirección de la cantidad de procesos a considerar.
* m, dirección de la cantidad de archivos a considerar.
* salida, dirección de dónde se va a guardar la ruta y el nombre del
* archivo de salida.
* directorio, dirección de dónde se va a guardar el directorio de entrada.
* statbuf, estructura de stat para poder usar la función de stat.
* argc, número de argumentos de la entrada.
* argv, argumentos de la entrada.
*
* Retorna: Nada, los cambios los hace en n,m,salida, y directorio.
*/
void verificarArgumentos(int *n, int *m, char **salida,char **directorio, struct stat statbuf, int argc, char *argv[]){
char *temp = NULL; //Variable temporal
char *temp2 = NULL; //Variable temporal
if(argc == 4){
//convertimos segundo y tercer argumentos a enteros
*n = strtol(argv[1],&temp,10);
*m = strtol(argv[2],&temp2,10);
//verificamos que el segundo y tercer arguento sean enteros
if (strcmp(temp,"") || strcmp(temp2,"")){
printf("\nError. El formato correcto para correr el programa es:\n");
printf("MiCuento [-d directorio] <n> <m> <salida>\n\n");
printf("donde <n> y <m> son enteros no negativos.\n");
exit(1);
}
*salida = strdup(argv[3]);
*directorio = ".";
} else if (argc == 6){
//verificamos que se introdujo un flag válido
if (strcmp(argv[1],"-d")){
printf("Error. %s NO es una opción válida.\n",argv[1]);
exit(1);
}
*directorio = (argv[2]);
if (stat(*directorio, &statbuf) != -1){
if (statbuf.st_mode & S_IFDIR){
}else{
printf("Error.\n%s NO es un directorio.\n",*directorio);
exit(1);
}
} else{
printf("Error.\n%s NO es un directorio.\n",*directorio);
exit(1);
}
*n = strtol(argv[3],&temp,10);
*m = strtol(argv[4],&temp2,10);
*salida = strdup(argv[5]);
} else {
printf("\nError. El formato correcto para correr el programa es:\n");
printf("MiCuento [-d directorio] <nrocarpetas> <nroarchivos> <salida>\n");
exit(1);
}
//verificamos que <m> y <n> sean enteros
if (strcmp(temp,"") || strcmp(temp2,"")){
printf("\nError. El formato correcto para correr el programa es:\n");
printf("MiCuento [-d directorio] <n> <m> <salida>\n\n");
printf("donde <n> y <m> son enteros no negativos.\n");
exit(1);
}
//verificamos que <n> sea mayor o igual a 0
//y menor o igual a 10
if ((*n < 0) || (*n > 10)){
printf("\nError. El formato correcto para correr el programa es:\n");
printf("MiCuento [-d directorio] <n> <m> <salida>\n\n");
printf("donde <n> es un entero no negativo menor o igual a 10.\n");
exit(1);
}
//verificamos que <m> sea mayor o igual a 0
//y menor o igual a 20
if ((*m < 0) || (*m > 20)){
printf("\nError. El formato correcto para correr el programa es:\n");
printf("MiCuento [-d directorio] <n> <m> <salida>\n\n");
printf("donde <m> es un entero no negativo menor o igual a 20.\n");
exit(1);
}
if (*n == 0){
printf("El número de directorios es 0.\n");
printf("Finaliza el programa.\n");
exit(0);
}
if (*m == 0){
printf("El número de archivos a leer es 0.\n");
printf("Finaliza el programa.\n");
exit(0);
}
}
/*
* inicializarArreglo escribe en un arreglo dado el valor 0 en todas sus casillas.
*
* Argumentos: arreglo, el arreglo a inicializar.
* tamano, entero que especifica el tamaño del arreglo.
*
* Salida: ninguna, los cambios los hace en memoria.
*/
void inicializarArreglo(int arreglo[], int tamano){
int i;
for(i = 0;i < tamano; i++)
arreglo[i] = 0;
}
<file_sep>/*
* listaEnlazada.h
*
* Descripción: Este es el archivo cabecera para listaEnlazada.c.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 21-05-2015.
*/
/*
* LISTA es una lista enlazada que guarda un par de nombres, el número de amigos
* de cada map, los amigos, y los comunes, además, la lista es doblemente enlazada,
* por lo tanto, tiene apuntadores al siguiente nodo y al anterior.
*/
typedef struct lista {
char *nombre[2];
int nroAmigos[3];
char **amigos1;
char **amigos2;
char **comunes;
struct lista *sig;
struct lista *ant;
} LISTA;
void insertar(LISTA **ultimo,char *nombre1,char *nombre2);
LISTA **buscar(LISTA **ultimo, char *nombre1, char *nombre2);
void destruirLista(LISTA **ultimo);
<file_sep>#!/bin/bash
find . -name *~ | xargs rm
#Fin del script.
<file_sep>default: mainProcesos.o mainHilos.o listaEnlazada.o
gcc -Wall -g -o friendfindP mainProcesos.o listaEnlazada.o
gcc -Wall -g -o friendfindH mainHilos.o -lpthread listaEnlazada.o
make clean
mainProcesos.o: mainProcesos.c listaEnlazada.h
gcc -g -c mainProcesos.c
mainHilos.o: mainHilos.c listaEnlazada.h
gcc -g -c mainHilos.c -lpthread
listaEnlazada.o: listaEnlazada.c listaEnlazada.h
gcc -g -c listaEnlazada.c -o listaEnlazada.o
clean:
rm -f *.o
reset
<file_sep>/*
* main.c
*
* Descripción: Este archivo contiene el ciclo principal del programa.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 22-06-2015.
*/
//Inclumimos las librerías que necesitaremos.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include "funcionesAuxiliares.h"
/*
* main es el ciclo principal del programa.
*
* Argumentos: argc, es el contador de argumentos pasados por entrada estándar.
* argv, contiene los distintos argumentos pasados por entrada estándar.
* Retorna: 0 si termina con éxito, otro entero en cualquier otro caso.
*/
int main(int argc, char *argv[]){
int n; //valor que el padre debe considerar y número de procesos a crear.
int m; //archivos que los procesos hijos deben considerar
char *salida; //nombre del archivo de salida
char *directorio; //directorio donde se encuentran los archivos de texto
char *rutaDir; //almacena el path
pid_t childpid;
pid_t *pidHijos;
int status = 0; //estado del hijo
int nroFilesT = 0; //número de archivos que el hijo transfirió al padre
int nroDirs = 0; //número de directorios a los que se accedió
int *aleatoriosPadre = NULL;//almecena los n numeros aletorios generados por el padre
int *aleatoriosHijo = NULL;//almecena los m numeros aletorios generados por el padre
char *nombre = NULL;
int i,j; //contadores
int filedescriptor;
int numeroAleatorio = -1; //Aquí se guarda temporalmente el número aleatorio.
int estaEnConjunto = -1; //Booleano que dice si el numero esta en el conjunto.
int pipefd[2]; //Aquí se guardan los descriptores de archivo del pipe.
char buffer; //Guardará los caracteres que se lean del pipe.
char *textoHijo = ""; //Aquí se almacenará lo que se reciba por un buffer.
int salidafd; //Descriptor del archivo de salida.
struct stat statbuf;
int longitud;
int *directorios;//Almacena los números asociados a los directorios
//a los que ya se se entró o intento entrar
int *archivos; //Almacena los números asociados a los directorios
//a los que ya se se entró o intento entrar
int nroIntentos = 0; //número de archivos o directorios a los que se intento acceder
verificarArgumentos(&n, &m, &salida, &directorio,statbuf, argc, argv);
////////////////////////////////////////////////////////////////////////////
//pedimos memoria
aleatoriosPadre = (int *)malloc(sizeof(int)*n);
aleatoriosHijo = (int *)malloc(sizeof(int)*m);
rutaDir = (char *)malloc(strlen(directorio) + 3);
directorios = (int *) malloc(sizeof(int *)*10);
archivos = (int *) malloc(sizeof(int)*20);
pidHijos = (pid_t *) malloc(sizeof(pid_t)*n);
//Se inicializan los números aleatorios que generará el padre
//y arreglo que almacena los números asociados a los directorios a los
//cuales ya intento acceder
inicializarArreglo(aleatoriosPadre, n);
inicializarArreglo(aleatoriosHijo, m);
inicializarArreglo(directorios, 10);
inicializarArreglo(archivos, 20);
srand(getpid());
//El padre genera n numeros aleatorios (mayores que 0 y menores o iguales a 10)
// y los almacena en un arreglo que actúa como conjunto. y |conjunto| = n.
for(i = 0; i< n; i++){
do{
//se genera un numero aleatorio entre 0 y 10
numeroAleatorio = rand() % (11);
//Se verifica si ya se intento acceder al directorio asociado
//al numero aleatorio generado
estaEnConjunto = verificarConjunto(numeroAleatorio,directorios, 10);
if(!estaEnConjunto && (numeroAleatorio != 0)){
//se almacena el número asociado al directorio al que se intentará
//acceder
directorios = directorios + nroIntentos;
*directorios = numeroAleatorio;
directorios = directorios - nroIntentos;
//se incrementa el numero de archivos al que se ha intentado acceder
nroIntentos++;
//se almacena la ruta del directorio al que se intetará acceder
sprintf(rutaDir,"%s/%d",directorio,numeroAleatorio);
//Se verifica que sea un archivo de tipo directorio
if (stat(rutaDir, &statbuf) != -1){
if (statbuf.st_mode & S_IFDIR){
aleatoriosPadre[i] = numeroAleatorio;
nroDirs++;
}
}
}
} while((aleatoriosPadre[i] == 0) && (nroIntentos < 10) );
}
//En caso de que no haya carpetas para ingresar.
if(nroDirs == 0){
puts("No se encontró ningún directorio.");
puts("Se finalizará el programa.");
exit(1);
}
//se reinicializa el número de intentos en 0
nroIntentos = 0;
//Creamos el pipe.
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
//creación de los hijos
for(i = 0; i< n; i++){
if ((childpid = fork()) < 0) {
perror("fork:");
exit(1);
}
// Código que ejecutarán los hijos
if (childpid == 0) {
if (aleatoriosPadre[i] == 0){
exit(nroFilesT);
}
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[0]);
close(pipefd[1]);
//Calculamos la longitud de la ruta
longitud = strlen(directorio) + 6;
//pedimos memoria
nombre = (char *) malloc(longitud * sizeof(char));
srand(getpid());
for(j = 0; j < m; j++){
do{
//Se genera un numero aleatorio entre 0 y 20
numeroAleatorio = rand() % (21);
//se almacena la ruta
sprintf(nombre,"%s/%d/%d",directorio,aleatoriosPadre[i],numeroAleatorio);
//se determina si ya se intento acceder al archivo asociado
//al numero aleatorio
estaEnConjunto = verificarConjunto(numeroAleatorio,archivos, 20);
if(!estaEnConjunto && (numeroAleatorio != 0)){
//se almacena el numero asociado al archivo
archivos = archivos + nroIntentos;
*archivos = numeroAleatorio;
archivos = archivos - nroIntentos;
//se incrementa el numero de archivos al que se ha
//intentado acceder
nroIntentos++;
//Se verifica que el archivo sea de tipo regular
if (stat(nombre, &statbuf) != -1){
if (statbuf.st_mode & S_IFREG){
//se lee el archivo y su contenido se almacena
//en el pipe
leerArchivo(nombre);
nroFilesT++;
aleatoriosHijo[j] = numeroAleatorio;
}
}
}
}while((aleatoriosHijo[j] == 0) && nroIntentos < 20);
}
//liberamos memoria
free(nombre);
exit(nroFilesT);
}
//Código que ejecutará el padre.
else
pidHijos[i] = childpid;
}
//Cambiamos la entrada estándar por el pipe en el modo de lectura.
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[1]);
close(pipefd[0]);
//Se abre el archivo de salida
salidafd = open(salida,O_WRONLY|O_CREAT,0600);
printf("El cuento aleatorio es: \n");
//se lee del pipe
while(read(0,&buffer,1) > 0){
write(STDOUT_FILENO, &buffer, 1); //Se escribe en pantalla.
write(salidafd,&buffer,1); //Se escribe en el archivo.
}
close(salidafd);//se ciera el archivo de salida
//el padre espera por sus hijos
printf("\n\n\nLa información de los procesos es la siguiente: \n");
for (i = 0; i < n; i++){
waitpid(pidHijos[i],&status,0);
nroFilesT = status / 256;
printf("El hijo %d procesó %d archivos.\n",pidHijos[i], nroFilesT);
}
//liberamos memoria
free(archivos);
free(aleatoriosPadre);
free(aleatoriosHijo);
free(rutaDir);
free(directorios);
free(salida);
free(pidHijos);
exit(0);
}
<file_sep>/*
* funcionesAuxiliares.h
*
* Descripción: Este archivo es la cabecera del archivo funcionesAuxiliares.c
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 22-06-2015
*/
void leerArchivo(char *nombre);
int verificarConjunto(int numero, int arreglo[], int tamano);
void verificarArgumentos(int *n, int *m, char **salida,char **directorio, struct stat statbuf, int argc, char *argv[]);
void inicializarArreglo(int arreglo[], int tamano);
<file_sep>/*
* mainProcesos.c
*
* Descripción: Este archivo contiene el ciclo principal del proyecto usando
* procesos.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 21-05-2015.
*/
//Inclumimos las librerías que necesitaremos.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "listaEnlazada.h"
#include <math.h>
#include <time.h>
/*
* mapProcesos es una función que dada una linea, reconoce a una persona y su
* lista de amigos. Luego, hace un mapeo de essa persona con sus amigos y el
* resultado lo guarda en un archivo. Esta función la hace un proceso HIJO,
* creado en el MAIN. El nombre del archivo es PID.txt donde PID es el PID del
* hijo.
* Argumentos: linea, es la línea a mapear.
* Retorna: crea un archivo en disco con el mapeado de la línea.
*/
void mapProcesos(char *linea){
char *temp = NULL;
char *temp2 = NULL;
char *persona[1];
char **amigos = NULL; //arreglo de amigos
int i,j,contador; //contador
char archivo[10];
int nroAmigos = 0; //Cantidad de amigos que posee la persona
sprintf(archivo,"%d",getpid());
strcat(archivo,".txt");
FILE *fp;
fp = fopen(archivo,"a");
//copiamos la línea en el temporal
temp = strdup(linea);
//guardamos el nombre de la persona
temp = strtok(temp," ");
persona[0] = temp;
//ponemos la flecha en el temporal pero no la guardamos
temp = strtok(NULL, " ");
while((temp = strtok(NULL, " "))!=NULL){
nroAmigos++;
}
free(temp);
amigos = (char **)malloc(nroAmigos * sizeof(char **));
contador = 0;
temp2 = strdup(linea);
temp2 = strtok(temp2," ");
temp2 = strtok(NULL," ");
while((temp2 = strtok(NULL," ")) != NULL){
amigos[contador] = strdup(temp2);
contador++;
}
amigos[nroAmigos-1] = strtok(amigos[nroAmigos-1],"\n");
for(i = 0; i < nroAmigos; i++){
if(!strcmp(amigos[i],"-none-")){
j = strcmp(persona[0],amigos[i]);
if(j<=0){
fprintf(fp,"(%s %s) -> ",persona[0],amigos[i]);
}else{
fprintf(fp,"(%s %s) -> ",amigos[i],persona[0]);
}
for(j = 0; j < nroAmigos; j++){
fprintf(fp," %s",amigos[j]);
}
fprintf(fp,"\n");
}
}
fclose(fp);
free(temp2);
free(amigos);
}
/*
* reduceProcesos es un procedimiento que, dada una lista enlazada de nodos,
* abre un archivo y guarda en él, los amigos que puedan tener en común dos
* personas de la red social. Esta función la ejecuta un proceso HIJO creado en
* el MAIN. El nombre del archivo es PID.txt donde PID es el PID del
* hijo.
* Argumentos: l, es una lista enlazada, apuntando al nodo a reducir.
* Retorna: crea un archivo en disco con los amigos en común de la persona.
*/
void reduceProcesos(LISTA **l){
int i,j;
char archivo[10];
FILE *fp;
int amigosEnComun = 0;
sprintf(archivo,"%d",getpid());
strcat(archivo,".txt");
fp = fopen(archivo,"a");
if((*l)->nroAmigos[1] != 0){
fprintf(fp,"(%s %s) ->",(*l)->nombre[0],(*l)->nombre[1]);
for(i = 0; i < (*l)->nroAmigos[0]; i++){
for(j = 0; j < (*l)->nroAmigos[1]; j++){
if (!strcmp((*l)->amigos1[i],(*l)->amigos2[j] )){
fprintf(fp," %s",(*l)->amigos1[i]);
amigosEnComun++;
}
}
}
if(amigosEnComun == 0)
fprintf(fp,"-none-");
fprintf(fp," \n");
}else{
fprintf(fp,"(%s %s) ->",(*l)->nombre[0],(*l)->nombre[1]);
}
fclose(fp);
}
/*
* main es el ciclo principal del programa, también, es el ciclo principal del
* proceso padre, aquí se generarán las llamadas a fork necesarias para que
* los hijos hagan MAP y REDUCE.
* Argumentos: argc, es el contador de argumentos pasados por entrada estándar.
* argv, contiene los distintos argumentos pasados por entrada estándar.
* Retorna: 0 si termina con éxito, otro entero en cualquier otro caso.
*/
int main(int argc, char *argv[]){
int nroProcesos;
char *nombreArchivo;
char *salida;
//Verificamos que la entrada del usuario sea correcta y ajustamos las variables.
if(argc == 5){
nroProcesos = atoi(argv[2]);
nombreArchivo = argv[3];
salida = argv[4];
}
else if (argc == 3){
nroProcesos = 1;
nombreArchivo = argv[1];
salida = argv[2];
}
if (nroProcesos == 0){
printf("El número de procesos debe ser positivo, ejecute el programa nuevamente.\n");
exit(1);
}
clock_t comienzo;
clock_t final;
int contador = 0;
int i;
int nroLineas[nroProcesos];//Nro de lineas a asignar a cada proceso
int lineasTotales = 0;//Nro de lineas que contiene el archivo
char *line = NULL;
size_t len = 0;
ssize_t read;
char **lineas;
int status;
pid_t childpid;
FILE *filepointer, *fp;
int *PIDs = NULL;
filepointer = fopen(nombreArchivo,"r");
if(filepointer == NULL){
perror("Lo lamentamos");
printf("Vuelva a ejecutar el programa con el nombre del archivo correcto.\n");
printf("errno = %d\n",errno);
exit(1);
}
printf("Abriendo el archivo...\n");
//inicializamos el numero de lineas a asignar a cada proceso en 0
for(i= 0; i < nroProcesos; i++ )
nroLineas[i] = 0;
i = 0;
//lectura y almacenado de lineas
//se determina cuantas y cuales lineas se le asignan a cada proceso
while ((read = getline(&line, &len, filepointer)) != -1) {
if(i == nroProcesos)
i = 0;
nroLineas[i]++;
lineasTotales++;
i++;
}
rewind(filepointer);
lineas = (char **)malloc(sizeof(char*) * lineasTotales);
i= 0;
//almacenamos las lineas
while ((read = getline(&line, &len, filepointer)) != -1) {
lineas[i] = strdup(line);
i++;
}
int j;
//creacion de hijos
PIDs = (int *)malloc(sizeof(int *) * nroProcesos);
int primera = 0;
int ultima = 0;
for (i = 0; i < nroProcesos; i++){
primera = ultima;
ultima = ultima + nroLineas[i];
if ((childpid = fork()) < 0){
perror("fork:");
exit(1);
}
if (childpid == 0){
while(primera<ultima){
mapProcesos(lineas[primera]);
primera++;
}
exit(0);
}
else{
comienzo = clock();
PIDs[i] = (int)childpid;
}
}
// El padre espera que terminen todos los hijos que creo.
for (i = 0; i < nroProcesos; i++){
wait(&status);
}
fclose(filepointer);
char *nombre1;
char *nombre2;
char **amigos;
char nombreHijo[10];
char *temp;
char *temp2;
int nroAmigos;
LISTA **lista;
lista = (LISTA **)malloc(sizeof(LISTA **));
*lista = NULL;
LISTA **listaTemp;
listaTemp = (LISTA **)malloc(sizeof(LISTA **));
*listaTemp = NULL;
int nodosTotales;
int *nroNodos = NULL;
int nroArchivos;
nroNodos = (int *)malloc(sizeof(int*));
puts("Ya los hijos terminaron de hacer map, ahora el padre juntará los datos.\n");
nodosTotales = 0;//nro de nodos
if(lineasTotales < nroProcesos){
nroArchivos = lineasTotales;
} else {
nroArchivos = nroProcesos;
}
//inicializamos el numero de nodos a asignar a cada proceso en 0
for(i= 0; i < nroProcesos; i++ ){
nroNodos[i] = 0;
}
//Ahora pasamos a la lectura de todos los archivos que los hijos crearon.
for (i = 0; i < nroArchivos; i++){
sprintf(nombreHijo,"%d",PIDs[i]);
strcat(nombreHijo,".txt");
filepointer = fopen(nombreHijo,"r");
j = 0;
//almacenamos las lineas
while ((read = getline(&line, &len, filepointer)) != -1) {
if(j == nroArchivos){
j = 0;
}
//copiamos la línea en el temporal
temp = strdup(line);
//guardamos el nombre de la primera persona
temp = strtok(temp," ");
nombre1 = temp;
//guardamos el nombre de la primera persona
temp = strtok(NULL," ");
nombre2 = temp;
//ponemos la flecha en el temporal pero no la guardamos
temp = strtok(NULL, " ");
while((temp = strtok(NULL, " "))!=NULL){
nroAmigos++;
}
free(temp);
temp2 = strdup(line);
temp2 = strtok(temp2," ");
temp2 = strtok(NULL," ");
temp2 = strtok(NULL," ");
amigos = (char **)malloc(contador * sizeof(char **));
while((temp2 = strtok(NULL," ")) != NULL){
amigos[contador] = strdup(temp2);
contador++;
}
nombre1 = strtok(nombre1,"(");//Removemos el "(" del nombre
nombre2 = strtok(nombre2,")");//Removemos el ")" del nombre
amigos[contador-1] = strtok(amigos[contador-1],"\n");
free(temp2);
listaTemp = buscar(lista,nombre1,nombre2);
if(listaTemp == NULL){
insertar(lista,nombre1,nombre2);
(*lista)->nroAmigos[0] = contador;
(*lista)->nroAmigos[1] = 0;
//pedimos espacio para almacenar a los amigos
(*lista)->amigos1 = (char **)malloc(nroAmigos * sizeof(char **));
for(contador =0; contador<(*lista)->nroAmigos[0];contador++){
(*lista)->amigos1[contador] = strdup(amigos[contador]);
}
nroNodos[j]++;
nodosTotales++;
} else{
(*listaTemp)->nroAmigos[1] = contador;
//pedimos espacio para almacenar a los amigos
(*listaTemp)->amigos2 = (char **)malloc(contador * sizeof(char **));
for(contador =0; contador<(*listaTemp)->nroAmigos[1];contador++){
(*listaTemp)->amigos2[contador] = strdup(amigos[contador]);
}
}
j++;
contador = 0;
}
free(amigos);
fclose(filepointer);
}
puts("################### Hijos Hacen reduce###################");
primera = 0;
ultima = 0;
for (i = 0; i < nroProcesos; i++){
primera = ultima;
ultima = ultima + nroNodos[i];
if ((childpid = fork()) < 0){
perror("fork:");
exit(1);
}
if (childpid == 0){
for(j = 0; j< ultima; j++){
if(j>=primera)
reduceProcesos(lista);
if((*lista) != NULL)
*lista = (*lista)->ant;
}
exit(0);
}
else
PIDs[i] = (int)childpid;
}
// El padre espera que terminen todos los hijos que creo.
for (i = 0; i < nroProcesos; i++){
wait(&status);
}
puts("################El padre escribe archivo de salida################");
if(nroArchivos == 1)
nroArchivos++;
for (i = 0; i < nroArchivos -1; i++){
sprintf(nombreHijo,"%d",PIDs[i]);
strcat(nombreHijo,".txt");
filepointer = fopen(nombreHijo,"r");
j = 0;
//Almacenamos las lineas de un archivo y las escribimos en la salida.
while ((read = getline(&line, &len, filepointer)) != -1) {
fp = fopen(salida,"a");
fputs(line,fp);
fclose(fp);
}
fclose(filepointer);
}
final = clock() - comienzo;
printf("La ejecución del programa tomo: %d unidades de tiempo.\n",(int)final);
free(lineas);
free(PIDs);
free(lista);
free(listaTemp);
free(nroNodos);
exit(0);
}
<file_sep>/**
* Bases.h
*
* Descripción: Este es el archivo cabecera de Bases.c.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 27-04-2015.
*/
#include "listaEnlazada.h"
void LeerArchivo(char nombre[], LISTA **listas);
void mostrarPregunta(PREGUNTA P);
void ConsultarComplejidad(LISTA **listas, int complejidad);
void EliminarPregunta(int codigo, LISTA **listas);
void InsertarPregunta(LISTA **listas);
void Salvar(char *nombre,LISTA **listas);
<file_sep>#!/bin/bash
# USO: du_extendido
for i in *;do du -sk $i;done
#fin del script
<file_sep>/*
* listaEnlazada.c
*
* Descripción: Este archivo contiene la definición y operaciones de una lista
* doblemente enlazada.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 21-05-2015.
*/
#include "listaEnlazada.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/*
* LISTA es una lista enlazada que guarda un par de nombres, el número de amigos
* de cada map, los amigos, y los comunes, además, la lista es doblemente enlazada,
* por lo tanto, tiene apuntadores al siguiente nodo y al anterior.
*/ /*
typedef struct lista {
char *nombre[2];
int nroAmigos[3];
char **amigos1;
char **amigos2;
char **comunes;
struct lista *sig;
struct lista *ant;
} LISTA;
*/
/*
* insertar es un procedimiento que añade una pregunta a la lista enlazada.
* La inserción se hace al final de la lista y se actualiza el puntero al último
* elemento.
* Argumentos: ultimo, es un apuntador a la última posición de la lista.
* nombre1, es una cadena de caracteres que representan al nombre del
* primer amigo.
* nombre2, es una cadena de caracteres que representan al nombre del
* segundo amigo.
* Retorna: nada, las modificaciones las hace a la lista enlazada en memoria.
*/
void insertar(LISTA **ultimo,char *nombre1,char *nombre2){
LISTA *nuevo;
nuevo = (LISTA *) malloc(sizeof(LISTA));
if (*ultimo != NULL)
(*ultimo)->sig = nuevo;
nuevo->nombre[0] = strdup(nombre1);
nuevo->nombre[1] = strdup(nombre2);
nuevo->ant = *ultimo;
*ultimo = nuevo;
}
/*
* Buscar es un procedimiento que itera sobre la lista enlazada buscando a una
* tupla de nombres.
* Argumentos: ultimo, es un apuntador a la última posición de la lista.
* nombre1, es una cadena de caracteres que representan al nombre del
* primer amigo.
* nombre2, es una cadena de caracteres que representan al nombre del
* segundo amigo.
* Retorna: Un apuntador al nodo de la lista que contiene a la tupla, si esta
* existe, en caso contrario, retorna NULL.
*/
LISTA **buscar(LISTA **ultimo, char *nombre1, char *nombre2){
LISTA **list;
list = ultimo;
while(*list != NULL){
if (!strcmp(((*list)->nombre[0]),nombre1)){
if(!strcmp(((*list)->nombre[1]), nombre2)){
return list;
}
}
list = &(*list)->ant;
}
return NULL;
}
/*
* destruirLista es un procedimiento que destruye la lista previamente creada.
* Esto para liberar memoria.
* Argumentos: ultimo, es un apuntador a la última posición de la lista.
* Retorna: nada, las modificaciones las hace a la lista enlazada en memoria.
*/
void destruirLista(LISTA **ultimo){
while(*ultimo != NULL){
free((*ultimo)->nombre[0]);
free((*ultimo)->nombre[1]);
free((*ultimo)->nombre);
free((*ultimo)->amigos1);
free((*ultimo)->amigos2);
free((*ultimo)->comunes);
(*ultimo)->sig = NULL;
if(((*ultimo)->ant != NULL)){
*ultimo = (*ultimo)->ant;
(*ultimo)->sig->ant = NULL;
}
else
*ultimo = NULL;
}
}
<file_sep>/**
* README
*
* Descripción: Este archivo contiene las instrucciones generales para
* el correcto funcionamiento de la compilación y ejecución de la tarea.
* También, incluye consideraciones generales.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 27-04-2015.
*/
Requisitos:
1- Sistema Operativo basado en UNIX.
2- Compilador GCC.
3- Tener instalado make.
Descripción general:
1- La carpeta de la tarea contiene los siguientes archivos:
- main.c.
- Bases.c.
- listaEnlazada.c
- Bases.h.
- listaEnlazada.h.
- Makefile.
- Este archivo README.
Instrucciones para compilar el proyecto:
1- Abrir una ventana de Terminal.
2- Hacer "cd" hasta la carpeta del proyecto.
3- Ejecutar el comando "make".
4- Los archivos compilados ".o" se encontrarán en la misma carpeta.
Instruccicones para ejecutar el proyecto:
1- En la misma ventana de terminal ejecutar el comando
"./preguntas nombreArchivo" donde en nombreA rchivo debe ir la dirección
del archivo.
Notas:
1- El proyecto fue compilado y ejecutado exitosamente en los siguientes
sistemas operativos: Debian GNU/Linux 7.8 (wheezy) y en los servidores del
LDC.
<file_sep>//MiPrimerProgramaEnC.
#include <stdio.h>
#include <stdlib.h>
//Creo el TIPO ARBOL, y llamo a arbol para poder referenciarlo a el mismo.
typedef struct arbol{
int nodo;
struct arbol *izq;
struct arbol *der;
} ARBOL;
/*
//Función para recorrer el árbol.
void recorridoEnArbol(ARBOL *miArbol,int k){
if (miArbol->der == NULL && miArbol->izq == NULL){
}
else{
}
}
*/
/*La estructura es la siguiente:
1- Se crea el árbol y se pide la memoria para el primer nodo y sus apuntadores.
2- Se inicializa el primer nodo en 0.
3- Para crear las otras cajas, hacemos que el sistema nos de memoria tanto en
el hijo izquierdo como en el derecho.
4- Inicializamos los otros hijos.
*/
void main(){
//Se define el árbol.
ARBOL *elArbol;
//Se pide memoria al sistema.
elArbol = (ARBOL *)malloc(sizeof(ARBOL));
//Inicializo el primer nodo.
elArbol->nodo= 0;
//Pido la memoria para los otros hijos.
elArbol->izq = (ARBOL *)malloc(sizeof(ARBOL));
elArbol->der = (ARBOL *)malloc(sizeof(ARBOL));
//Inicializo los hijos izquierdos y derechos.
elArbol->izq->nodo = 1;
elArbol->izq->izq = NULL;
elArbol->izq->der = NULL;
elArbol->der->nodo = 2;
elArbol->der->izq = NULL;
elArbol->der->der = NULL;
printf("nodo %d\n",elArbol->nodo);
printf("nodo %d\n",elArbol->izq->nodo);
printf("nodo %d\n",elArbol->der->nodo);
free(elArbol);
}
<file_sep>/**
* listaEnlazada.c
*
* Descripción: Este archivo contiene las funciones y procedimientos principales
* para la definición del tipo LISTA y PREGUNTA, así como sus atributos.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 27-04-2015.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
/*
* NivelDeComplejidad es un tipo enumerado que representa la complejidad de
* las preguntas.
* basico -> 0.
* intermedio -> 1.
* avanzado -> 2.
*/
enum NivelDeComplejidad {basico, intermedio, avanzado};
/*
* PREGUNTA es un tipo de datos apoyado en la estructura pregunta. Modela
* el esquema de preguntas que se estarán manejando en los archivos y en las
* listas enlazadas.
* Atributos: codigo, entero que representa a la pregunta unívocamente.
* area, caracter
* complejidad, tipo enumerado que representa la dificultad de la
* pregunta, básico->0;intermedio ->1;avanzado->2.
* strings, es un arreglo que almacena 4 strings de largo a lo sumo 100.
* la primera posición almacena la pregunta y las demás, las
* respuestas.
* respuestaCorrecta, entero del 1 al 3 que identifica la respuesta
* correcta a la pregunta.
*/
typedef struct pregunta{
int codigo;
char area;
enum NivelDeComplejidad complejidad;
char strings[4][100];
int respuestaCorrecta;
} PREGUNTA;
/*
* LISTA es un tipo de datos apoyado en la estructura lista. Es la implementación
* en C de una lista doblemente enlazada. En LISTA se guarda una pregunta y dos
* apuntadores a otros elementos de la misma.
* Atributos: preg, es una PREGUNTA.
* sig, apuntador al siguiente elemento de la lista.
* ant, apuntador al elemento anterior de la lista.
*/
typedef struct lista {
PREGUNTA preg;
struct lista *sig;
struct lista *ant;
} LISTA;
/*
* insertar es un procedimiento que añade una pregunta a la lista enlazada.
* La inserción se hace al final de la lista y se actualiza el puntero al último
* elemento.
* Argumentos: ultimo, es un apuntador a la última posición de la lista.
* pregunta, es el tipo PREGUNTA que se va a añadir.
* Retorna: nada, las modificaciones las hace a la lista enlazada en memoria.
*/
void insertar(LISTA **ultimo, PREGUNTA pregunta){
LISTA *nuevo;
nuevo = (LISTA *) malloc(sizeof(LISTA));
if (*ultimo != NULL)
(*ultimo)->sig = nuevo;
nuevo->preg = pregunta;
nuevo->sig = NULL;
nuevo->ant = *ultimo;
*ultimo = nuevo;
}
/*
* buscar es una función que recorre la lista enlazada para encontrar una
* pregunta con el código dado.
* Argumentos: ultimo, es un apuntador a la última posición de la lista.
* codigo, es un entero que representa el código de la pregunta a buscar.
* Retorna: un apuntador al elemento de la lista que contiene a la pregunta con
* el código buscado, si existe. En caso contrario, devuelve NULL.
*/
LISTA **buscar(LISTA **ultimo, int codigo){
LISTA **list;
list = ultimo;
while(*list != NULL){
if (((*list)->preg.codigo) == codigo){
return list;
}
list = &(*list)->ant;
}
return NULL;
}
/*
* eliminar es una función que dado un elemento de la lista, lo elimina y hace
* free para liberar memoria.
* Argumentos: list, es un apuntador a la lista.
* codigo, es un entero que representa el código de la pregunta a eliminar.
* Retorna: 1 si elimina la pregunta exitosamente, 0 en caso contrario.
*/
int eliminar(LISTA **list, int codigo){
LISTA **temp;
temp = buscar(list,codigo);
if (temp != NULL){
//Cuando hay un solo elemento en la lista.
if((*temp)->sig == NULL && (*temp)->ant == NULL){
*list = NULL;
free(*temp);
}
//Aquí estamos eliminando el último nodo.
else if((*temp)->sig == NULL && (*temp)->ant != NULL){
**list = *(*list)->ant; //Situamos el último en el anterior.
(*list)->sig = NULL;
free(*temp);
}
//Aquí estamos eliminando el primer nodo.
else if((*temp)->sig != NULL && (*temp)->ant == NULL){
(*temp)->sig->ant = NULL;
free(*temp);
}
//Aquí estamos en un caso del medio.
else{
(*temp)->ant->sig = (*temp)->sig;
(*temp)->sig->ant = (*temp)->ant;
free(*temp);
}
return 1;
}
else
return 0;
}
<file_sep>/**
* main.c
*
* Descripción: Este archivo contiene el ciclo principal del programa.
*
* Autores:
* Br. <NAME>, carné: 12-11152.
* Br. <NAME>, carné: 10-10613.
*
* Última modificación: 27-04-2015.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "bases.h"
/*
* Es una función que verifica que las opciones presionadas por el usuario
* sean válidas, como por ejemplo: no se llame dos veces a leer del archivo
* en la misma sesión ó que se hagan operaciones sin que estén los datos
* cargados en memoria.
* Argumentos: listas, apuntador al arreglo de las listas enlazadas.
* Respuesta, es un caracter que contiene la respuesta del usuario.
* valor, entero que dice si es primera vez que se entra a la función.
* Retorna: un entero que dice si la operación es válida o no. Si devuelve 1 es
* válida, en caso contrario, devuelve 0.
*/
int verificarErrores(LISTA **listas,char Respuesta,int valor){
//Primero verificamos si hay datos leídos de la base en memoria.
if(listas[0] == NULL && listas[1] == NULL && listas[2] == NULL && valor != 1){
//Como no hay nada en memoria verificamos si la respuesta fue leer de la
//base de datos.
if(Respuesta == '1' || Respuesta == '0')
return 1;
else
printf("Lo lamentamos, no hay datos en memoria y por lo tanto no\
puede hacer esta operación.\n");
printf("Será devuelto al menú principal.\n");
return 0;
}
else{
//Como si hay datos en la memoria, verificaremos que no vuelva a leer
//del archivo.
if(Respuesta == '1'){
printf("Lo lamentamos, ya los datos de la base de datos se leyeron.\n");
printf("Será devuelto al menú principal.\n");
return 0;
}
else
return 1;
}
}
/*
* main es la función principal del programa. En ella están las verificaciones
* básicas del programa; como el pasaje de parámetros correctos. Además, está el
* ciclo principal de interacción con el usuario y la base de datos.
* Argumentos: argc, entero que cuenta los argumentos.
* argv, cadena de caracteres, en argv[0] está el nombre del programa,
* en argv[1] está el directorio del archivo.
*
*/
int main (int argc, char *argv[]){
if(argc != 2){
printf("Disculpe, el formato es ./nombreDePrograma nombreDeArchivo\n");
printf("Vuelva a ejecutar el programa.\n");
exit(1);
}
else{
/*
* Cuando el número de argumentos es correcto, pasamos a mostrar la
* bienvenida al programa y enseguida mostramos las opciones. Recibiremos
* la respuesta y con un Switch se decidirá qué hará el programa.
*/
char Respuesta;
int numero;
int valor = 0;
LISTA *listas[3];
listas[0] = NULL; //Preguntas de complejidad 0.
listas[1] = NULL; //Preguntas de complejidad 1.
listas[2] = NULL; //Preguntas de complejidad 2.
printf("Bienvidos al programa. Creadores: <NAME> y Leslie\
Rodrigues\n\n");
do{
printf("#######################################################\n");
printf("################## MENÚ #################\n");
printf("#######################################################\n");
printf("Para usar el menú, escriba el número de la opción que quiera\
que el programa realice.");
printf("\n");
printf("\tOpción 1: Leer los datos de la base de datos.\n");
printf("\tOpción 2: Consultar la base de datos.\n");
printf("\tOpción 3: Consultar la base de datos por complejidad.\n");
printf("\tOpción 4: Eliminar una pregunta.\n");
printf("\tOpción 5: Insertar una pregunta.\n");
printf("\tOpción 6: Salvar los cambios en la base de datos.\n");
printf("\tOpción 0: Salir del sistema.\n\n");
scanf("%c",&Respuesta);
getchar();
if(verificarErrores(listas,Respuesta,valor)){
switch(Respuesta){
case '1':
printf("#######################################################\n");
printf("################## LEER ARCHIVO #################\n");
printf("#######################################################\n");
LeerArchivo(argv[1],&listas[0]);
valor = 1;
printf("A continuación será regresado al menú principal.\n\n");
break;
case '2':
printf("#######################################################\n");
printf("############### CONSULTAR TODOS DATOS #############\n");
printf("#######################################################\n");
ConsultarComplejidad(&listas[0],0);
ConsultarComplejidad(&listas[0],1);
ConsultarComplejidad(&listas[0],2);
printf("A continuación será regresado al menú principal.\n\n");
break;
case '3':
printf("#######################################################\n");
printf("############### CONSULTA POR NIVEL #############\n");
printf("#######################################################\n");
printf("Indique el nivel de complejidad que quiera consultar\n");
scanf("%d",&numero);
getchar();
ConsultarComplejidad(&listas[0],numero);
printf("A continuación será regresado al menú principal.\n\n");
break;
case '4':
printf("#######################################################\n");
printf("############### ELIMINAR UNA PREGUNTA #############\n");
printf("#######################################################\n");
printf("Introduzca el codigo de la pregunta que desea eliminar: ");
scanf("%d",&numero);
getchar();
printf("\n");
EliminarPregunta(numero,&listas[0]);
printf("A continuación será regresado al menú principal.\n");
break;
case '5':
printf("#######################################################\n");
printf("############### INSERTAR UNA PREGUNTA #############\n");
printf("#######################################################\n");
InsertarPregunta(&listas[0]);
printf("A continuación será regresado al menú principal.\n\n");
break;
case '6':
printf("#######################################################\n");
printf("############### SALVAR LOS DATOS #############\n");
printf("#######################################################\n");
Salvar(argv[1],&listas[0]);
printf("A continuación será regresado al menú principal.\n\n");
break;
case '0':
printf("#######################################################\n");
printf("############### SALIR DEL SISTEMA #############\n");
printf("#######################################################\n");
Salvar(argv[1],&listas[0]);
printf("Esperamos que el sistema haya sido de su agrado. Hasta pronto.\n");
break;
default:
printf("El caracter %c no es válido. Introduzca nuevamente la\
opción\n",Respuesta);
}
}
} while(Respuesta != '0');
exit(0);
}
}
<file_sep>#
# Makefile
#
# Archivo de make para compilar y limpiar los directorios del proyecto.
#
# Autores:
# Br. <NAME>, carné: 12-11152.
# Br. LeslieRodrigues, carné: 10-10613.
#
# Última modificación: 22-06-2015.
#
#Definimos nuestras variables.
CC := gcc
MODULOS := main.o funcionesAuxiliares.o
default: $(MODULOS)
$(CC) -Wall -o MiCuento $(MODULOS)
make clean
main.o: main.c funcionesAuxiliares.h
$(CC) -c main.c -o main.o
funcionesAuxiliares.o: funcionesAuxiliares.c funcionesAuxiliares.h
$(CC) -c funcionesAuxiliares.c -o funcionesAuxiliares.o
clean:
rm -f *.o
reset
| c76412b86a42b4f05afa8b3d531d476b2163f5aa | [
"Text",
"C",
"Makefile",
"Shell"
] | 23 | C | fernandobperezm/LabSistemasOperativos | b04017c77e38f82b08577d7be30d5fca20880b20 | f853f0d2e6ea563983a5dffc4034228fd9e90ba7 |
refs/heads/master | <file_sep>package tennis;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class SerialClient extends Network {
private Float[] ball_coord = new Float[2];
private Float[] racketL_coord = new Float[2];
private Float[] racketR_coord = new Float[2];
private Integer[] score = new Integer[2];
Boolean sendConnected = false;
Boolean startedSendConnection = false;
Boolean listenConnected = false;
Boolean startedListenConnection = false;
public String joinedIP;
SerialClient(Control c) {
super(c);
sendPort=10006;
listenPort=10007;
}
private class ReceiverThread implements Runnable {
public void run() {
try {
while (true) {
String received;
while((received = in.readLine()) == null);
switch(received.charAt(0))
{
case 'B':
ball_coord[0]=Float.parseFloat(received.substring(1).trim());
while((received = in.readLine()) == null);
ball_coord[1]=Float.parseFloat(received.trim());
control.setBall_inst(ball_coord);
break;
case 'L':
racketL_coord[1]=Float.parseFloat(received.substring(1).trim());
control.setRacketL(racketL_coord);
break;
case 'R':
racketR_coord[1]=Float.parseFloat(received.substring(1).trim());
control.setRacketR(racketR_coord);
break;
case 'S':
score[0]=Integer.parseInt(received.substring(1).trim());
while((received = in.readLine()) == null);
score[1]=Integer.parseInt(received.trim());
control.setScore(score);
break;
case 'G':
switch (Integer.parseInt(received.substring(1).trim()))
{
case 0: control.continueGame(); break;
case 1: control.pauseGame(); break;
default:
}
break;
case 'E': control.exitGame(); break;
default:
System.out.println("Kapott: \""+received+"\"");
}
}
} catch (Exception ex) {
control.networkError(ex,"CLIENT_READOBJECT");
System.out.println(ex.getMessage());
System.err.println("Server disconnected!");
disconnectListen();
System.out.println("Try to reconnect");
sendReconnect();
connect();
}
}
}
void send(Key toSend) {
try {
if (out == null)
connect();
String sentence;
System.out.println("sendKey");
sentence = 'K'+toSend.getName() + '\n' + Boolean.toString(toSend.getState())+ '\n';
out.writeBytes(sentence);
} catch (IOException ex) {
control.networkError(ex,"CLIENT_SENDKEY");
System.err.println("Send error.");
disconnectSend();
}
}
void connect(){
connect(joinedIP);
}
void connect(String ip) {
joinedIP=ip;
try {
if(!startedSendConnection && !sendConnected)
{
startedSendConnection=true;
sendSocket = new Socket(ip,sendPort);
out = new DataOutputStream(sendSocket.getOutputStream());
sendConnected=true;
startedSendConnection=false;
}
if(!startedListenConnection && !listenConnected)
{
startedListenConnection = true;
listenSocket = new Socket(ip,listenPort);
in = new BufferedReader(new InputStreamReader(listenSocket.getInputStream()));
listenConnected=true;
startedListenConnection = false;
Thread rec = new Thread(new ReceiverThread());
rec.start();
}
} catch (IllegalArgumentException ex) {
control.networkError(ex,"CLIENT_CONSTRUCT");
System.err.println("One of the arguments are illegal");
} catch (UnknownHostException ex) {
control.networkError(ex,"CLIENT_CONNECT");
System.err.println("Don't know about host");
} catch (IOException ex) {
control.networkError(ex,"CLIENT_CONNECT");
System.err.println("Couldn't get I/O for the connection. ");
JOptionPane.showMessageDialog(null, "Cannot connect to server!");
}
}
@Override
void disconnectSend() {
try {
sendConnected=false;
if (out != null)
out.close();
if (sendSocket != null)
sendSocket.close();
} catch (IOException ex) {
control.networkError(ex,"CLIENT_DISCONNECT");
System.err.println("Error while closing conn.");
}
System.out.println("disconnectedSend");
}
@Override
void disconnectListen() {
try{
listenConnected=false;
if (in != null)
in.close();
if (listenSocket != null)
listenSocket.close();
} catch (IOException ex) {
control.networkError(ex,"CLIENT_DISCONNECT");
System.err.println("Error while closing conn.");
}
System.out.println("disconnectedListen");
}
@Override
void disconnect() {
disconnectListen();
disconnectSend();
}
void sendReconnect()
{
try {
if(out==null)
connect();
out.writeBytes("J\n");
} catch (IOException ex) {
control.networkError(ex,"CLIENT_SENDKEY");
System.err.println("Send error.");
disconnectSend();
}
}
@Override
void sendExit()
{
try {
if(out==null)
connect();
out.writeBytes("E\n");
} catch (IOException ex) {
control.networkError(ex,"CLIENT_SENDKEY");
System.err.println("Send error.");
disconnectSend();
}
}
}
<file_sep>package tennis;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.net.Socket;
abstract class Network {
protected Control control;
protected Socket sendSocket;
protected Socket listenSocket;
protected Integer sendPort;
protected Integer listenPort;
protected DataOutputStream out;
protected BufferedReader in;
Network(Control c) {
control = c;
}
abstract void sendExit();
abstract void disconnect();
abstract void disconnectListen();
abstract void disconnectSend();
}<file_sep>package tennis;
public class PaprikasKrumpli {
private final String weight="Sok";
private final String taste="Jó";
PaprikasKrumpli(){}
public void getPaprikasKrumpli(){
System.out.println("Elkészítés: A hagymát megtisztítjuk és kockára vágjuk. Kevés olajat forrósítunk egy lábasban, beletesszük a hagymát és a felkarikázott kolbászt, és megpirítjuk. Lehúzzuk a lábast a tűzről, és megszórjuk 2 fakanálnyi pirospaprikával. Átkeverjük, majd hozzáadjuk a megmosott, megtisztított és kockára vágott burgonyát és felöntjük annyi vízzel, ami majdnem ellepi. Megsózzuk, borsozzuk, ételízesítőt is tehetünk bele, és addig főzzük, amíg a burgonya majdnem meg nem puhul. Ekkor hozzáadjuk a felkarikázott virslit, és addig főzzük, amíg meg nem puhul. Friss kenyérrel, savanyú uborkával tálaljuk.");
}
}<file_sep>package tennis;
import java.security.InvalidParameterException;
public abstract class GeometricObject {
// pálya méretek
protected final Integer xFieldMax = 1280;
protected final Integer xFieldMin = 0;
protected final Integer yFieldMax = 620;
protected final Integer yFieldMin = 0;
protected Integer[] colourRGB = new Integer[3];
protected Float[] coordinates = new Float[2];
protected Float direction; // [0, 2*pi) intervallum, 0 irány: D-kr x tengelye (óramutató járásával ellentétes irányú)
protected Float velocity; // "pixel / time_tick" mértékegység
public GeometricObject(Integer Colour[]) throws InvalidParameterException {
if(Colour.length == 3 && 0<=Colour[0] && Colour[0]<256 && 0<=Colour[1] && Colour[1]<256 && 0<=Colour[2] && Colour[2]<256)
colourRGB = Colour;
else
{
throw new InvalidParameterException();
}
velocity = (float)0;
}
public Integer[] getColour() {
return colourRGB;
}
public Float[] getCoordinates() {
return coordinates;
}
public Float getDirection() {
return direction;
}
public Float getVelocity() {
return velocity;
}
// pálya koordinátáit konvertálja GUI koordinátákra
// pályán y tengely lentről fel nő, GUI-n fordítva
public Integer[] getGUIcoords (){
Integer[] coordsInt = new Integer[2];
coordsInt[0] = Math.round(this.coordinates[0]);
coordsInt[1] = yFieldMax - Math.round(this.coordinates[1]) +10;
return coordsInt;
}
public Integer[] getasdf(){
Integer[] asdf = new Integer[2];
asdf[0] = 200;
asdf[1] = 500;
return asdf;
}
abstract void setCoordinates(Float[] coordinates) throws InvalidParameterException;
abstract void setDirection(Float Dir) throws InvalidParameterException;
public void setVelocity(Float Vel){
velocity = Vel;
}
abstract public void time();
}<file_sep>package tennis;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
abstract class DrawPanel extends JPanel
{
private static final int WIDTH_WINDOW = 1280;
private static final int HEIGHT_WINDOW = 720;
protected List<Point> ball;
protected List<Point> racket_1;
protected List<Point> racket_2;
public DrawPanel()
{
ball = new ArrayList<>();
racket_1 = new ArrayList<>();
racket_2 = new ArrayList<>();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH_WINDOW, 10);
g.fillRect(0, 630, WIDTH_WINDOW, 10);
for (Point ball : ball)
{
g.fillOval(ball.x-10, ball.y-10, 20, 20);
}
/*
for (Point ball : ball)
{
g.fillRect(ball.x-10, ball.y-10, 20, 20);
}
*/
for (Point racket_1 : racket_1)
{
g.fillRect(racket_1.x-5, racket_1.y-50, 10, 100);
}
for (Point racket_2 : racket_2)
{
g.fillRect(racket_2.x-5, racket_2.y-50, 10, 100);
}
}
}<file_sep>package tennis;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
public class Field extends DrawPanel
{
protected DrawPanel field_panel;
protected JPanel score_panel;
protected JLabel score_label;
public Field(int WIDTH_WINDOW)
{
//Pálya
setLayout(null);
setBounds(0, 80, WIDTH_WINDOW,640);
setBackground(Color.black);
setFocusable(true);
//Billentyűzet gombok
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0), "pause");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "pressed 1_up");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "released 1_up");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "pressed 1_down");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "released 1_down");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "pressed 2_up");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "released 2_up");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "pressed 2_down");
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "released 2_down");
//Eredményjelzõ
score_panel = new JPanel();
score_panel.setLayout(null);
score_panel.setBounds(0, 0, WIDTH_WINDOW,80);
score_panel.setBackground(Color.black);
score_panel.setVisible(false);
score_label = new JLabel("0 : 0");
score_label.setBounds(WIDTH_WINDOW/2-81, 0, 162, 80);
score_label.setFont(new Font("0 : 0", Font.BOLD, 80));
score_label.setForeground(Color.WHITE);
score_panel.add(score_label);
setVisible(false);
}
//Labda, ütők kirajzolása
public void ball(int x, int y) {
ball.clear();
ball.add(new Point(x, y));
repaint();
}
public void racket_1(int x, int y) {
racket_1.clear();
racket_1.add(new Point(x, y));
repaint();
}
public void racket_2(int x, int y) {
racket_2.clear();
racket_2.add(new Point(x, y));
repaint();
}
public void setScore(String score){
score_label.setText(score);
}
//gomb esemény aktiválás
protected void add_action(AbstractAction pause_action, AbstractAction pressed_1_up_action, AbstractAction released_1_up_action, AbstractAction pressed_1_down_action, AbstractAction released_1_down_action, AbstractAction pressed_2_up_action, AbstractAction released_2_up_action, AbstractAction pressed_2_down_action, AbstractAction released_2_down_action)
{
getActionMap().put("pause", pause_action);
getActionMap().put("pressed 1_up", pressed_1_up_action);
getActionMap().put("released 1_up", released_1_up_action);
getActionMap().put("pressed 1_down", pressed_1_down_action);
getActionMap().put("released 1_down", released_1_down_action);
getActionMap().put("pressed 2_up", pressed_2_up_action);
getActionMap().put("released 2_up", released_2_up_action);
getActionMap().put("pressed 2_down", pressed_2_down_action);
getActionMap().put("released 2_down", released_2_down_action);
}
}<file_sep>package tennis;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.ParseException;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.AbstractAction;
import javax.swing.Timer;
public class GUI extends JFrame implements ActionListener
{
private static final int WIDTH_WINDOW = 1280;
private static final int HEIGHT_WINDOW = 720;
private static final int WIDTH_MENU = 435;
private static final int HEIGHT_MENU = 400;
private static final int TIMER_DELAY = 20;
private Timer time;
private Control control;
private Field field_panel;
private Menu menu;
private String winner;
private Pattern ip_pattern;
private int state = 0;
private static final int OFFLINE = 1;
private static final int ONLINE = 2;
private static final int HOST = 3;
private static final int CLIENT = 4;
private Integer racketL_before=0;
private Integer racketR_before=0;
public GUI(Control c)
{
super("Tenisz");
control=c;
setSize(WIDTH_WINDOW+6, HEIGHT_WINDOW+30);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
setResizable(false);
//Pálya kirajzolása 50Hz-el
time = new Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Integer[] coords = new Integer[2];
// bal ütő koordináták megszerzése
coords = control.getRacketL().getGUIcoords();
field_panel.racket_1(coords[0],coords[1]);
if(state==HOST)
if(Math.abs(racketL_before-coords[1])>0)
{
control.hostRacketLChanged();
racketL_before=coords[1];
}
// jobb ütő koordináták megszerzése
coords = control.getRacketR().getGUIcoords();
field_panel.racket_2(coords[0],coords[1]);
if(state==HOST)
if(Math.abs(racketR_before-coords[1])>0)
{
control.hostRacketRChanged();
racketR_before=coords[1];
}
// labda ütő koordináták megszerzése
coords = control.getBall().getGUIcoords();
field_panel.ball(coords[0],coords[1]);
field_panel.setScore(control.getScores()[0] + " : " + control.getScores()[1]);
winner = null;
if(control.getScores()[0] == 5)
{
winner = "<NAME>";
}
if(control.getScores()[1] == 5)
{
winner = "<NAME>";
}
if(winner != null)
{
Object[] button = {"Visszavágó", "Kilépés a menübe"};
if(JOptionPane.showOptionDialog(field_panel, "A nyertes: "+winner,"Vége a játéknak", JOptionPane.OK_OPTION,JOptionPane.PLAIN_MESSAGE, null, button, null) == 1)
{
time.stop();
control.stopGame();
field_panel.setVisible(false);
field_panel.score_panel.setVisible(false);
menu.menu_main_panel.setVisible(true);
control.resetGame();
}
else
{
control.resetGame();
}
}
if(state == HOST)
{
control.hostBall();
}
}
});
//Billentyűzet esemény kezelés
AbstractAction pause_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("Pause",true));
}
};
AbstractAction pressed_1_up_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("UP_Left",true));
}
};
AbstractAction released_1_up_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("UP_Left",false));
}
};
AbstractAction pressed_1_down_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("DOWN_Left",true));
}
};
AbstractAction released_1_down_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("DOWN_Left",false));
}
};
AbstractAction pressed_2_up_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("UP_Right",true));
}
};
AbstractAction released_2_up_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("UP_Right",false));
}
};
AbstractAction pressed_2_down_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("DOWN_Right",true));
}
};
AbstractAction released_2_down_action = new AbstractAction (){
@Override
public void actionPerformed(ActionEvent e) {
control.keyStroke(new Key("DOWN_Right",false));
}
};
//ip cím formátum
ip_pattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
//Menü, pálya példányosítás
try {
menu = new Menu(WIDTH_MENU, HEIGHT_MENU, WIDTH_WINDOW);
} catch (ParseException e1) {
e1.printStackTrace();
}
menu.add_action(this);
field_panel = new Field(WIDTH_WINDOW);
field_panel.add_action(pause_action, pressed_1_up_action, released_1_up_action, pressed_1_down_action, released_1_down_action, pressed_2_up_action, released_2_up_action, pressed_2_down_action, released_2_down_action);
menu.add(field_panel);
menu.add(field_panel.score_panel);
field_panel.add(menu.pause_panel);
setContentPane(menu);
setVisible(true);
}
protected void start()
{
field_panel.setVisible(true);
field_panel.score_panel.setVisible(true);
time.start();
}
public int getState(){
return state;
}
//Menügomb esemény kezelés
@Override
public void actionPerformed(ActionEvent e) {
//control.buttonStroke(e.getActionCommand());
String command = e.getActionCommand();
switch (command) {
case "Offline":
state = OFFLINE;
menu.menu_main_panel.setVisible(false);
menu.menu_offline_panel.setVisible(true);
break;
case "Online":
state = ONLINE;
menu.menu_main_panel.setVisible(false);
menu.menu_online_panel.setVisible(true);
break;
case "Kilépés":
System.exit(0);
break;
case "Host":
state = HOST;
menu.menu_online_panel.setVisible(false);
menu.menu_offline_panel.setVisible(true);
break;
case "Kliens":
state = CLIENT;
control.resetGame();
//menu.host_wait_label.setVisible(false);
menu.menu_online_panel.setVisible(false);
menu.menu_client_panel.setVisible(true);
break;
case "<NAME>":
if(state == OFFLINE)
{
control.resetGame();
control.delNet();
menu.menu_offline_panel.setVisible(false);
start();
}
if(state == HOST)
{
control.resetGame();
control.waitClient();
control.startServer();
}
break;
case "Játék betöltése":
if(state == OFFLINE)
{
control.resetGame();
try {
control.loadFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
menu.menu_offline_panel.setVisible(false);
start();
}
if(state == HOST)
{
control.resetGame();
control.waitClient();
try {
control.loadFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
control.startServer();
}
break;
case "Vissza - offline":
if(state == OFFLINE)
{
menu.menu_offline_panel.setVisible(false);
menu.menu_main_panel.setVisible(true);
state = 0;
}
if(state == HOST)
{
menu.menu_offline_panel.setVisible(false);
menu.menu_online_panel.setVisible(true);
//menu.host_wait_label.setVisible(false);
//menu.client_error_label.setVisible(false);
}
break;
case "Vissza - online":
menu.menu_online_panel.setVisible(false);
menu.menu_main_panel.setVisible(true);
//menu.host_wait_label.setVisible(false);
//menu.client_error_label.setVisible(false);
state = 0;
break;
case "Játék mentése":
//showGame();
try {
control.saveFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case "Vissza - pause":
menu.pause_panel.setVisible(false);
control.continueGame();
time.start();
break;
case "Kilépés a menübe":
time.stop();
control.stopGame();
control.disconnect();
control.resetGame();
state = 0;
menu.save_button.setVisible(true);
menu.pause_panel.setVisible(false);
menu.menu_main_panel.setVisible(true);
field_panel.setVisible(false);
field_panel.score_panel.setVisible(false);
break;
case "Csatlakozás":
if(ip_pattern.matcher(menu.ip.getText()).matches())
{
try {
System.out.println(menu.ip.getText());
control.startClient(menu.ip.getText());
menu.menu_client_panel.setVisible(false);
start();
} catch (Exception exp) {
//guibol hivni errort
}
}
break;
case "Vissza - client":
menu.menu_client_panel.setVisible(false);
menu.menu_online_panel.setVisible(true);
//menu.client_error_label.setVisible(false);
state = ONLINE;
break;
default:
break;
}
}
public void ResetGui()
{
time.stop();
state = 0;
menu.save_button.setVisible(true);
menu.pause_panel.setVisible(false);
menu.menu_main_panel.setVisible(true);
field_panel.setVisible(false);
field_panel.score_panel.setVisible(false);
control.stopGame();
control.resetGame();
}
public void showPauseMenu()
{
if(state == CLIENT)
{
menu.save_button.setVisible(false);
}
menu.pause_panel.setVisible(true);
time.stop();
}
public void hidePauseMenu()
{
//control.continueGame();
menu.pause_panel.setVisible(false);
time.start();
}
public Boolean clientConnected(){
if(!time.isRunning())
{
if(state==HOST)
{
menu.menu_offline_panel.setVisible(false);
start();
//menu.host_wait_label.setVisible(true);
return true;
}
else
control.disconnect();
}
return false;
}
}<file_sep>package tennis;
import java.security.InvalidParameterException;
public class Racket extends GeometricObject{
// ütő méretek
private final Float width;
private final Float height;
// ütő sebesség konstans
private final Float speed = 1f;
public Racket(Integer colour[],Float coordinates[], Float wid, Float hei) throws InvalidParameterException{
super(colour);
if(wid<xFieldMax/2 && wid>0)
{
this.width=wid;
}
else
{
throw new InvalidParameterException();
}
if(hei<yFieldMax && hei>0)
{
this.height=hei;
}
else
{
throw new InvalidParameterException();
}
if(coordinates[0]>wid/2+xFieldMin && coordinates[0]<xFieldMax-wid/2)
{
this.coordinates[0] = coordinates[0];
}
else
{
throw new InvalidParameterException();
}
//setCoordinates(coordinates);
this.coordinates = coordinates;
this.direction=(float) (Math.PI/2);
}
@Override
void setCoordinates(Float[] coordinates) throws InvalidParameterException {
if(coordinates[1]>((this.height/2)+yFieldMin) && coordinates[1]<(yFieldMax-(this.height/2))){
this.coordinates[1]=coordinates[1];
}else{
throw new InvalidParameterException();
}
}
@Override
void setDirection(Float Dir) throws InvalidParameterException {
this.direction=(float) (Math.PI/2);
}
public Float getHeight() {
return height;
}
public Float getWidth() {
return width;
}
public void time(){
// amikor eltelik egy "system tick" az ütő y koordinátája megváltozik, x változatlan
// ütő mozgatása: sebesség (velocity) állításával
// ütő iránya (direction) nem érdekes
float y;
y = coordinates[1] + velocity * speed;
// ütő max állásban
if(y + height/2 > yFieldMax){
y = yFieldMax - height/2;
velocity = 0.0f;
}
// ütő min állásban
if(y - height/2 < yFieldMin){
y = yFieldMin + height/2;
velocity = 0.0f;
}
coordinates[1] = y;
}
}
<file_sep>package tennis;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
public class SerialServer extends Network {
private ServerSocket serverListenSocket = null;
private ServerSocket serverSendSocket = null;
private Key got = new Key();
Boolean sendConnected = false;
Boolean startedSendConnection = false;
Boolean listenConnected = false;
Boolean startedListenConnection = false;
SerialServer(Control c) {
super(c);
sendPort=10007;
listenPort=10006;
}
private class connectThread implements Runnable {
public void run() {
try {
System.out.println("Waiting for Client ->to send");
sendSocket = serverSendSocket.accept();
sendConnected=true;
startedSendConnection=false;
out = new DataOutputStream(sendSocket.getOutputStream());
control.clientConnected();
System.out.println("Client connected ->to send");
} catch (IOException e) {
control.networkError(e,"SERVER_WAITING");
System.err.println("Accept failed.send");
disconnectSend();
}
}
}
private class ReceiverThread implements Runnable {
public void run() {
try {
System.out.println("Waiting for Client ->to receive");
listenSocket = serverListenSocket.accept();
listenConnected = true;
startedListenConnection =false;
System.out.println("Client connected ->to receive");
} catch (IOException ex) {
control.networkError(ex,"SERVER_WAITING");
System.err.println("Accept failed.listen");
disconnectListen();
}
try {
in = new BufferedReader(new InputStreamReader(listenSocket.getInputStream()));
} catch (IOException ex) {
control.networkError(ex,"SERVER_CONSTRUCTOR");
System.err.println("Error in = new BufferedReader");
disconnectListen();
return;
}
try {
String received;
while (true) {
while((received = in.readLine()) == null);
switch(received.charAt(0))
{
case 'K':
got.setName(received.substring(1).trim());
received = in.readLine();
got.setState(Boolean.parseBoolean(received.trim()));
control.keyReceived(got);
break;
case 'E':
control.exitGame();
break;
case 'J':
Thread emergency = new Thread(new connectThread());
emergency.run();
break;
default: break;
}
}
}catch (IOException ex) {
//control.networkError(ex,"SERVER_READOBJECT");
System.out.println(ex.getMessage());
System.err.println("Client disconnected! - RecThread.Vege");
disconnectListen();
connect();
}
}
}
void sendBall(Ball ball_ins)
{
if (out == null)
connect();
try {
String floatToString;
floatToString = "B"+Float.toString(ball_ins.getCoordinates()[0]) + '\n' + Float.toString(ball_ins.getCoordinates()[1]) + '\n';
out.writeBytes(floatToString);
} catch (IOException ex) {
control.networkError(ex,"SERVER_SENDSTATES");
System.err.println("Send error.");
disconnectSend();
}
}
void sendRacketL(Racket racketL)
{
if (out == null)
connect();
try {
String floatToString;
floatToString = "L"+Float.toString(racketL.getCoordinates()[1]) + '\n';
out.writeBytes(floatToString);
} catch (IOException ex) {
control.networkError(ex,"SERVER_SENDSTATES");
System.err.println("Send error.");
disconnectSend();
}
}
void sendRacketR(Racket racketR)
{
if (out == null)
connect();
try {
String floatToString;
floatToString = "R"+Float.toString(racketR.getCoordinates()[1]) + '\n';
out.writeBytes(floatToString);
} catch (IOException ex) {
control.networkError(ex,"SERVER_SENDSTATES");
System.err.println("Send error.");
disconnectSend();
}
}
void sendScore(Scores toSend){
try {
if (out == null)
connect();
String intToString;
intToString = "S" + Integer.toString(toSend.getScores()[0]) + '\n'+ Integer.toString(toSend.getScores()[1]) + '\n';
out.writeBytes(intToString);
} catch (IOException ex) {
control.networkError(ex,"SERVER_SENDSCORE");
System.err.println("Send error.");
disconnectSend();
}
}
void sendPause(Integer toSend){
try {
if (out == null)
connect();
String intToString;
intToString = "G" + Integer.toString(toSend) + '\n';
out.writeBytes(intToString);
} catch (IOException ex) {
control.networkError(ex,"SERVER_SENDSCORE");
System.err.println("Send error.");
disconnectSend();
}
}
void connect() {
try {
if(!startedListenConnection && !listenConnected)
{
startedListenConnection=true;
serverListenSocket = new ServerSocket(listenPort);
Thread listen = new Thread(new ReceiverThread());
listen.start();
}
} catch (IOException ex) {
control.networkError(ex,"SERVER_CONNECT");
System.err.println("Could not listen on port: 10007.");
disconnectListen();
}
try{
if(!startedSendConnection && !sendConnected)
{
startedSendConnection=true;
serverSendSocket = new ServerSocket(sendPort);
Thread sendConnect = new Thread(new connectThread());
sendConnect.start();
}
}catch (IOException ex) {
control.networkError(ex,"SERVER_CONNECT");
System.err.println("Could not send on port: 10006.");
disconnectSend();
}
}
@Override
void disconnectListen() {
try {
listenConnected = false;
if (in != null)
in.close();
if (listenSocket != null)
listenSocket.close();
if (serverListenSocket != null)
serverListenSocket.close();
} catch (IOException ex) {
control.networkError(ex,"SERVER_DISCONNECT");
Logger.getLogger(SerialServer.class.getName()).log(Level.SEVERE,null, ex);
}
}
@Override
void disconnectSend() {
try {
sendConnected=false;
if (out != null)
out.close();
if (sendSocket != null)
sendSocket.close();
if (serverSendSocket != null)
serverSendSocket.close();
} catch (IOException ex) {
control.networkError(ex,"SERVER_DISCONNECT");
Logger.getLogger(SerialServer.class.getName()).log(Level.SEVERE,null, ex);
}
}
@Override
void disconnect() {
disconnectListen();
disconnectSend();
}
@Override
void sendExit()
{
try {
if(out==null)
connect();
out.writeBytes("E\n");
} catch (IOException ex) {
control.networkError(ex,"CLIENT_SENDKEY");
System.err.println("Send error.");
disconnectSend();
}
}
}
| c86e78c34b421cd4c64b32e1459e177fad6eb068 | [
"Java"
] | 9 | Java | Somi25/Tennis | 4f09aaad911ea3e8f46f2991d5bfb79a154b910f | b9e0e85f6ca1b9ed7c5180d7f4a2ae467fc89b3c |
refs/heads/master | <file_sep>package engine_test
import (
"testing"
"github.com/m110/moonshot-rts/internal/engine"
"github.com/stretchr/testify/require"
)
type intEvent struct {
value int
}
type stringEvent struct {
value string
}
type subscriber struct {
ints []int
strings []string
}
func (s *subscriber) HandleEvent(e engine.Event) {
switch event := e.(type) {
case intEvent:
s.ints = append(s.ints, event.value)
case stringEvent:
s.strings = append(s.strings, event.value)
default:
panic("received unknown event")
}
}
func TestEventBus(t *testing.T) {
eb := engine.NewEventBus()
s1 := &subscriber{}
s2 := &subscriber{}
eb.Subscribe(intEvent{}, s1)
eb.Subscribe(stringEvent{}, s1)
eb.Subscribe(intEvent{}, s2)
eb.Publish(intEvent{1})
eb.Publish(intEvent{2})
eb.Publish(intEvent{3})
eb.Publish(stringEvent{"a"})
eb.Publish(stringEvent{"b"})
eb.Publish(stringEvent{"c"})
require.Equal(t, []int{1, 2, 3}, s1.ints)
require.Equal(t, []string{"a", "b", "c"}, s1.strings)
require.Equal(t, []int{1, 2, 3}, s2.ints)
require.Nil(t, s2.strings)
}
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type buildingControlEntity interface {
engine.Entity
components.WorldSpaceOwner
components.TimeActionsOwner
}
type spawnedEntity interface {
engine.Entity
components.ClickableOwner
components.MovableOwner
}
type BuildingControlSystem struct {
BaseSystem
entities EntityList
activeBuilding buildingControlEntity
buildPanel *archetypes.Panel
spawnedEntities []spawnedEntity
}
func NewBuildingControlSystem(base BaseSystem) *BuildingControlSystem {
return &BuildingControlSystem{
BaseSystem: base,
}
}
func (b *BuildingControlSystem) Start() {
b.EventBus.Subscribe(EntitySelected{}, b)
b.EventBus.Subscribe(EntityUnselected{}, b)
}
func (b *BuildingControlSystem) Update(dt float64) {
// TODO Rework this (with events?)
spawned := b.spawnedEntities
b.spawnedEntities = nil
for _, u := range spawned {
if u.GetMovable().Target == nil {
u.GetClickable().Enable()
} else {
b.spawnedEntities = append(b.spawnedEntities, u)
}
}
for _, e := range b.entities.All() {
entity, ok := e.(components.UnitSpawnerOwner)
if !ok {
continue
}
// TODO this nil-check doesn't look good
timer := entity.GetUnitSpawner().Timer
if timer != nil {
timer.Update(dt)
for _, c := range e.(buildingControlEntity).GetWorldSpace().Children {
// TODO casting to concrete struct is a hack, there should be a better way to do this
p, ok := c.(archetypes.ProgressBar)
if ok {
p.SetProgress(timer.PercentDone())
}
}
}
}
}
func (b *BuildingControlSystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntitySelected:
foundEntity, ok := b.entities.ByID(event.Entity.ID())
if !ok {
return
}
b.activeBuilding = foundEntity.(buildingControlEntity)
b.ShowBuildPanel()
case EntityUnselected:
if b.activeBuilding != nil && event.Entity.Equals(b.activeBuilding) {
b.activeBuilding = nil
b.Spawner.Destroy(*b.buildPanel)
b.buildPanel = nil
}
}
}
func (b *BuildingControlSystem) ShowBuildPanel() {
getter := atlasSpriteGetter{}
spawner, ok := b.activeBuilding.(components.UnitSpawnerOwner)
if !ok {
// TODO Add more building types?
return
}
// TODO get this from a component
team := components.TeamBlue
var configs []archetypes.ButtonConfig
for i := range spawner.GetUnitSpawner().Options {
o := spawner.GetUnitSpawner().Options[i]
configs = append(configs, archetypes.ButtonConfig{
Sprite: getter.SpriteForUnit(team, o.Class),
Action: func() { b.startSpawningUnit(o) },
})
}
buildPanel := archetypes.NewFourButtonPanel(configs)
b.Spawner.Spawn(buildPanel)
pos := b.activeBuilding.GetWorldSpace().WorldPosition()
buildPanel.GetWorldSpace().SetInWorld(pos.X, pos.Y)
b.buildPanel = &buildPanel
}
func (b *BuildingControlSystem) startSpawningUnit(option components.UnitSpawnerOption) {
// Sanity check, this shouldn't happen
if b.activeBuilding == nil {
return
}
entity := b.activeBuilding.(components.UnitSpawnerOwner)
entity.GetUnitSpawner().AddToQueue(option)
b.addSpawnUnitTimer(b.activeBuilding)
}
func (b *BuildingControlSystem) addSpawnUnitTimer(entity buildingControlEntity) {
unitSpawner := entity.(components.UnitSpawnerOwner).GetUnitSpawner()
if unitSpawner.Timer == nil {
option, ok := unitSpawner.PopFromQueue()
if !ok {
return
}
b.showProgressBar(entity)
timer := engine.NewCountdownTimer(option.SpawnTime, func() {
// TODO get this from a component
team := components.TeamBlue
pos := entity.GetWorldSpace().WorldPosition()
b.spawnUnit(pos, team, option.Class)
unitSpawner.Timer = nil
for _, c := range entity.GetWorldSpace().Children {
// TODO casting to concrete struct is a hack, there should be a better way to do this
p, ok := c.(archetypes.ProgressBar)
if ok {
b.Spawner.Destroy(p)
// TODO A RemoveChild is missing here. Not trivial for now, and despawning should work fine
}
}
b.addSpawnUnitTimer(entity)
})
unitSpawner.Timer = timer
}
}
func (b *BuildingControlSystem) showProgressBar(entity buildingControlEntity) {
progressBar := archetypes.NewHorizontalProgressBar()
b.Spawner.Spawn(progressBar)
entity.GetWorldSpace().AddChild(progressBar)
// TODO better position
progressBar.GetWorldSpace().Translate(0, -30)
}
func (b *BuildingControlSystem) spawnUnit(spawnPosition engine.Vector, team components.Team, class components.Class) {
// TODO This should be based on tiles, not absolute position
target := spawnPosition
target.Translate(
float64(engine.RandomRange(-32, 32)),
float64(engine.RandomRange(12, 32)),
)
// TODO This is a terrible duplication :(
switch class {
case components.ClassWorker:
worker := archetypes.NewWorker(team, atlasSpriteGetter{})
b.Spawner.Spawn(worker)
worker.GetWorldSpace().SetInWorld(spawnPosition.X, spawnPosition.Y)
worker.Clickable.Disable()
worker.GetMovable().SetTarget(target)
b.spawnedEntities = append(b.spawnedEntities, worker)
default:
unit := archetypes.NewUnit(team, class, atlasSpriteGetter{})
b.Spawner.Spawn(unit)
unit.GetWorldSpace().SetInWorld(spawnPosition.X, spawnPosition.Y)
unit.Clickable.Disable()
unit.GetMovable().SetTarget(target)
b.spawnedEntities = append(b.spawnedEntities, unit)
}
}
func (b *BuildingControlSystem) Add(entity buildingControlEntity) {
b.entities.Add(entity)
}
func (b *BuildingControlSystem) Remove(entity engine.Entity) {
b.entities.Remove(entity)
}
<file_sep>package main
import (
"bytes"
"fmt"
"os"
"reflect"
"strings"
"text/template"
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/archetypes/tiles"
"github.com/m110/moonshot-rts/internal/components"
)
const rootPkg = "github.com/m110/moonshot-rts/"
const prefix = "*components."
const archetypeInterfaceTemplate = `
func ({{.Short}} {{.Struct}}) Get{{.TypeName}}() {{.Prefix}}{{.TypeName}} {
return {{.Short}}.{{.TypeName}}
}
`
const componentOwnerTemplate = `
type {{.TypeName}}Owner interface {
Get{{.TypeName}}() *{{.TypeName}}
}
`
type archetypeData struct {
Short string
Struct string
TypeName string
Prefix string
}
type componentData struct {
TypeName string
}
var allArchetypes = []interface{}{
archetypes.Building{},
archetypes.Object{},
archetypes.Overlay{},
archetypes.Panel{},
archetypes.PanelButton{},
archetypes.ProgressBar{},
tiles.Tile{},
archetypes.Unit{},
archetypes.Worker{},
}
var allComponents = []interface{}{
components.Area{},
components.AreaOccupant{},
components.Builder{},
components.Button{},
components.Clickable{},
components.Collider{},
components.Drawable{},
components.Movable{},
components.ProgressBar{},
components.ResourcesSource{},
components.ResourcesCollector{},
components.Selectable{},
components.Size{},
components.TimeActions{},
components.UnitSpawner{},
components.WorldSpace{},
}
func main() {
archetypesContent := map[string]string{}
archetypeTpl, err := template.New("").Parse(archetypeInterfaceTemplate)
if err != nil {
panic(err)
}
for _, s := range allArchetypes {
t := reflect.TypeOf(s)
pkg := strings.Replace(t.PkgPath(), rootPkg, "", 1)
pkg += "/getters_gen.go"
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if strings.HasPrefix(f.Type.String(), prefix) {
data := archetypeData{
Short: string(strings.ToLower(t.Name())[0]),
Struct: t.Name(),
TypeName: strings.Replace(f.Type.String(), prefix, "", 1),
Prefix: prefix,
}
b := bytes.Buffer{}
err = archetypeTpl.Execute(&b, data)
if err != nil {
panic(err)
}
archetypesContent[pkg] += b.String()
}
}
}
for path, c := range archetypesContent {
o, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
elements := strings.Split(path, "/")
pkg := elements[len(elements)-2]
header := fmt.Sprintf("package %v\n\nimport \"%vinternal/components\"\n", pkg, rootPkg)
_, err = o.WriteString(header + c)
if err != nil {
panic(err)
}
}
componentsContent := map[string]string{}
componentTpl, err := template.New("").Parse(componentOwnerTemplate)
if err != nil {
panic(err)
}
for _, c := range allComponents {
t := reflect.TypeOf(c)
pkg := strings.Replace(t.PkgPath(), rootPkg, "", 1)
pkg += "/owners_gen.go"
names := strings.Split(t.Name(), ".")
typeName := names[len(names)-1]
data := componentData{
TypeName: typeName,
}
b := bytes.Buffer{}
err = componentTpl.Execute(&b, data)
if err != nil {
panic(err)
}
componentsContent[pkg] += b.String()
}
for path, c := range componentsContent {
o, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
elements := strings.Split(path, "/")
pkg := elements[len(elements)-2]
header := fmt.Sprintf("package %v\n", pkg)
_, err = o.WriteString(header + c)
if err != nil {
panic(err)
}
}
}
<file_sep>package components
type AreaOwner interface {
GetArea() *Area
}
type AreaOccupantOwner interface {
GetAreaOccupant() *AreaOccupant
}
type BuilderOwner interface {
GetBuilder() *Builder
}
type ButtonOwner interface {
GetButton() *Button
}
type ClickableOwner interface {
GetClickable() *Clickable
}
type ColliderOwner interface {
GetCollider() *Collider
}
type DrawableOwner interface {
GetDrawable() *Drawable
}
type MovableOwner interface {
GetMovable() *Movable
}
type ProgressBarOwner interface {
GetProgressBar() *ProgressBar
}
type ResourcesSourceOwner interface {
GetResourcesSource() *ResourcesSource
}
type ResourcesCollectorOwner interface {
GetResourcesCollector() *ResourcesCollector
}
type SelectableOwner interface {
GetSelectable() *Selectable
}
type SizeOwner interface {
GetSize() *Size
}
type TimeActionsOwner interface {
GetTimeActions() *TimeActions
}
type UnitSpawnerOwner interface {
GetUnitSpawner() *UnitSpawner
}
type WorldSpaceOwner interface {
GetWorldSpace() *WorldSpace
}
<file_sep>package game
import (
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/m110/moonshot-rts/internal/engine"
"github.com/m110/moonshot-rts/internal/systems"
)
type Game struct {
config systems.Config
eventBus *engine.EventBus
systems []systems.System
drawers []systems.Drawer
}
func NewGame(config systems.Config) *Game {
g := &Game{
config: config,
}
g.Start()
return g
}
// Start starts a new game. It can also work as a restart, so all important initialisation
// should happen here, instead of NewGame.
// Why not initialize systems in their constructors? For example, the subscribers can be set up
// in the constructors, and when the Start() is executing, you know all systems are in place.
// So it's possible to use spawner in the Start() methods.
func (g *Game) Start() {
g.eventBus = engine.NewEventBus()
baseSystem := systems.NewBaseSystem(g.config, g.eventBus, g)
tilemapSystem := systems.NewTilemapSystem(baseSystem)
g.systems = []systems.System{
tilemapSystem,
systems.NewDrawingSystem(baseSystem),
systems.NewSelectionSystem(baseSystem),
systems.NewUISystem(baseSystem),
systems.NewResourcesSystem(baseSystem),
systems.NewUnitControlSystem(baseSystem, tilemapSystem),
systems.NewBuildingControlSystem(baseSystem),
systems.NewClickingSystem(baseSystem),
systems.NewButtonsSystem(baseSystem),
systems.NewTimeActionsSystem(baseSystem),
systems.NewProgressBarSystem(baseSystem),
systems.NewCollisionSystem(baseSystem),
systems.NewAreaOccupySystem(baseSystem),
systems.NewAreaSystem(baseSystem),
}
for _, s := range g.systems {
d, ok := s.(systems.Drawer)
if ok {
g.drawers = append(g.drawers, d)
}
s.Start()
}
}
func (g *Game) Update() error {
if inpututil.IsKeyJustPressed(ebiten.KeyR) {
g.Start()
return nil
}
dt := 1.0 / float64(ebiten.MaxTPS())
for _, s := range g.systems {
s.Update(dt)
}
g.eventBus.Flush()
return nil
}
func (g Game) Draw(screen *ebiten.Image) {
screenSprite := engine.NewSpriteFromImage(screen)
for _, s := range g.drawers {
s.Draw(screenSprite)
}
}
func (g Game) Layout(outsideWidth, outsideHeight int) (int, int) {
return outsideWidth, outsideHeight
}
func (g Game) Systems() []systems.System {
return g.systems
}
<file_sep>package engine
import "time"
type CountdownTimer struct {
time time.Duration
resetTime time.Duration
action func()
}
func NewCountdownTimer(duration time.Duration, action func()) *CountdownTimer {
return &CountdownTimer{
time: duration,
resetTime: duration,
action: action,
}
}
func (t CountdownTimer) Done() bool {
return t.time <= 0
}
func (t *CountdownTimer) Update(dt float64) {
if !t.Done() {
t.time -= time.Duration(float64(time.Second) * dt)
if t.Done() {
t.action()
}
}
}
func (t CountdownTimer) PercentDone() float64 {
pct := float64(t.resetTime-t.time) / float64(t.resetTime)
if pct > 1.0 {
pct = 1.0
}
return pct
}
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
var baseResources = components.Resources{
Food: 3,
Wood: 2,
Stone: 0,
Gold: 1,
Iron: 0,
}
type resourcesEntity interface {
engine.Entity
components.AreaOccupantOwner
components.ColliderOwner
components.MovableOwner
components.ResourcesCollectorOwner
}
type ResourcesUpdated struct {
UsedResources components.Resources
AvailableResources components.Resources
}
type ResourcesSystem struct {
BaseSystem
entities EntityMap
availableResources components.Resources
usedResources components.Resources
tileOverlays map[resourcesEntity]archetypes.Object
}
func NewResourcesSystem(base BaseSystem) *ResourcesSystem {
r := &ResourcesSystem{
BaseSystem: base,
tileOverlays: map[resourcesEntity]archetypes.Object{},
}
r.EventBus.Subscribe(EntityOccupiedArea{}, r)
r.EventBus.Subscribe(EntityStoppedOccupyingArea{}, r)
return r
}
func (r *ResourcesSystem) Start() {
r.updateResources()
}
func (r *ResourcesSystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntityOccupiedArea:
ent, ok := r.entities.ByID(event.Entity.ID())
if !ok {
return
}
tile, ok := event.Area.(components.ResourcesSourceOwner)
if !ok {
return
}
entity := ent.(resourcesEntity)
entity.GetResourcesCollector().CurrentResources = tile.GetResourcesSource().Resources
entity.GetResourcesCollector().Collecting = true
r.updateResources()
case EntityStoppedOccupyingArea:
ent, ok := r.entities.ByID(event.Entity.ID())
if !ok {
return
}
entity := ent.(resourcesEntity)
entity.GetResourcesCollector().Collecting = false
r.updateResources()
}
}
func (r *ResourcesSystem) updateResources() {
r.availableResources = baseResources
for _, e := range r.entities.All() {
entity := e.(resourcesEntity)
if entity.GetResourcesCollector().Collecting {
r.availableResources.Update(entity.GetResourcesCollector().CurrentResources)
}
}
r.EventBus.Publish(ResourcesUpdated{
UsedResources: r.usedResources,
AvailableResources: r.availableResources,
})
}
func (r ResourcesSystem) Update(dt float64) {}
func (r *ResourcesSystem) Add(entity resourcesEntity) {
r.entities.Add(entity)
}
func (r *ResourcesSystem) Remove(entity engine.Entity) {
r.entities.Remove(entity)
}
<file_sep>package archetypes
import (
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type Panel struct {
Object
*components.Clickable
buttons []PanelButton
}
type ButtonConfig struct {
Sprite engine.Sprite
Action func()
}
func NewFourButtonPanel(buttonConfigs []ButtonConfig) Panel {
p := Panel{
Object: NewObject(sprites.PanelBrown, components.LayerUIPanel),
}
p.Drawable.Sprite.Scale(engine.Vector{X: 1.5, Y: 1.5})
p.Clickable = &components.Clickable{
Bounds: components.BoundsFromSprite(p.Drawable.Sprite),
}
x := 20
y := 15
for i, s := range buttonConfigs {
b := NewPanelButton(components.UIColorBeige, s.Sprite, s.Action)
p.buttons = append(p.buttons, b)
p.WorldSpace.AddChild(b)
b.WorldSpace.Translate(float64(x), float64(y))
if i%2 != 0 {
y += 60
x = 20
} else {
x += 60
}
}
return p
}
type PanelButton struct {
Object
*components.Clickable
*components.Button
}
func NewPanelButton(color components.UIColor, spriteTop engine.Sprite, action func()) PanelButton {
spriteTop.SetPivot(engine.NewPivotForSprite(spriteTop, engine.PivotCenter))
var spriteReleased, spritePressed engine.Sprite
switch color {
case components.UIColorBeige:
spriteReleased = sprites.ButtonBeige
spritePressed = sprites.ButtonBeigePressed
case components.UIColorBrown:
spriteReleased = sprites.ButtonBrown
spritePressed = sprites.ButtonBrownPressed
}
b := PanelButton{
Object: NewObject(engine.Sprite{}, components.LayerUIButton),
Button: &components.Button{
Action: action,
Pressed: false,
SpriteTop: spriteTop,
SpriteReleased: spriteReleased,
SpritePressed: spritePressed,
},
}
b.Clickable = &components.Clickable{
Bounds: components.BoundsFromSprite(b.Button.SpriteReleased),
}
return b
}
type ProgressBar struct {
Object
*components.ProgressBar
}
func NewHorizontalProgressBar() ProgressBar {
return ProgressBar{
Object: NewObject(engine.NewBlankSprite(1, 1), components.LayerForeground),
ProgressBar: &components.ProgressBar{
Background: components.ProgressBarSprites{
Left: sprites.BarBackHorizontalLeft,
Mid: sprites.BarBackHorizontalMid,
Right: sprites.BarBackHorizontalRight,
},
Foreground: components.ProgressBarSprites{
Left: sprites.BarGreenHorizontalLeft,
Mid: sprites.BarGreenHorizontalMid,
Right: sprites.BarGreenHorizontalRight,
},
},
}
}
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type timeActionsEntity interface {
engine.Entity
components.TimeActionsOwner
}
type TimeActionsSystem struct {
BaseSystem
entities EntityList
}
func NewTimeActionsSystem(base BaseSystem) *TimeActionsSystem {
return &TimeActionsSystem{
BaseSystem: base,
}
}
func (t *TimeActionsSystem) Start() {
}
func (t *TimeActionsSystem) Update(dt float64) {
for _, e := range t.entities.All() {
entity := e.(timeActionsEntity)
timers := entity.GetTimeActions().Timers
entity.GetTimeActions().Timers = nil
for _, t := range timers {
t.Update(dt)
if !t.Done() {
entity.GetTimeActions().AddTimer(t)
}
}
}
}
func (t *TimeActionsSystem) Add(entity timeActionsEntity) {
t.entities.Add(entity)
}
func (t *TimeActionsSystem) Remove(entity engine.Entity) {
t.entities.Remove(entity)
}
<file_sep>module github.com/m110/moonshot-rts
go 1.14
require (
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20201101223321-f087fae2c024 // indirect
github.com/hajimehoshi/ebiten/v2 v2.1.0-alpha.2.0.20201107194443-e09f3aa2865e
github.com/stretchr/testify v1.6.1
golang.org/x/exp v0.0.0-20201008143054-e3b2a7f2fdc7 // indirect
golang.org/x/image v0.0.0-20200927104501-e162460cd6b5
golang.org/x/sys v0.0.0-20201107080550-4d91cf3a1aaf // indirect
)
<file_sep>package components
import (
"github.com/m110/moonshot-rts/internal/engine"
)
type UIColor int
const (
UIColorBeige UIColor = iota
UIColorBrown
)
type Button struct {
Action func()
Pressed bool
SpriteTop engine.Sprite
SpriteReleased engine.Sprite
SpritePressed engine.Sprite
}
<file_sep>package systems
type Config struct {
TileMap TilemapConfig
UI UIConfig
}
func (c Config) WindowSize() (width int, height int) {
width = c.TileMap.TotalWidth()
height = c.UI.Height + c.TileMap.TotalHeight()
return width, height
}
<file_sep>package archetypes
import (
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type Tree struct {
Object
}
func NewTree(treeType TreeType) Tree {
var sprite engine.Sprite
size := engine.RandomRange(0, 1)
switch treeType {
case TreeStandard:
if size == 0 {
sprite = sprites.TreeBig
} else {
sprite = sprites.TreeSmall
}
case TreePine:
if size == 0 {
sprite = sprites.PineBig
} else {
sprite = sprites.PineSmall
}
}
return Tree{
Object: NewObject(sprite, components.LayerObjects),
}
}
<file_sep>package systems
import (
"fmt"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/text"
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
"golang.org/x/image/colornames"
"golang.org/x/image/font"
)
type UIConfig struct {
OffsetX int
OffsetY int
Width int
Height int
Font font.Face
}
type UISystem struct {
BaseSystem
resources archetypes.Object
fps archetypes.Object
}
func NewUISystem(base BaseSystem) *UISystem {
return &UISystem{
BaseSystem: base,
}
}
func (u *UISystem) Start() {
u.EventBus.Subscribe(ResourcesUpdated{}, u)
sprite := engine.NewFilledSprite(u.Config.UI.Width, u.Config.UI.Height, colornames.Black)
ui := archetypes.NewObject(sprite, components.UILayerBackground)
ui.Translate(
float64(u.Config.UI.OffsetX),
float64(u.Config.UI.OffsetY),
)
resourcesSprite := engine.NewBlankSprite(u.Config.UI.Width, u.Config.UI.Height)
u.resources = archetypes.NewObject(resourcesSprite, components.UILayerText)
ui.GetWorldSpace().AddChild(u.resources)
u.resources.Translate(20, 20)
fpsSprite := engine.NewBlankSprite(200, u.Config.UI.Height)
u.fps = archetypes.NewObject(fpsSprite, components.UILayerText)
ui.GetWorldSpace().AddChild(u.fps)
u.fps.Translate(float64(u.Config.UI.Width-200), 20)
u.Spawner.Spawn(ui)
}
func (u UISystem) updateResources(used components.Resources, available components.Resources) {
content := fmt.Sprintf("Food: %v/%v Wood: %v/%v Stone: %v/%v Gold: %v/%v Iron: %v/%v",
used.Food, available.Food,
used.Wood, available.Wood,
used.Stone, available.Stone,
used.Gold, available.Gold,
used.Iron, available.Iron,
)
u.resources.Sprite.Image().Fill(colornames.Black)
bounds := text.BoundString(u.Config.UI.Font, content)
text.Draw(
u.resources.Sprite.Image(),
content,
u.Config.UI.Font,
0, bounds.Dy(), colornames.White,
)
}
func (u UISystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case ResourcesUpdated:
u.updateResources(event.UsedResources, event.AvailableResources)
}
}
func (u UISystem) Update(_ float64) {
content := fmt.Sprintf("FPS: %2.0f", ebiten.CurrentFPS())
u.fps.Sprite.Image().Fill(colornames.Black)
bounds := text.BoundString(u.Config.UI.Font, content)
text.Draw(
u.fps.Sprite.Image(),
content,
u.Config.UI.Font,
0, bounds.Dy(), colornames.White,
)
}
func (u UISystem) Remove(entity engine.Entity) {}
<file_sep># Moonshot RTS
This is a game in development for [Github Game Off 2020](https://itch.io/jam/game-off-2020). Made in Go with [ebiten](https://github.com/hajimehoshi/ebiten).
## Why Go?
While I usually use Unity for game jams, I decided to try writing a game in Go this time.
* It's fun to build a simple engine from scratch, even if it takes longer time.
* Since it's GitHub's Game Off, I want this game to be fully open source.
* While Unity is a complete platform, it feels bloated at times and I had a terrible experience using it together with git.
* I hope the simplicity of Go's syntax can make it easier to understand the project for anyone looking to get into Go or gamedev.
## Theme
* It's a moonshot, because it's my first attempt at an RTS. 😅
* Building an empire out of a small settlement is a moonshot as well.
## Engine
I use [ebiten](https://github.com/hajimehoshi/ebiten) library for drawing images and basic game loop.
I'm trying to build a practical [Entity-Component-System](https://en.wikipedia.org/wiki/Entity_component_system) pattern.
What I did so far is heavily inspired by [EngoEngine/ecs](https://github.com/EngoEngine/ecs). However, I took a bit
different approach with interfaces. This is still under heavy development, though. 🙂
The TL;DR version of ECS is:
* The entire game is built out of **Entities**, **Components**, and **Systems**.
* An **entity** is a container for **components** with a unique ID.
* A **component** is a data structure, describing some set of common values.
* A **system** is where the game logic lives for a particular area.
For example, there's `DrawingSystem` that draws sprites on the screen.
It requires an entity with `Drawable` (a sprite) and `WorldSpace` (a position) components.
## Project structure
* `internal/`
* `archetypes`
* `assets`
* `components`
* `engine`
* `game`
* `systems`
## Game
* Right now, my idea is a mix between Age of Empires style RTS, and Civilzation resource tiles
* However, I started out focusing on the engine, so I'm not sure where this will go yet. 😀
## Assets
This will possibly change, but right now:
* [Medieval RTS from Kenney](https://kenney.nl/assets/medieval-rts)
* [UI Pack: RPG Expansion from Kenney](https://kenney.nl/assets/ui-pack-rpg-expansion)
* OpenSans font from Google
## Running
```
go run ./cmd/rts
```
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/engine"
)
type System interface {
Start()
Update(dt float64)
Remove(entity engine.Entity)
}
type Drawer interface {
Draw(canvas engine.Sprite)
}
type systemsProvider interface {
Systems() []System
}
<file_sep>package tiles
import (
"math/rand"
"golang.org/x/image/colornames"
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type GroundType int
const (
GroundGrass GroundType = iota
GroundSand
GroundSea
)
func NewGroundTile(groundType GroundType) Tile {
var sprite engine.Sprite
switch groundType {
case GroundGrass:
sprite = sprites.Grass1
case GroundSand:
sprite = sprites.Sand1
case GroundSea:
sprite = sprites.Water1
}
width, height := sprite.Size()
areaOverlay := archetypes.NewOverlay(width, height, engine.PivotTopLeft, colornames.Lime)
t := Tile{
BaseEntity: engine.NewBaseEntity(),
WorldSpace: &components.WorldSpace{},
Drawable: &components.Drawable{
Sprite: sprite,
Layer: components.LayerGround,
},
Clickable: &components.Clickable{
Bounds: components.BoundsFromSprite(sprite),
},
Collider: &components.Collider{
Bounds: components.BoundsFromSprite(sprite),
Layer: components.CollisionLayerGround,
},
ResourcesSource: &components.ResourcesSource{},
Area: &components.Area{
Overlay: areaOverlay,
},
}
t.GetWorldSpace().AddChild(areaOverlay)
return t
}
type ForestType int
const (
ForestStandard ForestType = iota
ForestPine
ForestMixed
)
func NewForestTile(groundType GroundType, forestType ForestType) Tile {
t := NewGroundTile(groundType)
treesCount := engine.RandomRange(2, 5)
y := engine.RandomRange(5, 15)
for i := 0; i < treesCount; i++ {
y += engine.RandomRange(5, 10)
tree := archetypes.NewTree(forestToTripType(forestType))
t.GetWorldSpace().AddChild(tree)
tree.Translate(
float64(rand.Intn(50)+5),
float64(y),
)
}
t.ResourcesSource.Resources.Wood = treesCount
return t
}
func forestToTripType(forestType ForestType) archetypes.TreeType {
switch forestType {
case ForestStandard:
return archetypes.TreeStandard
case ForestPine:
return archetypes.TreePine
case ForestMixed:
r := engine.RandomRange(0, 1)
if r == 0 {
return archetypes.TreeStandard
} else {
return archetypes.TreePine
}
default:
return archetypes.TreeStandard
}
}
func NewMountainsTile(groundType GroundType, mountainType archetypes.MountainType) Tile {
t := NewGroundTile(groundType)
width := int(t.Clickable.Bounds.Width)
height := int(t.Clickable.Bounds.Height)
widthOffset := width / 4.0
heightOffset := height / 4.0
mountain := archetypes.NewMountain(mountainType)
mountain.GetWorldSpace().SetLocal(
float64(engine.RandomRange(widthOffset, width-widthOffset)),
float64(engine.RandomRange(heightOffset, height-heightOffset)),
)
t.GetWorldSpace().AddChild(mountain)
switch mountainType {
case archetypes.MountainStone:
t.ResourcesSource.Resources.Stone = 1
case archetypes.MountainIron:
t.ResourcesSource.Resources.Iron = 1
case archetypes.MountainGold:
t.ResourcesSource.Resources.Gold = 1
}
return t
}
func NewBuildingTile(groundType GroundType, buildingType components.BuildingType) Tile {
t := NewGroundTile(groundType)
buildingPos := engine.Vector{
X: t.Clickable.Bounds.Width / 2.0,
Y: t.Clickable.Bounds.Height,
}
building := archetypes.NewBuilding(buildingPos, buildingType)
t.GetWorldSpace().AddChild(building)
return t
}
<file_sep>package systems
import (
"fmt"
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/archetypes/tiles"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type Spawner struct {
systemsProvider systemsProvider
}
func NewSpawner(systemsProvider systemsProvider) Spawner {
return Spawner{
systemsProvider: systemsProvider,
}
}
func (s Spawner) Spawn(e engine.Entity) {
switch entity := e.(type) {
case tiles.Tile:
s.spawnTile(entity)
case archetypes.Building:
s.spawnBuilding(entity)
case archetypes.Unit:
s.spawnUnit(entity)
case archetypes.Worker:
s.spawnWorker(entity)
case archetypes.Panel:
s.spawnPanel(entity)
case archetypes.PanelButton:
s.spawnPanelButton(entity)
case archetypes.ProgressBar:
s.spawnProgressBar(entity)
default:
// Fallback to drawing system for the simplest entities
if drawingEntity, ok := e.(DrawingEntity); ok {
s.spawnDrawingEntity(drawingEntity)
} else {
panic(fmt.Sprintf("No suitable function found to spawn entity %#v", entity))
}
}
// Spawn all children
if worldSpaceOwner, ok := e.(components.WorldSpaceOwner); ok {
for _, child := range worldSpaceOwner.GetWorldSpace().Children {
s.Spawn(child.(engine.Entity))
}
}
}
func (s Spawner) Destroy(e engine.Entity) {
switch entity := e.(type) {
case archetypes.Panel:
s.destroyPanel(entity)
case archetypes.PanelButton:
s.destroyPanelButton(entity)
case archetypes.ProgressBar:
s.destroyProgressBar(entity)
default:
panic(fmt.Sprintf("No suitable function found to destroy entity %#v", entity))
}
// Destroy all children
if worldSpaceOwner, ok := e.(components.WorldSpaceOwner); ok {
for _, child := range worldSpaceOwner.GetWorldSpace().Children {
s.Destroy(child.(engine.Entity))
}
}
}
func (s Spawner) spawnTile(tile tiles.Tile) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(tile)
case *CollisionSystem:
system.Add(tile)
case *AreaSystem:
system.Add(tile)
}
}
}
func (s Spawner) spawnBuilding(building archetypes.Building) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(building)
case *SelectionSystem:
system.Add(building)
case *BuildingControlSystem:
system.Add(building)
case *ClickingSystem:
system.Add(building)
case *TimeActionsSystem:
system.Add(building)
case *CollisionSystem:
system.Add(building)
}
}
}
func (s Spawner) spawnUnit(unit archetypes.Unit) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(unit)
case *SelectionSystem:
system.Add(unit)
case *UnitControlSystem:
system.Add(unit)
case *ClickingSystem:
system.Add(unit)
case *CollisionSystem:
system.Add(unit)
case *AreaOccupySystem:
system.Add(unit)
}
}
}
func (s Spawner) spawnWorker(worker archetypes.Worker) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(worker)
case *SelectionSystem:
system.Add(worker)
case *UnitControlSystem:
system.Add(worker)
case *ClickingSystem:
system.Add(worker)
case *CollisionSystem:
system.Add(worker)
case *AreaOccupySystem:
system.Add(worker)
case *ResourcesSystem:
system.Add(worker)
}
}
}
func (s Spawner) spawnPanel(panel archetypes.Panel) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(panel)
case *ClickingSystem:
system.Add(panel)
}
}
}
func (s Spawner) destroyPanel(panel archetypes.Panel) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Remove(panel)
case *ClickingSystem:
system.Remove(panel)
}
}
}
func (s Spawner) spawnPanelButton(button archetypes.PanelButton) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(button)
case *ClickingSystem:
system.Add(button)
case *ButtonsSystem:
system.Add(button)
}
}
}
func (s Spawner) destroyPanelButton(button archetypes.PanelButton) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Remove(button)
case *ClickingSystem:
system.Remove(button)
case *ButtonsSystem:
system.Remove(button)
}
}
}
func (s Spawner) spawnProgressBar(progressBar archetypes.ProgressBar) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(progressBar)
case *ProgressBarSystem:
system.Add(progressBar)
}
}
}
func (s Spawner) destroyProgressBar(progressBar archetypes.ProgressBar) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Remove(progressBar)
case *ProgressBarSystem:
system.Remove(progressBar)
}
}
}
func (s Spawner) spawnDrawingEntity(entity DrawingEntity) {
for _, sys := range s.systemsProvider.Systems() {
switch system := sys.(type) {
case *DrawingSystem:
system.Add(entity)
}
}
}
<file_sep>package archetypes
import (
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type TreeType int
const (
TreeStandard TreeType = iota
TreePine
)
type Object struct {
*engine.BaseEntity
*components.WorldSpace
*components.Drawable
}
func NewObject(sprite engine.Sprite, layer components.DrawingLayer) Object {
return Object{
BaseEntity: engine.NewBaseEntity(),
WorldSpace: &components.WorldSpace{},
Drawable: &components.Drawable{
Sprite: sprite,
Layer: layer,
},
}
}
<file_sep>package systems
import (
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type selectionEntity interface {
engine.Entity
components.WorldSpaceOwner
components.SelectableOwner
components.ClickableOwner
}
type SelectionSystem struct {
BaseSystem
entities EntityList
selectedEntities []selectionEntity
}
type EntitySelected struct {
Entity engine.Entity
}
type EntityUnselected struct {
Entity engine.Entity
}
func NewSelectionSystem(base BaseSystem) *SelectionSystem {
s := &SelectionSystem{
BaseSystem: base,
}
s.EventBus.Subscribe(EntityClicked{}, s)
s.EventBus.Subscribe(EntitiesClicked{}, s)
s.EventBus.Subscribe(PointClicked{}, s)
return s
}
func (s *SelectionSystem) Start() {
}
func (s *SelectionSystem) Update(dt float64) {
if inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonRight) {
s.unselectCurrentEntities()
}
}
func (s *SelectionSystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntityClicked:
if len(s.selectedEntities) > 0 {
_, ok := s.entities.ByID(event.Entity.ID())
if ok {
s.unselectCurrentEntities()
return
}
}
s.selectEntity(event.Entity)
case EntitiesClicked:
if len(s.selectedEntities) > 0 {
s.unselectCurrentEntities()
return
}
for _, entity := range event.Entities {
s.selectEntity(entity)
}
case PointClicked:
s.unselectCurrentEntities()
}
}
func (s *SelectionSystem) selectEntity(e engine.Entity) bool {
_, ok := s.entities.ByID(e.ID())
if !ok {
return false
}
entity := e.(selectionEntity)
entity.GetSelectable().Select()
s.selectedEntities = append(s.selectedEntities, entity)
s.EventBus.Publish(EntitySelected{
Entity: entity,
})
return true
}
func (s *SelectionSystem) unselectCurrentEntities() {
if len(s.selectedEntities) == 0 {
return
}
for _, e := range s.selectedEntities {
e.GetSelectable().Unselect()
s.EventBus.Publish(EntityUnselected{Entity: e})
}
s.selectedEntities = nil
}
func (s *SelectionSystem) Add(entity selectionEntity) {
s.entities.Add(entity)
}
func (s SelectionSystem) Remove(entity engine.Entity) {
s.entities.Remove(entity)
}
<file_sep>package systems
import "github.com/m110/moonshot-rts/internal/engine"
type EntityList struct {
entities []engine.Entity
}
func (l *EntityList) All() []engine.Entity {
return l.entities
}
func (l *EntityList) Clear() {
l.entities = nil
}
func (l EntityList) Empty() bool {
return len(l.entities) == 0
}
func (l *EntityList) ByID(id engine.EntityID) (engine.Entity, bool) {
for _, e := range l.entities {
if e.ID() == id {
return e, true
}
}
return nil, false
}
func (l *EntityList) Add(entity engine.Entity) {
l.entities = append(l.entities, entity)
}
func (l *EntityList) Remove(entity engine.Entity) {
foundIndex := -1
for i, e := range l.entities {
if e.Equals(entity) {
foundIndex = i
break
}
}
if foundIndex >= 0 {
l.entities = append(l.entities[:foundIndex], l.entities[foundIndex+1:]...)
}
}
type EntityMap struct {
entities map[engine.EntityID]engine.Entity
}
func (m *EntityMap) All() []engine.Entity {
var entities []engine.Entity
for _, e := range m.entities {
entities = append(entities, e)
}
return entities
}
func (m *EntityMap) Clear() {
m.entities = map[engine.EntityID]engine.Entity{}
}
func (m EntityMap) Empty() bool {
return len(m.entities) == 0
}
func (m *EntityMap) ByID(id engine.EntityID) (engine.Entity, bool) {
if m.entities == nil {
return nil, false
}
e, ok := m.entities[id]
return e, ok
}
func (m *EntityMap) Add(entity engine.Entity) {
if m.entities == nil {
m.entities = map[engine.EntityID]engine.Entity{}
}
m.entities[entity.ID()] = entity
}
func (m *EntityMap) Remove(entity engine.Entity) {
delete(m.entities, entity.ID())
}
<file_sep>package sprites
import (
"encoding/xml"
"image"
_ "image/png"
"io/ioutil"
"os"
"github.com/hajimehoshi/ebiten/v2"
)
type Atlas struct {
tiles []Tile
tilesMap map[string]Tile
}
type Tile struct {
Name string
X int
Y int
Width int
Height int
Image *ebiten.Image
}
type textureAtlas struct {
TextureAtlas xml.Name `xml:"TextureAtlas"`
ImagePath string `xml:"imagePath,attr"`
SubTextures []subTexture `xml:"SubTexture"`
}
type subTexture struct {
Name string `xml:"name,attr"`
X int `xml:"x,attr"`
Y int `xml:"y,attr"`
Width int `xml:"width,attr"`
Height int `xml:"height,attr"`
}
func NewAtlas(descriptorPath string) (Atlas, error) {
descriptorFile, err := os.Open(descriptorPath)
if err != nil {
return Atlas{}, err
}
descriptorContent, err := ioutil.ReadAll(descriptorFile)
if err != nil {
return Atlas{}, err
}
var texAtlas textureAtlas
err = xml.Unmarshal(descriptorContent, &texAtlas)
if err != nil {
return Atlas{}, err
}
tilesFile, err := os.Open(texAtlas.ImagePath)
if err != nil {
return Atlas{}, err
}
imgContent, _, err := image.Decode(tilesFile)
if err != nil {
return Atlas{}, err
}
tilesImage := ebiten.NewImageFromImage(imgContent)
var tiles []Tile
tilesMap := map[string]Tile{}
for _, st := range texAtlas.SubTextures {
subImage := tilesImage.SubImage(image.Rect(st.X, st.Y, st.X+st.Width, st.Y+st.Height)).(*ebiten.Image)
tile := Tile{
Name: st.Name,
X: st.X,
Y: st.Y,
Width: st.Width,
Height: st.Height,
Image: subImage,
}
tiles = append(tiles, tile)
tilesMap[st.Name] = tile
}
return Atlas{
tiles: tiles,
tilesMap: tilesMap,
}, nil
}
func (a Atlas) Tiles() []Tile {
return a.tiles
}
func (a Atlas) TileByName(name string) Tile {
tile, ok := a.tilesMap[name]
if !ok {
panic("tile not found: " + name)
}
return tile
}
func (a Atlas) ImageByName(name string) *ebiten.Image {
return a.TileByName(name).Image
}
<file_sep>package archetypes
import (
"time"
"golang.org/x/image/colornames"
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type Building struct {
Object
*components.Selectable
*components.Clickable
*components.Collider
*components.UnitSpawner
*components.TimeActions
}
func NewBuilding(position engine.Vector, buildingType components.BuildingType) Building {
var options []components.UnitSpawnerOption
switch buildingType {
case components.BuildingSettlement:
options = []components.UnitSpawnerOption{
{
Class: components.ClassWorker,
SpawnTime: 5 * time.Second,
},
}
case components.BuildingBarracks:
options = []components.UnitSpawnerOption{
{
Class: components.ClassWarrior,
SpawnTime: 5 * time.Second,
},
{
Class: components.ClassKnight,
SpawnTime: 10 * time.Second,
},
}
case components.BuildingChapel:
options = []components.UnitSpawnerOption{
{
Class: components.ClassPriest,
SpawnTime: 15 * time.Second,
},
}
}
bottomSprite, topSprite := SpritesForBuilding(buildingType)
w, h := bottomSprite.Size()
if !topSprite.IsZero() {
h += topSprite.Height()
}
overlay := NewOverlay(w, h, engine.PivotBottom, colornames.White)
b := Building{
Object: NewObject(bottomSprite, components.LayerObjects),
Selectable: &components.Selectable{
Overlay: overlay,
},
Clickable: &components.Clickable{
Bounds: components.BoundsFromSprite(overlay.GetDrawable().Sprite),
},
Collider: &components.Collider{
Bounds: components.BoundsFromSprite(bottomSprite),
Layer: components.CollisionLayerBuildings,
},
UnitSpawner: &components.UnitSpawner{
Options: options,
},
TimeActions: &components.TimeActions{},
}
b.GetWorldSpace().AddChild(overlay)
b.WorldSpace.SetLocal(position.X, position.Y)
if !topSprite.IsZero() {
topSprite := NewObject(topSprite, components.LayerForeground)
topSprite.GetWorldSpace().SetLocal(0, float64(-bottomSprite.Height()))
b.GetWorldSpace().AddChild(topSprite)
}
return b
}
func SpritesForBuilding(buildingType components.BuildingType) (bottomSprite engine.Sprite, topSprite engine.Sprite) {
switch buildingType {
case components.BuildingSettlement:
return sprites.Castle, sprites.CastleTop
case components.BuildingBarracks:
return sprites.Barracks, sprites.BarracksTop
case components.BuildingChapel:
return sprites.Chapel, sprites.ChapelTop
case components.BuildingForge:
return sprites.Forge, engine.Sprite{}
case components.BuildingTower:
return sprites.Tower, sprites.TowerTop
}
return engine.Sprite{}, engine.Sprite{}
}
func SpriteForBuilding(buildingType components.BuildingType) engine.Sprite {
bottom, top := SpritesForBuilding(buildingType)
if top.IsZero() {
return bottom
}
bottomWidth, bottomHeight := bottom.Size()
_, topHeight := top.Size()
width := bottomWidth
height := bottomHeight + topHeight
sprite := engine.NewBlankSprite(width, height)
sprite.DrawAtPosition(top, width/2, topHeight)
sprite.DrawAtPosition(bottom, width/2, height)
return sprite
}
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type areaEntity interface {
engine.Entity
components.AreaOwner
}
type AreaSystem struct {
BaseSystem
entities EntityMap
}
func NewAreaSystem(base BaseSystem) *AreaSystem {
a := &AreaSystem{
BaseSystem: base,
}
a.EventBus.Subscribe(EntityOccupiedArea{}, a)
a.EventBus.Subscribe(EntityStoppedOccupyingArea{}, a)
return a
}
func (a *AreaSystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntityOccupiedArea:
entity, ok := a.entities.ByID(event.Area.ID())
if !ok {
return
}
area := entity.(areaEntity).GetArea()
area.Occupants++
if area.Occupants > 0 {
area.Overlay.GetDrawable().Enable()
}
case EntityStoppedOccupyingArea:
entity, ok := a.entities.ByID(event.Area.ID())
if !ok {
return
}
area := entity.(areaEntity).GetArea()
area.Occupants--
if area.Occupants <= 0 {
area.Overlay.GetDrawable().Disable()
}
}
}
func (a AreaSystem) Start() {
}
func (a *AreaSystem) Update(dt float64) {
}
func (a *AreaSystem) Add(entity areaEntity) {
a.entities.Add(entity)
}
func (a *AreaSystem) Remove(entity engine.Entity) {
a.entities.Remove(entity)
}
<file_sep>package archetypes
import (
"image/color"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type Overlay struct {
*engine.BaseEntity
*components.WorldSpace
*components.Drawable
*components.Size
}
func NewOverlay(width int, height int, pivotType engine.PivotType, c color.RGBA) Overlay {
o := Overlay{
BaseEntity: engine.NewBaseEntity(),
WorldSpace: &components.WorldSpace{},
Size: &components.Size{
Width: width,
Height: height,
},
}
o.Drawable = &components.Drawable{
Sprite: NewRectangleSprite(o, pivotType, c),
Layer: components.LayerUI,
Disabled: true,
}
return o
}
func NewRectangleSprite(owner components.SizeOwner, pivotType engine.PivotType, c color.RGBA) engine.Sprite {
width := float64(owner.GetSize().Width)
height := float64(owner.GetSize().Height)
c.A = 175
sprite := engine.NewBlankSprite(int(width), int(height))
sprite.SetPivot(engine.NewPivotForSprite(sprite, pivotType))
lineSize := 3.0
ebitenutil.DrawRect(sprite.Image(), 0, 0, width, lineSize, c)
ebitenutil.DrawRect(sprite.Image(), 0, 0, lineSize, height, c)
ebitenutil.DrawRect(sprite.Image(), width-lineSize, 0, lineSize, height, c)
ebitenutil.DrawRect(sprite.Image(), 0, height-lineSize, width, lineSize, c)
return sprite
}
<file_sep>package tiles
import "github.com/m110/moonshot-rts/internal/components"
func (t Tile) GetWorldSpace() *components.WorldSpace {
return t.WorldSpace
}
func (t Tile) GetDrawable() *components.Drawable {
return t.Drawable
}
func (t Tile) GetClickable() *components.Clickable {
return t.Clickable
}
func (t Tile) GetCollider() *components.Collider {
return t.Collider
}
func (t Tile) GetResourcesSource() *components.ResourcesSource {
return t.ResourcesSource
}
func (t Tile) GetArea() *components.Area {
return t.Area
}
<file_sep>package engine
import "math"
type Vector struct {
X float64
Y float64
}
func (v Vector) IsZero() bool {
return v.X == 0 && v.Y == 0
}
func (v Vector) Unpack() (x float64, y float64) {
return v.X, v.Y
}
func (v *Vector) Set(x float64, y float64) {
v.X = x
v.Y = y
}
func (v *Vector) Translate(dx float64, dy float64) {
v.X += dx
v.Y += dy
}
func (v Vector) Add(other Vector) Vector {
return Vector{
X: v.X + other.X,
Y: v.Y + other.Y,
}
}
func (v Vector) Sub(other Vector) Vector {
return Vector{
X: v.X - other.X,
Y: v.Y - other.Y,
}
}
func (v Vector) Mul(factor float64) Vector {
return Vector{
X: v.X * factor,
Y: v.Y * factor,
}
}
func (v Vector) Length() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (v Vector) Distance(other Vector) float64 {
return other.Sub(v).Length()
}
func (v Vector) Normalized() Vector {
length := v.Length()
return Vector{
X: v.X / length,
Y: v.Y / length,
}
}
<file_sep>package engine
import (
"fmt"
"image"
"image/color"
"math/rand"
"github.com/hajimehoshi/ebiten/v2"
)
type PivotType int
const (
PivotTop PivotType = iota
PivotCenter
PivotBottom
PivotTopLeft
PivotTopRight
PivotBottomLeft
PivotBottomRight
)
type Sprite struct {
image *ebiten.Image
pivot Vector
}
type Sprites []Sprite
func (s Sprites) Random() Sprite {
return s[rand.Intn(len(s))]
}
func NewBlankSprite(width int, height int) Sprite {
return Sprite{
image: ebiten.NewImage(width, height),
}
}
func NewFilledSprite(width int, height int, c color.Color) Sprite {
image := ebiten.NewImage(width, height)
image.Fill(c)
return Sprite{
image: image,
}
}
func NewBlankSpriteWithPivot(width int, height int, pivot Vector) Sprite {
return Sprite{
image: ebiten.NewImage(width, height),
pivot: pivot,
}
}
func NewSpriteFromImage(image *ebiten.Image) Sprite {
return Sprite{
image: image,
}
}
func NewSpriteFromImageWithPivotType(image *ebiten.Image, pivotType PivotType) Sprite {
return Sprite{
image: image,
pivot: NewPivotForImage(image, pivotType),
}
}
func NewSpriteFromImageWithPivot(image *ebiten.Image, pivot Vector) Sprite {
return Sprite{
image: image,
pivot: pivot,
}
}
func NewSpriteFromSprite(s Sprite) Sprite {
return Sprite{
image: ebiten.NewImageFromImage(s.image),
pivot: s.Pivot(),
}
}
func (s Sprite) IsZero() bool {
return s.image == nil
}
func (s Sprite) Image() *ebiten.Image {
return s.image
}
func (s Sprite) Size() (width int, height int) {
return s.image.Size()
}
func (s Sprite) Width() int {
w, _ := s.image.Size()
return w
}
func (s Sprite) Height() int {
_, h := s.image.Size()
return h
}
func (s *Sprite) SetPivot(p Vector) {
s.pivot = p
}
func (s Sprite) Pivot() Vector {
return s.pivot
}
func (s *Sprite) Scale(scale Vector) {
w, h := s.image.Size()
scaled := ebiten.NewImage(int(float64(w)*scale.X), int(float64(h)*scale.Y))
op := &ebiten.DrawImageOptions{}
op.GeoM.Scale(scale.Unpack())
scaled.DrawImage(s.image, op)
s.image = scaled
}
// Draw draws source sprite on the sprite.
func (s Sprite) Draw(source Sprite) {
s.DrawAtPosition(source, 0, 0)
}
// DrawAtVector draws source sprite on the sprite at given vector.
func (s Sprite) DrawAtVector(source Sprite, v Vector) {
s.DrawAtPosition(source, int(v.X), int(v.Y))
}
// DrawAtVector draws source sprite on the sprite at given point.
func (s Sprite) DrawAtPoint(source Sprite, p Point) {
s.DrawAtPosition(source, p.X, p.Y)
}
// DrawAtPosition draws source sprite on the sprite at given position.
func (s Sprite) DrawAtPosition(source Sprite, x int, y int) {
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(
float64(x)-source.Pivot().X,
float64(y)-source.Pivot().Y,
)
s.image.DrawImage(source.image, op)
}
func (s Sprite) DrawInSection(source Sprite, rect Rect) {
op := &ebiten.DrawImageOptions{}
x := int(rect.Position.X)
y := int(rect.Position.Y)
width := x + int(rect.Width)
height := y + int(rect.Height)
imageRect := image.Rect(x, y, width, height)
s.image.SubImage(imageRect).(*ebiten.Image).DrawImage(source.image, op)
}
func NewPivotForSprite(sprite Sprite, pivotType PivotType) Vector {
return NewPivotForImage(sprite.image, pivotType)
}
func NewPivotForImage(image *ebiten.Image, pivotType PivotType) Vector {
w, h := image.Size()
wCenter := float64(w / 2)
hCenter := float64(h / 2)
switch pivotType {
case PivotTop:
return Vector{X: wCenter, Y: 0}
case PivotCenter:
return Vector{X: wCenter, Y: hCenter}
case PivotBottom:
return Vector{X: wCenter, Y: float64(h)}
case PivotTopLeft:
return Vector{X: 0, Y: 0}
case PivotTopRight:
return Vector{X: float64(w), Y: 0}
case PivotBottomLeft:
return Vector{X: 0, Y: float64(h)}
case PivotBottomRight:
return Vector{X: float64(w), Y: float64(h)}
default:
panic(fmt.Sprintf("unknown pivot: %v", pivotType))
}
}
<file_sep>package engine
import "math/rand"
// RandomRange returns a pseudo-random number in [min,max]
func RandomRange(min int, max int) int {
return rand.Intn(max-min+1) + min
}
<file_sep>package components
import "github.com/m110/moonshot-rts/internal/engine"
type CollisionLayer int
const (
CollisionLayerGround CollisionLayer = iota
CollisionLayerUnits
CollisionLayerBuildings
)
type Collider struct {
Bounds engine.Rect
Layer CollisionLayer
Overlay DrawableOwner
collisions map[engine.EntityID]engine.Entity
}
func (c Collider) HasCollision(other engine.Entity) bool {
_, ok := c.collisions[other.ID()]
return ok
}
func (c *Collider) AddCollision(other engine.Entity) {
if c.collisions == nil {
c.collisions = map[engine.EntityID]engine.Entity{}
}
c.collisions[other.ID()] = other
}
func (c *Collider) RemoveCollision(other engine.Entity) {
delete(c.collisions, other.ID())
}
<file_sep>package engine
import "fmt"
type Event interface {
}
type Subscriber interface {
HandleEvent(event Event)
}
type EventBus struct {
subscribers map[Event][]Subscriber
queue []Event
debug bool
}
func NewEventBus() *EventBus {
return &EventBus{
subscribers: map[Event][]Subscriber{},
debug: false,
}
}
// Flush should be called between game ticks to ensure systems don't conflict with each other.
func (e *EventBus) Flush() {
// The outer loop is needed, because events can trigger more events.
for len(e.queue) > 0 {
queue := e.queue
e.queue = nil
for _, event := range queue {
for _, s := range e.subscribers[eventName(event)] {
if e.debug {
fmt.Printf("%T -> %T\n", event, s)
}
s.HandleEvent(event)
}
}
}
}
func (e *EventBus) Publish(event Event) {
if e.debug {
fmt.Printf("Publishing %T\n", event)
}
e.queue = append(e.queue, event)
}
func (e *EventBus) Subscribe(event Event, subscriber Subscriber) {
if e.debug {
fmt.Printf("Subscribing %T -> %T\n", event, subscriber)
}
name := eventName(event)
e.subscribers[name] = append(e.subscribers[name], subscriber)
}
func eventName(event Event) string {
return fmt.Sprintf("%T", event)
}
<file_sep>package tiles
import (
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
"golang.org/x/image/colornames"
)
func NewDebugTile(width int, height int) archetypes.Object {
c := colornames.Pink
c.A = 120
debugSprite := engine.NewFilledSprite(width-2, height-2, c)
debugPointSprite := engine.NewFilledSprite(1, 1, colornames.Red)
sprite := engine.NewBlankSprite(width, height)
sprite.DrawAtPosition(debugPointSprite, 0, 0)
sprite.DrawAtPosition(debugSprite, 1, 1)
sprite.DrawAtPosition(debugPointSprite, width/2, height/2)
return archetypes.Object{
BaseEntity: engine.NewBaseEntity(),
WorldSpace: &components.WorldSpace{},
Drawable: &components.Drawable{
Sprite: sprite,
Layer: components.LayerForeground,
Disabled: true,
},
}
}
<file_sep>package sprites
import (
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/text"
"github.com/m110/moonshot-rts/internal/assets/fonts"
"golang.org/x/image/colornames"
)
type Showcase struct {
atlas Atlas
width int
height int
}
func NewShowcase(atlas Atlas) Showcase {
var maxWidth, maxHeight int
for _, t := range atlas.tiles {
if t.Width > maxWidth {
maxWidth = t.Width
}
if t.Height > maxHeight {
maxHeight = t.Height
}
}
return Showcase{
atlas: atlas,
width: maxWidth * 2,
height: int(float64(maxHeight) * 1.25),
}
}
func (s Showcase) Draw(canvas *ebiten.Image) {
i := 0
for dy := 0; dy < canvas.Bounds().Max.Y-s.height; dy += s.height {
for dx := 0; dx < canvas.Bounds().Max.X-s.width; dx += s.width {
if i == len(s.atlas.Tiles()) {
return
}
tile := s.atlas.Tiles()[i]
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(float64(dx+s.width/2), float64(dy+s.height/2))
canvas.DrawImage(tile.Image, op)
text.Draw(
canvas,
tile.Name,
fonts.OpenSansRegular,
dx+s.width/4,
dy+int(float64(s.height)*1.25),
colornames.White,
)
i++
}
}
}
<file_sep>package components
import "github.com/m110/moonshot-rts/internal/engine"
type Clickable struct {
// Bounds defines position relative to WorldSpace
Bounds engine.Rect
Disabled bool
ByOverlay bool
}
func (c *Clickable) Disable() {
c.Disabled = true
}
func (c *Clickable) Enable() {
c.Disabled = false
}
func BoundsFromSprite(sprite engine.Sprite) engine.Rect {
w, h := sprite.Size()
pivot := sprite.Pivot()
return engine.Rect{
Position: engine.Vector{
X: -pivot.X,
Y: -pivot.Y,
},
Width: float64(w),
Height: float64(h),
}
}
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type areaOccupyEntity interface {
engine.Entity
components.AreaOccupantOwner
}
type AreaOccupySystem struct {
BaseSystem
entities EntityMap
}
type EntityOccupiedArea struct {
Entity engine.Entity
Area engine.Entity
}
type EntityStoppedOccupyingArea struct {
Entity engine.Entity
Area engine.Entity
}
func NewAreaOccupySystem(base BaseSystem) *AreaOccupySystem {
t := &AreaOccupySystem{
BaseSystem: base,
}
t.EventBus.Subscribe(EntityMoved{}, t)
t.EventBus.Subscribe(EntityReachedTarget{}, t)
t.EventBus.Subscribe(EntitiesCollided{}, t)
t.EventBus.Subscribe(EntitiesOutOfCollision{}, t)
return t
}
func (t AreaOccupySystem) Start() {
}
func (t *AreaOccupySystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntityMoved:
ent, ok := t.entities.ByID(event.Entity.ID())
if !ok {
return
}
entity := ent.(areaOccupyEntity)
occupant := entity.GetAreaOccupant()
if occupant.Occupying && occupant.OccupiedArea != nil {
occupant.Occupying = false
t.EventBus.Publish(EntityStoppedOccupyingArea{
Entity: entity,
Area: entity.GetAreaOccupant().OccupiedArea,
})
}
case EntityReachedTarget:
ent, ok := t.entities.ByID(event.Entity.ID())
if !ok {
return
}
entity := ent.(areaOccupyEntity)
occupant := entity.GetAreaOccupant()
if occupant.OccupiedArea != nil {
occupant.Occupying = true
t.EventBus.Publish(EntityOccupiedArea{
Entity: entity,
Area: occupant.OccupiedArea,
})
}
case EntitiesCollided:
ent, ok := t.entities.ByID(event.Entity.ID())
if !ok {
return
}
entity := ent.(areaOccupyEntity)
occupant := entity.GetAreaOccupant()
_, ok = event.Other.(components.AreaOwner)
if !ok {
return
}
if occupant.OccupiedArea == nil {
occupant.OccupiedArea = event.Other
} else {
occupant.NextArea = event.Other
}
case EntitiesOutOfCollision:
ent, ok := t.entities.ByID(event.Entity.ID())
if !ok {
return
}
entity := ent.(areaOccupyEntity)
occupant := entity.GetAreaOccupant()
if occupant.OccupiedArea == nil || !occupant.OccupiedArea.Equals(event.Other) {
return
}
if occupant.NextArea != nil {
occupant.OccupiedArea = occupant.NextArea
occupant.NextArea = nil
}
}
}
func (t AreaOccupySystem) Update(dt float64) {
}
func (t *AreaOccupySystem) Add(entity areaOccupyEntity) {
t.entities.Add(entity)
}
func (t *AreaOccupySystem) Remove(entity engine.Entity) {
t.entities.Remove(entity)
}
<file_sep>package main
import (
"math/rand"
"time"
"github.com/hajimehoshi/ebiten/v2"
"github.com/m110/moonshot-rts/internal/assets/fonts"
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/game"
"github.com/m110/moonshot-rts/internal/systems"
)
func main() {
rand.Seed(time.Now().UnixNano())
err := fonts.LoadFonts()
if err != nil {
panic(err)
}
err = sprites.LoadSprites("assets/spritesheet.xml", "assets/ui.xml")
if err != nil {
panic(err)
}
tileMapConfig := systems.TilemapConfig{
OffsetX: 0,
OffsetY: 128,
Width: 24,
Height: 12,
TileWidth: 64,
TileHeight: 64,
}
config := systems.Config{
TileMap: tileMapConfig,
UI: systems.UIConfig{
OffsetX: 0,
OffsetY: 0,
Width: tileMapConfig.TotalWidth(),
Height: tileMapConfig.OffsetY,
Font: fonts.OpenSansRegular,
},
}
g := game.NewGame(config)
ebiten.SetWindowSize(config.WindowSize())
err = ebiten.RunGame(g)
if err != nil {
panic(err)
}
}
<file_sep>package systems_test
import (
"testing"
"github.com/m110/moonshot-rts/internal/engine"
"github.com/m110/moonshot-rts/internal/systems"
"github.com/stretchr/testify/require"
)
func TestEntityList_Remove(t *testing.T) {
list := systems.EntityList{}
a := engine.NewBaseEntity()
b := engine.NewBaseEntity()
c := engine.NewBaseEntity()
d := engine.NewBaseEntity()
list.Add(a)
list.Add(b)
list.Add(c)
list.Add(d)
require.Equal(t, []engine.Entity{a, b, c, d}, list.All())
list.Remove(c)
require.Equal(t, []engine.Entity{a, b, d}, list.All())
list.Remove(a)
require.Equal(t, []engine.Entity{b, d}, list.All())
list.Remove(d)
require.Equal(t, []engine.Entity{b}, list.All())
list.Remove(b)
require.Equal(t, []engine.Entity{}, list.All())
// Idempotency
list.Remove(b)
require.Equal(t, []engine.Entity{}, list.All())
}
<file_sep>package components
import "github.com/m110/moonshot-rts/internal/engine"
type WorldSpace struct {
worldPosition engine.Vector
localPosition engine.Vector
Parent *WorldSpace
Children []WorldSpaceOwner
}
func (w *WorldSpace) SetInWorld(x float64, y float64) {
current := w.worldPosition
w.worldPosition.Set(x, y)
w.localPosition.Translate(x-current.X, y-current.Y)
for _, child := range w.Children {
child.GetWorldSpace().updateWorldPositionFromParents()
}
}
func (w *WorldSpace) SetLocal(x float64, y float64) {
current := w.localPosition
w.localPosition.Set(x, y)
w.worldPosition.Translate(x-current.X, y-current.Y)
for _, child := range w.Children {
child.GetWorldSpace().updateWorldPositionFromParents()
}
}
func (w *WorldSpace) Translate(x float64, y float64) {
if w.HasParent() {
w.localPosition.Translate(x, y)
w.worldPosition.Translate(x, y)
} else {
w.worldPosition.Translate(x, y)
}
for _, child := range w.Children {
child.GetWorldSpace().updateWorldPositionFromParents()
}
}
func (w WorldSpace) HasParent() bool {
return w.Parent != nil
}
func (w *WorldSpace) updateWorldPositionFromParents() {
if w.Parent == nil {
return
}
w.worldPosition = w.localPosition
parent := w.Parent
for parent != nil {
w.worldPosition = w.worldPosition.Add(parent.LocalPosition())
parent = parent.Parent
}
for _, child := range w.Children {
child.GetWorldSpace().updateWorldPositionFromParents()
}
}
func (w WorldSpace) LocalPosition() engine.Vector {
if w.HasParent() {
return w.localPosition
}
return w.worldPosition
}
func (w WorldSpace) WorldPosition() engine.Vector {
return w.worldPosition
}
func (w *WorldSpace) AddChild(child WorldSpaceOwner) {
w.Children = append(w.Children, child)
child.GetWorldSpace().Parent = w
child.GetWorldSpace().updateWorldPositionFromParents()
}
<file_sep>package tiles
import (
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type Tile struct {
*engine.BaseEntity
*components.WorldSpace
*components.Drawable
*components.Clickable
*components.Collider
*components.ResourcesSource
*components.Area
}
<file_sep>package components
import "github.com/m110/moonshot-rts/internal/engine"
const AllLayers = 8
type DrawingLayer int
const (
LayerBackground DrawingLayer = iota
LayerGround
LayerObjects
LayerUnits
LayerForeground
LayerUI
LayerUIPanel
LayerUIButton
)
const (
UILayerBackground DrawingLayer = iota
UILayerText
)
type Drawable struct {
Sprite engine.Sprite
Layer DrawingLayer
Disabled bool
}
func (d *Drawable) Enable() {
d.Disabled = false
}
func (d *Drawable) Disable() {
d.Disabled = true
}
<file_sep>package archetypes
import (
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type MountainType int
const (
MountainStone MountainType = iota
MountainGold
MountainIron
)
type Mountain struct {
Object
}
func NewMountain(mountainType MountainType) Mountain {
var sprite engine.Sprite
switch mountainType {
case MountainStone:
size := engine.RandomRange(0, 3)
switch size {
case 0:
sprite = sprites.StoneSmall
case 1:
sprite = sprites.StoneBig
case 2:
sprite = sprites.StoneTwo
case 3:
sprite = sprites.StoneThree
}
case MountainGold:
sprite = sprites.GoldThree
case MountainIron:
sprite = sprites.IronThree
}
return Mountain{
Object: NewObject(sprite, components.LayerObjects),
}
}
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type progressBarEntity interface {
engine.Entity
components.DrawableOwner
components.ProgressBarOwner
}
type ProgressBarSystem struct {
BaseSystem
entities EntityList
}
func NewProgressBarSystem(base BaseSystem) *ProgressBarSystem {
return &ProgressBarSystem{
BaseSystem: base,
}
}
func (p ProgressBarSystem) Start() {
}
func (p ProgressBarSystem) Update(dt float64) {
for _, e := range p.entities.All() {
entity := e.(progressBarEntity)
updateProgressBarSprite(entity)
}
}
func updateProgressBarSprite(entity progressBarEntity) {
bar := entity.GetProgressBar()
width := float64(bar.Background.Full.Width()) * bar.Progress
rect := engine.Rect{
Position: engine.Vector{X: 0, Y: 0},
Width: width,
Height: float64(bar.Background.Full.Height()),
}
entity.GetDrawable().Sprite.Image().Clear()
entity.GetDrawable().Sprite.Draw(bar.Background.Full)
entity.GetDrawable().Sprite.DrawInSection(bar.Foreground.Full, rect)
}
func fillProgressBar(sprites components.ProgressBarSprites, midLength int) engine.Sprite {
width := sprites.Left.Width() + midLength*sprites.Mid.Width() + sprites.Right.Width()
height := sprites.Left.Width() + midLength*sprites.Mid.Width() + sprites.Right.Width()
sprite := engine.NewBlankSprite(width, height)
sprite.DrawAtPosition(sprites.Left, 0, 0)
x := sprites.Left.Width()
for i := 0; i < midLength; i++ {
sprite.DrawAtPosition(sprites.Mid, x, 0)
x += sprites.Mid.Width()
}
sprite.DrawAtPosition(sprites.Right, x, 0)
return sprite
}
func (p *ProgressBarSystem) Add(entity progressBarEntity) {
midLength := 3
bar := entity.GetProgressBar()
bar.Background.Full = fillProgressBar(bar.Background, midLength)
bar.Foreground.Full = fillProgressBar(bar.Foreground, midLength)
entity.GetDrawable().Sprite = engine.NewBlankSprite(bar.Background.Full.Size())
entity.GetDrawable().Sprite.SetPivot(engine.NewPivotForSprite(entity.GetDrawable().Sprite, engine.PivotCenter))
p.entities.Add(entity)
}
func (p *ProgressBarSystem) Remove(entity engine.Entity) {
p.entities.Remove(entity)
}
<file_sep>package systems
import (
"fmt"
"github.com/hajimehoshi/ebiten/v2"
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/archetypes/tiles"
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type unitControlEntity interface {
engine.Entity
components.WorldSpaceOwner
components.MovableOwner
components.AreaOccupantOwner
}
type tileFinder interface {
TileAtPosition(position engine.Vector) (tiles.Tile, bool)
}
type UnitControlSystem struct {
BaseSystem
tileFinder tileFinder
entities EntityList
activeEntities EntityList
buildMode bool
buildingToBuild components.BuilderOption
buildingsQueued map[engine.EntityID]queuedBuilding
buildIcon engine.Sprite
actionButton *archetypes.PanelButton
actionsPanel *archetypes.Panel
highlightedTile archetypes.Object
tileSelectionMode bool
}
type queuedBuilding struct {
DestinationTile tiles.Tile
Option components.BuilderOption
}
type EntityReachedTarget struct {
Entity engine.Entity
}
type EntityMoved struct {
Entity engine.Entity
}
func NewUnitControlSystem(base BaseSystem, tileFinder tileFinder) *UnitControlSystem {
u := &UnitControlSystem{
BaseSystem: base,
tileFinder: tileFinder,
buildingsQueued: map[engine.EntityID]queuedBuilding{},
}
u.EventBus.Subscribe(PointClicked{}, u)
u.EventBus.Subscribe(EntitySelected{}, u)
u.EventBus.Subscribe(EntityUnselected{}, u)
u.EventBus.Subscribe(EntityOccupiedArea{}, u)
return u
}
func (u *UnitControlSystem) Start() {
u.buildMode = false
u.buildIcon = sprites.Hammer
u.buildIcon.Scale(engine.Vector{X: 0.5, Y: 0.5})
u.highlightedTile = tiles.NewHighlightTile(u.Config.TileMap.TileWidth, u.Config.TileMap.TileHeight)
u.Spawner.Spawn(u.highlightedTile)
}
func (u UnitControlSystem) Update(dt float64) {
u.moveEntities(dt)
u.updateHighlightedTile()
}
func (u *UnitControlSystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntitySelected:
foundEntity, ok := u.entities.ByID(event.Entity.ID())
if !ok {
return
}
u.tileSelectionMode = true
u.activeEntities.Add(foundEntity)
if len(u.activeEntities.All()) > 1 {
u.hideActionButton()
} else {
u.showActionButton()
}
case EntityUnselected:
u.activeEntities.Remove(event.Entity)
u.tileSelectionMode = false
u.buildMode = false
u.hideActionButton()
u.hideActionsPanel()
case PointClicked:
for _, e := range u.activeEntities.All() {
entity := e.(unitControlEntity)
_, ok := u.buildingsQueued[entity.ID()]
if ok {
// Entity moved after commanded to build - cancel the building
delete(u.buildingsQueued, entity.ID())
}
if u.buildMode {
tile, ok := u.tileFinder.TileAtPosition(event.Point)
if !ok {
fmt.Println("Tile not found at position", event.Point)
return
}
u.buildMode = false
if !canBuildOnTile(tile) {
return
}
u.buildingsQueued[entity.ID()] = queuedBuilding{
DestinationTile: tile,
Option: u.buildingToBuild,
}
if entity.GetAreaOccupant().OccupiedArea.Equals(tile) {
u.attemptBuildOnOccupy(entity, tile)
return
}
}
entity.GetMovable().SetTarget(event.Point)
}
case EntityOccupiedArea:
entity, ok := u.entities.ByID(event.Entity.ID())
if !ok {
return
}
u.attemptBuildOnOccupy(entity, event.Area)
}
}
func (u *UnitControlSystem) moveEntities(dt float64) {
for _, e := range u.entities.All() {
entity := e.(unitControlEntity)
movable := entity.GetMovable()
if movable.Disabled {
continue
}
if movable.Target != nil {
if entity.GetWorldSpace().WorldPosition().Distance(*movable.Target) < 1.0 {
u.EventBus.Publish(EntityReachedTarget{Entity: entity})
movable.ClearTarget()
} else {
direction := movable.Target.Sub(entity.GetWorldSpace().WorldPosition()).Normalized()
entity.GetWorldSpace().Translate(direction.Mul(50 * dt).Unpack())
u.EventBus.Publish(EntityMoved{Entity: entity})
}
}
}
}
func (u *UnitControlSystem) updateHighlightedTile() {
u.highlightedTile.GetDrawable().Disable()
if u.tileSelectionMode {
x, y := ebiten.CursorPosition()
v := engine.Vector{X: float64(x), Y: float64(y)}
tile, ok := u.tileFinder.TileAtPosition(v)
if ok {
u.highlightedTile.GetDrawable().Enable()
u.highlightedTile.GetWorldSpace().SetInWorld(
tile.GetWorldSpace().WorldPosition().X,
tile.GetWorldSpace().WorldPosition().Y,
)
}
}
}
func (u *UnitControlSystem) showActionButton() {
entity := u.activeEntities.All()[0].(unitControlEntity)
_, ok := entity.(components.BuilderOwner)
if ok {
u.showBuildButton(entity)
}
}
func (u *UnitControlSystem) showBuildButton(e engine.Entity) {
entity := e.(unitControlEntity)
button := archetypes.NewPanelButton(components.UIColorBrown, u.buildIcon, func() {
u.hideActionButton()
u.showActionPanel()
})
entity.GetWorldSpace().AddChild(button)
u.Spawner.Spawn(button)
u.actionButton = &button
}
func (u *UnitControlSystem) hideActionButton() {
if u.actionButton == nil {
return
}
u.Spawner.Destroy(*u.actionButton)
u.actionButton = nil
}
func (u *UnitControlSystem) showActionPanel() {
entity := u.activeEntities.All()[0].(unitControlEntity)
_, ok := entity.(components.BuilderOwner)
if ok {
u.showBuildPanel(entity)
}
}
func (u *UnitControlSystem) showBuildPanel(e engine.Entity) {
entity := e.(unitControlEntity)
options := entity.(components.BuilderOwner).GetBuilder().Options
var configs []archetypes.ButtonConfig
for i := range options {
o := options[i]
sprite := archetypes.SpriteForBuilding(o.BuildingType)
sprite.Scale(engine.Vector{X: 0.5, Y: 0.5})
configs = append(configs, archetypes.ButtonConfig{
Sprite: sprite,
Action: func() {
u.buildMode = true
u.buildingToBuild = o
u.hideActionsPanel()
},
})
}
panel := archetypes.NewFourButtonPanel(configs)
u.Spawner.Spawn(panel)
entity.GetWorldSpace().AddChild(panel)
u.actionsPanel = &panel
}
func (u *UnitControlSystem) hideActionsPanel() {
if u.actionsPanel == nil {
return
}
u.Spawner.Destroy(*u.actionsPanel)
u.actionsPanel = nil
}
func (u *UnitControlSystem) attemptBuildOnOccupy(entity engine.Entity, other engine.Entity) {
queued, ok := u.buildingsQueued[entity.ID()]
if !ok {
return
}
if !queued.DestinationTile.Equals(other) {
return
}
uce := entity.(unitControlEntity)
uce.GetMovable().ClearTarget()
buildingPos := engine.Vector{
X: float64(u.Config.TileMap.TileWidth) / 2.0,
Y: float64(u.Config.TileMap.TileHeight),
}
building := archetypes.NewBuilding(buildingPos, queued.Option.BuildingType)
queued.DestinationTile.GetWorldSpace().AddChild(building)
u.Spawner.Spawn(building)
delete(u.buildingsQueued, entity.ID())
}
func canBuildOnTile(tile tiles.Tile) bool {
// TODO Find a better way?
for _, c := range tile.GetWorldSpace().Children {
_, ok := c.(components.SelectableOwner)
if ok {
return false
}
}
return true
}
func (u *UnitControlSystem) Add(entity unitControlEntity) {
u.entities.Add(entity)
}
func (u *UnitControlSystem) Remove(entity engine.Entity) {
u.entities.Remove(entity)
}
<file_sep>package systems
import (
"math"
"github.com/m110/moonshot-rts/internal/archetypes"
"golang.org/x/image/colornames"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type clickingEntity interface {
engine.Entity
components.WorldSpaceOwner
components.DrawableOwner
components.ClickableOwner
}
type EntityClicked struct {
Entity engine.Entity
}
type EntitiesClicked struct {
Entities []engine.Entity
}
type PointClicked struct {
Point engine.Vector
}
type ClickReleased struct {
}
type ClickingSystem struct {
BaseSystem
entities []EntityList
overlay archetypes.Overlay
overlayAnchor engine.Vector
overlayEnabled bool
}
func NewClickingSystem(base BaseSystem) *ClickingSystem {
return &ClickingSystem{
BaseSystem: base,
entities: make([]EntityList, components.AllLayers),
}
}
func (c *ClickingSystem) Start() {
c.overlay = archetypes.NewOverlay(1, 1, engine.PivotTopLeft, colornames.White)
c.overlay.GetDrawable().Disable()
c.Spawner.Spawn(c.overlay)
}
func (c *ClickingSystem) Update(dt float64) {
cx, cy := ebiten.CursorPosition()
position := engine.Vector{X: float64(cx), Y: float64(cy)}
if inpututil.IsMouseButtonJustReleased(ebiten.MouseButtonLeft) {
c.EventBus.Publish(ClickReleased{})
if c.overlayEnabled {
c.hideOverlay()
entities := c.findAllEntitiesInOverlay()
if len(entities) > 0 {
c.EventBus.Publish(EntitiesClicked{
Entities: entities,
})
} else {
// TODO should have a dedicated event?
c.EventBus.Publish(PointClicked{
Point: position,
})
}
}
}
if inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) {
entity := c.findFirstClickedEntity(position)
if entity == nil {
c.EventBus.Publish(PointClicked{
Point: position,
})
c.showOverlay(position)
} else {
c.EventBus.Publish(EntityClicked{
Entity: entity,
})
}
}
if c.overlayEnabled {
c.updateOverlay(position)
}
}
func (c ClickingSystem) findFirstClickedEntity(position engine.Vector) engine.Entity {
for i := len(c.entities) - 1; i >= 0; i-- {
l := c.entities[i]
for _, e := range l.All() {
entity := e.(clickingEntity)
bounds := entity.GetClickable().Bounds
bounds.Position = bounds.Position.Add(entity.GetWorldSpace().WorldPosition())
if bounds.WithinBounds(position) {
return e
}
}
}
return nil
}
func (c ClickingSystem) findAllEntitiesInOverlay() []engine.Entity {
var entities []engine.Entity
r := engine.Rect{
Position: c.overlay.WorldSpace.WorldPosition(),
Width: float64(c.overlay.GetSize().Width),
Height: float64(c.overlay.GetSize().Height),
}
for _, l := range c.entities {
for _, e := range l.All() {
entity := e.(clickingEntity)
clickable := entity.GetClickable()
if clickable.Disabled || !clickable.ByOverlay {
continue
}
bounds := entity.GetClickable().Bounds
bounds.Position = bounds.Position.Add(entity.GetWorldSpace().WorldPosition())
if bounds.Intersects(r) {
entities = append(entities, entity)
}
}
}
return entities
}
func (c *ClickingSystem) showOverlay(cursor engine.Vector) {
c.overlayAnchor = cursor
c.overlay.GetWorldSpace().SetInWorld(cursor.X, cursor.Y)
c.overlay.GetDrawable().Enable()
c.overlayEnabled = true
}
func (c *ClickingSystem) updateOverlay(cursor engine.Vector) {
var pos engine.Vector
switch {
case cursor.X < c.overlayAnchor.X && cursor.Y < c.overlayAnchor.Y:
pos = engine.Vector{X: cursor.X, Y: cursor.Y}
case cursor.X < c.overlayAnchor.X && cursor.Y > c.overlayAnchor.Y:
pos = engine.Vector{X: cursor.X, Y: c.overlayAnchor.Y}
case cursor.X > c.overlayAnchor.X && cursor.Y < c.overlayAnchor.Y:
pos = engine.Vector{X: c.overlayAnchor.X, Y: cursor.Y}
default:
pos = engine.Vector{X: c.overlayAnchor.X, Y: c.overlayAnchor.Y}
}
c.overlay.WorldSpace.SetInWorld(pos.X, pos.Y)
c.overlay.Size.Set(
int(math.Abs(cursor.X-c.overlayAnchor.X)),
int(math.Abs(cursor.Y-c.overlayAnchor.Y)),
)
if c.overlay.Size.Width == 0 {
c.overlay.Size.Width = 1
}
if c.overlay.Size.Height == 0 {
c.overlay.Size.Height = 1
}
c.overlay.Drawable.Sprite = archetypes.NewRectangleSprite(c.overlay, engine.PivotTopLeft, colornames.White)
}
func (c *ClickingSystem) hideOverlay() {
c.overlayEnabled = false
c.overlay.Drawable.Disable()
}
func (c *ClickingSystem) Add(entity clickingEntity) {
c.entities[entity.GetDrawable().Layer].Add(entity)
}
func (c *ClickingSystem) Remove(entity engine.Entity) {
for i := range c.entities {
c.entities[i].Remove(entity)
}
}
<file_sep>package engine
type Rect struct {
Position Vector
Width float64
Height float64
}
func (r Rect) WithinBounds(v Vector) bool {
return v.X > r.Position.X && v.Y > r.Position.Y && v.X < r.Position.X+r.Width && v.Y < r.Position.Y+r.Height
}
func (r Rect) Intersects(other Rect) bool {
return !(r.Position.X > other.Position.X+other.Width ||
r.Position.X+r.Width < other.Position.X ||
r.Position.Y > other.Position.Y+other.Height ||
r.Position.Y+r.Height < other.Position.Y)
}
<file_sep>package engine
import (
"fmt"
"sync/atomic"
)
type EntityID int64
var (
nextEntityID int64
)
type Entity interface {
ID() EntityID
Equals(Entity) bool
}
type BaseEntity struct {
id EntityID
parent Entity
children []Entity
}
func NewBaseEntity() *BaseEntity {
return &BaseEntity{
id: EntityID(atomic.AddInt64(&nextEntityID, 1)),
}
}
func (e BaseEntity) ID() EntityID {
return e.id
}
func (e BaseEntity) Equals(other Entity) bool {
return e.ID() == other.ID()
}
func (e *BaseEntity) String() string {
return fmt.Sprintf("Entity [%v]", e.id)
}
<file_sep>package components
import "github.com/m110/moonshot-rts/internal/engine"
type Area struct {
Occupants int
Overlay DrawableOwner
}
// TODO This should be a "has" relation, not "is"
type AreaOccupant struct {
OccupiedArea engine.Entity
NextArea engine.Entity
Occupying bool
}
<file_sep>package components
import (
"time"
"github.com/m110/moonshot-rts/internal/engine"
)
type Selectable struct {
Selected bool
Overlay DrawableOwner
}
func (s *Selectable) Select() {
s.Selected = true
s.Overlay.GetDrawable().Disabled = false
}
func (s *Selectable) Unselect() {
s.Selected = false
s.Overlay.GetDrawable().Disabled = true
}
type Movable struct {
Target *engine.Vector
Disabled bool
}
func (m *Movable) Enable() {
m.Disabled = false
}
func (m *Movable) Disable() {
m.Disabled = true
}
func (m *Movable) ClearTarget() {
m.Target = nil
}
func (m *Movable) SetTarget(target engine.Vector) {
m.Target = &target
}
type MovementArea struct {
// TODO ?
Speed float64
}
type Size struct {
Width int
Height int
}
func (s *Size) Set(w int, h int) {
s.Width = w
s.Height = h
}
type UnitSpawnerOption struct {
Class Class
SpawnTime time.Duration
}
type UnitSpawner struct {
Options []UnitSpawnerOption
Queue []UnitSpawnerOption
Timer *engine.CountdownTimer
}
func (u *UnitSpawner) AddToQueue(option UnitSpawnerOption) {
u.Queue = append(u.Queue, option)
}
func (u *UnitSpawner) PopFromQueue() (UnitSpawnerOption, bool) {
if len(u.Queue) > 0 {
opt := u.Queue[0]
u.Queue = u.Queue[1:]
return opt, true
}
return UnitSpawnerOption{}, false
}
type BuildingType int
const (
BuildingSettlement BuildingType = iota
BuildingBarracks
BuildingChapel
BuildingForge
BuildingTower
)
type SettlementType int
const (
SettlementColony SettlementType = iota
SettlementVillage
SettlementCastle
)
type BuilderOption struct {
BuildingType BuildingType
SpawnTime time.Duration
}
type Builder struct {
Options []BuilderOption
Queue []BuilderOption
Timer *engine.CountdownTimer
}
func (b *Builder) AddToQueue(option BuilderOption) {
b.Queue = append(b.Queue, option)
}
func (b *Builder) PopFromQueue() (BuilderOption, bool) {
if len(b.Queue) > 0 {
opt := b.Queue[0]
b.Queue = b.Queue[1:]
return opt, true
}
return BuilderOption{}, false
}
type TimeActions struct {
Timers []*engine.CountdownTimer
}
func (t *TimeActions) AddTimer(timer *engine.CountdownTimer) {
t.Timers = append(t.Timers, timer)
}
type Team int
const (
TeamBlue Team = iota
TeamRed
TeamGreen
TeamGray
)
type Class int
const (
ClassWorker Class = iota
ClassWarrior
ClassKnight
ClassPriest
ClassKing
)
type Citizen struct {
Team Team
Class Class
}
type ProgressBarSprites struct {
Left engine.Sprite
Mid engine.Sprite
Right engine.Sprite
Full engine.Sprite
}
type ProgressBar struct {
Background ProgressBarSprites
Foreground ProgressBarSprites
Progress float64
}
func (p *ProgressBar) SetProgress(progress float64) {
if progress < 0 {
progress = 0
} else if progress > 1.0 {
progress = 1.0
}
p.Progress = progress
}
<file_sep>package components
type Resources struct {
Food int
Wood int
Stone int
Gold int
Iron int
}
func (r *Resources) Update(update Resources) {
r.Food = nonZero(r.Food + update.Food)
r.Wood = nonZero(r.Wood + update.Wood)
r.Stone = nonZero(r.Stone + update.Stone)
r.Gold = nonZero(r.Gold + update.Gold)
r.Iron = nonZero(r.Iron + update.Iron)
}
func nonZero(v int) int {
if v < 0 {
return 0
}
return v
}
type ResourcesSource struct {
Resources Resources
}
type ResourcesCollector struct {
CurrentResources Resources
Collecting bool
}
<file_sep>package archetypes
import "github.com/m110/moonshot-rts/internal/components"
func (b Building) GetSelectable() *components.Selectable {
return b.Selectable
}
func (b Building) GetClickable() *components.Clickable {
return b.Clickable
}
func (b Building) GetCollider() *components.Collider {
return b.Collider
}
func (b Building) GetUnitSpawner() *components.UnitSpawner {
return b.UnitSpawner
}
func (b Building) GetTimeActions() *components.TimeActions {
return b.TimeActions
}
func (o Object) GetWorldSpace() *components.WorldSpace {
return o.WorldSpace
}
func (o Object) GetDrawable() *components.Drawable {
return o.Drawable
}
func (o Overlay) GetWorldSpace() *components.WorldSpace {
return o.WorldSpace
}
func (o Overlay) GetDrawable() *components.Drawable {
return o.Drawable
}
func (o Overlay) GetSize() *components.Size {
return o.Size
}
func (p Panel) GetClickable() *components.Clickable {
return p.Clickable
}
func (p PanelButton) GetClickable() *components.Clickable {
return p.Clickable
}
func (p PanelButton) GetButton() *components.Button {
return p.Button
}
func (p ProgressBar) GetProgressBar() *components.ProgressBar {
return p.ProgressBar
}
func (u Unit) GetWorldSpace() *components.WorldSpace {
return u.WorldSpace
}
func (u Unit) GetCitizen() *components.Citizen {
return u.Citizen
}
func (u Unit) GetDrawable() *components.Drawable {
return u.Drawable
}
func (u Unit) GetMovable() *components.Movable {
return u.Movable
}
func (u Unit) GetSelectable() *components.Selectable {
return u.Selectable
}
func (u Unit) GetClickable() *components.Clickable {
return u.Clickable
}
func (u Unit) GetCollider() *components.Collider {
return u.Collider
}
func (u Unit) GetAreaOccupant() *components.AreaOccupant {
return u.AreaOccupant
}
func (w Worker) GetBuilder() *components.Builder {
return w.Builder
}
func (w Worker) GetResourcesCollector() *components.ResourcesCollector {
return w.ResourcesCollector
}
<file_sep>package systems
import (
"math/rand"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/archetypes/tiles"
"github.com/m110/moonshot-rts/internal/assets/sprites"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
"golang.org/x/image/colornames"
)
type TilemapConfig struct {
OffsetX int
OffsetY int
Width int
Height int
TileWidth int
TileHeight int
}
func (t TilemapConfig) TotalWidth() int {
return t.Width * t.TileWidth
}
func (t TilemapConfig) TotalHeight() int {
return t.Height * t.TileHeight
}
type TilemapSystem struct {
BaseSystem
world archetypes.Object
tiles []tiles.Tile
debugTiles []archetypes.Object
castlePosition engine.Point
}
func NewTilemapSystem(base BaseSystem) *TilemapSystem {
return &TilemapSystem{
BaseSystem: base,
}
}
func (t *TilemapSystem) Start() {
worldSprite := engine.NewFilledSprite(
t.Config.TileMap.TotalWidth(),
t.Config.TileMap.TotalHeight(),
colornames.White,
)
t.world = archetypes.NewObject(worldSprite, components.LayerBackground)
t.world.GetWorldSpace().Translate(
float64(t.Config.TileMap.OffsetX),
float64(t.Config.TileMap.OffsetY),
)
t.Spawner.Spawn(t.world)
t.spawnTiles()
t.spawnDebugTiles()
t.spawnUnits()
}
func (t *TilemapSystem) spawnTiles() {
w := t.Config.TileMap.Width
h := t.Config.TileMap.Height
desertEndX := engine.RandomRange(w/4, w/2)
desertEndY := engine.RandomRange(h/4, h/2)
seaStartX := engine.RandomRange(w-w/3, w)
seaStartY := engine.RandomRange(h-h/3, h)
t.castlePosition = engine.Point{
X: engine.RandomRange(2, seaStartX-2),
Y: engine.RandomRange(2, seaStartY-2),
}
for y := 0; y < t.Config.TileMap.Height; y++ {
for x := 0; x < t.Config.TileMap.Width; x++ {
position := engine.Vector{
X: float64(x * t.Config.TileMap.TileWidth),
Y: float64(y * t.Config.TileMap.TileWidth),
}
var forestChance int
var mountainChance int
var ground tiles.GroundType
if x < desertEndX && y < desertEndY {
forestChance = 0
mountainChance = 4
ground = tiles.GroundSand
} else if x > seaStartX && y > seaStartY {
forestChance = 0
mountainChance = 0
ground = tiles.GroundSea
} else {
forestChance = 3
mountainChance = 2
ground = tiles.GroundGrass
}
var tile tiles.Tile
if x == t.castlePosition.X && y == t.castlePosition.Y {
tile = tiles.NewBuildingTile(ground, components.BuildingSettlement)
} else {
if rand.Intn(10) < forestChance {
forestType := tiles.ForestType(rand.Intn(3))
tile = tiles.NewForestTile(ground, forestType)
} else if rand.Intn(10) < mountainChance {
mountainsType := archetypes.MountainType(rand.Intn(3))
tile = tiles.NewMountainsTile(ground, mountainsType)
} else {
tile = tiles.NewGroundTile(ground)
}
}
t.tiles = append(t.tiles, tile)
t.world.GetWorldSpace().AddChild(tile)
tile.GetWorldSpace().Translate(position.X, position.Y)
t.Spawner.Spawn(tile)
}
}
}
func (t *TilemapSystem) spawnDebugTiles() {
for y := 0; y < t.Config.TileMap.Height; y++ {
for x := 0; x < t.Config.TileMap.Width; x++ {
pos := engine.Vector{
X: float64(x * t.Config.TileMap.TileWidth),
Y: float64(y * t.Config.TileMap.TileHeight),
}
tile := tiles.NewDebugTile(t.Config.TileMap.TileWidth, t.Config.TileMap.TileHeight)
t.world.GetWorldSpace().AddChild(tile)
tile.GetWorldSpace().Translate(pos.X, pos.Y)
t.debugTiles = append(t.debugTiles, tile)
t.Spawner.Spawn(tile)
}
}
}
func (t TilemapSystem) spawnUnits() {
unitsX := func(o int) float64 {
return float64((t.castlePosition.X+o)*t.Config.TileMap.TileWidth + t.Config.TileMap.TileWidth/2)
}
unitsY := func(o int) float64 {
return float64((t.castlePosition.Y+o)*t.Config.TileMap.TileHeight + t.Config.TileMap.TileHeight/2)
}
spriteGetter := atlasSpriteGetter{}
king := archetypes.NewUnit(components.TeamBlue, components.ClassKing, spriteGetter)
t.world.GetWorldSpace().AddChild(king)
king.GetWorldSpace().Translate(unitsX(0), unitsY(1))
t.Spawner.Spawn(king)
}
func (t TilemapSystem) Update(_ float64) {
if inpututil.IsKeyJustPressed(ebiten.KeyD) {
for _, t := range t.debugTiles {
t.GetDrawable().Disabled = !t.GetDrawable().Disabled
}
}
}
func (t TilemapSystem) TileAtPosition(position engine.Vector) (tiles.Tile, bool) {
for _, tile := range t.tiles {
bounds := tile.GetClickable().Bounds
bounds.Position = bounds.Position.Add(tile.GetWorldSpace().WorldPosition())
if bounds.WithinBounds(position) {
return tile, true
}
}
return tiles.Tile{}, false
}
func (t TilemapSystem) Remove(e engine.Entity) {}
type atlasSpriteGetter struct{}
func (a atlasSpriteGetter) SpriteForUnit(team components.Team, class components.Class) engine.Sprite {
return sprites.Units[team][class].Random()
}
<file_sep>package engine
type Point struct {
X int
Y int
}
func (p Point) Unpack() (x int, y int) {
return p.X, p.Y
}
func (p *Point) Set(x int, y int) {
p.X = x
p.Y = y
}
func (p *Point) Translate(dx int, dy int) {
p.X += dx
p.Y += dy
}
<file_sep>package fonts
import (
"io/ioutil"
"os"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
)
var (
OpenSansRegular font.Face
OpenSansRegularSmall font.Face
)
func LoadFonts() error {
fontFile, err := os.Open("assets/OpenSans-Regular.ttf")
if err != nil {
return err
}
fontBytes, err := ioutil.ReadAll(fontFile)
if err != nil {
return err
}
font, err := opentype.Parse(fontBytes)
if err != nil {
return err
}
face, err := opentype.NewFace(font, &opentype.FaceOptions{
Size: 34,
DPI: 70,
})
if err != nil {
return err
}
smallFace, err := opentype.NewFace(font, &opentype.FaceOptions{
Size: 14,
DPI: 70,
})
if err != nil {
return err
}
OpenSansRegular = face
OpenSansRegularSmall = smallFace
return nil
}
<file_sep>package archetypes
import (
"time"
"golang.org/x/image/colornames"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type Unit struct {
*engine.BaseEntity
*components.WorldSpace
*components.Citizen
*components.Drawable
*components.Movable
*components.Selectable
*components.Clickable
*components.Collider
*components.AreaOccupant
}
type Worker struct {
Unit
*components.Builder
*components.ResourcesCollector
}
type spriteGetter interface {
SpriteForUnit(components.Team, components.Class) engine.Sprite
}
func NewUnit(team components.Team, class components.Class, spriteGetter spriteGetter) Unit {
sprite := spriteGetter.SpriteForUnit(team, class)
w, h := sprite.Size()
overlay := NewOverlay(w+20, h+20, engine.PivotBottom, colornames.White)
colliderBounds := engine.Rect{
Position: engine.Vector{
X: 0,
Y: 0,
},
Width: 1,
Height: 1,
}
colliderOverlay := NewOverlay(int(colliderBounds.Width), int(colliderBounds.Height), engine.PivotTopLeft, colornames.Red)
u := Unit{
engine.NewBaseEntity(),
&components.WorldSpace{},
&components.Citizen{
Team: team,
Class: class,
},
&components.Drawable{
Sprite: sprite,
Layer: components.LayerUnits,
},
&components.Movable{},
&components.Selectable{
Overlay: overlay,
},
&components.Clickable{
Bounds: components.BoundsFromSprite(sprite),
ByOverlay: true,
},
&components.Collider{
Bounds: colliderBounds,
Layer: components.CollisionLayerUnits,
Overlay: colliderOverlay,
},
&components.AreaOccupant{},
}
u.GetWorldSpace().AddChild(overlay)
overlay.GetWorldSpace().Translate(0, 10)
u.GetWorldSpace().AddChild(colliderOverlay)
colliderOverlay.GetWorldSpace().Translate(colliderBounds.Position.X, colliderBounds.Position.Y)
return u
}
func NewWorker(team components.Team, spriteGetter spriteGetter) Worker {
unit := NewUnit(team, components.ClassWorker, spriteGetter)
options := []components.BuilderOption{
{
BuildingType: components.BuildingBarracks,
SpawnTime: time.Second * 10,
},
{
BuildingType: components.BuildingForge,
SpawnTime: time.Second * 5,
},
{
BuildingType: components.BuildingChapel,
SpawnTime: time.Second * 15,
},
{
BuildingType: components.BuildingTower,
SpawnTime: time.Second * 20,
},
}
return Worker{
Unit: unit,
Builder: &components.Builder{
Options: options,
},
ResourcesCollector: &components.ResourcesCollector{},
}
}
<file_sep>package systems
import (
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
// TODO Come up with a better way to define this
var collisionsMatrix = map[components.CollisionLayer][]components.CollisionLayer{
components.CollisionLayerGround: {
components.CollisionLayerUnits,
},
components.CollisionLayerUnits: {
components.CollisionLayerGround,
components.CollisionLayerBuildings,
},
components.CollisionLayerBuildings: {
components.CollisionLayerUnits,
},
}
type collisionEntity interface {
engine.Entity
components.WorldSpaceOwner
components.ColliderOwner
}
type EntitiesCollided struct {
Entity engine.Entity
Other engine.Entity
}
type EntitiesOutOfCollision struct {
Entity engine.Entity
Other engine.Entity
}
type CollisionSystem struct {
BaseSystem
entities EntityMap
recentlyMovedEntities EntityList
}
func NewCollisionSystem(base BaseSystem) *CollisionSystem {
c := &CollisionSystem{
BaseSystem: base,
}
c.EventBus.Subscribe(EntityMoved{}, c)
return c
}
func (c CollisionSystem) Start() {
}
func (c *CollisionSystem) Update(dt float64) {
for _, e := range c.recentlyMovedEntities.All() {
for _, o := range c.entities.All() {
entity := e.(collisionEntity)
other := o.(collisionEntity)
if entity.Equals(other) {
continue
}
// TODO This should be moved to a common func
entityBounds := entity.GetCollider().Bounds
entityBounds.Position = entityBounds.Position.Add(entity.GetWorldSpace().WorldPosition())
otherBounds := other.GetCollider().Bounds
otherBounds.Position = otherBounds.Position.Add(other.GetWorldSpace().WorldPosition())
intersects := entityBounds.Intersects(otherBounds)
// Already collide with each other
if entity.GetCollider().HasCollision(other) {
// No longer collide
if !intersects {
entity.GetCollider().RemoveCollision(other)
other.GetCollider().RemoveCollision(entity)
c.EventBus.Publish(EntitiesOutOfCollision{
Entity: entity,
Other: other,
})
c.EventBus.Publish(EntitiesOutOfCollision{
Entity: other,
Other: entity,
})
}
continue
}
if !intersects {
continue
}
collisions := collisionsMatrix[entity.GetCollider().Layer]
collides := false
for _, l := range collisions {
if l == other.GetCollider().Layer {
collides = true
break
}
}
if !collides {
continue
}
entity.GetCollider().AddCollision(other)
other.GetCollider().AddCollision(entity)
c.EventBus.Publish(EntitiesCollided{
Entity: entity,
Other: other,
})
c.EventBus.Publish(EntitiesCollided{
Entity: other,
Other: entity,
})
}
}
if inpututil.IsKeyJustPressed(ebiten.KeyC) {
for _, e := range c.entities.All() {
entity := e.(collisionEntity)
overlay := entity.GetCollider().Overlay
if overlay != nil {
overlay.GetDrawable().Disabled = !overlay.GetDrawable().Disabled
}
}
}
c.recentlyMovedEntities.Clear()
}
func (c *CollisionSystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntityMoved:
_, ok := c.entities.ByID(event.Entity.ID())
if !ok {
return
}
c.recentlyMovedEntities.Add(event.Entity)
}
}
func (c *CollisionSystem) Add(entity collisionEntity) {
c.entities.Add(entity)
c.recentlyMovedEntities.Add(entity)
}
func (c *CollisionSystem) Remove(entity engine.Entity) {
c.entities.Remove(entity)
}
<file_sep>package systems
import "github.com/m110/moonshot-rts/internal/engine"
type BaseSystem struct {
Config Config
EventBus *engine.EventBus
Spawner Spawner
}
func NewBaseSystem(config Config, eventBus *engine.EventBus, systemsProvider systemsProvider) BaseSystem {
return BaseSystem{
Config: config,
EventBus: eventBus,
Spawner: NewSpawner(systemsProvider),
}
}
<file_sep>package sprites
import (
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
var (
Grass1 engine.Sprite
Sand1 engine.Sprite
Water1 engine.Sprite
FieldSmallEmpty engine.Sprite
FieldSmallWheat engine.Sprite
FieldBigEmpty engine.Sprite
FieldBigWheat engine.Sprite
TreeBig engine.Sprite
TreeSmall engine.Sprite
PineBig engine.Sprite
PineSmall engine.Sprite
StoneSmall engine.Sprite
StoneBig engine.Sprite
StoneTwo engine.Sprite
StoneThree engine.Sprite
GoldThree engine.Sprite
IronThree engine.Sprite
Castle engine.Sprite
CastleTop engine.Sprite
Barracks engine.Sprite
BarracksTop engine.Sprite
Chapel engine.Sprite
ChapelTop engine.Sprite
Tower engine.Sprite
TowerTop engine.Sprite
Forge engine.Sprite
Units = map[components.Team]map[components.Class]engine.Sprites{}
PanelBrown engine.Sprite
ButtonBeige engine.Sprite
ButtonBeigePressed engine.Sprite
ButtonBrown engine.Sprite
ButtonBrownPressed engine.Sprite
Hammer engine.Sprite
BarBackHorizontalLeft engine.Sprite
BarBackHorizontalMid engine.Sprite
BarBackHorizontalRight engine.Sprite
BarGreenHorizontalLeft engine.Sprite
BarGreenHorizontalMid engine.Sprite
BarGreenHorizontalRight engine.Sprite
)
type TeamSprites struct {
Blue engine.Sprite
Red engine.Sprite
Green engine.Sprite
Gray engine.Sprite
}
func LoadSprites(rtsPath string, uiPath string) error {
rtsAtlas, err := NewAtlas(rtsPath)
if err != nil {
return err
}
uiAtlas, err := NewAtlas(uiPath)
if err != nil {
return err
}
Grass1 = engine.NewSpriteFromImage(rtsAtlas.ImageByName("grass_1"))
Sand1 = engine.NewSpriteFromImage(rtsAtlas.ImageByName("sand_1"))
Water1 = engine.NewSpriteFromImage(rtsAtlas.ImageByName("water_1"))
FieldSmallEmpty = engine.NewSpriteFromImage(rtsAtlas.ImageByName("grass_field_small_empty"))
FieldSmallWheat = engine.NewSpriteFromImage(rtsAtlas.ImageByName("grass_field_small_wheat"))
FieldBigEmpty = engine.NewSpriteFromImage(rtsAtlas.ImageByName("grass_field_big_empty"))
FieldBigWheat = engine.NewSpriteFromImage(rtsAtlas.ImageByName("grass_field_big_wheat"))
loadSpritePivotBottom := func(name string) engine.Sprite {
return engine.NewSpriteFromImageWithPivotType(rtsAtlas.ImageByName(name), engine.PivotBottom)
}
TreeBig = loadSpritePivotBottom("tree_big")
TreeSmall = loadSpritePivotBottom("tree_small")
PineBig = loadSpritePivotBottom("pine_big")
PineSmall = loadSpritePivotBottom("pine_small")
StoneSmall = loadSpritePivotBottom("stone_small")
StoneBig = loadSpritePivotBottom("stone_big")
StoneTwo = loadSpritePivotBottom("stone_two")
StoneThree = loadSpritePivotBottom("stone_three")
GoldThree = loadSpritePivotBottom("gold_three")
IronThree = loadSpritePivotBottom("iron_three")
Castle = loadSpritePivotBottom("castle")
CastleTop = loadSpritePivotBottom("castle_top")
Barracks = loadSpritePivotBottom("barracks")
BarracksTop = loadSpritePivotBottom("barracks_top")
Chapel = loadSpritePivotBottom("chapel")
ChapelTop = loadSpritePivotBottom("chapel_top")
Tower = loadSpritePivotBottom("tower")
TowerTop = loadSpritePivotBottom("tower_top")
Forge = loadSpritePivotBottom("forge")
Units = map[components.Team]map[components.Class]engine.Sprites{
components.TeamBlue: {
components.ClassWorker: {
loadSpritePivotBottom("unit_blue_worker_man"),
loadSpritePivotBottom("unit_blue_worker_woman"),
},
components.ClassWarrior: {loadSpritePivotBottom("unit_blue_warrior")},
components.ClassKnight: {loadSpritePivotBottom("unit_blue_knight")},
components.ClassPriest: {loadSpritePivotBottom("unit_blue_priest")},
components.ClassKing: {loadSpritePivotBottom("unit_blue_king")},
},
components.TeamRed: {
components.ClassWorker: {
loadSpritePivotBottom("unit_red_worker_man"),
loadSpritePivotBottom("unit_red_worker_woman"),
},
components.ClassWarrior: {loadSpritePivotBottom("unit_red_warrior")},
components.ClassKnight: {loadSpritePivotBottom("unit_red_knight")},
components.ClassPriest: {loadSpritePivotBottom("unit_red_priest")},
components.ClassKing: {loadSpritePivotBottom("unit_red_king")},
},
components.TeamGreen: {
components.ClassWorker: {
loadSpritePivotBottom("unit_green_worker_man"),
loadSpritePivotBottom("unit_green_worker_woman"),
},
components.ClassWarrior: {loadSpritePivotBottom("unit_green_warrior")},
components.ClassKnight: {loadSpritePivotBottom("unit_green_knight")},
components.ClassPriest: {loadSpritePivotBottom("unit_green_priest")},
components.ClassKing: {loadSpritePivotBottom("unit_green_king")},
},
components.TeamGray: {
components.ClassWorker: {
loadSpritePivotBottom("unit_gray_worker_man"),
loadSpritePivotBottom("unit_gray_worker_woman"),
},
components.ClassWarrior: {loadSpritePivotBottom("unit_gray_warrior")},
components.ClassKnight: {loadSpritePivotBottom("unit_gray_knight")},
components.ClassPriest: {loadSpritePivotBottom("unit_gray_priest")},
components.ClassKing: {loadSpritePivotBottom("unit_gray_king")},
},
}
PanelBrown = engine.NewSpriteFromImage(uiAtlas.ImageByName("panel_brown"))
ButtonBeige = engine.NewSpriteFromImage(uiAtlas.ImageByName("buttonSquare_beige"))
ButtonBeigePressed = engine.NewSpriteFromImage(uiAtlas.ImageByName("buttonSquare_beige_pressed"))
ButtonBrown = engine.NewSpriteFromImage(uiAtlas.ImageByName("buttonSquare_brown"))
ButtonBrownPressed = engine.NewSpriteFromImage(uiAtlas.ImageByName("buttonSquare_brown_pressed"))
hammerImg, _, err := ebitenutil.NewImageFromFile("assets/hammer.png")
if err != nil {
return err
}
Hammer = engine.NewSpriteFromImage(hammerImg)
BarBackHorizontalLeft = engine.NewSpriteFromImage(uiAtlas.ImageByName("barBack_horizontalLeft"))
BarBackHorizontalMid = engine.NewSpriteFromImage(uiAtlas.ImageByName("barBack_horizontalMid"))
BarBackHorizontalRight = engine.NewSpriteFromImage(uiAtlas.ImageByName("barBack_horizontalRight"))
BarGreenHorizontalLeft = engine.NewSpriteFromImage(uiAtlas.ImageByName("barGreen_horizontalLeft"))
BarGreenHorizontalMid = engine.NewSpriteFromImage(uiAtlas.ImageByName("barGreen_horizontalMid"))
BarGreenHorizontalRight = engine.NewSpriteFromImage(uiAtlas.ImageByName("barGreen_horizontalRight"))
return nil
}
<file_sep>package systems
import (
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type buttonsEntity interface {
engine.Entity
components.DrawableOwner
components.ButtonOwner
}
type ButtonsSystem struct {
BaseSystem
entities EntityMap
activeButton buttonsEntity
}
func NewButtonsSystem(base BaseSystem) *ButtonsSystem {
return &ButtonsSystem{
BaseSystem: base,
}
}
func (b *ButtonsSystem) Start() {
b.EventBus.Subscribe(EntityClicked{}, b)
b.EventBus.Subscribe(ClickReleased{}, b)
}
func (b *ButtonsSystem) HandleEvent(e engine.Event) {
switch event := e.(type) {
case EntityClicked:
_, ok := b.entities.ByID(event.Entity.ID())
if !ok {
return
}
entity := event.Entity.(buttonsEntity)
entity.GetButton().Pressed = true
b.updateSprite(entity)
entity.GetButton().Action()
b.activeButton = entity
case ClickReleased:
if b.activeButton == nil {
return
}
b.activeButton.GetButton().Pressed = false
b.updateSprite(b.activeButton)
b.activeButton = nil
}
}
func (b ButtonsSystem) Update(dt float64) {}
func (b *ButtonsSystem) Add(entity buttonsEntity) {
b.updateSprite(entity)
b.entities.Add(entity)
}
func (b ButtonsSystem) Remove(entity engine.Entity) {
b.entities.Remove(entity)
}
func (b *ButtonsSystem) updateSprite(entity buttonsEntity) {
button := entity.GetButton()
var baseSprite engine.Sprite
if button.Pressed {
baseSprite = button.SpritePressed
} else {
baseSprite = button.SpriteReleased
}
sprite := engine.NewBlankSprite(baseSprite.Size())
sprite.Draw(baseSprite)
sprite.DrawAtPosition(button.SpriteTop, baseSprite.Width()/2, baseSprite.Height()/2)
entity.GetDrawable().Sprite = sprite
}
<file_sep>package tiles
import (
"github.com/m110/moonshot-rts/internal/archetypes"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
"golang.org/x/image/colornames"
)
func NewHighlightTile(width int, height int) archetypes.Object {
c := colornames.Cyan
c.A = 75
highlightedSprite := engine.NewFilledSprite(width, height, c)
return archetypes.Object{
BaseEntity: engine.NewBaseEntity(),
WorldSpace: &components.WorldSpace{},
Drawable: &components.Drawable{
Sprite: highlightedSprite,
Layer: components.LayerForeground,
Disabled: true,
},
}
}
<file_sep>package systems
import (
"sort"
"github.com/hajimehoshi/ebiten/v2"
"github.com/m110/moonshot-rts/internal/components"
"github.com/m110/moonshot-rts/internal/engine"
)
type DrawingEntity interface {
engine.Entity
components.WorldSpaceOwner
components.DrawableOwner
}
type DrawingSystem struct {
BaseSystem
entities []EntityList
canvas engine.Sprite
layers [][]spriteAtPosition
}
type spriteAtPosition struct {
Sprite engine.Sprite
Position engine.Vector
}
func NewDrawingSystem(base BaseSystem) *DrawingSystem {
canvas := engine.NewSpriteFromImage(ebiten.NewImage(base.Config.WindowSize()))
layers := make([][]spriteAtPosition, components.AllLayers)
return &DrawingSystem{
BaseSystem: base,
entities: make([]EntityList, components.AllLayers),
canvas: canvas,
layers: layers,
}
}
func (d *DrawingSystem) Add(e DrawingEntity) {
d.entities[e.GetDrawable().Layer].Add(e)
}
func (d *DrawingSystem) Remove(e engine.Entity) {
for i := range d.entities {
d.entities[i].Remove(e)
}
}
func (d *DrawingSystem) Start() {
}
func (d *DrawingSystem) Update(_ float64) {}
func (d DrawingSystem) Draw(screen engine.Sprite) {
for i := range d.layers {
// TODO this is probably not really performant
d.layers[i] = nil
}
for _, l := range d.entities {
for _, e := range l.All() {
de := e.(DrawingEntity)
d.drawEntity(de)
}
}
for _, l := range d.layers {
// Sort the sprites in a layer, so the objects below cover the objects "behind" them
sort.Slice(l, func(i, j int) bool {
return l[i].Position.Y < l[j].Position.Y
})
for _, s := range l {
d.canvas.DrawAtVector(s.Sprite, s.Position)
}
}
screen.Draw(d.canvas)
}
func (d DrawingSystem) drawEntity(e DrawingEntity) {
if e.GetDrawable().Disabled {
return
}
drawable := e.GetDrawable()
d.layers[drawable.Layer] = append(d.layers[drawable.Layer], spriteAtPosition{
Sprite: drawable.Sprite,
Position: e.GetWorldSpace().WorldPosition(),
})
}
| 90411091dfadaf5ee94ea73aa9ed9811e03b077c | [
"Markdown",
"Go Module",
"Go"
] | 60 | Go | m110/moonshot-rts | 65675aec588507ef93ca7311cabf8e6c6b4030f7 | e3bdfe9a2b4a4637a549d929f1c28469d39171ba |
refs/heads/master | <repo_name>KaranSaini/EnglishToPigLatin<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
animations: [ //will attempt angular animations here
]
})
export class AppComponent {
bindedWord;
pigLatinify(word) {
if(word.length < 3) {
return word;
}
return word.slice(1) + '-' + word[0].toLowerCase() + 'ay';
}
onKey(typed) {
of(typed).pipe(
map(event => event.target.value),
map(wordString => wordString.split(/\s+/)),
map(wordArray => wordArray.map(this.pigLatinify))
).subscribe(
translated => this.bindedWord = translated
);
this.bindedWord = this.bindedWord.join(" ");
}
}
<file_sep>/README.md
# PiglatinTranslator
This project converts english to piglatin in "real time" using the RXJS library.
Hosted at: https://karansaini.github.io/EnglishToPigLatin/
To run locally, clone and then `npm install`
| ca2f5f5229aeee4b7158c85d3e44c2c52aa22ae1 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | KaranSaini/EnglishToPigLatin | c30b0553d0b5cec1ea5c60ac7dc2f280df00aa11 | 1dc817dd46fadd2922291508a41d45f529908b88 |
refs/heads/main | <repo_name>Liubov-Pastukhova/react-way-of-samurai<file_sep>/README.md
Задача: написать аналог социальной сети (клиентская часть).
Используемый стек:
- ReactJS
- Redux
- React-Redux
- для запросов на сервер - Axios
<file_sep>/src/data/profilePage-reducer.js
import { profileAPI } from "../api/api";
const ADD_POST = 'ADD-POST';
const UPDATE_NEW_POST_TEXT = 'UPDATE-NEW-POST-TEXT';
const SET_USER_PROFILE = 'SET_USER_PROFILE';
const SET_STATUS_PROFILE = 'SET_STATUS_PROFILE';
let initialState = {
postsData: [
{ id: 1, message: "It's my first post. How are you?", likesCount: 25 },
{ id: 2, message: "Second post", likesCount: 15 },
{ id: 3, message: "Third post", likesCount: 10 }
],
newPostText: 'new post',
profile: null,
status: ''
}
const profilePageReducer = (state = initialState, action) => {
switch(action.type) {
case ADD_POST: {
return {
...state,
newPostText: '',
postsData: [...state.postsData, { id: 4, message: state.newPostText, likesCount: 0}]
};
}
case UPDATE_NEW_POST_TEXT: {
return {
...state,
newPostText: action.newText
};
}
case SET_USER_PROFILE: {
return {
...state,
profile: action.profile
}
}
case SET_STATUS_PROFILE: {
return {
...state,
status: action.status
}
}
default:
return state;
}
}
export const addPost = () => {
return {type: ADD_POST}
}
export const updateNewPostText = (text) => {
return { type: UPDATE_NEW_POST_TEXT,
newText: text
}
}
export const setUserProfile = (profile) => {
return {type: SET_USER_PROFILE, profile}
}
export const setStatusProfile = (status) => {
return {type: SET_STATUS_PROFILE, status}
}
export const getUserProfile = (userId) => (dispatch) => {
return profileAPI.getProfile(userId)
.then(response => {
dispatch(setUserProfile(response.data));
});
}
export const getStatusProfile = (userId) => (dispatch) => {
return profileAPI.getStatus(userId)
.then(response => {
dispatch(setStatusProfile(response.data));
});
}
export const updateStatusProfile = (status) => (dispatch) => {
return profileAPI.updateStatus(status)
.then(response => {
if (response.data.resultCode === 0)
dispatch(setStatusProfile(status));
});
}
export default profilePageReducer;<file_sep>/src/data/navBar-reducer.js
let initialState = {
navbarItems: [
{path: "/profile", title: "Profile"},
{path: "/dialogs", title: "Messages"},
{path: "/newspage", title: "News"},
{path: "/music", title: "Music"},
{path: "/users", title: "Users"},
{path: "/settings", title: "Settings"},
{path: "/friends", title: "FRIENDS"}
]
}
const navBarReducer = (state = initialState, action) => {
return state;
}
export default navBarReducer;<file_sep>/src/components/Profile/MyPosts/Post/Post.jsx
import React from 'react';
import classes from './Post.module.css';
const Post = (props) => {
return (
<div className={classes.posts}>
<img src="https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg" />
<div className={classes.item}>{props.message}</div>
<button>Like</button>
{props.likesCount}
<button>Dislike</button>
</div>
);
}
export default Post;<file_sep>/src/components/Navbar/NavbarFriendsItem/NavbarFriendsItem.jsx
import React from 'react';
import classes from './NavbarFriendsItem.module.css';
const NavbarFriendsItem = (props) => {
return (
<div>
<div className={classes.navFriendsItem}>
<div><img src={props.img} /></div>
<div>{props.name}</div>
</div>
</div>
)
}
export default NavbarFriendsItem;<file_sep>/src/components/App/App.js
import React from 'react';
import { Route} from 'react-router-dom';
import './App.css';
import DialogsContainer from '../Dialogs/DialogsContainer';
import Newspage from '../Newspage/Newspage';
import Music from '../Music/Music';
import { Settings } from '../../components/Settings/Settings';
import NavbarContainer from '../Navbar/NavbarContainer';
import FriendsContainer from '../Friends/FriendsContainer';
import UsersContainer from '../Users/UsersContainer';
import ProfileContainer from '../Profile/ProfileContainer';
import HeaderContainer from '../Header/HeaderContainer';
import Login from '../Login/Login';
const App = () => {
return (
<div className='app-wrapper'>
<HeaderContainer />
<NavbarContainer />
<div className='app-wrapper-content'>
<Route path='/profile/:userId?' render={() => <ProfileContainer />} />
<Route path='/dialogs' render={() => <DialogsContainer />} />
<Route path='/newspage' render={() => <Newspage />} />
<Route path='/music' render={() => <Music />} />
<Route path='/users' render={() => <UsersContainer />} />
<Route path='/settings' render={() => <Settings />} />
<Route path='/friends' render={() => <FriendsContainer />} />
<Route path='/login' render={() => <Login />} />
</div>
</div>
);
}
export default App;
<file_sep>/src/data/store.js
import dialogsPageReducer from "./dialogsPage-reducer";
import navBarReducer from "./navBar-reducer";
import profilePageReducer from "./profilePage-reducer";
let store = {
_state: {
profilePage: {
postsData: [
{ id: 1, message: "It's my first post. How are you?", likesCount: 25 },
{ id: 2, message: "Second post", likesCount: 15 },
{ id: 3, message: "Third post", likesCount: 10 }
],
newPostText: 'new post'
},
dialogsPage: {
messagesData: [
{ id: 1, message: 'Hi' },
{ id: 2, message: 'How are you?' }
],
newMessageText: 'new message',
dialogsData: [
{ id: 1, name: 'Илья', img: 'https://whatsism.com/uploads/posts/2018-07/1530545833_il2zmvzx9py.jpg' },
{ id: 2, name: 'Света', img: 'https://klike.net/uploads/posts/2019-03/1551511784_4.jpg' },
{ id: 3, name: 'E M', img: 'https://cdn66.printdirect.ru/cache/product/9d/39/8392279/tov/all/480z480_front_35_0_0_0_d764b3424a2d7f37ad1341720f99.jpg?rnd=1550819450' }
]
},
navBar: {
navbarItems: [
{path: "/profile", title: "Profile"},
{path: "/dialogs", title: "Messages"},
{path: "/newspage", title: "News"},
{path: "/music", title: "Music"},
{path: "/settings", title: "Settings"},
{path: "/friends", title: "FRIENDS"}
]
}
},
_callSubscriber() {
console.log('State changed');
},
getState() {
return this._state;
},
subscribe (observer) {
this._callSubscriber = observer;
},
dispatch(action) { // { type: 'ADD-POST' }
this._state.profilePage = profilePageReducer(this._state.profilePage, action);
this._state.dialogsPage = dialogsPageReducer(this._state.dialogsPage, action);
this._state.navBar = navBarReducer(this._state.navBar, action);
this._callSubscriber(this._state);
}
}
export default store;
window.store = store;<file_sep>/src/components/Friends/Friend/Friend.jsx
import React from 'react';
import classes from './Friend.module.css';
import { NavLink } from 'react-router-dom';
const Friend = (props) => {
let path = '/friends/' + props.id;
return (
<div className={classes.friend}>
<NavLink to={path}>
<img src={props.img} />
<span>{props.name}</span>
</NavLink>
</div>
);
}
export default Friend;<file_sep>/src/components/Dialogs/Dialogs.jsx
import React from 'react';
import classes from './Dialogs.module.css';
import DialogItem from './DialogItem/DialogItem';
import Message from './Message/Message';
const Dialogs = (props) => {
let state = props.dialogsPage;
let dialogsElements = state.dialogsData.map(dialog => (<DialogItem id={dialog.id} name={dialog.name} key={dialog.id} img={dialog.img} />))
let messagesElements = state.messagesData.map(message => (<Message message={message.message} key={message.id} />))
let onSendMessage = () => {
props.sendMessage();
}
let onMessageChange = (e) => {
let text = e.target.value;
props.updateNewMessageText(text);
}
return (
<div className={classes.dialogs}>
<div className={classes.dialogItems}>{dialogsElements}</div>
<div className={classes.messages}>
<div>{messagesElements}</div>
<div className={classes.textarea}>
<textarea onChange={onMessageChange} value={state.newMessageText} />
</div>
<div>
<button onClick={onSendMessage}>Send message</button>
</div>
</div>
</div>
)
}
export default Dialogs;<file_sep>/src/components/Header/Header.jsx
import React from 'react';
import classes from './Header.module.css';
import mainLogo from '../../assets/images/logo.jpg'
import { NavLink } from 'react-router-dom';
const Header = (props) => {
return (
<header className={classes.header}>
<div>
<img src={mainLogo} />
</div>
<div className={classes.loginBlock}>
{ props.isAuth ? <span>{props.login}</span> : <NavLink to={'/login'}>Log in</NavLink>}
</div>
</header>
);
}
export default Header;<file_sep>/src/components/Navbar/NavbarItem/NavbarItem.jsx
import React from 'react';
import classes from './NavbarItem.module.css';
import { NavLink } from 'react-router-dom';
const NavbarItem = (props) => {
return (
<div className={classes.item}>
<NavLink to={props.path} activeClassName={classes.activeLink}>
{props.title}
</NavLink>
</div>
)
}
export default NavbarItem;<file_sep>/src/data/redux-store.js
import {applyMiddleware, combineReducers, createStore} from 'redux';
import dialogsPageReducer from './dialogsPage-reducer';
import navBarReducer from './navBar-reducer';
import profilePageReducer from './profilePage-reducer';
import usersReducer from './users-reducer';
import authReducer from './auth-reducer';
import thunkMiddleware from "redux-thunk";
import { reducer as formReducer } from 'redux-form'
let reducers = combineReducers({
profilePage: profilePageReducer,
dialogsPage: dialogsPageReducer,
navBar: navBarReducer,
usersPage: usersReducer,
auth: authReducer,
form: formReducer
});
let store = createStore(reducers, applyMiddleware(thunkMiddleware));
window.store = store;
export default store;<file_sep>/src/components/Navbar/Navbar.jsx
import React from 'react';
import classes from './Navbar.module.css';
import NavbarFriendsItem from './NavbarFriendsItem/NavbarFriendsItem';
import NavbarItem from './NavbarItem/NavbarItem';
const Navbar = (props) => {
let navbarElements = props.navbarItems.map(navItem =>
(<NavbarItem path={navItem.path}
title={navItem.title} key={navItem.id} />))
let navbarFriendsElements = props.dialogsData.map(navFriendsItem =>
(<NavbarFriendsItem img={navFriendsItem.img}
name={navFriendsItem.name} key={navFriendsItem.id} />))
return (
<div>
<nav className={classes.nav}>
<div>{navbarElements}</div>
<div className={classes.navFriendsItemBlock}>{navbarFriendsElements}</div>
</nav>
</div>
);
}
export default Navbar;<file_sep>/src/components/Profile/MyPosts/MyPosts.jsx
import React from 'react';
import classes from './MyPosts.module.css';
import Post from './Post/Post';
import { Field, reduxForm } from 'redux-form';
const AddPostsForm= (props) => {
return (
<form onSubmit={props.handleSubmit}>
<div>
<Field component={"textarea"} name={"newPostBody"} placeholder={"Enter your message"} onChange={props.onPostChange} value={props.newPostText} />
</div>
<div>
<button onClick={props.onAddPost}>Add post</button>
</div>
</form>
)
}
const MyPostsReduxForm = reduxForm({
form: 'myPosts'
})(AddPostsForm)
const MyPosts = (props) => {
const onSubmit = (formData) => {
console.log(formData)
}
let postsElement = props.postsData.map ( post => (<Post message={post.message} key={post.id} likesCount={post.likesCount} />))
let onAddPost = () => {
props.addPost();
}
let onPostChange = (event) => {
let text = event.target.value;
props.updateNewPostText(text);
}
return (
<div className={classes.postsDecoration}>
<div>My posts</div>
<MyPostsReduxForm onAddPost={onAddPost} onPostChange={onPostChange} newPostText={props.newPostText} onSubmit={onSubmit} />
{postsElement}
</div>
);
}
export default MyPosts; | be2a0d10ff9223778c2207b6dd2dd209da78e40a | [
"Markdown",
"JavaScript"
] | 14 | Markdown | Liubov-Pastukhova/react-way-of-samurai | e09beafb7e33c661c8e748401c03c0588444eaf3 | 6216ffe9e83a1379da86a2e7b3a6ab599b91b84e |
refs/heads/master | <repo_name>Ajay311/DotNetCoreConsoleShootingGame<file_sep>/ShootingGame.Test/SelectGunTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
namespace ShootingGame.Test
{
[TestClass]
public class SelectGunTest
{
[TestMethod]
public void SelectGun_Pistol()
{
string userInput = "1";
using (StringReader sr = new StringReader(userInput))
{
Console.SetIn(sr);
Gun currgun = Program.SelectGun();
Console.Write(currgun.Name);
Assert.AreEqual<string>(Constant.Pistol, currgun.Name);
}
}
[TestMethod]
public void SelectGun_Rifle()
{
string userInput = "2";
using (StringReader sr = new StringReader(userInput))
{
Console.SetIn(sr);
Gun currgun = Program.SelectGun();
Assert.AreEqual<string>(Constant.Rifle, currgun.Name);
}
}
[TestMethod]
public void SelectGun_Invalid_Number()
{
string userInput = "4";
using (StringReader sr = new StringReader(userInput))
{
Console.SetIn(sr);
Gun currgun = Program.SelectGun();
Assert.IsNull(currgun);
}
}
[TestMethod]
public void SelectGun_Invalid_Char()
{
string userInput = "abc";
using (StringReader sr = new StringReader(userInput))
{
Console.SetIn(sr);
Gun currgun = Program.SelectGun();
Assert.IsNull(currgun);
}
}
}
}
<file_sep>/README.md
# .Net Core Console App Shooting Game
Console Shooting Game .Net Core 2.1 and C#, Select Gun, Shoot Animal, Collect Points and Show points at Game over, Unit test cases, Visual Studio 2019
Controls
Move Gun Up: Up Arrow,
Move Gun Down: Down Arrow,
Shoot: Space Bar,
Exit: Esc,
Animal: #,
Gun: -/=
Select Gun
1. Pistol (Speed 3/5)
2. Rifle (Speed 5/5)
Press 1 or 2
and Hit Enter to Start
| afbbe3e6e0d8e99c3c7396b379e72b9934cbb0f5 | [
"Markdown",
"C#"
] | 2 | C# | Ajay311/DotNetCoreConsoleShootingGame | ac0bbac2da2ef16be755c3fec896dfba431510dd | 180689620250479424135b9ed9491ea598d773fc |
refs/heads/master | <repo_name>sodawave/nrn-app-fake<file_sep>/test/testFakeImporter.js
const assert = require('assert');
const { App } = require('@doc.ai/neuron-app');
const FakeImporter = require('../src/FakeImporter');
describe('FakeImporter access from app', () => {
const customConfig = {
name: 'fake',
groups: 'phonyome',
category: 'phonyome',
duration: 500,
failureProbability: 0.1,
};
const app = new App({ customConfig });
it('Importer registration should not raise an error', () => {
app.registerImporter('fake', FakeImporter);
});
it('Importer should show up in app importers list', () => {
assert.deepStrictEqual(Object.keys(app.importers), ['fake']);
});
it('Importer should have the specified name', () => {
assert.strictEqual(app.importers.fake.instance.name, 'fake');
});
it('Importer should have the specified groups', () => {
assert.deepStrictEqual(app.importers.fake.instance.groups, ['phonyome']);
});
it('Importer should have the specified duration', () => {
assert.strictEqual(app.importers.fake.instance.duration, 500);
});
it('Importer should have the specified failureProbability', () => {
assert.strictEqual(app.importers.fake.instance.failureProbability, 0.1);
});
it('Importer should have a logo defined', () => {
assert(app.importers.fake.instance.logo);
});
it('Importer collect should succeed (when appropriate)', (done) => {
app.importers.fake.instance.failureProbability = -1;
const collection = app.importers.fake.instance.collect();
collection.then((result) => {
if (result.iterations) {
return done();
}
return done(new Error(`Result: ${result} -- no iterations key`));
}).catch(err => done(err));
});
it('Importer collect should fail (when appropriate)', (done) => {
app.importers.fake.instance.failureProbability = 1;
const collection = app.importers.fake.instance.collect();
collection
.then(() => done(new Error('Expected: collection failure, actual: collection success')))
.catch(() => done());
});
it('Importer transform should do nothing', (done) => {
const initialObject = { msg: 'lol' };
app.importers.fake.instance.transform(initialObject)
.then((transformedObject) => {
assert.deepStrictEqual(transformedObject, initialObject);
done();
})
.catch(done);
});
});
<file_sep>/Dockerfile
FROM node:9.11.2-alpine
RUN mkdir -p /app
WORKDIR /app
COPY . .
# Reference: https://github.com/nodejs/docker-node/issues/282
RUN apk add --no-cache --virtual .gyp \
python \
make \
g++ \
&& npm install --prod \
&& apk del .gyp
CMD ["node", "src/index.js"]
<file_sep>/k8s/generate.bash
#!/bin/bash
# Generates YAML manifests from the template files provided in this directory
# Note: This is a stop-gap until we come up with a better templating solution
set -e -u -o pipefail
TAG=$1
# ID is any id you want to add that allows blue green deployments.
ID=$2
TEMPLATES=$(ls)
echo "Applying TAG: ${TAG} and ID: ${ID}:"
export TAG=$TAG ID=$ID
for SOURCE_FILE in $TEMPLATES; do
if [[ $SOURCE_FILE = *.template ]] ; then
TARGET_FILE=${SOURCE_FILE%.template}
echo -e "\tTemplate: $SOURCE_FILE -> Target: $TARGET_FILE"
envsubst '${TAG} ${ID}' <$SOURCE_FILE > $TARGET_FILE
fi
done
echo "Done!"<file_sep>/README.md
# nrn-fake-importer
Fake importer for testing (and instructive) purposes
- - -
## Entrypoint and importer registration
An importer makes its existence known as an `nrn-app` by:
1. Importing `App` from `@doc-ai/neuron-app`
1. Instantiating an instance of `App`, call it `app` with the appropriate configuration
1. Calling `app.registerImporter('<importer name>', <importer implementation>)`
1. Calling `app.start()`
## Importer implementation
An importer is any object which inherits from the `Importer` class defined in `node-neuron-app`. The
fake importer is implemented in [`src/FakeImporter.js`](./src/FakeImporter.js).
| 6b49c8d36d5fd7bbff2bc6f37f279678930d272b | [
"JavaScript",
"Dockerfile",
"Markdown",
"Shell"
] | 4 | JavaScript | sodawave/nrn-app-fake | b825a350e66e7639228871045b4073ee65ee150e | 407f205a0cca83bdf20d509bbf2bac7bb59f8d47 |
refs/heads/master | <file_sep>export class HungryBear {
constructor(name) {
this.name = name;
this.foodLevel = 10;
}
setHunger() {
setInterval(() => {
this.foodLevel--;
}, 1000);
}
didYouGetEaten() {
if (this.foodLevel > 0) {
return false;
} else {
return true;
}
}
feed() {
this.foodLevel = 13;
}
}
////////
// let bear = new Object;
// bear.name = "Fuzzy Wuzzy";
//
// bear.introduction = function() {
// console.log("Name in the outer function: " + this.name);
// let doThis = () => {
// console.log("Name in the inner function: " + this.name);
// return `My name is ${this.name}`
// }
// return doThis()
// }
//
// setTimeout(function(){
// alert("Hello friend! Maybe you should sign up for our newsletter!");
// }, 20000);
//
// setInterval(function(){
// //check and display time every second!
// }, 1000);
//
// bear.introduction();
<file_sep>import { HungryBear } from './../js/hungryBear.js';
$(document).ready(function() {
let fuzzy = new HungryBear("fuzzy");
fuzzy.setHunger();
setInterval(function(){ console.log(fuzzy.foodLevel);
if (fuzzy.foodLevel > 10) {
$("#normal").hide();
$("#eating").show();
$("#angry").hide();
$("#message").hide();
}
if (fuzzy.foodLevel < 11) {
$("#normal").show();
$("#eating").hide();
$("#angry").hide();
$("#message").hide();
}
if (fuzzy.foodLevel < 5) {
$("#normal").hide();
$("#angry").show();
$("#message").hide();
}
if (fuzzy.foodLevel <= 0) {
$("#angry").hide();
$("#feed").hide();
$("#dead").show();
$("#message").show();
$("#playagain").show();
}}, 1000);
$("#feed").click(function() {
fuzzy.feed();
});
});
| e87016b5942f37f133b8c5d33fb65b2bffdc5a9b | [
"JavaScript"
] | 2 | JavaScript | kruebling/bear-game | 6b0bd26c772471313a65289a55e83bec09174103 | 9c76eeded864c165b5daf6d8b3338828a670eb42 |
refs/heads/master | <file_sep>$(document).ready(function () {
$('#buggin').click(function () {
$("#mediaplayer").attr("src", "GenXvideos/buggin.mp4");
});
$('#bones').click(function () {
$("#mediaplayer").attr("src", "GenXvideos/bones.mp4");
});
$('#crib').click(function () {
$("#mediaplayer").attr("src", "GenXvideos/crib.mp4");
});
});<file_sep>//requires jquery and javascript
$(document).ready(function () {
$("#genx").hide();
$("#millennial").hide();
$("#genz").hide();
$('body').removeClass(".hidepage").fadeIn(3500);
$('#genxm').click(function () {
$("#genx").slideToggle();
$("#millennial").slideUp();
$("#genz").slideUp();
});
$('#millennialm').click(function () {
$("#genx").slideUp();
$("#millennial").slideToggle();
$("#genz").slideUp();
});
$('#genzm').click(function () {
$("#genx").slideUp();
$("#millennial").slideUp();
$("#genz").slideToggle();
});
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
// create new image object to use as pattern
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = function () {
// create pattern
var ptrn = ctx.createPattern(img, 'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, 200, 150);
}
}
draw();
function displayTime() {
var countDownDate = new Date("April 17, 2029 15:00:00").getTime();
var x = setInterval(function () {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (seconds < 10) {
// Add the "0" digit to the front
// so 9 becomes "09"
seconds = "0" + seconds;
}
// If the minutes digit is less than ten
if (minutes < 10) {
minutes = "0" + minutes;
}
// If the hours digit is less than ten
if (hours < 10) {
hours = "0" + hours;
}
//if days=0, show docs
document.getElementById("capsule").innerHTML = days + ":" + hours + ":" +
minutes + ":" + seconds + "";
});
}
displayTime();
draw();
});
| 67018fff85478d8a2cdb149d4706a98e8b90e2e4 | [
"JavaScript"
] | 2 | JavaScript | 0lonestar/vkellyy.github.io | 5fb38ed0f8c2882f4e198ee47d0ddeec597b1a4c | d22bc66c885caf3ae7adc62ab2a07f917bee612c |
refs/heads/main | <file_sep>
import os
import sys
def __init__():
project_path = os.getcwd()
print(project_path)
os.chdir(project_path)
os.path.join(os.path.dirname(sys.argv[0]))
project_path = os.getcwd()
print(project_path)
os.chdir(project_path)
os.path.join(os.path.dirname(sys.argv[0]))
import moyu_engine.config.main
moyu_engine.config.main.run() <file_sep>
import pickle
import moyu_engine.config.data.constants as C
class SavaSystem:
def save_tilemap():
f=open('moyu_engine/config/data/game_save','wb')
save_data = {'window':C.window}
pickle.dump(save_data, f)
f.close()
def read_tilemap():
f=open('moyu_engine/config/data/game_save', 'rb')
read_data = pickle.load(f)
C.window = read_data['window']
f.close()<file_sep>
import moyu_engine.config.data.constants as C
class MoveSystem:
@ staticmethod
def move():
if C.window['move_switch']['up'] == True:
C.window['move'][1] += C.window['move_speed']
if C.window['move_switch']['down'] == True:
C.window['move'][1] -= C.window['move_speed']
if C.window['move_switch']['left'] == True:
C.window['move'][0] += C.window['move_speed']
if C.window['move_switch']['right'] == True:
C.window['move'][0] -= C.window['move_speed']
@ staticmethod
def zoom():
if C.window['zoom_switch']['in'] == True:
if C.window['tilemap_level'] <= 0.25:
C.window['tilemap_level'] = 0.25
else:
C.window['tilemap_level'] -= 0.025
C.window['move'][1] -= 4.25
C.window['move'][0] -= 7.9
if C.window['zoom_switch']['out'] == True:
if C.window['tilemap_level'] >= 1:
C.window['tilemap_level'] = 1
else:
C.window['tilemap_level'] += 0.025
C.window['move'][1] += 4.25
C.window['move'][0] += 7.9<file_sep>###### MoYuStudio MYSG01 Dv
Mineland 吾之地 <br/><br/>
=======================
# Game News 游戏新闻
None
# Game Introduction 游戏简介
《 Mineland 吾之地 》是一款沙盒游戏
###### `本游戏由 MoYuStudio 摸魚社® 100%原创开发`
###### `MoYuStudio 摸魚社® & C-Prismera Tech Corp 淩创科技® reserves the right of final explanation` <br/><br/>
### Game Doc 游戏文档
移动视角:W A S D & 方向键 上下左右
缩放视角:Q E
还原视角:Z
随机重制地图(测试使用):X
建造:B
收获:R
保存:M
Update Log 更新日志
-------
##### 11/06/2021 Update Log 更新日志
项目立项
<file_sep>
import os
import sys
import pygame
from pygame.locals import *
import moyu_engine.config.data.constants as C
class AssetsSystem:
pygame.display.set_mode(C.window['size'],pygame.RESIZABLE)
@ staticmethod
def loader(folder_path = 'moyu_engine/assets'):
def cleaner(path):
if path.endswith('.DS_Store'): # Mac OS
os.remove(path)
if path.endswith('.ini'): # Windows
os.remove(path)
if path.endswith('.db'): # Windows
os.remove(path)
else:
pass
for root,dirs,files in os.walk(folder_path):
for file in files:
cleaner(os.path.join(root,file))
for dir in dirs:
C.assets[dir] = []
path = root+'/'+dir+'/'
file_num = len(os.listdir(path))
tmp = os.listdir(path)
for file_name in tmp:
file_num -= 1
if file_name.endswith('.ttf'):
C.assets[dir].append(pygame.font.Font(os.path.join(path,dir+f'{file_num}.ttf'),25))
if file_name.endswith('.png'):
C.assets[dir].append(pygame.image.load(os.path.join(path,dir+f'{file_num}.png')))#.convert_alpha()
if __name__ == "__main__":
pass
<file_sep>
import sys
import pygame
from pygame.locals import *
import moyu_engine.config.data.constants as C
import moyu_engine.config.system.tilemap_system
class MainWindow:
def blit():
blit_surface = pygame.Surface(C.window['size']).convert_alpha()
background_surface = pygame.Surface(C.window['size']).convert_alpha()
tilemap_surface = pygame.Surface((int(C.window['set_size'][0]/C.window['tilemap_level']),int(C.window['set_size'][1]/C.window['tilemap_level']))).convert_alpha()
sprite_surface = pygame.Surface((int(C.window['set_size'][0]/C.window['tilemap_level']),int(C.window['set_size'][1]/C.window['tilemap_level']))).convert_alpha()
gui_surface = pygame.Surface(C.window['size']).convert_alpha()
background_surface.fill((255,55,55,0))
tilemap_surface.fill((255,55,55,0))
moyu_engine.config.system.tilemap_system.TilemapSystem.loarder(tilemap_surface,C.window['move'][0],C.window['move'][1])
# for x in range(C.tilemap['boarder']):
# for y in range(C.tilemap['boarder']):
# if ((C.tilemap['tilemap'])[x][y])[0] == 5:
# rect = pygame.Rect((((C.tilemap['tilemap'])[x][y])[6]+C.window['move'][0],((C.tilemap['tilemap'])[x][y])[7]+C.window['move'][1],16,16),width=0)
# if C.player_rect.colliderect(rect):
# print('1')
# pygame.draw.rect(sprite_surface,(0,255,0),rect)
# else:
# print('2')
sprite_surface.blit(C.assets['player1-s'][-(0)-1],(C.window['set_size'][0]/2-8,C.window['set_size'][1]/2-8))
tilemap_surfaceFin = pygame.transform.scale(tilemap_surface,(C.window['size']))
sprite_surfaceFin = pygame.transform.scale(sprite_surface,(C.window['size']))
blit_surface.blit(background_surface, (0, 0))
blit_surface.blit(tilemap_surfaceFin, (0, 0))
blit_surface.blit(sprite_surfaceFin, (0, 0))
C.screen.blit(blit_surface, (0, 0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == K_UP or event.key == K_w:
C.window['move_switch']['up'] = True
if event.key == K_DOWN or event.key == K_s:
C.window['move_switch']['down'] = True
if event.key == K_LEFT or event.key == K_a:
C.window['move_switch']['left'] = True
if event.key == K_RIGHT or event.key == K_d:
C.window['move_switch']['right'] = True
if event.key == K_q:
C.window['zoom_switch']['in'] = True
if event.key == K_e:
C.window['zoom_switch']['out'] = True
if event.type == pygame.KEYUP:
if event.key == K_UP or event.key == K_w:
C.window['move_switch']['up'] = False
if event.key == K_DOWN or event.key == K_s:
C.window['move_switch']['down'] = False
if event.key == K_LEFT or event.key == K_a:
C.window['move_switch']['left'] = False
if event.key == K_RIGHT or event.key == K_d:
C.window['move_switch']['right'] = False
if event.key == K_q:
C.window['zoom_switch']['in'] = False
if event.key == K_e:
C.window['zoom_switch']['out'] = False
<file_sep>
import random
import noise
import pygame
import moyu_engine.config.data.constants as C
class TilemapSystem:
def builder():
#random.seed(random.randint(100000000, 999999999))
C.tilemap['seed'] = random.randint(100000, 999999)
# 0 tile land 1 tile build 2 tile preview 3 time 4 buildable 5 hitable 6 tile button x 7 tile button y 8 Dv Code
C.tilemap['tilemap'] = [
[
[
int(noise.pnoise2((x/C.tilemap['freq'])+C.tilemap['seed'],(y/C.tilemap['freq'])+C.tilemap['seed'],C.tilemap['octaves'])*100+50),
random.randint(0,200),
0,
0,
0,
0,
0,
0,
0
] for x in range(0,C.tilemap['boarder'],1)
] for y in range(0,C.tilemap['boarder'],1)
]
def loarder(tilemap_surface,move_x,move_y):
tilemap_surface.fill((255,55,55,0))
tilemap_n = len(C.tilemap['tilemap'])
tilemap_m = len(C.tilemap['tilemap'][0])
for tilemap_x in range(tilemap_n):
for tilemap_y in range(tilemap_m):
tile_info = C.tilemap['tilemap'][tilemap_x][tilemap_y]
if tile_info[7] == 0:
# === 0 tile_land ===
#print(tile_info[0])
if -100 <=tile_info[0]<= 37:
tile_info[0] = 5
if 38 <=tile_info[0]<= 40:
tile_info[0] = 0
if 41 <=tile_info[0]<= 65:
tile_info[0] = 0
if 66 <=tile_info[0]<= 70:
tile_info[0] = 2
if 70 <=tile_info[0]<= 110:
tile_info[0] = 3
# === 1 tile_building ===
if 0<=tile_info[2]<=30:
tile_info[2] = 0
if 31<=tile_info[2]<=100 and tile_info[0] == 6:
tile_info[2] = 105
if 101<=tile_info[2]<=200 and tile_info[0] == 16:
tile_info[2] = 155
# === 2 tile_preview ===
# === 3 tile_time ===
# === 4 tile_buildable ===
# === 5 tile_hitable ===
# === 6 tile_pos_x ===
tile_info[6] = (tilemap_x*C.tilemap['tile_size'])
# === 7 tile_pos_y ===
tile_info[7] = (tilemap_y*C.tilemap['tile_size'])
# === 8 tile_dvcode ===
tile_info[8] = 1
#print(tilemap)
if tile_info[8] == 1:
# === 0 tile_land ===
if tile_info[0] == 0:
tilemap_surface.blit(C.assets['tileland'][-(0)-1],((tilemap_x*C.tilemap['tile_size']+move_x,tilemap_y*C.tilemap['tile_size']+move_y)))
if tile_info[0] == 1:
tilemap_surface.blit(C.assets['tileland'][-(1)-1],((tilemap_x*C.tilemap['tile_size']+move_x,tilemap_y*C.tilemap['tile_size']+move_y)))
if tile_info[0] == 2:
tilemap_surface.blit(C.assets['tileland'][-(2)-1],((tilemap_x*C.tilemap['tile_size']+move_x,tilemap_y*C.tilemap['tile_size']+move_y)))
if tile_info[0] == 3:
tilemap_surface.blit(C.assets['tileland'][-(3)-1],((tilemap_x*C.tilemap['tile_size']+move_x,tilemap_y*C.tilemap['tile_size']+move_y)))
if tile_info[0] == 4:
tilemap_surface.blit(C.assets['tileland'][-(4)-1],((tilemap_x*C.tilemap['tile_size']+move_x,tilemap_y*C.tilemap['tile_size']+move_y)))
if tile_info[0] == 5:
tilemap_surface.blit(C.assets['tileland'][-(5)-1],((tilemap_x*C.tilemap['tile_size']+move_x,tilemap_y*C.tilemap['tile_size']+move_y)))
# # === 1 tile_preview ===
# if tile_info[1] == 0:
# pass
# if tile_info[1] == 1:
# tilemap_surface.blit(G.pretile_choose,((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y - 1))
# tilemap_surface.blit(G.pretile_green,((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y - 1))
# if C.build == True:
# tile_info[2] = C.tile_type
# C.build = False
# if tile_info[1] == 2:
# tilemap_surface.blit(G.pretile_choose,((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y - 1))
# tilemap_surface.blit(G.pretile_red,((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y - 1))
# if tile_info[1] == 3:
# tilemap_surface.blit(G.pretile_choose,((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y - 1))
# if C.reward == True:
# if tile_info[2] == 5:
# tile_info[1] = 0
# tile_info[2] = 1
# tile_info[3] = 0
# C.money += 80
# C.reward = False
# def tile_preview_top():
# if tile_info[1] == 3:
# tilemap_surface.blit(G.pretile_reward,((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y - 6))
# # === 2 tile_building ===
if tile_info[2] == 0:
pass
if tile_info[2] == 1:
tilemap_surface.blit(C.assets['tilebuilding'][-2],((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y))
if tile_info[2] == 2:
tilemap_surface.blit(C.assets['tilebuilding'][-3],((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y))
tile_info[3] += C.time_speed
if tile_info[3] >= 4000:
tile_info[2] = 3
if tile_info[2] == 3:
tilemap_surface.blit(C.assets['tilebuilding'][-4],((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y))
tile_info[3] += C.time_speed
if tile_info[3] >= 8000:
tile_info[2] = 4
if tile_info[2] == 4:
tilemap_surface.blit(C.assets['tilebuilding'][-5],((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y))
tile_info[3] += C.time_speed
if tile_info[3] >= 12000:
tile_info[2] = 5
if tile_info[2] == 5:
tilemap_surface.blit(C.assets['tilebuilding'][-6],((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y))
tile_info[3] += C.time_speed
if tile_info[2] == 105 and tile_info[0] == 6:
tilemap_surface.blit(C.assets['tilebuilding'][-7],((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))-32+move_y))
if tile_info[2] == 155 and tile_info[0] == 16:
tilemap_surface.blit(C.assets['tilebuilding'][-8],((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x,(tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))-32+move_y))
# # === 1 tile_preview top ===
# tile_preview_top()
# # === 3 tile_time ===
# # === 4 tile_buildable ===
# if C.tile_type == 1:
# if tile_info[0] == 1 or \
# tile_info[0] == 6:
# tile_info[4] = 1
# else:
# tile_info[4] = 0
# if C.tile_type == 2:
# if tile_info[2] == 1:
# tile_info[4] = 1
# else:
# tile_info[4] = 0
# === 5 tile_hitable ===
if tile_info[0] == 3:
rect = pygame.Rect((tile_info[6]+move_x,tile_info[7]+move_y,16,16),width=0)
if C.player_rect.colliderect(rect):
pygame.draw.rect(tilemap_surface,(0,255,0),rect)
C.window['move_switch']['up'] = False
C.window['move_switch']['down'] = False
C.window['move_switch']['right'] = False
C.window['move_switch']['left'] = False
if tile_info[0] == 5:
rect = pygame.Rect((tile_info[6]+move_x,tile_info[7]+move_y,16,16),width=0)
if C.player_rect.colliderect(rect):
pygame.draw.rect(tilemap_surface,(0,255,0),rect)
C.window['move_switch']['up'] = False
C.window['move_switch']['down'] = False
C.window['move_switch']['right'] = False
C.window['move_switch']['left'] = False
# # === 5 tile_pos_x ===
# # 16*tilemap_surface_level,9*tilemap_surface_level
# tile_info[5] = ((tilemap_y*(C.tilemap['tile_size']/2)-tilemap_x*(C.tilemap['tile_size']/2))+move_x)*C.surface_level
# # === 6 tile_pos_y ===
# tile_info[6] = ((tilemap_y*(C.tilemap['tile_size']/4)+tilemap_x*(C.tilemap['tile_size']/4))+move_y)*C.surface_level
# # === 7 tile_dvcode ===
def tilemap_clicker():
pass
<file_sep>
import pygame
from pygame.locals import *
window =\
{
# window
'size' : [1280,720],
'set_size' : [320,180],
'size_level' : 0.5,
'fps' : 60,
'title' : 'Mineland',
'surface_level': 1,
'tilemap_level': 1,
# move
'move':[8,20],
'move_speed':2,
'move_switch':
{
'up' : False,
'down' : False,
'left' : False,
'right': False,
},
'zoom_switch':
{
'in' : False,
'out': False,
},
# window ppt
'page_switch' :
{
'switch':False,
'menu_main_page' : True,
'game_main_page' : False,
}
}
tilemap =\
{
# tilemap
'tilemap': [],
'boarder': 64,
'seed' : 0,
'octaves': 2,
'freq' : 12,
# tile
'tile_size' : 16,
'pretile_type' : 0,
'tile_type' : 0,
'build' : False,
'reward' : False,
'tile_choose' : False,
'tile_choose_info': [0,0,0],
'tile_choose_info': [0,0,0,0,0,0],
# tile time
'time_speed': 1000,
}
assets = {}
gui =\
{
'button_preclick': False,
'button_num' : 0,
}
transition =\
{
'fade_black' : False,
}
screen = pygame.display.set_mode(window['size'],pygame.RESIZABLE)
player_rect = pygame.Rect((window['set_size'][0]/2-8,window['set_size'][1]/2-8,16,16),width=0)
hitable_map = []<file_sep>
import sys
import pygame
from pygame.locals import *
import moyu_engine.config.data.constants as C
import moyu_engine.config.system.assets_system
import moyu_engine.config.system.tilemap_system
import moyu_engine.config.system.move_system
import moyu_engine.config.window.main_window
def init():
pygame.init()
pygame.mixer.init()
SCREEN = pygame.display.set_mode(C.window['size'],pygame.RESIZABLE)
SCREEN_TITLE = pygame.display.set_caption(C.window['title'])
#pygame.display.set_icon(G.tl16)
CLOCK = pygame.time.Clock()
pygame.display.flip()
moyu_engine.config.system.assets_system.AssetsSystem.loader()
moyu_engine.config.system.tilemap_system.TilemapSystem.builder()
while True:
moyu_engine.config.system.move_system.MoveSystem.move()
moyu_engine.config.window.main_window.MainWindow.blit()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
CLOCK.tick(C.window['fps'])
def run():
init()
if __name__ == "__main__":
pass
| c836ca61ec10c3854dc3338926e10c1a6e6b6a5c | [
"Markdown",
"Python"
] | 9 | Python | MoYuStudio/MYSG01 | 2bb33f6258893d881466689cd2f0de50e866915d | 590c6cbc2af1339c168885a5ddeb5f6b71c63d0e |
refs/heads/master | <repo_name>llwor94/back-end-project-week<file_sep>/server.js
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const configureRoutes = require('./config');
const server = express();
server.use(express.json());
server.use(morgan('dev'));
server.use(cors());
configureRoutes(server);
server.get('/', (req, res) => {
res.send('ya made it mon');
});
module.exports = server;
<file_sep>/_secrets/keys.js
module.exports = {
jwtKey: 'Hella secretz <PASSWORD> the secrets',
};
<file_sep>/config/routes/authRoutes.js
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const router = express.Router();
const jwtKey = require('../../_secrets/keys').jwtKey;
const db = require('../../database/dbConfig');
function generateToken(id) {
const payload = {
id,
};
const options = {
expiresIn: '1h',
jwtid: '12345',
subject: `${id}`,
};
return jwt.sign(payload, process.env.SECRET || jwtKey, options);
}
router.post('/register', (req, res, next) => {
let { username, password } = req.body;
if (!username || !password) next({ code: 400 });
body.password = <PASSWORD>.hashSync(password, 12);
db('users')
.insert({ username, password })
.then(([id]) => {
const token = generateToken(id);
res.json({
error: false,
message: 'User created successfully',
user: id,
token,
});
})
.catch(next);
});
router.post('/login', (req, res, next) => {
let { username, password } = req.body;
if (!username || !password) next({ code: 400 });
db('users')
.where({ username: username })
.first()
.then(user => {
console.log(user);
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user.id);
return res.json({
error: false,
message: 'Log in Successful',
user: user,
token,
});
} else next({ code: 404 });
})
.catch(next);
});
module.exports = router;
<file_sep>/config/middleware.js
const jwt = require('jsonwebtoken');
const jwtKey = require('../_secrets/keys').jwtKey;
module.exports = {
errorHandler: function(err, req, res, next) {
console.log(err);
if (err.errno === 19)
return res.json({ error: true, msg: 'Username is already taken' });
switch (err.code) {
case 404:
res.json({
error: true,
msg: 'The requested file does not exist.',
});
break;
case 400:
res.json({
error: true,
msg: 'Please complete all the required fields',
});
break;
case 403:
res.json({
error: true,
msg: 'You are unathorized to view the content.',
});
break;
default:
res.status(500).json({
error: true,
message: 'There was an error performing the required operation',
});
break;
}
},
authenticate: function(req, res, next) {
const token = req.headers.authorization;
if (token) {
jwt.verify(token, jwtKey, (err, decodedToken) => {
console.log('err', err);
if (err)
return res.json({
error: true,
msg: 'Invalid Token',
});
console.log(decodedToken);
req.user = { id: decodedToken.id };
next();
});
} else {
next({ code: 403 });
}
},
};
<file_sep>/config/routes/noteRoutes.js
const express = require('express');
const router = express.Router();
const db = require('../../database/dbConfig');
router.get('/', (req, res, next) => {
db('notes')
.then(data => {
res.status(200).json(data);
})
.catch(next);
});
router.get('/:id', (req, res, next) => {
db('notes')
.where({ id: req.params.id })
.first()
.then(note => {
if (!note) return next({ code: 404 });
res.status(200).json(note);
})
.catch(next);
});
router.post('/', (req, res, next) => {
let { title, content } = req.body;
if (!title || !content) return next({ code: 400 });
db('notes')
.insert({ title, content })
.then(data => {
res.status(200).json({
error: false,
message: 'Post successful',
});
})
.catch(next);
});
router.put('/:id', (req, res, next) => {
let { title, content, index } = req.body;
if (!title && !content && !index) return next({ code: 400 });
if (!index) {
db('notes')
.where({ id: req.params.id })
.update({ title, content })
.then(response => {
if (!response) return next({ code: 404 });
res.status(200).json({
error: false,
message: 'Update successful',
});
})
.catch(next);
}
let id = index + 1;
db('notes').where('id', '>', index).increment('id', 1).then(response => console.log(response));
});
router.delete('/:id', (req, res, next) => {
db('notes')
.where({ id: req.params.id })
.del()
.then(response => {
if (!response) return next({ code: 404 });
res.status(200).json({
error: false,
message: 'Delete successful',
});
})
.catch(next);
});
module.exports = router;
<file_sep>/config/index.js
const authRoutes = require('./routes/authRoutes');
const noteRoutes = require('./routes/noteRoutes');
const { errorHandler, authenticate } = require('./middleware');
module.exports = server => {
server.use('/api', authRoutes);
server.use('/api/notes', noteRoutes);
server.use(errorHandler);
};
| 37f00b16d194d92d6aca4988bf7ef45d155b6457 | [
"JavaScript"
] | 6 | JavaScript | llwor94/back-end-project-week | ae6443bef2a6dc0c05519346c423d3d923e70975 | 06c2921e09b425be7a5a3113d1a346468f935539 |
refs/heads/master | <file_sep>using Microsoft.EntityFrameworkCore;
namespace EFCoreDemos.Database;
public class DemoDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<ProductGroup> ProductGroups { get; set; }
public DbSet<Studio> Studios { get; set; }
public DbSet<Price> Prices { get; set; }
public DbSet<Seller> Sellers { get; set; }
public DemoDbContext(DbContextOptions<DemoDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var groups = GenerateProductGroups(10);
var studios = GenerateStudio(5);
var products = GenerateProducts(groups, studios, 100);
var prices = GeneratePrices(products, 10);
var sellers = GenerateSellers(2);
var sellerProducts = GenerateSellerProducts(products, sellers);
modelBuilder.Entity<ProductGroup>(builder =>
{
builder.Property(g => g.Id).ValueGeneratedNever();
builder.HasData(groups);
});
modelBuilder.Entity<Studio>(builder =>
{
builder.Property(s => s.Id).ValueGeneratedNever();
builder.HasData(studios);
});
modelBuilder.Entity<Product>(builder =>
{
builder.Property(p => p.Id).ValueGeneratedNever();
builder.HasIndex(p => new { p.ProductGroupId, p.Id })
.IncludeProperties(p => p.Name);
builder.HasData(products);
});
modelBuilder.Entity<Price>(builder =>
{
builder.Property(p => p.Id).ValueGeneratedNever();
builder.Property(p => p.Value).HasPrecision(19, 2);
builder.HasData(prices);
});
modelBuilder.Entity<Seller>(builder =>
{
builder.Property(s => s.Id).ValueGeneratedNever();
builder.HasMany(s => s.Products)
.WithMany(p => p.Sellers)
.UsingEntity<Seller_Product>(sellerProductsBuilder => sellerProductsBuilder.HasOne(sp => sp.Product).WithMany(),
sellerProductsBuilder => sellerProductsBuilder.HasOne(sp => sp.Seller).WithMany(),
sellerProductsBuilder =>
{
sellerProductsBuilder.ToTable("SellerProducts");
sellerProductsBuilder.HasKey(sp => new { sp.ProductId, sp.SellerId });
sellerProductsBuilder.HasData(sellerProducts);
});
builder.HasData(sellers);
});
}
private static List<Price> GeneratePrices(
List<Product> products,
int numberOfPricesPerProduct)
{
var prices = new List<Price>();
for (var i = 0; i < products.Count; i++)
{
var product = products[i];
prices.AddRange(Enumerable.Range(1, numberOfPricesPerProduct)
.Select(j => new Price
{
Id = i * numberOfPricesPerProduct + j,
ProductId = product.Id,
Value = 42
}));
}
return prices;
}
private static List<Seller> GenerateSellers(int numberOfSellers)
{
return Enumerable.Range(1, numberOfSellers)
.Select(i => new Seller
{
Id = i,
Name = $"Seller {i}"
})
.ToList();
}
private static List<object> GenerateSellerProducts(
List<Product> products,
List<Seller> sellers)
{
var sellersProduct = new List<object>();
foreach (var product in products)
foreach (var seller in sellers)
{
sellersProduct.Add(new
{
ProductId = product.Id,
SellerId = seller.Id
});
}
return sellersProduct;
}
private static List<Studio> GenerateStudio(int numberOfStudios)
{
return Enumerable.Range(1, numberOfStudios)
.Select(i => new Studio
{
Id = i,
Name = $"Studio {i}"
})
.ToList();
}
private static List<ProductGroup> GenerateProductGroups(int numberOfGroups)
{
return Enumerable.Range(1, numberOfGroups)
.Select(i => new ProductGroup
{
Id = i
})
.ToList();
}
private static List<Product> GenerateProducts(
List<ProductGroup> groups,
List<Studio> studios,
int numberOfProducts)
{
return Enumerable.Range(1, numberOfProducts)
.Select(i => new Product
{
Id = i,
Name = $"Product {i}",
DeliverableFrom = new DateTime(2000, 01, 01),
DeliverableUntil = new DateTime(2030, 01, 01),
ProductGroupId = groups[i % groups.Count].Id,
StudioId = studios[i % studios.Count].Id
})
.ToList();
}
}
<file_sep>namespace EFCoreDemos.Database;
public class Seller_Product
{
public int SellerId { get; set; }
public virtual Seller Seller { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}<file_sep>using EFCoreDemos.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace EFCoreDemos;
public class Demos
{
private readonly ILogger<Demos> _logger;
private readonly DemoDbContext _ctx;
public Demos(
ILogger<Demos> logger,
DemoDbContext ctx)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_ctx = ctx ?? throw new ArgumentNullException(nameof(ctx));
}
public void Execute()
{
// The following demos are using the sync-API for simplicity reasons
// Demo_1_1();
// Demo_1_2();
//
// Approach_1_1();
// Approach_1_2();
//
// Demo_1_3();
// Approach_1_3();
//
// Demo_2_1();
// Approach_2_1();
//
// Demo_2_2();
// Approach_2_2();
// Approach_2_2_without_AsSplitQuery();
// Demo_3_1();
}
private void Demo_1_1()
{
var products = _ctx.Products.ToList();
_logger.LogInformation("{NumberOfProducts} products loaded", products.Count);
var prices = new List<Price>();
foreach (var product in products)
{
var price = GetPrice(product.Id);
prices.Add(price);
}
}
private Price GetPrice(int productId)
{
// oversimplified
return _ctx.Prices.FirstOrDefault(p => p.ProductId == productId);
}
private void Demo_1_2()
{
var products = _ctx.Products.ToList();
_logger.LogInformation("{NumberOfProducts} products loaded", products.Count);
var prices = products.Select(product => GetPrice(product.Id))
.ToList();
}
private void Approach_1_1()
{
// Use-case specific method
var productsWithPrices = _ctx.Products
// merely symbolic, fetching prices is usually more complex
.Include(p => p.Prices)
.ToList();
}
private void Approach_1_2()
{
var products = _ctx.Products.ToList();
var productIds = products.Select(p => p.Id);
var prices = GetPrices(productIds);
}
private List<Price> GetPrices(IEnumerable<int> productIds)
{
return _ctx.Prices
.Where(p => productIds.Contains(p.ProductId))
.ToList();
}
private void Demo_1_3()
{
// Activate lazy-loading!
var productsByStudio = _ctx.Products
.ToLookup(p => p.Studio.Name);
}
private void Approach_1_3()
{
// Activate lazy-loading!
var productsByStudio = _ctx.Products
.Include(p => p.Studio)
.ToLookup(p => p.Studio.Name);
}
private void Demo_2_1()
{
var products = _ctx.Products
.Include(p => p.Studio)
.Include(p => p.Prices)
.Include(p => p.Sellers)
.ToList();
}
private void Approach_2_1()
{
var products = _ctx.Products
.AsSplitQuery()
.Include(p => p.Studio)
.Include(p => p.Prices)
.Include(p => p.Sellers)
.ToList();
}
private void Demo_2_2()
{
var result = _ctx.ProductGroups
// .AsSplitQuery() // leads to an InvalidOperationException
.Select(g => new
{
Group = g,
Products = g.Products
.Select(p => new
{
Product = p,
p.Prices,
p.Sellers
})
})
.ToList();
}
private void Approach_2_2()
{
var groupQuery = _ctx.ProductGroups; // may have additional filters
var groups = groupQuery.ToList();
var products = groupQuery.SelectMany(g => g.Products)
.AsSplitQuery()
.Include(p => p.Prices)
.Include(p => p.Sellers)
.ToList();
// Build the desired data structure
var result = groups
// .AsSplitQuery() // leads to an InvalidOperationException
.Select(g => new
{
Group = g,
Products = g.Products // "Products" is populated thanks to ChangeTracking
.Select(p => new
{
Product = p,
p.Prices,
p.Sellers
})
})
.ToList();
}
// Alternative way without "AsSplitQuery" (which was the only way before EF 5)
private void Approach_2_2_without_AsSplitQuery()
{
var groupQuery = _ctx.ProductGroups; // may have additional filters
var groups = groupQuery.ToList();
var productsQuery = groupQuery.SelectMany(g => g.Products); // may have additional filters
var products = productsQuery.ToList(); // Alternatively, we can fetch the Products along with the ProductGroups
var prices = productsQuery.SelectMany(p => p.Prices).ToList();
// cannot use "productsQuery.Select(p => p.Sellers)" because JoinTable "Seller_Product" won't be selected
var sellers = _ctx.Set<Seller_Product>()
.Join(productsQuery, sp => sp.ProductId, p => p.Id, (sp, p) => sp)
.Include(sp => sp.Seller)
.ToList();
// Build the desired data structure
var result = groups
// .AsSplitQuery() // leads to an InvalidOperationException
.Select(g => new
{
Group = g,
Products = g.Products // "Products" is populated thanks to ChangeTracking
.Select(p => new
{
Product = p,
p.Prices,
p.Sellers
})
})
.ToList();
}
private void Demo_3_1()
{
var groups1 = _ctx.ProductGroups
.Select(g => new
{
g.Products.FirstOrDefault().Id,
g.Products.FirstOrDefault().Name
})
.ToList();
var groups2 = _ctx.ProductGroups
.Select(g => g.Products
.Select(p => new
{
p.Id,
p.Name
})
.FirstOrDefault())
.ToList();
}
}
<file_sep>using EFCoreDemos.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace EFCoreDemos;
class Program
{
private const bool _ENSURE_DATABASE = false;
private const bool _ACTIVATE_LAZY_LOADING = false;
static async Task Main()
{
var serviceProvider = BuildServiceProvider();
if (_ENSURE_DATABASE)
await EnsureDatabaseAsync(serviceProvider);
using var scope = serviceProvider.CreateScope();
scope.ServiceProvider.GetRequiredService<Demos>().Execute();
}
private static async Task EnsureDatabaseAsync(IServiceProvider serviceProvider)
{
using var scope = serviceProvider.CreateScope();
var ctx = scope.ServiceProvider.GetRequiredService<DemoDbContext>();
await ctx.Database.EnsureCreatedAsync();
}
private static IServiceProvider BuildServiceProvider()
{
var config = GetConfiguration();
var connString = config.GetConnectionString(nameof(DemoDbContext))
?? throw new Exception($"No connection string for '{nameof(DemoDbContext)}' provided");
var services = new ServiceCollection()
.AddSingleton(config)
.AddLogging(builder =>
{
var serilog = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger();
builder.AddSerilog(serilog);
})
.AddScoped<Demos>()
.AddDbContext<DemoDbContext>((serviceProvider, builder) => builder.UseSqlServer(connString)
.UseLazyLoadingProxies(_ACTIVATE_LAZY_LOADING)
.UseLoggerFactory(serviceProvider.GetRequiredService<ILoggerFactory>())
.EnableDetailedErrors()
.EnableSensitiveDataLogging());
return services.BuildServiceProvider();
}
private static IConfiguration GetConfiguration()
{
return new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
}
}
<file_sep>namespace EFCoreDemos.Database;
public class ProductGroup
{
public int Id { get; set; }
public virtual List<Product> Products { get; set; }
}<file_sep>namespace EFCoreDemos.Database;
public class Price
{
public int Id { get; set; }
public int ProductId { get; set; }
public decimal Value { get; set; }
}<file_sep>namespace EFCoreDemos.Database;
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DeliverableFrom { get; set; }
public DateTime DeliverableUntil { get; set; }
public int ProductGroupId { get; set; }
public virtual ProductGroup ProductGroup { get; set; }
public int StudioId { get; set; }
public virtual Studio Studio { get; set; }
public virtual List<Price> Prices { get; set; }
public virtual List<Seller> Sellers { get; set; }
}<file_sep># Entity Framework Core - Performance-Optimierung aus der Praxis
## Setup
1) `ConnectionString` in `appsettings.json` prüfen.
2) Die Variable `_ensureDatabase` in `Program.cs` schaltet das automatische Anlegen der Datenbank ein- und aus. Beim ersten Durchlauf muss die Variable `true` sein.
## Verwendung
Die Klasse `Demos.cs` enthält die einzelnen Demos. Pro Durchlauf nur 1 Demo laufen lassen, ansonsten sieht man den erwarteten Effekt ggf. nicht, da der `DbContext` ein Cache ist.
Für einige Demos muss das Lazy-Loading aktiviert sein, diese haben den Kommentar `Activate lazy-loading`. Hierfür muss die Variable `_ENSURE_DATABASE` in `Program.cs` auf `true` gesetzt werden.
| 2b0187a26678e77867bed339595cee54208d3ae9 | [
"Markdown",
"C#"
] | 8 | C# | thinktecture/ef-core-performance-webinar-2020 | 5f21f63ae0534e3dee0fdf1e4eb72c48edb39059 | 7a3de46b6077275fc2ee3d7768799a5082d0af8d |
refs/heads/master | <file_sep>let board = [];
function play(clickedId) {
let playerSpan = document.getElementById('player');
let clickedElement = document.getElementById(clickedId);
let boardFull = true;
let winner = true;
winnersMessage = `PLAYER ${playerSpan.innerText} WON!`;
for (var i = 0; i < 9; i++) {
if (board[i] === undefined) {
boardFull = false;
}
}
// ALERTS "CATS GAME" IF BOARD IS FULL AND HAS NO WINNER
if (boardFull) {return (window.alert('CATS GAME'))}
// -------------------------------------------------------
if (clickedElement.innerText === '') {
if (playerSpan.innerText === 'X') {
playerSpan.innerText = 'O';
clickedElement.innerText = 'X';
board[clickedId] = 'X';
} else {
playerSpan.innerText = 'X';
clickedElement.innerText = 'O';
board[clickedId] = 'O';
}
}
// CHECKS ALL POSSIBLE WINNING COMBINATIONS
if (board[0] !== undefined && board[0] === board[1] && board[0] === board[2]) {window.alert(winnersMessage); reset()}; // TOP ROW
if (board[3] !== undefined && board[3] === board[4] && board[3] === board[5]) {window.alert(winnersMessage); reset()}; // MIDDLE ROW
if (board[6] !== undefined && board[6] === board[7] && board[6] === board[8]) {window.alert(winnersMessage); reset()}; // BOTTOM ROW
if (board[0] !== undefined && board[0] === board[3] && board[0] === board[6]) {window.alert(winnersMessage); reset()}; // LEFT COLUMN
if (board[1] !== undefined && board[1] === board[4] && board[1] === board[7]) {window.alert(winnersMessage); reset()}; // MIDDLE COLUMN
if (board[2] !== undefined && board[2] === board[5] && board[2] === board[8]) {window.alert(winnersMessage); reset()}; // RIGHT COLUMN
if (board[0] !== undefined && board[0] === board[4] && board[0] === board[8]) {window.alert(winnersMessage); reset()}; // BACKWARD DIAGONAL
if (board[6] !== undefined && board[6] === board[4] && board[6] === board[2]) {window.alert(winnersMessage); reset()}; // FORWARD DIAGONAL
}
function reset() {
board = [];
for (var i = 0; i < 9; i++) {
document.getElementById(i).innerText = '';
}
} | 4bb58f0e53986fca931853f080519950bdb750a6 | [
"JavaScript"
] | 1 | JavaScript | ProPiloty/vanillajs-1-afternoon | b6fcb9aad5a0bf73e0d70c7e1ecfab69f04d0dd3 | af71b46ef38fd797cb313a0306fea7c0a120ecd0 |
refs/heads/master | <file_sep>## Trabalho LP GO
Primeiro trabalho LP
<file_sep>package main
import (
"bufio"
"log"
"os"
"strings"
"strconv"
)
func lecatalogo(l *Lista) *Lista{//lê o arquivo catalogo.txt e salva suas informações
var floataux float64
file, err := os.Open("catalogo.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() != "" {
switch strings.ToLower(scanner.Text()) {
case "apto":
var imovelaux Imovel
var residenciaaux Residencia
var apartamentoaux Apartamento
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
residenciaaux.quartos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
residenciaaux.vagas, err = strconv.Atoi(scanner.Text())
scanner.Scan()
apartamentoaux.andar, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
apartamentoaux.aconstruida = float32(floataux)
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
residenciaaux.preco = float32(floataux)
scanner.Scan()
if scanner.Text() == "S" {apartamentoaux.alazer = 1.15}
if scanner.Text() == "N" {apartamentoaux.alazer = 1.0}
scanner.Scan()
apartamentoaux.totalandares, err = strconv.Atoi(scanner.Text())
//terminou de ler o apto
residenciaaux.residencia = &apartamentoaux
imovelaux.imovel = &residenciaaux
l = insereLista(l,imovelaux)
case "casa":
var imovelaux Imovel
var residenciaaux Residencia
var casaaux Casa
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
residenciaaux.quartos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
residenciaaux.vagas, err = strconv.Atoi(scanner.Text())
scanner.Scan()
casaaux.numpavimentos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
casaaux.apavimento = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
residenciaaux.preco = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
casaaux.alivre = float32(floataux)
scanner.Scan()
casaaux.palivre, err = strconv.Atoi(scanner.Text())
//terminou de ler a casa
residenciaaux.residencia = &casaaux
imovelaux.imovel = &residenciaaux
l = insereLista(l,imovelaux)
case "triang":
var imovelaux Imovel
var terrenoaux Terreno
var triang Triangular
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
triang.base = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
triang.altura = float32(floataux)
//terminou de ler o terreno triangular
terrenoaux.terreno = &triang
imovelaux.imovel = &terrenoaux
l = insereLista(l, imovelaux)
case "retang":
var imovelaux Imovel
var terrenoaux Terreno
var retang Retangular
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
retang.lado1 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
retang.lado2 = float32(floataux)
//terminou de ler o terreno retangular
terrenoaux.terreno = &retang
imovelaux.imovel = &terrenoaux
l = insereLista(l, imovelaux)
case "trapez":
var imovelaux Imovel
var terrenoaux Terreno
var trapez Trapezoidal
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.base1 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.base2 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.altura = float32(floataux)
//terminou de ler o terreno trapezoidal
terrenoaux.terreno = &trapez
imovelaux.imovel = &terrenoaux
l = insereLista(l, imovelaux)
}
}
}
return l
}
func leoperacoes(l *Lista) *Lista{//lê o arquivo atual.txt e salva informações
var floataux float64
file, err := os.Open("atual.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() != ""{
switch strings.ToLower(scanner.Text()){
case "i":
scanner.Scan()
if scanner.Text() == "apto" {
var imovelaux Imovel
var residenciaaux Residencia
var apartamentoaux Apartamento
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
residenciaaux.quartos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
residenciaaux.vagas, err = strconv.Atoi(scanner.Text())
scanner.Scan()
apartamentoaux.andar, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
apartamentoaux.aconstruida = float32(floataux)
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
residenciaaux.preco = float32(floataux)
scanner.Scan()
if scanner.Text() == "S" {apartamentoaux.alazer = 1.15}
if scanner.Text() == "N" {apartamentoaux.alazer = 1.0}
scanner.Scan()
apartamentoaux.totalandares, err = strconv.Atoi(scanner.Text())
//terminou de ler o apto
residenciaaux.residencia = &apartamentoaux
imovelaux.imovel = &residenciaaux
l = insereLista(l,imovelaux)
}
if scanner.Text() == "casa" {
var imovelaux Imovel
var residenciaaux Residencia
var casaaux Casa
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
residenciaaux.quartos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
residenciaaux.vagas, err = strconv.Atoi(scanner.Text())
scanner.Scan()
casaaux.numpavimentos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
casaaux.apavimento = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
residenciaaux.preco = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
casaaux.alivre = float32(floataux)
scanner.Scan()
casaaux.palivre, err = strconv.Atoi(scanner.Text())
//terminou de ler a casa
residenciaaux.residencia = &casaaux
imovelaux.imovel = &residenciaaux
l = insereLista(l,imovelaux)
}
if scanner.Text() == "triang" {
var imovelaux Imovel
var terrenoaux Terreno
var triang Triangular
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
triang.base = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
triang.altura = float32(floataux)
//terminou de ler o terreno triangular
terrenoaux.terreno = &triang
imovelaux.imovel = &terrenoaux
l = insereLista(l, imovelaux)
}
if scanner.Text() == "retang" {
var imovelaux Imovel
var terrenoaux Terreno
var retang Retangular
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
retang.lado1 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
retang.lado2 = float32(floataux)
//terminou de ler o terreno retangular
terrenoaux.terreno = &retang
imovelaux.imovel = &terrenoaux
l = insereLista(l, imovelaux)
}
if scanner.Text() == "trapez" {
var imovelaux Imovel
var terrenoaux Terreno
var trapez Trapezoidal
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.base1 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.base2 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.altura = float32(floataux)
//terminou de ler o terreno trapezoidal
terrenoaux.terreno = &trapez
imovelaux.imovel = &terrenoaux
l = insereLista(l, imovelaux)
}
case "e":
scanner.Scan()
i := 0
i, err =strconv.Atoi(scanner.Text())
l = removeLista(l, i)
case "a":
scanner.Scan()
if scanner.Text() == "apto" {
var imovelaux Imovel
var residenciaaux Residencia
var apartamentoaux Apartamento
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
residenciaaux.quartos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
residenciaaux.vagas, err = strconv.Atoi(scanner.Text())
scanner.Scan()
apartamentoaux.andar, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
apartamentoaux.aconstruida = float32(floataux)
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
residenciaaux.preco = float32(floataux)
scanner.Scan()
if scanner.Text() == "S" {apartamentoaux.alazer = 1.15}
if scanner.Text() == "N" {apartamentoaux.alazer = 1.0}
scanner.Scan()
apartamentoaux.totalandares, err = strconv.Atoi(scanner.Text())
//terminou de ler o apto
residenciaaux.residencia = &apartamentoaux
imovelaux.imovel = &residenciaaux
l = removeLista(l, imovelaux.identificador)
l = insereLista(l,imovelaux)
}
if scanner.Text() == "casa" {
var imovelaux Imovel
var residenciaaux Residencia
var casaaux Casa
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
residenciaaux.quartos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
residenciaaux.vagas, err = strconv.Atoi(scanner.Text())
scanner.Scan()
casaaux.numpavimentos, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
casaaux.apavimento = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
residenciaaux.preco = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
casaaux.alivre = float32(floataux)
scanner.Scan()
casaaux.palivre, err = strconv.Atoi(scanner.Text())
//terminou de ler a casa
residenciaaux.residencia = &casaaux
imovelaux.imovel = &residenciaaux
l = removeLista(l, imovelaux.identificador)
l = insereLista(l,imovelaux)
}
if scanner.Text() == "triang" {
var imovelaux Imovel
var terrenoaux Terreno
var triang Triangular
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
triang.base = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
triang.altura = float32(floataux)
//terminou de ler o terreno triangular
terrenoaux.terreno = &triang
imovelaux.imovel = &terrenoaux
l = removeLista(l, imovelaux.identificador)
l = insereLista(l, imovelaux)
}
if scanner.Text() == "retang" {
var imovelaux Imovel
var terrenoaux Terreno
var retang Retangular
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
retang.lado1 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
retang.lado2 = float32(floataux)
//terminou de ler o terreno retangular
terrenoaux.terreno = &retang
imovelaux.imovel = &terrenoaux
l = removeLista(l, imovelaux.identificador)
l = insereLista(l, imovelaux)
}
if scanner.Text() == "trapez" {
var imovelaux Imovel
var terrenoaux Terreno
var trapez Trapezoidal
scanner.Scan()
imovelaux.identificador, err = strconv.Atoi(scanner.Text())
scanner.Scan()
imovelaux.nome = scanner.Text()
scanner.Scan()
if scanner.Text() == "A" {terrenoaux.solo = 0.9}
if scanner.Text() == "G" {terrenoaux.solo = 1.3}
if scanner.Text() == "R" {terrenoaux.solo = 1.1}
scanner.Scan()
terrenoaux.preco, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.base1 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.base2 = float32(floataux)
scanner.Scan()
floataux, err = strconv.ParseFloat(scanner.Text(), 64)
trapez.altura = float32(floataux)
//terminou de ler o terreno trapezoidal
terrenoaux.terreno = &trapez
imovelaux.imovel = &terrenoaux
l = removeLista(l, imovelaux.identificador)
l = insereLista(l, imovelaux)
}
}
}
}
return l
}
func leespec(s Especificacao) Especificacao{//lê o arquivo espec.txt e salva informações
var floataux float64
file, err := os.Open("espec.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Scan()
s.perimocaro, err = strconv.Atoi(scanner.Text())
scanner.Scan()
s.permenarg, err = strconv.Atoi(scanner.Text())
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
s.alimite= float32(floataux)
scanner.Scan()
floataux, err = (strconv.ParseFloat(scanner.Text(), 64))
s.precolimite = float32(floataux)
scanner.Scan()
s.vi, err = strconv.Atoi(scanner.Text())
scanner.Scan()
s.vj, err = strconv.Atoi(scanner.Text())
scanner.Scan()
s.vk, err = strconv.Atoi(scanner.Text())
return s
}
<file_sep>package main
import (
"os"
"strconv"
)
type Lista struct{
imovel Imovel
proximo *Lista
}
func insereLista(l *Lista,i Imovel) *Lista{ //insere um elemenento novo na lista
var novo Lista
novo.imovel = i
novo.proximo = l
return &novo
}
func insereListaUltimo(l *Lista, i Imovel) *Lista{ //insere um elemento na ultima posição da lista
var novo Lista
var aux *Lista
novo.imovel = i
if l == nil {
return &novo
}
for aux = l; aux.proximo != nil; aux = aux.proximo{
}
aux.proximo = &novo
return l
}
func removeLista(l *Lista, ident int) *Lista{ //remove um elemento da lista
var aux *Lista
var aux2 *Lista
for aux = l; aux != nil; aux = aux.proximo{
if aux.imovel.identificador == ident {
//remove
if aux2 == nil { //caso seja o primeiro elemento da lista
return l.proximo
}
if aux.proximo == nil { //caso seja o ultimo elemento da lista
aux2.proximo = nil
return l
}
aux2.proximo = aux.proximo
return l
}
aux2 = aux
}
return l
}
func imprimeLista(l *Lista){ //imprime os elementos de uma lista num arquivo listaimpressa.txt (função para teste)
file, err := os.Create("listaimpressa.txt")
if err != nil {
return
}
defer file.Close()
var aux *Lista
for aux = l; aux != nil; aux = aux.proximo{
file.WriteString(strconv.FormatInt(int64(aux.imovel.identificador), 10))
file.WriteString(" - ")
file.WriteString(aux.imovel.nome)
file.WriteString(" - ")
file.WriteString(strconv.FormatFloat(float64(aux.imovel.imovel.defineTipoImovel()), 'f', 6, 64))
file.WriteString("\n")
}
}
func copiaLista(l *Lista) *Lista{//copia a lista, utilizada para salvar a lista original
var a *Lista
for aux:=l; aux != nil; aux = aux.proximo{
a = insereLista(a, aux.imovel)
}
return a
}
func criaListaImoveisCaros(l *Lista, a *Lista) *Lista{//cria lista organizada com os imoveis mais caros em ordem crescente
var tam int
for aux := l; aux != nil; aux = aux.proximo{
tam++
}
var menor float32
var atual float32
var aux2 *Lista
var aux *Lista
for i:=0; i < tam; i++{
menor = 0.0
atual = 0.0
for aux = l; aux !=nil; aux = aux.proximo{
atual = aux.imovel.imovel.defineTipoImovel()
if atual == menor{//caso seja igual
if aux.imovel.identificador < aux2.imovel.identificador{ //pega o com o menor identificador e seta como menor
menor = atual
aux2 = aux
}
}
if menor < atual{
menor = atual
aux2 = aux
}
}
a = insereListaUltimo(a, aux2.imovel)
l = removeLista(l, aux2.imovel.identificador)
}
return a
}
func pegaPorcListaCaros(a *Lista, s Especificacao) *Lista{//retorna lista dos imóveis mais caros em ordem crescente de preço, na quantidade especificada em spec.txt
var por float32
var tam int
var novalista *Lista
for aux := a; aux != nil; aux = aux.proximo{
tam++
}
por = float32(s.perimocaro)*float32(tam)/100.0
b := int(por)
i := 0
for aux := a; i < b; aux = aux.proximo{
novalista = insereLista(novalista, aux.imovel)
i++
}
return novalista
}
func listaMenoresTerrenosArgilosos(l *Lista, a *Lista) *Lista{//retorn lista com menores terrenos
var tam int
for aux := l; aux != nil; aux = aux.proximo{
if aux.imovel.imovel.getAreaTerreno() != 0 && aux.imovel.imovel.getTipoTerreno() == 1.3{tam++}
}
var menor float32
var atual float32
var aux2 *Lista
var aux *Lista
for i:=0; i < tam; i++{
menor = 0.0
atual = 0.0
for aux = l; aux !=nil; aux = aux.proximo{
if aux.imovel.imovel.getAreaTerreno() != 0 && aux.imovel.imovel.getTipoTerreno() == 1.3{
atual = aux.imovel.imovel.getAreaTerreno()
if atual == menor{//caso seja igual
if aux.imovel.identificador < aux2.imovel.identificador{//pega o com o menor identificador e seta como menor
menor = atual
aux2 = aux
}
}
if menor < atual{
menor = atual
aux2 = aux
}
}
}
a = insereLista(a, aux2.imovel)
l = removeLista(l, aux2.imovel.identificador)
}
return a
}
func pegaPorcListaMenores(a *Lista, s Especificacao) *Lista{//retorna lista do item b
var por float32
var tam int
var novalista *Lista
for aux := a; aux != nil; aux = aux.proximo{
tam++
}
por = float32(s.permenarg)*float32(tam)/100.0
b := int(por)
i := 0
for aux := a; i < b; aux = aux.proximo{
novalista = insereLista(novalista, aux.imovel)
i++
}
return novalista
}
func listaAreaCasa(l *Lista, a *Lista, s Especificacao) *Lista{//retorna lista do item c
var tam int
for aux := l; aux != nil; aux = aux.proximo{
if aux.imovel.imovel.getAreaCasa() > s.alimite && aux.imovel.imovel.defineTipoImovel() < s.precolimite{tam++}
}
var menor int
var atual int
var aux2 *Lista
var aux *Lista
for i:=0; i < tam; i++{
menor = 0
atual = 0
for aux = l; aux !=nil; aux = aux.proximo{
if aux.imovel.imovel.getAreaCasa() > s.alimite && aux.imovel.imovel.defineTipoImovel() < s.precolimite{
atual = aux.imovel.imovel.getNumeroQuartos()
if atual == menor{//caso seja igual
if aux.imovel.identificador > aux2.imovel.identificador{ //pega o com o menor identificador e seta como menor
menor = atual
aux2 = aux
}
}
if menor < atual{
menor = atual
aux2 = aux
}
}
}
a = insereListaUltimo(a, aux2.imovel)
l = removeLista(l, aux2.imovel.identificador)
}
return a
}
<file_sep>package main
import (
"os"
"strconv"
)
func result(a *Lista, b *Lista, c *Lista, s Especificacao){//gera o arquivo result.txt
file, err := os.Create("result.txt")
if err != nil {
return
}
defer file.Close()
var total int
var cont int
cont = 1
for aux:=a;aux != nil; aux = aux.proximo{
if cont == s.vi{
total = aux.imovel.identificador
}
cont++
}
cont = 1
for aux:=b;aux != nil; aux = aux.proximo{
if cont == s.vj{
total = total + aux.imovel.identificador
}
cont++
}
cont = 1
for aux:=c;aux != nil; aux = aux.proximo{
if cont == s.vk{
total = total + aux.imovel.identificador
}
cont++
}
file.WriteString(strconv.FormatInt(int64(total), 10))
}
func saida(a *Lista, b *Lista, c *Lista, s Especificacao){//gera o arquivo saida.txt
file, err := os.Create("saida.txt")
if err != nil {
return
}
defer file.Close()
for aux:=a;aux != nil; aux = aux.proximo{
if aux.proximo == nil{
file.WriteString(strconv.FormatInt(int64(aux.imovel.identificador), 10))
file.WriteString("\n")
break
}
file.WriteString(strconv.FormatInt(int64(aux.imovel.identificador), 10))
file.WriteString(", ")
}
for aux:=b;aux != nil; aux = aux.proximo{
if aux.proximo == nil{
file.WriteString(strconv.FormatInt(int64(aux.imovel.identificador), 10))
file.WriteString("\n")
break
}
file.WriteString(strconv.FormatInt(int64(aux.imovel.identificador), 10))
file.WriteString(", ")
}
for aux:=c;aux != nil; aux = aux.proximo{
if aux.proximo == nil{
file.WriteString(strconv.FormatInt(int64(aux.imovel.identificador), 10))
break
}
file.WriteString(strconv.FormatInt(int64(aux.imovel.identificador), 10))
file.WriteString(", ")
}
}
<file_sep>package main
type tipoImovel interface{
defineTipoImovel() float32 //calcula o preço do imovel
getAreaTerreno() float32 //caso seja 0 é um terreno, caso seja 1 é uma residência
getAreaCasa() float32 //retorna area da casa, caso imovel não seja casa retorna 0
getNumeroQuartos() int //retorna numero de quartos
getTipoTerreno() float32 //retorna o tipo do terreno de acordo com seu fator multiplicativo
}
type tipoTerreno interface{
areaTerreno() float32
}
type tipoResidencia interface{
infoResidencia() float32
infoResidenciaCasa() float32
areaCasa() float32
}
type Imovel struct{//Terreno e Residencia são tipoImovel
nome string
identificador int
imovel tipoImovel
}
type Terreno struct{//Retangular, Triangular, e Trapezoidal são terrenos tipoTerreno
preco int //preco m^2 terreno
solo float32
terreno tipoTerreno
//O fatorMultiplicativo varia de acordo com o tipo predominante de solo. Se o solo é
//arenoso, o fator multiplicativo é 0,9; se o solo é argiloso, é 1,3; e se o solo é rochoso, é
//1,1.
}
type Retangular struct{
lado1 float32
lado2 float32
}
type Triangular struct{
base float32
altura float32
}
type Trapezoidal struct{
base1 float32
base2 float32
altura float32
}
type Residencia struct{//Casa e Apartamento são tipoResidencia
quartos int
preco float32 //preco m^2 residencia
vagas int
residencia tipoResidencia
}
type Casa struct{
numpavimentos int
apavimento float32
alivre float32
palivre int
}
type Apartamento struct{
andar int
aconstruida float32
alazer float32 //será 1.15 caso tenha area de lazer e 1 caso não possua
totalandares int
}
type Especificacao struct{
perimocaro int
permenarg int
alimite float32
precolimite float32
vi int
vj int
vk int
}
func (t *Terreno) defineTipoImovel() float32 {
return (float32)(t.preco)*t.terreno.areaTerreno()*t.solo
}
func (t *Trapezoidal)areaTerreno() float32{
return t.altura*((t.base1+t.base2)/2.0)
}
func (t *Triangular)areaTerreno() float32{
return (t.base*t.altura)/2.0
}
func (r *Retangular)areaTerreno() float32{
return r.lado1*r.lado2
}
func (c *Casa)areaCasa() float32{
return c.apavimento*(float32)(c.numpavimentos)
}
func (a *Apartamento)areaCasa() float32{
return 0 //retorna 0 pois não é casa
}
func (r *Residencia) defineTipoImovel() float32 {
return r.preco*r.residencia.infoResidencia() + r.residencia.infoResidenciaCasa()
}
func (c *Casa)infoResidencia() float32{
return c.apavimento*(float32)(c.numpavimentos)
}
func (a *Apartamento)infoResidencia() float32{
return a.aconstruida*(0.9 + (float32)(a.andar)/(float32)(a.totalandares))*a.alazer
}
func (a *Apartamento)infoResidenciaCasa() float32{
return 0.0
}
func (c *Casa)infoResidenciaCasa() float32{
return (float32)(c.palivre)*c.alivre
}
func (t *Terreno) getAreaTerreno() float32 {
return t.terreno.areaTerreno()
}
func (r *Residencia) getAreaTerreno() float32 {
return 0 //retorna 0 pois não é terreno
}
func (t *Terreno) getAreaCasa() float32 {
return 0 //retorna - pois não é casa
}
func (r *Residencia) getAreaCasa() float32 {
return r.residencia.areaCasa()
}
func (t *Terreno) getNumeroQuartos() int {
return 0 //retorna - pois não é residencia
}
func (r *Residencia) getNumeroQuartos() int {
return r.quartos
}
func (r *Residencia) getTipoTerreno() float32 {
return 0 //não é um terreno
}
func (t *Terreno) getTipoTerreno() float32 {
return t.solo
}
func main() {
var l *Lista
var copia *Lista
var a *Lista
var b *Lista
var c *Lista
var spec Especificacao
l = lecatalogo(l)// leitura do arquivo catalogo.txt
l = leoperacoes(l)//leitura do arquivo de operaçoes a serem realizadas
spec = leespec(spec)//le as especificacoes
copia = copiaLista(l)//copia lista original
a = criaListaImoveisCaros(l,a)//cria lista ordenada com os imoveis mais caros
l = copiaLista(copia)//copia lista original
a = pegaPorcListaCaros(a, spec)//Lista dos imóveis mais caros em ordem crescente de preço, respeitando a quantidade especificada
b = listaMenoresTerrenosArgilosos(l, b)//lista dos terrenos com menor área
b = pegaPorcListaMenores(b, spec)//lista dos terrenos com menor área, respeitando a quantidade especificada
l = copiaLista(copia)//copia lista original
c = listaAreaCasa(l,c,spec)//lista do item c
result(a,b,c,spec)//imprime em arquivo result.txt o resultado
saida(a,b,c,spec)//imprime a saída em arquivo saida.txt
}
| 78ebd26ba85921b73793bc1c6c9d0a5092278cfc | [
"Markdown",
"Go"
] | 5 | Markdown | andremartinelli/Trabalho-LP-GO | bcf09e8f053b3138fc642f12ddb9c324670bed53 | cb74101efa368581feb8d79c7dfacb2b00ac8f39 |
refs/heads/master | <repo_name>prateek3189/react_assignment<file_sep>/src/components/userInfo/UserInfo.js
import React from 'react';
import './userInfo.css';
class UserInfo extends React.Component {
constructor(props) {
super(props);
this.handleEditBtn = this.handleEditBtn.bind(this);
}
handleEditBtn(e) {
this.props.editUserDetails(this.props.user, e.target.name);
}
render() {
var {user} = this.props;
return (
<article className="user-info">
<span style={{fontSize:'14px'}}>{user.name}</span>
<p style={{fontSize:'12px'}}> Address: {user.address.street} {user.address.suite}</p>
<p style={{fontSize:'12px'}}>{user.address.city}</p>
<p style={{fontSize:'12px'}}>{user.address.zipcode}</p>
<button name="edit" onClick={this.handleEditBtn}>Edit</button>
<button name="location" onClick={this.handleEditBtn}>Location</button>
</article>
)
}
}
export default UserInfo;
<file_sep>/src/pages/UserInfoPage.js
import React, {Component} from 'react';
import Header from '../components/header/Header';
import Footer from '../components/footer/Footer';
import UserList from '../components/aside/UserList';
import UserDetails from '../components/section/UserDetails';
const axios = require('axios');
class UserInfoPage extends React.Component {
constructor(props) {
super(props);
this.state = {
userData: [],
filteredData: [],
user: null,
eventName: ''
}
this.handleSearch = this.handleSearch.bind(this);
this.editUserDetails = this.editUserDetails.bind(this);
}
async componentDidMount() {
let response = await axios.get('https://jsonplaceholder.typicode.com/users')
.then(function (response) {
return response
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
this.setState({
userData: response.data,
filteredData: response.data
})
}
handleSearch(searchWord) {
let filteredData = this.state.userData.filter( element => {
return element.name.indexOf(searchWord) >= 0;
});
this.setState({filteredData});
}
editUserDetails(user, eventName) {
this.setState({user: user, eventName: eventName});
}
render() {
return (
<div className="container">
<Header />
<UserList userList={this.state.filteredData} handleSearch={this.handleSearch} editUserDetails={this.editUserDetails}/>
{
this.state.user ? (
<UserDetails userData={this.state.user} eventName={this.state.eventName}/>
) : (<div className="user-details"></div>)
}
<Footer />
</div>
);
}
}
export default UserInfoPage;<file_sep>/src/components/section/UserDetails.js
import React from 'react';
import "./user-details.css"
import { statement } from '@babel/template';
class UserDetails extends React.Component {
constructor(props) {
super(props);
console.log(this.props);
this.state={
name: this.props.userData.name,
userName: this.props.userData.username,
email: this.props.userData.email
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
console.log(this.state);
}
render() {
return (
<div className="user-details">
<form onSubmit={this.handleSubmit}>
<div className="input-field">
<label for="name">Name</label>
<input id="name" type="text" value={this.state.name} name="name" onChange={this.handleChange}/>
</div>
<div className="input-field">
<label for="userName">User Name </label>
<input id="userName" type="text" value={this.state.userName} name="userName" onChange={this.handleChange}/>
</div>
<div className="input-field">
<label for="emailAddress">Email</label>
<input id="emailAddress" type="email" value={this.state.email} name="email" onChange={this.handleChange}/>
</div>
<div>
<button type="submit">update</button>
</div>
</form>
</div>
)
}
}
export default UserDetails;
<file_sep>/src/components/aside/UserList.js
import React from 'react';
import UserInfo from '../userInfo/UserInfo';
import './user-list.css';
import UserSearch from '../search/UserSearch';
class UserList extends React.Component {
render() {
return (
<div className="user-list">
<UserSearch {...this.props}/>
{
this.props.userList && this.props.userList.length > 0 ? (
this.props.userList.map(element => {
return (
<UserInfo user={element} {...this.props} key={element.id}/>
)
})
): ''
}
</div>
)
}
}
export default UserList;
| f969aa1424619ee42e75c7fa7304af25e5d19742 | [
"JavaScript"
] | 4 | JavaScript | prateek3189/react_assignment | c4d24d3ec9850946e40890fb4118961a7139b414 | fdf48ced2b81f6d48f6f5ae1d93985de5867bab8 |
refs/heads/master | <file_sep>package View;
import Control.ControlCoffee;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Machine extends JFrame implements ActionListener {
private JPanel mainPanel;
private JLabel namePanel;
private JButton buttonCappuccino, buttonDecaf, buttonEspresso, buttonWhipped, buttonEnd;
public String nameCoffee;
ControlCoffee controlCoffee;
public Machine() {
mainPanel = new JPanel(new GridLayout(6, 1));
namePanel = new JLabel(" What kind of coffee do you want?");
showButtons();
this.add(mainPanel, BorderLayout.CENTER);
addButtons();
this.setTitle(" Coffee Machine! ^3^ ");
addActions();
this.setLocationRelativeTo(null);
this.setSize(280, 245);
this.setVisible(true);
}
/* Single responsability principle:
A class should have one, and only one, reason to change. */
public void addActions(){
buttonCappuccino.addActionListener(this);
buttonDecaf.addActionListener(this);
buttonEspresso.addActionListener(this);
buttonWhipped.addActionListener(this);
buttonEnd.addActionListener(this);
}
public void showButtons(){
buttonCappuccino = new JButton("Cappuccino");
buttonDecaf = new JButton("Decaf");
buttonEspresso = new JButton("Espresso");
buttonWhipped = new JButton("Whipped");
buttonEnd = new JButton("Finish");
}
public void addButtons(){
mainPanel.add(namePanel);
mainPanel.add(buttonCappuccino);
mainPanel.add(buttonDecaf);
mainPanel.add(buttonEspresso);
mainPanel.add(buttonWhipped);
mainPanel.add(buttonEnd);
}
public void attend(String nameCoffee){
controlCoffee = new ControlCoffee();
controlCoffee.setNameCoffee(nameCoffee);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonCappuccino)
{
nameCoffee = buttonCappuccino.getText();
}
if (e.getSource() == buttonDecaf)
{
nameCoffee = buttonDecaf.getText();
}
if (e.getSource() == buttonEspresso)
{
nameCoffee = buttonEspresso.getText();
}
if (e.getSource() == buttonWhipped)
{
nameCoffee = buttonWhipped.getText();
}
if (e.getSource() == buttonEnd)
{
Answer message = new Answer();
message.showMessage("Thanks for to run this program .^^. ");
System.exit(0);
}
this.setVisible(false);
attend(nameCoffee);
}
}
<file_sep>package Control;
import Model.Cappuccino;
import Model.Coffee;
import Model.Decaf;
import Model.Espresso;
import Model.Whipped;
import View.Answer;
public class ControlCoffee extends Coffee{
Answer anAnswer;
@Override
public void setNameCoffee(String nameCoffee) {
/* Preparing a coffee
It applies Dependency Inversion Principle:
It should depend on the most abstract, should not depend on the most concrete.
*/
Coffee objectCoffee = null;
super.setNameCoffee(nameCoffee);
prepare(objectCoffee);
}
public Coffee prepare(Coffee objectCoffee) {
/* It applies Polymorphism:
(1) Dynamic ligation: It relates the call of method at runtime.
*/
switch(getNameCoffee()){
case "Cappuccino":
objectCoffee = new Cappuccino();
break;
case "Decaf":
objectCoffee = new Decaf();
break;
case "Espresso":
objectCoffee = new Espresso();
break;
case "Whipped":
objectCoffee = new Whipped();
break;
}
/* - It applied Liskov substitution principle (created by <NAME>)
This coffee class is extended, because is important creating the derivated classes so, They can be handled like the base class.
*/
objectCoffee.setNameCoffee(getNameCoffee());
if(objectCoffee!=null)
{
answer(objectCoffee.getNameCoffee());
}
return objectCoffee;
}
@Override
public void addCoffee() {
}
public void answer(String nameCoffee){
anAnswer = new Answer();
anAnswer.showMessage("Your "+nameCoffee+" coffee is ready!");
answer();
}
/*
Polymorphism
(3) Overload or ad-hoc:
Capacity to define several functions using the same name with different parameters (in the same class)
*/
public void answer(){
String answerCustomer;
answerCustomer = anAnswer.showQuestion(" Do you want another cup of coffee? ");
if( answerCustomer.equals("Yes!")){
Customer.order();
}else{
anAnswer.showMessage("Thanks for to run this program .^^. ");
System.exit(0);
}
}
@Override
public Coffee prepare() {
return null;
}
}
<file_sep>import random
from random import sample
def Contar(mazo,iterador,contador):
if iterador != len(mazo):
return Contar(mazo,iterador+1,ValorCarta(mazo[iterador],contador))
else:
return contador
#Opcional
def ImprimirMazos(mazoCasa, mazoJugador):
print "Mazo de la Casa"
print mazoCasa
print "Mazo del Jugador"
print mazoJugador
print "\n"
return None
def RepartirInicio(mazoJugador, mazoCasa, mazo):
mazoCasa.append(mazo[0])
mazoJugador.append(mazo[1])
mazoJugador.append(mazo[2])
for i in range(3):
mazo.remove(mazo[0])
ImprimirMazos(mazoCasa, mazoJugador)
if Contar(mazoJugador,0,0)>21:
for i in range(0,len(mazoJugador)):
if (mazoJugador[i])[0] == 'A':
mazoJugador.append(['a',(mazoJugador[i])[1]])
mazoJugador.pop(i)
break
if raw_input("Presione 1 para seguir jugando ").strip() == '1':
return Repartir(mazoCasa, mazoJugador, mazo, 1)
else:
return Repartir(mazoCasa, mazoJugador, mazo, 2)
def Repartir(mazoCasa, mazoJugador, mazo, turno):
if turno==1:
mazoJugador.append(mazo[0])
mazo.remove(mazo[0])
ImprimirMazos(mazoCasa, mazoJugador)
if Contar(mazoJugador,0,0)>21:
for i in range(0,len(mazoJugador)):
if (mazoJugador[i])[0] == 'A':
mazoJugador.append(['a',(mazoJugador[i])[1]])
mazoJugador.pop(i)
break
if Contar(mazoJugador,0,0)>21:
print "GAME OVER"
elif raw_input("Presione 1 para seguir jugando ").strip() == '1':
return Repartir(mazoCasa, mazoJugador, mazo, 1)
else:
return Repartir(mazoCasa, mazoJugador, mazo, 2)
if turno==2:
mazoCasa.append(mazo[0])
mazo.remove(mazo[0])
ImprimirMazos(mazoCasa, mazoJugador)
if Contar(mazoCasa,0,0)>21:
for i in range(0,len(mazoCasa)):
if (mazoCasa[i])[0] == 'A':
mazoCasa.append(['a',(mazoCasa[i])[1]])
mazoCasa.pop(i)
break
if Contar(mazoCasa,0,0)>21:
print "GANASTE"
elif Contar(mazoCasa,0,0) > Contar(mazoJugador,0,0):
print "GAME OVER"
elif Contar(mazoCasa,0,0) == Contar(mazoJugador,0,0):
if DetColor(mazoCasa, 0, 0) < DetColor(mazoJugador, 0, 0):
print "Gana el jugador!"
else:
print "Gana la casa"
else:
return Repartir(mazoCasa, mazoJugador, mazo, 2)
def CrearMazo():
return sample([(x,y) for x in ['A','J','Q','K']+list(range(2,11)) for y in ['Picas','Treboles','Diamantes','Corazones']],52)
def Jugar(mazo):
if mazo!=[]:
print "\n"
return RepartirInicio([], [], mazo)
def ValorCarta(carta,contador):
if carta[0] == 'J' or carta[0] == 'K' or carta[0] == 'Q':
return 10+contador
elif carta[0] == 'A':
return 11+contador
elif carta[0] == 'a':
return 1+contador
else:
return carta[0]+contador
#Determinar color (mazoCasa, mazoJugador, 0)
def DetColor(mazo, iterador, contador):
if iterador != len(mazo):
if (mazo[iterador])[1] == 'Corazones' or (mazo[iterador])[1] == 'Diamantes':
return DetColor(mazo, iterador+1, contador+1)
else:
return DetColor(mazo, iterador+1, contador)
else:
return contador
while True:
Jugar(CrearMazo())
if raw_input("Volver a jugar presiona Y:").strip() != 'Y':
break
<file_sep># Modelos de Programación II
Juego 21: Black Jack con Programación sin estados, elaborado en la versión 2.7 de Python.
Estudiantes:
<NAME> (código académico: 2015202095)
<NAME> (código académico: 20151020019)
<NAME> (código académico: 20151020046)
Docente: Ing. <NAME>
<file_sep># Juego en JavaScript y HTML con estilos en CSS
Modelos de Programación II.
Presentado por:
<NAME> (código académico: 2015202095)
<NAME> (código académico: 20151020019)
<NAME> (código académico: 20152020046)
<file_sep>package Model;
public class Espresso extends Coffee {
@Override
public Coffee prepare() {
addCoffee();
addWater();
return this;
}
@Override
public void addCoffee() {
}
}<file_sep>$(document).ready(inicio);
$(document).keydown(manejar_evento);
var puntos = 0;
function inicio() {
/* Identificador del Canvas (lienzo) */
lienzo = $("#lienzo")[0];
contexto = lienzo.getContext("2d");
/* Definiendo un buffer */
buffer = document.createElement("canvas");
/* Javascript no es orientado a objetos propiamente */
mono = new Mono();
animar();
}
function animar() {
buffer.width = lienzo.width;
buffer.height = lienzo.height;
contextoBuffer = buffer.getContext("2d");
// contexto para el barril
contextoBufferBarril = buffer.getContext("2d");
contextoBuffer.clearRect(0, 0, buffer.width, buffer.height);
contextoBufferBarril.clearRect(0, 0, buffer.width, buffer.height)
mono.dibujar(contextoBuffer);
//mono.dibujarBarril(contextoBuffer);
mono.dibujarBarril(contextoBufferBarril);
mono.mover_Barril();
contexto.clearRect(0, 0, lienzo.width, lienzo.height);
/* Buffer como si fuera una imagen*/
contexto.drawImage(buffer, 0, 0);
setTimeout("animar()", 50);
}
function manejar_evento(event) {
//alert(typeof event.which + event.which);
if (event.which == 37) {
mono.mover_Mono("izquierda");
}
if (event.which == 39) {
mono.mover_Mono("derecha");
}
}
function valorAbs(num) {
if (num < 0) {
return num * -1;
} else {
return num;
}
}
function detectar_Colision(x, y, xBarril, yBarril) {
xBarril = parseInt(xBarril);
//console.log(x,y,xBarril,yBarril, valorAbs(x-xBarril));
/* 96 es la mitad de la altura del barril.
111 es aprox la mitad de la anchura del barril
Para que los codos del mono también generen una colision xD
*/
if (valorAbs(x - xBarril) <= 141 && valorAbs(y - yBarril) <= 96) {
alert('Game over!\n Para jugar de nuevo, por favor recargue la página.');
}
}
function Mono() {
this.x = 700;
this.y = 600;
this.xBarril = null;
this.yBarril = 0;
this.spriteBarril = 0;
this.spriteMono = 0;
/* Signo pesos, propio de Jquery, los maneja como arreglos */
this.img = [$("#mono1")[0],$("#mono1")[0],$("#mono1")[0],$("#mono1")[0] , $("#mono2")[0],$("#mono2")[0],$("#mono2")[0],$("#mono2")[0]];
this.imgBarril = [$("#barril1")[0],$("#barril2")[0]];
/* ctx: contexto*/
this.dibujarBarril = function(ctxBarril) {
ctxBarril.drawImage(this.imgBarril[this.spriteBarril], this.xBarril, this.yBarril);
}
this.dibujar = function(ctx) {
ctx.drawImage(this.img[this.spriteMono], this.x, this.y);
}
this.mover_Barril = function() {
if (this.xBarril == null) {
objpunto = document.getElementById("punto");
objpunto.innerHTML = "Puntos: " + puntos;
this.xBarril = Math.random() * (1500);
}
if (this.yBarril < 800) {
detectar_Colision(this.x, this.y, this.xBarril, this.yBarril);
this.yBarril += 25;
} else {
this.xBarril = Math.random() * (1500);
detectar_Colision(this.x, this.y, this.xBarril, this.yBarril);
this.yBarril = 0;
puntos = puntos + 1;
console.log(puntos);
objpunto = document.getElementById("punto");
objpunto.innerHTML = "Puntos: " + puntos;
}
// para darle al mono un movimiento de agitacion
this.spriteBarril = (this.spriteBarril + 1) % 2;
this.spriteMono = (this.spriteMono + 1 ) % 8;
}
this.mover_Mono = function(accion) {
if (accion == "derecha") {
if (this.x < 1500) {
this.x += 40;
}
} else if (accion == "izquierda") {
if (this.x > 0) {
this.x -= 40;
}
}
}
detectar_Colision(this.x, this.y, this.xBarril, this.yBarril);
}
/*
¿Como detectar colisiones?
Barriles que caen de arriba king kong parte de abajo,
se puede mover a der y a izq si el barril cae al piso hay punto
si lo toca un barril se muere.*/
<file_sep>package Model;
public abstract class Coffee{
/* - Open/Close principle:
You should be able to extend a classes behavior, without modyfing it.
If the client implements a new type of coffee, then you can create it as a new class, which inherits of Coffee class.
*/
private String nameCoffee;
public String getNameCoffee() {
return nameCoffee;
}
public void setNameCoffee(String nameCoffee) {
this.nameCoffee = nameCoffee;
}
public void addSugar(){
}
public void addMilk(){
}
public void addMilkCream(){
}
public void addWater(){
}
public abstract Coffee prepare();
public abstract void addCoffee();
}
<file_sep>#!/usr/bin/python
import random
from random import*
def mazo():
return sample([(x,y) for x in ['A','J','Q','K']+list(range(2,11)) for y in ['picas','treboles','diamantes','corazones']],52)
def inicio(mazo,numero):
if mazo != [] and numero == 2:
print "casa"
print mazo[0]
print "Jugador"
print mazo[1]
print mazo[2]
if contarMazo(mazo,numero,0) > 21:
print "GAME OVER"
elif raw_input("1 para pedir, de lo contrario digite otra tecla")== '1':
print mazo[numero+1]
return inicio(mazo,numero+1)
else:
for i in range(0,numero):
mazo.pop(1)
jugarCasa(mazo,contarMazo(mazo,numero,0),0)
def jugarCasa(mazo,numeroJugador,contador):
if contador == 0:
print "mazo de casa"
print mazo[contador]
print mazo[contador+1]
return jugarCasa(mazo,numeroJugador,contador+2)
if contarMazo(mazo,contador,-1) >= numeroJugador and 21 >= contarMazo(mazo,contador,-1):
print mazo[contador]
print "GAME OVER"
elif contarMazo(mazo,contador,-1) > 21 :
print mazo[contador]
print "GANASTE!!!"
else:
return jugarCasa(mazo,numeroJugador,contador+1)
def comprobarA(mazo, numero, contador):
if (contador+10)<=21:
print "Retorno 11"
return contarMazo(mazo,numero-1,11+contador)
else:
print "Retorno 1"
return contarMazo(mazo,numero-1,1+contador)
def contarMazo(mazo,numero,contador):
if contador != -1:
if numero != 0:
if (mazo[numero])[0] == 'J' or (mazo[numero])[0] == 'Q' or (mazo[numero])[0] == 'K':
return contarMazo(mazo,numero-1,10+contador)
elif (mazo[numero])[0] == 'A':
return comprobarA(mazo,numero,contador)
for i in range(2,11):
if i == (mazo[numero])[0]:
return contarMazo(mazo,numero-1,i+contador)
else:
return contador
else:
if numero != -1:
if (mazo[numero])[0] == 'J' or (mazo[numero])[0] == 'Q' or (mazo[numero])[0] == 'K':
return contarMazo(mazo,numero-1,10+contador)
elif (mazo[numero])[0] == 'A':
return contarMazo(mazo,numero-1,11+contador)
for i in range(2,11):
if i == (mazo[numero])[0]:
return contarMazo(mazo,numero-1,i+contador)
else:
return contador+1
while True:
inicio(mazo(),2)
if raw_input("Volver a jugar:").strip() != 'Y':
break
<file_sep>package Model;
/* Whipped = batido */
public class Whipped extends Coffee{
@Override
public Coffee prepare() {
addMilk();
addCoffee();
addSugar();
addWater();
return this;
}
@Override
public void addCoffee() {
}
} | 794a74f82321f30bd752798c2f4ec1e56ae4afc1 | [
"Markdown",
"Java",
"Python",
"JavaScript"
] | 10 | Java | LeidyAldana/Modelos_de_Programacion_II | f1960db879fa707a064b1d3af9dcae213836adf1 | e6268280886a04e155996f9b48ecb831b238b1ee |
refs/heads/master | <repo_name>balykin/sh_jobs<file_sep>/clone_repo.py
#!/usr/bin/python2.7
import os
import subprocess
import requests
######################################Clone Client Repo###################################
reponame = raw_input("Enter the full name of git repository: ")
print(reponame)
#directory=reponame.strip('<EMAIL>:someRepoOwnerrr/')
directory=reponame[15:]
pwd=os.getcwd()
pipe=subprocess.Popen(['git', 'clone', str(reponame), str(pwd +'/'+ directory)])
pipe.wait()
os.chdir(directory)
print('master is cloned to ' + os.getcwd())
def getnamebrances():
proc = subprocess.Popen(['git', 'branch', '-a'],stdout=subprocess.PIPE)
text = proc.communicate()[0].decode('utf-8')
branches = []
counter = 0
for i in text.splitlines():
counter += 1
# if counter>2:
branches.append(i[17:])
return branches
branchList=getnamebrances()
print('total branches = ' + str(len(branchList)))
for branch in branchList:
pipe=subprocess.Popen(['git', 'checkout', '-b', branch, str('origin/'+ branch) ])
pipe.wait()
######################################Create a new Repo####################################
params = (
('access_token', 'put_your_tocken_here'),
)
#data = '{"name":"test-public-site.git", "private":"true"}'
data = '{"name":"'+ directory +'", "private":"true"}'
response = requests.post('https://api.github.com/user/repos', params=params, data=data)
print(list(response))
######################################Push to new Repo#####################################
newOrigin = directory.replace("/","-")
pipe=subprocess.Popen(['git', 'remote', 'rename', 'origin', 'old_origin'])
pipe.wait()
pipe=subprocess.Popen(['git', 'remote', 'add', 'origin', '<EMAIL>:someRepoOwnerrr/'+str(newOrigin)])
pipe.wait()
pipe=subprocess.Popen(['git', 'remote', 'remove', 'old_origin'])
pipe.wait()
pipe=subprocess.Popen(['git', 'remote', '-v'])
print('current is '+'<EMAIL>:someRepoOwnerrr/'+str(newOrigin))
pipe=subprocess.Popen(['git', 'push', '-u', 'origin', '--all'])
pipe.wait()
<file_sep>/14days_cleaner.sh
#!/bin/bash
sudo find /opt/backup_allVM/ -name "*.*" -mtime +14 -exec rm -Rf {} \;
#Script runs by cron and allow to keep vmdumps not older then 14 days in /var/lib/vz/dump/ in local server
| 7b59529c3cf54497d61980c849805543c80e4d1d | [
"Python",
"Shell"
] | 2 | Python | balykin/sh_jobs | b9926f55a21099954a31dc0668a60e0c7aa4069a | a18325759455ca110a1544f5855069d5c8178681 |
refs/heads/main | <repo_name>markytpa/j2w-lekce03-priklad01<file_sep>/src/main/java/cz/czechitas/java2webapps/lekce3/controller/CardController.java
package cz.czechitas.java2webapps.lekce3.controller;
import cz.czechitas.java2webapps.lekce3.entity.Address;
import cz.czechitas.java2webapps.lekce3.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.time.LocalDate;
@Controller
public class CardController {
@GetMapping("/")
public ModelAndView karticka() {
ModelAndView result = new ModelAndView("card");
result.addObject("person", new Person("Jan", "Palach", LocalDate.of(1948, 8, 11)));
result.addObject("address", new Address("Smetanova 337", "Všetaty", "27716"));
return result;
}
}
| 435f28e17d6c055dae1d0cb025bab91c29ba9a44 | [
"Java"
] | 1 | Java | markytpa/j2w-lekce03-priklad01 | 81d3caeb228d567ed18e7da8201842cc0b7300ce | 9ae6d070136a2cd7184eb9d7a4a7237aa85fd5ef |
refs/heads/master | <file_sep>package Server;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
public class Server extends Thread
{
private Hashtable<String, String> usridPwdMap = new Hashtable<String,String>();
private String Username;
private ServerUI sui;
private TPA tpa;
private Socket serverSocket;
/**
* The data data block size in bytes that would be size of chunks of data in the file that would be
* considered for Parity bytes generation and Error correction
*/
public static final int DATABLOCK_SIZE = 100;
/**
* The size of parity bytes. This size decide how much errors bytes in a data block can be corrected.
*/
public static final int PARITYBYTES_SIZE = 50;
public static class OnlyExt implements FilenameFilter
{
String ext;
public OnlyExt(String ext)
{
this.ext = "." + ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext);
}
}
Server()
{
usridPwdMap.put("admin", "admin");
usridPwdMap.put("student", "student");
}
Server(Socket Connection, ServerUI psui, TPA ptpa)
{
usridPwdMap.put("admin", "admin");
usridPwdMap.put("student", "student");
serverSocket = Connection;
this.sui = psui;
this.tpa = ptpa;
}
/**
* Called on a new client connection to the server. Handles the communication with a client on a given connection.
*/
public void run()
{
String clientRequestCMD;
String Response = "";
String RequestType;
String delimiter = "\\|";
String[] clientRequestCMDTokens;
RSA rsa = new RSA();
try
{
//InputStream to read data from the client in binary format
InputStream inputFromClientStream= serverSocket.getInputStream();
//Reader to read data from the client in character format
Reader inputFromClientReader = new InputStreamReader(inputFromClientStream);
//OutputStream to write data to the client in binary format
DataOutputStream outToClientStream = new DataOutputStream(serverSocket.getOutputStream());
while(true)
{
//try to read initial data in character format. Line at a time. Using the Reader
String commandTxt=CommProtocolHelper.readLineFromStream(inputFromClientStream);
clientRequestCMD = rsa.decrypt(commandTxt);
System.out.println("\nRequest : " + clientRequestCMD);
clientRequestCMDTokens = clientRequestCMD.split(delimiter);
RequestType = clientRequestCMDTokens[0];
if(RequestType.equalsIgnoreCase("LOGIN"))
{
/* Login command.
* Protocol
* LOGIN|<username>|<password>
*/
System.out.println(" CMD:LOGIN"+clientRequestCMDTokens[1]);
if(loginValidation(clientRequestCMDTokens[1], clientRequestCMDTokens[2]))
{
//if login successful, create a directory on server for the user (if not already there)
File file=new File(clientRequestCMDTokens[1]);
if(!file.exists())
file.mkdir();
file=new File(clientRequestCMDTokens[1]+"/.rs");
if(!file.exists())
file.mkdir();
//LoadFiles();
Response = new String("SUCCESSFUL");
}
else
Response = new String("FAILED");
}
else if(RequestType.equalsIgnoreCase("UPLOAD"))
{
/* Upload file command.
* Protocol
* UPLOAD|<filename>|<filesize>
* <file data continues in next line. The byte count should match the file size indicate in the command statement above>
*/
FileOutputStream fileErasureOutstream=null;
FileOutputStream fileDataOutstream=null;
try{
//Create a file output stream to write to a file on server side using data coming from client (save file on server)
fileDataOutstream = new FileOutputStream(getUserDirectoryPath(clientRequestCMDTokens[1]));
//Create a file output stream to write to a file erasure data (erasure data has to parity bytes as per ReedSolomon)
fileErasureOutstream = new FileOutputStream(getUserDirectoryErasurePath(clientRequestCMDTokens[1]+".rs"));
ReedSolomon rs=new ReedSolomon(Server.PARITYBYTES_SIZE);
// Read data from the Client and write to the local file on the server
// The amount of data read from the client is based on the data size indicated by the
// client in its UPLOAD command. The file name and file byte size is given in the command
int dataSize=Integer.parseInt(clientRequestCMDTokens[2]);
int dataRead=0;
byte[] buff=new byte[Server.DATABLOCK_SIZE]; //buffer for the data chunk read off the client input socket stream
byte[] erasureBuff = new byte[rs.NPAR];//buffer for erasure/parity data calculated for the fle data chunk
System.out.println(" CMD: UPLOAD file:"+ clientRequestCMDTokens[1] + " Size:" + dataSize + " available " + inputFromClientStream.available() + "\n Uploading...");
while(dataRead<dataSize){
int bytesRead;
bytesRead=CommProtocolHelper.readBinary(inputFromClientStream, buff, Math.min(buff.length, (dataSize-dataRead)));
fileDataOutstream.write(buff,0,bytesRead);
//get the erasure data for the file data part
erasureBuff=rs.getErasure(buff, Server.DATABLOCK_SIZE);
fileErasureOutstream.write(erasureBuff);
dataRead=dataRead+bytesRead;
System.out.print(dataRead + " .. ");
}
System.out.println("Done");
Response = new String("SUCCESSFUL");
}
catch(Exception ex)
{
Response = "FAILED|" + ex.getMessage()+ ex.toString();
System.out.println("CMD: UPLOAD. Error: " + ex.getMessage());
ex.printStackTrace();
}
finally{
if(fileDataOutstream!=null)
fileDataOutstream.close();
if(fileErasureOutstream!=null)
fileErasureOutstream.close();
}
}
else if(RequestType.equalsIgnoreCase("DOWNLOAD"))
{
/* Download file command.
* Request Protocol
* DOWNLOAD|<filename>
* Response Protocol
* CONTENT-SIZE|<filesize>
* <file data content ...>
* SUCCESSFUL
*/
int bytesRead=0;
byte[] buff=new byte[1000]; //buffer for the data chunk read off the client input socket stream
FileInputStream fileInputStream = null;
try
{
File fileRequested=new File(getUserDirectoryPath(clientRequestCMDTokens[1]));
//Send content size of the file. This required for the client to know the end of file data on the stream
//Client is expected to assume end of file, after reading the indicated content size
Response = new String("CONTENT-LENGTH|") + fileRequested.length();
CommProtocolHelper.writeCommand(outToClientStream, Response);
System.out.println(Response+" sending file data...");
//Start writing file content to the client
fileInputStream = new FileInputStream(getUserDirectoryPath(clientRequestCMDTokens[1]));
int totalBytesSent=0;
while((bytesRead=fileInputStream.read(buff, 0, buff.length))>0){
outToClientStream.write(buff,0,bytesRead);
totalBytesSent+=bytesRead;
System.out.print(totalBytesSent + " .. ");
}
System.out.println("Done");
System.out.println("File " +clientRequestCMDTokens[1] + " downloaded to Client");
Response = new String("SUCCESSFUL");
}
catch(Exception ex)
{
Response = "FAILED|" + ex.getMessage() + ex.toString();
System.out.println("CMD: DOWNLOAD. Error: " + ex.getMessage());
ex.printStackTrace();
}
finally{
if(fileInputStream!=null)
fileInputStream.close();
}
}
else if(RequestType.equalsIgnoreCase("DELETE"))
{
try{
File f1 = new File(getUserDirectoryPath(clientRequestCMDTokens[1]));
boolean success = f1.delete();
if (!success)
Response = "FAILED";
else
Response = "SUCCESSFUL";
//delete the erasure file
f1= new File(getUserDirectoryErasurePath(clientRequestCMDTokens[1]+".rs"));
success = f1.delete();
}
catch(Exception ex){
ex.printStackTrace();
Response ="FAILED|"+ex.getMessage() + ex.toString();
}
}
else if(RequestType.equalsIgnoreCase("GETFILENAMES"))
{
try{
File file = new File(getUserDirectoryPath(""));
//FilenameFilter textFiles = new Server.OnlyExt("txt");
File Files[] = file.listFiles(); //textFiles);
Response = "FILES|";
for(int i = 0; i < Files.length; i++)
{
if(Files[i].isDirectory())
continue;
Response = Response + Files[i].getName();
if(i == Files.length - 1)
break;
Response = Response + "|";
}
}
catch(Exception ex){
ex.printStackTrace();
Response ="FAILED|"+ex.getMessage() + ex.toString();
}
}
else if(RequestType.equalsIgnoreCase("VERIFY"))
{
try{
tpa.setTextArea("Received request to verify file " + clientRequestCMDTokens[1] + " for user " + getUsername() + "\n");
boolean hasErrors=verifyAndCorrectFile(clientRequestCMDTokens[1]);
if (hasErrors)
{
Response = "FILE CORRECTED";
tpa.setTextArea("File " + clientRequestCMDTokens[1] + " was corrected and recovered successfully" + "\n");
}
else
{
tpa.setTextArea("No errors were found in the file " + clientRequestCMDTokens[1] + "\n");
Response = "FILE OK";
}
}
catch(Exception ex){
ex.printStackTrace();
Response ="FAILED|"+ex.getMessage() + ex.toString();
}
}
else if(RequestType.equalsIgnoreCase("LOGOFF"))
{
inputFromClientReader.close();
outToClientStream.close();
serverSocket.close();
this.stop();
}
System.out.println("Response : " + Response);
//flush any more data on the input communication stream
CommProtocolHelper.flushInputStream(inputFromClientStream);
//Write Command response
CommProtocolHelper.writeCommand(outToClientStream, Response);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
String getUsername()
{
return Username;
}
String getUserDirectoryPath(String Filename)
{
return Username + "\\" + Filename;
}
String getUserDirectoryErasurePath(String Filename)
{
return Username + "\\.rs\\" + Filename;
}
boolean loginValidation(String Username, String Password)
{
String HashtablePassword;
if (usridPwdMap.get(Username.toLowerCase()) != null)
{
HashtablePassword = usridPwdMap.get(Username.toLowerCase()).toString();
if(Password.equalsIgnoreCase(HashtablePassword))
{
this.Username = Username;
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
/**
* Load files in the user directory. Here user directory is same name as the username on the
* server file system. Only files with extension txt is listed.
*/
/* public void LoadFiles()
{
File userDirectory = new File(getUsername());
FileInputStream fileInputStream = null;
FilenameFilter textFilesFilter = new Server.OnlyExt("txt");
File Files[] = userDirectory.listFiles(textFilesFilter);
//Iterate through each file in the user directory
for(File file: Files)
{
int ch;
StringBuffer strContent = new StringBuffer("");
try
{
fileInputStream = new FileInputStream(file);
while ((ch = fileInputStream.read()) != -1)
strContent.append((char) ch);
fileInputStream.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}*/
/**
* Verify contents of file using it erasure data (.rs file). If errors are found,
* a recovery is attempted and wherever possible the recovered/corrected data is
* written to the file. This is done by using a temp file, which is later overwritten
* on the original file on recovery.
*
*/
public boolean verifyAndCorrectFile(String Filename) throws IOException
{
FileOutputStream verifiedDataFileInputStream =null;
FileInputStream fileDataInputStream = null;
FileInputStream fileErasureInputStream =null;
boolean errorsFound=false;
try{
//Create a file output stream to write corrected data, temperory file
verifiedDataFileInputStream = new FileOutputStream(getUserDirectoryPath(Filename)+".tmp");
//Create a file Input stream to read current file data
fileDataInputStream = new FileInputStream(getUserDirectoryPath(Filename));
//Create a file Input stream to read erasure data (erasure data is the parity bytes as per ReedSolomon)
fileErasureInputStream = new FileInputStream(getUserDirectoryErasurePath(Filename+".rs"));
ReedSolomon rs=new ReedSolomon(Server.PARITYBYTES_SIZE);
// Read data from the Current data file, and the corresponding erasure file and output verified / corrected data to a tmp file
int dataRead=0;
byte[] buff=new byte[Server.DATABLOCK_SIZE]; //buffer for the data chunk read off the Original file
byte[] verifiedCorrectedDataBuff;//buffer for the verified & corrected data
byte[] erasureBuff = new byte[rs.NPAR];//buffer for erasure/parity data calculated for the fle data chunk
System.out.println(" Verifying and Correcting: file:"+ Filename +"\n Verifying ...");
while(true){
int bytesRead=fileDataInputStream.read(buff, 0, buff.length);
fileErasureInputStream.read(erasureBuff,0,Server.PARITYBYTES_SIZE);
if(bytesRead<0) break;
if(rs.checkIfErrorInData(buff, Server.DATABLOCK_SIZE, erasureBuff)){
errorsFound=true;
//when error in data, call correction mechanism
System.out.println("Found Error in...\n\t" + new String(buff));
verifiedCorrectedDataBuff=rs.getErrorCorrected(buff, Server.DATABLOCK_SIZE, erasureBuff);
System.out.println("corrected as...\n\t" + new String(verifiedCorrectedDataBuff));
}else{
verifiedCorrectedDataBuff=buff;//user original data if found without errors
}
verifiedDataFileInputStream.write(verifiedCorrectedDataBuff,0,bytesRead);
dataRead=dataRead+bytesRead;
System.out.print(dataRead + " .. ");
}
System.out.println("Done");
//Close all files
fileDataInputStream.close();fileDataInputStream=null;
fileErasureInputStream.close();fileErasureInputStream=null;
verifiedDataFileInputStream.close();verifiedDataFileInputStream=null;
if(errorsFound){
//If errors found, overwrite the current file with the error corrected file
//Delete the original file
boolean success=new File(getUserDirectoryPath(Filename)).delete();
System.out.println("File "+getUserDirectoryPath(Filename)+ " deleted?" + success);
//Make the corrected file as original file name
success=new File(getUserDirectoryPath(Filename)+".tmp").renameTo(new File(getUserDirectoryPath(Filename)));
System.out.println(" Original file " + getUserDirectoryPath(Filename) + " overwritten with corrected file?" +success);
}else{
new File(getUserDirectoryPath(Filename)+".tmp").delete();
}
return errorsFound;
}
catch(Exception ex)
{
if(fileDataInputStream!=null)
fileDataInputStream.close();
if(fileErasureInputStream!=null)
fileErasureInputStream.close();
if(verifiedDataFileInputStream!=null)
verifiedDataFileInputStream.close();
System.out.println("Verify Error: " + ex.getMessage()+ ex.toString());
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public static void main(String argv[]) throws Exception
{
//Server server = new Server();
ServerSocket serverSocket = new ServerSocket(8888);
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
ServerUI serverWindow = new ServerUI();
serverWindow.setVisible(true);
TPA tpaWindow = new TPA();
tpaWindow.setVisible(true);
tpaWindow.setLocation(637,0);
while(true)
{
Socket connectionSocket = serverSocket.accept();
//Create a new server client Socket communication handler
Server server = new Server(connectionSocket, serverWindow, tpaWindow);
server.start();
}
}
}<file_sep>package Server.Common;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
/**
* Helper class with utility method for the Handling Communication between client and sever
*
*/
public class CommProtocolHelper {
private static RSA rsa=new RSA();
/**
* Reads a line from the input stream. The stream is assumed to be a binary stream.
* Character reading till newline
* @param inStream
* @return the data string read
* @throws IOException
*/
public static String readLineFromStream(InputStream inStream) throws IOException{
StringBuffer dataLine=new StringBuffer();
Reader inputReader= new InputStreamReader(inStream);//Convert to character stream
char c[]=new char[1];
while(inputReader.read(c)>0){
if((c[0]=='\n' || c[0]=='\r'))
break;
dataLine.append(c[0]);
//System.out.print(c[0]);
}
return dataLine.toString();
}
/**
* Remove all data in the Stream. Used when resetting communication streams for next
* communication. Used at both Client and Server on the socket input streams before
* executing the next command (Client) or waiting for next command (Server)
* @throws IOException
*/
public static void flushInputStream(InputStream inputStreamToFlush) throws IOException{
// int bytesToFlushed=0;
// while(inputStreamToFlush.available()>0){
// System.out.println((byte)inputStreamToFlush.read());
// bytesToFlushed++;
// }
// System.out.println(" Flushed " + bytesToFlushed);
}
/**
* Writes a command on the communication stream. Encrypts the command, adds a new line0
* at the end command, as the delimiter. The delimiter is not encrypted.
* @param outCommStream the output communication stream to write to (of type DataOutputStream)
* @return
* @throws IOException
*/
public static void writeCommand(OutputStream outCommStream, String command) throws IOException{
outCommStream.write((rsa.encrypt(command) + "\n").getBytes()); // note only command is encrypted not the new line
}
/**
* Read into a binary array. A helper method provided to enable future expansion of on the stream encryption
* @param inStream
* @param readDataBytes
* @param bytesToRead
* @return
* @throws IOException
*/
public static int readBinary(InputStream inStream, byte[] readDataBytes, int bytesToRead) throws IOException{
return inStream.read(readDataBytes, 0, bytesToRead);
}
}
<file_sep>package Server;
class Test
{
public static void main(String argv[]) throws Exception
{
RSA rsa = new RSA();
String emsg = rsa.encrypt("LOGIN|admin|admin");
emsg = emsg + "\n";
System.out.println(emsg);
System.out.println(rsa.decrypt(emsg));
}
}<file_sep>package Server;
class RSA
{
int p, q, n, z, d, e;
RSA()
{
p = 13;
q = 17;
n = p * q;
z = (p - 1) * (q - 1);
d = 19;
for(e = 1; e < z; ++e)
{
if((( e * d) % z) == 1)
break;
}
}
int gcd(int x,int y)
{
while(x != y)
{
if(x > y)
x = (short)(x - y);
else
y = (short)(y - x);
}
return x;
}
int modexp(int x, int y, int n)
{
int k = 1, i;
for(i = 0; i < y; i++)
k = (k * x) % n;
return k;
}
String encrypt(String msg)
{
int i;
char[] cmsg = new char[msg.length() + 1];
char[] emsg = new char[msg.length() + 1];
int[] imsg = new int[msg.length() + 1];
msg.getChars(0, msg.length(), cmsg, 0);
for(i = 0; i < msg.length(); i++)
imsg[i] = cmsg[i];
for(i = 0; i < msg.length(); i++)
emsg[i] = (char)modexp(imsg[i], e, n);
System.out.println("Encrypted string is : " + new String(emsg, 0, msg.length()));
return msg;
}
String decrypt(String msg)
{
int i;
char[] cmsg = new char[msg.length() + 1];
char[] dmsg = new char[msg.length() + 1];
int[] imsg = new int[msg.length() + 1];
msg.getChars(0, msg.length(), cmsg, 0);
for(i = 0; i < msg.length(); i++)
imsg[i] = cmsg[i];
for(i = 0; i < msg.length(); i++)
dmsg[i] = (char)modexp(imsg[i], d, n);
System.out.println("Decrypted string is : " + msg);
return msg;
}
public static void main(String argv[]) throws Exception
{
RSA rsa = new RSA();
String emsg = rsa.encrypt("LOGIN|admin|password");
String dmsg = rsa.decrypt(emsg);
System.out.println(emsg);
System.out.println(dmsg);
}
} | a4d099b64057a0a48535ba04b4ef7acc2c1a8c0f | [
"Java"
] | 4 | Java | Nazaf/Ensuring-Data-Security-in-Cloud-Computing | 937c0a5a62d93958da4a585e9e3c425d18de159b | 815aa1f0524f0ed661258aaba0e4581c0af3eacb |
refs/heads/master | <file_sep>package com.example.android.guesstheword.screens.score
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class ScoreViewModel(private val finalScore : Int) : ViewModel() {
// The score
private val _score = MutableLiveData<Int>()
val score: LiveData<Int>
get() = _score
// The play again Event
private val _playAgainEvent = MutableLiveData<Boolean>()
val playAgainEvent: LiveData<Boolean>
get() = _playAgainEvent
init {
_score.value = finalScore
}
fun onPlayAgain() {
_playAgainEvent.value = true
}
fun onPlayAgainFinished() {
_playAgainEvent.value = false
}
} | b6ecc976d93ff2622c8c02f191a1ff4aa7410da4 | [
"Kotlin"
] | 1 | Kotlin | IainS1986/Udacity.GuessIt | 03e2f0159f15d7dc83010c2823d387ed5043be0e | 1484d84ad17d7b917a37992d5ec42bbab0c56b68 |
refs/heads/master | <repo_name>KimSejune/homework<file_sep>/170810/three_compare.js
function Compare(x, y, z) {
if (x >= y && x >= z) {
return x;
}else if(y >= x && y>=z){
return y;
}else {
return z;
}
}
console.log(Compare(2, 11, 8));
var arr = [1,2,3];
var max = Math.max.apply(null,arr);
console.log(max);
function threeMax(a,b,c){
return Math.max(a,b,c);
}
console.log(threeMax(1,2,3));<file_sep>/170810/findday.js
function findDay(x) {
var today = new Date();
today.setDate(x);
var daynames = [('일'), ('월'), ('화'), ('수'), ('목'), ('금'), ('토')];
return daynames[today.getDay(x)];
}
console.log(findDay(6));
function getDay(n) {
var daynames = [('일'), ('월'), ('화'), ('수'), ('목'), ('금'), ('토')];
return daynames[n%7];
}
console.log(getDay(2));<file_sep>/170814/js/findMinDistance.js
// 20. 최단 거리 1차원 점의 쌍 구하기 (DAUM)
// 1 차원의 점들이 주어졌을 때, 그 중 가장 거리가 짧은 것(들) 의
// 쌍을 배열로 반환하는 함수를 작성하라.(단 점들의 배열은 모두 정렬되어있다고 가정한다.)
// 예를들어[1, 3, 4, 8, 13, 17, 20, 23, 24] 이 주어졌다면,
// 결과값은[[3, 4], [23, 24]] 가 될 것이다.
function findMinDistance(array) {
var store = []; // 차이값 저장을 위한 배열 선언
var sub = 0; // value값의 차이를 전달하기위한 number 선언
array.reduce(function (previousValue, currentValue) {
sub = currentValue - previousValue; // sub에 전달한 차이값 저장
store.push(sub); // sub에 저장된 차이값을 store에 push
return currentValue; // currentValue이 previousvalue값으로 return된다.
});
var min = Math.min.apply(null, store); // 차이값의 min값을 var min에 저장
var str = []; // 차이값이 가장작은 2개의 수를 새로운 배열로 저장
var store2 = []; // 새로운 배열들을 push
for (var i = 0; i < store.length; i++) { // store의 길이 만큼 for문을 실행한다.
if (min == store[i]) { // min값과 일치하면 아래 코드 실행한다.
str = new Array(array[i], array[i + 1]); // str에 차이값이 min인 2개의 값배열 저장
store2.push(str); // store2에 push
}
}
return store2; // 값을 return
}
var array = [1, 3, 4, 8, 13, 17, 20, 23, 24];
console.log(findMinDistance(array)); // [[3, 4], [23, 24]]<file_sep>/170810/count_average.js
function Average(n){
var add = 0;
for(var i=0; i<n.length; i++){
add += n[i];
}
console.log(add/n.length);
}
var arr = [1,2,3,4,5,6,7,8,9,10];
var n = arr;
Average(n);
function Average2(n2){
return n2.reduce(function(prev,curv){return prev+curv})/n2.length;
}
var n2 = [1,2,3,4,5];
console.log(Average2(n2));<file_sep>/170810/returnchar.js
var arr = ['a', 'b', 'c', 'd', 'e'];
var x = arr.join('');
console.log(x);
function returnchar(arr) {
var y = '';
for (var i = 0; i < arr.length; i++) {
y += arr[i];
}
return y;
}
console.log(returnchar(arr));<file_sep>/170731/for.js
for (var a = 0; a < 10; a += 2) {
console.log(a); // a에다가 2씩 증가하는 값을 만들어서 짝수를 출력한다.
}
console.log('\n'); // 개행.
var result = ''; // result에 string값을 저장한다.
for (var b = 0; b < 10; b += 2) { // b에다가 2씩 증가하는 값을 만들어서 짝수를 출력한다.
result += b; // result에다가 b를 string값으로 저장한다.
}
console.log(result); // 저장한 b값들을 출력한다.
console.log('\n'); // 개행.
for (var c = 9; c > 0; c -= 2) { // 홀수 9부터 출력하기 위해서 c=9를 넣는다. 그뒤에 2씩 줄여서 홀수를 출력한다.
console.log(c); // c를 출력한다.
}
console.log('\n'); // 개행
var d = -1; // d 선언 및 초기화 -1 + 2 한 값이 초기값
while (d < 8) { // d 값이 < 8보다 작을때까지 2씩증가
d += 2; // 2씩 증가
console.log(d); // 출력
}
console.log('\n'); // 개행
var e = 11; // e 선언 및 초기화 11 -2 한 값이 초기값
while (e > 1) { // e > 1보다 클때까지 2씩 감소
e -= 2; // 2씩 감소
console.log(e); // 출력
}
console.log('\n'); // 개행
var result = ''; // result에 string 선언 및 초기화
for (var i = 1; i <= 5; i++) { // i값이 5이하이면 1씩 증가시킨다.
for (var j = 0; j < i; j++) { // j값이 i미만이면 1씩 증가시킨다.
j = '*'; // j에다가 * string을 추가한다.
result += j; // result에다가 j를 추가한다.
}
console.log(result); // result 값을 출력한다,
}
console.log('\n'); // 개행
var result = ''; // result에 string 선언 및 초기화
for (var i = 1; i <= 3; i++) { // i값이 3이하이면 1씩 증가시킨다.
for (var j = 0; j < i; j++) { // j값이 i미만이면 1씩 증가시킨다.
j = '*'; // j에다가 * string을 추가한다.
result += j; // result에다가 j를 추가한다.
}
console.log(result); // result 값을 출력한다,
}
var result = ''; // result에 string 선언 및 초기화
for (var i = 1; i <= 5; i++) { // i값이 5이하이면 1씩 증가시킨다.
for (var j = 0; j < i; j++) { // j값이 i미만이면 1씩 증가시킨다.
j = '*'; // j에다가 * string을 추가한다.
result += j; // result에다가 j를 추가한다.
}
console.log(result); // result 값을 출력한다,
}
console.log('\n');
for (i = 0; i < 10; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
console.log('\n');
var result = '';
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
result += i;
}
}
console.log(result);
console.log('\n');
for (var i = 9; i > 0; i--) { //i값이 9부터 0까지 loop를 한다.
if (i % 2 === 1) {
console.log(i);
}
}
console.log('\n');
// i=0 ~ 10까지 1씩 증가시킨다.
var i = 0;
while (i < 10) {
if (i % 2 === 0) { // 나머지가 0이면 내부명령실행
console.log(i);
}
i++;
}
console.log('\n');
// i=9 ~ 0까지 1식 감소시킨다.
var i = 9;
while (i > 0) {
if (i % 2 === 1) {
console.log(i);
}
i--;
}
console.log('\n');
var result = '';
for (var i = 0; i < 5; i++) {
for (var j = 0; j < i + 1; j++) {
result += '*';
}
result += '\n';
}
console.log(result);
<file_sep>/170810/average.js
function Average(sum, count) {
this.sum = 0;
this.count = 0;
}
Average.prototype.add = function (array) {
array.forEach(function (element) {
this.sum += element;
this.count++;
}, this);
console.log(arr.sum/arr.count);
};
var arr = new Average();
arr.add([1, 2, 3, 4]);
var arr1 = [1,2,3,4,5]
function Aver(arr1){
var total = 0;
for(var i =0; i<arr1.length;i++){
total += arr1[i];
}
return total/arr1.length;
}
console.log(Aver(arr1));<file_sep>/170818/js/toWeirdCaseteach.js
// # 6. 이상한 문자만들기
// toWeirdCase함수는 문자열 s를 매개변수로 입력받는다.
// 문자열 s에 각 단어의 짝수번째 인덱스 문자는 대문자로, 홀수번째 인덱스 문자는 소문자로
// 바꾼 문자열을 리턴하도록 함수를 완성하라.
// 예를 들어 s가 ‘try hello world’라면 첫 번째 단어는 ‘TrY’, 두 번째 단어는 ‘HeLlO’, 세 번째 단어는 ‘WoRlD’로 바꿔 ‘TrY HeLlO WoRlD’를 리턴한다.
// 주의) 문자열 전체의 짝/홀수 인덱스가 아니라 단어(공백을 기준)별로 짝/홀수 인덱스를 판단한다.
function toWeirdCase(s) {
var str = s.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = UpperLower(str[i]);
}
return str.join(' ');
}
function UpperLower(arr) {
var res = '';
for (var i = 0; i < arr.length; i++) {
res += i % 2 == 0 ? arr[i].toUpperCase() : arr[i].toLowerCase();
}
return res;
}
console.log(toWeirdCase('try hello world')); // 'TrY HeLlO WoRlD'`
console.log(toWeirdCase('hello world')); // ‘HeLlO WoRlD’
console.log(toWeirdCase('my name is lee')); // ‘My NaMe Is LeE’<file_sep>/todoList/js/index.js
(function (window, document) {
'use strict'; // 엄격한것
function addListItem(e) {
if (!input.value.trim()) return;
if ((e.keyCode === 13) || e.type === 'click') {
itemPost(input.value);
insertItem(todoList, input.value);
input.value = '';
input.focus();
}
}
// List Item을 delete method로 제거하는 함수
function deleteListItem(id, target) {
var xhr = new XMLHttpRequest();
xhr.open('delete', '/toDoList/' + id, true);
xhr.send(null);
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
console.log('this.responseText: ', this.responseText);
//DB에서 성공적으로 제거 됐을 경우 DOM에서도 지움
//target(눌리는 button)의 부모인 li를 삭제해야해서 parentNode를 사용한다.
//<li class="todo-item">task<button class ="deletebtn">삭제</button></li>
todoList.removeChild(target.parentNode);
}
}
}
}
// List Item을 Post method로 등록하는 함수
// input.value값이 task로 들어가기 때문이다.
function itemPost(task) {
var xhr = new XMLHttpRequest();
xhr.open('post', '/toDoList', true);
// HTTP 통신패킷의 header 속성을 바꿔주는 API content-type을 application/json으로 변경해준다.
xhr.setRequestHeader('Content-type', 'application/json');
var data = {
task
};
// data를 Json화 시켜서 HTTP 통신 패킷의 body에 넣어서 보냄
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 201) {
console.log(this.responseText);
// 통신이 성공했을 경우 해당 List item을 DOM에 추가
// JSON 형식의 문자열 => 객체
var item = JSON.parse(this.responseText);
insertItem(todoList, item.task, item.id);
}
}
}
}
//DB로 부터 List item list를 get metho를 통해 가져오는 함수
function getListItem() {
var xhr = new XMLHttpRequest();
xhr.open('get', '/toDoList', true);
xhr.send(null);
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
console.log('this.responseText: ', this.responseText);
var toDoItemList = JSON.parse(this.responseText);
// 통신이 성공하면item을 list에 추가
toDoItemList.forEach(function (item) {
console.log('이것이 item.task: ', item.task);
insertItem(todoList, item.task, item.id);
});
} else {
console.error('GET failed')
}
}
}
}
// List item 추가해주는 함수
// element = toDoList이며 , task,id는 data.json을 보면 알 수 있다.
function insertItem(element, task, id) {
element.insertAdjacentHTML('beforeend', '<li class="todo-item">' + task + '<button class ="deletebtn">삭제</button></li>');
// li안에 delete button이 동적으로 생성 되기 때문에 DOM에 추가한 후 클릭 이벤트 바인딩
bindDeleteButton(id);
}
// deleteButton을 바인딩 시켜주는 함수
function bindDeleteButton(id) {
// 비동기라서 삭제 버튼은 생성한 후에 찾아야한다. 모든요소를 찾아야해서 All을 사용.
var deletebtn = document.querySelectorAll('.deletebtn');
console.log('deletebtn :', deletebtn[deletebtn.length - 1]);
// li 요소가 추가 될 때 delete button은 항상 마지막 요소이기 때문에
// 마지막 버튼에 이벤트 바인딩
deletebtn[deletebtn.length - 1].addEventListener('click', function () {
deleteListItem(id, this);
});
}
var input = document.querySelector('.input');
var button = document.querySelector('.button');
var todoList = document.querySelector('.todo-list');
button.addEventListener('click', addListItem);
input.addEventListener('keyup', addListItem);
// CRUD create, read, update, delete
// HTTP method post, get, put, delete
getListItem();
})(window, document);<file_sep>/170810/n_compare.js
var n = [1,8,2,1];
var n = n.sort(function(a,b){return a-b;})
console.log(n[n.length-1]);
function nMax(){
var arr = Array.prototype.slice.call(arguments);
return Math.max.apply(this,arr);
}
console.log(nMax(1,2,66,2,55));<file_sep>/170810/reverse.js
var n = ['1', '2', '3', '4'];
console.log(n.reverse());
console.log(n); // 기존 문자열도 변경된다.
function returnchar(arr) {
// var y = '';
// for (var i = arr.length-1; i >= 0; i--) {
// y += arr[i];
// }
// return y;
return arr.split('').reverse().join('');
}
console.log(returnchar('안녕ㅁㄴㅇㅁㄴㅇ'));
<file_sep>/170818/js/nextSqaure.js
// nextSqaure함수는 정수 n을 매개변수로 받는다.
// n이 임의의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 임의의 정수 x의 제곱이 아니라면 ‘no’을 리턴하는 함수를 작성하라.
// 예를들어 n이 121이라면 이는 정수 11의 제곱이므로 (11+1)의 제곱인 144를 리턴하고, 3이라면 ‘no’을 리턴한다.
function nextSqaure(n) {
// 정수일 경우 n+1할 값을 받아둘 변수 선언
var root = 0;
// n의 제곱근이 정수일경우 root에 n의 제곱근+1을 할당
if (Number.isInteger(Math.sqrt(n)) === true) {
var root = (Math.sqrt(n) + 1);
// root의 제곱을 반환
return root * root;
} else {
// n의 제곱근이 정수가 아닐경우 'no'를 반환
return 'no';
}
}
console.log(nextSqaure(3)); // no
console.log(nextSqaure(121)); // 144<file_sep>/170818/js/waterMelon.js
// waterMelon 함수는 정수 n을 매개변수로 입력받는다.
// 길이가 n이고, 수박수박수...와 같은 패턴을 유지하는 문자열을 리턴하도록 함수를 완성하라.
// 예를들어 n이 4이면 ‘수박수박‘을 리턴하고 3이라면 ‘수박수‘를 리턴한다.
function waterMelon(n) {
// 반환할 문자열 선언
var water = [];
// n 의 크기만큼 for문 실행
for( var i=0; i<n; i++){
// i%2의 나머지가 0이라면 water에 '수'를 붙인다.
if(i%2 == 0){
water += '수';
} // 아니라면 water에 '박'를 붙인다.
else{
water += '박';
}
}
// water를 반환한다.
return water;
}
console.log('n이 3인 경우: ' + waterMelon(3));
console.log('n이 4인 경우: ' + waterMelon(4)); | ff94efe061b9cdfc88e7c8851bbc138a66108fa6 | [
"JavaScript"
] | 13 | JavaScript | KimSejune/homework | 6fe540b830f931adc8a6e236b0a7e5ab180e4728 | 7d6b909da2ee07f654144a34a511d7b765cce8b3 |
refs/heads/master | <file_sep>package com.bilchege.commuteazy.Entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.lang.Nullable;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;
@Column(name = "first_name")
@JsonProperty("firstName")
private String firstName;
@Column(name = "last_name")
@JsonProperty("lastName")
private String lastName;
@Column(name = "user_name")
@JsonProperty("userName")
private String userName;
@Column(name = "phone")
@JsonProperty("phone")
private Long phone;
@Column(name = "email")
@JsonProperty("email")
private String email;
@Column(name = "password")
@JsonProperty("password")
private String accountPassword;
public User() {
}
public User(String firstName, String lastName, String userName, Long phone, String email, String accountPassword, @Nullable List<Review> reviews) {
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.phone = phone;
this.email = email;
this.accountPassword = accountPassword;
//this.reviews = reviews;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAccountPassword() {
return accountPassword;
}
public void setAccountPassword(String accountPassword) {
this.accountPassword = <PASSWORD>;
}
}
<file_sep>package com.bilchege.commuteazy.Services;
import com.bilchege.commuteazy.Entities.Feed;
import com.bilchege.commuteazy.Repositories.FeedRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class FeedService {
@Autowired
private FeedRepository feedRepository;
public Feed addFeed(Feed feed){
return feedRepository.save(feed);
}
public Optional<Feed> getFeed(Long id){
return feedRepository.findById(id);
}
public List<Feed> getAllFeeds(){
List<Feed> feeds = new ArrayList<>();
feedRepository.findAll().forEach(feeds::add);
SortByDate s = new SortByDate();
Collections.sort(feeds,s.reversed());
return feeds;
}
public void deleteFeed(Long id){
feedRepository.deleteById(id);
}
public class SortByDate implements Comparator<Feed>{
@Override
public int compare(Feed o1, Feed o2) {
return (int) (o1.getDateCreated().getTime()-o2.getDateCreated().getTime());
}
}
}
<file_sep>package com.bilchege.commuteazy.Services;
import com.bilchege.commuteazy.Entities.Operator;
import com.bilchege.commuteazy.Entities.Review;
import com.bilchege.commuteazy.Entities.User;
import com.bilchege.commuteazy.Repositories.ReviewsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class ReviewService {
@Autowired
private ReviewsRepository reviewsRepository;
public void addReview(Review review){
reviewsRepository.save(review);
}
public Optional<Review> getReview(Long id){
return reviewsRepository.findById(id);
}
public List<Review> getReviewbyUser(User user){
List<Review> reviews = new ArrayList<>();
reviewsRepository.findReviewsByUser(user).forEach(reviews::add);
return reviews;
}
public List<Review> getReviewbyOperator(Operator operator){
List<Review> reviews = new ArrayList<>();
reviewsRepository.findReviewsByOperator(operator).forEach(reviews::add);
return reviews;
}
public List<Review> getReviewbyOperatorAndUser(Operator operator,User user){
List<Review> reviews = new ArrayList<>();
reviewsRepository.findReviewsByOperatorAndUser(operator,user).forEach(reviews::add);
return reviews;
}
public List<Review> getReviews(){
List <Review> reviews = new ArrayList<>();
reviewsRepository.findAll().forEach(reviews::add);
return reviews;
}
public void updateReview(Review review,Long id){
reviewsRepository.save(review);
}
public void deleteReview(Long id){
reviewsRepository.deleteById(id);
}
}
<file_sep>rootProject.name = 'commuteazy'
<file_sep>package com.bilchege.commuteazy.Repositories;
import com.bilchege.commuteazy.Entities.Terminus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
public interface TerminusRepository extends CrudRepository<Terminus,String> {
}
<file_sep>package com.bilchege.commuteazy.Services;
import com.bilchege.commuteazy.Entities.Operator;
import com.bilchege.commuteazy.Repositories.OperatorRepository;
import com.bilchege.commuteazy.ResponseObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
@Service
public class OperatorService {
@Autowired
private OperatorRepository operatorRepository;
@Autowired
private PlaceService placeService;
public HashSet<Operator> getOperators(){
HashSet<Operator> thisList = new HashSet<>();
operatorRepository.findAll().forEach(thisList::add);
return thisList;
}
public Optional<Operator> getOperator(Long id){
Operator o = new Operator();
return operatorRepository.findById(id);
}
public Operator addOperator(Operator operator){
return operatorRepository.save(operator);
}
public Optional<Operator> login(String name,String password){
return operatorRepository.findOperatorByOperatorNameAndAccountPassword(name,password);
}
public void updateOperator(Long id,Operator operator){
operatorRepository.save(operator);
}
public List<ResponseObj> operatorsOnRoute(String origin,String destination){
return operatorRepository.fetchOperatorOnRoute(origin,destination);
}
}
<file_sep>package com.bilchege.commuteazy.Repositories;
import com.bilchege.commuteazy.Entities.Operator;
import com.bilchege.commuteazy.Entities.Review;
import com.bilchege.commuteazy.Entities.User;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface ReviewsRepository extends CrudRepository<Review,Long> {
List<Review> findReviewsByUser(User user);
List<Review> findReviewsByOperator(Operator operator);
List<Review> findReviewsByOperatorAndUser(Operator operator,User user);
}
<file_sep>spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/commuteeazy
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.port=8085<file_sep>function save_operator_data(){
var name = document.getElementById("operator_name").value;
var email = document.getElementById("operator_email").value;
var phone = document.getElementById("operator_phone").value;
var password = document.getElementById("operator_password").value;
var formData= '{"operatorName":"'+name+'","email":"'+email+'","phone":'+parseInt(phone)+',"password":"'+<PASSWORD>+'"}';
console.log(formData);
var d = JSON.parse(formData);
console.log(d );
$.ajax({
type:"POST",
url:"../addOperator",
data:JSON.stringify({
name:name,
email:email,
phone:parseInt(phone),
password:<PASSWORD>
}),
contentType:"application/json",
dataType:"json",
success:function (response) {
console.log(response);
},
error:function(error,response){
console.log(response);
}
});
}<file_sep>package com.bilchege.commuteazy.Entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
@Entity
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long reviewID;
@Column(name = "comment")
@JsonProperty("comment")
private String comment;
@ManyToOne
@JoinColumn(name = "operatorID")
@JsonProperty("operator")
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonManagedReference
@JsonIgnore
private Operator operator;
@ManyToOne
@JoinColumn(name = "userID")
@JsonProperty("user")
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonManagedReference
@JsonIgnore
private User user;
public Review() {
}
public Review(String comment, Operator operator, User user) {
this.comment = comment;
this.operator = operator;
this.user = user;
}
public Long getReviewID() {
return reviewID;
}
public void setReviewID(Long reviewID) {
this.reviewID = reviewID;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
<file_sep>package com.bilchege.commuteazy;
public class ResponseObj {
private String operatorName;
private String address;
private double latitude;
private double longitude;
public ResponseObj() {
}
public ResponseObj(String operatorName, String address, double latitude, double longitude) {
this.operatorName = operatorName;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
}
public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
<file_sep>package com.bilchege.commuteazy.Controllers;
import com.bilchege.commuteazy.Entities.Feed;
import com.bilchege.commuteazy.Services.FeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
public class FeedController {
@Autowired
private FeedService feedService;
@RequestMapping(method = RequestMethod.POST,value = "/addfeed")
public Feed addFeed(@RequestBody Feed feed){
return feedService.addFeed(feed);
}
@RequestMapping("/getfeed/{id}")
public Optional<Feed> getFeed(@PathVariable Long id){
return feedService.getFeed(id);
}
@RequestMapping("/getfeeds")
public List<Feed> getFeeds(){
return feedService.getAllFeeds();
}
@RequestMapping("/deletefeed/{id}")
public void deleteFeed(@PathVariable Long id){
feedService.deleteFeed(id);
}
}
| 6b65d5e6c37102c35e1a45970f8a4259f9b0fa33 | [
"JavaScript",
"Java",
"INI",
"Gradle"
] | 12 | Java | Bildad-Chege/CommuteEazy | cd76534277d450dd1dfb372e1098a0a3fd3941a3 | 6ba32889f671b702d9f994e23d9c659275d7850c |
refs/heads/main | <repo_name>CoennW/pokedex<file_sep>/README.md
# pokedex
Code in master branche

| 9881b135a04f53d9381915467cccfbec7a905916 | [
"Markdown"
] | 1 | Markdown | CoennW/pokedex | 038615d99bcdef003e882cb0a107ed73eb5a6a41 | 519a9022ca0c9e71034e7de89ad5de0d23253c07 |
refs/heads/main | <repo_name>cryptwh0ads/social-media-app<file_sep>/src/pages/Profile/index.jsx
import "./styles.css"
import Navbar from "../../components/Navbar";
import LeftSideBar from "../../components/Sidebars/Left";
import Feed from "../../components/Feed";
import RightSideBar from "../../components/Sidebars/Right";
import axios from "axios";
import {useEffect, useState} from "react";
import { useParams } from 'react-router'
export default function Profile() {
const [user, setUser] = useState({})
const username = useParams().username
const publicFolder = process.env.REACT_APP_PUBLIC_FOLDER
const fetchUser = async () => {
const res = await axios.get(`/users?username=${username}`)
setUser(res.data.data)
}
useEffect(() => {
fetchUser()
}, [])
return (
<div>
<Navbar />
<div className={"profile-container"}>
<LeftSideBar />
<div className={"profile-right"}>
<div className={"profile-right-top"}>
<div className={"profile-cover"}>
<img className={"profile-cover-img"} src={user.coverPicture || publicFolder+"person/noCover.png"} alt={"Cover Image"}/>
<img className={"profile-user-img"} src={user.profilePicture || publicFolder+"person/noAvatar.png"} alt={"Profile Image"}/>
</div>
<div className={"profile-info"}>
<h4 className={"profile-info-name"}>{user.username}</h4>
<span className={"profile-info-description"}>{user.description}</span>
</div>
</div>
<div className={"profile-right-bottom"}>
<Feed username={username} />
<RightSideBar profile={user}/>
</div>
</div>
</div>
</div>
)
}<file_sep>/src/components/Feed/Post/index.jsx
import "./styles.css"
import {MoreVert} from "@material-ui/icons";
import {useEffect, useState} from "react";
import axios from "axios";
import { format } from 'timeago.js'
import {Link} from "react-router-dom";
export default function PostComponent({ post }) {
const [like, setLike] = useState(post.likes.length)
const [isLiked, setIsLiked] = useState(false)
const [user, setUser] = useState({})
const publicFolder = process.env.REACT_APP_PUBLIC_FOLDER
const likeHandle = () => {
setLike(isLiked ? like - 1 : like + 1)
setIsLiked(!isLiked)
}
const fetchUser = async () => {
const res = await axios.get(`/users?userId=${post.userId}`)
setUser(res.data.data)
}
useEffect(() => {
fetchUser()
}, [post.userId])
return (
<div className={"post"}>
<div className={"post-wrapper"}>
<div className={"post-top"}>
<div className={"post-top-left"}>
<Link to={`profile/${user.username}`}><img className={"post-profile-img"} src={user.profilePicture || publicFolder+"person/noAvatar.png" } alt={"Post Profile"} /></Link>
<span className={"post-username"}>{user.username}</span>
<span className={"post-date"}>{format(post.createdAt)}</span>
</div>
<div className={"post-top-right"}>
<MoreVert />
</div>
</div>
<div className={"post-center"}>
<span className={"post-text"}>{post?.description}</span>
{post?.postPicture ? <img className={"post-img"} src={publicFolder+post.postPicture} alt={"Post image"}/> : null }
</div>
<div className={"post-bottom"}>
<div className={"post-bottom-left"}>
<img className={"like-icon"} src={`${publicFolder}like.png`} alt={"like"} onClick={likeHandle}/>
<img className={"like-icon"} src={`${publicFolder}heart.png`} alt={"like"} onClick={likeHandle}/>
<span className={"post-like-counter"}>{like} people like it</span>
</div>
<div className={"post-bottom-right"}>
<span className={"post-comment-text"}>{post.comments} comments</span>
</div>
</div>
</div>
</div>
)
}
<file_sep>/src/components/Navbar/index.jsx
import "./styles.css"
import {Chat, Notifications, Person, Search} from "@material-ui/icons";
import {Link} from "react-router-dom";
export default function NavBar() {
return (
<div className={"container"}>
<div className={"left"}>
<Link to={"/"} style={{textDecoration: "none"}}>
<span className={"logo"}>SocialMedia</span>
</Link>
</div>
<div className={"center"}>
<div className={"search-bar"}>
<Search className={"search-icon"} />
<input placeholder={"What do you like to search..."} className={"search-input"} />
</div>
</div>
<div className={"right"}>
<div className={"links"}>
<Link to={"/"} style={{textDecoration: "none"}}>
<span className={"item-link"}>Home</span>
</Link>
<span className={"item-link"}>Timeline</span>
</div>
<div className={"icons"}>
<div className={"item-icon"}>
<Person />
<span className={"icon-badge"}>1</span>
</div>
<div className={"item-icon"}>
<Chat />
<span className={"icon-badge"}>2</span>
</div>
<div className={"item-icon"}>
<Notifications />
<span className={"icon-badge"}>3</span>
</div>
</div>
<img src={"/assets/person/1.jpeg"} alt={"Profile Picture"} className={'profile-img'} />
</div>
</div>
)
}<file_sep>/src/pages/Home/index.jsx
import Navbar from '../../components/Navbar'
import LeftSideBar from "../../components/Sidebars/Left";
import Feed from "../../components/Feed";
import RightSideBar from "../../components/Sidebars/Right";
import "./styles.css"
export default function Home() {
return (
<div>
<Navbar />
<div className={"home-container"}>
<LeftSideBar />
<Feed />
<RightSideBar />
</div>
</div>
)
}<file_sep>/src/components/Feed/index.jsx
import axios from 'axios'
import "./styles.css"
import ShareComponent from "./Share";
import PostComponent from "./Post";
import {useEffect, useState} from "react";
export default function Feed({ username }) {
const [posts, setPosts] = useState([])
const fetchPosts = async () => {
const res = username ? await axios.get("/posts/profile/" + username)
: await axios.get('posts/timeline/60f44ed445b0f0a47f2e88dc')
setPosts(res.data.data)
}
useEffect(() => {
fetchPosts()
}, [])
return (
<div className={"feed"}>
<div className={"feed-wrapper"}>
<ShareComponent />
{posts.map(post => (
<PostComponent key={post._id} post={post} />
))}
</div>
</div>
)
}<file_sep>/src/components/Feed/Share/index.jsx
import "./styles.css"
import {EmojiEmotions, Label, PermMedia, Room} from "@material-ui/icons";
export default function ShareComponent(){
return(
<div className={"share"}>
<div className={"share-wrapper"}>
<div className={"share-top"}>
<img className={"share-profile-img"} src={"/assets/person/1.jpeg"} alt={''} />
<input
placeholder={"What's in your mind?"}
className={"share-input"}/>
</div>
<hr className={'share-hr'} />
<div className={"share-bottom"}>
<div className={"share-options"}>
<div className={"share-option"}>
<PermMedia className={"share-icon"} />
<span className={"share-option-desc"}>Photo / Video</span>
</div>
<div className={"share-option"}>
<Label className={"share-icon"} />
<span className={"share-option-desc"}>Tag</span>
</div>
<div className={"share-option"}>
<Room className={"share-icon"} />
<span className={"share-option-desc"}>Location</span>
</div>
<div className={"share-option"}>
<EmojiEmotions className={"share-icon"} />
<span className={"share-option-desc"}>Feelings</span>
</div>
</div>
<button className={"share-button"}>Share</button>
</div>
</div>
</div>
)
}<file_sep>/src/components/Sidebars/Right/index.jsx
import "./styles.css"
import { Users } from "../../../Data/User";
import OnlineUsersComponent from "./OnlineUsers";
export default function RightSideBar({ profile }) {
const publicFolder = process.env.REACT_APP_PUBLIC_FOLDER
const HomeRightBar = () => {
return (
<>
<div className={"birthday-container"}>
<img className={"birthday-img"} src={"assets/gift.png"} alt={"Gift image"} />
<span className={"birthday-text"}>
<b><NAME></b> and <b>9 other friends</b> have a birthday today
</span>
</div>
<h4 className={"right-title"}>Online Friends</h4>
<ul className={"right-friend-list"}>
{Users.map(user => (
<OnlineUsersComponent key={user.id} user={user} />
))}
</ul>
</>
)
}
const ProfileRightBar = () => {
return (
<>
<h4 className={"rightbar-title"}>User Information</h4>
<div className={"rightbar-info"}>
<div className={"rightbar-info-item"}>
<span className={"rightbar-info-key"}>City: </span>
<span className={"rightbar-info-value"}>{profile.city} </span>
</div>
<div className={"rightbar-info-item"}>
<span className={"rightbar-info-key"}>From: </span>
<span className={"rightbar-info-value"}>{profile.from} </span>
</div>
<div className={"rightbar-info-item"}>
<span className={"rightbar-info-key"}>Relationship: </span>
<span className={"rightbar-info-value"}>{
profile.relationship === 1 ? 'Single'
: profile.relationship === 2 ? 'Married'
: profile.relationship === 3 ? 'In loving'
: '-'} </span>
</div>
</div>
<h4 className={"rightbar-title"}>User Friends</h4>
<div className={"rightbar-followings"}>
<div className={"rightbar-following"}>
<img src={`${publicFolder}person/1.jpeg`} alt={"User Follow"} className={"rightbar-following-img"} />
<span className={"rightbar-following-name"}>D<NAME>za</span>
</div>
<div className={"rightbar-following"}>
<img src={`${publicFolder}person/1.jpeg`} alt={"User Follow"} className={"rightbar-following-img"} />
<span className={"rightbar-following-name"}>D<NAME>za</span>
</div>
<div className={"rightbar-following"}>
<img src={`${publicFolder}person/1.jpeg`} alt={"User Follow"} className={"rightbar-following-img"} />
<span className={"rightbar-following-name"}><NAME></span>
</div>
<div className={"rightbar-following"}>
<img src={`${publicFolder}person/1.jpeg`} alt={"User Follow"} className={"rightbar-following-img"} />
<span className={"rightbar-following-name"}><NAME></span>
</div>
<div className={"rightbar-following"}>
<img src={`${publicFolder}person/1.jpeg`} alt={"User Follow"} className={"rightbar-following-img"} />
<span className={"rightbar-following-name"}><NAME></span>
</div>
<div className={"rightbar-following"}>
<img src={`${publicFolder}person/1.jpeg`} alt={"User Follow"} className={"rightbar-following-img"} />
<span className={"rightbar-following-name"}><NAME></span>
</div>
</div>
</>
)
}
return (
<>
<div className={"right-sidebar"}>
<div className={"right-wrapper"}>
{(profile ? <ProfileRightBar/> : <HomeRightBar/>)}
</div>
</div>
</>
)
}<file_sep>/src/pages/Auth/Register/index.jsx
import "./styles.css"
export default function Register() {
return (
<div className={"login"}>
<div className={"login-wrapper"}>
<div className={"login-left"}>
<h3 className={"login-logo"}>SocialMedia</h3>
<span className={"login-description"}>
Connect with friend and the world.
</span>
</div>
<div className={"login-right"}>
<div className={"login-box"}>
<input type={"text"} placeholder={"Username"} className={"login-input"} />
<input type={"text"} placeholder={"Email"} className={"login-input"} />
<input type={"password"} placeholder={"<PASSWORD>"} className={"login-input"} />
<input type={"<PASSWORD>"} placeholder={"<PASSWORD>"} className={"login-input"} />
<button className={"login-button"}>Sign Up</button>
<button className={"login-register-button"}>
Log into account
</button>
</div>
</div>
</div>
</div>
)
} | b42eb7078e009325199902a79784b73a88dd1c05 | [
"JavaScript"
] | 8 | JavaScript | cryptwh0ads/social-media-app | de26f300e6ce5f14589ce74acef03e8f48a43f31 | 3a7c4781b5f0ea867e9050315d9f6d60ded2f9a0 |
refs/heads/master | <file_sep>'''
----------------------------------------------------------------------------
The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5
Software Development Kit for iControl"; you may not use this file except in
compliance with the License. The License is included in the iControl
Software Development Kit.
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
The Original Code is iControl Code and related documentation
distributed by F5.
The Initial Developer of the Original Code is F5 Networks,
Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2004 F5 Networks,
Inc. All Rights Reserved. iControl (TM) is a registered trademark of F5 Networks, Inc.
Alternatively, the contents of this file may be used under the terms
of the GNU General Public License (the "GPL"), in which case the
provisions of GPL are applicable instead of those above. If you wish
to allow use of your version of this file only under the terms of the
GPL and not to allow others to use your version of this file under the
License, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your
version of this file under either the License or the GPL.
----------------------------------------------------------------------------
'''
import re
import suds
from xml.sax import SAXParseException
# Project info
class F5Error(Exception):
def __init__(self, e):
self.exception=e
self.msg=str(e)
if isinstance(e,suds.WebFault):
try:
parts=e.fault.faultstring.split('\n')
e_source=parts[0].replace("Exception caught in ","")
e_type=parts[1].replace("Exception: ","")
e_msg=re.sub("\serror_string\s*:\s*","",parts[4])
self.msg="%s: %s"%(e_type,e_msg)
except IndexError:
self.msg=e.fault.faultstring
if isinstance(e,SAXParseException):
self.msg="Unexpected server response. %s"%e.message
def __str__(self):
return self.msg
<file_sep>from setuptools import setup, find_packages
setup(
name = "pycontrol",
version = "2.0.1a",
packages = find_packages(),
# Project uses suds SOAP client module.
install_requires = ['suds>=0.3.9'],
#entry_points ="""
# [console_scripts]
# pycontrol = pycontrol.pycontrol:main
# """
)
<file_sep>iRuler
======
Remote editing of F5 BigIP iRules with vim
Getting Started
---------------
Use [Vundle](https://github.com/gmarik/Vundle.vim) or
[Pathogen](https://github.com/tpope/vim-pathogen/) to load
http://github.com/wfaulk/iRuler.vim
* For Vundle, add `Plugin 'wfaulk/iRuler.vim'` to the appropriate location
in your `.vimrc`.
* For Pathogen:
cd ~/.vim/bundle/<br />
git clone http://github.com/wfaulk/iRuler.vim
Once installed, inside vim, run `:F5Connect` to connect to your BigIP, then run
`:F5GetRules` to get a list of rules. (They will be folded; use `zo`
to open folds.) Move your cursor to the iRule you want to edit and
run `:F5OpenRule`. Edit the rule as desired, then run `:F5PubRule` to
upload your changes.
Important Data Retention Notice
-------------------------------
iRuler does not currently flush your changes to the BigIP's on-disk config.
This will change in the future, but make sure you do it yourself by hand for
now. The easiest way is probably to click any "Update" button in the BigIP's
web interface.
Notes
-----
iRuler requires a python-enabled vim.
iRuler currently includes the python modules pycontrol and suds. This
may change to a prerequisite, but I personally had trouble with keeping
them elsewhere non-global and having MacVim find them.
Credits
-------
The majority of the functional code is taken directly from
[vim-iruler](https://devcentral.f5.com/d/vim-based-irule-editor)
but updated to work better as a Pathogen/Vundle plugin.
<file_sep>#!/bin/env python
'''
----------------------------------------------------------------------------
The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5
Software Development Kit for iControl"; you may not use this file except in
compliance with the License. The License is included in the iControl
Software Development Kit.
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
The Original Code is iControl Code and related documentation
distributed by F5.
The Initial Developer of the Original Code is F5 Networks,
Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2004 F5 Networks,
Inc. All Rights Reserved. iControl (TM) is a registered trademark of F5 Networks, Inc.
Alternatively, the contents of this file may be used under the terms
of the GNU General Public License (the "GPL"), in which case the
provisions of GPL are applicable instead of those above. If you wish
to allow use of your version of this file only under the terms of the
GPL and not to allow others to use your version of this file under the
License, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your
version of this file under either the License or the GPL.
----------------------------------------------------------------------------
'''
from logging import getLogger
log = getLogger(__name__)
from datetime import datetime
import os
import sys
import glob
import sgmllib
from logging import getLogger
import urllib2
from urllib2 import URLError
from tempfile import gettempdir
log = getLogger(__name__)
ICONTROL_URI = "/iControl/iControlPortal.cgi"
def longest_common_prefix(strings):
"""
Taken from: http://boredzo.org/blog/archives/2007-01-06/longest-common-prefix-in-python-2
This function returns the longest common prefix of one or more sequences. Raises an exception when zero sequences are provided.
"""
assert strings, 'Longest common prefix of no strings requested. Such behavior is highly irrational and is not tolerated by this program.'
if len(strings) == 1: return strings[0]
strings = [pair[1] for pair in sorted((len(fi), fi) for fi in strings)]
for i, comparison_ch in enumerate(strings[0]):
for fi in strings[1:]:
ch = fi[i]
if ch != comparison_ch:
return fi[:i]
return strings[0]
def setupHTTPAuth(url, username, password):
""" Setup authentication if we're pulling from BigIP iControlPortal.cgi"""
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
def get_wsdls(options):
""" fetch the wsdls from BigIP and save them off in options.wsdl_dir"""
wsdl_names = []
setupHTTPAuth(options.bigip_url,options.username,options.password)
log.info("Getting list of WSDLs on BigIP: %s..." % options.bigip_url)
try:
wsdl_list_url = "%s%s?WSDL" % (options.bigip_url,ICONTROL_URI)
wsdl_index_page = urllib2.urlopen(wsdl_list_url).read()
parser = WebParser()
parser.parse(wsdl_index_page)
links = parser.get_hyperlinks()
wsdl_names = [x[x.find('=')+1:] for x in links]
except URLError,e:
log.error("Error getting list of WSDLs on BigIP: %s" % wsdl_list_url)
raise
log.info("Done. Found %d WSDLs" % len(wsdl_names))
log.info("Downloading required WSDLs...")
n = 0
for wsdl_name in wsdl_names:
#if options.setup_demo and not wsdl_name=="LocalLB.Pool":
# continue
#if not is_matching_wsdl(wsdl_name, options.setup_wsdl_patterns):
# continue
wsdl_url = "%s%s?WSDL=%s" % (options.bigip_url, ICONTROL_URI, wsdl_name)
wsdl_file_name = os.path.join(options.wsdl_dir,"%s.wsdl" % (wsdl_name))
print "WSDL FILE NAME is: %s" % wsdl_file_name
if options.setup_force or not os.path.exists(wsdl_file_name):
log.debug("Downloading %s..." % (wsdl_file_name))
wsdl_text = urllib2.urlopen(wsdl_url).read()
wsdl_file = open(wsdl_file_name,"w+")
wsdl_file.write(wsdl_text)
wsdl_file.close()
n+=1
log.info("Done. Downloaded %d missing and required WSDLs." % n)
return True
def empty_wsdl_dir(wsdl_dir):
""" delete the wsdl files """
for filename in glob.glob(os.path.join(wsdl_dir,"*.wsdl")):
os.remove(filename)
def rebuild_wsdl_dir(options, empty):
if empty: empty_wsdl_dir(options.wsdl_dir)
get_wsdls(options)
class WebParser(sgmllib.SGMLParser):
"""A simple parser class."""
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."
sgmllib.SGMLParser.__init__(self, verbose)
self.hyperlinks = []
def start_a(self, attributes):
"Process a hyperlink and its 'attributes'."
for name, value in attributes:
if name == "href":
self.hyperlinks.append(value)
def get_hyperlinks(self):
"Return the list of hyperlinks."
return self.hyperlinks
def is_matching_wsdl(wsdl_name, wsdls_list):
#log.debug("Testing wsdl_name %s against list: %s"%(wsdl_name,wsdls_list))
if wsdls_list:
module_name,interface_name = wsdl_name.split('.')
wsdls_list = [x.split(".") for x in wsdls_list]
for m,i in wsdls_list:
if (m == "*" or m.upper() == module_name.upper()) and (i == "*" or i.upper() == interface_name.upper()):
#log.debug("Testing wsdl_name %s MATCHED: %s.%s"%(wsdl_name,m,i))
return True
#log.debug("Testing wsdl_name %s NO MATCH"%(wsdl_name))
return False
class UsefulU64(object):
"""
A port of this Java class to Python:
http://devcentral.f5.com/Default.aspx?tabid=63&articleType=ArticleView&articleId=78
Makes dealing with the "ULong64 type returned in statistics calls from the iControl API" easier.
"""
def __init__(self,ulong):
self.ulong=ulong
self.value=0
high=ulong.high
low=ulong.low
rollOver = 0x7fffffff
rollOver += 1
tmpVal=0
if(high >=0):
tmpVal = high << 32 & 0xffff0000
else:
tmpVal = ((high & 0x7fffffff) << 32) + (0x80000000 << 32)
if(low >=0):
tmpVal = tmpVal + low
else:
tmpVal = tmpVal + (low & 0x7fffffff) + rollOver
self.value=tmpVal
def __str__(self):
size = ""
value=self.value
if(value / 1024 >= 1.0):
size = "K"
value = value / 1024
if(value / 1024 >= 1.0):
size = "M"
value = value / 1024
if(value / 1024 >= 1.0):
size = "G"
value = value / 1024
return "%.2f%s"%(value,size)
def __call__(self):
return self.__str__()
class Options(object):
pass
if __name__ == '__main__':
if len(sys.argv) < 4:
print "Usage: %s <hostname> <username> <password>"% sys.argv[0]
sys.exit()
host,username,password = sys.argv[1:]
o = Options()
o.wsdl_dir = gettempdir()
o.bigip_url = 'https://%s' % host
o.username = username
o.password = <PASSWORD>
o.setup_demo = False
o.setup_wsdl_patterns = False
o.setup_force = True
get_wsdls(o)
| d0020bf2f3fb846d7b623fa928703ec0ee3cc6e3 | [
"Markdown",
"Python"
] | 4 | Python | wfaulk/iRuler.vim | a6327752637aeecf49721ebfa6b2897bcc8be2b5 | f946575a19fd420e916049c0a8a64b3ea5ccb88a |
refs/heads/main | <file_sep>package posSystem;
public class employeeRoster {
private EmployeeOrderInfo head;
public employeeRoster() {
head = null;
}
//will have options to add different items
public void addEmployee(Long employeeID, Long orderNumber, double time1, double time2, double elapsedTime) {
if(head == null) {
head = new EmployeeOrderInfo(employeeID, orderNumber, time1, time2, elapsedTime);
return;
}
}
public void addEmployee(EmployeeOrderInfo front) {
front.setNext(head);
head = front;
}
public void addEmployeeFront(long employeeID, String name) {
EmployeeOrderInfo temp = new EmployeeOrderInfo(employeeID, name);
temp.setNext(head);
head = temp;
}
public void addEmployeeFront(Long employeeID, Long orderNumber, double time1, double time2, double elapsedTime) {
EmployeeOrderInfo temp = new EmployeeOrderInfo(employeeID, orderNumber, time1, time2, elapsedTime);
temp.setNext(head);
head = temp;
}
// will have option to add a record in a sorted format
public void addSorted(EmployeeOrderInfo sort) {
if(head == null ) { //if the list is empty
head = sort;
return;
}
if(sort.getEmployeeID() < head.getEmployeeID()) { //if the UIN is smaller than the head
sort.setNext(head);
head = sort;
return;
}
EmployeeOrderInfo temp = head;
while(temp != null) { // make sure there is not and identical uin
//if(temp.getPrice() == sort.getPrice() ) {
//System.out.println("Please use a different price.");
//return;
//}
if(temp.getNext() == null) { // adds it at the end of the list if there is no more uins
temp.setNext(sort);
return;
}
//place it between the correct numbers
if(temp.getEmployeeID() < sort.getEmployeeID() && temp.getNext().getEmployeeID() > sort.getEmployeeID()) {
sort.setNext(temp.getNext());
temp.setNext(sort);
return;
}
temp = temp.getNext();
}
}
// will have the code needed to delete an item ordered
//will have the toString method
public String toString() {
if(head ==null)
return "Empty list";// if there is nothing on the list will say empty list
String toReturn = new String();
EmployeeOrderInfo temp = head;
while(temp != null) {//if head is not null we will printout the information needeed
toReturn += temp.toString() + ",";
temp = temp.getNext();
}
return toReturn;
}
public String toCSV() {
String strexport = "";
EmployeeOrderInfo node = head;
while(node != null) {
strexport += node.toCSV() + "\n" ;
node = node.getNext();
}
return strexport;
}
public void printList() {
//prints the list selected
EmployeeOrderInfo node = head; //pointer
while(node != null) { //goes through the entire list
System.out.println(node.toString());
node = node.getNext();
}
}
public employeeRoster clone() { //COPIES THE LIST IN REVERSE
employeeRoster result = new employeeRoster(); //creates a new roster to store the cloned values
EmployeeOrderInfo temp = head;
while(temp != null) { //goes through the list and if temp(head) is not null clone the element
result.addEmployee(temp.clone());
temp= temp.getNext(); // goes to the next element
}
return result; //returns the new roster
}
public boolean employeeSearch(long searchId) {
EmployeeOrderInfo node = head;
while(node != null) {
if(node.getEmployeeID() == searchId) {
return true;
}
node = node.getNext();
}
return false;
}
public EmployeeOrderInfo Search(long search) {
EmployeeOrderInfo node = head;
while(node != null) {
if(node.getEmployeeID() == search) {
return node;
}
node = node.getNext();
}
return node;
}
}
<file_sep>package posSystem;
public class MenuOptions {
//will display the options selected
private String ingredients;
private String recipe;
private double price;
private String nutritionalInfo;
MenuOptions next;
private Integer num;
public MenuOptions(String ingredients, String recipe, double price, String nutritionalInfo) {
super();
this.ingredients = ingredients;
this.recipe = recipe;
this.price = price;
this.nutritionalInfo = nutritionalInfo;
}
public MenuOptions(Integer num,String recipe, String ingredients, double price, String nutritionalInfo) {
super();
this.num = num;
this.ingredients = ingredients;
this.recipe = recipe;
this.price = price;
this.nutritionalInfo = nutritionalInfo;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
@Override
public String toString() {
return "Burger number: " + num + " --- " + "Recipe Name: " + recipe + " --- " + "Ingredients: " + ingredients +
" --- " + "Price: $" + price + " --- " + "Nutrional Info: " + nutritionalInfo;
//return "\nIngredients " + ingredients + ", recipe name: " + recipe + ", price: " + price + ", nutritionalInfo: " + nutritionalInfo + ".\n";
}
public String toStringAdOn() {
return "Ad-On number: " + num + " --- " + "Ad-On Name: " + recipe + " --- " +
"Price: $" + price + " --- " + "Nutrional Info: " + nutritionalInfo;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public String getRecipe() {
return recipe;
}
public void setRecipe(String recipe) {
this.recipe = recipe;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getNutritionalInfo() {
return nutritionalInfo;
}
public void setNutritionalInfo(String nutritionalInfo) {
this.nutritionalInfo = nutritionalInfo;
}
public MenuOptions getNext() {
return next;
}
public void setNext(MenuOptions nextOp) {
this.next = nextOp;
}
public MenuOptions clone() {
return new MenuOptions(ingredients, recipe, price, nutritionalInfo);
}
public String toCSV() {
return new String(ingredients + "\n" + recipe + "\n" + price + "\n" + nutritionalInfo);
}
}
<file_sep>package posSystem;
public class searchItem {
//will have the methods needed to search for an specific item
//have an option to look up up to 3 ingredients that match
//or a range of prices
//or by nutrition info
}
<file_sep>package posSystem;
public class cartItems {
private int quantity;
private String name;
private double price;
}
| dd2360fcc333d5ed562d91cb7597b8ce7aa8eb29 | [
"Java"
] | 4 | Java | valesita-coding/posSystem | bce89fb401ec74dab9d7d382092ef2dd5eb11dbe | 661251c2d0fe2158d6bf356789a78a238a6f33ea |
refs/heads/main | <file_sep>import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import Index from './pages/index.vue';
// import Sales from '@pages/sales/index.js';
// import Delivery from '@pages/delivery/index.js';
// import Contacts from '@pages/contacts/index.js';
// import Card from '@pages/card/index.vue';
// import Profile from '@pages/profile/index.vue';
// import Feedback from '@pages/feedback/index.js';
// import E404 from '@pages/404/index.js';
// import E403 from '@pages/403/index.js';
const routes = [
{
path: '/:id',
name: 'main',
component: Index
}
];
export const router = new VueRouter({
routes,
mode: 'history'
});
<file_sep>import Vue from 'vue'
import { router } from '@src/routes.js'
export default {
namespaced: true,
state: {
menu: []
},
getters: {
getMenuItems: state => {
let menuItems = state.menu.map((item)=> {
return {
id: item.id,
title: item.menu_title,
subtitle: item.menu_subtitle
};
});
return menuItems;
},
getPage: state => id => {
let data = state.menu.find( item => item.id == id)
return data;
},
},
mutations: {
setMenu(state, data) {
// отфильтруем повторяющиеся id
let idArray = [];
let dataArray = data.filter( item => {
let isRepeat = idArray.find( id => item.id == id);
if (!isRepeat) {
idArray.push(item.id);
return true;
}
return false;
});
state.menu = dataArray;
router.push({path: '/' + state.menu[0].id})
}
},
actions: {
getData({commit, state}) {
if(state.menu.length < 1) {
let action = 'http://localhost:3000/menu';
let method = 'get';
Vue.http[method](action)
.then(response => response.json())
.then(data => {
commit('setMenu', data);
}, data => {
})
}
}
}
};<file_sep># Инструкция по установке
Клоинруем репозиторий в локальное хранилище
# В корне проекта
npm install
# запустить
json-server --watch db.json
json-server использовался для имметирования бэкенда и базы данных, для демонстрации http-запросов, которые так же являются ассинхронными функциями.
Затем во втором терминале
npm run dev
# build for production with minification
npm run build
```
В json-данных были повторяющиеся страницы ( страница 4 ), поскольку одинаковые id элементов вприцнипе ведут /
за собой множество проблем для приложения,
решил оптимальным вариантом будем фильровать данные по уникальности id и отсеивать повторяющиеся.
Так же полученные данные кладутся в localstorage с целью избежания дальнейших ненужных запросов.
Адаптивной верстке следовало бы уделить больше внимания, но без макета и дизайнерского опыта это может занять приличное время.
В целом постарался показать что знаком с flexbox, брейкпоинтами, медиазапросами и другим аспектам верстки.
На работу потрачено 11 часов.
| e83f64cead87eaca5c67519fd1bcae549dc3de72 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | lednik/telebreeze | e6694c7998a509aa87f677bea5550026c2f56b64 | 412d0554ba6ff4e0dbeecb92cf97b7b068f371dc |
refs/heads/master | <file_sep>using System.Linq;
using System.Threading.Tasks;
namespace Core
{
public class CryptoChecker
{
private const int TIMEOUT_MILLISECONDS = 10 * 1000;
public CryptoChecker(
Configuration config,
CryptoPrices priceService,
Notifications notifications)
{
this.Config = config;
this.PriceService = priceService;
this.Notifications = notifications;
}
private Configuration Config { get; }
private CryptoPrices PriceService { get; }
private Notifications Notifications { get; }
public string Run()
{
var checks = this.Config.CryptoToMonitor();
var tasks = checks.Select(a => ExecuteCheck(a)).ToArray();
Task.WaitAll(tasks, TIMEOUT_MILLISECONDS);
return string.Join("\r\n", tasks.Select(t => t.Result));
}
private async Task<string> ExecuteCheck(string symbol)
{
var price = await this.PriceService.GetAsync(symbol);
if (price == null)
{
return $"{symbol} prices unavailable";
}
var sellTriggered = false;
var buyTriggered = false;
var message = $"{price.Ticker.Base} price: {price.Ticker.Price}";
if (price.Ticker.Price >= this.Config.GetHigh(symbol))
{
sellTriggered = true;
await this.Notifications.NotifyAsync(message);
}
if (price.Ticker.Price <= this.Config.GetLow(symbol))
{
buyTriggered = true;
await this.Notifications.NotifyAsync(message);
}
return $"{price.Ticker.Base} @ {price.Ticker.Price} sell: {sellTriggered}, buy: {buyTriggered}";
}
}
}<file_sep>
using Xunit;
using Amazon.Lambda.TestUtilities;
using System;
namespace MyFunction.Tests
{
public class FunctionTest
{
[Fact]
public void TestToUpperFunction()
{
Environment.SetEnvironmentVariable("topic", "blabla");
Environment.SetEnvironmentVariable(
"config",
@"[{""symbol"":""eth-usd"",""low"":190,""high"":243},{""symbol"":""ltc-usd"",""low"":80,""high"":100}]"
);
// Invoke the lambda function and confirm the string was upper cased.
var function = new Function();
var context = new TestLambdaContext();
var result = function.FunctionHandlerAsync("hello world", context);
Assert.Contains("ETH", result);
Assert.Contains("LTC", result);
}
}
}
<file_sep>using System;
using Amazon.Lambda.Core;
using Core;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace MyFunction
{
public class Function
{
public string FunctionHandlerAsync(object input, ILambdaContext context)
{
var topic = GetEnvironmentVariable("topic");
var configJson = GetEnvironmentVariable("config");
var checker = new CryptoChecker(
new Configuration(configJson),
new CryptoPrices(),
new Notifications(topic)
);
return checker.Run();
}
private string GetEnvironmentVariable(string name)
{
var var = Environment.GetEnvironmentVariable(name);
if (string.IsNullOrEmpty(var))
{
throw new InvalidOperationException("Missing environment variable " + name);
}
return var;
}
}
}
<file_sep>using System.Net.Http;
using Newtonsoft.Json;
namespace Core
{
public class CryptoPrices
{
private static HttpClient _client = new HttpClient();
public async System.Threading.Tasks.Task<Prices> GetAsync(string symbol)
{
var url = $"https://api.cryptonator.com/api/full/{symbol}";
var result = await _client.GetAsync(url);
result.EnsureSuccessStatusCode();
var content = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Prices>(content);
}
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Core
{
public class Configuration
{
private Dictionary<string, LowHigh> _toMonitor;
public Configuration(string configJson)
{
var arr = JsonConvert.DeserializeObject<LowHigh[]>(configJson);
_toMonitor = arr.ToDictionary(a => a.Symbol, a => a);
}
public IEnumerable<string> CryptoToMonitor() => _toMonitor.Keys;
public int GetHigh(string symbol) => _toMonitor[symbol].High;
public int GetLow(string symbol) => _toMonitor[symbol].Low;
private struct LowHigh
{
public LowHigh(string symbol, int low, int high)
{
this.Symbol = symbol;
this.Low = low;
this.High = high;
}
public string Symbol;
public int Low;
public int High;
}
}
}<file_sep>using Newtonsoft.Json;
namespace Core
{
public partial class Prices
{
[JsonProperty("ticker")]
public Ticker Ticker { get; set; }
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("error")]
public string Error { get; set; }
}
public partial class Ticker
{
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("target")]
public string Target { get; set; }
[JsonProperty("price")]
public float Price { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("change")]
public string Change { get; set; }
[JsonProperty("markets")]
public Market[] Markets { get; set; }
}
public partial class Market
{
[JsonProperty("market")]
public string MarketMarket { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
[JsonProperty("volume")]
public double Volume { get; set; }
}
}
<file_sep>using System.Threading.Tasks;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
namespace Core
{
public class Notifications
{
private string _topic;
public Notifications(string topic)
{
this._topic = topic;
}
public async Task NotifyAsync(string message)
{
var request = new PublishRequest
{
TopicArn = _topic,
Message = message
};
var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast1);
await client.PublishAsync(request);
}
}
}<file_sep># Description
This lambda function that pings cryptocurrency price endpoint and sends notice if the price is either above or below a certain threshold. This is useful to let you know when a particular cryptocurrency price is low enough to buy more, or if the price is high enough where a sell could give you a certain return on your previous purchase.
# Cryptocurrency check
api.cryptonator.com is used for cryptocurrency to USD conversion rates.
# Notifications
AWS SNS email notifications are used when price threshold is reached.
# Configuration
- create SNS topic and specify topic as an environment variable "topic" in lambda configuration
- for currency check config, create an environment variable "config" in lambda configuration. Example configuration:
```[{"symbol":"eth-usd","low":190,"high":243},{"symbol":"ltc-usd","low":80,"high":114}]```
The above checks ETH-USD rate and sends notice if the value is either above 243 or below 190. LTC-USD is signalled if the value is below 80 or above 114.
| 7123512eb59509737da8b08f5ae6c23bb880a1be | [
"Markdown",
"C#"
] | 8 | C# | laimis/lambda-test | bfe71d659e4b3ded20c9c6cd508f4a6bce4ad627 | 60cc535d8327534c41f7deb4895d951337e274b0 |
refs/heads/master | <repo_name>NajiYoussef/getalife<file_sep>/cm2019/src/cours01/Animal.java
package cours01;
public class Animal {
public Animal(String species, String name, int age) {
this.species = species;
this.name = name;
this.age = age;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
private String species;
private String name;
private int age;
private double weight;
private double height;
private String color;
public void sleep() {}
public void move() {}
public void eat() {}
public static void main(String[] args) {
Animal felix = new Animal();
felix.name = "felix";
felix.species ="chat";
felix.age = 5 ;
felix.height = 50;
felix.weight =3;
felix.color = "fauve";
Animal milou = new Animal();
milou.name = "milou";
milou.species = "chien";
milou.age =7;
milou.height = 80;
milou.weight= 8;
milou.color="blanc";
}
public Animal() {
}
}
<file_sep>/cm2019/src/cours01/MainLivre.java
package cours01;
public class MainLivre {
Livre livre1 = new Livre("game of thrones","<NAME>",3);
}
<file_sep>/cm2019/src/cours01/Etudiants.java
package cours01;
public class Etudiants {
public Etudiants(String name, String prenom, int number) {
this.name = name;
this.prenom = prenom;
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Etudiants() {
}
private String name;
private String prenom;
private int number;
public static void main(String[] args) {
Etudiants etudiant1 = new Etudiants();
etudiant1.number= 42;
etudiant1.name = "Castiaux";
etudiant1.prenom = "Julien";
Etudiants etudiant2 = new Etudiants ();
etudiant2.number = 3;
etudiant2.name = "Dupont";
etudiant2.prenom = "Jérémy";
}
}
| 9fb8342e4698f69c597e46643eab3898ae07383e | [
"Java"
] | 3 | Java | NajiYoussef/getalife | e52e144edd8ccbb26b24d22b3425477437c40fb2 | 6c9054f2591c23337de8aa6b1a12572857543ff5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.