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>swelty2/TipCalculator<file_sep>/TipCalculator/ViewController.swift // // ViewController.swift // TipCalculator // // Created by Sarah on 9/11/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billValue: UITextField! @IBOutlet weak var tipSegmentValue: UISegmentedControl! @IBOutlet weak var customValue: UISlider! @IBOutlet weak var customValueTextField: UILabel! @IBOutlet weak var billTotal: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. }//end of viewDidLoad() //------------------------ Class Methods @IBAction func tipSelectedSegement(_ sender: UISegmentedControl) { let bill = Double(billValue.text!) if ((bill == nil) || (bill! <= 0)) { print("Error Handler- Bill total is NIL or NEGATIVE") //alert user that first name field is empty let alert = UIAlertController(title: "Error", message: "Bill total must be a positive value (example: 25.67)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) }//end of if else { //now calculate the tip based on segment chosen if (self.tipSegmentValue.selectedSegmentIndex == 0 ) { //tip is 10% let tipPerc = 0.10 self.billTotal.text = String(((tipPerc * bill!) + bill! )) print("Tip% is \(10)") } else if (self.tipSegmentValue.selectedSegmentIndex == 1) { let tipPerc = 0.15 self.billTotal.text = String(((tipPerc * bill!) + bill! )) print("Tip% is \(15)") } else if (self.tipSegmentValue.selectedSegmentIndex == 2 ) { let tipPerc = 0.18 self.billTotal.text = String(((tipPerc * bill!) + bill!)) print("Tip% is \(18)") } else if (self.tipSegmentValue.selectedSegmentIndex == 3) { //self.billTotal.text = String((tipPerc * bill!)) self.customValueTextField.text = String((customValue!.value * 100)) } } } @IBAction func sliderChanged(_ sender: UISlider) { self.customValueTextField.text = String(Int((customValue!.value * 100)) ) + " %" } /* let currentValue = Int(sender.value) self.customValueTextField.text = "\(currentValue)" */ /* @IBAction func billTotalValueChanged(_ sender: UITextField) { //Check that bill total is positive & not nil //unwrap bill total user input field let billTotal = Double(billValue.text!) // Check that input is numerical and is a positive val if (billTotal! <= 0) { //alert user that bill value is not a positive value let alert = UIAlertController(title: "Error", message: "Bill Total Must Be A Positive Number", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) }//end of if if (billTotal == nil) { //alert user that first name field is empty let alert = UIAlertController(title: "Error", message: "Input Bill Total", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } print("User successfully entered Bill Total") } */ //Slider Control Logic }
a5ad32a3b2f53718b15cde9c7ed7b1a8747a6e11
[ "Swift" ]
1
Swift
swelty2/TipCalculator
74ccb0efb49639c0ecbc49839eed64e6e0d3a7e6
288590bdd1cf8f7c7b1ef8c54047c80b1a2200b8
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; public class GameSettingsEditor : EditorWindow { public enum SettingsType { Player, Weapon } private SettingsType settingsType; private float playerSpeed; private float fireRate; private float bulletSpeed; private Impulse impulse; [MenuItem("Game Settings/Player")] public static void OpenPlayerSettings() { var window = (GameSettingsEditor)GetWindow(typeof(GameSettingsEditor)); PlayerSettings settings = Resources.Load<PlayerSettings>("PlayerSettings"); if (settings != null) { window.playerSpeed = settings.PlayerSpeed; } window.settingsType = SettingsType.Player; window.Show(); } [MenuItem("Game Settings/Weapon")] public static void OpenWeaponSettings() { var window = (GameSettingsEditor)GetWindow(typeof(GameSettingsEditor)); WeaponSettings settings = Resources.Load<WeaponSettings>("WeaponSettings"); if (settings != null) { window.fireRate = settings.FireRate; window.bulletSpeed = settings.BulletSpeed; window.impulse = settings.ImpactImpulse; } window.settingsType = SettingsType.Weapon; window.Show(); } private void OnGUI() { switch (settingsType) { case SettingsType.Player: DrawPlayerSettings(); break; case SettingsType.Weapon: DrawWeaponSettings(); break; } } private void DrawPlayerSettings() { GUILayout.Space(5); GUILayout.Label("Player Settings", EditorStyles.boldLabel); GUILayout.Space(5); EditorGUILayout.LabelField(new GUIContent("Speed:")); playerSpeed = EditorGUILayout.FloatField(playerSpeed); if (GUILayout.Button("Save")) { var settings = ScriptableObject.CreateInstance<PlayerSettings>(); settings.PlayerSpeed = playerSpeed; SaveAsset(settings, "PlayerSettings"); } } private void DrawWeaponSettings() { GUILayout.Space(5); GUILayout.Label("Weapon Settings", EditorStyles.boldLabel); GUILayout.Space(5); EditorGUILayout.LabelField(new GUIContent("Fire Rate:")); fireRate = EditorGUILayout.FloatField(fireRate); GUILayout.Space(5); EditorGUILayout.LabelField(new GUIContent("Bullet Speed:")); bulletSpeed = EditorGUILayout.FloatField(bulletSpeed); GUILayout.Space(5); EditorGUILayout.LabelField(new GUIContent("Impact Impulse:")); EditorGUI.indentLevel += 1; EditorGUILayout.LabelField(new GUIContent("Weak")); impulse.Weak = EditorGUILayout.FloatField(impulse.Weak); EditorGUILayout.LabelField(new GUIContent("Medium")); impulse.Medium = EditorGUILayout.FloatField(impulse.Medium); EditorGUILayout.LabelField(new GUIContent("Strong")); impulse.Strong = EditorGUILayout.FloatField(impulse.Strong); EditorGUI.indentLevel -= 1; if (GUILayout.Button("Save")) { var settings = ScriptableObject.CreateInstance<WeaponSettings>(); settings.FireRate = fireRate; settings.BulletSpeed = bulletSpeed; settings.ImpactImpulse = impulse; SaveAsset(settings, "WeaponSettings"); } } private void SaveAsset(ScriptableObject asset, string assetName) { string settingsDir = "Assets/Settings/Resources/"; string folderDir = Application.dataPath + "/Settings/Resources/"; if (!Directory.Exists(folderDir)) Directory.CreateDirectory(folderDir); AssetDatabase.CreateAsset(asset, settingsDir + assetName + ".asset"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [Serializable] public struct Impulse { public float Weak; public float Medium; public float Strong; } public class WeaponSettings : ScriptableObject { public float FireRate; public float BulletSpeed; public Impulse ImpactImpulse; } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerInput : MonoBehaviour { private bool isPaused = false; private CursorSettings cursorSettings; private void Start() { Time.timeScale = 1f; } public bool Quit() { return Input.GetKeyDown(KeyCode.Escape); } public bool EnterCombatState() { return Input.GetKeyDown(KeyCode.Return); } public bool GetMoveInput() { return Input.GetMouseButton(0); } public float GetHorizontal() { return Input.GetAxis("Mouse X"); } public float GetVertical() { return Input.GetAxis("Mouse Y"); } public bool GetFireInput() { return Input.GetMouseButton(0); } public bool GetFireInputUp() { return Input.GetMouseButtonUp(0); } public bool GetFireInputDown() { return Input.GetMouseButtonDown(0); } public void PauseGame() { if (isPaused) { Time.timeScale = 1; Cursor.lockState = cursorSettings.LockState; Cursor.visible = cursorSettings.IsVisible; } else { Time.timeScale = 0; cursorSettings.IsVisible = Cursor.visible; cursorSettings.LockState = Cursor.lockState; Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } isPaused = !isPaused; } } public struct CursorSettings { public CursorLockMode LockState; public bool IsVisible; } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; [Serializable] public enum BulletImpulse { Weak, Medium, Strong } public class Weapon : MonoBehaviour { public Transform Muzzle; public Projectile ProjectilePrefab; public float SpreadAngle = 0f; public BulletImpulse Impulse; private float impulse; private float fireRate; private float bulletSpeed; private float currentInterval; private void Start() { LoadWeaponSettings(); } public void HandleShoot() { if (currentInterval >= fireRate) { float angle = SpreadAngle / 180f; Vector3 spreadDirection = Vector3.Slerp(Muzzle.forward, Random.insideUnitSphere, angle); Projectile projectile = Instantiate(ProjectilePrefab, Muzzle.position, Quaternion.LookRotation(spreadDirection)); projectile.Shoot(bulletSpeed, impulse); currentInterval = 0; } currentInterval += Time.deltaTime; } private void LoadWeaponSettings() { var settings = Resources.Load<WeaponSettings>("WeaponSettings"); switch (Impulse) { case BulletImpulse.Weak: impulse = settings.ImpactImpulse.Weak; break; case BulletImpulse.Medium: impulse = settings.ImpactImpulse.Medium; break; case BulletImpulse.Strong: impulse = settings.ImpactImpulse.Strong; break; } bulletSpeed = settings.BulletSpeed; fireRate = settings.FireRate; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { public LayerMask HittableLayers = -1; public float GravityDownAcceleration = 0.1f; public float Radius = 0.01f; public float ImpactLife = 1f; public GameObject ImpactParticlePref; private Vector3 velocity; private Vector3 lastPosition; private float impactImpulse; private void Update() { this.transform.position += velocity * Time.deltaTime; if (GravityDownAcceleration > 0) velocity += Vector3.down * GravityDownAcceleration * Time.deltaTime; Vector3 direction = this.transform.position - lastPosition; RaycastHit[] hits = Physics.SphereCastAll(lastPosition, Radius, direction.normalized, direction.magnitude, HittableLayers, QueryTriggerInteraction.Collide); foreach (var hit in hits) OnHit(hit.point, hit.normal, hit.collider); lastPosition = this.transform.position; } public void Shoot(float speed, float impulse) { velocity = this.transform.forward * speed; impactImpulse = impulse; } private void OnHit(Vector3 point, Vector3 normal, Collider collider) { var damageable = collider.GetComponentInParent<IDamageable>(); if (damageable == null) return; damageable.OnDamage(); var rgbodie = collider.GetComponent<Rigidbody>(); if (rgbodie != null) rgbodie.AddForceAtPosition(velocity * impactImpulse, point + normal); if (ImpactParticlePref != null) { GameObject impactParticles = Instantiate(ImpactParticlePref, point + normal, Quaternion.LookRotation(normal)); if (ImpactLife > 0) Destroy(impactParticles.gameObject, ImpactLife); } Destroy(this.gameObject); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Collider))] public class Tower : MonoBehaviour { public float VisibilityDistance = 100; private void OnTriggerEnter(Collider other) { if (other.tag == "Player") { var enemies = FindObjectsOfType<ZombieAI>(); foreach (var enemy in enemies) { if (Vector3.Distance(other.transform.position, enemy.transform.position) < VisibilityDistance) { Tips.Instance.ShowTip("There are enemies. Press \"Enter\" button to enter in combat state. To quit combat state press that button again." + "\n Sorry for the vision from the tower :3"); } } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using DG.Tweening; using UnityEngine; using UnityEngine.SceneManagement; [RequireComponent(typeof(CanvasGroup))] public class MainUI : MonoBehaviour { private PlayerInput playerInput; private CanvasGroup canvasGroup; private bool isOpen = false; private void Start() { playerInput = FindObjectOfType<PlayerInput>(); canvasGroup = this.GetComponent<CanvasGroup>(); } private void Update() { if (playerInput.Quit()) { Show(); } } public void Show() { if (isOpen) { playerInput.PauseGame(); canvasGroup.DOFade(0, 0.5f); canvasGroup.interactable = false; } else { canvasGroup.DOFade(1, 0.5f).OnComplete(() => playerInput.PauseGame()); canvasGroup.interactable = true; } isOpen = !isOpen; } public void Restart() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerSettings : ScriptableObject { public float PlayerSpeed; } <file_sep>using System; using System.Collections; using System.Collections.Generic; using Cinemachine; using UnityEngine; using UnityEngine.AI; public enum PlayerState { Travel, Combat } [RequireComponent(typeof(PlayerInput), typeof(Animator), typeof(NavMeshAgent))] public class PlayerController : MonoBehaviour { public LayerMask InteractionLayers = -1; public Weapon WeaponPrefab; public Transform WeaponSocket; public Transform Spine; public Transform AimCamera; public CinemachineVirtualCameraBase VirtualCamera; public GameObject Crosshair; public Vector2 VerticalClamp = new Vector2(-30f, 40f); public float RotationSpeed = 1f; public float CameraYCorrection = 70f; private PlayerInput playerInput; private Animator animator; private NavMeshAgent agent; private Camera cam; private float verticalAngle; private float horizontalAngle; private float spineAngleCorrection = 10f; private Weapon weapon; public PlayerState CurrentPlayerState { get; private set; } = PlayerState.Travel; public float CurrentSpeed => agent.velocity.magnitude; private void Start() { playerInput = this.GetComponent<PlayerInput>(); animator = this.GetComponent<Animator>(); agent = this.GetComponent<NavMeshAgent>(); cam = Camera.main; weapon = Instantiate(WeaponPrefab, WeaponSocket); LoadPlayerSettings(); } private void Update() { if (playerInput.EnterCombatState()) { CurrentPlayerState = CurrentPlayerState == PlayerState.Travel ? PlayerState.Combat : PlayerState.Travel; SwitchPlayerState(); } if (CurrentPlayerState == PlayerState.Combat) { HandleFireInput(); } } private void LateUpdate() { switch (CurrentPlayerState) { case PlayerState.Travel: HandleMovingInput(); break; case PlayerState.Combat: HandleAimingInput(); break; } } private void LoadPlayerSettings() { var settings = Resources.Load<PlayerSettings>("PlayerSettings"); agent.speed = settings.PlayerSpeed; } private void SwitchPlayerState() { if (CurrentPlayerState == PlayerState.Combat) { animator.SetLayerWeight(1, 1); VirtualCamera.Priority += 1; Crosshair.SetActive(true); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } else { animator.SetLayerWeight(1, 0); VirtualCamera.Priority -= 1; Crosshair.SetActive(false); Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } } private void HandleAimingInput() { verticalAngle -= playerInput.GetVertical() * RotationSpeed * Time.deltaTime; verticalAngle = Mathf.Clamp(verticalAngle, VerticalClamp.x, VerticalClamp.y); horizontalAngle = playerInput.GetHorizontal() * RotationSpeed * Time.deltaTime; Spine.localEulerAngles = new Vector3(verticalAngle + spineAngleCorrection, 0, 0); this.transform.Rotate(Vector3.up, horizontalAngle); AimCamera.transform.Rotate(Vector3.up, horizontalAngle); AimCamera.localEulerAngles = new Vector3(verticalAngle, this.transform.eulerAngles.y - CameraYCorrection, 0); if (Physics.Raycast(cam.ViewportPointToRay(new Vector3(0.5f, 0.5f)), out var hit, float.PositiveInfinity, InteractionLayers)) weapon.Muzzle.LookAt(hit.point); } private void HandleMovingInput() { if (playerInput.GetMoveInput()) { Ray ray = cam.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out var hit, float.PositiveInfinity, InteractionLayers)) agent.SetDestination(hit.point); } animator.SetFloat("Speed", CurrentSpeed); } private void HandleFireInput() { if (playerInput.GetFireInputDown()) animator.SetBool("Firing", true); if (playerInput.GetFireInput()) weapon.HandleShoot(); if (playerInput.GetFireInputUp()) animator.SetBool("Firing", false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; [RequireComponent(typeof(NavMeshAgent))] public class ZombieAI : MonoBehaviour, IDamageable { public float WalkRadius = 15f; public float MinSpeed = 0.5f; public float MaxSpeed = 5f; private NavMeshAgent agent; private Animator animator; private Vector3 destination; private float velocity; private float animationSpeed; private Coroutine walkCoroutine; public float AgentSpeed => agent.velocity.magnitude; private void Start() { agent = this.GetComponent<NavMeshAgent>(); animator = this.GetComponent<Animator>(); walkCoroutine = StartCoroutine(StartWalking()); } private void Update() { animationSpeed = Mathf.SmoothDamp(animationSpeed, AgentSpeed, ref velocity, 0.5f); animator.SetFloat("Speed", animationSpeed); } private IEnumerator StartWalking() { Vector3 point = Random.insideUnitSphere * WalkRadius; point += transform.position; if (NavMesh.SamplePosition(point, out var hit, WalkRadius, 1)) { destination = hit.position; agent.SetDestination(destination); } agent.speed = Random.Range(MinSpeed, MaxSpeed); while (this.transform.position != destination) { yield return null; } walkCoroutine = StartCoroutine(StartWalking()); } public void OnDamage() { animator.enabled = false; agent.speed = 0f; if (walkCoroutine != null) StopCoroutine(walkCoroutine); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using DG.Tweening; using TMPro; using UnityEngine; [RequireComponent(typeof(CanvasGroup))] public class Tips : MonoBehaviour { public TextMeshProUGUI Text; [Range(0f, 20f)] public float TimeToShow = 10f; [Range(0f, 5f)] public float FadeTime = 1.5f; [Range(0f, 500f)] public float MoveDistance = 100f; private CanvasGroup canvasGroup; private float yPos; public static Tips Instance { get; private set; } private void Start() { canvasGroup = this.GetComponent<CanvasGroup>(); yPos = this.transform.position.y; if (Instance == null) Instance = this; else Destroy(this.gameObject); ShowTip("There are some zombies around that can eat you. Be careful!!!\nNo. They're just walking around, you can shoot them by pressing \"Enter\" button."); } public void ShowTip(string text) { Text.text = text; StopAllCoroutines(); StartCoroutine(ShowUI()); } private IEnumerator ShowUI() { canvasGroup.DOFade(1, FadeTime); this.transform.position = new Vector3(this.transform.position.x, yPos - MoveDistance, this.transform.position.z); float endValue = yPos; this.transform.DOMoveY(endValue, FadeTime); yield return new WaitForSeconds(TimeToShow); canvasGroup.DOFade(0, FadeTime); endValue = yPos + MoveDistance; this.transform.DOMoveY(endValue, FadeTime); } }
29db94be62c9b72089deb297c6947159a4047d64
[ "C#" ]
11
C#
MemphisNyasha/ShooterProject
a695933b9176fc0c1c73300ebf5c80f348d5934f
c0218a4d09f6c24f0df7ab2d9368ec8b11de4015
refs/heads/master
<file_sep>import java.io.File; public class Test { public Test() { Runtime r = Runtime.getRuntime(); try { File moduleFile = new File (Test.class.getProtectionDomain() .getCodeSource().getLocation().toURI()); String dir = System.getProperty("user.dir"); r.exec("cmd.exe /c cd "+dir+" & start cmd.exe /K \"" + "java -cp "+moduleFile.getName()+" Main\""); } catch (Exception e){ System.out.println(e.toString()); } } public static void main(String[] args) { new Test(); } } <file_sep># AB Jar Generator > Generate JAR easy way ### How to 1. Masukkan program dalam satu folder (didrive D aja) bersama dengan source java (biar rapi) 2. Lalu buat file config.txt, diisi dengan nama class yang akan dicompile, Main class ditaruh paling atas, disave lalu close 3. Lalu jalankan program, dan file jar sudah dibuatkan ### Note: - Untuk package, tulis diconfig dengan format berikut: package/Class, atau package/* Tapi untuk baris awal, gk boleh ada *, karena direserve untuk main class - MyJar.jar - standard - ForWindows.jar - bisa langsung muncul consolenya untuk di Windows (Java yang belum GUI gk bisa langsung executable klu double klik MyJar.jar) (Kalau javanya sudah GUI, pakai yg MyJar.jar uda bisa executable) ### JANGAN DIHAPUS untuk : - Test.java (Untuk buat ForWindows.jar) - config.txt ### TAMBAHAN : - Jalanin JAR java -jar namajar.jar By AB13-0
0ff54e64f3c10e958425ea40acea2d655ca4e146
[ "Markdown", "Java" ]
2
Java
bluejack13/ab-jar-generator
5a8bceed7e3dc8a1cbc7379a71a6aa796fa03ef7
7eeb01f78cc98c5db14c0ec6962eb0ce5d412296
refs/heads/master
<file_sep>package com.rabbitmq.fanout; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.rabbitmq.RabbitMQApplication; @SpringBootTest(classes=RabbitMQApplication.class) @RunWith(SpringJUnit4ClassRunner.class) public class RabbitFanoutTest { @Autowired private AmqpTemplate rabbitTemplate; @Test public void sendPengleiTest() { String context = "此消息在,广播模式或者订阅模式队列下,有 FanoutReceiver1 FanoutReceiver2 可以收到"; //routekey可以是任何,但是必须要有,exchange也是 String routeKey = "text"; //"topic.penglei.net"; String exchange = "fanoutExchanges"; System.out.println("sendPengleiTest : " + context); context = "context:" + exchange + ",routeKey:" + routeKey + ",context:" + context; //只需要自定义一个叫exchange就行 this.rabbitTemplate.convertAndSend(exchange, "", context); } } <file_sep>package com.rabbitmq.fanout; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @RabbitListener(queues="xiaoxiong.harry") public class FanoutReceiver1 { @RabbitHandler public void process(String message) { System.out.println("接收者 FanoutReceiver1," + message); } }
43380fdaf52b55c1ce6650c004b0e29bc9fa8fe0
[ "Java" ]
2
Java
XiaoXiongPotter/RabbitMQ
4d4ed746bc30e66dd040a9f44d59beaee839c067
78d2784d3350771576d0f737b9414f614863eac8
refs/heads/main
<file_sep>package com.myjava; public class EmployeeAttendence { public static void main(String[] args) { System.out.println("Welcome to Employee Wage Computation"); int wagPerHrs = 20; int workingHours; int totalWorkingHours = 0; int totalDays = 0; int counterForPresentFullTime=0; int counterForPresentHalfTime=0; int totalSalary = 0; while( totalDays <= 19 && totalWorkingHours <= 100) { totalDays++; int employWorkingTime = (int)(Math.random() *3); switch(employWorkingTime) { case 1: workingHoursc= 8; counterForPresentFullTime = counterForPresentFullTime + workingHours; if(counterForPresentFullTime == 100) { totalWorkingHours = 100; } break; case 2: workingHours = 4; counterForPresentHalfTime = counterForPresentHalfTime + workingHours; if(counterForPresentHalfTime == 100 ) { totalWorkingHours = 100; } break; default: workingHours = 0; break; } } System.out.println("the days" +totalDays); System.out.println("the total working hours " +totalWorkingHours); if( totalDays == 20 ) { totalSalary= wagPerHrs * counterForPresentFullTime * totalDays; System.out.println("employee for full time salery "+totalSalary); totalSalary= wagPerHrs * counterForPresentHalfTime * totalDays; System.out.println("employee for half time salery "+totalSalary); } else { totalSalary = wagPerHrs * totalWorkingHours; System.out.println("employee for full time salery "+totalSalary); totalSalary = wagPerHrs * totalWorkingHours ; System.out.println("employee for half time salery "+totalSalary); } } }
a7aa2f84277d479bb4a7f9aee873fb611666d43d
[ "Java" ]
1
Java
shaileshdubeyr/Employee
fe08d0873bbc053d45c41ca5ce5a9cfa73c23cd1
be93ef87d06ebbef57ccf47d1a9dc97c36b15d25
refs/heads/master
<repo_name>mmaci/vutbr-fit-bio-cgp-image-filters<file_sep>/src/main.cpp #include <iostream> #include "cgp.cuh" int main(int32 argc, char** argv) { std::string filename, refFilename, methodname, kerneltype; // default values are set here imcgp::FitnessMethod method = imcgp::MDPP; uint32 numRuns = 1, numMutations = 5, numGenerations = 30000, numPopulation = 5, numInputs = CGP_PARAM_INPUTS_3X3; uint32 opts = 0; for (int32 i = 1; i < argc; ++i) { // input image if ((std::string(argv[i]) == "-i" || std::string(argv[i]) == "--input") && i + 1 < argc) { filename = argv[++i]; } if ((std::string(argv[i]) == "-r" || std::string(argv[i]) == "--reference") && i + 1 < argc) { refFilename = argv[++i]; } if ((std::string(argv[i]) == "-m" || std::string(argv[i]) == "--method") && i + 1 < argc) { methodname = argv[++i]; if (methodname == "mdpp") method = imcgp::MDPP; else if (methodname == "psnr") method = imcgp::PSNR; else if (methodname == "mse") method = imcgp::MSE; } if ((std::string(argv[i]) == "-k" || std::string(argv[i]) == "--kernel") && i + 1 < argc) { kerneltype = argv[++i]; if (kerneltype == "3x3") numInputs = CGP_PARAM_INPUTS_3X3; else if (kerneltype == "5x5") numInputs = CGP_PARAM_INPUTS_5X5; } if ((std::string(argv[i]) == "-R" || std::string(argv[i]) == "--runs") && i + 1 < argc) { numRuns = atoi(argv[++i]); } if ((std::string(argv[i]) == "-M" || std::string(argv[i]) == "--mutations") && i + 1 < argc) { numMutations = atoi(argv[++i]); } if ((std::string(argv[i]) == "-g" || std::string(argv[i]) == "--generations") && i + 1 < argc) { numGenerations = atoi(argv[++i]); } if ((std::string(argv[i]) == "-p" || std::string(argv[i]) == "--population") && i + 1 < argc) { numPopulation = atoi(argv[++i]); } if (std::string(argv[i]) == "-v" || std::string(argv[i]) == "--verbose") { opts |= imcgp::OPT_VERBOSE; } if (std::string(argv[i]) == "-C" || std::string(argv[i]) == "--cuda") { opts |= imcgp::OPT_CUDA_ACCELERATION; } if (std::string(argv[i]) == "-c" || std::string(argv[i]) == "--csv") { opts |= imcgp::OPT_OUTPUT_CSV; } } if (filename.empty()) { std::cerr << "Unspecified input image." << std::endl; return EXIT_FAILURE; } if (refFilename.empty()) { std::cerr << "Unspecified reference image." << std::endl; return EXIT_FAILURE; } imcgp::CGPWrapper cgp; cgp.set_options(opts); if (cgp.load_image(filename, imcgp::ORIGINAL_IMAGE) && cgp.load_image(refFilename, imcgp::REFERENCE_IMAGE)) { bool result = cgp.run(method, numRuns, numGenerations, numPopulation, numMutations, numInputs); if (!result) { std::cerr << "Error occured while running evolution." << std::endl; return EXIT_FAILURE; } } else { std::cerr << "Cannot load file." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <file_sep>/src/cgp_enums.h /** * @file cgp_enums.h * @brief CGP structures. * * Used structures are held here. * * @author <NAME> <<EMAIL>> */ #ifndef H_CGP_ENUMS #define H_CGP_ENUMS #include <vector> #include <chrono> /////////////////////////////////////////////////////////////// // Typedefs /////////////////////////////////////////////////////////////// typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef char int8; typedef short int16; typedef int int32; typedef std::chrono::duration<double, std::ratio<1, 1000000000>> Ticks; /////////////////////////////////////////////////////////////// // Defines /////////////////////////////////////////////////////////////// /** @brief Number of CGP rows. */ #define CGP_PARAM_ROWS 6 /** @brief Number of CGP columns. */ #define CGP_PARAM_COLS 6 /** @brief Number of inputs. Should be 9 because of a 3x3 image kernel. */ #define CGP_PARAM_INPUTS_3X3 9 /** @brief Number of inputs. Should be 25 because of a 5x5 image kernel. */ #define CGP_PARAM_INPUTS_5X5 25 /** @brief Number of outputs. Should be 1 because of a single pixel output. */ #define CGP_PARAM_OUTPUTS 1 /** @brief Distance between columns, we can choose candidates from. */ #define CGP_PARAM_LBACK 1 /** @brief inputs + rows*cols + ouputs */ #define CGP_PARAM_TOTAL_3X3 46 /** @brief inputs + rows*cols + ouputs */ #define CGP_PARAM_TOTAL_5X5 62 /** @brief rows * cols * (func_inputs + 1) + outputs */ #define CGP_CHROMOSOME_SIZE 109 /////////////////////////////////////////////////////////////// // Functions & Methods /////////////////////////////////////////////////////////////// /// Image CGP wrapper. namespace imcgp { /////////////////////////////////////////////////////////////// // Enums /////////////////////////////////////////////////////////////// /** @brief Run options. */ enum Options { OPT_VERBOSE = 0x00000001, OPT_MEASURE = 0x00000002, OPT_CUDA_ACCELERATION = 0x00000004, OPT_OUTPUT_CSV = 0x00000008 }; /** @brief Functions used to design a filter. */ enum Function { FUNC_CONST, ///< 255 FUNC_IDENTITY, ///< in1 FUNC_INVERT, ///< 255 - in1 FUNC_OR, ///< in1 | in2 FUNC_AND, ///< in1 & in2 FUNC_NAND, ///< ~(in1 & in2) FUNC_XOR, ///< in1 ^ in2 FUNC_SHR1, ///< in1 >> 1 FUNC_SHR2, ///< in1 >> 2 FUNC_SWAP, ///< in2 FUNC_ADD, ///< max(in1 + in2, 255) FUNC_AVERAGE, ///< (in1 + in2) >> 1 FUNC_MAX, ///< max(in1, in2) FUNC_MIN, ///< min(in1, in2) FUNC_SHL1, ///< in1 << 1 FUNC_SHL2, ///< in1 << 2 NUM_FUNCTIONS ///< total number of functions }; /** @brief Types of images used. */ enum ImageType { ORIGINAL_IMAGE, REFERENCE_IMAGE, FILTERED_IMAGE, MAX_IMAGE_TYPES }; /** @brief Represents a chromosome. * * mod 0, 1 values represent inputs * mod 2 values represent function * last value represents output */ struct Chromosome { uint32 val[CGP_CHROMOSOME_SIZE]; }; /** @brief An array of chromosomes, representing a population. */ typedef std::vector<Chromosome> Population; const float ERROR_FITNESS = -1.f; ///< Fitness error. const int32 ERROR_FILTER = -1; ///< Filter error. /** @brief Different methods how to calculate fitness. */ enum FitnessMethod { MDPP, ///< Mean difference per pixel PSNR, ///< Peak signal-to-noise ratio MSE, ///< Mean square error NUM_FITNESS_METHODS }; /** @brief A structure to simplify saving run stats. */ struct Statistics { std::string input_file; std::string reference_file; Chromosome best_filter; float fitness; double total_time, average_gen_time, init_time; Population initial_population; uint32 num_generations, num_genes_mutated, population_size, num_inputs; FitnessMethod method; }; } #endif // H_CGP_ENUMS <file_sep>/README.md # Imcgp Imcgp (Image CGP) is a library and a tool for evolutionary design of image filters improving the quality of damaged images using Cartesian Genetic Programming. It is originally a semester project at <a href="http://www.fit.vutbr.cz/">BUT FIT</a> for <a href="http://www.fit.vutbr.cz/study/course-l.php?id=9884">BIN</a>. ## What's inside? * C++ CGP library * CUDA accelerated CGP library * MSVC project to build your own executable * Results and measurements ## How to build? *Requirements:* CUDA 6.5, OpenCV 2.4.*, Microsoft Visual Studio 2013 * Open the solution: bio-image-filters-cuda.sln in msvc folder * C/C++ > Additional Include Directories : set to your OpenCV include directory * Linker > Additional Library Directories : set to your OpenCV lib directory * Linker > Input > Additional Dependencies : add all needed OpenCV libs * CUDA should somehow manage on it's own if you have CUDA Toolkit installed (CUDA 7.0 propably won't work due to OpenCV dependency on CUDA 6.5) * When everything is set up, the solution can be normally built. ## How to use the executable? The executable supports several configuration options: * -i --input [filename] Input image. (required) * -r --reference [filename] Reference image. (required) * -m --method [name] Fitness method used. Options: mdpp (default), psnr, mde * -R --runs [number] Number of runs (default: 1). * -M --mutations)[number] Number of mutations inside the chromosome (default: 5). * -g --generations [number] Number of generations (default: 30000). * -p --population [number] Population count inside a generation (default: 5). * -k --kernel [kernel type] Type of kernel to use. Options: 3x3 (default), 5x5 * -v --verbose Verbose output. * -C --cuda Use CUDA acceleration. * -c --csv Output fitness values per generation inside a CSV file. ## Other information ### Documentation Doxygen-generated documentation can be found on: <a href="http://imcgp.maciste.cz">http://imcgp.maciste.cz</a> or you can generate ### Contributing The whole project is under construction and is only a school project, therefore there are still a lot of TODOs and a lot less spare time. If you are interested in this topic, would like to contribute or have anything else on mind, you can contact me at <a href="mailto:<EMAIL>"><EMAIL></a> or via github. In case you would like to use it, feel free to do so, only add some form of an acknowledgement. I would also be happy to help, if it would lead to something useful. <file_sep>/src/CMakeLists.txt project(IMCGP) cmake_minimum_required(VERSION 2.8) set(WBD_VERSION_MAJOR 1) set(WBD_VERSION_MINOR 0) # --------------------------------------------- # LIBRARIES # --------------------------------------------- # OPENCV if (WIN32) # if you have custom build OpenCV and use WIN, set it here set(OpenCV_DIR "C:/dev/libs/opencv249/build32") else () set(OpenCV_DIR "/usr/lib/opencv") endif () find_package(OpenCV REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) # CUDA find_package(CUDA REQUIRED) SET(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-O3 -gencode arch=compute_30,code=sm_30) # --------------------------------------------- # --------------------------------------------- # Sources file(GLOB local_sources *.cpp *.h *.cuh *.cu) set (IMCGP_SOURCES ${local_sources}) cuda_add_executable(imcgp ${IMCGP_SOURCES}) target_link_libraries(imcgp ${OpenCV_LIBS}) # --------------------------------------------- # --------------------------------------------- # Install options if (WIN32) set(INSTALL_DIR ${PROJECT_BINARY_DIR}/../bin) else () # whatever options you want endif () install(TARGETS imcgp DESTINATION ${INSTALL_DIR}) # ---------------------------------------------
99affd9b600605935fd591ad5281cab2eaf64c18
[ "Markdown", "CMake", "C++" ]
4
C++
mmaci/vutbr-fit-bio-cgp-image-filters
e40b2f66d40f1f1e9eec2e7ae85297dd64a8ae2e
90827313b184be3cd1cf652c0c7af625ff57d591
refs/heads/master
<repo_name>QuasiData/PongMultiplayer<file_sep>/game.py import socket import math import threading from network_utils import update_game, send_paddle, send_ball from colorama import Fore, init import pygame as pg init() class Game: """ A game object. Handles all logic for the game """ def __init__(self, screen_rect: pg.Rect, fps: int, ip: str = '', port: int = 5050, host: bool = True): self.fps = fps self.host = host if host: self.ip = socket.gethostbyname(socket.gethostname() + ".local") else: self.ip = ip self.port = port self.screen_rect = screen_rect self.paddle = Paddle(screen_rect[3], (screen_rect.width / 20, screen_rect.height / 5), [0, (screen_rect.height / 2)], fps) self.other_paddle = Paddle(screen_rect[3], (screen_rect.width / 20, screen_rect.height / 5), [screen_rect.width - screen_rect.width / 20, (screen_rect.height / 2)], fps) self.ball = Ball(screen_rect[2], (screen_rect.center[0], screen_rect.center[1]), fps) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if host: self.socket.bind((self.ip, port)) self.connection = None else: self.connection = self.socket self.update_thread = None def update(self): """ Updates the state of all actors in the game """ self.ball.move() self.upper_bound() if self.bounds(): send_ball(self, self.connection) if self.bounce(): vel = self.ball.velocity + 0.1 if vel > self.paddle.width: vel = self.paddle.width - self.paddle.width / 10 self.ball.velocity = vel send_ball(self, self.connection) send_paddle(self, self.connection) def bounds(self): """ Checks if a players has won the game and updates the ball Returns(bool): True if current game won """ if self.ball.pos_x < 0: print(f"{Fore.RED}You lost that round!") return True elif self.ball.pos_x > self.screen_rect[2]: print(f"{Fore.GREEN}You won that round!") self.ball.pos_x = self.screen_rect[2] / 2 self.ball.pos_y = self.screen_rect[3] / 2 self.ball.dir_x = 1 self.ball.dir_y = 0 self.ball.velocity = 0.2 return True return False def upper_bound(self): """ Checks if ball hit the top or bottom of the screen and changes its direction accordingly """ if self.ball.pos_y < 0 or self.ball.pos_y > self.screen_rect[3]: self.ball.dir_y = -self.ball.dir_y def bounce(self): """ Checks if ball has collided with the games paddle and changes its direction accordingly Calculates an angle between -60 and 60 depending on how far from center the ball is Returns(bool): True if collision is detected """ collide = self.paddle.rect.collidepoint(self.ball.pos_x, self.ball.pos_y) if collide: angle = (self.ball.pos_y - self.paddle.rect.centery) / (self.paddle.height / 2) * 60 self.ball.dir_x = math.cos(math.radians(angle)) self.ball.dir_y = math.sin(math.radians(angle)) return True return False def start(self): """ Starts the game by connecting the sockets Host waits for a connection from another game If not host connects to host """ if self.host: print(f"{Fore.CYAN}Server is starting...") self.socket.listen() print(f"{Fore.CYAN}Server is listening on {Fore.YELLOW + self.ip}...") conn, addr = self.socket.accept() print(f"{Fore.YELLOW}{addr} {Fore.CYAN}connected\n{Fore.YELLOW}") self.connection = conn else: print(f"{Fore.CYAN}Connecting to server at {Fore.YELLOW}{self.ip}") try: self.socket.connect((self.ip, self.port)) except TimeoutError: print(f"{Fore.CYAN}Connection timed out. (Server might not be running)") quit() # Make the ball start moving self.ball.dir_x = -1 self.update_thread = threading.Thread(target=update_game, args=(self, self.connection), daemon=True) self.update_thread.start() def stop(self): # self.socket.shutdown(socket.SHUT_RDWR) # self.socket.close() # quit() # Not currently implemented # Meant to be a graceful exit and reset colorama pass class Paddle: """ A paddle object. Keeps track of data concerning paddles """ def __init__(self, field_height: int, size: tuple, position: list, fps: int): self.field_height = field_height self.width, self.height = size self.position = position self.fps = fps self.rect = pg.Rect(self.position[0], self.position[1] - int(self.height / 2), self.width, self.height) def move(self, direction: int): """ Moves the paddle an amount of pixels based on the games field size and fps Args: direction(int): 1 for up and -1 for down """ if self.rect.centery - (self.height / 2) < 0 and direction == 1: pass elif self.rect.centery + (self.height / 2) > self.field_height and direction == -1: pass elif direction == 1: self.rect.centery -= math.ceil((float(self.height) / float(self.fps)) * 2) elif direction == -1: self.rect.centery += math.ceil((float(self.height) / float(self.fps)) * 2) class Ball: """ A ball object. Keeps track of data concerning the ball """ def __init__(self, field_width: int, position: tuple, fps: int, direction: tuple = (0, 0), velocity: float = 0.2): self.field_width = field_width self.pos_x, self.pos_y = position self.fps = fps self.dir_x, self.dir_y = direction self.velocity = velocity def move(self): """ Move the ball an amount of pixels based on the game field size and fps """ self.pos_x += self.dir_x * self.velocity * self.field_width / self.fps self.pos_y += self.dir_y * self.velocity * self.field_width / self.fps <file_sep>/main.py from app import main import argparse parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-b', '--bind', help='Binds the socket to this ip. Acts as host for game', action='store_true') group.add_argument('-ip', '--address', help='Ip address of the host', type=str) parser.add_argument('-p', '--port', help='Port to connect to', type=int, required=True) args = parser.parse_args() main(host=args.bind, port=args.port, ip=args.address) <file_sep>/network_utils.py import threading from colorama import Fore from socket import socket from typing import TYPE_CHECKING if TYPE_CHECKING: from game import Game def read_payload(payload): # Kind of a meh function currently if len(payload.split(",")) > 1: return 'ball' def update_game(game: Game, conn: socket): """ Receives updates about the ball and paddle of the other game. Runs on a separate thread. Args: game(Game): Current Game object conn(socket): The socket the game is connected to """ connected = True while connected: try: header = conn.recv(32).decode("utf-8") if header: length = header.split(" ")[0] payload = conn.recv(int(length)).decode('utf-8') if read_payload(payload) == 'ball': payload = payload.strip('()') data = payload.split(',') pos_x, pos_y, dir_x, dir_y, vel = [float(x) for x in data] data = game.screen_rect[2] - pos_x, pos_y, -dir_x, dir_y, vel game.ball.pos_x, game.ball.pos_y, game.ball.dir_x, game.ball.dir_y, game.ball.velocity = data else: game.other_paddle.rect.centery = int(payload) except ConnectionAbortedError or ConnectionResetError as e: print(f"{Fore.RED}{e}") connected = False game.stop() def send_paddle(game: Game, conn: socket): """ Sends the y position of the paddle to the other game Args: game(Game): Current Game object conn(socket): The socket the game is connected to """ try: y = game.paddle.rect.centery payload = f"{y}".encode('utf-8') arg = f"{len(payload)}".encode('utf-8') header = arg + b" " * (32 - len(arg)) msg = header + payload conn.sendall(msg) except (ConnectionAbortedError, ConnectionResetError) as e: print(f"{Fore.RED}{e}") game.stop() def send_ball(game: Game, conn: socket): """ Sends the position, direction and velocity of the ball to the other game Args: game(Game): Current Game object conn(socket): The socket the game is connected to """ try: pos_x, pos_y = game.ball.pos_x, game.ball.pos_y dir_x, dir_y = game.ball.dir_x, game.ball.dir_y vel = game.ball.velocity payload = f"{pos_x,pos_y,dir_x,dir_y,vel}".encode('utf-8') arg = f"{len(payload)}".encode('utf-8') header = arg + b" " * (32 - len(arg)) msg = header + payload conn.sendall(msg) except (ConnectionAbortedError, ConnectionResetError) as e: print(f"{Fore.RED}{e}") game.stop() <file_sep>/README.md # PongMultiplayer A pong game for 2 players connected over sockets. # Packages Pygame is used to make the gui of the game `pip install pygame` # Usage ``` python main.py [-h] (-b | -ip ADDRESS) -p PORT requiered arguments: -b, --bind Binds the socket to this ip. Acts as host for game or -ip, --address Ip address of the host -p, --port Port to connect to optional arguments: -h, --help show this help message and exit ``` <file_sep>/app.py import sys import pygame as pg from game import Game SCREEN_SIZE = (810, 810) BACKGROUND = pg.Color("black") FPS = 60 class App: """ An App object. Keeps track of data concerning the flow of the game and initialises a Game """ def __init__(self, host: bool, port: int, ip: str): self.screen = pg.display.get_surface() self.screen_rect = self.screen.get_rect() self.clock = pg.time.Clock() if host: self.game = Game(screen_rect=self.screen_rect, fps=FPS, port=port, host=host) else: self.game = Game(screen_rect=self.screen_rect, fps=FPS, ip=ip, port=port, host=host) self.game.start() self.prev_paddle_rect = None self.prev_other_paddle_rect = None self.prev_ball_pos = None self.first_loop = True self.done = False def draw(self): """ Draws the paddles and ball and copies their position """ pg.draw.rect(self.screen, (255, 255, 255), self.game.paddle.rect) pg.draw.rect(self.screen, (255, 255, 255), self.game.other_paddle.rect) pg.draw.circle(self.screen, (255, 255, 255), (int(self.game.ball.pos_x), int(self.game.ball.pos_y)), 20) self.prev_paddle_rect = self.game.paddle.rect.copy() self.prev_other_paddle_rect = self.game.other_paddle.rect.copy() self.prev_ball_pos = (int(self.game.ball.pos_x), int(self.game.ball.pos_y)) def update(self): """ Updates all actors in game and moves paddles based on key held """ keys = pg.key.get_pressed() if keys[pg.K_e]: self.game.paddle.move(1) elif keys[pg.K_d]: self.game.paddle.move(-1) self.game.update() def render(self): """ Uses method draw to draw everything on the screen and update it """ if self.first_loop: self.screen.fill(BACKGROUND) self.draw() else: pg.draw.rect(self.screen, (0, 0, 0), self.prev_paddle_rect) pg.draw.rect(self.screen, (0, 0, 0), self.prev_other_paddle_rect) pg.draw.circle(self.screen, (0, 0, 0), self.prev_ball_pos, 20) self.draw() pg.display.update() def event_loop(self): """ Handles single key presses and events """ for event in pg.event.get(): if event.type == pg.QUIT: self.done = True def main_loop(self): """ Main loop for the game """ while not self.done: self.event_loop() self.update() self.render() self.clock.tick(FPS) if self.first_loop: self.first_loop = False self.game.stop() def main(host: bool, port: int, ip: str): """ Initialises pygame and screen. Creates an App object and calls its main_loop method Args: host(bool): True if this App should act as host port(int): The port of the connection ip(str): IP address to connect to if not host """ pg.init() pg.display.set_mode(SCREEN_SIZE) if host: pg.display.set_caption("HOST") else: pg.display.set_caption("CLIENT") App(host, port, ip).main_loop() pg.quit() sys.exit()
48cfdb75475b219f1ff72e58019091ea4ba10e8b
[ "Markdown", "Python" ]
5
Python
QuasiData/PongMultiplayer
8478c8c42d68ea1c5513451cd3226490aa2d1836
e6e6c19840cff529d3a57e6a3da0533e165a4be0
refs/heads/master
<repo_name>CullynMillar/Kubernetes_Basics<file_sep>/README.md # LearnKubernetes This project is run through setting up Kubernetes with a basic Docker image running a node js web application. This will include the following: * Vagrant script for spinning up a development environment including a docker install * Dockerfile for creating an image and spinning up Docker containers in Kubernetes * YAML files for the Kubernetes setup and testing * Node.js raw code for the Docker image <file_sep>/Vagrant Files/provision.sh #! /bin/bash sudo apt-get update # install Docker Community Edition onto the dev environment to compile docker images #Install dependencies for Docker-CE repo to be usable sudo apt install apt-transport-https ca-certificates curl software-properties-common #Add the Docker GPG key curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - #Verify the GPG key sudo apt-key fingerprint 0EBFCD88 #Add the stable docker repo sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" #Install Docker-CE sudo apt-get install docker-ce docker-ce-cli containerd.io -y #Install NodeJS for the NodeJS application compilation automation sudo apt install nodejs -y #create test account sudo adduser --home /home/test_account --disabled-password #expire password to force change on next login sudo passwd --expire test_account #add in private and public key generation for vagrant ssh sudo ssh-keygen -f test_account #add in github pull below and copy command to /home/test_account #put in password set thing<PASSWORD> here?<file_sep>/Vagrant Files/Vagrantfile VAGRANT_COMMAND = ARGV[0] Vagrant.configure("2") do | config | if VAGRANT_COMMAND == "ssh" config.ssh.username = "test_account" end config.vm.box = "ubuntu/bionic64" config.vm.hostname = "Docker-NodeJS-Dev-Environment" config.vm.provision "shell", path: "provision.sh" config.vm.provider "virtualbox" do |v| v.name = "Docker_Host" v.memory = 3000 config.vm.network "forwarded_port", guest: 80, host: 8080 end end
322b7cbcac5cb8c1cba742a409316cecc3c3c7ae
[ "Markdown", "Ruby", "Shell" ]
3
Markdown
CullynMillar/Kubernetes_Basics
22ece402a3e02c77ec7c5dbd552c6740cd6f7d3b
772b9eb7718a557e40f3073f6b73b9b7ad6e578e
refs/heads/master
<file_sep><?php $welcomeheading=null; $debuggingloginlink=null; $signuplink=null; if($user=="customer"){ $welcomeheading="Customer Login"; $debuggingloginlink="../../php/customercontent/customeroverview.php"; $signuplink="../../php/customercontent/customer-registration.php"; } if($user=="restaurant"){ $welcomeheading="Restaurant Login"; $debuggingloginlink="../../php/restaurantcontent/restaurantoverview.php"; $signuplink="../../php/restaurantcontent/restaurant-registration.php"; } if($user=="default"){ //TODO: double check that this is a valid case $welcomeheading=""; $debuggingloginlink=""; $signuplink=""; } ?> <section id="login-section"> <div class="container text-center" id="login-container" > <div class="row row-centered"> <div class="col-sm-5 panel panel-default col-centered " id="login-panel"> <div class="panel-header text-center"> <h1><?php echo$welcomeheading;?></h1></div> <div class="panel-body"> <form action="/" method="POST" role="form"> <div class="form-group"> <label class="sr-only" for="username">Username:</label> <input type="text" class="form-control" name="username" id="username" placeholder="Username"/> <label class="sr-only" for="password">Password:</label> <input type="<PASSWORD>" class="form-control" name="password" id="password" placeholder="<PASSWORD>"/> </div> <div id="forgotpass"><a href='#'>Forgot Password?</a> </div> <div id="loginsign-up">New to J3Foods? <!-- Deciding whether to redirect to customer registration page or restaurant registration page --> <a <?php echo " href='".$signuplink."' "; ?> >Sign up</a> <?php if($user=="customer"){ $guestbutton="<button class='btn btn-sm btn-default ' /> Enter as a Guest</button>"; echo $guestbutton; } ?> </div> </div> <div class="sign-up "> </div> <a <?php if (isset($debuggingloginlink)) { echo "href='".$debuggingloginlink."'"; } //adding an attribute ?> > <div class="login-btn btn btn-lg btn-primary center-block btn-block" />Log In</div> <!-- //:TODO a href is only here for debugging until login starts working using php to redirect when pressing the login button to help debuggin --> </a> </form> </div> </div> </div><!-- container ---> </div> </div> </section> <file_sep><?php require("../../head.php"); ?> <body> <?php require("../../php/customercontent/customertopbar.php"); ?> <?php require("../../php/customercontent/customeroverview-content.php"); ?> <script> $(function() { }); </script> </body> <footer> <?php require("../../php/footer/footer.php"); ?> </footer> </html> <file_sep><?php require("head.php"); ?> <?php require("/php/topbar/topbar_logged.php"); ?> <body> <?php require("profile-content.php"); ?> <script> $(function() { }); </script> </body> <?php require("php/footer/footer.php"); ?> </html> <file_sep><?php class DatabaseConnection{ //----------------------------------------------------- // Variables //----------------------------------------------------- public $db_connection; //----------------------------------------------------- // Variables //----------------------------------------------------- //================================================================================ // STATIC FUNCTIONS BEGINS //================================================================================ //============================================================ // STATIC FUNCTIONS //================================================================================ // ============================================================ // DB CONNECTION FUNCTIONS BEGINS //================================================================================ /*dbConnect connects to the database and returns a boolean indicating the connection result */ function dbConnect() { $host = "localhost"; $user = "username"; $pass = "<PASSWORD>"; $database = "j3delivery"; // Create connection $conn = new mysqli($host, $user, $pass, $database); $this->db_connection = $conn; return ($conn->connect_errno == NULL) ? TRUE : FALSE; }//dbConnect /*dbClose closes the mysqli connection*/ function dbClose() { if($this->checkConnection()){ $thread_id = $this->db_connection->thread_id; $this->db_connection->kill($thread_id); $this->db_connection->close(); $this->db_connection = NULL; } }//dbClose /*checkConnection returns true if the mysqli connection is active, false otherwise*/ function checkConnection() { if(!$this->db_connection) return FALSE; if($this->db_connection == NULL) return FALSE; if($this->db_connection->connect_error){ return FALSE; } else { return TRUE; } }//checkConnection /*destructor closes the connection if it is still open*/ function __destruct() { if($this->checkConnection()) $this->dbClose(); }//desctuctor // ============================================================ // DB CONNECTION FUNCTIONS //================================================================================ } <file_sep><?php require("../../head.php"); ?> <body> <?php require("../../php/customercontent/customertopbar.php"); ?> <div class="container"> <div class="row"> <div class="col-sm-12"> <h1>Confirmation Page</h1> <div class="list-group"> <div class="list-group-item "> <h4 class="list-group-item-heading">Order details</h4> <div class="table-responsive"><!-- Start table container --> <table class="table table-condensed table-bordered"> <tbody> <tr> <td>1x</td> <td>Super Burger. Sauce Option: Garlic</td> <td>$8.00</td> </tr> <tr> <td>1x</td> <td>Super Burger. Sauce Option: Garlic</td> <td>$8.00</td> </tr> <tr> <td>1x</td> <td>Super Burger. Sauce Option: Garlic</td> <td>$8.00</td> </tr> <tr> <td>1x</td> <td>Super Burger. Sauce Option: Garlic</td> <td>$8.00</td> </tr> </tbody> </table> </div><!-- End table container --> </div> <div class="list-group-item "> <h4 class="list-group-item-heading">Price </h4> <div class="table-responsive"><!-- Start table container --> <table class="table table-condensed table-bordered"> <tbody> <tr> <td>Subtotal</td> <td>$32</td> </tr> <tr> <td>Tax</td> <td>$4</td> </tr> <tr> <td>Total Purchases</td> <td>$36</td> </tr> <tr> <td>Minimum Order Fee</td> <td>$7</td> </tr> </tbody> </table> </div><!-- End table container --> </div> <div class="list-group-item text-right" id="confirm-page-btn"> <div class="btn btn-default btn-lg" data-toggle="modal" data-target="#confirmation-result">Order</div> </div> </div> </div> </div> </div> <!-- container--> <!-- Modal --> <div id="confirmation-result" class="modal fade" role="dialog"> <div class="modal-dialog modal-sm"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <p>Order Successfully Processed</p> </div> <div class="modal-footer"> <a href="../../php/customercontent/customeroverview.php"><button type="button" class="btn btn-default" >Return</button></a> </div> </div> </div> </div> <script> $(function() {}); </script> </body> <footer> <?php require("../../php/footer/footer.php"); ?> </footer> </html> <file_sep><?php require("../../head.php"); ?> <body> <?php require("../../php/topbar/topbar_logged.php"); ?> <?php require("../../php/restaurantcontent/restaurantnav.php"); ?> <?php require("../../php/restaurantcontent/restaurantoverview-content.php"); ?> <?php require("../../php/restaurantcontent/orderdropdown.php"); ?> <?php require("../../php/footer/footer.php"); ?> <script> $(function() { $("#restaurantnavlink-orders").addClass("active"); $('[data-toggle="tooltip"]').tooltip(); }); </script> </body> </html> <file_sep><section id="restaurant-header"> <div id="restaurant-hdrcontainer" class="container"> <div class="row"> <div id="rhdr-left" class="col-sm-3"> <img src="../../images/logoplaceholder.PNG" /> </div> <div id="rhdr-center" class="col-sm-6 text-center"> <div id="avgrating"> <span id="avgrating-emptystar" class="glyphicon glyphicon-star-empty"></span> <span id="avgrating-star" class="glyphicon glyphicon-star"></span> </div> </div> <div id="rhdr-right" class="col-sm-3"> <a data-toggle="collapse" data-target="#shopping-cart"><span class="glyphicon glyphicon-shopping-cart" id="rhdr-shoppingicon" data-toggle="tooltip" title="Click to show Shopping Cart"></span></a> <?php //TODO: add a popover to explain what the button does clicking activates a popoutmenu ?> <div id="rhdr-info"> <p> <span class="glyphicon glyphicon-map-marker"></span> Tim Street </p> <p> <span class="glyphicon glyphicon-earphone"></span> 905-356-6899 </p> <p> <span class="glyphicon glyphicon-envelope"></span> <EMAIL> </p> <p> <span class="glyphicon glyphicon-globe"></span> www.burgergrill.com </p> </div> </div> </div> </div> <hr /> </section> <file_sep><div id="history-content-container" class="container table-responsive"> <table class="highchart table table-condensed table-bordered" data-graph-container-before="1" data-graph-type="column"> <thead> <tr> <th>Month</th> <th>Sales</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>8000</td> </tr> <tr> <td>February</td> <td>12000</td> </tr> <tr> <td>March</td> <td>12000</td> </tr> <tr> <td>April</td> <td>12000</td> </tr> </tbody> </table> </div> <file_sep><?php require("../../head.php"); ?> <body> <?php require("../../php/customercontent/customertopbar.php"); ?> <section id="profile-section"> <div class="container text-center" id="profile-container" > <div class="row row-centered"> <div class="col-sm-5 panel panel-default col-centered " id="profile-panel"> <div class="panel-header center-block"> <?php require("../../php/customercontent/customer-profile-contentbar.php"); ?> </div> <div class="panel-body"> <form action="/" method="POST" role="form"> <div class="form-group"> <!-- List group --> <ul class="list-group"> <li class="list-group-item"> Duncan Street <button type="button" class="close" data-dismiss="modal">&times; <div class="row"> <div class="row"> </div> <div class="row"> </div> </div> </button></li> <li class="list-group-item">Tim Street <button type="button" class="close" data-dismiss="modal">&times;</button></li> <li class="list-group-item">Morbi leo risus <button type="button" class="close" data-dismiss="modal">&times;</button></li> <li class="list-group-item">Porta ac consectetur ac <button type="button" class="close" data-dismiss="modal">&times;</button></li> <li class="list-group-item">Vestibulum at eros <button type="button" class="close" data-dismiss="modal">&times;</button></li> </ul> </div> <div class="btn btn-primary " /><span class="glyphicon glyphicon-plus"></span>New Address</div> </form> </div> </div> </div><!-- container ---> </div> </div> </section> <script> $(function() { $("#cpcontent-addresses").addClass("active"); }); </script> </body> <footer> <?php require("../../php/footer/footer.php"); ?> </footer> </html> <file_sep> <?php $pageTitle="J3 Foods - Online Food Ordering"; require("head.php"); //TODO: everytime we include head.php we have to set a pageTitle test commit ?> <body> <?php require("/php/topbar/topbar.php"); ?> <?php require("/landingpage-content.php"); ?> </body> <?php require("php/footer/footer.php"); ?> </html> <file_sep><?php include('head.php'); ?> <body> <main id="wrap"> <div id="topbar"><div class="container"> <div id="topbar-logo"><a href="./index.php"></a></div> <h1>ABOUT US</h1> </div></div> <section id="inner-page"> <div class="container"> Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500'lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960'larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur. </div> </section> </main> <?php require("php/footer/footer.php"); ?> </body> </html> <file_sep><?php $pageTitle= "Login"; require("../../head.php"); ?> <body> <?php require("../../php/topbar/topbar.php"); ?> <?php $user=null; if (isset($_GET["user"])) { if ($_GET["user"] == "customer") { $user="customer"; } elseif ($_GET["user"] == "restaurant") { $user= "restaurant"; } } else{ $user= "default"; //no login value specified } require("login-content.php"); ?> <script>$(function() { });</script> </body> <?php require("../../php/footer/footer.php"); ?> </html> <file_sep><?php require("../../head.php"); ?> <body> <?php require("../../php/topbar/topbar_logged.php"); ?> <?php require("../../php/restaurantcontent/restaurantnav.php"); ?> <?php require("../../php/customercontent/menu-overview-content.php"); ?> <script> $(function() { $("#restaurantnavlink-menu").addClass("active"); $('[data-toggle="tooltip"]').tooltip(); }); </script> </body> <footer> <?php require("../../php/footer/footer.php"); ?> </footer> </html> <file_sep><footer > <div class="container-fluid" id="footer"> <div class="row"> <div class="f-content"> <div class="f-copy">Copyright &copy; 2016 - <?php echo date("Y"); ?> <a href="http://www.j3foods.com">j3foods.com</a></div> <ul class="f-subnav"> <li><a href="./about.php">About us</a></li> <li><a href="./privacy.php">Privacy Policy</a></li> <li><a href="./terms.php">Terms &amp; Conditions</a></li> <li><a href="./help/index.html">Help</a></li> </ul> </div> </div> </div> </footer> <file_sep><div id="topbar-logged" class="topbar"> <nav class="navbar topbar-loggednav navbar-default navbar-fixed-top "> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="http://localhost/J3Foods/php/customercontent/customeroverview.php"> <span class="glyphicon glyphicon-road"></span> J3 Delivery </a> </div> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <form class="navbar-form" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-search"></span> </button> </form> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span>Categories</span> <span class="caret"></span></a> </a> <ul class="dropdown-menu"> <li><a href="#">Chicken</a></li> <li><a href="#">Pizza</a></li> <li><a href="#">Pasta</a></li> </ul> </li> <li> <a href="#" > <span class="glyphicon glyphicon-shopping-cart"></span><?php //TODO: add a popover to explain what the button does clicking activates a popoutmenu ?> </a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="glyphicon glyphicon-user"></span> <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Welcome</a></li> <li><a href="../../php/customercontent/customer-profile-editprofile.php">Edit Profile</a></li> <li><a href="#">Help</a></li> <li class="separator"> </li> <li><a href="http://localhost/J3Foods/index.php#">Logout</a></li> </ul> </li> </li> </ul> </div> </div> </nav> </div> <file_sep><?php require("head.php"); ?> <body> <?php require("/php/topbar/topbar_logged.php"); ?> <?php require("/php/topbar/subbar.php"); ?> <section id="overview-section"> <div class="overview-container"> <div class="row overview-content"> <div class="col-md-6" "> <img src="images/placeholder.jpg" alt="..." class="img-rounded center-block img-responsive" id="overview-mainimg"> </div> <div class="col-md-6" "> <div class="list-group"> <li class="list-group-item"> <div class="media"> <div class="media-left"> <a href="#"> <img class="media-object " src="images/placeholderuser.png" alt="..."> </a> </div> <div class="media-body"> <h4 class="media-heading">Media heading</h4> <p> Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500'lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960'larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur. </p> </div> </div> </li> <li class="list-group-item"> <div class="media"> <div class="media-left"> <a href="#"> <img class="media-object" src="images/placeholderuser.png" alt="..."> </a> </div> <div class="media-body"> <h4 class="media-heading">Media heading</h4> <p> Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500'lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960'larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur. </p> </div> </div> </li> <li class="list-group-item"> <div class="media"> <div class="media-left "> <a href="#"> <img class="media-object" src="images/placeholderuser.png" alt="..."> </a> </div> <div class="media-body"> <h4 class="media-heading">Media heading</h4> <p> Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500'lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960'larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur. </p> </div> </div> </li> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="card card-block"> <h1 class="card-title">Create an Order</h1> <p class="card-text">Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500'lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960'larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur.</p> <a href="http://localhost/J3Foods/createorder.php" class="btn btn-primary btn-block">Create</a> </div> </div> <div class="col-md-6"> <div class="card card-block"> <h1 class="card-title">View Groups</h1> <p class="card-text">Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500'lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960'larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur.</p> <a href="http://localhost/J3Foods/viewgroups.php" class="btn btn-primary btn-block">View</a> </div> </div> </div> </div> </section> <?php require("php/footer/footer.php"); ?> <script> $(function() { $("#subbarlink-home").addClass("active"); }); </script> </body> </html> <file_sep><?php $pageTitle= "Customer Sign Up"; require("../../head.php"); ?> <body> <?php require("../../php/topbar/topbar.php"); ?> <?php require("customer-registration-content.php"); ?> <script>$(function() { });</script> </body> <?php require("../../php/footer/footer.php"); ?> </html> <file_sep><div id="menu-overview-content-container" class="container"> <?php require("../../php/customercontent/restaurant-header.php"); ?> <?php require("../../php/customercontent/menu-specials.php"); ?> <?php require("../../php/customercontent/menu-appetizers.php"); ?> <?php require("../../php/customercontent/menu-mains.php"); ?> </div> <file_sep><?php $root = "/J3Foods"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1.0, shrink-to-fit=no'/> <meta http-equiv='x-ua-compatible' content='ie=edge'/> <!--Title Define the title for each page by creating a pageTitle variable before each inclusion of head.php that value is echoed here --> <title> <?php echo $pageTitle; ?> </title> <!-- CSS --> <link rel='stylesheet' type='text/css' href="<?php echo $root; ?>/css/reset.css" /> <link rel="stylesheet" type='text/css' href="<?php echo $root; ?>/css/jquery-ui.min.css"> <link rel="stylesheet" type='text/css' href="<?php echo $root; ?>/css/jquery-ui.structure.min.css"> <link rel="stylesheet" type='text/css' href="<?php echo $root; ?>/css/jquery-ui.theme.min.css"> <link rel="stylesheet" type='text/css' href="<?php echo $root; ?>/css/bootstrap.min.css"> <link rel="stylesheet" type='text/css' href="<?php echo $root; ?>/css/bootstrap-theme.min.css"> <link rel="stylesheet" type='text/css' href="<?php echo $root; ?>/css/font-awesome.min.css"> <link rel="stylesheet" type='text/css' href="<?php echo $root; ?>/css/style.css"/> <!-- javascript --> <script src="<?php echo $root; ?>/js/jquery-1.12.0.min.js"></script> <script src="<?php echo $root; ?>/js/jquery-ui.min.js"></script> <script src="<?php echo $root; ?>/js/bootstrap.min.js"></script> <script src="<?php echo $root; ?>/js/highcharts.js"></script> <script src="<?php echo $root; ?>/js/jqueryhighchartTable-min.js"></script> <script src="https://code.highcharts.com"></script> </head> <file_sep><?php require("../../head.php"); ?> <body> <?php require("../../php/customercontent/customertopbar.php"); ?> <section id="profile-section"> <div class="container text-center" id="profile-container" > <div class="row row-centered"> <div class="col-sm-5 panel panel-default col-centered " id="profile-panel"> <div class="panel-header center-block"> <?php require("../../php/customercontent/customer-profile-contentbar.php"); ?> </div> <div class="panel-body"> <form action="/" method="POST" role="form"> <div class="form-group"> <div class="input-row row"> <label class="sr-only" for="email">Email:</label> <input type="text" class="form-control" name="email" id="email" placeholder="Email"/> </div> <div class="input-row row"> <label class="sr-only" for="firstname">Firstname:</label> <input type="text" class="form-control" name="firstname" id="firstname" placeholder="First Name"/> </div> <div class="input-row row"> <label class="sr-only" for="lastname">Last Name:</label> <input type="text" class="form-control" name="lastname" id="lastname" placeholder="Last Name"/> </div> <div class="input-row row"> <label class="sr-only" for="phonenumber">Phone Number:</label> <input type="text" class="form-control" name="phoneno" id="phoneno" placeholder="Phone Number"/> </div> <div class="input-row row"> <div class="btn btn-default" data-toggle="collapse" data-target="#changepassword">Change Password?</div> <div id="changepassword" class="collapse input-row"> <div class="row"> <div class="col-sm-4"> <label class="sr-only" for="password">Password:</label> <input type="<PASSWORD>" class="form-control" name="password" id="password" placeholder="<PASSWORD>"/> </div> <div class="col-sm-4"> <label class="sr-only" for="password">Password:</label> <input type="<PASSWORD>" class="form-control" name="password" id="password" placeholder="<PASSWORD>"/> </div> </div> </div> </div> </div> <div class="login-btn btn btn-lg btn-primary center-block btn-block" />Save Changes</div> </form> </div> </div> </div><!-- container ---> </div> </div> </section> <script> $(function() { $("#cpcontent-profile").addClass("active"); }); </script> </body> <footer> <?php require("../../php/footer/footer.php"); ?> </footer> </html>
77308c37020e053914225dc7acb740ac46f80dd4
[ "PHP" ]
20
PHP
ds12rb/J3Delivery
77e1c9b5670b1748de9a69a7653b5fad218e4714
6e342ae7d27dcfbedd41dd65a00858ca6e3d03f3
refs/heads/main
<repo_name>igorivanov0988/Notes-app<file_sep>/src/components/list/index.js import React, { Component } from 'react'; import NoteCard from '../noteCard'; import "./styles.css"; class List extends Component { render() { const { notes, editNote, deleteNote } = this.props; const cards = notes.map((note, index) => { return ( <NoteCard key={index} index={index} note={note} editNote={editNote} deleteNote={deleteNote} /> ); }); const sortCard = cards.sort((item1, item2) => item1.props.note.selectCategory > item2.props.note.selectCategory ? 1 : -1) return ( <div className="card_container"> {sortCard} </div> ); } } export default List;<file_sep>/src/App.js import React, {Component} from "react"; import './App.css'; import Header from "./components/header"; import Note from "./components/note"; import List from "./components/list"; class App extends Component { constructor(props) { super(props); this.state = { showNote: false, editNote: {}, categories: JSON.parse(localStorage.getItem('categories')) || [], labels: JSON.parse(localStorage.getItem('labels')) || [], notes: JSON.parse(localStorage.getItem('notes')) || [], }; } toggleNote = () => { this.setState({ showNote: ! this.state.showNote, editNote: {}, }) } toggleEditNote = () => { this.setState({ showNote: ! this.state.showNote, }) } createNewCategory = (category) => { const {categories} = this.state this.setState({categories: [...categories, category]}) localStorage.setItem('categories', JSON.stringify([...categories, category])) } createNewLabel = (label) => { const {labels} = this.state this.setState({labels: [...labels, label]}) localStorage.setItem('labels', JSON.stringify([...labels, label])) } saveNote = (note) => { const {notes} = this.state this.setState({notes: [...notes, note]}) localStorage.setItem('notes', JSON.stringify([...notes, note])) this.toggleNote() } editNote = (note) => { this.setState({editNote: note}) this.toggleEditNote() } deleteNote = (id) => { const {notes} = this.state let delNote = notes.filter((note) => note.id !== id) this.setState(() => ({notes: delNote})) localStorage.setItem('notes', JSON.stringify([...delNote])) } changeNote = (note) => { const {notes} = this.state let searchNote = notes.findIndex(elem => elem.id === note.id) notes[searchNote] = note localStorage.setItem('notes', JSON.stringify([...notes])) this.toggleNote() } render(){ const { showNote, notes, categories, labels, editNote } = this.state; return ( <div className="App"> <div> <Header toggleNote={this.toggleNote} showNote={showNote}/> </div> <div> { showNote ? <Note createNewCategory={this.createNewCategory} listCategory={categories} editNote={editNote} createNewLabel={this.createNewLabel} listLabels={labels} saveNote={this.saveNote} changeNote={this.changeNote} /> : <List notes={notes} editNote={this.editNote} deleteNote={this.deleteNote} /> } </div> </div> ); }} export default App; <file_sep>/src/config/colors.js export const Colors = [ {value: 'blue', label: 'blue', color: '#184a7a'}, {value: 'white', label: 'white', color: '#fff'}, {value: 'gray', label: 'gray', color: '#8C8C8C'}, {value: 'lightBlue', label: 'lightBlue', color: '#5B93FC'}, {value: 'red', label: 'red', color: '#D6041D'}, {value: 'green', label: 'green', color: '#029311'}, {value: 'yellow', label: 'yellow', color: '#FFB200'}, {value: 'pink', label: 'pink', color: '#F73893'}, ] <file_sep>/src/components/noteCard/index.js import React, { Component } from 'react'; import "./styles.css"; class NoteCard extends Component { render() { const {note, editNote, deleteNote} = this.props const labels = note.selectLabel return( <div style={{backgroundColor: note.selectColor}} className="noteCardContainer"> <div className="noteCardTitle"> <div className="titleText"> {note.nameNote} </div> </div> <div className="propertiesContainer"> <div> {note.selectCategory} </div> <div> {labels.map(item => item.label)} </div> </div> <div className="noteCardContent"> <div className="textNote"> {note.textNote} </div> </div> <div className="buttonCardContainer"> <div> <button className="buttonCard" onClick={() => editNote(note)}> <text className="buttonTextCard">Edit Note</text> </button> </div> <div> <button className="buttonCard" onClick={() => deleteNote(note.id)}> <text className="buttonTextCard">Delete Note</text> </button> </div> </div> </div> ); } } export default NoteCard;<file_sep>/src/config/defaultLabel.js export const defaultLabel = ['Label1', 'Label2', 'Label3']
cb422cfa276e98a29bcf51c497745e99783471aa
[ "JavaScript" ]
5
JavaScript
igorivanov0988/Notes-app
a9a75a5967462c8f2f6c066e8eb751dc331e9a77
c976bee2eebd5d461d1b746f84a6a4e139903fc7
refs/heads/master
<file_sep># Numerical Methods Numerical Algorithms that solve mathematical problems in a variety of ways through the use of java code <file_sep>public class NumericalDiff { public static double func(double x){ return Math.log(x); //return (6 * Math.pow(x, 2) + 2)/(2 * x); } public static double forwardDiff(double x, double h){ return (func(x+h) - func(x))/h; } public static double backwardsDiff(double x, double h){ return (func(x)- func(x-h))/h; } public static double centerDiff(double x, double h){ return (func(x+h)-func(x-h))/(2*h); } public static double secondCenter(double x, double h){ return (func(x+h) + func(x-h) - (2*func(x)))/(Math.pow(h, 2)); } }<file_sep>public class DiffDriver { public static void main(String[] args) { double h[] = new double[15]; for(int i=0; i<h.length; i++){ h[i] = Math.pow(10, -(i+1)); } PrintDiff(h, 1); } public static void PrintDiff(double[] h, double x){ System.out.println("Forward \t \tBackwards \t \tCenter \t \t\tSecondCenter"); for(int i=0; i<h.length; i++){ System.out.print(NumericalDiff.forwardDiff(x,h[i]) + "\t"); System.out.print(NumericalDiff.backwardsDiff(x,h[i]) + "\t"); System.out.print(NumericalDiff.centerDiff(x,h[i]) + "\t"); System.out.print(NumericalDiff.secondCenter(x,h[i]) + "\n"); } System.out.println(); } } //output lines from 10^-1 next line 10^-2 <file_sep>import java.io.*; public class IntegrateDriver { public static void main(String[] args) throws IOException{ double[] traps = new double[100]; for(int i=0; i<100; i++) traps[i] = -1; readFile(traps); double a = 0, b = 2; int n = 2048; int j = 16; traps = Integrate.TrapOpti(a, b, 32, traps); //System.out.println(traps[31]); double[][] R = Integrate.Romberg(traps, 6); for(int i=0; i<6; i++){ for(int k=0; k<6; k++){ if(R[i][k] == -1){ System.out.print("x.xxxxxxxxxxxxxxxx\t"); } else{ System.out.format("%.16f", R[i][k]); System.out.print(" \t"); } } System.out.println(); } //Integrate.PrintIntegral(a,b,n); if(!writeFile(traps)){ System.out.println("Error writing to file."); System.exit(1); } } public static double[] readFile(double[] traps) throws NumberFormatException, IOException{ BufferedReader fr = null; try { fr = new BufferedReader(new FileReader("/Users/albertrodriguez/Documents/VS/Integration/traps.txt")); } catch (FileNotFoundException e) { System.out.println("File Not found"); System.exit(1); } int count = 0; String line; while((line = fr.readLine()) != null){ traps[count] = Double.parseDouble(line); count++; } fr.close(); return traps; } public static boolean writeFile(double[] traps) throws IOException{ BufferedWriter fw; try { fw = new BufferedWriter(new FileWriter("/Users/albertrodriguez/Documents/VS/Integration/traps.txt")); } catch (IOException e) { e.printStackTrace(); return false; } int writeCount = 0; while(traps[writeCount] != -1){ fw.write(Double.toString(traps[writeCount])); if(traps[writeCount+1] != -1){ fw.newLine(); } writeCount++; } fw.close(); return true; } }
7276905e02e4ccef2c59ee51a33bc340e4c9db23
[ "Markdown", "Java" ]
4
Markdown
aRodriguez96/Numerical-Methods
41bb0967132c6ea511ceb5cc2beb5c3fa264db6b
65da151fc230175cd35f698e3335cd791e45571e
refs/heads/master
<file_sep>using System.Collections; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed = 6f; Vector3 movement; Animator anim; Rigidbody playerRB; int floorMask; float camRayLength = 100f; float buffDuration; bool isBuffed = false; private void Awake() { floorMask = LayerMask.GetMask("Floor"); anim = GetComponent<Animator>(); playerRB = GetComponent<Rigidbody>(); } private void FixedUpdate() { float h = Input.GetAxisRaw("Horizontal"); float v = Input.GetAxisRaw("Vertical"); Move(h, v); Turning(); Animating(h,v); } public void Move(float h, float v) { movement.Set(h, 0f, v); movement = movement.normalized * speed * Time.deltaTime; playerRB.MovePosition(transform.position + movement); } private void Turning() { Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit floorHit; if (Physics.Raycast(camRay, out floorHit, camRayLength, floorMask)) { Vector3 playerToMouse = floorHit.point - transform.position; playerToMouse.y = 0f; Quaternion newRotation = Quaternion.LookRotation(playerToMouse); playerRB.MoveRotation(newRotation); } } public void Animating(float h, float v) { bool isWalking = (h != 0f || v != 0f); anim.SetBool("IsWalking", isWalking); } #region tambahan // memberi player speed buff, dan mengakhiri buff tersebut ketika durasi nya sudah habis public void Buff(float duration, float multiplier) { if (isBuffed) return; buffDuration = duration; isBuffed = true; StartCoroutine(GetSpeedBuff(multiplier)); } private IEnumerator GetSpeedBuff(float multiplier) { speed *= multiplier; yield return new WaitForSeconds(buffDuration); speed /= multiplier; isBuffed = false; } #endregion } <file_sep># Survival Shooter Fitur yang ditambahkan - Ammo System - Pickup items (MedKit, SpeedBuff) # Player Controls Key Bindings: - R to reload the gun - Basic WASD Movement <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public enum ItemType { MedKit, Soda } public class PickupItem : MonoBehaviour { private Rigidbody rb; private PlayerHealth playerHealth; private PlayerMovement playerMovement; public ItemType itemType; private void Awake() { rb = GetComponent<Rigidbody>(); } // menonaktifkan gravity pickup item ketika menyentuh tanah dan menyalakan trigger colldiernya private void OnCollisionEnter(Collision collision) { if (collision.collider.tag == "Floor") { rb.useGravity = false; rb.velocity = Vector3.zero; GetComponent<Collider>().isTrigger = true; } } // mengecek kalau trigger pickup item dimasuki oleh collider player yang tidak memiliki trigger(capsule), // maka akan memberikan player buff/heal private void OnTriggerEnter(Collider other) { if (other.tag == "Player" && !other.isTrigger) { playerHealth = other.GetComponent<PlayerHealth>(); playerMovement = other.GetComponent<PlayerMovement>(); PickItem(); Destroy(gameObject); } } public void PickItem() { switch (itemType) { case ItemType.MedKit: playerHealth.Heal(20); // shouldn't be hardcode this break; case ItemType.Soda: playerMovement.Buff(6f, 1.8f); // this too break; } } } <file_sep>using UnityEngine; using UnityEngine.UI; public class PlayerShooting : MonoBehaviour { public int damagePerShot = 20; public int magSize = 30; public float reloadDelay = 2.5f; public float timeBetweenBullets = 0.15f; public float range = 100f; public Text ammoText; public Slider reloadSlider; int shootableMask; int currentMag; float timer; float reloadTimer; float effectsDisplayTime = 0.2f; Ray shootRay = new Ray(); RaycastHit shootHit; bool isReloading; ParticleSystem gunParticles; LineRenderer gunLine; AudioSource gunAudio; Light gunLight; void Awake() { shootableMask = LayerMask.GetMask("Shootable"); gunParticles = GetComponent<ParticleSystem>(); gunLine = GetComponent<LineRenderer>(); gunAudio = GetComponent<AudioSource>(); gunLight = GetComponent<Light>(); currentMag = magSize; } void Update() { timer += Time.deltaTime; // mengecek jika player sedang reload, maka akan melakukan sequence reload if (isReloading) { reloadSlider.gameObject.SetActive(true); reloadTimer += Time.deltaTime; reloadSlider.value = (reloadTimer / reloadDelay) * 100; if (reloadTimer >= reloadDelay) { isReloading = false; currentMag = magSize; reloadTimer = 0; reloadSlider.gameObject.SetActive(false); } } if (currentMag > 0 && Input.GetButton("Fire1") && timer >= timeBetweenBullets && !isReloading) { Shoot(); } if (currentMag != magSize && Input.GetKey(KeyCode.R)) { Reload(); } if (timer >= timeBetweenBullets * effectsDisplayTime) { DisableEffects(); } ammoText.text = string.Format("Ammo: {0}", currentMag); } public void DisableEffects() { gunLine.enabled = false; gunLight.enabled = false; } public void Shoot() { timer = 0f; currentMag--; gunAudio.Play(); gunLight.enabled = true; gunParticles.Stop(); gunParticles.Play(); gunLine.enabled = true; gunLine.SetPosition(0, transform.position); shootRay.origin = transform.position; shootRay.direction = transform.forward; if (Physics.Raycast(shootRay, out shootHit, range, shootableMask)) { EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>(); if (enemyHealth != null) { enemyHealth.TakeDamage(damagePerShot, shootHit.point); } gunLine.SetPosition(1, shootHit.point); } else { gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range); } } private void Reload() { isReloading = true; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PickupManager : MonoBehaviour { private static PickupManager _instance; public static PickupManager Instance { get { if (_instance == null) { _instance = FindObjectOfType<PickupManager>(); } return _instance; } } private float baseChance = 0.1f; public GameObject[] pickupPrefabs; public float spawnItemChance = 0.1f; // mengspawn pickup item dari object musuh dengan random chance public void SpawnPickupItem(Transform spawnPos) { float rand = Random.Range(0f, 1f); if (rand <= spawnItemChance) { spawnItemChance = baseChance; int pickupIndex = Random.Range(0, pickupPrefabs.Length); GameObject pickupItem = Instantiate(pickupPrefabs[pickupIndex], spawnPos.position + Vector3.up, spawnPos.rotation); pickupItem.GetComponent<Rigidbody>().velocity = Vector3.one; } else { spawnItemChance += 0.02f; } } }
ba103ed2eeec33d65b585074ef43013a29361efe
[ "Markdown", "C#" ]
5
C#
tryToNotCopyMe/Survival-Shooter
a312d27f70fb2808e7d4ba605270c10d59d5d8a9
e54bcd7d807fdbfbc02696e34e25678fd2686cf6
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class openSphereRain : MonoBehaviour { public GameObject door; public activateRigidBody activateRigidBody; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnCollisionEnter(Collision collision) { door.transform.Translate(Vector3.down * Time.deltaTime * 10); activateRigidBody.ActivateRigidBody(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class IsInside : MonoBehaviour { public Material m_material; public GameObject nextLevelDoor; public GameObject arch; public Animator doorAnimator; public Animator archAnimator; // Start is called before the first frame update void Start() { m_material = GetComponent<Renderer>().material; } // Update is called once per frame void Update() { } private void OnCollisionEnter(Collision collision) { print("win"); m_material.color = Color.green; doorAnimator.SetTrigger("isTriggered"); archAnimator.SetTrigger("isTriggered"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnMeteorites : MonoBehaviour { public float delay = 0.05f; public GameObject meteorites; // Start is called before the first frame update void Start() { meteorites.AddComponent<Rigidbody>(); meteorites.GetComponent<Rigidbody>().AddForce(Physics.gravity * 1f, ForceMode.Acceleration); meteorites.tag = "EnemySphere"; } // Update is called once per frame void Update() { } void Spawn() { Instantiate(meteorites, new Vector3(Random.Range(51, 123), Random.Range(70, 90), Random.Range(66, 70)), Quaternion.identity); } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Player")) { CancelInvoke("Spawn"); InvokeRepeating("Spawn", delay, delay); } } private void OnCollisionExit(Collision collision) { if (collision.gameObject.CompareTag("Player")) { CancelInvoke("Spawn"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class move : MonoBehaviour { // Win condition private bool[] levelsEnded = new bool[3]; private bool haveIWin = false; public RawImage youWinImage; public RawImage pauseImage; private bool isPauseActive = false; private float timer = 0f; private Vector3 beginPosition = new Vector3(0,0,0); private Vector3 startPosition; public int life = 3; [SerializeField] private float speed = 1.5f; [SerializeField] private float jumpForce = 10f; private Rigidbody rigidbody; private int jumpStack = 2; float timeLeft = 5.0f; public Camera camera; // Manage UI public RawImage life1; public RawImage life2; public RawImage life3; public Text jumpAvailable; public Text timerText; // Start is called before the first frame update void Start() { LaunchGame(); rigidbody = GetComponent<Rigidbody>(); } private void LaunchGame() { timer = 0f; youWinImage.gameObject.SetActive(false); pauseImage.gameObject.SetActive(false); levelsEnded[0] = false; levelsEnded[1] = false; levelsEnded[2] = false; startPosition = beginPosition; } // Update is called once per frame void Update() { WinCondition(); LooseByFalling(); CheckLife(); UpdateUI(); Timer(); if (timeLeft <= 0) { timeLeft = 0; if (jumpStack < 2) { timeLeft = 3; jumpStack += 1; } } else { timeLeft -= Time.deltaTime; } if (Input.GetKeyDown(KeyCode.Escape)) { if (haveIWin == true) { LaunchGame(); return; } else { isPauseActive = !isPauseActive; pauseImage.gameObject.SetActive(isPauseActive); } } if (haveIWin == true) { return; } // Go forward if (Input.GetKey(KeyCode.UpArrow)) { if (Input.GetKey(KeyCode.LeftShift)) { transform.Translate(Vector3.right * Time.deltaTime * speed * 5); } else { transform.Translate(Vector3.right * Time.deltaTime * speed); } } // Turn left if (Input.GetKey(KeyCode.LeftArrow)) { if (Input.GetKey(KeyCode.LeftShift)) { transform.Rotate(transform.up * -10f * Time.fixedDeltaTime); } else { transform.Rotate(transform.up * -50f * Time.fixedDeltaTime); } } // Go backward if (Input.GetKey(KeyCode.DownArrow)) { transform.Translate(Vector3.left * Time.deltaTime * speed); } // Turn right if (Input.GetKey(KeyCode.RightArrow)) { if (Input.GetKey(KeyCode.LeftShift)) { transform.Rotate(transform.up * 10f * Time.fixedDeltaTime); } else { transform.Rotate(transform.up * 50f * Time.fixedDeltaTime); } } // Move the camera up and down if (Input.GetKey(KeyCode.W)) { camera.transform.Rotate(Vector3.right * 30f * Time.fixedDeltaTime); } if (Input.GetKey(KeyCode.S)) { camera.transform.Rotate(Vector3.left * 30f * Time.fixedDeltaTime); } // Go backward if (Input.GetKeyDown(KeyCode.Space) && (timeLeft <= 0 || jumpStack >= 1)) { rigidbody.AddForce(transform.up * jumpForce, ForceMode.VelocityChange); timeLeft = 3; jumpStack -= 1; } } private void CheckLife() { if (life == 0) { transform.position = startPosition; life += 3; } } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("EnemyCylinder")) { life -= 1; rigidbody.AddForce(Vector3.left * 10, ForceMode.VelocityChange); } if (collision.gameObject.CompareTag("EnemySphere")) { life -= 1; rigidbody.AddForce(Vector3.back * 10, ForceMode.VelocityChange); } if (collision.gameObject.CompareTag("Level1End") || collision.gameObject.CompareTag("Level2End") || collision.gameObject.CompareTag("Level3End")) { startPosition = collision.transform.position + new Vector3(0, 5, 0); if (collision.gameObject.CompareTag("Level1End")) { levelsEnded[0] = true; } if (collision.gameObject.CompareTag("Level2End")) { levelsEnded[1] = true; } if (collision.gameObject.CompareTag("Level3End")) { levelsEnded[2] = true; } } if (collision.contacts.Length > 0) { ContactPoint contact = collision.contacts[0]; if (Vector3.Dot(contact.normal, Vector3.up) > 0.5) { //collision was from below jumpStack = 2; } } } private void LooseByFalling() { if (transform.position.y <= 0) { life = 0; } } private void UpdateUI() { // Manage life display if (life == 3) { life1.gameObject.SetActive(true); life2.gameObject.SetActive(true); life3.gameObject.SetActive(true); } if (life == 2) { life1.gameObject.SetActive(false); life2.gameObject.SetActive(true); life3.gameObject.SetActive(true); } if (life == 1) { life1.gameObject.SetActive(false); life2.gameObject.SetActive(false); life3.gameObject.SetActive(true); } // Manage Jump display jumpAvailable.text = jumpStack.ToString(); } private void WinCondition() { if (levelsEnded[0] == true && levelsEnded[1] == true && levelsEnded[2] == true) { haveIWin = true; } if (haveIWin == true) { youWinImage.gameObject.SetActive(true); } } private void Timer() { if (!isPauseActive) { timer += Time.deltaTime; } int minutes = Mathf.FloorToInt(timer / 60F); int seconds = Mathf.FloorToInt(timer - minutes * 60); string niceTime = string.Format("{0:0}:{1:00}", minutes, seconds); timerText.text = niceTime; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class activateRigidBody : MonoBehaviour { // Start is called before the first frame update private Rigidbody[] rigidbodies; void Start() { rigidbodies = GetComponentsInChildren<Rigidbody>(); } // Update is called once per frame void Update() { } public void ActivateRigidBody() { foreach (Rigidbody body in rigidbodies) { body.useGravity = true; } } } <file_sep># F21GP_unity_game The github repo for my game in unity for the coursework 1
51e30e43ecf2f74b591427d4f1bd903207343ef0
[ "Markdown", "C#" ]
6
C#
loupmasneri/F21GP_unity_game
f2843f6e9214d54b8f7b3bca29130c77595d701f
f852c247bbf5fb9d74eec0bfea00d9336b26295e
refs/heads/master
<repo_name>YakovlevAl/PMIneproga<file_sep>/README.md sends "PMI - ne proga" to every new VK conversation member DISCLAIMER: I wrote it for myself and didn't pay enough attention to readability of the code, so attempts to understand it can lead to serious eye injuries (sorry).<file_sep>/requirements.txt vk==2.0.2 requests==2.18.4 <file_sep>/main.py import vk import requests import random from settings import token session = vk.Session(access_token = token) vk_api = vk.API(session) data = vk_api.groups.getLongPollServer(v = 5.101, group_id = 184953916) phrases = ['ПМИ - не прога!', 'ПМИ - не прога.', 'Направление "Прикладная математика и информатика" не является программированием.', 'ПМИ не программирование.'] while True: response = requests.get( '{server}?act=a_check&key={key}&ts={ts}&wait=25'.format(server=data['server'], key=data['key'], ts=data['ts'])).json() updates = response['updates'] #print(updates) if updates and 'action' in updates[0]['object'] and updates[0]['type'] == 'message_new' and (updates[0]['object']['action']['type'] == 'chat_invite_user' or updates[0]['object']['action']['type'] == 'chat_invite_user_by_link'): peer_id = updates[0]['object']['peer_id'] message = random.choice(phrases) vk_api.messages.send(v = 5.101, peer_id = peer_id, message = message, random_id = random.randint(0, 10 ** 6)) data['ts'] = response['ts']
779e24124d8f80fd6b9f94451f31864549ecbd4c
[ "Markdown", "Python", "Text" ]
3
Markdown
YakovlevAl/PMIneproga
b910ab300e9d4df1f0795b63356a26677e4f02e7
b8460bb63d40898168fbbb2d9ee196a2565d6b99
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin_complex_filter', '0001_initial'), ] operations = [ migrations.AlterField( model_name='item', name='item_id', field=models.CharField(max_length=30, blank=True), ), migrations.AlterField( model_name='item', name='link', field=models.URLField(blank=True), ), migrations.AlterField( model_name='item', name='notes', field=models.CharField(max_length=400, blank=True), ), migrations.AlterField( model_name='item', name='price', field=models.IntegerField(null=True), ), migrations.AlterField( model_name='item', name='special', field=models.CharField(max_length=30, blank=True), ), migrations.AlterField( model_name='item', name='title', field=models.CharField(max_length=100, blank=True), ), ] <file_sep>from django.db import models from django import forms # Create your models here. class CustomAdminDisplayModelChoiceField(forms.ModelChoiceField): """This does the second part of the customization. Instead of simply displaying the author's name, adds the "(age)" to that. Here we have access to the object, and should return its representation. Less hacky, more worky. """ def label_from_instance(self, obj): return u"{name} ({age})".format(name=obj.name, age=obj.age) class ForeignCustomDisplayKey(models.ForeignKey): """Hooks up the custom model choice field to the model. """ def formfield(self, **kwargs): kwargs.update({'form_class': CustomAdminDisplayModelChoiceField}) return super(ForeignCustomDisplayKey, self).formfield(**kwargs) class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() def __str__(self): return u"{}".format(self.name) class Book(models.Model): name = models.CharField(max_length=200) authors = ForeignCustomDisplayKey(Author, null=True) def __str__(self): return u"{}".format(self.name) <file_sep>from django.db import models # Create your models here. class Item(models.Model): item_id = models.CharField(max_length=30, blank=True) title = models.CharField(max_length=100, blank=True) link = models.URLField(blank=True) price = models.IntegerField(null=True) special = models.CharField(max_length=30, blank=True) notes = models.CharField(max_length=400, blank=True) available = models.BooleanField(default=False) def __str__(self): return u"({id}) {title}".format(id=self.item_id, title=self.title) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import model_select_customized.models class Migration(migrations.Migration): dependencies = [ ('model_select_customized', '0001_initial'), ] operations = [ migrations.AlterField( model_name='book', name='authors', field=model_select_customized.models.ForeignCustomDisplayKey(to='model_select_customized.Author', null=True), ), ] <file_sep># django-examples Examples of django projects that include either features of either core django or other django apps. Why? ---- Needed a place to store code more complex than snippets. The plan --------- Complete projects will be stored here. These will illustrate a specific feature or a comprehensive feature set. These projects will be grouped (hopefully semantically) in different folders. If too much boilerplate code needs to be writter, some kind of project skeleton will be used for building the "example" on top of it. Results ------- Project `model_select_customized` introduces 2 customizations to the django's Select widget (default ForeignKeyField widget) https://github.com/vladiibine/django-examples/blob/master/admin-gallery/widget_customization/model_select_customized/ ![](https://github.com/vladiibine/django-examples/blob/master/admin-gallery/widget_customization/model_select_customized/static/django-example-1.png) <file_sep>1. Run `pip install .` when inside the same directory as `setup.py` 2. Run `django-admin runserver 8080 --settings=widget_customization.settings` 3. In your browser visit `http://localhost:8080/admin/model_select_customized/book/add/` (The credentials are username=root, password=<PASSWORD>) 4. Check out the "Authors" select element. You'll see explanations in the code how that was implemented. The simpler (and more hackish) customization (that adds `>>><<<`)is done in the admin The more complex customization, that adds the age of the author, is done in models.py 5. This is the end result: Notice the `>>><<<` and the `(year)` close to the name of the authors ![](https://github.com/vladiibine/django-examples/blob/master/admin-gallery/widget_customization/model_select_customized/static/django-example-1.png) <file_sep>from distutils.core import setup setup( name='widget_customization', version='1.0', packages=['widget_customization', 'model_select_customized'], url='https://github.com/vladiibine/', license='MIT', author='<NAME>', include_package_data=True, package_data={'widget_customization': ['db.sqlite3']}, author_email='', description='Example project showing various admin customization options', install_requires=['Django>=1.8,<1.9'], ) <file_sep>from django.contrib import admin from django.forms import widgets from .models import Author, Book # Register your models here. class CustomBookNameWidget(widgets.Select): """If the desired choices is "ASDF", makes if look like ">>>ASDF<<<" The desired choice is given by the str(model) (or unicode in Py2) You'd ask yourself... "If I can override my model's `str`, then why bother?" - well because sometimes the model is in another app. This applies to situations when you create relationships between your models and Django's User, Group, or whatever, and lets you still customize your admin Remarks: It couldn't be done in __init__ even though it looks like it. Here's the __init__ def __init__(self, attrs=None, choices=()): super(Select, self).__init__(attrs) self.choices = list(choices) ... the thing is, somewhere (in the RelatedFieldWidgetWrapper.render) the .choices is overwritten, so we can intersect this assignment and tweak it. """ @property def choices(self): return self._choices @choices.setter def choices(self, val): self._choices = list( (key, ">>>{}<<<".format(value) if key else value) for key, value in val ) class BookAdmin(admin.ModelAdmin): """This admin simply replaces the default Select widget, with a custom one """ def formfield_for_foreignkey(self, db_field, request=None, **kwargs): old_field = super(BookAdmin, self).formfield_for_foreignkey( db_field, request, **kwargs) old_widget = old_field.widget new_widget = CustomBookNameWidget(old_widget.attrs, old_widget.choices) old_field.widget = new_widget return old_field admin.site.register(Author) admin.site.register(Book, BookAdmin) <file_sep>from django.contrib import admin # Register your models here. from django.contrib.admin import filters from .models import Item class ComplexListFilter(filters.SimpleListFilter): title = 'complex filter' parameter_name = 'complex' template = 'admin_complex_filter/filter_template.html' def lookups(self, request, model_admin): return( (1, 11), (2, 22) ) def queryset(self, request, queryset): return queryset @admin.register(Item) class ItemAdmin(admin.ModelAdmin): list_filter = (ComplexListFilter, 'available')
03458e45eb35629e74600929fc4b5b89bb9d1af5
[ "Markdown", "Python" ]
9
Python
vladiibine/django-examples
859761e1f37f3be2bc7c2b7404a29605ad80a7a4
20755983a483f8a610b54aa2c9242f4d822b4727
refs/heads/master
<repo_name>noahgriff99/388Final<file_sep>/flask_app/__init__.py # 3rd-party packages from flask import Flask, render_template, request, redirect, url_for from flask_mongoengine import MongoEngine from flask_login import ( LoginManager, current_user, login_user, logout_user, login_required, ) from flask_bcrypt import Bcrypt from werkzeug.utils import secure_filename from flask_mail import Mail # stdlib from datetime import datetime import os # local from .client import MovieClient mail = Mail() db = MongoEngine() login_manager = LoginManager() bcrypt = Bcrypt() movie_client = MovieClient(os.environ.get("OMDB_API_KEY")) # from .routes import main from flask_app.users.routes import users from flask_app.movies.routes import movies def page_not_found(e): return render_template("404.html"), 404 def create_app(test_config=None): app = Flask(__name__) app.config["MONGODB_HOST"] = os.getenv("MONGODB_HOST") app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PASSWORD'] = '<PASSWORD>' app.config['MAIL_USERNAME'] = '<EMAIL>' app.config['MAIL_USE_TLS'] = True app.config['MAIL_PORT'] = 587 mail.init_app(app) app.register_blueprint(movies) app.register_blueprint(users) app.config.from_pyfile("config.py", silent=False) if test_config is not None: app.config.update(test_config) db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) # app.register_blueprint(main) app.register_error_handler(404, page_not_found) login_manager.login_view = "users.login" return app <file_sep>/flask_app/movies/routes.py from flask import Blueprint, render_template, url_for, redirect, request, flash from flask_login import current_user from .. import movie_client, mail from ..forms import MovieReviewForm, SearchForm, LocationForm, SurveyForm from ..models import User, Review, Location, Survey from ..utils import current_time movies = Blueprint('movies', __name__) @movies.route("/", methods=["GET", "POST"]) def index(): form = SearchForm() if form.validate_on_submit(): return redirect(url_for("movies.query_results", query=form.search_query.data)) return render_template("index.html", form=form) @movies .route("/search-results/<query>", methods=["GET"]) def query_results(query): result = Location.objects(address__icontains=query) return render_template("query.html", results = result) # @movies.route("/search-results/<query>", methods=["GET"]) # def query_results(query): # try: # results = movie_client.search(query) # except ValueError as e: # flash(str(e)) # return redirect(url_for("movies.index")) # return render_template("query.html", results=results) @movies.route("/movies/<movie_id>", methods=["GET", "POST"]) def movie_detail(movie_id): try: result = movie_client.retrieve_movie_by_id(movie_id) except ValueError as e: flash(str(e)) return redirect(url_for("users.login")) form = MovieReviewForm() if form.validate_on_submit() and current_user.is_authenticated: review = Review( commenter=current_user._get_current_object(), content=form.text.data, date=current_time(), imdb_id=movie_id, movie_title=result.title, ) review.save() return redirect(request.path) reviews = Review.objects(imdb_id=movie_id) return render_template( "movie_detail.html", form=form, movie=result, reviews=reviews ) @movies.route("/user/<username>") def user_detail(username): user = User.objects(username=username).first() reviews = Review.objects(commenter=user) return render_template("user_detail.html", username=username, reviews=reviews) @movies.route("/add", methods=["GET", "POST"]) def add(): # username_form = UpdateUsernameForm() form = LocationForm() if form.validate_on_submit(): # User(username=form.username.data, email=form.email.data, password=<PASSWORD>) location = Location(address=form.address.data, state=form.state.data, zipcode=form.zipcode.data) location.save() return redirect(url_for("movies.survey")) return render_template("add.html", location_form = form) @movies.route("/survey", methods=["GET", "POST"]) def survey(): # username_form = UpdateUsernameForm() form = SurveyForm() if form.validate_on_submit(): # User(username=form.username.data, email=form.email.data, password=<PASSWORD>) # location = Location(address=form.address.data, state=form.state.data, zipcode=form.zipcode.data) survey = Survey(appeal=form.data) return redirect(url_for("users.login")) return render_template("survey.html", survey_form = form) @movies.route("/about", methods=["GET", "POST"]) def about(): return render_template("about.html")<file_sep>/flask_app/forms.py from flask_login import current_user from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired, FileAllowed from werkzeug.utils import secure_filename from wtforms import StringField, IntegerField, SubmitField, TextAreaField, PasswordField, SelectField from wtforms.validators import ( InputRequired, DataRequired, NumberRange, Length, Email, EqualTo, ValidationError, ) from .models import User class SearchForm(FlaskForm): search_query = StringField( "Query", validators=[InputRequired(), Length(min=1, max=100)] ) submit = SubmitField("Search") class MovieReviewForm(FlaskForm): text = TextAreaField( "Comment", validators=[InputRequired(), Length(min=5, max=500)] ) submit = SubmitField("Enter Comment") class RegistrationForm(FlaskForm): username = StringField( "Username", validators=[InputRequired(), Length(min=1, max=40)] ) email = StringField("Email", validators=[InputRequired(), Email()]) password = PasswordField("<PASSWORD>", validators=[InputRequired()]) confirm_password = PasswordField( "<PASSWORD>", validators=[InputRequired(), EqualTo("<PASSWORD>")] ) submit = SubmitField("Sign Up") def validate_username(self, username): user = User.objects(username=username.data).first() if user is not None: raise ValidationError("Username is taken") def validate_email(self, email): user = User.objects(email=email.data).first() if user is not None: raise ValidationError("Email is taken") class LoginForm(FlaskForm): username = StringField("Username", validators=[InputRequired()]) password = PasswordField("<PASSWORD>", validators=[InputRequired()]) submit = SubmitField("Login") class UpdateUsernameForm(FlaskForm): username = StringField( "Username", validators=[InputRequired(), Length(min=1, max=40)] ) submit = SubmitField("Update Username") def validate_username(self, username): if username.data != current_user.username: user = User.objects(username=username.data).first() if user is not None: raise ValidationError("That username is already taken") class LocationForm(FlaskForm): address = StringField("Address", validators=[InputRequired()]) state = StringField("State", validators=[InputRequired()]) zipcode = IntegerField("Zipcode", validators=[InputRequired()]) submit = SubmitField("Add Survey") class SurveyForm(FlaskForm): appeal = SelectField(u'appeal', choices=['bad','ok','nice','very nice']) submit = SubmitField("Submit Survey") <file_sep>/README.md # Project 5: Untested Apps? No, Broken Apps. **Assigned**: March 31st, 2021 **Due**: April 16th, 2021 11:59 pm EST **Late Deadline**: April 18th, 2021 11:59pm EST ## Description This project is based partly off of your previous project. As the Flask docs so elegantly say, "Something that is untested is broken." We're sorry we have been making you all develop broken apps for the entire semester, but you'll learn how to make actually-functional apps with this project. This project has most of the functionality of project 4 implemented, excluding profile pictures. The emphasis on this project is **testing** (and blueprints, to a lesser extent). ## Setup The setup of your API key should be complete from project 3. Activate your virtual environment (we recommend using the same one you've used for other projects, you don't need a new one). Then to install all necessary packages, run `pip3 install -r requirements.txt` For this project we'll be using the - `requests` - `Flask` - `Flask-MongoEngine` - `Flask-WTF` - `Flask-Bcrypt` - `Flask-Login` - `python-dotenv` - `pytest` libraries ## Project This is the `p5/` directory structure ![p5 directory](./images/directory.png "Directory Structure") To run this project, stay in the `p5/` directory and use the `flask run` command. This project is run the same way as project 4. The application fully works as it is given. In `__init__.py`, apps are now created by calling the `create_app()` function. Optionally, a `test_config` parameter can be passed in so that the application will be configured with the desired settings for testing. We create the `db`, `login_manager`, and `movie_client` objects and initialize them using the `init_app()` function of these extensions. Then we register the `main` blueprint (you'll change this later) and set a global 404 error handler function. The configuration is loaded from `config.py`. Although we don't have many configuration values for this project, this kind of pattern is the best practice for when your apps might get more complicated and have lots of configuration values. ### routes.py In this file, you'll notice that there is a `main` blueprint. This is the blueprint that contains all of the routes, and it was registered to our application in `__init__.py`. You have to reorganize the project to make it more modular. It doesn't make sense to have the functions concerned with user management side by side with the functions concerned with entering or viewing reviews. So you'll see that we created two directories that each have a `routes.py` inside of them. To complete this part of the project, you'll need to 1. Create blueprints inside of `users.routes` and `movies.routes` named `users` and `movies`, respectively. 2. Put all user management view functions into the `users` blueprint. These are: - `register`, - `login`, - `account`, - `logout` 3. Put all other view functions into the `movies` blueprint. These are: - `index` - `query_results` - `movie_detail` - `user_detail` 4. Rename routes from `main.some_route` to `users.some_route` or `movies. some_route` as appropriate. These changes will need to happen in the template files and in the function bodies as needed. 5. Register these blueprints with the main `Flask` object. ### tests In the `tests/` directory, you'll notice four files. The `conftest.py` file is provided with everything fully implemented. We'll go into detail about how this code works: - `@pytest.fixture` indicates that the *return value* of the function will be passed as a parameter to any `test_*` function that has a parameter with the same name as the function. For example, we create the `app` fixture and we pass it in as a parameter to the `client` fixture further down in the code. - `app()` configures the Flask application with custom testing settings, clears the database, pushes an app context, and returns the app. - `client()` returns a test client for the application - `AuthActions` consists of convenience methods to help you register, login, and log out of your application. It's used in `auth()` below. - `auth()` is a fixture that provides authentication actions. The `test_factory.py` file is provided with implemented tests so you can see how we test that our configuration values are properly set. You'll have to implement some tests in `test_movies.py` and `test_users.py`. `test_movies.py` - Implement `test_search_input_validation(client, query, message)` with `pytest.mark.parametrize` - Test that with an empty query, you get the error "This field is required." - Test that with a very short string, you get the error "Too many results" - Test that with some gibberish (maybe a random string?) you get the error "Movie not found" - Test that with a string that's too long, you get the error "Field must be between 1 and 100 characters long." - Implement `test_movie_review(client, auth)` - A beginning implementation is already provided to check if the movie detail page for the 'Guardians of the Galaxy' page will show up. The choice of this id is arbitrary, and you can change it to something else if you want. - Register and login - Submit a movie review with a randomly generated string (to make sure that you're adding a truly unique review) - Test that the review shows up on the page - Test that the review is saved in the database - Implement `test_movie_review_redirects(client, movie_id, message)` with `pytest.mark.parametrize` - This test refers to navigating to movies at a certain `/movies/<movie_id>` url. - Test that with an empty movie_id, you get a status code of `404` and that you see the custom 404 page. - Test that with (1) a movie_id shorter than 9 characters, (2) a movie_id exactly 9 characters (but an invalid id), and (3) a movie_id longer than 9 characters, the request has a status code of `302` and the error message "Incorrect IMDb ID" is displayed on the page you're redirected to. - Implement `test_movie_review_input_validation(client, auth, comment, message)` with `pytest.mark.parametrize` - This test checks whether the proper validation errors from `MovieReviewForm` are raised when you provide incorrect input. - Test that with an empty string, you get the error "This field is required" - Test that with (1) a string shorter than 5 characters and (2) a string longer than 500 characters, you get the error "Field must be between 5 and 500 characters long." - **Hint:** `'a' * 10 == 'aaaaaaaaaa'` - You can use any movie id here, just make sure it's valid or your test will fail. `test_users.py` - Implement `test_login_input_validation(auth, username, password, message)` with `pytest.mark.parametrize` - Test that if you try to log in with an empty (1) username or (2) password, you get the error "This field is required" - Test that when you successfully register but have (1) a bad username or (2) a bad password, you get the error message "Login failed. Check your username and/or password" - Implement `test_logout(client, auth)` - Register, login, check that you successfully logged in, and then logout, and check that you successfully logged out - Implement `test_change_username(client, auth)` - Test that the account page loads successfully and that you can successfully change the username of the logged-in user. - Test that the new username shows up on the account page - Test that the new username change is reflected in the database - Implement `test_change_username_taken(client, auth)` - Test that if we try to change the username to a different user's username, then we get the error message "That username is already taken" - Implement `test_change_username_input_validation(client, auth, new_username)` - Test that if we pass in an empty string, we get the error "This field is required." - Test that if we pass in a string that's too long, we get the error "Field must be between 1 and 40 characters long." There are a total of 21 tests. Each case in the input validation tests counts as a different test. For the input validation tests, you have to figure out what to put inside the function. Then you can adjust the parameters being passed in according to the specifications above, and you will cover all cases for validating that input! ## Testing ### blueprints Try to perform all of the usual functions on the website, such as registration, login, going to your account, changing your username, performing movie queries, posting reviews, going into your user detail page, etc. Also try navigating to the account page when you're not logged in, or try some other bad actions to make sure that your blueprints are working. If you implement the tests part of the project first, you can probably avoid checking that your blueprints are correct manually. ### tests Make sure you've covered every test case as detailed above. When you're in the `p5/` directory, run `python -m pytest`. This will say "4 failed, 9 passed, 5 skipped" when you start your project. By the end, it should be "30 passed". ## Submission For submission, submit the `p5/` directory. Feel free to delete `__pycache__` directories and `.pyc` files. If you don't submit according to the instructions above, you may lose **up to 25%** of your score on this project. Also make sure that you don't include your virtual environment in the submission. It makes your submissions much larger, and we don't need them in order to grade. If you include your virtual environment, you may lose **up to 25%** of your score on this project. ## Grading If you don't use MongoDB or don't use the packages mentioned in [Setup](#setup), then you will get a zero on this project. This will be graded on (1) correctness and (2) robustness You will have to implement 21 tests. There will be 30 tests in total and each will be worth 5 points for a total of 150 points for writing tests. 45 of these points are given in the tests that were already passing when you got this project. Every test that passes gives you 5 points. For blueprints, you will get - 5 points for creating each blueprint (2 total) - 5 points for correctly separating each of the 8 functions into the two blueprints. If we get an error related to your view functions being improperly configured in the blueprints, then you'll lose points. In total, there are 200 points. **Robustness:** Refer to the syllabus for the robustness requirement for all projects. The syllabus has been updated with this information, since it will be common to all projects. <file_sep>/tests/test_movies.py import pytest from types import SimpleNamespace import random import string from flask_app.forms import SearchForm, MovieReviewForm from flask_app.models import User, Review def test_index(client): resp = client.get("/") assert resp.status_code == 200 search = SimpleNamespace(search_query="guardians", submit="Search") form = SearchForm(formdata=None, obj=search) response = client.post("/", data=form.data, follow_redirects=True) assert b"Guardians of the Galaxy" in response.data @pytest.mark.parametrize( ("query", "message"), ( ("",b"This field is required."), ("1",b"Too many results"), ("azertg",b"Movie not found!"), ('a' * 101, b"Field must be between 1 and 100 characters long.") ) ) def test_search_input_validation(client, query, message): resp = client.get("/") assert resp.status_code == 200 search = SimpleNamespace(search_query=query,submit="Search") form = SearchForm(formdata=None, obj=search) response = client.post("/", data=form.data, follow_redirects=True) assert message in response.data def test_movie_review(client, auth): guardians_id = "tt2015381" url = f"/movies/{guardians_id}" resp = client.get(url) assert resp.status_code == 200 auth.register() auth.login() testData = ''.join(random.choice(string.ascii_lowercase) for i in range(10)) review = SimpleNamespace(text=testData,submit="Enter Comment") form = MovieReviewForm(formdata=None, obj=review) response = client.post(f"/movies/{guardians_id}", data=form.data, follow_redirects=True) assert bytes(testData, encoding='utf-8') in response.data # reviews = Review.objects(imdb_id=guardians_id) # print(reviews) # assert testData in reviews # assert bytes(testData, encoding='utf-8') in reviews @pytest.mark.parametrize( ("movie_id", "message"), ( ("1",b"Incorrect IMDb ID"), ("123456789",b"Incorrect IMDb ID"), ("12345678910",b"Incorrect IMDb ID"), ) ) def test_movie_review_redirects(client, movie_id, message): resp = client.get(f"/movies/") assert resp.status_code == 404 # resp = client.get(f"/movies/{movie_id}") resp = client.post(f"/movies/{movie_id}", data=None, follow_redirects=False) assert resp.status_code == 302 resp = client.post(f"/movies/{movie_id}", data=None, follow_redirects=True) assert message in resp.data # assert message in resp.data @pytest.mark.parametrize( ("comment", "message"), ( ("",b"This field is required."), ('a',b"Field must be between 5 and 500 characters long"), ('a' * 501,b"Field must be between 5 and 500 characters long"), ) ) def test_movie_review_input_validation(client, auth, comment, message): guardians_id = "tt2015381" url = f"/movies/{guardians_id}" resp = client.get(url) assert resp.status_code == 200 auth.register() auth.login() review = SimpleNamespace(text=comment,submit="Enter Comment") form = MovieReviewForm(formdata=None, obj=review) response = client.post(f"/movies/{guardians_id}", data=form.data, follow_redirects=True) assert message in response.data <file_sep>/tests/test_users.py from flask import session, request import pytest from types import SimpleNamespace from flask_app.forms import RegistrationForm, LoginForm, UpdateUsernameForm from flask_app.models import User from wtforms.validators import ( ValidationError, ) def test_register(client, auth): """ Test that registration page opens up """ resp = client.get("/register") assert resp.status_code == 200 response = auth.register() assert response.status_code == 200 user = User.objects(username="test").first() assert user is not None @pytest.mark.parametrize( ("username", "email", "password", "confirm", "message"), ( ("test", "<EMAIL>", "test", "test", b"Username is taken"), ("p" * 41, "<EMAIL>", "test", "test", b"Field must be between 1 and 40"), ("username", "test", "test", "test", b"Invalid email address."), ("username", "<EMAIL>", "test", "test2", b"Field must be equal to"), ), ) def test_register_validate_input(auth, username, email, password, confirm, message): if message == b"Username is taken": auth.register() response = auth.register(username, email, password, confirm) assert message in response.data def test_login(client, auth): """ Test that login page opens up """ resp = client.get("/login") assert resp.status_code == 200 auth.register() response = auth.login() with client: client.get("/") assert session["_user_id"] == "test" @pytest.mark.parametrize( ("username", "password", "message"), ( ("", "test", b"This field is required"), ("test", "", b"This field is required"), ("test","fake", b"Login failed. Check your username and/or password"), ("asdf","test", b"Login failed. Check your username and/or password"), ) ) def test_login_input_validation(client,auth, username, password, message): # review = SimpleNamespace(text=comment,submit="Enter Comment") # form = MovieReviewForm(formdata=None, obj=review) # response = client.post(f"/movies/{guardians_id}", data=form.data, follow_redirects=True) auth.register() login = SimpleNamespace(username=username, password=<PASSWORD>, submit="Login") form = LoginForm(formdata=None, obj=login) response = client.post("login", data=form.data, follow_redirects=True) assert message in response.data def test_logout(client, auth): auth.register() auth.login() auth.logout() resp = client.get("/login") assert resp.status_code == 200 def test_change_username(client, auth): auth.register() auth.login() resp = client.get("/account") assert resp.status_code == 200 update = SimpleNamespace(username="update",submit="Update Username") form = UpdateUsernameForm(formdate=None, obj=update) response = client.post("/account", data=form.data, follow_redirects=True) auth.login(username="update",password="<PASSWORD>") resp = client.get("/account") assert b"update" in resp.data def test_change_username_taken(client, auth): auth.register() auth.register(username="taken", email="<EMAIL>") auth.login() with client: client.get("/") assert session["_user_id"] == "test" update = SimpleNamespace(username="taken",submit="Update Username") form = UpdateUsernameForm(formdate=None, obj=update) response = client.post("/account", data=form.data, follow_redirects=True) assert b"That username is already taken" in response.data @pytest.mark.parametrize( ("new_username", "message"), ( ("",b"This field is required."), ("a" * 41, b"Field must be between 1 and 40 characters long."), ) ) def test_change_username_input_validation(client, auth, new_username, message): auth.register() auth.login() resp = client.get("/account") assert resp.status_code == 200 update = SimpleNamespace(username=new_username,submit="Update Username") form = UpdateUsernameForm(formdate=None, obj=update) response = client.post("/account", data=form.data, follow_redirects=True) assert message in response.data <file_sep>/flask_app/templates/about.html {% extends "header.html" %} {% block content %} <div class="row"> </div> <div class="row"> <div class="col"> This is a project made by <NAME>. This project is a sample of a surveying website used by real estate agents to identify what needs repairs. </div> </div> {% endblock %}><file_sep>/flask_app/users/routes.py from flask import Blueprint, redirect, url_for, render_template, flash, request from flask_login import current_user, login_required, login_user, logout_user from flask_pymongo import PyMongo from flask_mail import Message from .. import bcrypt, db, mail from ..forms import RegistrationForm, LoginForm, UpdateUsernameForm, LocationForm, SurveyForm from ..models import User, Location, Survey users = Blueprint('users', __name__) @users.route("/search-results/<query>", methods=["GET"]) def query_results(query): result = Location.objects(address=query) return result @users.route("/register", methods=["GET", "POST"]) def register(): if current_user.is_authenticated: return redirect(url_for("movies.index")) form = RegistrationForm() if form.validate_on_submit(): hashed = bcrypt.generate_password_hash(form.password.data).decode("utf-8") user = User(username=form.username.data, email=form.email.data, password=hashed) user.save() # msg = Message("Hello", sender="<EMAIL>", recipients=[form.email.data]) # mail.send(msg) return redirect(url_for("users.login")) return render_template("register.html", title="Register", form=form) @users.route("/login", methods=["GET", "POST"]) def login(): if current_user.is_authenticated: return redirect(url_for("movies.index")) form = LoginForm() if form.validate_on_submit(): user = User.objects(username=form.username.data).first() if user is not None and bcrypt.check_password_hash( user.password, form.password.data ): login_user(user) msg = Message("Hello, nice email", sender="<EMAIL>", recipients=[user.email]) mail.send(msg) return redirect(url_for("users.account")) else: flash("Login failed. Check your username and/or password") return redirect(url_for("users.login")) return render_template("login.html", title="Login", form=form) @users.route("/logout") @login_required def logout(): logout_user() return redirect(url_for("movies.index")) @users.route("/account", methods=["GET", "POST"]) @login_required def account(): username_form = UpdateUsernameForm() if username_form.validate_on_submit(): # current_user.username = username_form.username.data current_user.modify(username=username_form.username.data) current_user.save() return redirect(url_for("users.account")) return render_template( "account.html", title="Account", username_form=username_form, ) # @users.route("/add", methods=["GET", "POST"]) # @login_required # def add(): # # username_form = UpdateUsernameForm() # form = LocationForm() # if form.validate_on_submit(): # # User(username=form.username.data, email=form.email.data, password=<PASSWORD>) # location = Location(address=form.address.data, state=form.state.data, zipcode=form.zipcode.data) # location.save() # return redirect(url_for("users.survey")) # return render_template("add.html", location_form = form) # @users.route("/survey", methods=["GET", "POST"]) # @login_required # def survey(): # # username_form = UpdateUsernameForm() # form = SurveyForm() # if form.validate_on_submit(): # # User(username=form.username.data, email=form.email.data, password=<PASSWORD>) # # location = Location(address=form.address.data, state=form.state.data, zipcode=form.zipcode.data) # survey = Survey(appeal=form.data) # return redirect(url_for("users.account")) # return render_template("survey.html", survey_form = form)
e95365a35b4da216f2b72ef1492c92b304c080be
[ "Markdown", "Python", "HTML" ]
8
Python
noahgriff99/388Final
4526e7df37c57253bc6bba23122b6339d8561dd1
c60fa2641cc985a7cbbca5e98630dfa1093e56b8
refs/heads/master
<file_sep>package com.in.threadWait; public class ThreadMain { public static void main(String[] args) throws InterruptedException { ThreadA threadA = new ThreadA(); threadA.start(); synchronized (threadA) { System.out.println("Main Thread calls child thread"); threadA.wait(); } System.out.println(threadA.total); for (int i=0 ; i <= 10; i++) { System.out.println("Enter into Main Thread "); } } } <file_sep>package com.in.designpattern.stateDesignPattern; public class NoCash implements AtmState{ ATMMachine atmMachine; NoCash(ATMMachine newAtmMachine){ this.atmMachine = newAtmMachine; } @Override public void insertCard() { System.out.println("We don't have money"); } @Override public void ejectCard() { System.out.println("We don't have money, we din't insert a card"); } @Override public void insertPin(int pinCode) { System.out.println("We don't have money"); } @Override public void requestCash(int cashToWithdraw) { System.out.println("We don't have money"); } } <file_sep>package com.in.StringOperation; import java.util.Arrays; public class OperationString { public static void main(String[] args) { //String test = "User IDV should be in range (123.00, 456.00) this shoulb in range"; //String[] split = test.split("[\\(\\)]"); // String s2 = Arrays.asList(test.split("[\\(\\)]")).get(1).split(",")[1]; //Done Working //Double d = Double.valueOf(s2); //System.out.println("String ===> "+s2); String bajaj = "Idv entered should be in between Rs. 40137/- And Rs.49055/-"; String test = Arrays.asList(bajaj.split("[\\.\\/]")).get(3); System.out.println("Bajaj ==> "+test); } } <file_sep>package com.in.dataStructure.linkedlist; public class LinkedList { private Node head; //insert without item LinkedList() { head = new Node(); head.value = 0; head.link = null; } //insert with item public boolean insertItem(int item){ Node n = new Node(); n.value = item; n.link = head; head = n; return true; } public void printList() { Node z = head.link; while (z != null){ System.out.println(z.value); z = z.link; } } //delete with inserted without item public boolean deleteItem(int item){ boolean isDelete = false; if(head.link.value == item) { head.link = head.link.link; isDelete = true; }else { Node x = head; Node y = head.link; while (true){ if(y == null || y.value == item){ break; }else { x = y ; y = y.link; } } if(y != null){ x.link = y.link; isDelete = true; } else { isDelete = false; } } return isDelete; } public boolean insertLast(int item){ Node n = new Node(); Node newNode = head; while (newNode.link != null) { newNode = newNode.link; } n.value = item; n.link = null; newNode.link = n; return true; } public void sortLinkedList(){ int c = 0; Node a = head.link; while (a.link != null ){ Node b = head.link; while (b.link != null){ if(b.value < b.link.value){ c = b.value; b.value = b.link.value; b.link.value = c; } b = b.link; } a = a.link; } } class Node{ int value ; Node link; } } <file_sep>package com.in.constructorreference; public class Sample { Sample() { System.out.println("Excecuting Sample calss Constructor"); } } <file_sep>package com.in.dataStructure; public class Person { String name; String rollno; public Person(String name, String rollno) { this.name = name; this.rollno = rollno; } public String getName() { return name; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", rollno='" + rollno + '\'' + '}'; } } <file_sep>package com.in.CommonClass; public class Student { String name ; Integer marks; public Student(String name, Integer marks) { this.name = name; this.marks = marks; } public Integer getMarks() { return marks; } public String getName() { return name; } } <file_sep>package com.in.dataStructure.queue; public class IntQueue { int[] queue ; int total; int front; int rear; int size; IntQueue() { size = 100; total = 0 ; front = 0; rear = 0; queue = new int[size]; } IntQueue(int size) { this.size = size; total = 0 ; front = 0; rear = 0; queue = new int[this.size]; } public boolean enQueue(int item) { if(isFull()){ return false; } else { total++; queue[rear] = item; rear= (rear +1) % size; return true; } } public int deQueue() { /*if(rear == front) { front= front +1 % size; }*/ int item = queue[front]; front= (front +1) % size; total --; return item; } private boolean isFull() { if(total == size) { return true; } return false; } public void showAll() { int f = front; if(total !=0) { for (int i = 0 ; i < total ; i++) { System.out.println(f +" "+queue[f]); f = (f+1) %size; System.out.println(f); } } } } <file_sep>package com.in.dataStructure; public class Dlist { } <file_sep>package com.in.Supplier; import java.util.function.*; public class TestSupplier { public static void main(String[] args) { Supplier<String> s = ()->{ String otp = ""; for (int i =0 ; i< 6; i++) { otp = otp + (int)(Math.random() * 10); } return otp; }; System.out.println(s.get()); System.out.println(s.get()); System.out.println(s.get()); System.out.println(s.get()); System.out.println(s.get()); } } <file_sep>package com.in.designpattern.ObserverDesignPattern; import java.util.ArrayList; import java.util.List; public class WeatherData implements Subject { List<Observer> listObserver ; private float humidity; private float temperature; private float pressure; WeatherData(){ listObserver = new ArrayList<>(); } @Override public void registerObserver(Observer observer) { listObserver.add(observer); } @Override public void removeObserver(Observer observer) { if(listObserver.indexOf(observer) >= 0) { listObserver.remove(observer); } } @Override public void notifyObserver() { listObserver.forEach(observer -> observer.update(temperature, humidity, pressure)); } public void setMeasurement(float temperature, float humidity, float pressure){ this.temperature = temperature; this.pressure = pressure; this.humidity = humidity; notifyObserver(); } } <file_sep>package com.in.dataStructure.linkedlist; import com.in.dataStructure.Person; public class PracticeLinkedList1 { Node head; Node tail; /*PracticeLinkedList1() { head = new Node(); head.value = new Person(); head.link = null; }*/ public void printLinkedList() { Node z = head.link; while (z != null) { System.out.println(z.value.toString()); z = z.link; } } public boolean insertlastItem(Person item){ Node newNode = new Node(); Node n = head; while (n.link != null) { n = n.link; } newNode.value = item; newNode.link = null; n.link = newNode; return true; } public boolean deleteItem(String item) { if(head.link.value.getName().equals(item)){ head.link = head.link.link; } Node x = head; Node y = head.link; while (y != null && !(y.value.getName().equals(item))) { x = y; y = y.link; } if(y != null){ x.link = y.link; return true; }else { return false; } } class Node { Person value ; Node link; } } <file_sep>package com.in.demo.Demo; public interface InterA { void test(); } <file_sep>package com.in.constructorreference; public interface TestInter { Sample get(); } <file_sep>package com.in.multithread; public class MythreadSynchronizedMain { public static void main(String[] args) { Display d = new Display(); MyThreadSynchronized t1 = new MyThreadSynchronized(d, "Kohli"); MyThreadSynchronized s1 = new MyThreadSynchronized(d, "Sunny"); MyThreadSynchronized s2 = new MyThreadSynchronized(d, "Mehul"); MyThreadSynchronized s3 = new MyThreadSynchronized(d, "Jinal"); MyThreadSynchronized s4 = new MyThreadSynchronized(d, "Maya"); Thread t = new Thread(t1); Thread t2 = new Thread(s1); Thread t3 = new Thread(s2); Thread t4 = new Thread(s3); t.start(); t2.start(); t3.start(); t4.start(); } } <file_sep>package com.in.dependency; public class Company { public static void main(String[] args) { Laptop laptop = new Laptop(); System.out.println(laptop.getHardDrive()); DefineOne defineOne = new DefineSecond(); defineOne.test(); } } class DefineOne{ public String test() { System.out.println("Returning DefineOne "); return "Returning DefineOne"; } } class DefineSecond extends DefineOne{ public String test() { System.out.println("Returning DefineSecond "); return "Returning DefineSecond "; } }<file_sep>package com.in.visitorpattern; public class TaxHolidayVisitor implements Visitor { @Override public Double visit(Bike bike) { System.out.println("Entered in Bike "); return bike.price * .5 +bike.price; } @Override public Double visit(Car car) { System.out.println("Entered in Car "); return car.price * .8 +car.price; } @Override public Double visit(Health health) { System.out.println("Entered in Health "); return health.price * .12 +health.price; } } <file_sep>package com.in.buildertest; import java.util.Base64; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class BuilderTest { public static void main(String[] args) { String sunnys = "<NAME>"; Set<String> sunny = Stream.of(sunnys).collect(Collectors.toSet()); System.out.println(sunny); } } <file_sep>package com.in.dataStructure; public interface isStackFull { public static void main(String[] args) { /*IntStack stack = new IntStack(); if(stack.isEmpty()) { stack.push(1); stack.push(2); } int pop = stack.pop(); System.out.println(pop); System.out.println(stack.top); System.out.println(stack.stack.length -1); */ Person per1 = new Person("Jainesh","0"); Person per2 = new Person("Sunny","1"); Person per3 = new Person("Test","2"); PersonStack personStack = new PersonStack(); personStack.push(per1); personStack.push(per3); personStack.push(per2); System.out.println(personStack.pop().toString()); System.out.println(personStack.pop().toString()); } } <file_sep>package com.in.interview; public class MainInheritance { public static void main(String[] args) { ParentClass parentClass = new ParentClass(); Subclass subclass = new Subclass(); ParentClass parentClass12 = new ParentClass(); if(parentClass == parentClass12){ System.out.println("1"); } if(parentClass.equals(parentClass12)){ System.out.println("2"); System.out.println(parentClass.hashCode()); } ParentClass parentClass123 = new Subclass(); parentClass123.m1("Suuny"); } } <file_sep>package com.in.dependencyInjection; public class Assembler { Payment getPaymentObject(){ SavingAccount savingAccount = new SavingAccount(); Payment payment = new Payment(); //Setter Injection payment.setSavingAccount(savingAccount); return payment; } } <file_sep>package com.in.dataStructure.doublelist; import com.in.dataStructure.linkedlist.LinkedList; public class DoubleLinkedList { Node head; Node tail; DoubleLinkedList(){ Node newNode = new Node(); newNode.value = 0; head = newNode; newNode.prev = null; newNode.next = null; } public boolean insertFirst(int item){ Node n = new Node(); n.value = item; n.prev = null; head.prev = n; n.next = head; return true; } public boolean deleteItem(int item){ boolean isDelete = false; if(head.next.value == item) { head.next = head.next.next; isDelete = true; }else { Node x = head; Node y = head.next; while (true){ if(y == null || y.value == item){ break; }else { x = y ; y = y.next; } } if(y != null){ x.next = y.next ; isDelete = true; } else { isDelete = false; } } return isDelete; } class Node{ Node prev ; int value; Node next; } } <file_sep>package com.in.timecomplexity; public class TimeComplexityMain { } <file_sep>package com.in.demo.Demo; public class InterImp implements InterA, InterB { @Override public void test() { System.out.println("Hey"); } } <file_sep>package com.in.multithread; public class MyThread1 extends Thread { Display d ; String name ; MyThread1(Display d , String name ) { this.d =d; this.name = name; } @Override public void run() { try { d.wish("Sunny"); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>package com.in.multithread; public class MyThread2 extends Thread { Display d ; String name ; MyThread2(Display d , String name ) { this.d =d; this.name = name; } @Override public void run() { try { Thread.sleep(2000); d.display(name); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>package com.in.function; public class Student { String name ; Integer marks; public Student(String name, Integer marks) { this.name = name; this.marks = marks; } } <file_sep>package com.in.bipredicate; import java.util.function.BiPredicate; public class BipredicateFunction { public static void main(String[] args) { BiPredicate<Integer, Integer> bp = (a,b)->(a+b) % 2==0; System.out.println(bp.test(5,10)); System.out.println(bp.negate()); System.out.println(bp.test(20,10)); System.out.println(bp.test(50,10)); } } <file_sep>package com.in.designpattern.ObserverDesignPattern; public class CurrentConditionDisplay implements Observer, DisplayElement { private float temparature; private float humidity; private float pressure; CurrentConditionDisplay(Subject wheatherData){ wheatherData.registerObserver(this); } @Override public void display() { System.out.println("temperature is : " + temparature); System.out.println("humidity is : " + humidity); System.out.println("pressure is : " + pressure); } @Override public void update(float temperature, float humidity, float pressure) { this.temparature = temperature; this.pressure = pressure; this.humidity = humidity; display(); } } <file_sep>package com.in.interviewquerry; public class A { public int i ; public int j; } <file_sep>package com.in.interviewquerry; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class Excercise1 { public static void main(String[] args) { Object i = new ArrayList<>().iterator(); System.out.print((i instanceof List)+",");// false System.out.print((i instanceof Iterator)+",");// true System.out.println(i instanceof ListIterator);// false System.out.println(new L1() { @Override public String toString() { System.out.print("Example"); return("A"); } }); } } <file_sep>package com.in.customdatastructure; public interface ErrorCodes { public String CHECK_PAST_DATE = " Policy Start Date cannot be a Past Date. "; public String PRE_POLICY_END_DATE_45_DAYS = "P re Policy End Date should be greater than today's date by 45 Days. "; public String PRE_POLICY_START_DATE_AND_END_DATE_VALIDATION = " Policy Start Date should be greater than PrePolicy End " + "Date by 1 or more day for 'New Vehicle', " + "Policy Start Date cannot be less than PrePolicy End Date by 1 day for 'New Vehicle'. "; public String MANUFACTURE_DATE_AND_REG_DATE_VALIDATE_2_YEARS = " Year of Manufacture should be less than or equal to the Purchase Regn Date by 2 years. "; public String NEW_VEHICLE_REGN_DATE_6_MONTH_VALIDATION = " Purchase Regn Date should be T-6 months to T (T = Current Date) for 'New Vehicle', " + "Policy Start Date cannot be greater than Purchase Regn Date by 6 months for 'New Vehicle'” new Vehicle date range previous 6 month. "; public String PURCHASE_REGN_DATE_FUTURE_VALIDATION = " Purchase Regn Date cannot be a Future Date. "; public String YEAR_OF_MANUFACTURE_AND_PRE_POLICY_START_DATE_LESS_VALIDATE = " Year of Manufacture should be less than the PrePolicy Start Date. "; String NO_QUOTE_FOUND_ERROR_MSG="No Quote found matching for request criteria."; String COULD_NOT_FETCH_QUOTE_REASON="Could not fetch Quote. Reason : "; String NO_MOTOR_POLICY_XML_FOUND="Motor Policy Object could not be blank."; String NULL_IDV_RESPONSE="idv response object is Null"; String VEHICLE_BLACK_LISTED = "Vehicle Make and Model is BlackListed"; String CORECT_DISCOUNT_ON_THE_PREVIOUS_POLICY = "PLEASE ENTER CORRECT DISCOUNT ON THE PREVIOUS POLICY"; String STANDALONE_EXCEPTION = "APOLOGIES! WE WON¿T BE ABLE TO OFFER YOU A STANDALONE OWN DAMAGE POLICY"; String STANDALONE_EXCEPTION_MESSAGE = "Apologies ! We wont be able to offer you a standalone own damage policy"; String COULD_NOT_FETCH = "Could not fetch Quote. Reason : UNKNOWN ERROR, PLEASE CONTACT WITH COMPANYREPRESENTATIVE"; String ERROR_FETCHING_MSG = "Could not fetch Quote."; String MODEL_NOT_AVAILABLE ="The Selected model is not available"; String DEFAULT_MSG = "Sorry! we are unable to generate quotes at this moment."; String HDFC_INSURER_ID = "HDFC_ERGO"; String EXCEPTION_IN_CALLING_PRC_GST_TAX_SPLIT = "EXCEPTION OCCURRED WHILE CALLING PRC_GSTTAXSPLIT"; String CASE_CANNOT_BE_PROCESSED = "Case cannot be processed online."; } <file_sep>package com.in.customdatastructure; import java.util.*; public class CustomDataStructure { public static void main(String[] args) { System.out.println(getErrorMsg("APOLOGIES! WE WON¿T BE ABLE TO OFFER YOU A STANDALONE OWN DAMAGE POLICY")); } public static String getErrorMsg(String errorMsg) { if (errorMsg.contains(ErrorCodes.VEHICLE_BLACK_LISTED) || errorMsg.contains(ErrorCodes.CORECT_DISCOUNT_ON_THE_PREVIOUS_POLICY) || errorMsg.contains(ErrorCodes.MODEL_NOT_AVAILABLE)) { return errorMsg; } else if (errorMsg.contains(ErrorCodes.EXCEPTION_IN_CALLING_PRC_GST_TAX_SPLIT)) { return ErrorCodes.CASE_CANNOT_BE_PROCESSED; } else if(errorMsg.contains(ErrorCodes.STANDALONE_EXCEPTION)){ return ErrorCodes.STANDALONE_EXCEPTION_MESSAGE; } else if (errorMsg.contains(ErrorCodes.COULD_NOT_FETCH)) { return ErrorCodes.ERROR_FETCHING_MSG; }else { return ErrorCodes.DEFAULT_MSG; } } } <file_sep>package com.in.multithread; public class ThreadMain { public static void main(String[] args) { Display d = new Display(); MyThread1 t1= new MyThread1(d, "Sunny"); MyThread2 t2 = new MyThread2(d, "karan"); t1.start(); t2.start(); } } <file_sep>package com.in.immutable; public final class ImmutableStudent { private final String name; private final int id ; private final Age age; public ImmutableStudent(String name, int id, Age age) { this.name = name; this.id = id; /*Age ageClone = new Age(); ageClone.setDay(age.getDay()); ageClone.setMonth(age.getMonth()); ageClone.setYear(age.getYear());*/ this.age = age; } public Age getAge() { return age; } public int getId() { return id; } public String getName() { return name; } } <file_sep>package com.in.interviewquerry; public interface L1 { String toString(); } <file_sep>package com.in.hashcollision; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; public class MyKey { int id ; @Override public int hashCode() { System.out.println("Calling Hash Code"); return id; } public void whenHashCodeIsCalledOnPut_thenCorrect() { MyKey key = new MyKey(); key.id = 1; Map<MyKey, String> map = new HashMap<>(); map.put(key, "val"); } public static void main(String[] args) { MyKey key = new MyKey(); key.whenHashCodeIsCalledOnPut_thenCorrect(); Map<String, String> keys = new HashMap<>(); String put = keys.put("1", "1"); String puts = keys.put("1", "2"); Hashtable hashtable = new Hashtable(); System.out.println(put); System.out.println(puts); } } <file_sep>package com.in.designpattern.builderDesignPattern; public class Phone { private String model; private String ram; private String os; private String processor; @Override public String toString() { return "Phone{" + "model='" + model + '\'' + ", ram='" + ram + '\'' + ", os='" + os + '\'' + ", processor='" + processor + '\'' + '}'; } public Phone(String model, String ram, String os, String processor) { this.model = model; this.ram = ram; this.os = os; this.processor = processor; } }
f88071dcb1713f0d6a9e8c95c0738ad5c2ee403a
[ "Java" ]
38
Java
SunnySupawala/programs
9947b79576cf593af6aff128ae58bd72898b3e30
e0af11a03724740696f4447719f55efcf3e3f9c9
refs/heads/master
<file_sep>⚠️ I am no longer maintaining scanless as of August 2023. ⚠️ # scanless This is a Python command-line utility and library for using websites that can perform port scans on your behalf. ## Supported Online Port Scanners * [ipfingerprints](http://www.ipfingerprints.com/portscan.php) * [spiderip](https://spiderip.com/online-port-scan.php) * [standingtech](https://portscanner.standingtech.com/) * [viewdns](http://viewdns.info/) * [yougetsignal](http://www.yougetsignal.com/tools/open-ports/) ## Install Do it up: ``` $ pip install scanless --user ``` ## CLI Usage ``` $ scanless --help usage: scanless [-h] [-v] [-t TARGET] [-s SCANNER] [-r] [-l] [-a] [-d] scanless, an online port scan scraper. options: -h, --help show this help message and exit -v, --version display the current version -t TARGET, --target TARGET ip or domain to scan -s SCANNER, --scanner SCANNER scanner to use (default: yougetsignal) -r, --random use a random scanner -l, --list list scanners -a, --all use all the scanners -d, --debug debug mode (cli mode off & show network errors) $ scanless --list +----------------+--------------------------------------+ | Scanner Name | Website | +----------------+--------------------------------------+ | ipfingerprints | https://www.ipfingerprints.com | | spiderip | https://spiderip.com | | standingtech | https://portscanner.standingtech.com | | viewdns | https://viewdns.info | | yougetsignal | https://www.yougetsignal.com | +----------------+--------------------------------------+ $ scanless -t scanme.nmap.org -s spiderip Running scanless v2.2.1 ... spiderip: PORT STATE SERVICE 21/tcp closed ftp 22/tcp open ssh 25/tcp closed smtp 80/tcp open http 110/tcp closed pop3 143/tcp closed imap 443/tcp closed https 465/tcp closed smtps 993/tcp closed imaps 995/tcp closed pop3s 1433/tcp closed ms-sql-s 3306/tcp closed mysql 3389/tcp closed ms-wbt-server 5900/tcp closed vnc 8080/tcp closed http-proxy 8443/tcp closed https-alt ``` ## Library Usage ``` >>> import scanless >>> sl = scanless.Scanless() >>> output = sl.scan('scanme.nmap.org', scanner='yougetsignal') >>> print(output['raw']) PORT STATE SERVICE 21/tcp closed ftp 22/tcp open ssh 23/tcp closed telnet 25/tcp closed smtp 53/tcp closed domain 80/tcp open http 110/tcp closed pop3 115/tcp closed sftp 135/tcp closed msrpc 139/tcp closed netbios-ssn 143/tcp closed imap 194/tcp closed irc 443/tcp closed https 445/tcp closed microsoft-ds 1433/tcp closed ms-sql-s 3306/tcp closed mysql 3389/tcp closed ms-wbt-server 5632/tcp closed pcanywherestat 5900/tcp closed vnc 6112/tcp closed dtspc >>> import json >>> print(json.dumps(output['parsed'], indent=2)) [ { "port": "21", "state": "closed", "service": "ftp", "protocol": "tcp" }, { "port": "22", "state": "open", "service": "ssh", "protocol": "tcp" }, { "port": "23", "state": "closed", "service": "telnet", "protocol": "tcp" }, { "port": "25", "state": "closed", "service": "smtp", "protocol": "tcp" }, { "port": "53", "state": "closed", "service": "domain", "protocol": "tcp" }, { "port": "80", "state": "open", "service": "http", "protocol": "tcp" }, ... ] ``` <file_sep>#!/usr/bin/env python import os from setuptools import setup directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(directory, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="scanless", packages=["scanless", "scanless.static"], package_data={"scanless.static": ["*.txt"]}, version="2.2.1", description="An online port scan scraper.", long_description=long_description, long_description_content_type="text/markdown", license="Unlicense", url="https://github.com/vesche/scanless", author="<NAME>", author_email="<EMAIL>", entry_points={ "console_scripts": [ "scanless = scanless.cli:main", ] }, install_requires=["beautifulsoup4", "crayons", "requests"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Information Technology", "License :: Public Domain", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Topic :: Security", ], ) <file_sep>import os import re from random import choice import bs4 import requests from scanless.exceptions import ScannerNotFound, ScannerRequestError URL_IPFINGERPRINTS = "https://www.ipfingerprints.com/scripts/getPortsInfo.php" URL_SPIDERIP = "https://spiderip.com/inc/port_scan.php" URL_STANDINGTECH = "https://portscanner.standingtech.com/portscan.php?port={0}&host={1}&protocol=TCP" URL_VIEWDNS = "https://viewdns.info/portscan/?host={0}" URL_YOUGETSIGNAL = "https://ports.yougetsignal.com/short-scan.php" pwd = os.path.abspath(os.path.dirname(__file__)) nmap_file = os.path.join(pwd, "static/nmap-services.txt") ua_file = os.path.join(pwd, "static/user-agents.txt") NMAP_SERVICES = open(nmap_file).read().splitlines() USER_AGENTS = open(ua_file).read().splitlines() OUTPUT_TEMPLATE = "PORT STATE SERVICE\n{lines}" NETWORK_ERROR_MSG = "Network error, see --debug for details." def lookup_service(port): for line in NMAP_SERVICES: if f"{port}/tcp" in line: return line.split()[0] def generate_output(raw_data): # raw_data = [(22, 'closed'), (23, 'open'), ...] lines = list() for raw in raw_data: p, state = raw service = lookup_service(p) port = f"{p}/tcp" lines.append(f"{port:<9} {state:<6} {service}") return OUTPUT_TEMPLATE.format(lines="\n".join(lines)) def parse(output): parsed_output = list() for line in output.split("\n"): if "/tcp" in line or "/udp" in line: port_str, state, service = line.split() port, protocol = port_str.split("/") parsed_output.append( { "port": port, "state": state, "service": service, "protocol": protocol, } ) return parsed_output class Scanless: def __init__(self, cli_mode=False): self.cli_mode = cli_mode self.session = requests.Session() self.scanners = { "ipfingerprints": self.ipfingerprints, "spiderip": self.spiderip, "standingtech": self.standingtech, "viewdns": self.viewdns, "yougetsignal": self.yougetsignal, } def scan(self, target, scanner="yougetsignal"): if scanner not in self.scanners: raise ScannerNotFound(f"Unknown scanner, {scanner}.") return self.scanners[scanner](target) def _randomize_user_agent(self): self.session.headers["User-Agent"] = choice(USER_AGENTS) def _request(self, url, payload=None, method="POST"): self._randomize_user_agent() try: response = self.session.request(method, url, data=payload, timeout=30) response.raise_for_status() except Exception as e: if self.cli_mode: return (None, "ERROR") raise ScannerRequestError(e) return (response.content.decode("utf-8"), "OK") def _return_dict(self, raw_output, parsed_output): return {"raw": raw_output, "parsed": parsed_output} def ipfingerprints(self, target): payload = { "remoteHost": target, "start_port": 20, "end_port": 512, "normalScan": "No", "scan_type": "connect", "ping_type": "none", "os_detect": "on", } scan_results, status = self._request(URL_IPFINGERPRINTS, payload) if status != "OK": return self._return_dict(NETWORK_ERROR_MSG, list()) output = re.sub("<[^<]+?>", "", scan_results) raw_output = output.replace("\\n", "\n").replace("\\/", "/")[36:-46].strip() parsed_output = parse(raw_output) return self._return_dict(raw_output, parsed_output) def spiderip(self, target): ports = [ 21, 22, 25, 80, 110, 143, 443, 465, 993, 995, 1433, 3306, 3389, 5900, 8080, 8443, ] payload = {"ip": target, "language[]": ports} scan_results, status = self._request(URL_SPIDERIP, payload) if status != "OK": return self._return_dict(NETWORK_ERROR_MSG, list()) scan_results = scan_results.split("/images/") scan_results.pop(0) raw_data = list() for result, port in zip(scan_results, ports): if "open" in result: raw_data.append((port, "open")) else: raw_data.append((port, "closed")) raw_output = generate_output(raw_data) parsed_output = parse(raw_output) return self._return_dict(raw_output, parsed_output) def standingtech(self, target): ports = [ 21, 22, 23, 25, 80, 110, 139, 143, 443, 445, 1433, 3306, 3389, 5900, ] raw_data = list() for p in ports: scan_results, status = self._request( URL_STANDINGTECH.format(p, target), method="GET" ) if status != "OK": return self._return_dict(NETWORK_ERROR_MSG, list()) if "open" in scan_results: raw_data.append((p, "open")) else: raw_data.append((p, "closed")) raw_output = generate_output(raw_data) parsed_output = parse(raw_output) return self._return_dict(raw_output, parsed_output) def viewdns(self, target): ports = [ 21, 22, 23, 25, 53, 80, 110, 139, 143, 443, 445, 1433, 1521, 3306, 3389, ] scan_results, status = self._request(URL_VIEWDNS.format(target), method="GET") if status != "OK": return self._return_dict(NETWORK_ERROR_MSG, list()) soup = bs4.BeautifulSoup(scan_results, "html.parser") table, rows = soup.find("table"), soup.findAll("tr") raw_data = list() for tr, port in zip(rows[7:22], ports): cols = str(tr.findAll("td")) if "error.GIF" in cols: raw_data.append((port, "closed")) else: raw_data.append((port, "open")) raw_output = generate_output(raw_data) parsed_output = parse(raw_output) return self._return_dict(raw_output, parsed_output) def yougetsignal(self, target): ports = [ 21, 22, 23, 25, 53, 80, 110, 115, 135, 139, 143, 194, 443, 445, 1433, 3306, 3389, 5632, 5900, 6112, ] payload = {"remoteAddress": target} scan_results, status = self._request(URL_YOUGETSIGNAL, payload) if status != "OK": return self._return_dict(NETWORK_ERROR_MSG, list()) soup = bs4.BeautifulSoup(scan_results, "html.parser") imgs = soup.findAll("img") raw_data = list() for img, port in zip(imgs, ports): if "red" in str(img): raw_data.append((port, "closed")) else: raw_data.append((port, "open")) raw_output = generate_output(raw_data) parsed_output = parse(raw_output) return self._return_dict(raw_output, parsed_output) <file_sep>import argparse from random import choice import crayons from scanless.core import Scanless SCAN_LIST = """\ +----------------+--------------------------------------+ | Scanner Name | Website | +----------------+--------------------------------------+ | ipfingerprints | https://www.ipfingerprints.com | | pingeu | https://ping.eu | | spiderip | https://spiderip.com | | standingtech | https://portscanner.standingtech.com | | viewdns | https://viewdns.info | | yougetsignal | https://www.yougetsignal.com | +----------------+--------------------------------------+""" VERSION = "2.2.1" sl = Scanless(cli_mode=True) def get_parser(): parser = argparse.ArgumentParser( description="scanless, an online port scan scraper." ) parser.add_argument( "-v", "--version", action="store_true", help="display the current version", ) parser.add_argument( "-t", "--target", help="ip or domain to scan", type=str, ) parser.add_argument( "-s", "--scanner", default="yougetsignal", help="scanner to use (default: yougetsignal)", type=str, ) parser.add_argument( "-r", "--random", action="store_true", help="use a random scanner", ) parser.add_argument( "-l", "--list", action="store_true", help="list scanners", ) parser.add_argument( "-a", "--all", action="store_true", help="use all the scanners", ) parser.add_argument( "-d", "--debug", action="store_true", help="debug mode (cli mode off & show network errors)", ) return parser def display(results): for line in results.split("\n"): if not line: continue elif "tcp" in line or "udp" in line: if "open" in line: line = crayons.green(line) elif "closed" in line: line = crayons.red(line) elif "filtered" in line: line = crayons.yellow(line) print(line) def main(): parser = get_parser() args = vars(parser.parse_args()) if args["version"]: print(f"v{VERSION}") return if args["list"]: print(SCAN_LIST) return if not args["target"]: parser.print_help() return if args["debug"]: sl.cli_mode = False target = args["target"] scanner = args["scanner"].lower() print(f"Running scanless v{VERSION} ...\n") scanners = sl.scanners.keys() if args["all"]: for s in scanners: print(f"{s}:") display(sl.scan(target, scanner=s)["raw"]) print() return if args["random"]: scanner = choice(list(scanners)) if scanner in scanners: print(f"{scanner}:") display(sl.scan(target, scanner=scanner)["raw"]) else: print("Scanner not found, see --list to view all supported scanners.") <file_sep>class ScannerNotFound(Exception): pass class ScannerRequestError(Exception): pass
8046f9f507dc2be8635f1ffe2361810927014948
[ "Markdown", "Python" ]
5
Markdown
bbhunter/scanless
3da40e9c19153563b5ef190a23405cb3c6bf1a70
8da3e1d644787d3d27f80ff680058c180eb330f4
refs/heads/master
<file_sep>function register(loginForm) { var email = loginForm.elements['email'].value; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { // state 4 = done if (xhttp.readyState === 4) { if (xhttp.status === 204) { alert("Check ya email!"); } else { alert('Registration Failed: ' + xhttp.responseText); } } }; xhttp.open("POST", "/register", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("email="+email); } <file_sep>var express = require('express'); router = express.Router(); passport = require('./../passport.js'); memorystore = require('./../model.js'); config = require('./../config/config.js'); router.get('/login/facebook', passport.authenticate('facebook', { scope : 'email' })); router.get( '/login/facebook/callback', passport.authenticate('facebook'), function(req, res) { memorystore.createToken(req.user, function(error, accessToken) { res.redirect("/success?token=" + accessToken.accessToken); }); } ); module.exports = router;<file_sep>function login(loginForm) { var email = loginForm.elements['email'].value; var password = loginForm.elements['password'].value; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { // state 4 = done if (xhttp.readyState === 4) { if (xhttp.status === 200) { var accessToken = JSON.parse(xhttp.responseText).access_token; window.location = "/success?token="+accessToken; } else { alert('Login Failed: ' + xhttp.responseText); } } }; xhttp.open("POST", "/oauth/token", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("username="+email+"&password="+<PASSWORD>+"&client_id=local&grant_type=password"); } <file_sep>var express = require('express'), bodyParser = require('body-parser'), oauthserver = require('oauth2-server'), mongoose = require('mongoose'), dbConfig = require('./config/database'), appConfig = require('./config/config'), passport = require('./passport'), memorystore = require('./model'); var app = module.exports = express(); app.use(passport.initialize()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/script', express.static(__dirname + '/script')); mongoose.connect(dbConfig.url); app.use(require('./controller/login.js')); app.use(require('./controller/facebook.js')); app.oauth = oauthserver({ model: memorystore, grants: ['password'], debug: true }); app.get('/', function(req, res) { res.redirect('/login'); }); app.listen(appConfig.nodePort); console.log("listening on port " + appConfig.nodePort); <file_sep>module.exports = { appID : process.env.SHEEPDOG__FACEBOOK_ID || 'facebook_id', appSecret : process.env.SHEEPDOG__FACEBOOK_SECRET || 'facebook_secret', callbackUrl : process.env.SHEEPDOG__FACEBOOK_CALLBACK || 'https://login.yarnyard.com/login/facebook/callback' }; <file_sep>var express = require('express'), router = express.Router(), path = require('path'), mongoose = require('mongoose'), crypto = require('crypto'), model = require('../model'), EmailConfirmationToken = mongoose.model('EmailConfirmationTokens'), User = mongoose.model('OAuthUsers'), config = require('../config/config.js'), app = require('../app.js'), mailer = require('../services/mailer'), rabbit = require('../services/rabbit'); router.post('/oauth/token', function (req, res) { req.body.client_id = config.clientId; req.body.client_secret = config.clientSecret; app.oauth.grant()(req, res, function (err) { if (err && err.name && err.name === 'OAuth2Error') { res.statusCode = 400; res.send(err.message); } }); }); /** * GET register is used to display the login form */ app.get('/register', function (req, res) { res.sendFile(path.resolve('view/register.html')); }); /** * POST register is used to create a confirmation token and send the email */ app.post('/register', function (req, res) { var email = req.body.email; var buffer = crypto.randomBytes(256); var randomToken = crypto.createHash('sha1').update(buffer).digest('hex'); var ConfirmationToken = new EmailConfirmationToken({ email: email, token: randomToken }); ConfirmationToken.save(function () { var protocol = 'http://'; var host = config.nodeHost; var port = config.nodePort; var setPasswordRoute = '/set-password'; var setPasswordLink = protocol + host + ':' + port + setPasswordRoute; mailer.sendMail( email, 'email_confirmation', { "token": randomToken, "email": email, "auth_host": setPasswordLink } ); res.statusCode = 204; res.send() }); }); /** * GET set-password is clicked on from email. Passes on confirmation token */ app.get('/set-password', function (req, res) { res.sendFile(path.resolve('view/set-password.html')); }); /** * POST set-password accepts e-mail, confirmation token and password to create * a user */ app.post('/set-password', function (req, res) { var email = req.body.email, password = req.body.password, confirmationTokenString = req.body.token; EmailConfirmationToken.findOne({ email: email, token: confirmationTokenString }, function (error, confirmationToken) { if (!confirmationToken) { res.statusCode = 400; res.send('Something wrong with your token / email combo'); return; } User.findOne({email: email}, function (error, tokenUser) { if (!tokenUser) { tokenUser = new User({ email: email, password: <PASSWORD> }); } else { tokenUser.password = <PASSWORD>; } tokenUser.save(); confirmationToken.remove(); // todo move to service var body = JSON.stringify({ 'event': 'email.changed', 'data': { 'user': tokenUser } }, function (key, value) { if (key == "password") { return undefined; } return value; }); // email updated event rabbit.getConnection().publish('yarnyard', body); model.createToken(tokenUser, function (error, accessToken) { res.send(accessToken); }); }); }); }); router.get('/success', function (req, res) { res.sendFile(path.resolve('view/success.html')); }); router.get('/login', function (req, res) { res.sendFile(path.resolve('view/login.html')); }); module.exports = router; <file_sep>var passport = require('passport'); mongoose = require('mongoose'); memorystore = require('./model.js'); User = mongoose.model('OAuthUsers'); Client = mongoose.model('OAuthClients'); Token = mongoose.model('OAuthAccessTokens'); fbConfig = require('./config/facebook.js'); FacebookStrategy = require('passport-facebook').Strategy; passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); passport.use( 'facebook', new FacebookStrategy({ clientID : fbConfig.appID, clientSecret : fbConfig.appSecret, callbackURL : fbConfig.callbackUrl, profileFields : ['id', 'email'] }, // facebook will send back the tokens and profile function(access_token, refresh_token, profile, done) { // asynchronous process.nextTick(function() { // find the user in the database based on their facebook id User.findOne({ 'fb.id' : profile.id }, function(err, user) { if (err) { return done(err); } if (user) { return done(null, user); } else { var primaryEmail = profile.emails[0].value; User.findOne({ 'email' : primaryEmail }, function(err, facebookUser) { if (!facebookUser) { facebookUser = new User(); } facebookUser.email = primaryEmail; facebookUser.fb.id = profile.id; facebookUser.fb.access_token = access_token; facebookUser.fb.email = primaryEmail; facebookUser.save(function(err) { if (err) { throw err; } return done(null, facebookUser); }); }); } }); }); }) ); module.exports = passport;<file_sep>module.exports = { nodeHost: process.env.SHEEPDOG__NODE_HOST || 'localhost', nodePort: process.env.SHEEPDOG__NODE_PORT || '3000', clientId: process.env.SHEEPDOG__AUTH_CLIENT || 'local', clientSecret: process.env.SHEEPDOG__AUTH_SECRET || 'test', audienceName: process.env.SHEEPDOG__AUTH_AUDIENCE || 'local', accessTokenLifetimeSeconds: 1200, rabbitMq: { username: process.env.SHEEPDOG__RABBIT_USER || 'guest', password: process.env.SHEEPDOG__RABBIT_PASS || '<PASSWORD>', host: process.env.SHEEPDOG__RABBIT_HOST || 'localhost', port: process.env.SHEEPDOG__RABBIT_PORT || '5672', queue: process.env.SHEEPDOG__RABBIT_QUEUE || 'yarnyard' } }; <file_sep>## Sheepdog This app is solely responsible for the validation and issuing of JWT tokens.
632c835a1d0e7860c06ec531aec5ed463c51e8a9
[ "JavaScript", "Markdown" ]
9
JavaScript
mickadoo/sheepdog
62bd4c2bb52d6ede7f2736a80d8607676e1ed95b
eb613b0089d6afdb0e41539eb9c7be0c2280c55d
refs/heads/master
<file_sep>'use strict' const webpack = require('webpack') const path = require('path') const ExtractTextPlugin = require('extract-text-webpack-plugin') const rootdir = path.join(__dirname, '../') module.exports = { mode: 'production', entry: { bundle: [path.join(rootdir, 'index.js')], }, output: { path: path.resolve(rootdir, './dist'), publicPath: './', filename: '[name].js', library: 'ChartFlow', libraryTarget: 'umd', umdNamedDefine: true, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { extractCSS: true, // 会把vue中的样式文件提取出来 loaders: { css: ExtractTextPlugin.extract({ use: 'css-loader', fallback: 'vue-style-loader', }), less: ExtractTextPlugin.extract({ use: 'css-loader!less-loader', fallback: 'vue-style-loader', }), }, postLoaders: { html: 'babel-loader', }, }, }, { test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/ }, { test: /\.(css|less)$/, use: ExtractTextPlugin.extract({ fallback: { loader: 'style-loader', options: { singleton: false, // 为true表示将页面上的所有css都放到一个style标签内 }, }, use: [ { loader: 'css-loader', options: { minimize: true, }, }, { loader: 'postcss-loader', options: { ident: 'postcss', plugins: [require('postcss-cssnext')(), require('cssnano')()], }, }, { loader: 'less-loader' }, ], }), }, { test: /\.(jpg|png|gif|bmp|jpeg)$/, use: [ { loader: 'url-loader', options: { esModule: false, limit: 8192, name: 'img/[hash:8].[name].[ext]', }, }, ], }, { test: /\.(svg|eot|ttf|woff|woff2)$/, use: ['file-loader'] }, ], }, plugins: [ new ExtractTextPlugin({ filename: 'bundle.css', allChunks: true, }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), ], } <file_sep>import Vue from 'vue' import App from './App.vue' import { Row, Input, Form, FormItem, Button, Scrollbar, MessageBox } from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.config.productionTip = false Vue.use(Row) Vue.use(Form) Vue.use(FormItem) Vue.use(Input) Vue.use(Button) Vue.use(Scrollbar) Vue.prototype.$MessageBox = MessageBox new Vue({ render: h => h(App), }).$mount('#app') <file_sep># chart-flow A simple visual flow editor that forked from [node-chart-flow](https://github.com/hong-boy/node-chart-flow) which based on [node-red](https://github.com/node-red/node-red) ## Install ```shell npm i @alkalixin/chart-flow -S ``` ## Quick Start ```javascript components: { ChartFlow: resolve => require(['@alkalixin/chart-flow'], resolve), }, methods:{ async registerNodeType(editor) { await editor.registerNodeType(function(a) { return new Promise(resolve => require(['../src/nodes/NodeType1.js'], resolve)) }) }, } ``` ```vue <template> <ChartFlow ref="flow" :registerNodeType="registerNodeType" :data="nodes" :readonly="false" :showTips="false" @clickedNode="clickedNode" @addedNode="addedNode" @addedLine="addedLine" @deletedNode="deletedNode" @deletedLine="deletedLine" @pastedNode="pastedNode" @onCompleted="onCompleted" @onReRenderNodes="onReRenderNodes" @dragNodes="dragNodes" @nodeChange="handleNodeChange" ></ChartFlow> </template> ``` ```javascript // main.js import '@alkalixin/chart-flow/dist/bundle.css' ``` ## Development You need `Node.js` at least `v8.9.4` ```shell npm run serve ``` ## Changelog Detailed changes for each release are documented in the [release notes](CHANGELOG.md). ## LICENSE [MIT](LICENSE)
11f0e582f561c1979db77af277bc6913d1dccdcb
[ "JavaScript", "Markdown" ]
3
JavaScript
alkalixin/chart-flow
930c6c909a511ee31c05de4d1b0626db5cd2f7c7
24897840ac65ae78aebf7fbd77a2d590ccaf858a
refs/heads/master
<repo_name>alicialsims/FSJS<file_sep>/app.js // YOU NEED THESE TO RUN THINGS const express = require('express'); const bodyParser = require('body-parser'); const router = require('./src/router'); const app = express(); require('./src/database'); //view engine setup app.set('view engine', 'pug'); app.set('views', __dirname + '/src/views'); //serve static files from public app.use(express.static(__dirname + '/public')); //Setting up that there router app.use('/', router); //HARK! Are you listening???? Dev mode... app.listen(8080, ()=> { console.log("Running on 8080"); }); // parse incoming requests //include routes // catch 404 //error handler app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); <file_sep>/src/models/Comment.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; // a CommentSchema const CommentSchema = new Schema({ name: {type: String, required: true, trim: true}, email: {type: String }, text: {type: String, required: true} }); const Comment = mongoose.model('Comment', CommentSchema); module.exports = Comment;
e6bf4324688b884467cd7114bc7e0f4b0b79fff1
[ "JavaScript" ]
2
JavaScript
alicialsims/FSJS
10e8d4c186001b630da90835cf2e05b5f3781db9
f282a3567c86c6d6aee1e526242c9b7370219953
refs/heads/master
<file_sep>const { validationResult } = require('express-validator') const NotesService = require('../services/notes.service') const create = async (request, response) => { const errors = validationResult(request) if (!errors.isEmpty()) { response.status(400).send({ errors: errors.array() }) } const note = request.body; try { const savedNote = await NotesService.create(note); return response.send(savedNote); } catch(e) { const code = e.errorCode || 500; console.log(e); return response.status(code).json({ errors: [{ msg: e.message }] }); } } const findAll = async (request, response) => { const errors = validationResult(request) if (!errors.isEmpty()) { response.status(400).send({ errors: errors.array() }) } const { startDate, endDate, userId } = request.query; try { const notes = await NotesService.findAll({ startDate, endDate, userId }); return response.send(notes); } catch (e) { const code = e.errorCode || 500; console.log(e); return response.status(code).json({ errors: [{ msg: e.message }] }); } } const findById = async (request, response) => { const errors = validationResult(request) if (!errors.isEmpty()) { response.status(400).send({ errors: errors.array() }) } const noteId = request.params.noteId; try { const note = await NotesService.findById(noteId); return response.send(note); } catch (e) { const code = e.errorCode || 500; console.log(e); return response.status(code).json({ errors: [{ msg: e.message }] }); } } const update = async (request, response) => { const errors = validationResult(request) if (!errors.isEmpty()) { response.status(400).send({ errors: errors.array() }) } const note = request.body; const noteId = request.params.noteId; try { const updatedNote = await NotesService.update(noteId, note); return response.send(updatedNote); } catch (e) { const code = e.errorCode || 500; console.log(e); return response.status(code).json({ errors: [{ msg: e.message }] }); } } const remove = async (request, response) => { const errors = validationResult(request) if (!errors.isEmpty()) { response.status(400).send({ errors: errors.array() }) } const noteId = request.params.noteId; try { await NotesService.remove(noteId); return response.send(); } catch (e) { const code = e.errorCode || 500; console.log(e); return response.status(code).json({ errors: [{ msg: e.message }] }); } } module.exports = { findAll, findById, create, remove, update }<file_sep>Before we can run the project we need to add an environment variable containing the connection string for mongo database You can either install MongoDB on your machine or create a cluster: * [MongoDB](https://www.mongodb.com/download-center/community) * [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) Create a file named `.env` in the root of the project and add the following line of configuration to set a required environment variable named CONNECTION_STRING ``` CONNECTION_STRING = mongodb+srv://<user>:<password>@<host>/<databaseb>?retryWrites=true&w=majority JWT_SECRET = <supersecret> ``` If you are using an Atlas cluster you can get your connection string from your settings dashboard <file_sep>const express = require('express') const cors = require('cors') const path = require('path') class App { constructor(port, routes = []) { this.port = port; this.app = new express(); this.app.set('view engine', 'pug') this.app.get('/', (request, response) => { response.render('index', { title: 'Hello', message: 'Hello World' }) }) // this.app.use(express.static(path.join(__dirname, 'public'))) this.initializeMiddlewares(); this.initializeRoutes(routes); } initializeRoutes(routes) { routes.forEach(router => { this.app.use('/api', router) }); } initializeMiddlewares() { this.app.use(express.json({ extended: false })) this.app.use(cors()) } async listen() { return new Promise((resolve, reject) => { this.app.listen(this.port, () => { resolve(); }).on('error', (error) => { reject(error); }) }) } } module.exports = App;<file_sep>const UsersService = require('../services/users.service') const { validationResult } = require('express-validator') const getProfile = async (request, response) => { const userId = request.params.userId; try { const user = await UsersService.findUserById(userId) response.render('profile', { name: user.name, email: user.email }) } catch (e) { response.render('not_found', { resource: 'User', id: userId }) } } const signIn = async (request, response) => { const errors = validationResult(request); if (!errors.isEmpty()) { return response.status(400).json({ errors: errors.array() }) } const { email, password } = request.body; try { const token = await UsersService.signIn(email, password); return response.send(token); } catch (e) { const code = e.errorCode || 500; console.log(e); return response.status(code).json({ errors: [{ msg: e.message }] }); } } const signUp = async (request, response) => { const errors = validationResult(request); if (!errors.isEmpty()) { return response.status(400).json({ errors: errors.array() }) } const { name, email, password } = request.body; try { const user = await UsersService.signUp(name, email, password); return user; } catch (e) { const code = e.errorCode || 500; console.log(e); return response.status(code).json({ errors: [{ msg: e.message }] }); } } module.exports = { signIn, signUp, getProfile }<file_sep>const { Router } = require('express') const { check } = require('express-validator') const UsersController = require('../controllers/users.controller') const router = new Router(); router.post('/signin', [ check('email', 'Email must be a valid email').exists().isEmail(), check('password').isLength({ min: 8 }).withMessage('Password must be at least 8 characters long'), ], UsersController.signIn) router.post('/signup', [ check('name', 'Name is required').notEmpty(), check('email', 'Email must be a valid email').isEmail(), check('password').isLength({ min: 8 }).withMessage('Password must be at least 8 characters long'), ], UsersController.signUp) router.get('/user/:userId', UsersController.getProfile); module.exports = router;<file_sep>const { Router } = require('express') const { check } = require('express-validator') const auth = require('../middlewares/auth.middleware') const NotesController = require('../controllers/notes.controller') const router = new Router(); router.get('/notes', [ auth, // check('content', 'Content is required').notEmpty().isLength({ max: 500 }) ], NotesController.findAll); router.get('/notes/:noteId', [ auth, check('noteId').isMongoId().withMessage('Invalid ID') ], NotesController.findById); router.post('/notes', [ auth, check('userId', 'userId is required').exists().isMongoId().withMessage('Invalid Id') ], NotesController.create); router.put('/notes/:noteId', auth, NotesController.update); router.delete('/notes/:noteId', auth, NotesController.remove); module.exports = router;
5cdb99baf9fd2372e3e4198f81befc1da5a69c9c
[ "JavaScript", "Markdown" ]
6
JavaScript
devjuliet/node-express-workshop
1017ef61a1f82ed933e852a8cec17d8215fe51c5
00334b4c72fb42d58554d504c4f319fa72dbab0b
refs/heads/master
<file_sep>BioGraPy - Biological Graphical Library in Python ================================================= Fork that adds support to plot the tracks below an existing figure, and adds some new features to draw such as text sequence with automatic font size and highlighted text. ```python import matplotlib import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import numpy as np import biograpy from Bio.SeqFeature import SeqFeature, FeatureLocation from Bio.Seq import Seq fig1, ax = plt.subplots(figsize=(10,3), dpi=300) ax.scatter(x=list(range(0, 1200)), y=np.random.random(1200)) ax.set_xlim([0,1200]) ax.set_ylim([0,2]) # We use the package biograpy to create Panel, tracks, and features panel = biograpy.Panel(fig1) track = biograpy.tracks.BaseTrack() # Simple feature drawn as a rectangle track.add_feature(biograpy.features.Simple(name='Simple1', start = 50, end = 300)) # Gene feature drawn as an arrow genefeat = SeqFeature(FeatureLocation(100,500), type='gene', strand=1) track.add_feature(biograpy.features.GeneSeqFeature(genefeat, name='GeneSeqFeature1')) # Simple feature with color track.add_feature(biograpy.features.Simple(name='Simple_colored1', start = 500, end = 820, color_by_cm=False, fc='r')) # Gene feature with color track.add_feature(biograpy.features.GeneSeqFeature(genefeat,name='GeneSeqFeature2_colored',fc='r')) # Very short gene feature (to test the arrow head automatic sizing) genefeat = SeqFeature(FeatureLocation(800,810), type='gene', strand=1) track.add_feature(biograpy.features.GeneSeqFeature(genefeat, name='GeneSeqFeature_very_short')) # mRNA with one CDS drawn as a shaded rectangle with an arrow on top CDS_feature = SeqFeature(FeatureLocation(180,1000), type='CDS', strand=-1) mRNA_feature = SeqFeature(FeatureLocation(180,1100), type='mRNA', strand=-1) mRNAandCDSfeat = biograpy.features.CoupledmRNAandCDS(mRNA_feature, CDS_feature, name='CoupledmRNAandCDS1_strandm', ec='k') track.add_feature(mRNAandCDSfeat) # mRNA with CDS, custom color CDS_feature = SeqFeature( FeatureLocation(200,600), type='CDS', strand=1) mRNA_feature = SeqFeature( FeatureLocation(100,800), type='mRNA', strand=1) mRNAandCDSfeat = biograpy.features.CoupledmRNAandCDS(mRNA_feature, CDS_feature, name='CoupledmRNAandCDS1_strandp_colored', ec='r', fc='r') track.add_feature(mRNAandCDSfeat) # Very short mRNA with CDS (to test the arrow head automatic sizing) CDS_feature = SeqFeature( FeatureLocation(250,260), type='CDS', strand=1) mRNA_feature = SeqFeature( FeatureLocation(220,300), type='mRNA', strand=1) mRNAandCDSfeat = biograpy.features.CoupledmRNAandCDS(mRNA_feature, CDS_feature, name='CoupledmRNAandCDS1_very_short') track.add_feature(mRNAandCDSfeat) # Gene feature on minus strand geneSeqfeat = SeqFeature( FeatureLocation(900,200), type = 'gene', strand=-1) genefeat = biograpy.features.GeneSeqFeature(geneSeqfeat, name='GeneSeqFeature3_strandm') track.add_feature(genefeat) track2 = biograpy.tracks.BaseTrack(biograpy.features.Simple(name='Simple3_track2', start= 0, end = 80)) panel.add_track(track) panel.add_track(track2) panel._draw_tracks() panel.save('biograpy_test1.png') ``` ![example1](/examples/biograpy_test1.png) ```python fig1, ax = plt.subplots(figsize=(11,3), dpi=400) ax.scatter(x=list(range(0, 100)), y=np.random.random(100)) ax.set_xlim([0,100]) ax.set_ylim([0,2]) # Create panel and track panel = biograpy.Panel(fig1) track = biograpy.tracks.BaseTrack() # Text sequence feature track.add_feature(biograpy.features.TextSequence( 'MKKVIVIGVNHAGTSFIRTLLSKSKDFQVNAYDRNTNISFLGCGIALAVSGVVKNTEDLFYSTPEELKAMGANVFMAHDVVGLDLDKKQVIVKDL', start=10, name="TextSequence1")) """ Pretty text sequence feature allows to pass a text sequence together with a list of regions to highlight. The font size is calculated automatically to fit the scale of the x axis. """ prettyTextFeat = biograpy.features.PrettyTextSequence( 'KSKDFQVNAYDRNMKKVIVIGVNHAGTSFIRTLLSKSKDFQVNAYDRNTNISFLGCGIALAVSGVVKNTEDLFYSTPEELKAMGANVFMAHDVVGLDLDKKQVIVKDLATGKETVDHY', highlightList=[{'start':0, 'end':10, 'background_color':'red', 'background_color_alpha':0.4, 'weight':900}, {'start':20, 'end':25, 'foreground_color':'blue', 'weight':100} ], start=20, name='PrettyTextSequence1') track.add_feature(prettyTextFeat) panel.add_track(track) panel.save('biograpy_test2.png') panel._draw_tracks() ``` ![example1](/examples/biograpy_test2.png)<file_sep>from .drawer import Panel from .seqrecord import SeqRecordDrawer, SliceSeqRec __import__('pkg_resources').declare_namespace(__name__) <file_sep> # coding: utf-8 # In[1]: import matplotlib get_ipython().magic('matplotlib inline') import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import numpy as np from pathlib import Path import biograpy from Bio.SeqFeature import SeqFeature, FeatureLocation from Bio.Seq import Seq savefig = False # In[2]: if False: fig1, ax = plt.subplots(figsize=(10,3), dpi=300) ax.scatter(x=list(range(0, 1200)), y=np.random.random(1200)) ax.set_xlim([0,1200]) ax.set_ylim([0,2]) # We use the package biograpy to plot Panel, tracks, and features panel = biograpy.Panel(fig1) track = biograpy.tracks.BaseTrack() track.add_feature(biograpy.features.Simple(name='Simple1', start = 50, end = 300)) genefeat = SeqFeature(FeatureLocation(100,500), type='gene', strand=1) track.add_feature(biograpy.features.GeneSeqFeature(genefeat, name='GeneSeqFeature1')) track.add_feature(biograpy.features.Simple(name='Simple_colored1', start = 500, end = 820, color_by_cm=False, fc='r')) track.add_feature(biograpy.features.GeneSeqFeature(genefeat,name='GeneSeqFeature2_colored',fc='r')) genefeat = SeqFeature(FeatureLocation(800,810), type='gene', strand=1) track.add_feature(biograpy.features.GeneSeqFeature(genefeat, name='GeneSeqFeature_very_short')) CDS_feature = SeqFeature(FeatureLocation(180,1000), type='CDS', strand=-1) mRNA_feature = SeqFeature(FeatureLocation(180,1100), type='mRNA', strand=-1) mRNAandCDSfeat = biograpy.features.CoupledmRNAandCDS(mRNA_feature, CDS_feature, name='CoupledmRNAandCDS1_strandm', ec='k') track.add_feature(mRNAandCDSfeat) CDS_feature = SeqFeature( FeatureLocation(200,600), type='CDS', strand=1) mRNA_feature = SeqFeature( FeatureLocation(100,800), type='mRNA', strand=1) mRNAandCDSfeat = biograpy.features.CoupledmRNAandCDS(mRNA_feature, CDS_feature, name='CoupledmRNAandCDS1_strandp_colored', ec='r', fc='r') track.add_feature(mRNAandCDSfeat) CDS_feature = SeqFeature( FeatureLocation(250,260), type='CDS', strand=1) mRNA_feature = SeqFeature( FeatureLocation(220,300), type='mRNA', strand=1) mRNAandCDSfeat = biograpy.features.CoupledmRNAandCDS(mRNA_feature, CDS_feature, name='CoupledmRNAandCDS1_very_short') track.add_feature(mRNAandCDSfeat) geneSeqfeat = SeqFeature( FeatureLocation(900,200), type = 'gene', strand=-1) genefeat = biograpy.features.GeneSeqFeature(geneSeqfeat, name='GeneSeqFeature3_strandm') track.add_feature(genefeat) track2 = biograpy.tracks.BaseTrack(biograpy.features.Simple(name='Simple3_track2', start= 0, end = 80)) panel.add_track(track) panel.add_track(track2) if savefig: panel.save('biograpy_test1.png') panel.close() else: panel._draw_tracks() fig1, ax = plt.subplots(figsize=(11,3), dpi=400) ax.scatter(x=list(range(0, 100)), y=np.random.random(100)) ax.set_xlim([0,100]) ax.set_ylim([0,2]) ############################################## panel = biograpy.Panel(fig1) track = biograpy.tracks.BaseTrack() track.add_feature(biograpy.features.TextSequence( 'MKKVIVIGVNHAGTSFIRTLLSKSKDFQVNAYDRNTNISFLGCGIALAVSGVVKNTEDLFYSTPEELKAMGANVFMAHDVVGLDLDKKQVIVKDL', start=10, name="TextSequence1")) # There is one limitation to our text features, is that the font size is calculated when creating the # PrettyTextSequence object, based on the current axis. Therefore, we cannot re-use the PrettyTextSequence # in another Panel, for example. Possibly in another track with the same dimensions should be ok. prettyTextFeat = biograpy.features.PrettyTextSequence( list('KSKDFQVNAYDRN') + [('A', {'fontproperties':FontProperties(**{'weight':'bold'}), 'size':20}), ('A', {})] + list('CGIALAVTE') + [('A', {'fontproperties':FontProperties(**{'weight':'bold', 'size':36})})] + # this gets overridden by automatic font size [(c, {'bbox':dict(facecolor='blue', alpha=0.4, edgecolor='none', pad=0.0)}) for c in list('ATGCATGC')] + list('KSKDFQVNAYDRN') + [(c, {'color':'red'}) for c in list('ATGCATGC')] + ['B', 'R', 'G', 'C', 'T', 'T', 'A', 'G', 'C'] + list('MKKVIVIGVNHAGTSFIRTLLSKSKDFQVNAYDRNTNISFLGCGIALAVSGVVKNTEDLFYSTPEELKAMGANVFMAHDVVGLDLDKKQVIVKDLATGKETVDHY'), start=20, name='PrettyTextSequence1') track.add_feature(prettyTextFeat) panel.add_track(track) if savefig: panel.save('biograpy_test2.png') panel.close() else: panel._draw_tracks() ############################################## # Here we test the exact same plot but with a longer range in the x axis, in order # to test the automatic font size of the sequence features. fig1, ax = plt.subplots(figsize=(11,3), dpi=400) ax.scatter(x=list(range(0, 200)), y=np.random.random(200)) ax.set_xlim([0,200]) ax.set_ylim([0,2]) # We use the package biograpy to plot Panel, tracks, and features panel = biograpy.Panel(fig1) track = biograpy.tracks.BaseTrack() track.add_feature(biograpy.features.TextSequence( 'MKKVIVIGVNHAGTSFIRTLLSKSKDFQVNAYDRNTNISFLGCGIALAVSGVVKNTEDLFYSTPEELKAMGANVFMAHDVVGLDLDKKQVIVKDLATGKETVDHYDQLVVASGAWPICMNVENEVTHTQLQFNHTDKYCGNIKNLISCKLYQHALTLIDSFRHDKSIKSVAIVGSGYIGLELAEAAWQCGKQVTVIDMLDKPAGNNFDEEFTNELEKAMKKAGINLMMGSAVKGFIVDADKNVVKGVETDKGRVDADLVIQSIGFRPNTQFVPKDRQFEFNRNGSIKVNEYLQALNHENVYVIGGAAAIYDAASEQYENIDLATNAVKSGLVAAMHMIGSKAVKLESIVGTNALHVFGLNLAATGLTEKRAKM', start=10, name="TextSequence1")) prettyTextFeat = biograpy.features.PrettyTextSequence( list('KSKDFQVNAYDRN') + [('A', {'fontproperties':FontProperties(**{'weight':'bold'}), 'size':20}), ('A', {})] + list('CGIALAVTE') + [('A', {'fontproperties':FontProperties(**{'weight':'bold', 'size':36})})] + # this gets overridden by automatic font size [(c, {'bbox':dict(facecolor='blue', alpha=0.4, edgecolor='none', pad=0.0)}) for c in list('ATGCATGC')] + list('KSKDFQVNAYDRN') + [(c, {'color':'red'}) for c in list('ATGCATGC')] + ['B', 'R', 'G', 'C', 'T', 'T', 'A', 'G', 'C'] + list('MKKVIVIGVNHAGTSFIRTLLSKSKDFQVNAYDRNTNISFLGCGIALAVSGVVKNTEDLFYSTPEELKAMGANVFMAHDVVGLDLDKKQVIVKDLATGKETVDHY'), start=20, name='PrettyTextSequence1') track.add_feature(prettyTextFeat) panel.add_track(track) if savefig: panel.save('biograpy_test2b.png') panel.close() else: panel._draw_tracks() # In[4]: ############################################## # We also test the MPN annotations import json import pandas as pd from mwTools.mpn_annotation_tools import plot_add_annotations from mwTools.paths import p p = p('isis') mpnAnnotationPath = p.mpnAnnotationPath # Import annotations with (mpnAnnotationPath / 'mpnAnnotFeaturesDf6ColList.json').open('r') as f: mpnAnnotFeaturesDf6ColList = json.load(f) mpnAnnotFeaturesDf = pd.read_json(str(mpnAnnotationPath / 'mpnAnnotFeaturesDf6B.json'))[mpnAnnotFeaturesDf6ColList] mpnPlot = mpnAnnotFeaturesDf[(mpnAnnotFeaturesDf.id == 'ncMPN015') & (mpnAnnotFeaturesDf.feature == 'ncRNA') ].iloc[0] xPad = 30 x0 = mpnPlot['start'] - xPad x1 = mpnPlot['end'] + xPad fig1, ax = plt.subplots(figsize=(11,3), dpi=400) ax.scatter(x=list(range(x0, x1)), y=np.random.random(x1 - x0)) ax.set_xlim([x0, x1]) ax.set_ylim([0, 1.5]) DNAFeatList = [('ncMPN015', [{'start':53 + mpnPlot['start'], 'end':56 + mpnPlot['start'], 'fontPropDict':{'bbox':dict(facecolor='red', alpha=0.4, edgecolor='blue', pad=0.0)}}, {'start':3 + mpnPlot['start'], 'end':6 + mpnPlot['start'], 'highlightColor':'red'} ] )] plot_add_annotations(ax=ax, fig=fig1, mpnAnnotFeaturesDf=mpnAnnotFeaturesDf, ncRNA=True, idCol='id', DNAFeatList=DNAFeatList)
f327fa62d15b591604ae49d1dd9c883a24aceefb
[ "Markdown", "Python" ]
3
Markdown
shouldsee/BioGraPy
2b31b122767c7c7872880436cf64da8e1ebb2ba9
7f776e464c6a58af8a8009fba3de7b717c9483c9
refs/heads/master
<repo_name>kpingul/tcproject<file_sep>/serve.js var express = require('express'), app = express(), port = 3000; app.use(express.static(__dirname + '/')); app.listen(port);
ca27d8d53d63a8c86ce0fb8bf266033a97546a7f
[ "JavaScript" ]
1
JavaScript
kpingul/tcproject
95e773d0dbd8570115e10214b324f5150edac768
42265f78a6005dbc4a2fc2cd41e928f98da66e6e
refs/heads/master
<file_sep># coding: utf-8 Gem::Specification.new do |spec| spec.name = "bonsai-elasticsearch-rails" spec.version = "0.2.0" spec.authors = ["<NAME>", "<NAME>"] spec.email = ["<EMAIL>", "<EMAIL>"] spec.summary = "Integrate your elasticsearch-rails gem with Bonsai Elasticsearch." spec.description = <<-EOF This gem offers a shim to connect Rails apps with a Bonsai Elasticsearch cluster. The official Elasticsearch gem package requires some minor configuration tweaks in order to work correctly with Bonsai (namely the client needs to be instantiated with the cluster location and HTTP authentication details), and the process can be somewhat complicated for users who are unfamiliar with the system. The bonsai-elasticsearch-rails gem automatically sets up the Elasticsearch client correctly so users don't need to worry about configuring it in their code or writing an initializer. In order for the gem to work correctly, the application needs an environment variable called `BONSAI_URL`, which is populated with the complete Bonsai Elaticsearch cluster URL, including the HTTP authentication. The cluster URL will follow this pattern: https://user1234:[email protected]/ On Heroku, this variable is created and populated automatically when Bonsai is added to the application. Heroku users therefore do not need to perform any additional configuration to connect to their cluster after adding the bonsai-elasticsearch-rails gem. Users who are self-hosting their Rails app will need to make sure this environment variable is present: export BONSAI_URL="https://user1234:[email protected]/" The cluster URL is available via the Bonsai dashboard. EOF spec.homepage = "https://github.com/omc/bonsai-elasticsearch-rails" spec.license = "MIT" spec.files = [ "lib/bonsai-elasticsearch-rails.rb", "lib/bonsai/elasticsearch/rails/railtie.rb" ] spec.require_paths = [ "lib" ] spec.add_dependency "elasticsearch-model", ">= 0", "< 6.0" spec.add_dependency "elasticsearch-rails", ">= 0", "< 6.0" spec.add_development_dependency "bundler", "~> 1" spec.add_development_dependency "rake", "< 11.0" end <file_sep># bonsai-elasticsearch-rails gem This gem offers a shim to connect Rails apps with a Bonsai Elasticsearch cluster. The official Elasticsearch gem package requires some minor configuration tweaks in order to work correctly with Bonsai (namely the client needs to be instantiated with the cluster location and HTTP authentication details), and the process can be somewhat complicated for users who are unfamiliar with the system. The bonsai-elasticsearch-rails gem automatically sets up the Elasticsearch client correctly so users don't need to worry about configuring it in their code or writing an initializer. ## Installation Add this line to your application's Gemfile: ``` gem 'bonsai-elasticsearch-rails' ``` And then run: ``` $ bundle install ``` Or install it yourself as: ``` $ gem install bonsai-elasticsearch-rails ``` You will now have access to the Elasticsearch ruby client via: ```ruby Elasticsearch::Model.client ``` ## Details In order for the gem to work correctly, the application needs an environment variable called `BONSAI_URL`, which is populated with the complete Bonsai Elaticsearch cluster URL, including the HTTP authentication. The cluster URL will follow this pattern: https://user1234:[email protected]/ On Heroku, this variable is created and populated automatically when Bonsai is added to the application. Heroku users therefore do not need to perform any additional configuration to connect to their cluster after adding the bonsai-elasticsearch-rails gem. Users who are self-hosting their Rails app will need to make sure this environment variable is present: ``` $ export BONSAI_URL="https://user1234:[email protected]/" ``` The cluster URL is available via the Bonsai dashboard. ## Support Having trouble with the gem? Find a problem or a bug? Just want to say thanks? Shoot us an [email](mailto:<EMAIL>)!
ea9e04574241c86c531b64c467fc9ea8f9ff33db
[ "Markdown", "Ruby" ]
2
Ruby
mobilizeio/bonsai-elasticsearch-rails
6833a121714c90b832d928ee3c990bfb1c4b1a20
02aea112235dc682deb22eec3bc9fa06903074b7
refs/heads/master
<repo_name>askmeegs/weatherstation<file_sep>/client.py from cassandra.cluster import Cluster from cassandra.policies import DCAwareRoundRobinPolicy import sched, time import random from random import randint import uuid cities=["New York", "Baltimore", "Charlotte", "Atlanta", "Orlando", "Austin", "Los Angeles", "Salt Lake City", "Chicago"] s = sched.scheduler(time.time, time.sleep) cluster = Cluster(['c2.default.svc.cluster.local', 'c1.default.svc.cluster.local', 'c0.default.svc.cluster.local'], load_balancing_policy=DCAwareRoundRobinPolicy(), port=9042) session = cluster.connect('starrynight') def write_weather(sc): insert_id = randint(10000000, 99999999) # 8-digit uuid timestamp = uuid.uuid1() city = random.choice(cities) temperature = randint(10, 90) print("inserting: %s %s %s %s" % (insert_id, city, temperature, timestamp)) session.execute( """ INSERT INTO weather (id, location, temperature, timestamp) VALUES (%s, %s, %s, %s) """, (insert_id, city, temperature, timestamp) ) s.enter(2, 1, write_weather, (sc,)) s.enter(2, 1, write_weather, (s,)) s.run() <file_sep>/README.md # weatherstation Cassandra + Istio VMs demo <file_sep>/Dockerfile # pull official base image FROM python:3.7-alpine # set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # set work directory WORKDIR /weatherstation # install dependencies RUN pip install --upgrade pip RUN pip install pipenv COPY ./Pipfile /weatherstation/Pipfile RUN pipenv install --skip-lock --system --dev # copy project COPY client.py /weatherstation/ CMD ["python", "/weatherstation/client.py"]
5135c825989706ed829f059f228cd5ac93dbefd3
[ "Markdown", "Python", "Dockerfile" ]
3
Python
askmeegs/weatherstation
f91cfa99464c39a6ca11e9fdfacbd3ce192f1b85
6516472eb33187847a1ace5d2bd5598553662de7
refs/heads/master
<repo_name>chocolat2000/pik.io<file_sep>/pmailsmtp.js 'use strict'; var mongoose = require('mongoose'); var nacl = require('js-nacl').instantiate(); var simplesmtp = require('simplesmtp'); var mailparser = require('mailparser').MailParser; //var tools = require('./pmail-tools'); var domains = ['pik.io']; var smtp = simplesmtp.createServer({ localAddress: '127.0.0.1', name: 'front1.pik.io', SMTPBanner: 'hello boy !', ignoreTLS: true, disableDNSValidation: true }); var usersSchema = new mongoose.Schema ({ username : String, boxnonce : String, signnonce : String, pk : String, sk : String, signpk : String, signsk : String, salt : String, meta : { nonce : String, value : String } }); var mailsSchema = new mongoose.Schema ({ username : String, folder : String, sign : String, nonce : String, pk : String, body : String }); var User = mongoose.model('users', usersSchema); var Mail = mongoose.model('mails', mailsSchema); mongoose.connect('mongodb://localhost/pmail'); smtp.listen(2525, function(err) { if(err) console.log(err); }); smtp.on('validateSender ', function(connection, email, done){ done(); }); smtp.on('startData', function(connection) { connection.parser = new mailparser(); //connection.parser.connection = connection; connection.parser.on('end',endParser); }); smtp.on('data', function(connection, chunk){ connection.parser.write(chunk); }); smtp.on('dataReady', function(connection, callback){ callback(null, 'thanks!'); connection.parser.end(); }); var endParser = function(mail) { var usernames = []; for(var key in mail.to) { var _to = (mail.to[key].address || '').split('@'); if(_to.length === 2 && (domains.indexOf(_to[1])>-1)) { usernames.push(_to[0]); } } if(usernames.length === 0) return; User.find({username : {$in : usernames}}, 'pk username', function(err, results) { for(var recipient in results) { if(results[recipient].pk) { var userPk = nacl.from_hex(results[recipient].pk); var sessionKeys = nacl.crypto_box_keypair(); var message = nacl.encode_utf8(JSON.stringify(mail)); var nonce = nacl.crypto_box_random_nonce(); var m_encrypted = nacl.crypto_box(message,nonce,userPk,sessionKeys.boxSk); (new Mail( { username: results[recipient].username, pk: nacl.to_hex(sessionKeys.boxPk), nonce: nacl.to_hex(nonce), body: nacl.to_hex(m_encrypted), folder: 'inbox' })) .save(function(err) { if(err) { console.log(err); } }); } } }); } <file_sep>/pmail.js 'use strict'; var express = require('express'); //var MemcachedStore = require('connect-memcached')(express); var tools = require('./pmail-tools'); var app = express(); //var domains = ['pik.io']; app.configure(function(){ app .use(express.favicon()) .use(express.compress()) .use(express.cookieParser()) //.use(express.session({ // secret: tools.randomSession(32), // store: new MemcachedStore({ // hosts: [ '127.0.0.1:11211' ] // }) //})) .use(express.session({secret: tools.randomSession(32)})) //.use(express.cookieSession()) .use(express.json()) .use(app.router); }); app .get('/', function(req, res) { res.redirect('/index.htm'); }) .post('/login/:username', function(req, res){ if((req.params.username.length < 3) || !req.body.hasOwnProperty('p')) { res.send({status: 'NOK'}); return; } tools.newUser(req.params.username,req.body.p,function(err,user) { if(err) { res.send({status: 'NOK'}); } else { req.session.user = user; res.send({status: 'OK'}); } }); }) .get('/login/:username', function(req, res){ if(!req.query.hasOwnProperty('p')) { res.send({status: 'NOK'}); return; } tools.loadUser(req.params.username,req.query.p,function(err,user) { if(err) { res.send({status: 'NOK'}); } else { req.session.user = user; res.send({ status: 'OK', meta:user.meta }); } }); }) .put('/login/:username', function(req, res){ if(!(req.session.user && (req.session.user.username === req.session.username))) { res.send({status: 'NOK'}); } else { var request = tools.decodeRequest(req); usersdb.get(req.session.username, function(err,result) { result.value.p = request.p; usersdb.set(req.session.username, result.value, function(err, result) { if(!err) { res.send({status: 'OK'}); } else { res.send({status: 'NOK'}); } }); }); } }) .get('/logout', function(req, res){ delete req.session.user; res.send({status: 'OK'}); }) .get('/inboxes', function(req, res){ if(req.session.user) { var params = { folder: 'inbox', limit: req.query.hasOwnProperty('limit') ? req.query.limit : 20, firstElem: req.query.hasOwnProperty('firstElem') ? req.query.firstElem : 0 }; tools.getMails(req.session.user,params,function(err,mails) { if(err) { res.send({ inboxes: [], meta : { status: 'NOK' } }); } else { res.send({ inboxes: mails, meta : { message : 'OK', hasNext : mails.length === params.limit, hasPrevious : params.firstElem > 0 } }); } }); } else { res.send({ inboxes: [], meta : { status: 'NOK' } }); } }) .get('/sents', function(req, res){ if(req.session.user) { var params = { folder: 'sent', limit: req.query.hasOwnProperty('limit') ? req.query.limit : 20, firstElem: req.query.hasOwnProperty('firstElem') ? req.query.firstElem : 0 }; tools.getMails(req.session.user,params,function(err,mails) { if(err) { res.send({ sents: [], meta : { status: 'NOK' } }); } else { res.send({ sents: mails, meta : { message : 'OK', hasNext : mails.length === params.limit, hasPrevious : params.firstElem > 0 } }); } }); } else { res.send({ sents: [], meta : { status: 'NOK' } }); } }) .get('/trashes', function(req, res){ if(req.session.user) { var params = { folder: 'trash', limit: req.query.hasOwnProperty('limit') ? req.query.limit : 20, firstElem: req.query.hasOwnProperty('firstElem') ? req.query.firstElem : 0 }; req.session.user.getMails(params, function(err,mails) { if(err) { res.send({ trashes: [], meta : { status: 'NOK' } }); } else { res.send({ trashes: mails, meta : { message : 'OK', hasNext : mails.length === params.limit, hasPrevious : params.firstElem > 0 } }); } }); } else { res.send({ trashes: [], meta : { status: 'NOK' } }); } }) .delete('/inboxes/:mailid', function(req, res){ if(req.session.user) { tools.deleteMail(req.params.mailid, function(err) { if(!err) { var params = { folder: 'inbox', limit: req.query.hasOwnProperty('limit') ? req.query.limit : 20, firstElem: req.query.hasOwnProperty('firstElem') ? req.query.firstElem : 0 }; tools.getMails(req.session.user,params,function(err,mails) { if(err) { res.send({ inboxes: [], meta : { status: 'NOK' } }); } else { res.send({ inboxes: mails, meta : { message : 'OK', hasNext : mails.length === params.limit, hasPrevious : params.firstElem > 0 } }); } }); } }); } }) .delete('/sents/:mailid', function(req, res){ if(req.session.user) { tools.deleteMail(req.params.mailid, function(err) { if(!err) { var params = { folder: 'sent', limit: req.query.hasOwnProperty('limit') ? req.query.limit : 20, firstElem: req.query.hasOwnProperty('firstElem') ? req.query.firstElem : 0 }; tools.getMails(req.session.user,params,function(err,mails) { if(err) { res.send({ sents: [], meta : { status: 'NOK' } }); } else { res.send({ sents: mails, meta : { message : 'OK', hasNext : mails.length === params.limit, hasPrevious : params.firstElem > 0 } }); } }); } }); } }) .delete('/trashes/:mailid', function(req, res){ if(req.session.user) { tools.deleteMail(req.params.mailid, function(err) { if(!err) { var params = { folder: 'trash', limit: req.query.hasOwnProperty('limit') ? req.query.limit : 20, firstElem: req.query.hasOwnProperty('firstElem') ? req.query.firstElem : 0 }; req.session.user.getMails(params, function(err,mails) { if(err) { res.send({ trashes: [], meta : { status: 'NOK' } }); } else { res.send({ trashes: mails, meta : { message : 'OK', hasNext : mails.length === params.limit, hasPrevious : params.firstElem > 0 } }); } }); } }); } }) .post('/sents', function(req, res){ if(req.session.user) { tools.sendMail(req.session.user,req.body.sent, function(err,result) { if(err) { res.send({ sent:[], meta: { message: 'KO' } }); } else { res.send({ sent:result, meta: { message: 'OK' } }); } }); } }) .put('/update', function(req, res) { if(req.session.user && req.body.meta) { req.session.user.meta = req.body.meta; tools.updateUser(req.session.user, function(err) { if(err) { res.send({status: 'NOK'}); } else { res.send({status: 'OK'}); } }); } }) .use(express.static(__dirname + '/static')) .use(function(req, res, next){ res.setHeader('Content-Type', 'text/html'); res.send(404, '<html><head><title>404</title></head><body><h1>Page introuvable !</h1></body></html>'); }); app.listen(8080); <file_sep>/test1.js var nacl_factory = require("js-nacl"); var nacl = nacl_factory.instantiate();
c532e719dbcf85cebc016fcf95afb1c0a4d48e71
[ "JavaScript" ]
3
JavaScript
chocolat2000/pik.io
8c7a824368d78bb776e734f1e1363afff5430b30
9f20258f0db06e3827241accab34ccf5f72cccf3
refs/heads/master
<file_sep>import argparse import os import torch import numpy as np import cv2 import matplotlib.pyplot as plt from typing import Tuple import yaml from fast_segmentation.core.consts import STANDARD_CROP_SIZE from fast_segmentation.model_components.data_cv2 import TransformationVal from fast_segmentation.model_components.transform_cv2 import ToTensor from fast_segmentation.core.utils import build_model from fast_segmentation.visualization.visualize import save_labels_mask_with_legend torch.set_grad_enabled(False) def parse_args(): """ Creates the parser for inference arguments Returns: The parser """ parse = argparse.ArgumentParser() parse.add_argument('--model', type=str, default='bisenetv2') parse.add_argument('--weight-path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/models/8/best_model.pth') parse.add_argument('--demo-path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/data/inference_results') parse.add_argument('--demo_im_anns', type=str, default='/home/bina/PycharmProjects/fast-segmentation/data/demo.txt') parse.add_argument('--im_root', type=str, default='/home/bina/PycharmProjects/fast-segmentation/data') parse.add_argument('--config_path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/configs/main_cfg.yaml') return parse.parse_args() def read_image_and_label(demo_im_anns: str, im_root: str) -> Tuple[np.ndarray, np.ndarray]: """ Reads image and label according to the first line in the given directory Args: demo_im_anns: the relative path to the file from the root data directory im_root: the root directory for the data Returns: image (rgb) and corresponding label (grayscale) """ with open(demo_im_anns) as ann_file: first_line = ann_file.readline() img_and_label = str.split(first_line, ',') image_path = os.path.join(im_root, img_and_label[0]).rstrip() label_path = os.path.join(im_root, img_and_label[1]).rstrip() image = np.asarray(cv2.imread(image_path)) label = np.asarray(cv2.imread(label_path, 0)) return image, label def create_empty_label(image: np.ndarray) -> np.ndarray: """ Creates an empty annotation mask according to the shape of the given image Args: image: an image with shape WxHxC (C is channels) Returns: black mask with the shape of (WxH) by the given image """ return np.zeros(image.shape[:2]) def preprocess_image(image: np.ndarray, crop_size: Tuple[int, int]) -> torch.Tensor: """ Converts the given image to a pytorch tensor and makes some operations on it Args: crop_size: image: rgb image with shape WxHxC Returns: pytorch tensor image with 4 dimensions (defined by the crop size) """ label = create_empty_label(image) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_label = {'image': image_rgb, 'label': label} image_label_cropped = TransformationVal(crop_size=crop_size)(image_label) image_tensor = ToTensor()(image_label_cropped)['image'] image_tensor = torch.unsqueeze(image_tensor, 0) image_tensor = image_tensor.cuda() # TODO: test that the processed image is the same as in the train return image_tensor def inference(image: np.ndarray, model_type: str, weight_path: str, crop_size: Tuple[int, int] = STANDARD_CROP_SIZE, demo_path: str = None, label: np.ndarray = None, plot: bool = False) -> np.ndarray: """ The main function that responsible of applying the semantic segmentation model on the given image, the result is saved to the corresponding paths Args: plot: crop_size: weight_path: demo_path: image: an image to run the segmentation model on model_type: the name of the model architecture type label: optional - an annotation mask to save next to the result Returns: the prediction - the output of the network, mask in shape WxH (with values in range (0, NUM_CLASSES-1)) """ net = build_model(model_type=model_type, is_distributed=False, pretrained_model_path=weight_path, is_train=False, use_sync_bn=False) image_tensor = preprocess_image(image=image, crop_size=crop_size) # get output from logits logits, *logits_aux = net(image_tensor) out = logits[:1].argmax(dim=1).squeeze().detach().cpu().numpy() original_shape = (image.shape[1], image.shape[0]) out = cv2.resize(src=out, dsize=original_shape, interpolation=cv2.INTER_NEAREST) # save image, label and inference if demo_path is not None: plt.imsave(os.path.join(demo_path, 'inf_image.jpg'), cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) figure, axes = save_labels_mask_with_legend(mask=out, save_path=os.path.join(demo_path, 'inf_result.jpg')) if plot: axes.plot() plt.show() if label is not None: save_labels_mask_with_legend(mask=label, save_path=os.path.join(demo_path, 'inf_label.jpg')) return out if __name__ == '__main__': args = parse_args() with open(args.config_path) as f: cfg = yaml.load(f, Loader=yaml.FullLoader) image_original, label_original = read_image_and_label(demo_im_anns=args.demo_im_anns, im_root=args.im_root) inference(image=image_original, label=label_original, model_type=args.model, weight_path=args.weight_path, demo_path=args.demo_path, crop_size=cfg['crop_size'], plot=True) <file_sep>NUM_WORKERS = 1 IGNORE_LABEL = 255 PIXELS_SCALE = 255 OTHER_LABEL = 0 BAD_IOU = 0.3 STANDARD_CROP_SIZE = (512, 768) LABEL_TO_COLOR = { 'other': (0, 0, 0), 'land': (29, 101, 181), 'trees': (0, 255, 0), 'buildings': (180, 180, 180), 'tents': (0, 20, 100), 'fences': (80, 100, 30), 'sky': (255, 248, 240), 'road': (50, 150, 250), 'country_road': (0, 200, 200), 'windows': (200, 40, 130), 'cars': (250, 0, 0), 'people': (0, 0, 255), } NUM_CLASSES = len(LABEL_TO_COLOR) <file_sep>import math import numpy as np import cv2 import torch from typing import Tuple from fast_segmentation.model_components.consts import MEAN, STD class RandomResizedCrop(object): """ size should be a tuple of (H, W) """ def __init__(self, size: Tuple[int, int], scales: Tuple = (1.,), is_random: bool = True): self.scales = scales self.size = size self.is_random = is_random def __call__(self, im_label): if self.size is None: return im_label image, label = im_label['image'], im_label['label'] assert image.shape[:2] == label.shape[:2], f'image shape is {image.shape}, label shape is {label.shape}' crop_h, crop_w = self.size scale = np.random.uniform(min(self.scales), max(self.scales)) if self.is_random else 1. im_h, im_w = [math.ceil(el * scale) for el in self.size] image = cv2.resize(image, (im_w, im_h)) label = cv2.resize(label, (im_w, im_h), interpolation=cv2.INTER_NEAREST) if (im_h, im_w) == (crop_h, crop_w): return dict(image=image, label=label) pad_h, pad_w = 0, 0 if im_h < crop_h: pad_h = (crop_h - im_h) // 2 + 1 if im_w < crop_w: pad_w = (crop_w - im_w) // 2 + 1 if pad_h > 0 or pad_w > 0: image = np.pad(image, ((pad_h, pad_h), (pad_w, pad_w), (0, 0))) label = np.pad(label, ((pad_h, pad_h), (pad_w, pad_w)), 'constant', constant_values=255) im_h, im_w, _ = image.shape sh, sw = np.random.random(2) sh, sw = int(sh * (im_h - crop_h)), int(sw * (im_w - crop_w)) return dict( image=image[sh:sh + crop_h, sw:sw + crop_w, :].copy(), label=label[sh:sh + crop_h, sw:sw + crop_w].copy() ) class RandomHorizontalFlip(object): def __init__(self, p=0.5): self.p = p def __call__(self, image_label): if np.random.random() < self.p: return image_label image, label = image_label['image'], image_label['label'] assert image.shape[:2] == label.shape[:2] return dict( image=image[:, ::-1, :], label=label[:, ::-1], ) class ColorJitter(object): def __init__(self, brightness=None, contrast=None, saturation=None, is_random=True): self.is_random = is_random if brightness is not None and brightness >= 0: self.brightness = [max(1 - brightness, 0), 1 + brightness] if contrast is not None and contrast >= 0: self.contrast = [max(1 - contrast, 0), 1 + contrast] if saturation is not None and saturation >= 0: self.saturation = [max(1 - saturation, 0), 1 + saturation] def __call__(self, im_label): im, label = im_label['image'], im_label['label'] assert im.shape[:2] == label.shape[:2] if self.brightness is not None: rate = np.random.uniform(*self.brightness) if self.is_random else np.mean(self.brightness) im = self.adj_brightness(im, rate) if self.contrast is not None: rate = np.random.uniform(*self.contrast) if self.is_random else np.mean(self.contrast) im = self.adj_contrast(im, rate) if self.saturation is not None: rate = np.random.uniform(*self.saturation) if self.is_random else np.mean(self.saturation) im = self.adj_saturation(im, rate) return dict(image=im, label=label, ) @staticmethod def adj_saturation(im, rate): m = np.float32([ [1 + 2 * rate, 1 - rate, 1 - rate], [1 - rate, 1 + 2 * rate, 1 - rate], [1 - rate, 1 - rate, 1 + 2 * rate] ]) shape = im.shape im = np.matmul(im.reshape(-1, 3), m).reshape(shape) / 3 im = np.clip(im, 0, 255).astype(np.uint8) return im @staticmethod def adj_brightness(im, rate): table = np.array([ i * rate for i in range(256) ]).clip(0, 255).astype(np.uint8) return table[im] @staticmethod def adj_contrast(im, rate): table = np.array([ 74 + (i - 74) * rate for i in range(256) ]).clip(0, 255).astype(np.uint8) return table[im] class ToTensor(object): """Convert numpy arrays in sample to Tensors.""" def __init__(self, mean=MEAN, std=STD): self.mean = mean self.std = std def __call__(self, image_label): image, label = image_label['image'], image_label['label'] if label is not None: label = torch.from_numpy(label.astype(np.int64).copy()).clone() image = image.transpose(2, 0, 1).astype(np.float32) image = torch.from_numpy(image).div_(255) dtype, device = image.dtype, image.device mean = torch.as_tensor(self.mean, dtype=dtype, device=device)[:, None, None] std = torch.as_tensor(self.std, dtype=dtype, device=device)[:, None, None] image = image.sub_(mean).div_(std).clone() return {'image': image, 'label': label} class Compose(object): def __init__(self, do_list): self.do_list = do_list def __call__(self, image_label): for comp in self.do_list: image_label = comp(image_label) return image_label <file_sep>import torch import torch.nn as nn from fast_segmentation.core.consts import NUM_CLASSES class SoftDiceLoss(nn.Module): """ Soft dice loss calculation for arbitrary batch size, number of classes, and number of spatial dimensions. Assumes the `channels_last` format. # Arguments y_true: b x X x Y( x Z...) x c One hot encoding of ground truth y_pred: b x X x Y( x Z...) x c Network output, must sum to 1 over c channel (such as after softmax) epsilon: Used for numerical stability to avoid divide by zero errors """ def __init__(self, ignore_label=255): super(SoftDiceLoss, self).__init__() self.ignore_label = ignore_label def forward(self, y_pred, y_true, epsilon=1e-6): # skip the batch and class axis for calculating Dice score y_true_one_hot = (torch.arange(NUM_CLASSES).cuda() == y_true[..., None] - 0).permute([0, 3, 1, 2]).type( torch.uint8) one_hot_shape = y_pred.shape y_pred = y_pred[y_true_one_hot != self.ignore_label].reshape([one_hot_shape[0], one_hot_shape[1], -1]) y_true_one_hot = y_true_one_hot[y_true_one_hot != self.ignore_label].reshape( [one_hot_shape[0], one_hot_shape[1], -1]) numerator = 2. * torch.sum(y_pred * y_true_one_hot, dim=[0, 2]) denominator = torch.sum(torch.square(y_pred) + torch.square(y_true_one_hot), dim=[0, 2]) return 1 - torch.mean((numerator + epsilon) / (denominator + epsilon)) # average over classes and batch <file_sep>from fast_segmentation.model_components.architectures.bisenetv2 import BiSeNetV2 model_factory = { 'bisenetv2': BiSeNetV2 } <file_sep>__version__ = '0.0.4.8' <file_sep>import os import os.path as osp import random import logging import argparse import numpy as np import yaml from tabulate import tabulate import torch import torch.distributed as dist import torch.cuda.amp as amp from torch.utils.tensorboard import SummaryWriter from torch.backends import cudnn from typing import Tuple, List import torch.nn as nn from evaluate import eval_model from fast_segmentation.core.utils import get_next_dir_name, get_next_file_name, build_model from fast_segmentation.model_components.data_cv2 import get_data_loader from fast_segmentation.model_components.soft_dice_loss import SoftDiceLoss from fast_segmentation.model_components.lr_scheduler import WarmupPolyLrScheduler from fast_segmentation.model_components.meters import TimeMeter, AvgMeter from fast_segmentation.model_components.logger import setup_logger, print_log_msg # fix all random seeds torch.manual_seed(123) torch.cuda.manual_seed(123) np.random.seed(123) random.seed(123) torch.backends.cudnn.deterministic = True def parse_args() -> argparse.Namespace: """ Creates the parser for train arguments Returns: The parser """ parse = argparse.ArgumentParser() parse.add_argument('--local_rank', dest='local_rank', type=int, default=0) parse.add_argument('--port', dest='port', type=int, default=44554) parse.add_argument('--model', dest='model', type=str, default='bisenetv2') parse.add_argument('--finetune-from', type=str, default='/home/bina/PycharmProjects/fast-segmentation/models/5/best_model.pth') parse.add_argument('--im_root', type=str, default='/home/bina/PycharmProjects/fast-segmentation/data') parse.add_argument('--train_im_anns', type=str, default='/home/bina/PycharmProjects/fast-segmentation/data/train.txt') parse.add_argument('--val_im_anns', type=str, default='/home/bina/PycharmProjects/fast-segmentation/data/val.txt') parse.add_argument('--log_path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/logs/regular_logs') parse.add_argument('--false_analysis_path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/data/false_analysis') parse.add_argument('--tensorboard_path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/logs/tensorboard_logs') parse.add_argument('--models_path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/models') parse.add_argument('--config_path', type=str, default='/home/bina/PycharmProjects/fast-segmentation/configs/main_cfg.yaml') parse.add_argument('--amp', type=bool, default=True) return parse.parse_args() def get_optimizer(net: nn.Module, lr_start, optimizer_betas, weight_decay) -> torch.optim.Optimizer: """ Builds the optimizer for the given pytorch model Args: net: a pytorch nn model weight_decay: optimizer_betas: lr_start: Returns: an Adam optimizer for the given model """ wd_params, non_wd_params = [], [] for name, param in net.named_parameters(): if param.dim() == 1: non_wd_params.append(param) elif param.dim() == 2 or param.dim() == 4: wd_params.append(param) params_list = [ {'params': wd_params}, {'params': non_wd_params, 'weight_decay': 0} ] optimizer = torch.optim.Adam(params_list, lr=lr_start, betas=optimizer_betas, weight_decay=weight_decay) return optimizer def get_meters(max_iter: int, num_aux_heads: int) -> Tuple[TimeMeter, AvgMeter, AvgMeter, List[AvgMeter]]: """ Creates the meters of the time and the loss Returns: tuple of - (time meter, loss meter, main loss meter, auxiliary loss meter) """ time_meter = TimeMeter(max_iter) loss_meter = AvgMeter('loss') loss_pre_meter = AvgMeter('loss_prem') loss_aux_meters = [AvgMeter('loss_aux{}'.format(i)) for i in range(num_aux_heads)] return time_meter, loss_meter, loss_pre_meter, loss_aux_meters def log_ious(writer: SummaryWriter, mious: List[float], iteration: int, headers: List[str], logger: logging.Logger, mode: str): single_scale_miou, single_scale_crop_miou, ms_flip_miou, ms_flip_crop_miou = mious writer.add_scalar(f"mIOU/{mode}/single_scale", single_scale_miou, iteration) writer.add_scalar(f"mIOU/{mode}/single_scale_crop", single_scale_crop_miou, iteration) writer.add_scalar(f"mIOU/{mode}/multi_scale_flip", ms_flip_miou, iteration) writer.add_scalar(f"mIOU/{mode}/multi_scale_flip_crop", ms_flip_crop_miou, iteration) logger.info(tabulate([mious, ], headers=headers, tablefmt='orgtbl')) def save_best_model(cur_score: float, best_score: float, models_dir: str, net: nn.Module) -> float: """ Saves the model if it is better than the last best model, and returns the score of the current best model Args: cur_score: the score of the current model best_score: the score of the last best model models_dir: the path of the directory of the model weights to save the weights of the best model net: the current pytorch model Returns: the best score """ if cur_score > best_score: best_score = cur_score save_pth = os.path.join(models_dir, f"best_model.pth") state = net.module.state_dict() if dist.get_rank() == 0: torch.save(state, save_pth) return best_score def save_evaluation_log(models_dir: str, logger: logging.Logger, net: nn.Module, writer: SummaryWriter, iteration: int, best_score: float, ims_per_gpu: int, crop_size: Tuple[int, int], log_path: str, im_root: str, val_im_anns: str, false_analysis_path: str, train_im_anns: str) -> float: """ Saves a log with the SummaryWriter, and if the model is the best model until now, saves the model as the best model Args: train_im_anns: false_analysis_path: val_im_anns: im_root: log_path: models_dir: path to the directory to save the model in, in case it is the best model logger: the logger that logs the evaluation log net: the pytorch network writer: the tensorboard summary writer iteration: the index of the current iteration best_score: the score of the best model until now crop_size: ims_per_gpu: Returns: the score of the best model """ log_pth = get_next_file_name(log_path, prefix='model_final_', suffix='.pth') logger.info(f'\nevaluating the model \nsave models to {log_pth}') torch.cuda.empty_cache() # evaluate val set heads_val, mious_val = eval_model(net=net, ims_per_gpu=ims_per_gpu, im_root=im_root, im_anns=val_im_anns, crop_size=crop_size, false_analysis_path=false_analysis_path) log_ious(writer, mious_val, iteration, heads_val, logger, mode='val') # evaluate train set heads_train, mious_train = eval_model(net=net, ims_per_gpu=ims_per_gpu, im_root=im_root, im_anns=train_im_anns, crop_size=crop_size, false_analysis_path=false_analysis_path) log_ious(writer, mious_train, iteration, heads_train, logger, mode='train') # save best model best_score = save_best_model(mious_val[0], best_score, models_dir, net) return best_score def save_checkpoint(models_dir: str, net: nn.Module): """ Saves a checkpoint of the given network to the given directory Args: models_dir: the path to the directory to save the model in net: a pytorch network Returns: None """ save_pth = get_next_file_name(models_dir, prefix='model_final_', suffix='.pth') state = net.module.state_dict() if dist.get_rank() == 0: torch.save(state, save_pth) def train(ims_per_gpu: int, scales: Tuple, crop_size: Tuple[int, int], max_iter: int, use_sync_bn: bool, num_aux_heads: int, warmup_iters: int, use_fp16: bool, message_iters: int, checkpoint_iters: int, lr_start: float, optimizer_betas: Tuple[float, float], weight_decay: float, log_path: str, im_root: str, val_im_anns: str, false_analysis_path: str, train_im_anns: str): """ The main function for training the semantic segmentation model Args: train_im_anns: false_analysis_path: val_im_anns: im_root: log_path: weight_decay: optimizer_betas: lr_start: ims_per_gpu: scales: num_aux_heads: warmup_iters: use_fp16: message_iters: checkpoint_iters: use_sync_bn: max_iter: crop_size: Returns: None """ logger = logging.getLogger() tensorboard_log_dir = get_next_dir_name(root_dir=args.tensorboard_path) models_dir = get_next_dir_name(root_dir=args.models_path) writer = SummaryWriter(log_dir=tensorboard_log_dir) is_dist = dist.is_initialized() # set all components data_loader = get_data_loader(data_path=args.im_root, ann_path=args.train_im_anns, ims_per_gpu=ims_per_gpu, scales=scales, crop_size=crop_size, max_iter=max_iter, mode='train', distributed=is_dist) net = build_model(args.model, is_train=True, is_distributed=is_dist, pretrained_model_path=args.finetune_from, use_sync_bn=use_sync_bn) criteria_pre = SoftDiceLoss() criteria_aux = [SoftDiceLoss() for _ in range(num_aux_heads)] optimizer = get_optimizer(net=net, lr_start=lr_start, optimizer_betas=optimizer_betas, weight_decay=weight_decay) scaler = amp.GradScaler() # mixed precision training time_meter, loss_meter, loss_pre_meter, loss_aux_meters = get_meters(max_iter=max_iter, num_aux_heads=num_aux_heads) lr_scheduler = WarmupPolyLrScheduler(optimizer, power=0.9, max_iter_=max_iter, warmup_iter=warmup_iters, warmup_ratio=0.1, warmup='exp', last_epoch=-1, ) best_score = 0 # train loop for iteration, (image, label) in enumerate(data_loader): image = image.cuda() label = label.cuda() if iteration == 0: writer.add_graph(net, image) label = torch.squeeze(label, 1) optimizer.zero_grad() with amp.autocast(enabled=use_fp16): # get main loss and auxiliary losses logits, *logits_aux = net(image) loss_pre = criteria_pre(logits, label) loss_aux = [criteria(logits, label) for criteria, logits in zip(criteria_aux, logits_aux)] loss = loss_pre + sum(loss_aux) writer.add_scalar("Loss/train", loss, iteration) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() torch.cuda.synchronize() time_meter.update() loss_meter.update(loss.item()) loss_pre_meter.update(loss_pre.item()) _ = [metric.update(loss.item()) for metric, loss in zip(loss_aux_meters, loss_aux)] # print training log message if (iteration + 1) % message_iters == 0: lr = lr_scheduler.get_lr() lr = sum(lr) / len(lr) print_log_msg(iteration, max_iter, lr, time_meter, loss_meter, loss_pre_meter, loss_aux_meters) # saving the model and evaluating it if (iteration + 1) % checkpoint_iters == 0: best_score = save_evaluation_log(models_dir, logger, net, writer, iteration, best_score, ims_per_gpu=ims_per_gpu, crop_size=crop_size, log_path=log_path, im_root=im_root, val_im_anns=val_im_anns, false_analysis_path=false_analysis_path, train_im_anns=train_im_anns) save_checkpoint(models_dir, net) lr_scheduler.step() writer.flush() writer.close() if __name__ == "__main__": args = parse_args() with open(args.config_path) as f: cfg = yaml.load(f, Loader=yaml.FullLoader) torch.cuda.empty_cache() torch.cuda.set_device(args.local_rank) dist.init_process_group( backend='nccl', init_method='tcp://127.0.0.1:{}'.format(args.port), world_size=torch.cuda.device_count(), rank=args.local_rank ) if not osp.exists(args.log_path): os.makedirs(args.log_path) setup_logger('{}-train'.format(args.model), args.log_path) train(ims_per_gpu=cfg['ims_per_gpu'], scales=cfg['scales'], crop_size=cfg['crop_size'], max_iter=cfg['max_iter'], use_sync_bn=cfg['use_sync_bn'], num_aux_heads=cfg['num_aux_heads'], warmup_iters=cfg['warmup_iters'], use_fp16=cfg['use_fp16'], message_iters=cfg['message_iters'], checkpoint_iters=cfg['checkpoint_iters'], lr_start=cfg['lr_start'], optimizer_betas=cfg['optimizer_betas'], weight_decay=cfg['weight_decay'], log_path=args.log_path, im_root=args.im_root, val_im_anns=args.val_im_anns, false_analysis_path=args.false_analysis_path, train_im_anns=args.train_im_anns) <file_sep>import cv2 import numpy as np from matplotlib import pyplot as plt from matplotlib.patches import Rectangle from typing import List, Tuple from fast_segmentation.core.consts import LABEL_TO_COLOR, IGNORE_LABEL, OTHER_LABEL, PIXELS_SCALE def labels_mask_to_colored_image(mask: np.ndarray) -> np.ndarray: """ Converts the mask to an image - replaces the labels with the matching colors Args: mask: a grayscale semantic segmentation annotation mask with values up to the number of classes (like in the consts) Returns: colored annotation mask - rgb """ return np.asarray(list(LABEL_TO_COLOR.values()), dtype=np.uint8)[mask] def put_colored_annotation_on_image(image: np.ndarray, annotation: np.ndarray, opacity: float = 0.5) -> np.ndarray: """ Creates an image with annotation on it Args: image: the original image in RGB format annotation: colored annotation mask in RGB format opacity: the amount of opacity to use in the visualization Returns: the combination of the image and the annotation """ return (((1 - opacity) * image) + (opacity * annotation)).astype("uint8") def get_legends(colors: List[Tuple[int]]) -> List[Rectangle]: """ Creates colored rects for legends of image Args: colors: a list of colors - a color is a tuple of rgb Returns: a list of colored rectangles """ legends = [Rectangle((0, 0), 1, 1, color=np.asarray(color[::-1]) / PIXELS_SCALE) for color in colors] return legends def save_image_with_legends_and_labels(save_path: str, image: np.ndarray, legends: List[Rectangle], labels: List[str]) -> (plt.Figure, plt.Axes): """ Saves the given image with the given legends rects and labels Args: save_path: the path to the folder to save the image image: the image to put the legends on legends: a list of colored rects labels: a list of the names of the legends Returns: the figure and the axes of matplotlib """ figure, axes = plt.subplots() axes.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) axes.legend(legends, labels) axes.axis('off') axes.plot() plt.savefig(save_path, bbox_inches='tight', pad_inches=0) return figure, axes def save_labels_mask_with_legend(mask: np.ndarray, save_path: str) -> (plt.Figure, plt.Axes): """ Converts the mask to a colored rgb mask and saves the new mask to the given path Args: mask: a grayscale mask with values up to the number of classes (like in the consts) save_path: the path to save the new mask Returns: the figure and the axes of matplotlib """ mask[mask == IGNORE_LABEL] = OTHER_LABEL image = labels_mask_to_colored_image(mask) labels = list(LABEL_TO_COLOR.keys()) legends = get_legends(list(LABEL_TO_COLOR.values())) figure, axes = save_image_with_legends_and_labels(save_path, image, legends, labels) return figure, axes <file_sep>import time import datetime from typing import Tuple class TimeMeter(object): """ A class for time measurement through iteration process """ def __init__(self, max_iter): self.iter = 0 self.max_iter = max_iter self.st = time.time() self.global_st = self.st self.curr = self.st def update(self): """ updates the number of iterations passed Returns: None """ self.iter += 1 def get(self) -> Tuple[float, str]: """ Calculates the time of the last iteration and the ETA (estimated time of arrival) Returns: a tuple of the last iteration time and a string of the ETA """ self.curr = time.time() interval = self.curr - self.st global_interval = self.curr - self.global_st eta = int((self.max_iter - self.iter) * (global_interval / (self.iter + 1))) eta = str(datetime.timedelta(seconds=eta)) self.st = self.curr return interval, eta class AvgMeter(object): """ A class for metric average measurement through time """ def __init__(self, name): self.name = name self.seq = [] self.global_seq = [] def update(self, val): """ Updates the lists of the metric - appends the new value Args: val: a new value for the metric Returns: None """ self.seq.append(val) self.global_seq.append(val) def get(self) -> Tuple[float, float]: """ Calculates the averages of the metric Returns: a tuple - (an average of the metric from the last call to this method, global average of the metric) """ avg = sum(self.seq) / len(self.seq) global_avg = sum(self.global_seq) / len(self.global_seq) self.seq = [] return avg, global_avg <file_sep>import os import shutil import torch import torch.distributed as dist from torch import nn from fast_segmentation.model_components.architectures import model_factory from fast_segmentation.core.consts import NUM_CLASSES def get_next_dir_name(root_dir: str) -> str: """ Finds the next index for a new directory name in the given path (searches for integer names for the new directory) Args: root_dir: the path of the directory to locate the new directory in Returns: the path for the new directory """ i = 0 path = os.path.join(root_dir, str(i)) while os.path.exists(path): i += 1 path = os.path.join(root_dir, str(i)) os.mkdir(path) return path def get_next_file_name(root_dir: str, prefix: str, suffix: str) -> str: """ Finds a name for a new file in the given folder - supposes that the file has the given prefix and suffix Args: root_dir: the path of the directory of the new file prefix: a string that is at the beginning of the new file name suffix: a string that is at the end of the new file name Returns: the path for the new file """ i = 0 while os.path.exists(os.path.join(root_dir, f"{prefix}{i}{suffix}")): i += 1 return os.path.join(root_dir, f"{prefix}{i}{suffix}") def build_model(model_type: str, num_classes: int = NUM_CLASSES, is_distributed: bool = True, pretrained_model_path: str = None, is_train: bool = True, use_sync_bn=False) -> nn.Module: """ Builds a model from the given type, if a path to model weights is given then loads the pretrained model Args: model_type: the name of the model architecture num_classes: the number of output channels of the neural network is_distributed: a flag for running the model distributed on multiple machines pretrained_model_path: a path for a pretrained model from the same type is_train: a flag for the mode of the model (training mode / evaluation mode) use_sync_bn: a flag for using SyncBatchNorm Returns: a pytorch neural network model """ net = model_factory[model_type](num_classes) if pretrained_model_path is not None: net.load_state_dict(torch.load(pretrained_model_path)) if use_sync_bn: net = nn.SyncBatchNorm.convert_sync_batchnorm(net) net.cuda() # Moves all model parameters and buffers to the GPU if is_train: net.train() # Sets the module in training mode else: net.eval() if is_distributed: local_rank = dist.get_rank() net = nn.parallel.DistributedDataParallel(net, device_ids=[local_rank, ], output_device=local_rank) return net def delete_directory_content(dir_path: str): for filename in os.listdir(dir_path): file_path = os.path.join(dir_path, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) <file_sep># Fast Urban Semantic Segmentation Our usage of [BiSeNetV2](https://arxiv.org/abs/1808.00897) for semantic segmentation in an urban images case You can install the package from [here](https://test.pypi.org/project/fast-segmentation/) ## platform My platform is like this: * ubuntu 20.04 * nvidia GTX 1080 Ti * cuda 11.2 * miniconda python 3.8 * pytorch 1.7.1 * torchvision 0.8.2 ## get start With a pretrained weight, you can run inference on a single image like this: ``` $ python src/models/inference.py --model bisenetv2 --weight-path models/path/to/your/weights.pth --img-path ./example.png ``` This would run inference on the image and save the result image to `data/inference_results` ## prepare dataset If you want to train on your own dataset, you should generate annotation files first with the format like this: ``` munster_000002_000019_leftImg8bit.png,munster_000002_000019_gtFine_labelIds.png frankfurt_000001_079206_leftImg8bit.png,frankfurt_000001_079206_gtFine_labelIds.png ... ``` Each line is a pair of training sample and ground truth image path, which are separated by a single comma `,`. Then you need to change the field of `im_root` and `train/val_im_anns` in the configuration files. ## train In order to train the model, you can run command like this: ``` $ export CUDA_VISIBLE_DEVICES=0,1 # if you want to train with apex $ python -m torch.distributed.launch --nproc_per_node=2 tools/train.py --model bisenetv2 # or bisenetv1 # if you want to train with pytorch fp16 feature from torch 1.6 $ python -m torch.distributed.launch --nproc_per_node=2 tools/train_amp.py --model bisenetv2 # or bisenetv1 ``` Note that though `bisenetv2` has fewer flops, it requires much more training iterations. The the training time of `bisenetv1` is shorter. ## finetune from trained model You can also load the trained model weights and finetune from it: ``` $ export CUDA_VISIBLE_DEVICES=0,1 $ python -m torch.distributed.launch --nproc_per_node=2 tools/train.py --finetune-from ./res/model_final.pth --model bisenetv2 # or bisenetv1 # same with pytorch fp16 feature $ python -m torch.distributed.launch --nproc_per_node=2 tools/train_amp.py --finetune-from ./res/model_final.pth --model bisenetv2 # or bisenetv1 ``` ## eval pretrained models You can also evaluate a trained model like this: ``` $ python tools/evaluate.py --model bisenetv1 --weight-path /path/to/your/weight.pth ``` <file_sep>import os.path as osp import cv2 import torch import torch.distributed as dist from torch.utils.data import Dataset, DataLoader from typing import Tuple from fast_segmentation.model_components import transform_cv2 as t from fast_segmentation.model_components.sampler import RepeatedDistSampler from fast_segmentation.model_components.transform_cv2 import ToTensor from fast_segmentation.core.consts import NUM_CLASSES, NUM_WORKERS, IGNORE_LABEL class UrbanDataset(Dataset): def __init__(self, data_root: str, ann_path: str, trans_func: callable = None, mode: str = 'train'): super(UrbanDataset, self).__init__() assert mode in ('train', 'val') self.n_cats = NUM_CLASSES self.label_ignore = IGNORE_LABEL self.mode = mode self.trans_func = trans_func self.to_tensor = ToTensor() with open(ann_path, 'r') as fr: pairs = fr.read().splitlines() self.img_paths, self.label_paths = [], [] for pair in pairs: img_pth, label_pth = pair.split(',') self.img_paths.append(osp.join(data_root, img_pth)) self.label_paths.append(osp.join(data_root, label_pth)) assert len(self.img_paths) == len(self.label_paths) self.len = len(self.img_paths) def __getitem__(self, idx): im_pth, label_pth = self.img_paths[idx], self.label_paths[idx] assert cv2.imread(im_pth) is not None, im_pth assert cv2.imread(label_pth, 0) is not None, label_pth img, label_ = cv2.cvtColor(cv2.imread(im_pth), cv2.COLOR_BGR2RGB), cv2.imread(label_pth, 0) assert img.shape[:2] == label_.shape[:2], f'image: {im_pth}, label: {label_pth}\n' \ f'image shape: {img.shape}, label shape: {label_.shape}' image_label = dict(image=img, label=label_) if self.trans_func is not None: image_label = self.trans_func(image_label) image_label = self.to_tensor(image_label) img_tensor, label_tensor = image_label['image'], image_label['label'] return img_tensor.detach(), label_tensor.unsqueeze(0).detach() def __len__(self): return self.len class TransformationTrain(object): def __init__(self, scales: Tuple, crop_size: Tuple[int, int]): self.trans_func = t.Compose([ t.RandomResizedCrop(scales=scales, size=crop_size), t.RandomHorizontalFlip(), t.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4) ]) def __call__(self, image_label): image_label = self.trans_func(image_label) return image_label class TransformationVal(object): def __init__(self, crop_size): self.trans_func = t.Compose([ t.RandomResizedCrop(size=crop_size, is_random=False), t.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, is_random=False) ]) def __call__(self, image_label): return self.trans_func(image_label) def get_data_loader(data_path: str, ann_path: str, ims_per_gpu: int, crop_size: Tuple[int, int], scales: Tuple = None, max_iter: int = None, mode: str = 'train', distributed=True): if mode == 'train': trans_func = TransformationTrain(scales=scales, crop_size=crop_size) batch_size = ims_per_gpu shuffle = True drop_last = True elif mode == 'val': trans_func = TransformationVal(crop_size=crop_size) batch_size = ims_per_gpu shuffle = False drop_last = False else: raise ValueError ds_ = UrbanDataset(data_path, ann_path, trans_func=trans_func, mode=mode) if distributed: assert dist.is_available(), "dist should be initialized" if mode == 'train': assert max_iter is not None n_train_images = ims_per_gpu * dist.get_world_size() * max_iter sampler = RepeatedDistSampler(ds_, n_train_images, shuffle=shuffle, data_source=None) else: sampler = RepeatedDistSampler(ds_, ims_per_gpu, shuffle=shuffle, data_source=None) batch_sampler = torch.utils.data.sampler.BatchSampler(sampler, batch_size, drop_last=drop_last) dl_ = DataLoader(ds_, batch_sampler=batch_sampler, num_workers=NUM_WORKERS, pin_memory=True) else: dl_ = DataLoader(ds_, batch_size=batch_size, shuffle=shuffle, drop_last=drop_last, num_workers=NUM_WORKERS, pin_memory=True) return dl_ <file_sep>import os import cv2 import numpy as np from pathlib import Path import random from consts import OTHER_LABEL, BUILDING_LABEL, MAPPING_DICT_ADE, IRRELEVANT_LABELS_ADE, MAPPING_DICT_CITYSCAPES, \ IRRELEVANT_LABELS_CITYSCAPES, MAPPING_DICT_BARAK, IRRELEVANT_LABELS_BARAK, TRAIN_PERCENT, VAL_PERCENT, TEST_PERCENT def delete_files_in_folder(folder): for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) def filter_data_folder(mapping_dict_, irrelevant_labels_, old_ann_folder_, new_ann_folder_, old_img_folder_, new_img_folder_): delete_files_in_folder(new_img_folder_) delete_files_in_folder(new_ann_folder_) image_counter = 0 relevant_images_counter = 0 # run on all the annotations in the folder list_dir = list(Path(old_ann_folder_).rglob("*.png")) for ann_path in list_dir: ann_old_path = str(ann_path) filename = ann_path.name if 'cityscapes' in ann_old_path and 'label' not in ann_old_path: continue image_counter += 1 old_ann = np.asarray(cv2.imread(ann_old_path)) # filter irrelevant images (by irrelevant annotations) if len(irrelevant_labels_) is not []: if np.in1d(old_ann, np.asarray(irrelevant_labels_)).any(): continue # create correct annotation image new_ann = np.zeros_like(old_ann) + OTHER_LABEL for new_label, old_labels in mapping_dict_.items(): for old_label in old_labels: new_ann[old_ann == old_label] = new_label # take only the width and height of the image if len(new_ann.shape) == 3: new_ann = new_ann[:, :, 1] # save annotation and matching image if BUILDING_LABEL in new_ann: relevant_images_counter += 1 print(relevant_images_counter) new_path = os.path.join(new_ann_folder_, filename) cv2.imwrite(new_path, new_ann) # copy the image of the annotation img_old_path = ann_old_path.replace(old_ann_folder_, old_img_folder_) if 'ADE' in ann_old_path: img_old_path = img_old_path.replace('png', 'jpg') elif 'cityscapes' in ann_old_path: img_old_path = img_old_path.replace('gtFine_labelIds', 'leftImg8bit') elif 'barak' in ann_old_path: img_old_path = img_old_path.replace('png', 'JPG') img_old_path = img_old_path.replace('_w', '') img_new_path = os.path.join(new_img_folder_, filename) # shutil.copy(img_old_path, img_new_path) img = cv2.imread(img_old_path) img = cv2.normalize(img, img, 0, 255, cv2.NORM_MINMAX) cv2.imwrite(img_new_path, img) print(f'There are {image_counter} images in the {old_img_folder_} data-set, {relevant_images_counter} of them are ' f'relevant') def create_train_val_test_txt_files(output_path, data_directories, train_val_test_ratio): train_thresh = train_val_test_ratio[0] val_thresh = train_thresh + train_val_test_ratio[1] random.seed(123) images_directory = 'relevant_images' annotations_directory = 'relevant_annotations' train_file = os.path.join(output_path, 'train.txt') open(train_file, 'w').close() val_file = os.path.join(output_path, 'val.txt') open(val_file, 'w').close() test_file = os.path.join(output_path, 'test.txt') open(test_file, 'w').close() # run on each data directory for directory in data_directories: images_path = os.path.join(base_path, directory, images_directory) image_filenames = [f for f in os.listdir(images_path)] # run on each image and annotation in the directory for img_name in image_filenames: ann_name = img_name if 'ADE' in directory: ann_name = ann_name.replace('jpg', 'png') prob = random.uniform(0, 1) if prob < train_thresh: file_to_write = train_file elif prob < val_thresh: file_to_write = val_file else: file_to_write = test_file img_path = os.path.join(directory, images_directory, img_name) ann_path = os.path.join(directory, annotations_directory, ann_name) # save the image and annotation in the file with open(file_to_write, 'a') as file: file.write(img_path + ',' + ann_path + '\n') if __name__ == '__main__': # ADE base_path = 'data/ADE20k_outdoors' old_img_folder = os.path.join(base_path, 'images/training') new_img_folder = os.path.join(base_path, 'relevant_images') old_ann_folder = os.path.join(base_path, 'annotations/training') new_ann_folder = os.path.join(base_path, 'relevant_annotations') mapping_dict = MAPPING_DICT_ADE irrelevant_labels = IRRELEVANT_LABELS_ADE filter_data_folder(mapping_dict, irrelevant_labels, old_ann_folder, new_ann_folder, old_img_folder, new_img_folder) # CITYSCAPES base_path = 'data/cityscapes' old_img_folder = os.path.join(base_path, 'leftImg8bit') new_img_folder = os.path.join(base_path, 'relevant_images') old_ann_folder = os.path.join(base_path, 'gtFine') new_ann_folder = os.path.join(base_path, 'relevant_annotations') mapping_dict = MAPPING_DICT_CITYSCAPES irrelevant_labels = IRRELEVANT_LABELS_CITYSCAPES filter_data_folder(mapping_dict, irrelevant_labels, old_ann_folder, new_ann_folder, old_img_folder, new_img_folder) # BARAK base_path = '../../data/barak' old_img_folder = os.path.join(base_path, 'images') new_img_folder = os.path.join(base_path, 'relevant_images') old_ann_folder = os.path.join(base_path, 'annotations') new_ann_folder = os.path.join(base_path, 'relevant_annotations') mapping_dict = MAPPING_DICT_BARAK irrelevant_labels = IRRELEVANT_LABELS_BARAK filter_data_folder(mapping_dict, irrelevant_labels, old_ann_folder, new_ann_folder, old_img_folder, new_img_folder) # create train, val, test txt files base_path = '../../data' data_dirs = [ 'ADE20k_outdoors', 'cityscapes', 'barak' ] create_train_val_test_txt_files(output_path=base_path, data_directories=data_dirs, train_val_test_ratio=[TRAIN_PERCENT, VAL_PERCENT, TEST_PERCENT]) <file_sep>torchvision~=0.8.2 opencv-python~=4.5.1.48 numpy~=1.19.4 tqdm~=4.54.1 matplotlib~=3.3.2 tabulate~=0.8.9 pillow~=8.1.0
7e95834849e52e06be52225dc0c352a0374fb582
[ "Markdown", "Python", "Text" ]
14
Python
eilonshi/fast-segmentation
bf9168fafa181ff4eac1d1eba0b0f8a06f5daae1
d7519228407d680e46d9b9e0970b78b45c6b4636
refs/heads/master
<file_sep>angular.module( 'ecp-contactapp', [ 'ecp-contactapp.services.preferences', 'ecp-contactapp.services.http', 'ecp-contactapp.services.offline', 'ecp-contactapp.services.backend', 'ecp-contactapp.services.authentication', 'ecp-contactapp.controllers.contacts', 'ecp-contactapp.controllers.about', 'ecp-contactapp.controllers.options', 'ionic', 'ngResource', 'jett.ionic.filter.bar']) .value('AppConfig', { appPrefix: 'contactapp', baseUrl: "http://127.0.0.1:8080" // TODO: move to preferences service ? }) .config( ["$ionicConfigProvider", function($ionicConfigProvider){ $ionicConfigProvider.tabs.position('bottom'); }]) .run( ["$ionicPlatform", "$rootScope", 'PreferencesService', function($ionicPlatform, $rootScope, PreferencesService) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required window.StatusBar.styleLightContent(); } // utility methods for any view $rootScope.isUndefined = function (thing) { return thing === null || (typeof thing === "undefined"); } $rootScope.isDefined = function (thing) { return !$rootScope.isUndefined(thing); } $rootScope.isDefinedWithLength = function (thing) { return $rootScope.isDefined(thing) && thing.length > 0 } $rootScope.isNotProduction = function (thing) { return PreferencesService.preferences.environment.selected !== "Production" } $rootScope.ionicPlatform = { deviceInformation: ionic.Platform.device(), isWebView: ionic.Platform.isWebView(), // ie running in Cordova isIPad: ionic.Platform.isIPad(), isIOS: ionic.Platform.isIOS(), isAndroid: ionic.Platform.isAndroid(), isWindowsPhone: ionic.Platform.isWindowsPhone(), platform: ionic.Platform.platform(), platformVersion: ionic.Platform.version(), onDevice: ionic.Platform.isWebView() // true if on a device } // for debugging $rootScope.huzzah = function() { $ionicPopup.alert({ title: 'Huzzah', template: 'it worked!' }); } }); }]) .config( ["$stateProvider", "$urlRouterProvider", function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider .state('login', { url: '/login', templateUrl: 'templates/login.html', controller: 'LoginCtrl as ctrl' }) .state('about', { cache: false, url: '/about', templateUrl: 'templates/about.html', controller: 'AboutCtrl as ctrl' }) .state('tab', { cache: false, url: '/tab', templateUrl: 'templates/tabs.html', controller: 'OptionsCtrl as ctrl' }) .state('tab.contactables', { cache: false, url: '/contactables', views: { 'tab-contactables': { templateUrl: 'templates/contactable-list.html', controller: 'ContactablesCtrl as ctrl' } } }) .state('tab.contactable-detail', { cache: false, url: '/contactables/:instanceId', views: { 'tab-contactables': { templateUrl: 'templates/contactable-detail.html', controller: 'ContactableDetailCtrl as ctrl' } } }) ; // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise(function ($injector, $location) { var $state = $injector.get("$state"); $state.go("login"); }); }]) ; <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.contacts.dom; import java.util.Collections; import java.util.List; import java.util.SortedSet; import javax.inject.Inject; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.query.QueryDefault; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroupRepository; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberType; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRole; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRoleRepository; @DomainService( nature = NatureOfService.DOMAIN, repositoryFor = Contact.class ) public class ContactRepository { @Programmatic public java.util.List<Contact> listAll() { return asSortedList(container.allInstances(Contact.class)); } @Programmatic public java.util.List<Contact> find( final String regex ) { java.util.SortedSet<Contact> contacts = Sets.newTreeSet(); contacts.addAll(findByName(regex)); contacts.addAll(findByCompany(regex)); contacts.addAll(findByContactRoleName(regex)); contacts.addAll(findByEmail(regex)); for (ContactGroup contactGroup : contactGroupRepository.findByName(regex)) { contacts.addAll(findByContactGroup(contactGroup)); } return asSortedList(contacts); } @Programmatic public java.util.List<Contact> findByName( final String regex ) { final List<Contact> contacts = container.allMatches( new QueryDefault<>( Contact.class, "findByName", "regex", regex)); return asSortedList(contacts); } @Programmatic public java.util.List<Contact> findByCompany( final String regex ) { final List<Contact> contacts = container.allMatches( new QueryDefault<>( Contact.class, "findByCompany", "regex", regex)); return asSortedList(contacts); } @Programmatic public java.util.List<Contact> findByContactGroup( ContactGroup contactGroup ) { java.util.SortedSet<Contact> contacts = Sets.newTreeSet(); for (ContactRole contactRole : contactRoleRepository.findByGroup(contactGroup)) { contacts.add(contactRole.getContact()); } return asSortedList(contacts); } @Programmatic public java.util.List<Contact> findByContactRoleName( String regex ) { java.util.SortedSet<Contact> contacts = Sets.newTreeSet(); for (ContactRole contactRole : contactRoleRepository.findByName(regex)) { contacts.add(contactRole.getContact()); } return asSortedList(contacts); } @Programmatic public java.util.List<Contact> findByEmail( String regex ) { final List<Contact> contacts = container.allMatches( new QueryDefault<>( Contact.class, "findByEmail", "regex", regex)); return asSortedList(contacts); } @Programmatic public java.util.List<Contact> listOrphanedContacts() { final List<Contact> contacts = container.allMatches( new QueryDefault<>( Contact.class, "listOrphanedContacts")); return asSortedList(contacts); } @Programmatic public Contact create( final String name, final String company, final String email, final String notes, final String officeNumber, final String mobileNumber, final String homeNumber) { final Contact contact = container.newTransientInstance(Contact.class); contact.setName(name); contact.setCompany(company); contact.setEmail(email); contact.setNotes(notes); container.persistIfNotAlready(contact); if (officeNumber != null) { contact.addContactNumber(officeNumber, ContactNumberType.OFFICE.title(), null); } if (mobileNumber != null) { contact.addContactNumber(mobileNumber, ContactNumberType.MOBILE.title(), null); } if (homeNumber != null) { contact.addContactNumber(homeNumber, ContactNumberType.HOME.title(), null); } return contact; } @Programmatic public Contact findOrCreate( final String name, final String company, final String email, final String notes, final String officeNumber, final String mobileNumber, final String homeNumber) { java.util.List<Contact> contacts = findByName(name); Contact contact; if (contacts.size() == 0) { contact = create(name, company, email, notes, officeNumber, mobileNumber, homeNumber); } else { contact = contacts.get(0); } return contact; } @Programmatic public void delete(final Contact contact) { final SortedSet<ContactRole> contactRoles = contact.getContactRoles(); for (ContactRole contactRole : contactRoles) { container.removeIfNotAlready(contactRole); } container.removeIfNotAlready(contact); } private static List<Contact> asSortedList(final List<Contact> contacts) { Collections.sort(contacts); return contacts; } private static List<Contact> asSortedList(final SortedSet<Contact> contactsSet) { final List<Contact> contacts = Lists.newArrayList(); // no need to sort, just copy over contacts.addAll(contactsSet); return contacts; } @javax.inject.Inject org.apache.isis.applib.DomainObjectContainer container; @Inject private ContactRoleRepository contactRoleRepository; @Inject private ContactGroupRepository contactGroupRepository; } <file_sep>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.role.integtests; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.services.wrapper.InvalidException; import org.incode.eurocommercial.contactapp.fixtures.DemoFixture; import org.incode.eurocommercial.contactapp.module.ContactAppDomainIntegTest; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactRepository; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroupRepository; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRole; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRoleRepository; import static org.assertj.core.api.Assertions.assertThat; public class ContactRoleIntegTest extends ContactAppDomainIntegTest { @Inject FixtureScripts fixtureScripts; @Inject ContactGroupRepository contactGroupRepository; @Inject ContactRepository contactRepository; @Inject ContactRoleRepository contactRoleRepository; DemoFixture fs; ContactRole contactRole; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() throws Exception { // given fs = new DemoFixture(); fixtureScripts.runFixtureScript(fs, null); nextTransaction(); this.contactRole = fs.getContacts().get(0).getContactRoles().first(); assertThat(this.contactRole).isNotNull(); } public static class AlsoInGroup extends ContactRoleIntegTest { @Test public void happy_case_using_existing_role_name() throws Exception { // given final int amountOfContactRolesBefore = contactRoleRepository.listAll().size(); assertThat(amountOfContactRolesBefore).isNotZero(); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoInGroup()); final String existingRole = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoInGroup()); final ContactRole newRole = wrap(this.contactRole).alsoInGroup(contactGroup, existingRole, null); // then assertThat(contactRoleRepository.listAll().size()).isEqualTo(amountOfContactRolesBefore + 1); assertThat(contactRoleRepository.listAll()).contains(newRole); } @Test public void happy_case_using_new_role_name() throws Exception { // given final int amountOfContactRolesBefore = contactRoleRepository.listAll().size(); assertThat(amountOfContactRolesBefore).isNotZero(); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoInGroup()); final String newRoleName = "New role"; final ContactRole newRole = wrap(this.contactRole).alsoInGroup(contactGroup, null, newRoleName); // then assertThat(contactRoleRepository.listAll().size()).isEqualTo(amountOfContactRolesBefore + 1); assertThat(contactRoleRepository.listAll()).contains(newRole); } @Test public void happy_case_using_new_role_name_which_also_in_list() throws Exception { // given final int amountOfContactRolesBefore = contactRoleRepository.listAll().size(); assertThat(amountOfContactRolesBefore).isNotZero(); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoInGroup()); final String existingNewRole = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoInGroup()); final ContactRole newRole = wrap(this.contactRole).alsoInGroup(contactGroup, null, existingNewRole); // then assertThat(contactRoleRepository.listAll().size()).isEqualTo(amountOfContactRolesBefore + 1); assertThat(contactRoleRepository.listAll()).contains(newRole); } @Test public void when_no_contact_group_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); // when final ContactGroup contactGroup = null; final String existingRole = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoInGroup()); wrap(this.contactRole).alsoInGroup(contactGroup, existingRole, null); } @Test public void when_no_role_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Must specify either an (existing) role or a new role"); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoInGroup()); wrap(this.contactRole).alsoInGroup(contactGroup, null, null); } @Test public void when_both_existing_role_and_new_role_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Must specify either an (existing) role or a new role"); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoInGroup()); final String existingRole = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoInGroup()); wrap(this.contactRole).alsoInGroup(contactGroup, existingRole, "New role"); } @Test public void possible_groups_should_not_include_any_for_which_contact_already_has_a_role() throws Exception { // given final List<ContactGroup> groupsContactHasRoleFor = contactRole.getContact().getContactRoles() .stream() .map(ContactRole::getContactGroup) .collect(Collectors.toList()); // when final List<ContactGroup> possibleGroups = contactRole.choices0AlsoInGroup(); // then for (ContactGroup contactGroup : possibleGroups) { assertThat(groupsContactHasRoleFor).doesNotContain(contactGroup); } } } public static class AlsoWithContact extends ContactRoleIntegTest { @Test public void happy_case_using_existing_role_name() throws Exception { // given final int amountOfContactRolesBefore = contactRoleRepository.listAll().size(); assertThat(amountOfContactRolesBefore).isNotZero(); // when final Contact contact = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoWithContact()); final String existingRole = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoWithContact()); final ContactRole newRole = wrap(this.contactRole).alsoWithContact(contact, existingRole, null); // then assertThat(contactRoleRepository.listAll().size()).isEqualTo(amountOfContactRolesBefore + 1); assertThat(contactRoleRepository.listAll()).contains(newRole); } @Test public void happy_case_using_new_role_name() throws Exception { // given final int amountOfContactRolesBefore = contactRoleRepository.listAll().size(); assertThat(amountOfContactRolesBefore).isNotZero(); // when final Contact contact = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoWithContact()); final String newRoleName = "New <PASSWORD>"; final ContactRole newRole = wrap(this.contactRole).alsoWithContact(contact, null, newRoleName); // then assertThat(contactRoleRepository.listAll().size()).isEqualTo(amountOfContactRolesBefore + 1); assertThat(contactRoleRepository.listAll()).contains(newRole); } @Test public void happy_case_using_new_role_name_which_also_in_list() throws Exception { // given final int amountOfContactRolesBefore = contactRoleRepository.listAll().size(); assertThat(amountOfContactRolesBefore).isNotZero(); // when final Contact contact = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoWithContact()); final String newExistingRoleName = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoWithContact()); final ContactRole newRole = wrap(this.contactRole).alsoWithContact(contact, null, newExistingRoleName); // then assertThat(contactRoleRepository.listAll().size()).isEqualTo(amountOfContactRolesBefore + 1); assertThat(contactRoleRepository.listAll()).contains(newRole); } @Test public void when_no_contact_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); // when final Contact contact = null; final String existingRole = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoWithContact()); wrap(this.contactRole).alsoWithContact(contact, existingRole, null); } @Test public void when_no_role_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Must specify either an (existing) role or a new role"); // when final Contact contact = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoWithContact()); wrap(this.contactRole).alsoWithContact(contact, null, null); } @Test public void when_both_existing_role_and_new_role_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Must specify either an (existing) role or a new role"); // when final Contact contact = fakeDataService.collections().anyOf(this.contactRole.choices0AlsoWithContact()); final String existingRole = fakeDataService.collections().anyOf(this.contactRole.choices1AlsoWithContact()); wrap(this.contactRole).alsoWithContact(contact, existingRole, "New role"); } @Test public void possible_contacts_should_not_include_any_which_already_have_a_role_in_group() throws Exception { // given final List<Contact> contactsWhichAlreadyHaveRole = contactRole.getContactGroup().getContactRoles() .stream() .map(ContactRole::getContact) .collect(Collectors.toList()); // when final List<Contact> possibleContacts = contactRole.choices0AlsoWithContact(); // then for (Contact contact : possibleContacts) { assertThat(contactsWhichAlreadyHaveRole).doesNotContain(contact); } } } public static class Edit extends ContactRoleIntegTest { @Test public void happy_case_using_existing_role_name() throws Exception { // when final String existingRoleName = fakeDataService.collections().anyOf(this.contactRole.choices0Edit()); wrap(this.contactRole).edit(existingRoleName, null); // then assertThat(this.contactRole.getRoleName()).isEqualTo(existingRoleName); } @Test public void happy_case_using_new_role_name() throws Exception { // given final String newRoleName = "New role"; List<String> rolesBefore = contactRoleRepository.listAll() .stream() .map(ContactRole::getRoleName) .collect(Collectors.toList()); assertThat(rolesBefore).doesNotContain(newRoleName); // when wrap(this.contactRole).edit(null, newRoleName); // then assertThat(this.contactRole.getRoleName()).isEqualTo(newRoleName); List<String> rolesAfter = contactRoleRepository.listAll() .stream() .map(ContactRole::getRoleName) .collect(Collectors.toList()); assertThat(rolesAfter).contains(newRoleName); } @Test public void happy_case_using_new_role_name_which_also_in_list() throws Exception { // when final String existingRoleNameAsNewRoleName = fakeDataService.collections().anyOf(this.contactRole.choices0Edit()); wrap(this.contactRole).edit(null, existingRoleNameAsNewRoleName); // then assertThat(this.contactRole.getRoleName()).isEqualTo(existingRoleNameAsNewRoleName); } @Test public void when_no_role_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Must specify either an (existing) role or a new role"); // when wrap(this.contactRole).edit(null, null); } @Test public void when_both_existing_role_and_new_role_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Must specify either an (existing) role or a new role"); // when final String newRoleName = fakeDataService.collections().anyOf(this.contactRole.choices0Edit()); wrap(this.contactRole).edit(newRoleName, "New role"); } } }<file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2015-2016 Eurocommercial Properties NV 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.incode.app</groupId> <artifactId>contactapp</artifactId> <version>${revision}</version> </parent> <artifactId>contactapp-webapp</artifactId> <name>Incode App ContactApp Webapp</name> <description>This module runs both the Wicket viewer and the Restfulobjects viewer in a single webapp configured to run using the datanucleus object store. It combines a number of the Isis addons.</description> <packaging>war</packaging> <properties> <maven-war-plugin.warName>${project.parent.artifactId}</maven-war-plugin.warName> <docker-plugin.imageName>incodehq/${project.parent.artifactId}</docker-plugin.imageName> <docker-plugin.resource.include>${maven-war-plugin.warName}.war</docker-plugin.resource.include> <docker-plugin.serverId>docker-hub</docker-plugin.serverId> <docker-plugin.registryUrl>https://index.docker.io/v1/</docker-plugin.registryUrl> <jetty.version>9.4.3.v20170317</jetty.version> <commons-lang.version>2.6</commons-lang.version> <commons-io.version>2.4</commons-io.version> </properties> <build> <resources> <resource> <filtering>false</filtering> <directory>src/main/resources</directory> </resource> <resource> <filtering>true</filtering> <directory>src/main/resources-filtered</directory> </resource> </resources> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <phase>validate</phase> <goals> <goal>maven-version</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>com.github.odavid.maven.plugins</groupId> <artifactId>mixin-maven-plugin</artifactId> <version>0.1-alpha-39</version> <extensions>true</extensions> <configuration> <mixins> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>standard</artifactId> </mixin> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>enforcerrelaxed</artifactId> </mixin> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>jettywar</artifactId> </mixin> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>jettyconsole</artifactId> </mixin> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>docker</artifactId> </mixin> </mixins> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>${project.groupId}</groupId> <artifactId>contactapp-app</artifactId> </dependency> <dependency> <groupId>org.apache.isis.mavendeps</groupId> <artifactId>isis-mavendeps-webapp</artifactId> <type>pom</type> </dependency> <dependency> <groupId>org.apache.isis.mavendeps</groupId> <artifactId>isis-mavendeps-intellij</artifactId> <type>pom</type> </dependency> <!-- enable -parameters support --> <dependency> <groupId>org.isisaddons.metamodel.paraname8</groupId> <artifactId>isis-metamodel-paraname8-dom</artifactId> </dependency> <!-- <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-servlet_3.0_spec</artifactId> </dependency> --> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.lazyluke</groupId> <artifactId>log4jdbc-remix</artifactId> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion> </exclusions> </dependency> <!-- https://github.com/ebay/cors-filter --> <dependency> <groupId>org.ebaysf.web</groupId> <artifactId>cors-filter</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.isisaddons.module.togglz</groupId> <artifactId>isis-module-togglz-glue</artifactId> </dependency> <dependency> <groupId>org.togglz</groupId> <artifactId>togglz-servlet</artifactId> </dependency> <dependency> <groupId>org.togglz</groupId> <artifactId>togglz-console</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.16</version> </dependency> </dependencies> <profiles> <profile> <id>resolving-conflicts</id> <activation> <property> <name>!skip.resolving-conflicts</name> </property> </activation> <dependencyManagement> <dependencies> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>${commons-lang.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-continuation</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-http</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-io</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-util</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-webapp</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.eclipse.jetty.websocket</groupId> <artifactId>websocket-server</artifactId> <version>${jetty.version}</version> </dependency> </dependencies> </dependencyManagement> </profile> <profile> <!-- makes o.a.i.WebServer available when running with IntelliJ IDEA --> <id>isis-mavendeps-webapp</id> <activation> <property> <name>idea.version</name> </property> </activation> <dependencies> <dependency> <groupId>org.apache.isis.core</groupId> <artifactId>isis-core-webserver</artifactId> </dependency> </dependencies> </profile> </profiles> </project> <file_sep>= Contact App The _Contact App_ is a contact management application developed for link:http://eurocommercial.com[Eurocommercial]. This app originated out of our users' need to quickly look up different employees of Eurocommercial's. At the same time the app managers would need to be able to easily edit or add to the existing contact information. We decided to create different Contact Groups consisting of multiple Contacts, each with their role within the group. image:http://i.imgur.com/j0x7bw8.png[width="97%"] == Apache Isis with Ionic Because of the requirements of the app - quick and portable access - we decided to create a mobile app for it using the link:http://ionicframework.com/[Ionic Framework]. For the backend we decided to use link:http://isis.apache.org[Apache Isis] since this allowed us to rapidly develop the required backend application and surface a REST API to which the mobile application could connect. We found that it worked together quite well, and with part of the team behind http://github.com/estatio/estatio[Estatio] we were able to create an app that is clear to use and manage. image:http://i.imgur.com/ETKG6Xe.png[width="32%"] image:http://i.imgur.com/zMX6OYq.png[width="32%"] image:http://i.imgur.com/qhXhKiu.png[width="32%"] As our first Apache Isis app making use of mobile technologies it opens the doors for more to follow. Ionic has proven easy to learn and build apps with, and has a helpful community. Meanwhile we've used Apache Isis' support for link://http://isis.apache.org/guides/ugbtb.html#_ugbtb_view-models_jaxb[JAXB view models] and in particular the http://isis.apache.org/guides/ugvro.html#_ugvro_simplified-representations_apache-isis-profile[simplified REST representations] introduced in v1.12.0. The result is code that is easy to follow and enhance. We expect that the scope of _Contact App_ will expand and new features added, these will (most likely) remain open source. Meanwhile we're now set up nicely to build further mobile apps using this technology stack. <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.number.dom; import org.junit.Before; import org.junit.Test; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberSpec; import static org.assertj.core.api.Assertions.assertThat; public class ContactNumberSpecTest { private ContactNumberSpec spec; @Before public void setUp() throws Exception { spec = new ContactNumberSpec(); } @Test public void happy_case() throws Exception { assertThat(spec.satisfies("+44 1234 5678")).isNull(); } @Test public void happy_case_no_spaces() throws Exception { assertThat(spec.satisfies("+44 12345678")).isNull(); } @Test public void sad_case_with_brackets() throws Exception { assertThat(spec.satisfies("+44 (0)1234 5678")).isEqualTo(ContactNumberSpec.ERROR_MESSAGE); } @Test public void sad_case_missing_first_plus() throws Exception { assertThat(spec.satisfies("44 1234 5678")).isEqualTo(ContactNumberSpec.ERROR_MESSAGE); } @Test public void sad_case_no_space() throws Exception { assertThat(spec.satisfies("+441234 5678")).isEqualTo(ContactNumberSpec.ERROR_MESSAGE); } @Test public void sad_case_ends_with_space() throws Exception { assertThat(spec.satisfies("+44 1234 5678 ")).isEqualTo(ContactNumberSpec.ERROR_MESSAGE); } @Test public void when_not_a_string() throws Exception { assertThat(spec.satisfies(new Object())).isNull(); } @Test public void when_null() throws Exception { assertThat(spec.satisfies(new Object())).isNull(); } }<file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2015-2016 Eurocommercial Properties NV 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.incode</groupId> <artifactId>incode-parent</artifactId> <!-- NB: also update incode-platform.version property below. --> <version>1.17.0.20190418-0755-7d3f32e7</version> <relativePath/> </parent> <groupId>org.incode.app</groupId> <artifactId>contactapp</artifactId> <version>${revision}</version> <name>Incode App ContactApp</name> <packaging>pom</packaging> <prerequisites> <maven>3.0.4</maven> </prerequisites> <properties> <revision>1.0.0-SNAPSHOT</revision> <isis.version>1.17.0.20190207-2036-bccfeda5</isis.version> <!-- NB: also update the parent of this pom. --> <incode-platform.version>1.17.0.20190418-0755-7d3f32e7</incode-platform.version> <isis-metamodel-paraname8.version>${incode-platform.version}</isis-metamodel-paraname8.version> <incode-module-note.version>1.15.1.1</incode-module-note.version> <incode-module-commchannel.version>1.15.1.1</incode-module-commchannel.version> <jbcrypt.version>0.3m</jbcrypt.version> <togglz.version>2.1.0.Final</togglz.version> <lombok.version>1.16.10</lombok.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <warName>contacts</warName> </properties> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>flatten-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <updatePomFile>true</updatePomFile> <pomElements> <dependencyManagement>resolve</dependencyManagement> <dependencies>resolve</dependencies> </pomElements> </configuration> <executions> <execution> <id>flatten</id> <phase>process-resources</phase> <goals> <goal>flatten</goal> </goals> </execution> <execution> <id>flatten.clean</id> <phase>clean</phase> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <modules> <module>app</module> <module>dom</module> <module>webapp</module> </modules> <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.isis.core</groupId> <artifactId>isis</artifactId> <version>${isis.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.isisaddons.metamodel.paraname8</groupId> <artifactId>isis-metamodel-paraname8-dom</artifactId> <version>${isis-metamodel-paraname8.version}</version> </dependency> <!-- this project's own modules --> <dependency> <groupId>${project.groupId}</groupId> <artifactId>contactapp-app</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>contactapp-dom</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>contactapp-webapp</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.audit</groupId> <artifactId>isis-module-audit-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.command</groupId> <artifactId>isis-module-command-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.docx</groupId> <artifactId>isis-module-docx-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.excel</groupId> <artifactId>isis-module-excel-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.fakedata</groupId> <artifactId>isis-module-fakedata-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.poly</groupId> <artifactId>isis-module-poly-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.security</groupId> <artifactId>isis-module-security-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.mindrot</groupId> <artifactId>jbcrypt</artifactId> <version>${jbcrypt.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.servletapi</groupId> <artifactId>isis-module-servletapi-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.sessionlogger</groupId> <artifactId>isis-module-sessionlogger-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.incode.module.settings</groupId> <artifactId>incode-module-settings-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.stringinterpolator</groupId> <artifactId>isis-module-stringinterpolator-dom</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.module.togglz</groupId> <artifactId>isis-module-togglz-glue</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.togglz</groupId> <artifactId>togglz-core</artifactId> <version>${togglz.version}</version> </dependency> <dependency> <groupId>org.togglz</groupId> <artifactId>togglz-junit</artifactId> <version>${togglz.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.togglz</groupId> <artifactId>togglz-servlet</artifactId> <version>${togglz.version}</version> </dependency> <dependency> <groupId>org.togglz</groupId> <artifactId>togglz-console</artifactId> <version>${togglz.version}</version> </dependency> <dependency> <groupId>org.isisaddons.wicket.excel</groupId> <artifactId>isis-wicket-excel-cpt</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.wicket.fullcalendar2</groupId> <artifactId>isis-wicket-fullcalendar2-cpt</artifactId> <version>${incode-platform.version}</version> </dependency> <dependency> <groupId>org.isisaddons.wicket.gmap3</groupId> <artifactId>isis-wicket-gmap3-cpt</artifactId> <version>${incode-platform.version}</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> </dependencies> <profiles> <!-- required to pull down parent pom (incode-parent) --> <profile> <id>repo-incode-work</id> <activation> <property> <name>!skip.repo-incode-work</name> </property> </activation> <repositories> <repository> <id>repo-incode-work</id> <url>https://repo.incode.work</url> <name>repo.incode.work</name> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>fail</checksumPolicy> </releases> <snapshots> <enabled>false</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>fail</checksumPolicy> </snapshots> <layout>default</layout> </repository> </repositories> </profile> <profile> <id>default-modules</id> <activation> <property> <name>!docker-deploy</name> </property> </activation> <modules> <module>webapp</module> </modules> </profile> <profile> <id>docker-deploy</id> <activation> <property> <name>docker-deploy</name> </property> </activation> <build> <plugins> <plugin> <!-- disable deploy for *this* parent pom, but not for child module --> <artifactId>maven-deploy-plugin</artifactId> <version>${maven-deploy-plugin.version}</version> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build> <modules> <module>webapp</module> </modules> </profile> </profiles> </project> <file_sep># # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # [main] ####### # isisModuleSecurityRealm ####### builtInCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager securityManager.cacheManager = $builtInCacheManager isisModuleSecurityRealm=org.isisaddons.module.security.shiro.IsisModuleSecurityRealm authenticationStrategy=org.isisaddons.module.security.shiro.AuthenticationStrategyForIsisModuleSecurityRealm securityManager.authenticator.authenticationStrategy = $authenticationStrategy ####### # configure security manager to use realm(s) ####### securityManager.realms = $isisModuleSecurityRealm ####### # optional: a "delegate" realm (eg ldap-based realm) ####### contextFactory = org.apache.isis.security.shiro.IsisLdapContextFactory contextFactory.url = ldap://localhost:10389 contextFactory.authenticationMechanism = CRAM-MD5 contextFactory.systemAuthenticationMechanism = simple contextFactory.systemUsername = uid=admin,ou=system contextFactory.systemPassword = <PASSWORD> ldapRealm = org.apache.isis.security.shiro.IsisLdapRealm ldapRealm.contextFactory = $contextFactory ldapRealm.searchBase = ou=groups,o=mojo ldapRealm.groupObjectClass = groupOfUniqueNames ldapRealm.uniqueMemberAttribute = uniqueMember ldapRealm.uniqueMemberAttributeValueTemplate = uid={0} # optional mapping from physical groups to logical application roles #ldapRealm.rolesByGroup = \ # LDN_USERS: user_role,\ # NYK_USERS: user_role,\ # HKG_USERS: user_role,\ # GLOBAL_ADMIN: admin_role,\ # DEMOS: self-install_role # configuring the Isis security realm to use the ldap realm as a "delegate" realm #isisModuleSecurityRealm.delegateAuthenticationRealm=$ldapRealm # ----------------------------------------------------------------------------- # Users and their assigned roles # ----------------------------------------------------------------------------- [users] # unused [roles] # unused <file_sep>/* * create our angular module and make sure we include the ion-radial-progress module */ angular.module('testApp', ['ion-radial-progress']);<file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.services.activity; import java.util.Collections; import java.util.List; import com.google.common.collect.Lists; import org.joda.time.LocalDate; import org.apache.isis.applib.AbstractService; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Optionality; import org.apache.isis.applib.annotation.Parameter; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.services.HasTransactionId; import org.apache.isis.applib.services.bookmark.Bookmark; import org.apache.isis.applib.services.bookmark.BookmarkService; import org.apache.isis.applib.services.clock.ClockService; import org.apache.isis.objectstore.jdo.applib.service.DomainChangeJdoAbstract; import org.isisaddons.module.audit.dom.AuditingServiceRepository; import org.isisaddons.module.command.dom.CommandServiceJdoRepository; import org.isisaddons.module.sessionlogger.dom.SessionLogEntry; @DomainService( nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY ) public class RecentActivityContributions extends AbstractService { /** * Depending on which services are available, returns either a list of {@link org.isisaddons.module.command.dom.CommandJdo command}s that have * caused a change in the domain object or a list of {@link org.isisaddons.module.audit.dom.AuditEntry audit entries} capturing the 'effect' * of that change. * * <p> * If {@link org.isisaddons.module.command.dom.CommandJdo command}s are returned, then the corresponding {@link org.isisaddons.module.audit.dom.AuditEntry audit entries} are * available from each command. */ @Action( semantics = SemanticsOf.SAFE ) @MemberOrder(sequence="30") public List<? extends DomainChangeJdoAbstract> recentActivity ( final Object targetDomainObject, @Parameter(optionality= Optionality.OPTIONAL) final LocalDate from, @Parameter(optionality= Optionality.OPTIONAL) final LocalDate to) { final Bookmark targetBookmark = bookmarkService.bookmarkFor(targetDomainObject); final List<DomainChangeJdoAbstract> changes = Lists.newArrayList(); if(commandServiceRepository != null) { changes.addAll(commandServiceRepository.findByTargetAndFromAndTo(targetBookmark, from, to)); } changes.addAll(auditingServiceRepository.findByTargetAndFromAndTo(targetBookmark, from, to)); Collections.sort(changes, DomainChangeJdoAbstract.compareByTimestampDescThenType()); return changes; } /** * Hide for commands, audit entries, published events, session log entries, and for {@link org.apache.isis.applib.ViewModel}s. */ public boolean hideRecentActivity(final Object targetDomainObject, final LocalDate from, final LocalDate to) { return getContainer().isViewModel(targetDomainObject) || targetDomainObject instanceof HasTransactionId || targetDomainObject instanceof SessionLogEntry || auditingServiceRepository == null || bookmarkService == null; } public LocalDate default1RecentActivity() { return clockService.now().minusDays(7); } public LocalDate default2RecentActivity() { return clockService.now(); } // ////////////////////////////////////// @javax.inject.Inject CommandServiceJdoRepository commandServiceRepository; @javax.inject.Inject AuditingServiceRepository auditingServiceRepository; @javax.inject.Inject BookmarkService bookmarkService; @javax.inject.Inject ClockService clockService; } <file_sep>angular.module( 'ecp-contactapp.services.http' , []) .service('HttpService', ['$q', '$http', '$ionicLoading', 'AppConfig', 'OfflineService', function($q, $http, $ionicLoading, AppConfig, OfflineService) { var service = this var isUndefined = function (thing) { return thing === null || (typeof thing === "undefined"); } var useIonicLoading = function(options) { return isUndefined(options) || !options.suppressIonicLoading } this.isOfflineEnabled = function() { return OfflineService.isOfflineEnabled() } var headerMap = { 'Accept': 'application/json;profile=urn:org.apache.isis/v1;suppress=true' } this.get = function(cacheKey, relativeUrl, onCached, onData, onOK, onError, options) { var url = AppConfig.baseUrl + relativeUrl var localStorageKey = AppConfig.appPrefix + "." + cacheKey var cached = OfflineService.get(cacheKey) if(cached) { // return the data we already have stored offline if(onCached) { onCached(cached.resp.data, cached.date) } } // asynchronously populate the offline cache if we can var showSpinner = !cached && useIonicLoading(options) if(showSpinner) { $ionicLoading.show({ delay: 200 }) } $http.get( url, { headers: headerMap } ) .then( function(resp) { if(showSpinner) { $ionicLoading.hide() } resp.data = onData(resp.data) if(OfflineService.isOfflineEnabled()) { OfflineService.put(cacheKey, resp) var stored = OfflineService.get(cacheKey) if(stored) { onOK(stored.resp.data, stored.date) } } else { onOK(resp.data, null) // suppress any message at end } }, function(err) { if(showSpinner) { $ionicLoading.hide() } if(onError && !cached) { // unable to obtain any data, and wasn't previously cached onError(err) } } ) } this.getMany = function(cacheKeys, relativeUrls, onData, onAllComplete) { var httpPromises = [] for (var i = 0; i < cacheKeys.length; i++) { var cacheKey = cacheKeys[i] var localStorageKey = AppConfig.appPrefix + "." + cacheKey var url = AppConfig.baseUrl + relativeUrls[i] var httpPromise = $http.get( url, { headers: headerMap } ) .then( function(resp) { resp.data = onData(resp.data) return resp } ) httpPromises.push(httpPromise) } $q.all(httpPromises.map(function(promise) { return promise.then( function(value) { return value; }, function(reason) { return null; } ); }) ) .then( function(responses) { if(OfflineService.isOfflineEnabled()) { OfflineService.putMany(cacheKeys, responses) } onAllComplete() } ) } this.lookup = function(cacheKey) { return OfflineService.lookup(cacheKey) } this.isCached = function(cacheKey) { return OfflineService.isCached(cacheKey) } }]) ; <file_sep>#!/bin/sh echo "CATALINA_HOME = " $CATALINA_HOME mkdir -p /run/conf if [ -s /run/secrets/*.context.xml ]; then # Symlink context.xml. ln -sf /run/secrets/*.context.xml $CATALINA_HOME/conf/Catalina/localhost/ROOT.xml echo "FOUND context.xml." else echo "context.xml NOT FOUND, proceeding with default config" fi if [ -s /run/secrets/*.shiro.ini ]; then # Symlink shiro.ini. ln -sf /run/secrets/*.shiro.ini /run/conf/shiro.ini echo "FOUND shiro.ini." else echo "shiro.ini NOT FOUND, proceeding with default config" fi if [ -s /run/secrets/*.setenv.sh ]; then # Symlink setenv.sh. ln -sf /run/secrets/*.setenv.sh $CATALINA_HOME/bin/setenv.sh echo "FOUND setenv.sh." else echo "setenv.sh NOT FOUND, proceeding with default config" fi if [ -s /run/secrets/*.isis.properties ] && [ -s /run/secrets/*.logging.properties ]; then # Symlink isis.properties. ln -sf /run/secrets/*.isis.properties /run/conf/isis.properties ln -sf /run/secrets/*.logging.properties /run/conf/logging.properties echo "FOUND isis.properties and logging.properties." else echo "isis.properties and/or logging.properties NOT FOUND, proceeding with default config" fi if [ -s /run/secrets/*.translations.po ]; then # Symlink isis.properties. ln -sf /run/secrets/*.translations.po /run/conf/translations.po echo "FOUND translations.po." else echo "translations.po NOT FOUND, proceeding with default config" fi # Running Catalina echo "Starting Catalina:" ${SERVER_HOME}/bin/catalina.sh run <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.rest.v1.contacts; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import javax.xml.bind.annotation.XmlTransient; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.isis.applib.DomainObjectContainer; import org.incode.eurocommercial.contactapp.app.rest.ViewModelWithUnderlying; import org.incode.eurocommercial.contactapp.app.rest.v1.number.ContactNumberViewModel; import org.incode.eurocommercial.contactapp.app.rest.v1.role.ContactRoleViewModel; import org.incode.eurocommercial.contactapp.module.contactable.dom.ContactableEntity; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.country.dom.Country; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRole; public class ContactableViewModel extends ViewModelWithUnderlying<ContactableEntity> { public enum Type { CONTACT, CONTACT_GROUP } public static class Functions { private Functions(){} } public static Function<Contact, ContactableViewModel> createForContact(final DomainObjectContainer container) { return new Function<Contact, ContactableViewModel>() { @Nullable @Override public ContactableViewModel apply(@Nullable final Contact input) { return input != null ? container.injectServicesInto(new ContactableViewModel(input)): null; } }; } public static Function<ContactGroup, ContactableViewModel> createForGroup(final DomainObjectContainer container) { return new Function<ContactGroup, ContactableViewModel>() { @Nullable @Override public ContactableViewModel apply(@Nullable final ContactGroup input) { return input != null? container.injectServicesInto(new ContactableViewModel(input)): null; } }; } private Contact contact() { return getType() == Type.CONTACT? (Contact) underlying : null; } private ContactGroup contactGroup() { return getType() == Type.CONTACT_GROUP? (ContactGroup) underlying : null; } public ContactableViewModel() { } public ContactableViewModel(Contact contact) { this.underlying = contact; } public ContactableViewModel(ContactGroup contactGroup) { this.underlying = contactGroup; } public Type getType() { return this.underlying instanceof Contact? Type.CONTACT: Type.CONTACT_GROUP; } public String getName() { final String name = underlying.getName(); // remove white space and &nbsp; return name != null ?name.replace(String.valueOf((char) 160), " ").trim() :null; } /** * Only populated for {@link #getType()} of {@link Type#CONTACT_GROUP}. */ public Integer getDisplayOrder() { return getType() == Type.CONTACT_GROUP? contactGroup().getDisplayOrder(): null; } public String getEmail() { return underlying.getEmail(); } public String getNotes() { return underlying.getNotes(); } public List<ContactNumberViewModel> getContactNumbers() { return Lists.newArrayList( Iterables.transform(underlying.getContactNumbers(), ContactNumberViewModel.create(container)) ); } /** * For searching by the filter bar. * @return */ @XmlTransient public String getContactRoleNames() { return Joiner.on(";").join( FluentIterable.from(getContactRoles()) .transform(ContactRoleViewModel.nameOf()) .filter(Predicates.notNull())); } /** * For {@link Type#CONTACT contacts}, returns the roles they have (in various groups) * For {@link Type#CONTACT_GROUP contact groups}, returns the roles that different contacts play within that group. * * @return */ @XmlTransient public List<ContactRoleViewModel> getContactRoles() { final Collection<ContactRole> contactRoles = getType() == Type.CONTACT_GROUP ? contactGroup().getContactRoles() : contact().getContactRoles(); return Lists.newArrayList( Iterables.transform( contactRoles, ContactRoleViewModel.create(container))); } /** * Only populated for {@link #getType()} of {@link Type#CONTACT}. */ public String getCompany() { if (getType() == Type.CONTACT_GROUP) { return null; } return contact().getCompany(); } /** * Only populated for {@link #getType()} of {@link Type#CONTACT_GROUP}. */ public String getCountry() { if(getType() == Type.CONTACT) return null; final Country country = contactGroup().getCountry(); return country != null? container.titleOf(country): null; } /** * Only populated for {@link #getType()} of {@link Type#CONTACT_GROUP}. */ public String getAddress() { if(getType() == Type.CONTACT) return null; return contactGroup().getAddress(); } static String firstNameFrom(final String name) { final int i = name.lastIndexOf(" "); return i != -1? name.substring(0, i): ""; } static String lastNameFrom(final String name) { final int i = name.lastIndexOf(" "); return i != -1? name.substring(i+1): name; } } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.role.dom; import java.util.SortedSet; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Programmatic; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; @DomainService( nature = NatureOfService.DOMAIN, repositoryFor = ContactRole.class ) public class ContactRoleRepository { @Programmatic public java.util.List<ContactRole> listAll() { return container.allInstances(ContactRole.class); } @Programmatic public SortedSet<String> roleNames() { final ImmutableList<String> roleNames = FluentIterable .from(listAll()) .transform(ContactRole::getRoleName) .filter(Predicates.notNull()).toList(); return Sets.newTreeSet(roleNames); } @Programmatic public ContactRole findByContactAndContactGroup( final Contact contact, final ContactGroup contactGroup ) { return container.uniqueMatch( new org.apache.isis.applib.query.QueryDefault<>( ContactRole.class, "findByContactAndContactGroup", "contact", contact, "contactGroup", contactGroup)); } @Programmatic public java.util.List<ContactRole> findByName( final String regex ) { return container.allMatches( new org.apache.isis.applib.query.QueryDefault<>( ContactRole.class, "findByName", "regex", regex)); } @Programmatic public java.util.List<ContactRole> findByContact( final Contact contact ) { return container.allMatches( new org.apache.isis.applib.query.QueryDefault<>( ContactRole.class, "findByContact", "contact", contact)); } @Programmatic public java.util.List<ContactRole> findByGroup( final ContactGroup contactGroup ) { return container.allMatches( new org.apache.isis.applib.query.QueryDefault<>( ContactRole.class, "findByContactGroup", "contactGroup", contactGroup)); } @Programmatic public ContactRole create(final Contact contact, final ContactGroup contactGroup, final String roleName) { final ContactRole contactRole = container.newTransientInstance(ContactRole.class); contactRole.setContact(contact); contactRole.setContactGroup(contactGroup); contactRole.setRoleName(roleName); contact.getContactRoles().add(contactRole); container.persistIfNotAlready(contactRole); return contactRole; } @Programmatic public ContactRole findOrCreate( final Contact contact, final ContactGroup contactGroup, final String roleName ) { ContactRole contactRole = findByContactAndContactGroup(contact, contactGroup); if (contactRole == null) { contactRole = create(contact, contactGroup, roleName); } return contactRole; } @javax.inject.Inject org.apache.isis.applib.DomainObjectContainer container; } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app; import com.google.common.base.Joiner; import org.apache.isis.applib.AppManifestAbstract2; import org.isisaddons.metamodel.paraname8.NamedFacetOnParameterParaname8Factory; import org.isisaddons.module.security.facets.TenantedAuthorizationFacetFactory; public class ContactAppAppManifest extends AppManifestAbstract2 { static final Builder BUILDER = Builder.forModule( new ContactAppAppModule() ).withAuthMechanism("shiro") .withConfigurationPropertiesFile( ContactAppAppManifest.class, "isis-non-changing.properties") .withConfigurationProperty( "isis.reflector.facets.include", Joiner.on(',').join( NamedFacetOnParameterParaname8Factory.class.getName() , TenantedAuthorizationFacetFactory.class.getName() ) ); public ContactAppAppManifest() { super(BUILDER); } } <file_sep>isis.appManifest=org.incode.eurocommercial.contactapp.app.ContactAppAppManifest isis.reflector.validator.allowDeprecated=false isis.reflector.facet.cssClassFa.patterns=\ new.*:fa-file-o,\ create.*:fa-file-o,\ also.*:fa-file-o,\ \ add.*:fa-plus-square,\ remove.*:fa-minus-square,\ \ update.*:fa-edit,\ edit.*:fa-edit, \ change.*:fa-edit,\ \ delete.*:fa-trash,\ move.*:fa-exchange,\ first.*:fa-star,\ find.*:fa-search,\ lookup.*:fa-search,\ clear.*:fa-remove,\ previous.*:fa-step-backward,\ next.*:fa-step-forward,\ list.*:fa-list, \ all.*:fa-list, \ download.*:fa-download, \ upload.*:fa-upload, \ execute.*:fa-bolt, \ run.*:fa-bolt, \ calculate.*:fa-calculator, \ verify.*:fa-check-circle, \ refresh.*:fa-refresh, \ install.*:fa-wrench isis.reflector.facet.cssClass.patterns=\ new.*:btn-success,\ create.*:btn-success,\ also.*:btn-success,\ edit.*:btn-primary,\ delete.*:btn-danger isis.services.eventbus.implementation=guava isis.services.audit.objects=all isis.services.command.actions=ignoreQueryOnly isis.value.format.date=dd-MM-yyyy isis.persistor.datanucleus.impl.datanucleus.schema.autoCreateAll=true isis.persistor.datanucleus.impl.datanucleus.schema.validateTables=true isis.persistor.datanucleus.impl.datanucleus.schema.validateConstraints=true isis.persistor.datanucleus.impl.datanucleus.persistenceByReachabilityAtCommit=false isis.persistor.datanucleus.impl.datanucleus.identifier.case=MixedCase isis.persistor.datanucleus.impl.datanucleus.cache.level2.type=none isis.persistor.datanucleus.impl.datanucleus.cache.level2.mode=ENABLE_SELECTIVE isis.viewer.wicket.maxTitleLengthInStandaloneTables=0 isis.viewer.wicket.maxTitleLengthInParentedTables=0 isis.viewer.wicket.rememberMe.encryptionKey=66e0312e-5531-4360-97e8-6dec93938057 isis.viewer.wicket.themes.showChooser=true isis.viewer.wicket.themes.enabled=bootstrap-theme,Cosmo,Flatly,Darkly,Sandstone,United isis.viewer.wicket.disableDependentChoiceAutoSelection=false isis.viewer.restfulobjects.RestfulObjectsSpecEventSerializer.baseUrl=http://localhost:8080/restful/ isis.services.translation.po.mode=read<file_sep>angular.module( 'ecp-contactapp.services.backend', []) .service( 'BackendService', ['PreferencesService', 'HttpService', 'AppConfig', '$filter', function(PreferencesService, HttpService, AppConfig, $filter) { var listAllKey = 'listAll' // for localStorage var instanceIdOf = function(href) { var n = href.lastIndexOf('/'); var result = href.substring(n + 1); return result; } var dataProvenanceMessage = function(date) { return date ? "Data from " + $filter('date')(date, 'd MMM, HH:mm:ss') : "" } this.isOfflineEnabled = function() { return HttpService.isOfflineEnabled() } this.loadContactableList = function(onComplete, options) { var sort = function(respData) { respData.sort(function(a,b) { // contact groups before contacts if(a.type === "Contact Group" && b.type === "Contact") { return -1 } if(a.type === "Contact" && b.type === "Contact Group") { return 1 } // then by display order if(a.displayOrder && !b.displayOrder) { return -1 } if(!a.displayOrder && b.displayOrder) { return 1 } if(a.displayOrder && b.displayOrder) { return a.displayOrder - b.displayOrder } // then by name return a.name.localeCompare(b.name) }) return respData } HttpService.get( listAllKey, "/restful/services/ContactableViewModelRepository/actions/listAll/invoke", function(cachedData, date) { onComplete(sort(cachedData), dataProvenanceMessage(date)) }, function(respData, date) { var trimmedData = respData.map( function(contactable){ contactable.$$instanceId = instanceIdOf(contactable.$$href) delete contactable.$$href delete contactable.$$title delete contactable.notes delete contactable.email if(contactable.type === "Contact" && !contactable.company) { contactable.company = "---" } if(contactable.type === "Contact Group" && !contactable.country) { contactable.country = "---" } return contactable } ) return trimmedData }, function(respData, date) { onComplete(sort(respData), dataProvenanceMessage(date)) }, function(err) { onComplete([], dataProvenanceMessage(null)) }, options ) } var trimContactable = function(respData) { delete respData.$$href delete respData.$$instanceId delete respData.$$title respData.contactNumbers = respData.contactNumbers.map( function(contactNumber){ delete contactNumber.$$instanceId delete contactNumber.$$href delete contactNumber.$$title return contactNumber } ) respData.contactRoles = respData.contactRoles.map( function(contactRole) { delete contactRole.$$href delete contactRole.$$title contactRole.contact.$$instanceId = instanceIdOf(contactRole.contact.href) delete contactRole.contact.href delete contactRole.contact.rel delete contactRole.contact.method delete contactRole.contact.type contactRole.contactGroup.$$instanceId = instanceIdOf(contactRole.contactGroup.href) delete contactRole.contactGroup.href delete contactRole.contactGroup.rel delete contactRole.contactGroup.method delete contactRole.contactGroup.type return contactRole } ) return respData } this.loadContactables = function(instanceIds, onEachComplete, onAllComplete) { var urls = instanceIds.map(function(instanceId) { return "/restful/objects/org.incode.eurocommercial.contactapp.app.rest.v1.contacts.ContactableViewModel/" + instanceId }) var num = 0; HttpService.getMany( instanceIds, urls, function(respData) { var trimmedData = trimContactable(respData) onEachComplete(++num, trimmedData) return trimmedData }, onAllComplete ) } this.loadContactable = function(instanceId, onComplete, options) { HttpService.get( instanceId, "/restful/objects/org.incode.eurocommercial.contactapp.app.rest.v1.contacts.ContactableViewModel/" + instanceId, function(cachedData, date) { onComplete(cachedData, dataProvenanceMessage(date)) }, trimContactable, function(respData, date) { onComplete(respData, dataProvenanceMessage(date)) return respData }, function(err, respData, date, resp) { onComplete({}, dataProvenanceMessage(null)) }, options ) } this.isCached = function(cacheKey) { return HttpService.isCached(cacheKey) } }]) ; <file_sep>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.number.integtests; import java.util.List; import javax.inject.Inject; import org.junit.Before; import org.junit.Test; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.incode.eurocommercial.contactapp.fixtures.DemoFixture; import org.incode.eurocommercial.contactapp.module.ContactAppDomainIntegTest; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumber; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberRepository; import static org.assertj.core.api.Assertions.assertThat; public class ContactNumberRepositoryTest extends ContactAppDomainIntegTest { @Inject FixtureScripts fixtureScripts; @Inject ContactNumberRepository contactNumberRepository; Contact contact; @Before public void setUp() throws Exception { // given DemoFixture fs = new DemoFixture(); fixtureScripts.runFixtureScript(fs, null); contact = fs.getContacts().get(0); } public static class ListAll extends ContactNumberRepositoryTest { @Test public void happy_case() throws Exception { // given, when final List<ContactNumber> contactNumbers = contactNumberRepository.listAll(); // then assertThat(contactNumbers.size()).isEqualTo(25); } } public static class FindByNumber extends ContactNumberRepositoryTest { @Test public void happy_case() throws Exception { // given final ContactNumber existingContactNumber = contact.getContactNumbers().first(); assertThat(existingContactNumber).isNotNull(); // when final ContactNumber contactNumber = contactNumberRepository.findByNumber(existingContactNumber.getNumber()); // then assertThat(contactNumber).isEqualTo(existingContactNumber); } } }<file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.contact.integtests; import java.util.List; import java.util.Objects; import java.util.SortedSet; import java.util.stream.Collectors; import javax.inject.Inject; import com.google.common.collect.FluentIterable; import org.assertj.core.groups.Tuple; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.services.wrapper.InvalidException; import org.isisaddons.module.fakedata.dom.FakeDataService; import org.incode.eurocommercial.contactapp.fixtures.DemoFixture; import org.incode.eurocommercial.contactapp.module.ContactAppDomainIntegTest; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactMenu; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactRepository; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroupRepository; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumber; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberType; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRole; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRoleRepository; import static org.assertj.core.api.Assertions.assertThat; public class ContactIntegTest extends ContactAppDomainIntegTest { @Inject FixtureScripts fixtureScripts; @Inject ContactRepository contactRepository; @Inject ContactGroupRepository contactGroupRepository; @Inject ContactRoleRepository contactRoleRepository; @Inject ContactMenu contactMenu; @Inject FakeDataService fakeDataService; DemoFixture fs; Contact contact; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() throws Exception { // given fs = new DemoFixture(); fixtureScripts.runFixtureScript(fs, null); contact = fs.getContacts().get(0); nextTransaction(); assertThat(contact).isNotNull(); } public static class Name extends ContactIntegTest { @Test public void accessible() throws Exception { // when final String name = wrap(contact).getName(); // then assertThat(name).isNotNull(); } } public static class Create extends ContactIntegTest { @Test public void happy_case() throws Exception { // when final String name = fakeDataService.name().fullName(); final String company = fakeDataService.strings().upper(Contact.MaxLength.COMPANY); final String officePhoneNumber = randomPhoneNumber(); final String mobilePhoneNumber = randomPhoneNumber(); final String homePhoneNumber = randomPhoneNumber(); final String email = fakeDataService.javaFaker().internet().emailAddress(); final Contact newContact = wrap(this.contact) .create(name, company, officePhoneNumber, mobilePhoneNumber, homePhoneNumber, email); nextTransaction(); // then assertThat(contact).isNotSameAs(newContact); assertThat(newContact.getName()).isEqualTo(name); assertThat(newContact.getCompany()).isEqualTo(company); assertThat(newContact.getEmail()).isEqualTo(email); assertThat(newContact.getContactNumbers()).hasSize(3); assertContains(newContact.getContactNumbers(), ContactNumberType.OFFICE.title(), officePhoneNumber); assertContains(newContact.getContactNumbers(), ContactNumberType.MOBILE.title(), mobilePhoneNumber); assertContains(newContact.getContactNumbers(), ContactNumberType.HOME.title(), homePhoneNumber); assertThat(newContact.getContactRoles()).isEmpty(); assertThat(newContact.getNotes()).isNull(); } @Test public void name_already_in_use_by_contact() throws Exception { // given final String name = this.contact.getName(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: This name is already in use by another contact"); // when final String company = fakeDataService.strings().upper(Contact.MaxLength.COMPANY); final String officePhoneNumber = randomPhoneNumber(); final String mobilePhoneNumber = randomPhoneNumber(); final String homePhoneNumber = randomPhoneNumber(); final String email = fakeDataService.javaFaker().internet().emailAddress(); wrap(this.contact).create(name, company, officePhoneNumber, mobilePhoneNumber, homePhoneNumber, email); } @Test public void name_already_in_use_by_contact_group() throws Exception { // given final String existingName = contactGroupRepository.listAll().get(0).getName(); assertThat(existingName).isNotEmpty(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: This name is already in use by a contact group"); // when final String company = fakeDataService.strings().upper(Contact.MaxLength.COMPANY); final String officePhoneNumber = randomPhoneNumber(); final String mobilePhoneNumber = randomPhoneNumber(); final String homePhoneNumber = randomPhoneNumber(); final String email = fakeDataService.javaFaker().internet().emailAddress(); wrap(this.contact).create(existingName, company, officePhoneNumber, mobilePhoneNumber, homePhoneNumber, email); } @Test public void when_name_not_provided() throws Exception { // when final String company = fakeDataService.strings().upper(Contact.MaxLength.COMPANY); final String officePhoneNumber = randomPhoneNumber(); final String mobilePhoneNumber = randomPhoneNumber(); final String homePhoneNumber = randomPhoneNumber(); final String email = fakeDataService.javaFaker().internet().emailAddress(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); final Contact newContact = wrap(this.contact).create(null, company, officePhoneNumber, mobilePhoneNumber, homePhoneNumber, email); } } public static class Edit extends ContactIntegTest { @Test public void happy_case() throws Exception { // when final String name = fakeDataService.name().fullName(); final String company = fakeDataService.strings().upper(Contact.MaxLength.COMPANY); final String email = fakeDataService.javaFaker().internet().emailAddress(); final String notes = fakeDataService.lorem().sentence(3); final Contact newContact = wrap(this.contact).edit(name, company, email, notes); nextTransaction(); // then assertThat(newContact).isSameAs(this.contact); assertThat(newContact.getName()).isEqualTo(name); assertThat(newContact.getCompany()).isEqualTo(company); assertThat(newContact.getEmail()).isEqualTo(email); assertThat(newContact.getNotes()).isEqualTo(notes); } @Test public void name_already_in_use_by_contact() throws Exception { // given final String existingName = fs.getContacts().get(1).getName(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: This name is already in use by another contact"); // when wrap(this.contact).edit(existingName, null, null, null); } @Test public void name_already_in_use_by_contact_group() throws Exception { // given final String existingName = contactGroupRepository.listAll().get(0).getName(); assertThat(existingName).isEqualTo("Amiens Property"); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: This name is already in use by a contact group"); // when wrap(this.contact).edit(existingName, null, null, null); } @Test public void when_name_not_provided() throws Exception { // when final String name = null; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); wrap(this.contact).edit(name, null, null, null); } @Test public void without_new_name() throws Exception { // given assertThat(this.contact.getName()).isEqualTo("<NAME>"); // when wrap(this.contact).edit(this.contact.default0Edit(), "New Company", null, null); // then assertThat(this.contact.getCompany()).isEqualTo("New Company"); // Naturally the name hasn't changed; this assertion merely ensures validateEdit // does not throw an exception assertThat(this.contact.getName()).isEqualTo("<NAME>"); } } public static class Delete extends ContactIntegTest { @Test public void happy_case() throws Exception { // given final List<Contact> contacts = contactRepository.listAll(); final int sizeBefore = contacts.size(); assertThat(sizeBefore).isGreaterThan(0); final Contact someContact = fakeDataService.collections().anyOf(contacts); final String someContactName = someContact.getName(); nextTransaction(); // when someContact.delete(); nextTransaction(); // then final List<Contact> contactsAfter = contactRepository.listAll(); final int sizeAfter = contactsAfter.size(); assertThat(sizeAfter).isEqualTo(sizeBefore - 1); assertThat(FluentIterable.from(contactsAfter).filter( contact -> { return Objects.equals(this.contact.getName(), someContactName); } )).isEmpty(); } } public static class AddNumber extends ContactIntegTest { String officePhoneNumber; @Before public void setUp() { // deliberately does not call super.setUp() // given final String name = fakeDataService.name().fullName(); this.officePhoneNumber = randomPhoneNumber(); this.contact = wrap(contactMenu).create(name, null, officePhoneNumber, null, null, null); nextTransaction(); assertContains(this.contact.getContactNumbers(), ContactNumberType.OFFICE.title(), officePhoneNumber); assertThat(this.contact.getContactNumbers()).hasSize(1); } @Test public void add_number_with_existing_type() throws Exception { // when final String newOfficePhoneNumber = randomPhoneNumber(); wrap(this.contact).addContactNumber(newOfficePhoneNumber, ContactNumberType.OFFICE.title(), null); nextTransaction(); // then assertThat(this.contact.getContactNumbers()).hasSize(2); assertContains(this.contact.getContactNumbers(), ContactNumberType.OFFICE.title(), newOfficePhoneNumber); assertContains(this.contact.getContactNumbers(), ContactNumberType.OFFICE.title(), this.officePhoneNumber); } @Test public void add_number_with_new_type() throws Exception { // when final String newAssistantPhoneNumber = randomPhoneNumber(); final String newType = "ASSISTANT"; wrap(this.contact).addContactNumber(newAssistantPhoneNumber, null, newType); nextTransaction(); // then assertThat(this.contact.getContactNumbers()).hasSize(2); assertContains(this.contact.getContactNumbers(), newType, newAssistantPhoneNumber); assertContains(this.contact.getContactNumbers(), ContactNumberType.OFFICE.title(), this.officePhoneNumber); } @Test public void add_number_when_already_have_number_of_any_type() throws Exception { // given final String existingNumber = this.contact.getContactNumbers().first().getNumber(); final String currentType = this.contact.getContactNumbers().first().getType(); final String newType = "New type"; assertThat(this.contact.getContactNumbers().first().getType()).isNotEqualToIgnoringCase(newType); // when wrap(this.contact).addContactNumber(existingNumber, null, newType); // then assertThat(this.contact.getContactNumbers()) .extracting( ContactNumber::getNumber, ContactNumber::getType) .doesNotContain( Tuple.tuple( existingNumber, currentType)); assertThat(this.contact.getContactNumbers()) .extracting( ContactNumber::getNumber, ContactNumber::getType) .contains( Tuple.tuple( existingNumber, newType)); } @Test public void when_no_type_specified() throws Exception { // when final String newOfficePhoneNumber = randomPhoneNumber(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) type or a new type"); wrap(this.contact).addContactNumber(newOfficePhoneNumber, null, null); } @Test public void when_both_existing_type_and_new_type_specified() throws Exception { // when final String newOfficePhoneNumber = randomPhoneNumber(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) type or a new type"); wrap(this.contact).addContactNumber(newOfficePhoneNumber, ContactNumberType.OFFICE.title(), "ASSISTANT"); } @Test public void when_no_number_provided() throws Exception { // when final String noNumber = null; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); wrap(this.contact).addContactNumber(noNumber, ContactNumberType.OFFICE.title(), null); } @Test public void invalid_number_format() throws Exception { // when final String invalidNumber = "This is an invalid number"; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Phone number should be in form: +44 1234 5678"); wrap(this.contact).addContactNumber(invalidNumber, ContactNumberType.OFFICE.title(), null); } } public static class RemoveNumber extends ContactIntegTest { String officePhoneNumber; String homePhoneNumber; @Before public void setUp() { // deliberately does not call super.setUp() // given final String name = fakeDataService.name().fullName(); this.officePhoneNumber = randomPhoneNumber(); this.homePhoneNumber = randomPhoneNumber(); this.contact = wrap(contactMenu).create(name, null, officePhoneNumber, null, homePhoneNumber, null); nextTransaction(); assertThat(this.contact.getContactNumbers()).hasSize(2); } @Test public void remove_number() throws Exception { final String existingNumber = fakeDataService.collections().anyOf(this.contact.choices0RemoveContactNumber()); nextTransaction(); // when wrap(this.contact).removeContactNumber(existingNumber); nextTransaction(); // then assertNotContains(this.contact.getContactNumbers(), existingNumber); } @Test public void remove_number_when_none_exists() throws Exception { // given final int numbersBefore = this.contact.getContactNumbers() .stream() .map(ContactNumber::getNumber) .collect(Collectors.toList()) .size(); // when final String nonexistingNumber = "+00 0000 0000"; wrap(this.contact).removeContactNumber(nonexistingNumber); // then assertThat(this.contact.getContactNumbers() .stream() .map(ContactNumber::getNumber) .collect(Collectors.toList()) .size()) .isEqualTo(numbersBefore); } } public static class AddRole extends ContactIntegTest { @Test public void happy_case_using_existing_role_name() throws Exception { // given final int numRolesBefore = this.contact.getContactRoles().size(); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contact.choices0AddContactRole()); final String existingRole = fakeDataService.collections().anyOf(this.contact.choices1AddContactRole()); final Contact contact = wrap(this.contact).addContactRole(contactGroup, existingRole, null); nextTransaction(); // then assertThat(contact.getContactRoles()).hasSize(numRolesBefore + 1); assertThat(contact.getContactRoles()) .extracting( ContactRole::getContactGroup, ContactRole::getRoleName, ContactRole::getContact) .contains( Tuple.tuple( contactGroup, existingRole, this.contact)); } @Test public void happy_case_using_new_role_name() throws Exception { // given final int numRolesBefore = this.contact.getContactRoles().size(); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contact.choices0AddContactRole()); final String newRole = "New role"; final Contact contact = wrap(this.contact).addContactRole(contactGroup, null, newRole); // then assertThat(contact.getContactRoles()).hasSize(numRolesBefore + 1); assertThat(contact.getContactRoles()) .extracting( ContactRole::getContactGroup, ContactRole::getRoleName, ContactRole::getContact) .contains( Tuple.tuple( contactGroup, newRole, this.contact)); } @Test public void happy_case_using_new_role_name_which_also_in_list() throws Exception { // given final int numRolesBefore = this.contact.getContactRoles().size(); // when final List<ContactRole> contactRoles = contactRoleRepository.findByContact(contact); assertThat(contactRoles).isNotEmpty(); ContactRole contactRole = contactRoles.get(0); // this role has no name provided by default contactRole.setRoleName("Role name"); final String newRoleInList = contactRole.getRoleName(); final ContactGroup contactGroup = contactRole.getContactGroup(); final Contact contact = wrap(this.contact).addContactRole(contactGroup, null, newRoleInList); // then assertThat(contact.getContactRoles()).hasSize(numRolesBefore); assertThat(contact.getContactRoles()) .extracting( ContactRole::getContactGroup, ContactRole::getRoleName, ContactRole::getContact) .contains( Tuple.tuple( contactGroup, newRoleInList, this.contact)); } @Test public void when_no_group_specified() throws Exception { // when final ContactGroup contactGroup = null; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); final Contact contact = wrap(this.contact).addContactRole(contactGroup, null, "new role"); } @Test public void when_no_role_specified() throws Exception { // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contact.choices0AddContactRole()); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) role or a new role"); final Contact contact = wrap(this.contact).addContactRole(contactGroup, null, null); } @Test public void when_both_existing_role_and_new_role_specified() throws Exception { // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contact.choices0AddContactRole()); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) role or a new role"); final Contact contact = wrap(this.contact).addContactRole(contactGroup, "existing role", "new role"); } @Test public void possible_groups_should_not_include_any_for_which_contact_already_has_a_role() throws Exception { // given final SortedSet<ContactRole> currentRoles = this.contact.getContactRoles(); assertThat(currentRoles).hasSize(1); final List<ContactGroup> allGroups = contactGroupRepository.listAll(); assertThat(allGroups).contains(currentRoles.first().getContactGroup()); // when final List<ContactGroup> possibleGroups = this.contact.choices0AddContactRole(); // then assertThat(possibleGroups).hasSize(allGroups.size() - currentRoles.size()); assertThat(possibleGroups).doesNotContain(currentRoles.first().getContactGroup()); } } public static class RemoveRole extends ContactIntegTest { @Test public void remove_role() throws Exception { // given final int contactRolesBefore = this.contact.getContactRoles().size(); assertThat(contactRolesBefore).isGreaterThan(0); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contact.choices0RemoveContactRole()); wrap(this.contact).removeContactRole(contactGroup); nextTransaction(); // then assertThat(contact.getContactRoles()).hasSize(contactRolesBefore - 1); } @Test public void remove_role_when_none_exists() throws Exception { // given final int contactRolesBefore = this.contact.getContactRoles().size(); assertThat(contactRolesBefore).isGreaterThan(0); // when final ContactGroup contactGroup = fakeDataService.collections().anyOf(this.contact.choices0AddContactRole()); wrap(this.contact).removeContactRole(contactGroup); nextTransaction(); // then assertThat(this.contact.getContactRoles()).hasSize(contactRolesBefore); } } }<file_sep>CAUTION: this repo has been archived; the current version now resides in a (private) gitlab repo. = Contact App image:https://img.shields.io/travis/incodehq/contactapp.svg["Build Status", link="https://travis-ci.org/incodehq/contactapp"] image:https://img.shields.io/badge/license-Apache%202-blue.svg["License", link="http://www.apache.org/licenses/LICENSE-2.0"] This is a contact management app made specifically for link:http://eurocommercial.com[Eurocommercial]. It gives a quick and easy way to manage company contacts and display them in a mobile app for users. + For the backend it uses an link:https://isis.apache.org/[Apache Isis] application surfacing a REST API. For the frontend it uses an link:http://ionicframework.com/[Ionic]/link:https://angularjs.org/[Angular] application using Typescript Refer to the link:https://github.com/incodehq/contactapp/wiki[Wiki] for detailed documentation. == Domain Model image:http://yuml.me/0ec16938.svg["Domain Model", link="http://yuml.me/edit/0ec16938"] == Screenshots These screenshots (taken 13 april 2016) show usage of the mobile app as well as the backend app. image:/docs/contactapp-frontend.png[width="100%"] image:/docs/contactapp-backend-homepage.png[width="100%"] image:/docs/contactapp-backend-amiens-property.png[width="100%"] image:/docs/contactapp-backend-benoit-foure.png[width="100%"] == License [source] ---- Copyright 2015-2016 Eurocommercial Properties NV 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. ---- <file_sep>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.number.integtests; import javax.inject.Inject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.services.wrapper.InvalidException; import org.incode.eurocommercial.contactapp.fixtures.DemoFixture; import org.incode.eurocommercial.contactapp.module.ContactAppDomainIntegTest; import org.incode.eurocommercial.contactapp.module.contactable.dom.ContactableEntity; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumber; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberRepository; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberType; import static org.assertj.core.api.Assertions.assertThat; public class ContactNumberIntegTest extends ContactAppDomainIntegTest { @Inject FixtureScripts fixtureScripts; @Inject ContactNumberRepository contactNumberRepository; ContactNumber contactNumber; DemoFixture fs; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() throws Exception { // given fs = new DemoFixture(); fixtureScripts.runFixtureScript(fs, null); contactNumber = fs.getContacts().get(0).getContactNumbers().first(); nextTransaction(); assertThat(contactNumber).isNotNull(); } public static class Create extends ContactNumberIntegTest { @Test public void add_number_with_existing_type() throws Exception { // given final String contactNumberType = ContactNumberType.OFFICE.title(); final String newOfficePhoneNumber = randomPhoneNumber(); assertThat(contactNumberRepository.listAll()) .extracting(ContactNumber::getNumber) .doesNotContain(newOfficePhoneNumber); // when wrap(this.contactNumber).create(newOfficePhoneNumber, contactNumberType, null); nextTransaction(); // then assertThat(contactNumberRepository.listAll()) .extracting(ContactNumber::getNumber) .contains(newOfficePhoneNumber); } @Test public void add_number_with_new_type() throws Exception { // given final String contactNumberType = "New type"; final String newOfficePhoneNumber = randomPhoneNumber(); assertThat(contactNumberRepository.listAll()) .extracting(ContactNumber::getNumber) .doesNotContain(newOfficePhoneNumber); // when wrap(this.contactNumber).create(newOfficePhoneNumber, null, contactNumberType); nextTransaction(); // then assertThat(contactNumberRepository.listAll()) .extracting(ContactNumber::getNumber) .contains(newOfficePhoneNumber); } @Test public void add_number_when_already_have_number_of_any_type() throws Exception { // given final String existingNumber = this.contactNumber.getNumber(); final String newType = "New type"; assertThat(this.contactNumber.getType()).isNotEqualToIgnoringCase(newType); // when wrap(this.contactNumber).create(existingNumber, null, newType); // then assertThat(this.contactNumber.getType()).isEqualTo(newType); assertThat(this.contactNumber.getNumber()).isEqualTo(existingNumber); } @Test public void when_no_type_specified() throws Exception { // given final String newPhoneNumber = randomPhoneNumber(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) type or a new type"); // when wrap(this.contactNumber).create(newPhoneNumber, null, null); } @Test public void when_both_existing_type_and_new_type_specified() throws Exception { // given final String newPhoneNumber = randomPhoneNumber(); // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) type or a new type"); // when wrap(this.contactNumber).create(newPhoneNumber, ContactNumberType.OFFICE.title(), "New type"); } @Test public void when_no_number_provided() throws Exception { // given final String noNumber = null; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); // when wrap(this.contactNumber).create(noNumber, ContactNumberType.OFFICE.title(), null); } @Test public void invalid_number_format() throws Exception { // given final String invalidNumber = "This is an invalid number"; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Phone number should be in form: +44 1234 5678"); // when wrap(this.contactNumber).create(invalidNumber, ContactNumberType.OFFICE.title(), null); } } public static class Edit extends ContactNumberIntegTest { @Test public void change_number() throws Exception { // given final String oldNumber = contactNumber.getNumber(); final String newNumber = randomPhoneNumber(); // when wrap(this.contactNumber).edit(newNumber, this.contactNumber.default1Edit(), null); // then assertThat(contactNumber.getNumber()).isEqualTo(newNumber); assertThat(contactNumberRepository.listAll()) .extracting(ContactNumber::getNumber) .doesNotContain(oldNumber); } @Test public void change_type_to_existing() throws Exception { // given final String currentType = this.contactNumber.getType(); final String existingType = ContactNumberType.OFFICE.title(); assertThat(currentType).isNotEqualToIgnoringCase(existingType); final long amountOfCurrentType = contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(currentType)) .count(); final long amountOfNewType = contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(existingType)) .count(); // when wrap(this.contactNumber).edit(this.contactNumber.default0Edit(), existingType, null); // then assertThat(this.contactNumber.getType()).isEqualToIgnoringCase(existingType); assertThat(contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(currentType)) .count()).isEqualTo(amountOfCurrentType - 1); assertThat(contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(existingType)) .count()).isEqualTo(amountOfNewType + 1); } @Test public void change_type_to_new_type() throws Exception { // given final String currentType = this.contactNumber.getType(); final String newType = "New Type"; assertThat(currentType).isNotEqualToIgnoringCase(newType); final long amountOfCurrentType = contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(currentType)) .count(); final long amountOfNewType = contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(newType)) .count(); // when wrap(this.contactNumber).edit(this.contactNumber.default0Edit(), null, newType); // then assertThat(this.contactNumber.getType()).isEqualToIgnoringCase(newType); assertThat(contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(currentType)) .count()).isEqualTo(amountOfCurrentType - 1); assertThat(contactNumberRepository.listAll() .stream() .filter(conNum -> conNum.getType().equalsIgnoreCase(newType)) .count()).isEqualTo(amountOfNewType + 1); } @Test public void when_change_number_to_already_existing() throws Exception { // given final String existingNumber = fakeDataService.collections() .anyOfExcept( contactNumberRepository.listAll(), (ContactNumber conNum) -> conNum.equals(this.contactNumber)) .getNumber(); assertThat(existingNumber).isNotEqualToIgnoringCase(this.contactNumber.getNumber()); // then thrown.expect(InvalidException.class); thrown.expectMessage("A contact number with this number already exists"); // when wrap(this.contactNumber).edit(existingNumber, this.contactNumber.default1Edit(), null); } @Test public void when_no_type_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) type or a new type"); // when wrap(this.contactNumber).edit(this.contactNumber.default0Edit(), null, null); } @Test public void when_both_existing_type_and_new_type_specified() throws Exception { // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Must specify either an (existing) type or a new type"); // when wrap(this.contactNumber).edit(this.contactNumber.default0Edit(), this.contactNumber.default1Edit(), "New type"); } @Test public void when_no_number_provided() throws Exception { // given final String noNumber = null; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Mandatory"); // when wrap(this.contactNumber).edit(noNumber, this.contactNumber.default1Edit(), null); } @Test public void invalid_number_format() throws Exception { // given final String invalidNumber = "This is an invalid number"; // then thrown.expect(InvalidException.class); thrown.expectMessage("Reason: Phone number should be in form: +44 1234 5678"); // when wrap(this.contactNumber).edit(invalidNumber, this.contactNumber.default1Edit(), null); } @Test public void without_new_number() throws Exception { // given assertThat(this.contactNumber.getNumber()).isEqualTo("+44 1233 444 555"); // when wrap(this.contactNumber).edit(this.contactNumber.default0Edit(), null, "New Type"); // then assertThat(this.contactNumber.getType()).isEqualTo("New Type"); // Naturally the number hasn't changed; this assertion merely ensures validateEdit // does not throw an exception assertThat(this.contactNumber.getNumber()).isEqualTo("+44 1233 444 555"); } } public static class Delete extends ContactNumberIntegTest { @Test public void happy_case() throws Exception { // given final String numberToBeDeleted = this.contactNumber.getNumber(); final int contactNumbersBefore = contactNumberRepository.listAll().size(); final ContactableEntity owner = this.contactNumber.getOwner(); assertThat(contactNumbersBefore).isNotZero(); assertThat(owner.getContactNumbers().first()).isEqualTo(this.contactNumber); assertThat(owner.getContactNumbers()).contains(this.contactNumber); // when wrap(this.contactNumber).delete(); // then assertThat(contactNumberRepository.findByNumber(numberToBeDeleted)).isNull(); assertThat(owner.getContactNumbers()).extracting(ContactNumber::getNumber).doesNotContain(numberToBeDeleted); } } }<file_sep>mvn -pl dom datanucleus:enhance -o <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.contact.integtests; import java.util.List; import javax.inject.Inject; import org.junit.Before; import org.junit.Test; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.services.xactn.TransactionService; import org.incode.eurocommercial.contactapp.fixtures.DemoFixture; import org.incode.eurocommercial.contactapp.module.ContactAppDomainIntegTest; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactRepository; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroupRepository; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRole; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRoleRepository; import static org.assertj.core.api.Assertions.assertThat; public class ContactRepositoryTest extends ContactAppDomainIntegTest { @Inject FixtureScripts fixtureScripts; @Inject ContactRepository contactRepository; @Inject ContactGroupRepository contactGroupRepository; @Inject TransactionService transactionService; @Before public void setUp() throws Exception { // given FixtureScript fs = new DemoFixture(); fixtureScripts.runFixtureScript(fs, null); transactionService.nextTransaction(); } public static class ListAll extends ContactRepositoryTest { @Test public void happyCase() throws Exception { // given, when final List<Contact> contacts = contactRepository.listAll(); // then assertThat(contacts.size()).isEqualTo(13); } } public static class ListOrphanedContacts extends ContactRepositoryTest { @Test public void happyCase() throws Exception { // given assertThat(contactRepository.listOrphanedContacts()).isEmpty(); // when final ContactGroup contactGroup = contactGroupRepository.listAll().get(0); wrap(contactGroup).delete(true); // then assertThat(contactRepository.listOrphanedContacts().size()).isEqualTo(5); } } public static class Find extends ContactRepositoryTest { @Test public void multipleFindersSingleQuery() throws Exception { // given String query = "(?i).*a.*"; // when final List<Contact> contacts = contactRepository.find(query); // then assertThat(contacts.size()).isEqualTo(13); } } public static class FindByName extends ContactRepositoryTest { @Test public void happyCase() throws Exception { // given final String contactName = contactRepository.listAll().get(0).getName(); // when final List<Contact> contacts = contactRepository.findByName(contactName); // then assertThat(contacts.size()).isGreaterThan(0); } @Test public void partial_name() throws Exception { // given final String contactName = contactRepository.listAll().get(0).getName(); final String firstName = contactName.split(" ")[0]; final String firstLetter = "b"; // when final List<Contact> contact = contactRepository.findByName("(?i).*" + firstName + ".*"); final List<Contact> contacts = contactRepository.findByName("(?i).*" + firstLetter + ".*"); // then assertThat(contact.size()).isEqualTo(1); assertThat(contacts.size()).isEqualTo(5); } @Test public void no_matches() throws Exception { // given final String contactName = "Not a name"; // when final List<Contact> contacts = contactRepository.findByName("(?i).*" + contactName + ".*"); // then assertThat(contacts.size()).isEqualTo(0); } } public static class FindByCompany extends ContactRepositoryTest { @Test public void happy_case() throws Exception { // given final String contactCompany = contactRepository.listAll().get(0).getCompany(); // when final List<Contact> contacts = contactRepository.findByCompany(contactCompany); // then assertThat(contacts.size()).isGreaterThan(0); } @Test public void partial_name() throws Exception { // given final String contactCompany = contactRepository.listAll().get(0).getCompany(); final String substring = contactCompany.substring(1, 3); // when final List<Contact> contact = contactRepository.findByCompany("(?i).*" + substring + ".*"); // then assertThat(contact.size()).isGreaterThan(0); } @Test public void sadCase() throws Exception { // given final String contactCompany = "Not a name"; // when final List<Contact> contacts = contactRepository.findByName("(?i).*" + contactCompany + ".*"); // then assertThat(contacts.size()).isEqualTo(0); } } public static class FindByContactGroup extends ContactRepositoryTest { @Inject ContactGroupRepository contactGroupRepository; @Test public void happy_case() throws Exception { // given final ContactGroup contactGroup = contactGroupRepository.listAll().get(0); // when final List<Contact> contacts = contactRepository.findByContactGroup(contactGroup); // then assertThat(contacts.size()).isGreaterThan(0); } @Test public void no_matches() throws Exception { // given final ContactGroup contactGroup = new ContactGroup(); // when final List<Contact> contacts = contactRepository.findByContactGroup(contactGroup); // then assertThat(contacts.size()).isEqualTo(0); } } public static class FindByContactRoleName extends ContactRepositoryTest { @Inject ContactRoleRepository contactRoleRepository; @Test public void happy_case() throws Exception { // given List<ContactRole> list = contactRoleRepository.listAll(); String regex = "No ContactRoleName in fixtures"; for(ContactRole contactRole : list) { if (contactRole.getRoleName() != null) { regex = contactRole.getRoleName(); } } // when final List<Contact> contacts = contactRepository.findByContactRoleName(regex); // then assertThat(contacts.size()).isGreaterThan(0); } @Test public void no_matches() throws Exception { // given final String roleName = "Not a role"; // when final List<Contact> contacts = contactRepository.findByContactRoleName(roleName); // then assertThat(contacts.size()).isEqualTo(0); } } }<file_sep>{ "compilerOptions": { "target": "ES5", "allowNonTsExtensions": true, "module": "commonjs", "sourceMap": true, "isolatedModules": true, "noEmitOnError": false, "rootDir": ".", "emitDecoratorMetadata": true, "experimentalDecorators": true }, "compileOnSave": false } <file_sep>HTTP Auth Interceptor Module ============================ for AngularJS ------------- This is the implementation of the concept described in [Authentication in AngularJS (or similar) based application](http://www.espeo.pl/1-authentication-in-angularjs-application/). There are releases for both AngularJS **1.0.x** and **1.2.x**, see [releases](https://github.com/witoldsz/angular-http-auth/releases). Launch demo [here](http://witoldsz.github.com/angular-http-auth/) or switch to [gh-pages](https://github.com/witoldsz/angular-http-auth/tree/gh-pages) branch for source code of the demo. Usage ------ - Install via bower: `bower install --save angular-http-auth` - ...or via npm: `npm install --save angular-http-auth` - Include as a dependency in your app: `angular.module('myApp', ['http-auth-interceptor'])` Manual ------ This module installs $http interceptor and provides the `authService`. The $http interceptor does the following: the configuration object (this is the requested URL, payload and parameters) of every HTTP 401 response is buffered and everytime it happens, the `event:auth-loginRequired` message is broadcasted from $rootScope. The `authService` has only one method: `loginConfirmed()`. You are responsible to invoke this method after user logged in. You may optionally pass in a data argument to the loginConfirmed method which will be passed on to the loginConfirmed $broadcast. This may be useful, for example if you need to pass through details of the user that was logged in. The `authService` will then retry all the requests previously failed due to HTTP 401 response. In the event that a requested resource returns an HTTP 403 response (i.e. the user is authenticated but not authorized to access the resource), the user's request is discarded and the `event:auth-forbidden` message is broadcast from $rootScope. #### Ignoring the 401 interceptor Sometimes you might not want the interceptor to intercept a request even if one returns 401 or 403. In a case like this you can add `ignoreAuthModule: true` to the request config. A common use case for this would be, for example, a login request which returns 401 if the login credentials are invalid. ###Typical use case: * somewhere (some service or controller) the: `$http(...).then(function(response) { do-something-with-response })` is invoked, * the response of that requests is a **HTTP 401**, * `http-auth-interceptor` captures the initial request and broadcasts `event:auth-loginRequired`, * your application intercepts this to e.g. show a login dialog: * DO NOT REDIRECT anywhere (you can hide your forms), just show login dialog * once your application figures out the authentication is OK, call: `authService.loginConfirmed()`, * your initial failed request will now be retried and when proper response is finally received, the `function(response) {do-something-with-response}` will fire, * your application will continue as nothing had happened. ###Advanced use case: ####Sending data to listeners: You can supply additional data to observers across your application who are listening for `event:auth-loginConfirmed`: $scope.$on('event:auth-loginConfirmed', function(event, data){ $rootScope.isLoggedin = true; $log.log(data) }); Use the `authService.loginConfirmed([data])` method to emit data with your login event. ####Updating [$http(config)](https://docs.angularjs.org/api/ng/service/$http): Successful login means that the previous request are ready to be fired again, however now that login has occurred certain aspects of the previous requests might need to be modified on the fly. This is particularly important in a token based authentication scheme where an authorization token should be added to the header. The `loginConfirmed` method supports the injection of an Updater function that will apply changes to the http config object. authService.loginConfirmed([data], [Updater-Function]) //application of tokens to previously fired requests: var token = reponse.token; authService.loginConfirmed('success', function(config){ config.headers["Authorization"] = token; return config; }) The initial failed request will now be retried, all queued http requests will be recalculated using the Updater-Function. <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.country.dom; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Programmatic; @DomainService( nature = NatureOfService.DOMAIN, repositoryFor = Country.class ) public class CountryRepository { @Programmatic public java.util.List<Country> listAll() { return container.allInstances(Country.class); } @Programmatic public Country findByName( final String name ) { return container.uniqueMatch( new org.apache.isis.applib.query.QueryDefault<>( Country.class, "findByName", "name", name)); } @Programmatic public Country create(final String name) { final Country country = container.newTransientInstance(Country.class); country.setName(name); container.persistIfNotAlready(country); return country; } @Programmatic public Country findOrCreate( final String name ) { Country country = findByName(name); if (country == null) { country = create(name); } return country; } @javax.inject.Inject org.apache.isis.applib.DomainObjectContainer container; } <file_sep>angular.module( 'ecp-contactapp.controllers.about', []) .controller('AboutCtrl', ['$scope', function($scope) { var ctrl = this; }]) ; <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.group.dom; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ContactGroupTest { ContactGroup contactGroup; @Before public void setUp() throws Exception { contactGroup = new ContactGroup(); } public static class Change extends ContactGroupTest { @Test public void happyCase() throws Exception { // given String name = "New name"; String address = "New address"; String email = "New email"; String notes = "New content"; // when contactGroup.edit(name, address, email, notes); // then assertThat(contactGroup.getName()).isEqualTo(name); assertThat(contactGroup.getEmail()).isEqualTo(email); assertThat(contactGroup.getAddress()).isEqualTo(address); assertThat(contactGroup.getNotes()).isEqualTo(notes); } } } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.seed; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.DomainServiceLayout; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.incode.eurocommercial.contactapp.module.country.seed.CountryRefData; import org.incode.eurocommercial.contactapp.module.role.seed.ApacheIsisRoleAndPermissions; import org.incode.eurocommercial.contactapp.module.role.seed.ContactAppAdminRoleAndPermissions; import org.incode.eurocommercial.contactapp.module.role.seed.ContactAppReadOnlyRoleAndPermissions; import org.incode.eurocommercial.contactapp.module.role.seed.ContactAppSuperadminRoleAndPermissions; import org.incode.eurocommercial.contactapp.module.user.seed.AdminUser; import org.incode.eurocommercial.contactapp.module.user.seed.LockIsisModuleSecurityAdminUser; import org.incode.eurocommercial.contactapp.module.user.seed.ReaderUser; import org.incode.eurocommercial.contactapp.module.user.seed.SuperadminUser; @DomainService( nature = NatureOfService.DOMAIN ) @DomainServiceLayout( menuOrder = "1100" // not visible, but determines the order initialized (must come after security module's seed service) ) public class ContactAppRolesAndPermissionsAndRefDataSeedService { //region > init @Programmatic @PostConstruct public void init() { fixtureScripts.runFixtureScript(new SeedFixtureScript(), null); } //endregion //region > (injected) @Inject FixtureScripts fixtureScripts; //endregion public static class SeedFixtureScript extends FixtureScript { @Override protected void execute(final ExecutionContext executionContext) { executionContext.executeChild(this, new ContactAppSuperadminRoleAndPermissions()); executionContext.executeChild(this, new ContactAppAdminRoleAndPermissions()); executionContext.executeChild(this, new ContactAppReadOnlyRoleAndPermissions()); executionContext.executeChild(this, new ApacheIsisRoleAndPermissions()); executionContext.executeChild(this, new SuperadminUser()); executionContext.executeChild(this, new AdminUser()); executionContext.executeChild(this, new ReaderUser()); executionContext.executeChild(this, new LockIsisModuleSecurityAdminUser()); // configured but not required by any user: // executionContext.executeChild(this, new ContactAppFixtureServiceRoleAndPermissions()); // executionContext.executeChild(this, new SettingsModuleRoleAndPermissions()); // not configured: // executionContext.executeChild(this, new TogglzModuleAdminRole()); // executionContext.executeChild(this, new AuditModuleRoleAndPermissions()); // executionContext.executeChild(this, new CommandModuleRoleAndPermissions()); // executionContext.executeChild(this, new PublishingModuleRoleAndPermissions()); // executionContext.executeChild(this, new SessionLoggerModuleRoleAndPermissions()); // executionContext.executeChild(this, new TranslationServicePoMenuRoleAndPermissions()); executionContext.executeChild(this, new CountryRefData()); } } } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.group.app; import java.util.List; import javax.annotation.Nullable; import javax.inject.Inject; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.Lists; import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.ViewModel; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Collection; import org.apache.isis.applib.annotation.CollectionLayout; import org.apache.isis.applib.annotation.DomainObjectLayout; import org.apache.isis.applib.annotation.MemberGroupLayout; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.PropertyLayout; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Title; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.bookmark.Bookmark; import org.apache.isis.applib.services.bookmark.BookmarkService; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroupRepository; import lombok.Getter; import lombok.Setter; @MemberGroupLayout( columnSpans = {6,0,0,6}, left = {"Group", "Ordering"} ) @DomainObjectLayout( cssClassFa = "sort-alpha-asc" ) public class ContactGroupOrderingViewModel implements ViewModel { @Inject BookmarkService bookmarkService; @Inject DomainObjectContainer container; @Override public String viewModelMemento() { final ContactGroup contactGroup = getContactGroup(); final Bookmark bookmark = bookmarkService.bookmarkFor(contactGroup); return bookmark.getIdentifier(); } @Override public void viewModelInit(final String memento) { final Bookmark bookmark = bookmarkService.bookmarkFor(ContactGroup.class, memento); this.contactGroup = (ContactGroup) bookmarkService.lookup(bookmark); } public ContactGroupOrderingViewModel() { } public ContactGroupOrderingViewModel(final ContactGroup contactGroup) { setContactGroup(contactGroup); } //@XmlElement @Property @PropertyLayout( hidden = Where.PARENTED_TABLES ) @Getter @Setter private ContactGroup contactGroup; // @XmlTransient private Integer displayOrder; @Property @PropertyLayout() public Integer getDisplayOrder() { return contactGroup.getDisplayOrder(); } @Title @Property @PropertyLayout( hidden = Where.OBJECT_FORMS ) public String getName() { return container.titleOf(contactGroup); } @Action(semantics = SemanticsOf.NON_IDEMPOTENT) @ActionLayout( cssClassFa = "arrow-up" ) @MemberOrder(name = "displayOrder", sequence = "1") public ContactGroupOrderingViewModel moveUp() { reorder(repository.listAll()); spreadOut(repository.listAll(), 10); updateCurrent(-15, Integer.MAX_VALUE); reorder(repository.listAll()); return this; } @Action(semantics = SemanticsOf.NON_IDEMPOTENT) @ActionLayout( cssClassFa = "arrow-down" ) @MemberOrder(name = "displayOrder", sequence = "2") public ContactGroupOrderingViewModel moveDown() { reorder(repository.listAll()); spreadOut(repository.listAll(), 10); updateCurrent(+15, Integer.MIN_VALUE); reorder(repository.listAll()); return this; } @Action(semantics = SemanticsOf.NON_IDEMPOTENT) @ActionLayout( cssClassFa = "ban" ) @MemberOrder(name = "displayOrder", sequence = "3") public ContactGroupOrderingViewModel clear() { contactGroup.setDisplayOrder(null); reorder(repository.listAll()); return this; } private void spreadOut(final List<ContactGroup> contactGroupsBefore, final int factor) { for (ContactGroup contactGroup : contactGroupsBefore) { final Integer displayOrder = contactGroup.getDisplayOrder(); if(displayOrder != null) { contactGroup.setDisplayOrder(displayOrder * factor); } else { return; } } } private void updateCurrent(final int adjust, final int fallback) { final Integer currDisplayOrder = contactGroup.getDisplayOrder(); contactGroup.setDisplayOrder( currDisplayOrder != null ? currDisplayOrder + adjust : fallback); } private void reorder(final List<ContactGroup> contactGroupsAfter) { int num = 0; for (ContactGroup contactGroup : contactGroupsAfter) { if(contactGroup.getDisplayOrder() != null) { contactGroup.setDisplayOrder(++num); } else { return; } } } @Collection( notPersisted = true // so that Apache Isis ignores when remapping ) @CollectionLayout( defaultView = "table", paged = 100 ) public List<ContactGroupOrderingViewModel> getContactGroups() { final List<ContactGroup> contactGroups = repository.listAll(); return Lists.newArrayList( FluentIterable.from(contactGroups) .transform(toViewModel()) ); } private Function<ContactGroup, ContactGroupOrderingViewModel> toViewModel() { return new Function<ContactGroup, ContactGroupOrderingViewModel>() { @Nullable @Override public ContactGroupOrderingViewModel apply(@Nullable final ContactGroup contactGroup) { final ContactGroupOrderingViewModel vm = ContactGroupOrderingViewModel.this; return contactGroup == vm.contactGroup ? vm // can't have two view models both representing the same contact group at same time : container.injectServicesInto(new ContactGroupOrderingViewModel(contactGroup)); } }; } // @XmlTransient @Inject ContactGroupRepository repository; static class Functions { private Functions(){} } } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.rest.v1.contacts; import java.util.List; import com.google.common.collect.FluentIterable; import com.google.common.collect.Lists; import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.SemanticsOf; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactRepository; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroupRepository; @DomainService( nature = NatureOfService.VIEW_REST_ONLY, objectType = "ContactableViewModelRepository" ) public class ContactableViewModelRepository { //public String id() { return ""; } @Action( semantics = SemanticsOf.SAFE, typeOf = ContactableViewModel.class ) public java.util.List<ContactableViewModel> listAll() { final List<ContactableViewModel> contactable = Lists.newArrayList(); contactable.addAll( FluentIterable .from(contactGroupRepository.listAll()) .transform(ContactableViewModel.createForGroup(container)) .toList()); contactable.addAll( FluentIterable .from(contactRepository.listAll()) .transform(ContactableViewModel.createForContact(container)) .toList()); return contactable; } @javax.inject.Inject ContactGroupRepository contactGroupRepository; @javax.inject.Inject ContactRepository contactRepository; @javax.inject.Inject DomainObjectContainer container; } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.contactable.dom; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; import javax.inject.Inject; import javax.jdo.annotations.Column; import javax.jdo.annotations.DatastoreIdentity; import javax.jdo.annotations.DiscriminatorStrategy; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.Queries; import javax.jdo.annotations.Version; import javax.jdo.annotations.VersionStrategy; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.BookmarkPolicy; import org.apache.isis.applib.annotation.Collection; import org.apache.isis.applib.annotation.CollectionLayout; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.DomainObjectLayout; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberGroupLayout; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Optionality; import org.apache.isis.applib.annotation.Parameter; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.PropertyLayout; import org.apache.isis.applib.annotation.RenderType; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.apache.isis.schema.utils.jaxbadapters.PersistentEntityAdapter; import org.incode.eurocommercial.contactapp.module.ContactAppDomainModule; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumber; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberRepository; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberSpec; import org.incode.eurocommercial.contactapp.module.number.dom.ContactNumberType; import org.incode.eurocommercial.contactapp.module.base.dom.StringUtil; import lombok.Getter; import lombok.Setter; @PersistenceCapable( identityType = IdentityType.DATASTORE ) @DatastoreIdentity( strategy = IdGeneratorStrategy.NATIVE, column = "id") @Version( strategy = VersionStrategy.DATE_TIME, column = "version") @javax.jdo.annotations.Discriminator( strategy = DiscriminatorStrategy.VALUE_MAP, column = "discriminator") @Queries({ }) @DomainObject( editing = Editing.DISABLED ) @DomainObjectLayout( bookmarking = BookmarkPolicy.AS_ROOT ) @MemberGroupLayout( columnSpans = { 6, 0, 0, 6 } ) @XmlJavaTypeAdapter(PersistentEntityAdapter.class) public class ContactableEntity { //region > title public static class MaxLength { private MaxLength() { } public static final int NAME = 50; public static final int EMAIL = 50; public static final int NOTES = ContactAppDomainModule.MaxLength.NOTES; } public String title() { return getName(); } //endregion @Column(allowsNull = "false", length = MaxLength.NAME) @Property @Getter @Setter private String name; @Column(allowsNull = "true", length = MaxLength.EMAIL) @Property @Getter @Setter private String email; @Column(allowsNull = "true", length = MaxLength.NOTES) @Property @PropertyLayout(multiLine = 6, hidden = Where.ALL_TABLES) @Getter @Setter private String notes; @Persistent(mappedBy = "owner", dependentElement = "true") @Collection() @CollectionLayout(render = RenderType.EAGERLY) @Getter @Setter private SortedSet<ContactNumber> contactNumbers = new TreeSet<ContactNumber>(); //region > addContactNumber (action) //endregion @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Add") @MemberOrder(name = "contactNumbers", sequence = "1") public ContactableEntity addContactNumber( @Parameter(maxLength = ContactNumber.MaxLength.NUMBER, mustSatisfy = ContactNumberSpec.class) final String number, @Parameter(maxLength = ContactNumber.MaxLength.TYPE, optionality = Optionality.OPTIONAL) final String type, @Parameter(maxLength = ContactNumber.MaxLength.TYPE, optionality = Optionality.OPTIONAL) final String newType ) { contactNumberRepository.findOrCreate(this, number, StringUtil.firstNonEmpty(newType, type)); return this; } public Set<String> choices1AddContactNumber() { return contactNumberRepository.existingTypes(); } public String default1AddContactNumber() { return ContactNumberType.OFFICE.title(); } public String validateAddContactNumber( final String number, final String type, final String newType) { return StringUtil.eitherOr(type, newType, "type"); } //region > removeContactNumber (action) //endregion @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Remove") @MemberOrder(name = "contactNumbers", sequence = "2") public ContactableEntity removeContactNumber(final String number) { final Optional<ContactNumber> contactNumberIfAny = Iterables .tryFind(getContactNumbers(), cn -> Objects.equal(cn.getNumber(), number)); if (contactNumberIfAny.isPresent()) { getContactNumbers().remove(contactNumberIfAny.get()); } return this; } public String disableRemoveContactNumber() { return getContactNumbers().isEmpty() ? "No contact numbers to remove" : null; } public List<String> choices0RemoveContactNumber() { return Lists.transform(Lists.newArrayList(getContactNumbers()), ContactNumber::getNumber); } public String default0RemoveContactNumber() { final List<String> choices = choices0RemoveContactNumber(); return choices.isEmpty() ? null : choices.get(0); } //region > helpers @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ContactableEntity)) return false; ContactableEntity contactableEntity = (ContactableEntity) obj; return contactableEntity.getName().equals(this.getName()); } @Override public String toString() { return org.apache.isis.applib.util.ObjectContracts.toString(this, "name"); } public static <T extends ContactableEntity> Function<T, String> nameOf() { return new Function<T, String>() { @Nullable @Override public String apply(final T contactGroup) { return contactGroup.getName(); } }; } //endregion //region > injected services //endregion @Inject ContactNumberRepository contactNumberRepository; } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.services.settings; import java.util.List; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.DomainServiceLayout; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.incode.module.settings.dom.ApplicationSettingsServiceRW; import org.incode.module.settings.dom.UserSettingsServiceRW; import org.incode.module.settings.dom.jdo.ApplicationSettingJdo; import org.incode.module.settings.dom.jdo.UserSettingJdo; @DomainService(nature = NatureOfService.VIEW_MENU_ONLY) @DomainServiceLayout( menuBar = DomainServiceLayout.MenuBar.TERTIARY, named = "Settings", menuOrder = "500" ) public class ContactAppSettingsService { @Action( semantics = SemanticsOf.SAFE, hidden = Where.EVERYWHERE // CURRENTLY NO APP SETTINGS, SO JUST HIDE FOR NOW... ) @ActionLayout( named = "Application Settings", cssClassFa = "fa-cog" ) @MemberOrder(sequence = "10") public List<ApplicationSettingJdo> listAllSettings() { // downcast using raw list final List applicationSettings = applicationSettingsService.listAll(); return applicationSettings; } @Programmatic public List<UserSettingJdo> listAllSettings(final String user) { // downcast using raw list final List userSettings = userSettingsService.listAllFor(user); return userSettings; } @Programmatic public <T extends Enum<T>> T get(final Class<T> enumCls) { final ApplicationSettingJdo setting = findSetting(enumCls); if (setting == null) { return null; } final String valueAsString = setting.getValueAsString(); final T[] enumConstants = enumCls.getEnumConstants(); for (final T enumConstant : enumConstants) { if(enumConstant.name().equals(valueAsString)) { return enumConstant; } } return null; } @Programmatic public <T extends Enum<T>> void set(final Class<T> enumCls, final T value) { final ApplicationSettingJdo setting = findSetting(enumCls); if(setting == null) { applicationSettingsService.newString(enumCls.getCanonicalName(), enumCls.getSimpleName(), value.name()); } else { setting.updateAsString(value.name()); } } protected <T extends Enum<T>> ApplicationSettingJdo findSetting(final Class<T> enumCls) { return (ApplicationSettingJdo) applicationSettingsService.find(enumCls.getCanonicalName()); } @javax.inject.Inject private ApplicationSettingsServiceRW applicationSettingsService; @javax.inject.Inject private UserSettingsServiceRW userSettingsService; } <file_sep>ion-radial-progress =================== Customizable radial progress bar Based on Flat Progress Bar: http://codepen.io/shankarcabus/pen/GzAfb Codepen: http://codepen.io/tgarlanger/pen/DtavH Usage: ```HTML <ion-radial-progress timer="60"></ion-radial-progress> ``` Where **timer** is the length of the timer <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.number.dom; import java.util.regex.Pattern; import org.apache.isis.applib.spec.Specification; public class ContactNumberSpec implements Specification { static final String ERROR_MESSAGE = "Phone number should be in form: +44 1234 5678"; private static Pattern pattern = Pattern.compile("\\+[\\d]{2} [\\d ]+\\d"); @Override public String satisfies(final Object obj) { if(obj == null || !(obj instanceof String)) { return null; } String str = (String) obj; if(pattern.matcher(str).matches()) { return null; } return ERROR_MESSAGE; } } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.rest; import javax.inject.Inject; import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.ViewModel; public abstract class ViewModelWithUnderlying<T> implements ViewModel { protected T underlying; @Override public String viewModelMemento() { return mementoService.viewModelMemento(this); } @Override public void viewModelInit(final String memento) { this.underlying = (T) mementoService.viewModelInit(memento); } public String title() { return container.titleOf(underlying); } @Override public String toString() { return underlying != null? underlying.toString(): "(no underlying)"; } @Inject protected DomainObjectContainer container; @Inject protected AbbreviatingMementoService mementoService; } <file_sep>FROM incodehq/tomcat:1.7.2 ADD ${docker-plugin.resource.include} ${DEPLOYMENT_DIR}/ROOT.war ADD entrypoint.sh / RUN chmod 755 /entrypoint.sh CMD /entrypoint.sh EXPOSE 8080 <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.services.homepage; import java.util.List; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Collection; import org.apache.isis.applib.annotation.CollectionLayout; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.ParameterLayout; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.ViewModel; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactRepository; import org.incode.eurocommercial.contactapp.module.country.dom.Country; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup; import org.incode.eurocommercial.contactapp.module.group.dom.ContactGroupRepository; @ViewModel public class HomePageViewModel { public String title() { return "Contact Groups"; } @Collection(editing = Editing.DISABLED) @CollectionLayout(paged=200) @org.apache.isis.applib.annotation.HomePage public List<ContactGroup> getGroups() { return contactGroupRepository.listAll(); } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Create", cssClassFa = "fa fa-plus") @MemberOrder(name = "groups", sequence = "1") public HomePageViewModel newContactGroup( final Country country, final String name) { contactGroupRepository.findOrCreate(country, name); return this; } @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Delete") @MemberOrder(name = "groups", sequence = "2") public HomePageViewModel deleteContactGroup( final ContactGroup contactGroup, @ParameterLayout(named = "This will also delete all Contact Roles connected to it, do you wish to proceed?") final boolean delete) { if (delete) { contactGroupRepository.delete(contactGroup); } return this; } public String validateDeleteContactGroup(final ContactGroup contactGroup, final boolean delete) { return delete ? null : "You have to agree"; } public List<ContactGroup> choices0DeleteContactGroup() { return contactGroupRepository.listAll(); } public ContactGroup default0DeleteContactGroup() { final List<ContactGroup> choices = choices0DeleteContactGroup(); return choices.isEmpty()? null: choices.get(0); } public String disableDeleteContactGroup() { return choices0DeleteContactGroup().isEmpty()? "No contact groups": null; } @javax.inject.Inject ContactGroupRepository contactGroupRepository; @javax.inject.Inject ContactRepository contactRepository; } <file_sep>angular.module( 'ecp-contactapp.services.preferences', []) .service( 'PreferencesService', ['AppConfig', '$rootScope', function(AppConfig, $rootScope) { var service = this; service.preferences = {} // // preferences.environment // var environmentKey = AppConfig.appPrefix + ".preferences.environment" var defaultEnvironment = "Production" // var defaultEnvironment = "Development" if(!window.localStorage[environmentKey]) { window.localStorage[environmentKey] = defaultEnvironment } service.preferences.environment = { options: [ { name: "Development", url: "http://localhost:8080" }, { name: "Test", url: "https://contactapp-test.dev.ecpnv.com" }, { name: "Production", url: "https://contacts.ecpnv.com" // default to the isis app that runs parallel in the container } ], selected: window.localStorage[environmentKey] } service.urlForSelectedEnvironment = function() { return service.preferences.environment.options.find( function(element) { return element.name === service.preferences.environment.selected }).url } service.updateEnvironment = function(environmentName) { service.preferences.environment.selected = environmentName window.localStorage[environmentKey] = environmentName } }]) ; <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.group.dom; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; import javax.inject.Inject; import javax.jdo.annotations.Column; import javax.jdo.annotations.Discriminator; import javax.jdo.annotations.InheritanceStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.Queries; import javax.jdo.annotations.Query; import javax.jdo.annotations.Unique; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Collection; import org.apache.isis.applib.annotation.CollectionLayout; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberGroupLayout; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Optionality; import org.apache.isis.applib.annotation.Parameter; import org.apache.isis.applib.annotation.ParameterLayout; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.PropertyLayout; import org.apache.isis.applib.annotation.RenderType; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.factory.FactoryService; import org.apache.isis.applib.services.layout.Object_rebuildMetamodel; import org.apache.isis.schema.utils.jaxbadapters.PersistentEntityAdapter; import org.incode.eurocommercial.contactapp.module.contactable.dom.ContactableEntity; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactRepository; import org.incode.eurocommercial.contactapp.module.country.dom.Country; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRole; import org.incode.eurocommercial.contactapp.module.role.dom.ContactRoleRepository; import org.incode.eurocommercial.contactapp.module.base.dom.StringUtil; import lombok.Getter; import lombok.Setter; @PersistenceCapable @javax.jdo.annotations.Inheritance(strategy = InheritanceStrategy.NEW_TABLE) @Discriminator("org.incode.eurocommercial.contactapp.dom.group.ContactGroup") @Queries({ @Query( name = "findByCountry", language = "JDOQL", value = "SELECT " + "FROM org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup " + "WHERE country == :country "), @Query( name = "findByCountryAndName", language = "JDOQL", value = "SELECT " + "FROM org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup " + "WHERE country == :country && name == :name "), @Query( name = "findByName", language = "JDOQL", value = "SELECT " + "FROM org.incode.eurocommercial.contactapp.module.group.dom.ContactGroup " + "WHERE name.matches(:regex) "), }) @Unique(name = "ContactGroup_displayNumber_UNQ", members = { "displayOrder" }) @DomainObject( editing = Editing.DISABLED ) @MemberGroupLayout( columnSpans = { 6, 0, 0, 6 }, left = { "General", "Other" } ) @XmlJavaTypeAdapter(PersistentEntityAdapter.class) public class ContactGroup extends ContactableEntity implements Comparable<ContactGroup> { public ContactGroup rebuild() { factoryService.mixin(Object_rebuildMetamodel.class, this).act(); return this; } @Inject FactoryService factoryService; //region > title public static class MaxLength { private MaxLength() { } public static final int ADDRESS = 255; } public String title() { // TODO: workaround, getCountry() sometimes returning null (eg after edit role name; don't know why as of yet). return getName() + (getCountry() != null? " (" + getCountry().getName() + ")" : ""); } //endregion @Column(allowsNull = "true") @Property() @PropertyLayout(hidden = Where.ALL_TABLES) @Getter @Setter private Integer displayOrder; private Country country; @javax.jdo.annotations.Persistent(defaultFetchGroup = "true") // eager load @Column(allowsNull = "false") @Property() @PropertyLayout(hidden = Where.REFERENCES_PARENT) public Country getCountry() { return country; } public void setCountry(final Country country) { this.country = country; } @Column(allowsNull = "true", length = MaxLength.ADDRESS) @Property @PropertyLayout(multiLine = 3) @Getter @Setter private String address; //region > create (action) @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Create", position = ActionLayout.Position.PANEL, cssClassFa = "fa fa-plus") public ContactGroup create( final Country country, @Parameter(maxLength = ContactableEntity.MaxLength.NAME) final String name) { return contactGroupRepository.findOrCreate(country, name); } public Country default0Create() { return getCountry(); } public String validateCreate( final Country country, final String name) { if (!contactGroupRepository.findByName(name).isEmpty()) { return "This name is already in use by another contact group"; } else { return contactRepository.findByName(name).isEmpty() ? null : "This name is already in use by a contact"; } } //endregion //region > edit (action) @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(position = ActionLayout.Position.PANEL) public ContactableEntity edit( @Parameter(maxLength = ContactableEntity.MaxLength.NAME) final String name, @Parameter(maxLength = MaxLength.ADDRESS, optionality = Optionality.OPTIONAL) @ParameterLayout(multiLine = 3) final String address, @Parameter(maxLength = ContactableEntity.MaxLength.EMAIL, optionality = Optionality.OPTIONAL) final String email, @Parameter(maxLength = ContactableEntity.MaxLength.NOTES, optionality = Optionality.OPTIONAL) @ParameterLayout(multiLine = 6) final String notes) { setName(name); setAddress(address); setEmail(email); setNotes(notes); return this; } public String default0Edit() { return getName(); } public String default1Edit() { return getAddress(); } public String default2Edit() { return getEmail(); } public String default3Edit() { return getNotes(); } public String validateEdit( final String name, final String address, final String email, final String notes) { if (!name.equals(this.getName()) && !contactGroupRepository.findByName(name).isEmpty()) { return "This name is already in use by another contact group"; } else { return contactRepository.findByName(name).isEmpty() ? null : "This name is already in use by a contact"; } } //endregion //region > delete (action) @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Delete", position = ActionLayout.Position.PANEL) public void delete(final @ParameterLayout(named = "This will also delete all Contact Roles connected to it, do you wish to proceed?") boolean delete) { if (delete) contactGroupRepository.delete(this); } public String validateDelete(final boolean delete) { return delete ? null : "You have to agree"; } @Persistent(mappedBy = "contactGroup", dependentElement = "true") @Collection() @CollectionLayout(named = "Role of Contacts in Group", render = RenderType.EAGERLY, defaultView = "table") @Getter @Setter private SortedSet<ContactRole> contactRoles = new TreeSet<ContactRole>(); //endregion //region > addContactRole (action) @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Add") @MemberOrder(name = "contactRoles", sequence = "1") public ContactGroup addContactRole( @Parameter(optionality = Optionality.MANDATORY) Contact contact, @Parameter(maxLength = ContactRole.MaxLength.NAME, optionality = Optionality.OPTIONAL) String role, @Parameter(maxLength = ContactRole.MaxLength.NAME, optionality = Optionality.OPTIONAL) String newRole) { final String roleName = StringUtil.firstNonEmpty(newRole, role); contactRoleRepository.findOrCreate(contact, this, roleName); return this; } public List<Contact> choices0AddContactRole() { final List<Contact> contacts = contactRepository.listAll(); final List<Contact> currentContacts = FluentIterable .from(getContactRoles()) .transform(ContactRole::getContact) .toList(); contacts.removeAll(currentContacts); return contacts; } public SortedSet<String> choices1AddContactRole() { return contactRoleRepository.roleNames(); } public String validateAddContactRole(final Contact contact, final String role, final String newRole) { return StringUtil.eitherOr(role, newRole, "role"); } //endregion //region > removeContactRole (action) @Action(semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(named = "Remove") @MemberOrder(name = "contactRoles", sequence = "2") public ContactGroup removeContactRole(final Contact contact) { final Optional<ContactRole> contactRoleIfAny = Iterables .tryFind(getContactRoles(), cn -> Objects.equal(cn.getContact(), contact)); if (contactRoleIfAny.isPresent()) { getContactRoles().remove(contactRoleIfAny.get()); } return this; } public Contact default0RemoveContactRole() { return getContactRoles().size() == 1 ? getContactRoles().iterator().next().getContact() : null; } public List<Contact> choices0RemoveContactRole() { return Lists.transform(Lists.newArrayList(getContactRoles()), ContactRole::getContact); } public String disableRemoveContactRole() { return getContactRoles().isEmpty() ? "No contacts to remove" : null; } //endregion //region > comparable private static final Ordering<ContactGroup> byDisplayNumberThenName = Ordering .natural() .nullsLast() .onResultOf(displayNumberOf()) .compound(Ordering .natural() .onResultOf(nameOf()) ); private static Function<ContactGroup, Integer> displayNumberOf() { return new Function<ContactGroup, Integer>() { @Nullable @Override public Integer apply(@Nullable final ContactGroup contactGroup) { return contactGroup.getDisplayOrder(); } }; } @Override public int compareTo(final ContactGroup other) { return byDisplayNumberThenName.compare(this, other); } //endregion //region > injected services @Inject ContactRoleRepository contactRoleRepository; @Inject ContactRepository contactRepository; @javax.inject.Inject ContactGroupRepository contactGroupRepository; //endregion } <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2015-2016 Eurocommercial Properties NV 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.incode.app</groupId> <artifactId>contactapp</artifactId> <version>${revision}</version> </parent> <artifactId>contactapp-dom</artifactId> <name>Incode App ContactApp DOM</name> <properties> <isis-maven-plugin.validate.appManifest>org.incode.eurocommercial.contactapp.module.ContactAppDomManifest</isis-maven-plugin.validate.appManifest> </properties> <build> <resources> <resource> <filtering>false</filtering> <directory>src/main/resources</directory> </resource> <resource> <filtering>false</filtering> <directory>src/main/java</directory> <includes> <include>**</include> </includes> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <testResources> <testResource> <filtering>false</filtering> <directory>src/test/java</directory> <includes> <include>**</include> </includes> <excludes> <exclude>**/*.java</exclude> </excludes> </testResource> </testResources> <plugins> <plugin> <groupId>com.github.odavid.maven.plugins</groupId> <artifactId>mixin-maven-plugin</artifactId> <version>0.1-alpha-39</version> <extensions>true</extensions> <configuration> <mixins> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>standard</artifactId> </mixin> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>datanucleusenhance</artifactId> </mixin> <!-- <mixin> <groupId>org.incode.mavenmixin</groupId> <artifactId>incode-mavenmixin-validate</artifactId> </mixin> --> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>staticanalysis</artifactId> </mixin> <mixin> <groupId>com.danhaywood.mavenmixin</groupId> <artifactId>surefire</artifactId> </mixin> </mixins> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.isis.core</groupId> <artifactId>isis-core-applib</artifactId> </dependency> <dependency> <groupId>org.apache.isis.core</groupId> <artifactId>isis-core-schema</artifactId> </dependency> <dependency> <groupId>org.apache.isis.core</groupId> <artifactId>isis-core-runtime</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.axonframework</groupId> <artifactId>axon-core</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.isisaddons.module.docx</groupId> <artifactId>isis-module-docx-dom</artifactId> </dependency> <dependency> <groupId>org.isisaddons.module.excel</groupId> <artifactId>isis-module-excel-dom</artifactId> </dependency> <dependency> <groupId>org.isisaddons.module.poly</groupId> <artifactId>isis-module-poly-dom</artifactId> </dependency> <dependency> <groupId>org.isisaddons.module.security</groupId> <artifactId>isis-module-security-dom</artifactId> </dependency> <dependency> <groupId>org.isisaddons.module.servletapi</groupId> <artifactId>isis-module-servletapi-dom</artifactId> </dependency> <dependency> <groupId>org.incode.module.settings</groupId> <artifactId>incode-module-settings-dom</artifactId> </dependency> <dependency> <groupId>org.isisaddons.module.stringinterpolator</groupId> <artifactId>isis-module-stringinterpolator-dom</artifactId> </dependency> <dependency> <groupId>org.togglz</groupId> <artifactId>togglz-core</artifactId> </dependency> <dependency> <groupId>org.isisaddons.wicket.fullcalendar2</groupId> <artifactId>isis-wicket-fullcalendar2-cpt</artifactId> <exclusions> <exclusion> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> </exclusion> <exclusion> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.isisaddons.wicket.gmap3</groupId> <artifactId>isis-wicket-gmap3-cpt</artifactId> </dependency> <!-- test --> <dependency> <groupId>org.apache.isis.mavendeps</groupId> <artifactId>isis-mavendeps-testing</artifactId> <type>pom</type> <scope>test</scope> </dependency> <dependency> <groupId>org.isisaddons.module.fakedata</groupId> <artifactId>isis-module-fakedata-dom</artifactId> <scope>test</scope> </dependency> </dependencies> </project> <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.app.services.export; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import com.google.common.base.Function; import com.google.common.io.Resources; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.output.DOMOutputter; import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.DomainServiceLayout; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.services.clock.ClockService; import org.apache.isis.applib.value.Blob; import org.isisaddons.module.docx.dom.DocxService; import org.isisaddons.module.docx.dom.LoadTemplateException; import org.isisaddons.module.docx.dom.MergeException; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import org.incode.eurocommercial.contactapp.module.contacts.dom.ContactRepository; //@DomainService ... REMOVED FOR NOW. @DomainServiceLayout( named="Contacts", menuOrder = "30" ) public class ExportToWordMenu { //region > exportToWordDoc (action) @Action( semantics = SemanticsOf.SAFE ) @ActionLayout( cssClassFa = "fa-download" ) @MemberOrder(sequence = "10") public Blob exportToWordDoc() throws IOException, JDOMException, MergeException { final List<Contact> list = contactRepository.listAll(); return exportToWordDoc(list); } //endregion //region > exportToWordDoc (programmatic) @Programmatic public Blob exportToWordDoc(final List<Contact> items) { return exportToWordDocCatchExceptions(items); } private Blob exportToWordDocCatchExceptions(final List<Contact> contacts) { final org.w3c.dom.Document w3cDocument; try { w3cDocument = asInputW3cDocument(contacts); final ByteArrayOutputStream docxTarget = new ByteArrayOutputStream(); docxService.merge(w3cDocument, getWordprocessingMLPackage(), docxTarget, DocxService.MatchingPolicy.LAX); final String blobName = "simpleObjects-" + timestamp() + ".docx"; final String blobMimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; final byte[] blobBytes = docxTarget.toByteArray(); return new Blob(blobName, blobMimeType, blobBytes); } catch (JDOMException | MergeException e) { throw new RuntimeException(e); } } private String timestamp() { return clockService.nowAsLocalDateTime().toString("yyyyMMdd'_'HHmmss"); } private org.w3c.dom.Document asInputW3cDocument(final List<Contact> items) throws JDOMException { final Document jdomDoc = asInputDocument(items); final DOMOutputter domOutputter = new DOMOutputter(); return domOutputter.output(jdomDoc); } private Document asInputDocument(final List<Contact> contacts) { final Element html = new Element("html"); final Document document = new Document(html); final Element body = new Element("body"); html.addContent(body); addPara(body, "ExportedOn", "date", clockService.nowAsLocalDateTime().toString("dd-MMM-yyyy")); final Element table = addTable(body, "SimpleObjects"); for(final Contact quickObject : contacts) { addTableRow(table, new String[] { quickObject.getName() }); } return document; } //endregion ( //region > helper: getWordprocessingMLPackage private WordprocessingMLPackage wordprocessingMLPackage; // lazily initialized to speed up bootstrapping (at cost of not failing fast). private WordprocessingMLPackage getWordprocessingMLPackage() { initializeIfNecessary(); return wordprocessingMLPackage; } private void initializeIfNecessary() { if(wordprocessingMLPackage == null) { try { final byte[] bytes = Resources.toByteArray(Resources.getResource(this.getClass(), "SimpleObjectsExport.docx")); wordprocessingMLPackage = docxService.loadPackage(new ByteArrayInputStream(bytes)); } catch (IOException | LoadTemplateException e) { throw new RuntimeException(e); } } } //endregion //region > helpers private static final Function<String, String> TRIM = input -> input.trim(); private static void addPara(final Element body, final String id, final String clazz, final String text) { final Element p = new Element("p"); body.addContent(p); p.setAttribute("id", id); p.setAttribute("class", clazz); p.setText(text); } private static Element addList(final Element body, final String id) { final Element ul = new Element("ul"); body.addContent(ul); ul.setAttribute("id", id); return ul; } private static Element addListItem(final Element ul, final String... paras) { final Element li = new Element("li"); ul.addContent(li); for (final String para : paras) { addPara(li, para); } return ul; } private static void addPara(final Element li, final String text) { if(text == null) { return; } final Element p = new Element("p"); li.addContent(p); p.setText(text); } private static Element addTable(final Element body, final String id) { final Element table = new Element("table"); body.addContent(table); table.setAttribute("id", id); return table; } private static void addTableRow(final Element table, final String[] cells) { final Element tr = new Element("tr"); table.addContent(tr); for (final String columnName : cells) { final Element td = new Element("td"); tr.addContent(td); td.setText(columnName); } } //endregion //region > injected services @javax.inject.Inject DomainObjectContainer container; @javax.inject.Inject private DocxService docxService; @javax.inject.Inject private ContactRepository contactRepository; @javax.inject.Inject private ClockService clockService; //endregion } <file_sep>angular.module( 'ecp-contactapp.controllers.contacts', []) .controller('ContactablesCtrl', ['BackendService', 'PreferencesService', '$state', '$ionicFilterBar', '$ionicSideMenuDelegate', function(BackendService, PreferencesService, $state, $ionicFilterBar, $ionicSideMenuDelegate) { var ctrl = this; ctrl.preferences = PreferencesService.preferences; ctrl.contactables = [] ctrl.showFilterBar = function() { ctrl.filterBarInstance = $ionicFilterBar.show({ items: ctrl.contactables, update: function (filteredItems, filterText) { ctrl.contactables = filteredItems; } }); } ctrl.showSideMenu = function() { $ionicSideMenuDelegate.toggleRight(); } BackendService.loadContactableList( function(contactables, messageIfAny) { ctrl.contactables = contactables ctrl.message = messageIfAny } ) /* no longer used... ctrl.firstLetter = function(name) { return name && name.charAt(0); } */ ctrl.cachedStateCssClass = function(contactable) { return contactable && contactable.$$instanceId && BackendService.isCached(contactable.$$instanceId) ? "cached" : "not-cached" } }]) .controller('ContactableDetailCtrl', ['BackendService', 'PreferencesService', '$stateParams', '$state', '$ionicSideMenuDelegate', function(BackendService, PreferencesService, $stateParams, $state, $ionicSideMenuDelegate) { var ctrl = this; ctrl.preferences = PreferencesService.preferences; ctrl.contactable = {} var instanceId = function(href) { var n = href.lastIndexOf('/'); var result = href.substring(n + 1); return result; } ctrl.showSideMenu = function() { $ionicSideMenuDelegate.toggleRight(); } BackendService.loadContactable( $stateParams.instanceId, function(contactable, messageIfAny) { ctrl.contactable = contactable ctrl.message = messageIfAny } ) var windowOpenSystem = function(href) { window.open(href, '_system'); } ctrl.sendEmail = function(email) { windowOpenSystem('mailto:' + email) } ctrl.dialNumber = function(number) { windowOpenSystem('tel:' + number); } ctrl.cachedStateCssClass = function(instanceId) { return instanceId && BackendService.isCached(instanceId) ? "cached" : "not-cached" } }]) ; <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.contact.dom; import org.junit.Before; import org.junit.Test; import org.incode.eurocommercial.contactapp.module.contacts.dom.Contact; import static org.assertj.core.api.Assertions.assertThat; public class ContactTest { Contact contact; @Before public void setUp() throws Exception { contact = new Contact(); } public static class Name extends ContactTest { @Test public void happyCase() throws Exception { // given String name = "Foobar"; assertThat(contact.getName()).isNull(); // when contact.setName(name); // then assertThat(contact.getName()).isEqualTo(name); } } public static class Change extends ContactTest { @Test public void happyCase() throws Exception { // given String name = "New name"; String company = "New company"; String email = "New email"; String notes = "New content"; // when contact.edit(name, company, email, notes); // then assertThat(contact.getName()).isEqualTo(name); assertThat(contact.getEmail()).isEqualTo(email); assertThat(contact.getCompany()).isEqualTo(company); assertThat(contact.getNotes()).isEqualTo(notes); } } } <file_sep>/* * Copyright 2015-2016 Eurocommercial Properties NV * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.incode.eurocommercial.contactapp.module.country.seed; import javax.inject.Inject; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.incode.eurocommercial.contactapp.module.country.dom.CountryRepository; public class CountryRefData extends FixtureScript { @Override protected void execute(ExecutionContext executionContext) { countryRepository.findOrCreate("Global"); countryRepository.findOrCreate("France"); countryRepository.findOrCreate("Italy"); countryRepository.findOrCreate("Sweden"); countryRepository.findOrCreate("Belgium"); } @Inject CountryRepository countryRepository; }
98279ba79a2ce7e6c8ccea1e6b2c15aa3d11380b
[ "JSON", "JavaScript", "Markdown", "Maven POM", "AsciiDoc", "INI", "Java", "Dockerfile", "Shell" ]
45
JavaScript
incodehq/contactapp
8d2414bdaf0ba0a69bd53d3082b51ce47b35642b
3ad776f8d162257b98e7720d8c86229ae132e592
refs/heads/master
<file_sep># angular-9z4ajd [Edit on StackBlitz ⚡️](https://stackblitz.com/edit/angular-9z4ajd)<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, ParamMap } from '@angular/router'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.css'] }) export class ProfileComponent implements OnInit { username$ = this.route.paramMap .pipe( map((params: ParamMap) => params.get('username')) ); constructor(private route: ActivatedRoute) { } ngOnInit() { } } /* Copyright Google LLC. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at https://angular.io/license */
bf2a26c6744997b6a4806859c19c26e1b59c9837
[ "Markdown", "TypeScript" ]
2
Markdown
ravirathor/angular-9z4ajd
f88329fc3ced839973d4d171e4dc8503d97bc518
7dfce20d04edfb8f84f59ac048c18f0e63bc8fb0
refs/heads/master
<file_sep>#include <signal.h> #include <unistd.h> #include "mraa.hpp" bool running = true; bool relay_state = false; int last_touch; void sig_handler(int signo) { if (signo == SIGINT) running = false; } int main(int argc, char* argv[]) { mraa::Gpio* touch_gpio = new mraa::Gpio(492); mraa::Gpio* relay_gpio = new mraa::Gpio(463); mraa::Result response; int touch; signal(SIGINT, sig_handler); response = touch_gpio->dir(mraa::DIR_IN); if (response != mraa::SUCCESS) return 1; response = relay_gpio->dir(mraa::DIR_OUT); if (response != mraa::SUCCESS) return 1; relay_gpio->write(relay_state); while (running) { touch = touch_gpio->read(); if (touch == 1 && last_touch == 0) { relay_state = !relay_state; response = relay_gpio->write(relay_state); usleep(100000); } last_touch = touch; } delete relay_gpio; delete touch_gpio; return response; }
2c721b77c463f9080a249b205f9c6fa39edd9e50
[ "C++" ]
1
C++
sophie-haynes/Starter_Kit_for_96Boards
51772a5484bcaed4d21004300a6102f1deb3fd6b
6a1a781659be5586d27aac42658c363bcfee5a42
refs/heads/master
<file_sep>package co.edkim.seniorcitizen; import android.app.Activity; import android.location.Address; import android.location.Geocoder; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; import java.util.List; import co.edkim.seniorcitizen.model.School; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link SchoolDetailsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link SchoolDetailsFragment#newInstance} factory method to * create an instance of this fragment. */ public class SchoolDetailsFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; // TODO: Rename and change types of parameters private String mParam1; private OnFragmentInteractionListener mListener; private AdView adView; MapFragment map; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @return A new instance of fragment SchoolDetailsFragment. */ // TODO: Rename and change types and number of parameters public static SchoolDetailsFragment newInstance(String param1) { SchoolDetailsFragment fragment = new SchoolDetailsFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); fragment.setArguments(args); return fragment; } public SchoolDetailsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); } } static View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { view = inflater.inflate(R.layout.fragment_school_details, container, false); } catch (Exception e) { e.printStackTrace(); } adView = (AdView) view.findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .addTestDevice("7DDD06BDE922F9125E7B97721D387C5C").build(); // Start loading the ad in the background. adView.loadAd(adRequest); map = (MapFragment) getFragmentManager().findFragmentById(R.id.map); GoogleMap iMap = map.getMap(); School p = SchoolFragment.schoolSet.get(mParam1); TextView textViewName = (TextView) view.findViewById(R.id.textViewName); textViewName.setText(p.FAC_NM); /*TextView textViewAddress = (TextView) view.findViewById(R.id.textViewAddress); textViewAddress.setText(p.address);*/ RatingBar ratingBar = (RatingBar) view.findViewById(R.id.ratingBar); ratingBar.setIsIndicator(true); //ratingBar.setNumStars(); ratingBar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getActivity(), "평가 기능을 준비 중입니다.", Toast.LENGTH_SHORT).show(); } }); TextView textViewContent = (TextView) view.findViewById(R.id.textViewContent); StringBuilder sb = new StringBuilder(); sb.append("구분 : "); sb.append(p.CODE_DESC); sb.append("\n"); sb.append("주소 : "); sb.append(p.FAC_ADDR); sb.append("\n"); if (p.TEL.length() > 0) { sb.append("연락처 : "); sb.append("02-" + p.TEL); sb.append("\n"); } textViewContent.setText(sb.toString()); textViewContent.setLineSpacing(9, 1); Geocoder geocoder = new Geocoder(getActivity()); List<Address> addresses = null; try { addresses = geocoder.getFromLocationName(p.FAC_ADDR, 5); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.size() > 0) { LatLng sLatLng = new LatLng(addresses.get(0).getLatitude(), addresses.get(0).getLongitude()); iMap.addMarker(new MarkerOptions() .position(sLatLng) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))); CameraUpdate center = CameraUpdateFactory.newLatLng(sLatLng); CameraUpdate zoom = CameraUpdateFactory.zoomTo(13); iMap.moveCamera(center); iMap.animateCamera(zoom); } return view; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onDestroyView() { super.onDestroyView(); if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) { parent.removeView(view); } } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } } <file_sep>seniorcitizen =============
205495805c851788ba3d4d5d1a8c2ca1eedfef0c
[ "Markdown", "Java" ]
2
Java
edkimco/seniorcitizen
193fc9275eb00d4e3b982bf3dca227bf40919484
76c87224fde27d30eb5cf0b0476f44aabd11b1a6
refs/heads/main
<file_sep><?php namespace App\Http\Resources\Product; use App\Http\Resources\Seller\SellerResource; use Illuminate\Http\Resources\Json\JsonResource; class ProductResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'price' => $this->price, 'color' => $this->color, 'size' => $this->size, 'stock_quantity' => $this->stock_quantity, 'availability' => $this->availability, 'product_cover' => $this->getMedia('product_cover')->first() ? $this->getMedia('product_cover')->first()->getUrl() : NULL, 'product_gallery' => $this->getMedia('product_gallery') ->map( function( $product_image ) { return $product_image->getUrl(); }), 'edit_route' => route('seller.products.edit', $this->id), 'delete_route' => route('api.products.destroy', $this->id), 'update_route' => route('api.products.update', $this->id), 'seller' => [ 'name' => $this->seller->name, ] ]; } } <file_sep><?php namespace Tests\Feature\Middleware; use Tests\TestCase; use App\Models\Role; use App\Models\User; use Tests\Traits\ActingAsTrait; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class SellerMiddlewareTest extends TestCase { use ActingAsTrait, RefreshDatabase; /** * unauthenticated user cannot access seller routes * * @return void */ public function test_unauthenticated_user_cannot_access_seller_routes() { $this->get(route('seller.products.index'))->assertRedirect(route('login')); } /** * only seller which has credibility can access sellers area * credibility Middleware [ auth, verified, isSeller ] * * @return void */ public function test_seller_can_access_seller_routes() { $this->actingAs($this->acting_as_seller()) ->get(route('seller.products.index')) ->assertOk(); } /** * non seller users cannot access sellers area * * @return void */ public function test_non_seller_users_cannot_access_sellers_area() { $this->actingAs($this->acting_as_admin()) ->get('seller/products') ->assertUnauthorized(); } /** * only verified seller can access seller routes * * @return void */ // public function test_only_verified_seller_can_access_seller_routes() // { // $this->withoutExceptionHandling(); // $this->override_user_data( ['email_verified_at' => ''] ); // $this->actingAs($this->acting_as_seller()) // ->get(route('seller.products.index')) // ->assertRedirect(route('verification.notice')); // } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register Cusotmor routes for the application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "Cusotmor" middleware group. Now create something great! | */ Route::resource('/orders', OrderController::class ); Route::resource('/wishlist', WishlistController::class ); <file_sep><?php namespace App\Jobs; use App\Models\Product; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Contracts\Queue\ShouldBeUnique; class UpdateProductCoverPhotoJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The product instance. * * @var \App\Models\Product */ protected $product; /** * Create a new job instance. * * @return void */ public function __construct(Product $product) { $this->product = $product; } /** * Execute the job. * * @return void */ public function handle() { if( request()->has( 'product_cover' ) ){ $this->product->clearMediaCollection('products'); $this->product->addMediaFromRequest('product_cover')->toMediaCollection('products'); } } } <file_sep><?php namespace App\Traits\Apis; trait AuthApiResponseTrait { public $status_code; public $response_data; public $route; public $api_access_token; public function setApiAccessToken(object $user) { $this->api_access_token = $user->createToken('access-token')->plainTextToken; return $this; } public function credintialsError() { return response()->json( [ 'status' => $this->status_code, 'response' => $this->response_data ], $this->status_code); } public function logedinSuccessfully() { return response()->json( [ 'access_token' => $this->api_access_token, 'status' => $this->status_code, 'route' => $this->route ], $this->status_code); } /** * Set the value of statusCode * * @return self */ public function setStatusCode(int $status_code) { $this->status_code = $status_code; return $this; } /** * Set the value of ResponseData * * @return self */ public function setResponseData(array $response_data) { $this->response_data = $response_data; return $this; } /** * Set the value of route * * @return self */ public function setRoute($route) { $this->route = $route; return $this; } } <file_sep><?php namespace App\Traits\Collection; use Illuminate\Database\Eloquent\Builder; trait MultTitenanable { public static function bootMultTitenanable() { static::addGlobalScope('created_by_user', function (Builder $builder) { $builder->where('created_by_user', auth()->id()); }); } } <file_sep><?php namespace App\QueryFilters\ProductFilters; use Closure; use Illuminate\Support\Str; abstract class Filter { public function handle( $request, Closure $next ) { if( ! request()->has( $this->filterName() ) ){ return $next( $request ); } return $this->applyFilter( $next( $request ) ); } protected function filterName() { return Str::snake( class_basename( $this ) ); } protected abstract function applyFilter( $builder ); } <file_sep><?php namespace Tests\Feature\collections; use Tests\TestCase; use Tests\Traits\ActingAsTrait; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class ActingAsTest extends TestCase { use RefreshDatabase, ActingAsTrait; public function test_acting_as_seller() { $seller = $this->acting_as_seller(); $this->assertRole( 'seller' ); } public function test_acting_as_customer() { $customer = $this->acting_as_customer(); $this->assertRole( 'customer' ); } public function test_acting_as_admin() { $admin = $this->acting_as_admin(); $this->assertRole( 'admin' ); } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register Admin routes for the application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "Admin" middleware group. Now create something great! | */ Route::resource('/statistics', StatisticController::class ); Route::resource('/categories', CategoryController::class ); Route::resource('/tags', TagController::class ); Route::resource('/posts', PostController::class ); <file_sep>import Api from "./Api"; export default { logout() { return Api().post("/logout").then( res => { localStorage.removeItem('access_token'); } ); } }; <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Category extends Model { use HasFactory; /** * Get all of the posts that are assigned this tag. */ public function products() { return $this->morphedByMany(Product::class, 'categorables'); } /** * Get the parent commentable model (post or video). */ // public function categorable() // { // return $this->morphTo(); // } } <file_sep><?php namespace App\Models; use Spatie\Image\Manipulations; use Illuminate\Pipeline\Pipeline; use Spatie\MediaLibrary\HasMedia; use App\Observers\ProductObserver; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use App\Traits\Collection\MultTitenanable; use Spatie\MediaLibrary\InteractsWithMedia; use Illuminate\Database\Eloquent\SoftDeletes; use Spatie\MediaLibrary\HasMedia\HasMediaTrait; use Illuminate\Database\Eloquent\Factories\HasFactory; use Spatie\MediaLibrary\MediaCollections\Models\Media; class Product extends Model implements HasMedia { use HasFactory, SoftDeletes, MultTitenanable, InteractsWithMedia; // Spatie\Image\ /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ "name", "created_by_user", 'price', "color", "size", "stock_quantity", "availability" ]; protected $appends = [ 'photo' ]; /** * The event map for the model. * * @var array */ protected $dispatchesEvents = [ 'saved' => ProductObserver::class, ]; /** * The relationships that should always be loaded. * * @var array */ protected $with = ['media', 'categories', 'sales' ]; /** * Get all of the Salles for the Product. */ public function sales() { return $this->hasMany(Sale::class, 'product_id'); } /** * Get all of the tags for the post. */ public function categories() { return $this->morphToMany(Category::class, 'categorables'); } public function categoriesName() { return $this->categories->implode('name', ', '); } /** * Get all of the tags for the post. */ public function categoriesIDS() { return $this->categories->pluck('id')->toArray(); } /** * Get all of the tags for the post. */ public function category( $category_id ) { return $this->categories->where('category_id', $category_id ); } /** * Add Product Cover sizes [ 50x50, 150x150, 300x300, 600x600 ] * */ public function registerMediaConversions(Media $media = null): void { $this->addMediaConversion('thumb-50x50') ->width(50) ->height(50); $this->addMediaConversion('medium-150x150') ->width(150) ->height(150); $this->addMediaConversion('medium-300x300') ->width(150) ->height(150); $this->addMediaConversion('medium-600x600') ->width(600) ->height(600); } public function getPhotoAttribute() { $file = $this->getMedia('products')->last(); if( $file ){ $file->cover = $file->getUrl(); $file->thumb = $file->getUrl('thumb-50x50'); $file->preview = $file->getUrl('medium-150x150'); $file->main = $file->getUrl('medium-300x300'); // $file->cover = $file->getUrl('medium-600x600'); } return $file; } public static function addPrductCoverMedia( $product ) { $product->addMediaFromRequest('product_cover')->toMediaCollection('products'); } /** * Get the User that owns the Product. */ public function seller() { return $this->belongsTo(Seller::class, 'created_by_user'); } /** * Scope a query to only include availabile Products. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeAvailableOnly($query, bool $availabile = true) { return $query->where('availability', true ); } /** * Scope a query to only include availabile Products. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeOrderByStockQuantity($query) { return $query->orderBy( 'stock_quantity', 'desc' ); } /** * Get the Product availability status * * @param string $value * @return string */ public function isAvailabile() { return $this->availability === 'Available' ?? false; } /** * Get the Product availability status * * @param string $value * @return string */ public function getAvailabilityAttribute($value) { return $value ? 'Available' : 'Not Availabile'; } public static function withFilteration() { return app( Pipeline::class ) ->send( Product::query() ) ->through( [ \App\QueryFilters\ProductFilters\Availability::class, \App\QueryFilters\ProductFilters\Category::class, \App\QueryFilters\ProductFilters\Sales::class, \App\QueryFilters\ProductFilters\Trahsed::class, ]) ->thenReturn() ->paginate( (int) request( 'limit' )) ->withQueryString(); } } <file_sep><?php namespace App\QueryFilters\ProductFilters; class Category extends Filter { protected function applyFilter( $builder ) { return $builder->Join('categorables', 'products.id', '=', 'categorables.categorables_id') ->join('categories', function ($join) { if ( request( $this->filterName() ) != 'all' ){ $join->on('categories.id', '=', 'categorables.category_id') ->where('categorables.category_id', '=', request( $this->filterName() ) ); }else{ $join->on('categories.id', '=', 'categorables.category_id'); } }) ->select('products.*') ->groupBy('products.id'); } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register Seller routes for the application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "seller" middleware group. Now create something great! | */ Route::post('/products/trash/bulk', [ \App\Http\Controllers\Seller\ProductController::class , 'trashBulk' ] )->name('products.trash.bulk'); Route::post('/products/trash/restore', [ \App\Http\Controllers\Seller\ProductController::class , 'trashRestore' ] )->name('products.trash.restore'); Route::post('/products/destroy/all', [ \App\Http\Controllers\Seller\ProductController::class , 'destroyAll' ] )->name('products.destroy.all'); Route::get('/products/filter', [ \App\Http\Controllers\Seller\ProductController::class , 'filter' ] )->name('products.filter'); Route::resource('/products', ProductController::class ); Route::resource('/statistics', StatisticController::class ); <file_sep><?php namespace Database\Factories; use App\Models\User; use App\Models\Product; use Illuminate\Database\Eloquent\Factories\Factory; class ProductFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Product::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => $this->faker->unique()->name, 'price' => rand(100,700), 'color' => $this->faker->randomElement(['orange,red,blue','orange,red','blue,red']), 'size' => $this->faker->randomElement(['sm,lg','lg,md','md,xl','lg,xl,xxl','md,xl,xxl']), 'stock_quantity' => $this->faker->randomElement([10,20,30,40]), 'availability' => $this->faker->randomElement([1,0]), 'created_by_user' => User::where('name' , 'LIKE', '%seller%')->get()->random(1)->pluck('id')->first() ]; } } <file_sep><?php namespace App\Models; class Customer extends User { } <file_sep><?php namespace App\Http\Controllers\Seller; use Excption; use App\Models\Seller; use App\Models\Product; use App\Models\Category; use Illuminate\Http\Request; use Illuminate\Pipeline\Pipeline; use Illuminate\Support\Collection; use App\Exceptions\NotProductOwner; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use App\Http\Resources\Product\ProductCollection; use App\QueryFilters\ProductFilters\Availability; use App\Http\Requests\Seller\CreateProductRequest; use App\Http\Requests\Seller\UpdateProductRequest; class ProductController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view( 'dashboard.product.index', [ 'products' => Product::availableOnly() ->orderByStockQuantity() // ->get() ->paginate(20) ->withQueryString() ] ); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view( 'dashboard.product.create' ); } /** * Store a newly created resource in storage. * * @param App\Http\Requests\Seller\CreateProductRequest $request * @return \Illuminate\Http\Response */ public function store(CreateProductRequest $request) { \DB::transaction(function () use($request) { $product = auth()->user()->products()->create( $request->validated() ); $product->addMediaFromRequest('image')->toMediaCollection('products'); }); return redirect(route('seller.products.index')) ->with( 'success', 'Product Created Successfully' ); } /** * Display the specified resource. * * @param \App\Models\Seller $seller * @return \Illuminate\Http\Response */ public function show(Seller $seller) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Product $seller * @return \Illuminate\Http\Response Product */ public function edit($product) { if( ! $product = Product::find($product) ){ throw new NotProductOwner; } return view( 'dashboard.product.update', [ 'product' => $product ] ); } /** * Update the specified resource in storage. * * @param App\Http\Requests\Seller\UpdateProductRequest $request * @param \App\Models\Seller $seller * @return \Illuminate\Http\Response */ public function update(UpdateProductRequest $request, Product $product) { // dd( $request->validated() ); $product->update( $request->validated() + [ 'create_by_user' => auth()->user() ] ); return redirect(route('seller.products.index')) ->with( 'success', 'Product '.$product->name.' Updated Successfully' ); } /** * Remove the specified resource from storage. * * @param \App\Models\Seller $seller * @return \Illuminate\Http\Response */ public function destroy(Product $product) { \DB::transaction(function () use($product) { $product->sales()->delete(); $product->clearMediaCollection('products'); $product->forceDelete(); }); session()->flash( 'success', 'Product '.$product->name.' Deleted Successfully' ); return redirect()->back(); } public function filter() { return view( 'dashboard.product.index', [ 'products' => Product::withFilteration() ] ); } public function trashBulk(Request $request) { Product::whereIn( 'id', $request->products_bluk )->each(function ($product, $key) { $product->delete(); }); session()->flash( 'Products Trashed Successfully' ); return redirect()->back(); } public function trashRestore(Request $request) { Product::onlyTrashed() ->whereIn( 'id', $request->products_bluk ) ->each(function ($product, $key) { $product->restore(); }); session()->flash( 'Products Restored Successfully' ); return redirect()->back(); } public function destroyAll(Request $request) { Product::whereIn( 'id', $request->products_bluk )->each(function ($product, $key) { DB::transaction(function () { $product->clearMediaCollection('products'); $product->categories()->detach(); $product->forceDelete(); }); }); session()->flash( 'Products Deleted Successfully' ); return redirect()->back(); } } <file_sep><?php namespace App\Http\Controllers\Auth; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\Providers\RouteServiceProvider; use App\Http\Requests\Auth\LoginRequest; use App\Traits\Apis\AuthApiResponseTrait; class AuthenticatedSessionController extends Controller { use AuthApiResponseTrait; /** * Display the login view. * * @return \Illuminate\View\View */ public function create() { return view('auth.login'); } /** * Handle an incoming authentication request. * * @param \App\Http\Requests\Auth\LoginRequest $request * @return \Illuminate\Http\RedirectResponse */ public function store(LoginRequest $request) { $request->authenticate(); $request->session()->regenerate(); return $this->authenticated($request, $this->guard()->user()); } /** * Destroy an authenticated session. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse */ public function destroy(Request $request) { Auth::guard('web')->logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); return redirect('/'); } /** * The user has been authenticated. * * @param \Illuminate\Http\Request $request * @param mixed $user * @return mixed */ private function authenticated(Request $request, $user) { if( $user->canAccessSpecificArea([ 'seller' ]) ) { return $this->setStatusCode(200) ->setRoute(route('seller.products.index')) ->setApiAccessToken($user) ->logedinSuccessfully(); } return $this->setStatusCode(200) ->setRoute(route('home')) ->setApiAccessToken($user) ->logedinSuccessfully(); } /** * Get the guard to be used during authentication. * * @return \Illuminate\Contracts\Auth\StatefulGuard */ protected function guard() { return Auth::guard(); } } <file_sep><?php namespace Database\Seeders; use App\Models\Sale; use App\Models\Product; use Illuminate\Database\Seeder; use Illuminate\Support\Collection; class SaleSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $products = ( new Product )->find(100); // // $products = ( new Product )->categories()->whereNull('categorables.categorables_id')->count(); // // return $this->roles()->whereIn( 'name' , $list_of_roles )->count(); $products = \DB::table('products') ->leftJoin('categorables', 'products.id', '=', 'categorables.categorables_id') ->leftJoin('sales', 'products.id', '=', 'sales.product_id') ->whereNull('categorables.categorables_id') ->select('products.*', \DB::raw('COUNT( sales.product_id ) as sales_count')) ->groupBy('products.id') ->havingRaw('COUNT( sales.product_id ) = 0') ->get(); $products->map( function($product){ dd( Product::where( 'id', $product->id )->get() ); dd( $product->id ); }); $categories = \DB::table('categories')->get()->random( 2 )->pluck('id')->toArray(); // Sale::factory() // ->count(500) // ->create(); } } <file_sep><?php namespace App\QueryFilters\ProductFilters; class Trahsed extends Filter { protected function applyFilter( $builder ) { return $builder->onlyTrashed(); } } <file_sep><?php namespace App\QueryFilters\ProductFilters; use Illuminate\Support\Str; class Sales extends Filter { protected function applyFilter( $builder ) { $request = Str::camel( request( 'sales' ) ); return $this->$request($builder); } protected function onlyHasSales($builder) { return $builder->leftJoin('sales', 'products.id', '=', 'sales.product_id') ->select('products.*') ->groupBy('products.id') ->havingRaw('COUNT( sales.product_id ) > 0') ->orderByRaw( 'COUNT( sales.product_id ) desc' ); } protected function hasNoSales($builder) { return $builder->leftJoin('sales', 'products.id', '=', 'sales.product_id') ->select('products.*') ->groupBy('products.id') ->havingRaw('COUNT( sales.product_id ) = 0'); } } <file_sep><?php namespace App\Traits\Apis; trait ApiResponseGenratorTrait { public $status_code; public function createdMsg(string $success_msg) { return response()->json( [ 'msg'=> $success_msg ], $this->status_code ); } public function created(array $data) { return response()->json( [ 'data'=> $data ], $this->status_code ); } public function retrievData($data) { return response()->json( [ 'status' => $this->status_code, 'data'=> $data], $this->status_code ); } protected function statusCode(int $status_code) { $this->status_code = $status_code; return $this; } } <file_sep><?php namespace App\Traits\Users; use App\Models\Role; use App\Models\Product; trait UserRolesTrait { public function roles() { return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id'); } public function canAccessSpecificArea( array $list_of_roles ) { return $this->roles()->whereIn( 'name' , $list_of_roles )->count(); } /** * Get all of the Products for the Seller. */ public function products() { return $this->hasMany(Product::class, 'created_by_user'); } } <file_sep>import Api from "../api"; export default form => { return Api().post("/login", form); }; <file_sep><?php namespace App\Models; class Admin extends User { } <file_sep><?php namespace App\QueryFilters\ProductFilters; use Closure; class Availability extends Filter { protected function applyFilter( $builder ) { return $builder->where( $this->filterName() , request( $this->filterName() ) ); } } <file_sep><?php namespace Tests\Traits; use App\Models\Role; use App\Models\User; trait ActingAsTrait { private $override_data; public function acting_as_admin() { return $this->acting_as( 'admin' ); } public function acting_as_customer() { return $this->acting_as( 'customer' ); } public function acting_as_seller() { return $this->acting_as( 'seller' ); } private function override_user_data( array $override_data = [] ) { $this->override_data = $override_data; } private function acting_as( $role_name ) { $user = User::factory()->create($this->override_data); $role = Role::factory()->create([ 'name' => $role_name, ]); $user->roles()->attach( $role->id ); return $user; } private function assertRole( $role_name ) { $this->assertDatabaseHas('roles', [ 'name' => $role_name, ]); } } <file_sep><?php namespace Database\Factories; use App\Models\Sale; use Illuminate\Database\Eloquent\Factories\Factory; class AddSalesFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Sale::class; /** * Define the model's default state. * * @return array */ public function definition() { $user = \DB::table('users') ->where('name', 'LIKE', "%seller%" ) ->inRandomOrder() ->first(); $product = \DB::table('products') ->where('created_by_user', $user->id ) ->where('availability', 1 ) ->inRandomOrder() ->first(); return [ 'product_id' => $product->id, 'sale_price' => $product->price, 'was_on_sale' => $this->faker->randomElement([1,0]), ]; } } <file_sep><?php namespace Tests\Feature\Product; use Tests\TestCase; use App\Models\Product; use Tests\Traits\ActingAsTrait; use Illuminate\Foundation\Testing\WithFaker; use App\Traits\Apis\ApiResponseGenratorTrait; use App\Http\Resources\Product\ProductResource; use Illuminate\Foundation\Testing\RefreshDatabase; class ProductTest extends TestCase { use ActingAsTrait,ApiResponseGenratorTrait, RefreshDatabase; private $product_data; private $errors_msg; private $http_status_code = 422; /** * cannot create product with out providing a name * * @return void */ public function test_product_name_is_required() { $this->overrideProductData( [ 'name' => '' ] ) ->errorMsgs( ) ->createProduct(); } /** * cannot create product with out providing a color * * @return void */ public function test_product_color_is_required() { $this->overrideProductData( [ 'color' => '' ] ) ->errorMsgs( [ "color" => [ "Product Color is Missing" ] ] ) ->createProduct(); } /** * cannot create product with out providing a size * * @return void */ public function test_product_size_is_required() { $this->overrideProductData( [ 'size' => '' ] ) ->errorMsgs( [ "size" => [ "Product Size is Missing" ] ] ) ->createProduct(); } /** * cannot create product with out providing a stock quantity * * @return void */ public function test_product_stock_quantity_is_required() { $this->overrideProductData( [ 'stock_quantity' => '' ] ) ->errorMsgs( [ "stock_quantity" => [ "Stock Quantity is Missing" ] ] ) ->createProduct(); } /** * cannot create product with out providing a availability * * @return void */ public function test_product_availability_is_required() { $this->overrideProductData( [ 'availability' => '' ] ) ->errorMsgs( [ "availability" => [ "Product availability is Missing" ] ] ) ->createProduct(); } public function test_return_seller_products() { $this->withoutExceptionHandling(); $seller = $this->createSellerMultipleProducts(); $this->json( 'GET', route('api.products.index') )->assertJson( [ 'data'=> $seller->products()->get()->toArray() ], 200 )->assertOk(); } private function overrideProductData( array $override_current_data = [] ) { $this->product_data = array_merge( [ 'name' => 'new product name', 'color' => 'orange,red,blue', 'size' => 'sm,lg,md', 'stock_quantity' => 10, 'availability' => true ], $override_current_data ); return $this; } private function errorMsgs( array $errors = [] ) { $this->errors_msg = [ "message" => "The given data was invalid.", "errors" => $errors ]; return $this; } private function createProduct() { $response = $this->postJson(route('api.products.store'), $this->product_data ); $response ->assertStatus($this->http_status_code) ->assertJson( $this->errors_msg ); } public function createSellerMultipleProducts() { // acting as seller $seller = $this->acting_as_seller(); $this->actingAs($seller); // Store many prodcut ProductResource::collection(Product::factory()->count(3)->make()) ->map(function ($product) use( $seller ) { $this->actingAs($seller); $response = $this->postJson(route('api.products.store'), [ "name" => $product->name, "color" => $product->color, "size" => $product->size, "stock_quantity" => $product->stock_quantity, "availability" => $product->availability ]); $response ->assertStatus(201) ->assertJson( [ 'msg' => "New Product Created successfully!" ] ); }); return $seller; } } <file_sep><?php namespace App\Models; class Seller extends User { // protected $with = [ 'products' ]; } <file_sep><?php namespace App\Observers; use App\Models\Product; use Illuminate\Http\Request; use App\Jobs\UpdateProductCoverPhotoJob; class ProductObserver { /** * Handle the Product "created" event. * * @param \App\Models\Product $product * @return void */ public function created(Product $product) { $product->categories()->sync( request()->categories ); } /** * Handle the Product "creating" event. * * @param \App\Models\Product $product * @return void */ public function creating(Product $product) { // } /** * Handle the Product "updated" event. * * @param \App\Models\Product $product * @return void */ public function updated(Product $product) { $product->categories()->sync( request()->categories ); } /** * Handle the Product after "updated" event. * * @param \App\Models\Product $product * @return void */ public function saved(Product $product) { $product->categories()->sync( request()->categories ); dispatch(new UpdateProductCoverPhotoJob($product) ); } /** * Handle the Product "deleted" event. * * @param \App\Models\Product $product * @return void */ public function deleted(Product $product) { // } /** * Handle the Product "restored" event. * * @param \App\Models\Product $product * @return void */ public function restored(Product $product) { // } /** * Handle the Product "force deleted" event. * * @param \App\Models\Product $product * @return void */ public function forceDeleted(Product $product) { // } } <file_sep><?php namespace Database\Factories; use App\Models\Sale; use App\Models\Product; use Illuminate\Support\Str; use Illuminate\Database\Eloquent\Factories\Factory; class SaleFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Sale::class; /** * Define the model's default state. * * @return array */ public function definition() { $product = Product::all()->random(1); return [ 'product_id' => $product->pluck('id')->first(), 'sale_price' => $product->pluck('price')->first(), 'was_on_sale' => $this->faker->randomElement([1,0]), 'created_at' => $this->faker->dateTimeBetween($startDate = '-5 month', $endDate = 'now', $timezone = null) ]; } } <file_sep><?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::post( '/products/upload/{product}' , [ App\Http\Controllers\Api\v1\ProductController::class, 'upload' ] ) ->name('api.products.images.upload'); Route::apiResource('/products', ProductController::class); // Route::get('/products/{productId}', [App\Http\Controllers\Api\v1\ProductController::class, 'singleProduct'])->name('products.single'); <file_sep><?php namespace Tests\Feature\Seller; use Tests\TestCase; use Tests\Traits\ActingAsTrait; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class SellerTest extends TestCase { use ActingAsTrait, RefreshDatabase; /** * Seller can create product * */ public function test_seller_can_create_new_product() { $this->withoutExceptionHandling(); $this->actingAs($this->acting_as_seller()); $response = $this->postJson(route('api.products.store'), [ 'name' => 'new product name', 'color' => 'orange,red,blue', 'size' => 'sm,lg,md', 'stock_quantity' => 10, 'availability' => true ]); $response ->assertStatus(201) ->assertJson([ "msg" => "New Product Created successfully!" ]); } } <file_sep><?php namespace App\Http\Requests\Seller; use Illuminate\Foundation\Http\FormRequest; class UpdateProductRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => [ 'required', "unique:products,name,$this->id", 'max:255' ], 'price' => [ 'required', 'numeric' ,'regex:/^\d*(\.\d{2})?$/' ], 'color' => [ 'required' ], 'size' => [ 'required' ], 'stock_quantity' => [ 'required', 'integer' ], 'availability' => [ 'boolean' ], 'product_cover' => [ 'sometimes', 'image', 'mimes:png,jpg', 'max:2000' ], 'categories' => [ 'required' ], ]; } public function messages() { return [ 'name.required' => 'Product Name is Missing', 'name.unique' => 'Product Already Exists', 'name.max' => 'Product Name must be 255 Charcters max', 'price.required' => 'Product Price is Missing', 'price.numeric' => 'Silly You :(', 'color.required' => 'Product Color is Missing', 'size.required' => 'Product Size is Missing', 'stock_quantity.required' => 'Stock Quantity is Missing', 'stock_quantity.integer' => 'Stock Quantity Must be Integer', 'availability.required' => 'Product availability is Missing', 'availability.boolean' => 'Silly You :(', 'product_cover.required' => 'Product Cover is Missing', 'product_cover.image' => 'Product Cover must be Image', 'product_cover.mimes' => 'Product Cover must be png|jpg', 'product_cover.max' => 'Product Cover size must be max 2000 MB', ]; } } <file_sep><?php namespace App\Http\Controllers\Api\v1; use App\Models\Seller; use App\Models\Product; use Illuminate\Http\Request; use App\Models\TemporaryFiles; use Illuminate\Support\Collection; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; use App\Traits\Apis\ApiResponseGenratorTrait; use App\Http\Resources\Product\ProductResource; use App\Http\Resources\Product\ProductCollection; use App\Http\Requests\APi\Products\CreateProductRequest; class ProductController extends Controller { use ApiResponseGenratorTrait; /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Product $product) { return $this->statusCode(200) ->retrievData( new ProductCollection(Product::with('seller')->available()->paginate(15))); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CreateProductRequest $request) { $request->user()->products()->create($request->validated()); return $this->statusCode(201)->createdMsg("New Product Created successfully!"); } /** * Display the specified resource. * * @param \App\Models\Product * @return \Illuminate\Http\Response */ public function show(Product $product) { return $this->statusCode(200) ->retrievData( new ProductResource($product) ); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function update(Request $request, Product $product) { // $this->validateRequest($product); // $product->update( $this->credentials() + [ 'create_by_user' => auth()->user() ] ); if( ! empty( $request->product_cover ) ){ $this->storeProductCover($product); } if( ! empty( $request->product_gallery ) ){ $this->storeProductGallery($product); } return $this->statusCode(200) ->created([ 'msg' => 'Product Updated Successfully!', 'route' => route('seller.products.index') ] ); } /** * Remove the specified resource from storage. * * @param \App\Models\Product $product * @return \Illuminate\Http\Response */ public function destroy(Product $product) { return $this->statusCode(200)->createdMsg("Product Deleted successfully!"); } /** * Upldoad Product Images to temporary Dir * @return temporary dir name */ public function upload(Request $request, Product $product) { if( $request->hasFile('product_gallery') ) { return $this->uploadProductGallery($product); } if( $request->hasFile('product_cover') ) { return $this->uploadProductCover(); } return ''; } private function storeProductCover($product) { $files_dir_name = TemporaryFiles::where( 'files_dir' , request()->product_cover )->first(); if( $files_dir_name ){ $tmp_path = storage_path( 'app/tmp/products/' . request()->product_cover . '/' . $files_dir_name->file ); $product->addMedia( $tmp_path )->toMediaCollection('product_cover'); rmdir( storage_path( 'app/tmp/products/' . request()->product_cover) ); $files_dir_name->delete(); } } private function storeProductGallery($product) { $files = TemporaryFiles::where( 'files_dir' , request()->product_gallery )->get(); // dd($files); if( $files ){ $files->map( function( $file ) use($product) { $tmp_path = storage_path( 'app/tmp/products/' . request()->product_gallery . '/' . $file->file ); $product->addMedia( $tmp_path )->toMediaCollection('product_gallery'); $file->delete(); }); rmdir( storage_path( 'app/tmp/products/' . request()->product_gallery) ); } } private function uploadProductCover() { $this->validateImage(); $file = request()->file('product_cover'); $files_tmp_dir_name = uniqid() .'-'. now()->timestamp; $file_name = $file->getClientOriginalName(); $file->storeAs( 'tmp/products/' . $files_tmp_dir_name, $file_name ); TemporaryFiles::create( [ 'files_dir' => $files_tmp_dir_name, 'file' => $file_name, ]); return $files_tmp_dir_name; } private function uploadProductGallery(Product $product) { // Validate each Image $images = request()->file('product_gallery'); dd($product); // Convert into Collection $files = Collection::wrap( request()->file('product_gallery') ); $file_name = $file->getClientOriginalName(); $file->storeAs( 'tmp/products/', $file_name ); TemporaryFiles::create( [ // 'files_dir' => $files_tmp_dir_name, 'file' => $file_name, 'collection' => 'product_gallery', 'model_id' => $product->id, ]); // Map & store each into one tmp dir // $files->each( function( $file ) use( $files_tmp_dir_name ) { // $file_name = $file->getClientOriginalName(); // $file->storeAs( 'tmp/products/' . $files_tmp_dir_name, $file_name ); // TemporaryFiles::create( [ // 'files_dir' => $files_tmp_dir_name, // 'file' => $file_name, // ]); // }); // return $files_tmp_dir_name; } public function validateRequest($product) { Validator::make( $this->credentials(), $this->rules($product), $this->messages() )->validate(); } private function credentials() { return request()->only([ 'name', 'price', 'color', 'size', 'stock_quantity', 'availability' ]); } private function rules($product) { return [ 'name' => [ 'required', "unique:products,name,$product->id", 'max:255' ], 'price' => [ 'required', 'numeric' ,'regex:/^\d*(\.\d{2})?$/' ], 'color' => [ 'required' ], 'size' => [ 'required' ], 'stock_quantity' => [ 'required', 'integer' ], 'availability' => [ 'required', 'boolean' ] ]; } private function messages() { return [ 'name.required' => 'Product Name is Missing', 'name.unique' => 'Product Already Exists', 'name.max' => 'Product Name must be 255 Charcters max', 'price.required' => 'Product Price is Missing', 'price.numeric' => 'Silly You :(', 'color.required' => 'Product Color is Missing', 'size.required' => 'Product Size is Missing', 'stock_quantity.required' => 'Stock Quantity is Missing', 'stock_quantity.integer' => 'Stock Quantity Must be Integer', 'availability.required' => 'Product availability is Missing', 'availability.boolean' => 'Silly You :(' ]; } private function validateImage() { Validator::make(request()->only('product_cover') ,[ 'product_cover' => [ 'required', 'image', 'mimes:png,jpg', 'max:2000' ], ], [ 'product_images.required' => 'Product Image is Missing', 'product_images.image' => 'Product Image must be Image', 'product_images.mimes' => 'Product Image must be png|jpg', 'product_images.max' => 'Product Image size must be max 2000 MB', ] )->validate(); } } <file_sep><?php namespace Database\Seeders; use App\Models\Role; use App\Models\User; use Illuminate\Database\Seeder; class RoleUserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $roles = Role::where('name' , 'seller')->get(); User::where('name' , 'LIKE', '%seller%')->each( function( $user ) use( $roles ) { $user->roles()->attach($roles->random(1)->pluck('id')); }); } } <file_sep><?php use App\Models\Product; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function() { $products = \DB::table('products') ->leftJoin('categorables', 'products.id', '=', 'categorables.categorables_id') ->leftJoin('sales', 'products.id', '=', 'sales.product_id') ->whereNull('categorables.categorables_id') ->select('products.*', \DB::raw('COUNT( sales.product_id ) as sales_count')) ->groupBy('products.id') ->havingRaw('COUNT( sales.product_id ) = 0') ->first(); // dd( $products ); $products->map( function($product){ dd( Product::where( 'id', $product->id )->get() ); print_r( $product->id ); }); $categories = \DB::table('categories')->get()->random( 2 )->pluck('id')->toArray(); // return view('welcome'); })->name('home'); require __DIR__.'/auth.php';
5c09785f8575ec787ece87f0bd0fa5fc284bc772
[ "JavaScript", "PHP" ]
38
PHP
ahmed1322/ecommerce-laravel-vuejs
e1287b72a80fa74aa4f6e2e2a8a8afc1c80b6fb1
7192cf2e02dd8f61536c660046e5b7bd53306586
HEAD
<repo_name>blackcell000/test<file_sep>/readme.txt This is a simple practise hello world
c56738e8c8276de8388df7f1c26507f415317a00
[ "Text" ]
1
Text
blackcell000/test
64d301017ad050034f35c4ebfe070266be3c23ed
ef938d331e025d793e0fb680aadf4f5d3d5e84cd
refs/heads/master
<file_sep># source from dmd-czech dtvt plugin - https://code.google.com/p/dmd-xbmc/source/detail?r=206 # modded by mx3L for easy port to enigma2 archivczsk plugin import calendar import cookielib import re import urllib import urllib2 import HTMLParser import xml.etree.ElementTree as ET import email.utils as eut import time import os,datetime import simplejson as json import util from Components.config import config from provider import ContentProvider _htmlParser_ = HTMLParser.HTMLParser() _rssUrl_ = 'http://video.aktualne.cz/rss/dvtv/' class dvtvlog(object): ERROR = 0 INFO = 1 DEBUG = 2 mode = INFO logEnabled = True logDebugEnabled = False LOG_FILE = "" @staticmethod def logDebug(msg): if dvtvlog.logDebugEnabled: dvtvlog.writeLog(msg, 'DEBUG') @staticmethod def logInfo(msg): dvtvlog.writeLog(msg, 'INFO') @staticmethod def logError(msg): dvtvlog.writeLog(msg, 'ERROR') @staticmethod def writeLog(msg, type): try: if not dvtvlog.logEnabled: return # if log.LOG_FILE=="": dvtvlog.LOG_FILE = os.path.join(config.plugins.archivCZSK.logPath.getValue(), 'dvtv.log') f = open(dvtvlog.LOG_FILE, 'a') dtn = datetime.datetime.now() f.write(dtn.strftime("%d.%m.%Y %H:%M:%S.%f")[:-3] + " [" + type + "] %s\n" % msg + '') f.close() except: print "####DVTV#### write log failed!!!" pass finally: print "####DVTV#### [" + type + "] " + msg class DVTVContentProvider(ContentProvider): def __init__(self, username=None, password=<PASSWORD>, filter=None, tmp_dir='/tmp'): ContentProvider.__init__(self, 'dvtv.cz', 'http://video.aktualne.cz/dvtv/', username, password, filter, tmp_dir) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar())) urllib2.install_opener(opener) def capabilities(self): return ['categories','resolve'] def categories(self): return self.list("0") def list(self, offset): result = [] url = _rssUrl_ offset = int(offset) if offset > 0: url+="?offset=%d"%(offset) rss = util.request(url) root = ET.fromstring(rss) for item in root.find('channel').findall('item'): link = item.find('link').text title = item.find('title').text description = item.find('description').text contentEncoded = item.find('{http://purl.org/rss/1.0/modules/content/}encoded').text extra = item.find('{http://i0.cz/bbx/rss/}extra') subtype = extra.get('subtype') dur = extra.get('duration') datetime = eut.parsedate(item.find('pubDate').text.strip()) date = time.strftime('%d.%m.%Y', datetime) image = re.compile('<img.+?src="([^"]*?)"').search(contentEncoded).group(1) vitem = self.video_item() vitem['title'] = title if dur: d = re.compile('([0-9]?[0-9]):([0-9][0-9])').search(dur.strip()) duration = (int(d.group(1))*60+int(d.group(2))) vitem['duration'] = duration if subtype == 'playlist': pass vitem['img'] = image vitem['plot'] = description vitem['url'] = link self._filter(result, vitem) nitem = self.dir_item() nitem['type'] = 'next' nitem['url'] = str(offset+30) self._filter(result, nitem) return result def resolve(self, item, captcha_cb=None, select_cb=None): result = [] twice = False item = item.copy() httpdata = util.request(item['url']) videos = re.compile('tracks:(?:.(?!\}\]\}))*.\}\]\}', re.S).findall(httpdata) if len(videos) > 1: # last item in playlist is doubled on page del videos[-1] if videos: title = re.compile('<meta property="og:title" content=".*">').search(httpdata).group(0) title = re.sub('<meta property="og:title" content="', '', title).replace('">', '') image = re.compile('<meta property="og:image" content=".*">').search(httpdata).group(0) image = re.sub('<meta property="og:image" content="', '', image).replace('">', '') description = re.compile('<meta property="og:description" content=".*">').search(httpdata).group(0) description = re.sub('<meta property="og:description" content="', '', description).replace('">', '') for video in videos: video = re.sub(re.compile('\sadverttime:.*', re.S), '', video) # live streams workaround video = video.replace('tracks: ', '') video = re.sub(r'[,\w]*$', '', video) detail = json.loads(video) if detail.has_key('MP4'): sources = detail['MP4'] for version in sources: url = version['src'] quality = version['label'] vitem = self.video_item() vitem['title'] = title vitem['surl'] = str(len(title)) vitem['img'] = image vitem['url'] = url vitem['quality'] = quality result.append(vitem) result.sort(key=lambda x:(len(x['quality']), x['quality']), reverse=True) if len(result) > 0 and select_cb: return select_cb(result) return result <file_sep>#!/bin/bash set -e set -x ./release.sh git commit -m 'release' git rev-parse HEAD > commit git add commit git commit -m 'set commit to current release'
6b43be2c70bf797c992d84194f48fe0eb663f876
[ "Python", "Shell" ]
2
Python
brkulin/archivczsk-doplnky
49b2d245123f25fa0f6057448356640074ddb3b7
b6390e36646a5fecac0c1c0aed18a8b07fe9af31
refs/heads/master
<file_sep>#ifndef DRAFT_2_RESULT_TYPE_H #define DRAFT_2_RESULT_TYPE_H #include <vector> #include "Cell.h" using namespace std; template<typename T> class Result_Type { public: T total_cost; vector<Cell> m_path; vector<vector<bool>> m_explored; double exec_time; long long expanded_cells_count; Result_Type() { total_cost = -1; exec_time = -1; } Result_Type(T total_cost, vector<Cell> path, vector<vector<bool>> explored, double exec_time, long long cells_expanded) : total_cost(total_cost), exec_time(exec_time), expanded_cells_count(cells_expanded) { m_path = path; m_explored = explored; } }; #endif //DRAFT_2_RESULT_TYPE_H <file_sep>#include <iostream> #include <map> #include "Input_Type.h" #include "Algo.h" #include "Result_Type.h" #include "Printer.h" using namespace std; struct Efficiency_Data { string field_type; bool path_found; bool uniform_weights; pair<int, int> field_size; pair<double, double> time; pair<long long, long long> expanded_cells_count; Efficiency_Data() = default; }; ostream& operator<<(ostream& out, const Efficiency_Data& data) { out << data.field_type << "\t"; out << data.uniform_weights << "\t"; out << data.path_found << "\t"; out << data.field_size.first << "\t" << data.field_size.second << "\t"; out << data.time.first << "\t" << data.time.second << "\t"; out << data.expanded_cells_count.first << "\t" << data.expanded_cells_count.second << endl; } void make_user_input(const bool is_uniform, const string& field_type, const pair<int, int> size_range) { ofstream test_out("input.txt"); int n, m; n = size_range.first + rand() % size_range.second; m = size_range.first + rand() % size_range.second; test_out << n << " " << m << "\n"; int start_x, start_y, finish_x, finish_y; start_x = rand() % n, start_y = rand() % m; finish_x = rand() % n, finish_y = rand() % m; test_out << start_x << " " << start_y << "\n"; test_out << finish_x << " " << finish_y << "\n"; test_out << "no\n"; // is manual input int max_weight; if (is_uniform) { max_weight = 1; } else { max_weight = 2 + rand() % 1000; } test_out << max_weight << "\n"; test_out << field_type << "\n"; int max_congestion_rate_percent; if (field_type == "snakes") { max_congestion_rate_percent = 20; } else if (field_type == "rooms") { max_congestion_rate_percent = 30; } else { max_congestion_rate_percent = 60; } double congestion_rate = (rand() % max_congestion_rate_percent) / 100.; test_out << congestion_rate << "\n"; string heuristic_key = "mnh"; test_out << heuristic_key << "\n"; string optimization = "-"; test_out << optimization << endl; } void gather_data(const Input_Type<int>& input, const Result_Type<int>& res_A_star, const Result_Type<int>& res_Dijkstra, vector<Efficiency_Data>& gathered_data) { Efficiency_Data data; data.field_type = input.get_field_type(); data.field_size = input.get_field_size(); data.path_found = (res_A_star.total_cost > -1); data.uniform_weights = input.get_max_weight() < 2; data.time = {res_A_star.exec_time, res_Dijkstra.exec_time}; data.expanded_cells_count = {res_A_star.expanded_cells_count, res_Dijkstra.expanded_cells_count}; gathered_data.push_back(data); } int main() { ofstream stat_out("statistics.txt"); vector<Efficiency_Data> gathered_data; vector<string> field_types = {/*"rooms", "snakes",*/ "rectangles", "islands"}; vector<pair<int, int>> size_ranges = {/*{1, 10}, */{500, 1000}}; const int tests_count = 1000; for (int cur_field_type_index = 0; cur_field_type_index < field_types.size(); ++cur_field_type_index) { for (int cur_range_index = 0; cur_range_index < size_ranges.size(); ++cur_range_index) { for (int is_uniform = 0; is_uniform <= 0; ++is_uniform) { for (int test_id = 0; test_id < tests_count; ++test_id) { auto size_range = size_ranges[cur_range_index]; cout << test_id << endl; auto field_type = field_types[cur_field_type_index]; cout << field_type << endl; make_user_input((bool)is_uniform, field_type, size_range); Input_Type<int> input; input.read_input(); Result_Type<int> res_A_star = Algo<int>::A_star(input); Printer<int>::print_main_info(input, res_A_star); //Printer<int>::print_map(input, res_A_star); input.change_h_key("0"); Result_Type<int> res_Dijkstra = Algo<int>::A_star(input); Printer<int>::print_main_info(input, res_Dijkstra); gather_data(input, res_A_star, res_Dijkstra, gathered_data); } } } } for (const auto& elem : gathered_data) { stat_out << elem; } //close file? return 0; } <file_sep>#include <utility> // // Created by ipakhalko on 9/1/19. // #ifndef DRAFT_2_GENERATOR_H #define DRAFT_2_GENERATOR_H #include <set> #include <string> #include <vector> #include "Cell.h" using namespace std; template <typename T> void adjust_directions_choice(set<string>& available_directions, long long cur_x, long long cur_y, long long prev_x, long long prev_y, vector<vector<T>>& weights) { if (cur_x - prev_x == 1) { available_directions.erase("up"); } else if (cur_x - prev_x == -1) { available_directions.erase("down"); } else if (cur_y - prev_y == 1) { available_directions.erase("right"); } else if (cur_y - prev_y == -1) { available_directions.erase("left"); } if (cur_x == weights.size() - 1) { available_directions.erase("down"); } if (cur_x == 0) { available_directions.erase("up"); } if (cur_y == weights.back().size() - 1) { available_directions.erase("right"); } if (cur_y == 0) { available_directions.erase("left"); } } template <typename T> void make_snakes(long long obstacle_count, vector<vector<T>>& weights, const Cell& start, const Cell& finish) { while (obstacle_count > 0) { long long snake_length = max(obstacle_count * 0.01, 1.); int snake_start_x, snake_start_y; do { snake_start_x = rand() % weights.size(); snake_start_y = rand() % weights.back().size(); } while (snake_start_x == start.x && snake_start_y == start.y); auto cur_x = snake_start_x, cur_y = snake_start_y; auto prev_x = cur_x, prev_y = cur_y; auto length_left = snake_length; long long segment_size_left = 0; while (length_left > 0) { weights[cur_x][cur_y] = -1; --length_left; if (cur_x + (cur_x - prev_x) >= 0 && cur_x + (cur_x - prev_x) < weights.size() && cur_y + (cur_y - prev_y) >= 0 && cur_y + (cur_y - prev_y) < weights.back().size() && segment_size_left > 0) { auto tmp = prev_x; prev_x = cur_x; cur_x = cur_x + (cur_x - tmp); tmp = prev_y; prev_y = cur_y; cur_y = cur_y + (cur_y - tmp); --segment_size_left; } else { segment_size_left = max((long long)((10 + rand() % 30) / 100. * length_left), 1LL); set<string> available_directions = {"up", "down", "left", "right"}; adjust_directions_choice(available_directions, cur_x, cur_y, prev_x, prev_y, weights); int delta = rand() % available_directions.size(); auto it = available_directions.begin(); while (delta > 0) { ++it; --delta; } string new_direction = *it; prev_x = cur_x, prev_y = cur_y; if (new_direction == "up") { cur_x = prev_x - 1; } else if (new_direction == "down") { cur_x = prev_x + 1; } else if (new_direction == "left") { cur_y = prev_y - 1; } else if (new_direction == "right") { cur_y = prev_y + 1; } } } obstacle_count -= snake_length; } weights[start.x][start.y] = max(1, weights[start.x][start.y]); weights[finish.x][finish.y] = max(1, weights[finish.x][finish.y]); } template <typename T> void make_rooms(long long obstacle_count, vector<vector<T>>& weights, const Cell& start, const Cell& finish) { double horizontal_walls_share = ((rand() % 20) + 40) / 100.; long long horizontal_walls_count = (obstacle_count * horizontal_walls_share) / weights.back().size(); long long vertical_walls_count = (obstacle_count * (1 - horizontal_walls_share)) / weights.size(); vector<int> x_coords; int prev_x = 0; while (horizontal_walls_count > 0) { int cur_x = prev_x + rand() % (max((long long)weights.size() - horizontal_walls_count - prev_x, 1LL)); if (cur_x < weights.size()) { x_coords.push_back(cur_x); for (int i = 0; i < weights.back().size(); ++i) { weights[cur_x][i] = -1; } prev_x = cur_x; } --horizontal_walls_count; } vector<int> y_coords; int prev_y = 0; while (vertical_walls_count > 0) { int cur_y = prev_y + rand() % (max((long long)weights.back().size() - vertical_walls_count - prev_y, 1LL)); if (cur_y < weights.back().size()) { y_coords.push_back(cur_y); for (int i = 0; i < weights.size(); ++i) { weights[i][cur_y] = -1; } prev_y = cur_y; } --vertical_walls_count; } prev_x = 0; for (int i = 0; i < x_coords.size(); ++i) { auto cur_x = x_coords[i]; prev_y = 0; for (int j = 0; j < y_coords.size(); ++j) { auto cur_y = y_coords[j]; /// double check this being sorted int vertical_segment_length = cur_x - prev_x + 1; int vertical_door_length = max(vertical_segment_length * (((rand() % 30) + 10) / 100.), 1.); int vertical_door_start = prev_x + rand() % (vertical_segment_length - vertical_door_length + 1); for (int delta = 0; delta < vertical_door_length; ++delta) { weights[vertical_door_start + delta][cur_y] = 1; } int horizontal_segment_length = cur_y - prev_y + 1; int horizontal_door_length = max(horizontal_segment_length * (((rand() % 30) + 10) / 100.), 1.); int horizontal_door_start = prev_y + rand() % (horizontal_segment_length - horizontal_door_length + 1); for (int delta = 0; delta < horizontal_door_length; ++delta) { weights[cur_x][horizontal_door_start + delta] = 1; } prev_y = cur_y; } prev_x = cur_x; } weights[start.x][start.y] = max(1, weights[start.x][start.y]); weights[finish.x][finish.y] = max(1, weights[finish.x][finish.y]); } template <typename T> void make_rectangles(long long obstacle_count, vector<vector<T>>& weights, const Cell& start, const Cell& finish) { long long n = weights.size(), m = weights.back().size(); while (obstacle_count > 0) { long long current_area = max(1LL, (long long)(obstacle_count * 0.1)); // upper bound of the actual area long long width = max(min(m / 3 + 1, current_area / (rand() % 9 + 1)), 1LL); long long height = max(min(n / 3 + 1, current_area / width), 1LL); int upperLeftCornerX = rand() % (n - height + 1); int upperLeftCornerY = rand() % (m - width + 1); if (!(start.x >= upperLeftCornerX && start.x <= upperLeftCornerX + height - 1 && start.y >= upperLeftCornerY && start.y <= upperLeftCornerY + width - 1) && !(finish.x >= upperLeftCornerX && finish.x <= upperLeftCornerX + height - 1 && finish.y >= upperLeftCornerY && finish.y <= upperLeftCornerY + width - 1)) { for (int i = upperLeftCornerX; i < upperLeftCornerX + height; ++i) { for (int j = upperLeftCornerY; j < upperLeftCornerY + width; ++j) { weights[i][j] = -1; } } } obstacle_count -= current_area; } } template <typename T> void make_islands(long long obstacle_count, vector<vector<T>>& weights, const Cell& start, const Cell& finish) { while (obstacle_count > 0) { long long snake_length = max(obstacle_count * 0.01, 1.); int snake_start_x, snake_start_y; do { snake_start_x = rand() % weights.size(); snake_start_y = rand() % weights.back().size(); } while (snake_start_x == start.x && snake_start_y == start.y); auto cur_x = snake_start_x, cur_y = snake_start_y; auto prev_x = cur_x, prev_y = cur_y; auto length_left = snake_length; while (length_left > 0) { weights[cur_x][cur_y] = -1; --length_left; set<string> available_directions = {"up", "down", "left", "right"}; adjust_directions_choice(available_directions, cur_x, cur_y, prev_x, prev_y, weights); int delta = rand() % available_directions.size(); auto it = available_directions.begin(); while (delta > 0) { ++it; --delta; } string new_direction = *it; prev_x = cur_x, prev_y = cur_y; if (new_direction == "up") { cur_x = prev_x - 1; } else if (new_direction == "down") { cur_x = prev_x + 1; } else if (new_direction == "left") { cur_y = prev_y - 1; } else if (new_direction == "right") { cur_y = prev_y + 1; } } obstacle_count -= snake_length; } weights[start.x][start.y] = max(1, weights[start.x][start.y]); weights[finish.x][finish.y] = max(1, weights[finish.x][finish.y]); } template <typename T> class Generator { string generator_type; double congestion_rate; public: Generator() { generator_type = "snakes"; congestion_rate = 0.1; } Generator(string field_type, double congestion_rate) : congestion_rate(congestion_rate), generator_type(field_type) {} void make_field(const Cell& start, const Cell& finish, vector<vector<T>>& weights, T max_weight) { for (size_t i = 0; i < weights.size(); ++i) { for (size_t j = 0; j < weights[i].size(); ++j) { weights[i][j] = rand() % max_weight + 1; } } long long obstacle_count = weights.size() * weights.back().size() * congestion_rate; if (generator_type == "snakes") { make_snakes<T>(obstacle_count, weights, start, finish); } else if (generator_type == "rooms") { make_rooms<T>(obstacle_count, weights, start, finish); } else if (generator_type == "rectangles") { make_rectangles<T>(obstacle_count, weights, start, finish); } else if (generator_type == "islands") { make_islands<T>(obstacle_count, weights, start, finish); } } }; #endif //DRAFT_2_GENERATOR_H <file_sep>/* // // Created by ipakhalko on 9/1/19. // #include "Generator.h" */ <file_sep>/* // // Created by ipakhalko on 9/6/19. // #include "Graph.h" */ <file_sep>// // Created by ipakhalko on 9/6/19. // #ifndef DRAFT_2_ALGO_H #define DRAFT_2_ALGO_H #include <ctime> #include <set> #include <algorithm> #include "Result_Type.h" #include "Input_Type.h" #include "Graph.h" using namespace std; template <typename T> class estimates { public: double f; T g; estimates(){} estimates(double f, T g) : f(f), g(g) {} }; double h(const Cell& current, const Cell& start, const Cell& goal, string h_type); template <typename T> class Algo { public: static Result_Type<T> A_star(Input_Type<T> input) { const int INF = 2e9; std::clock_t c_start = std::clock(); //build Graph object Graph<T, vector<vector<T>>> g(input); //make other magic auto start = input.get_start(); auto finish = input.get_finish(); if (input.get_weight(start) == -1 || input.get_weight(finish) == -1) { return Result_Type<T>(); } int n = input.get_field_size().first, m = input.get_field_size().second; set<pair<double, Cell>> f_queue; vector<vector<bool>> used(n, vector<bool>(m)); vector<vector<Cell>> parent(n, vector<Cell>(m)); vector<vector<estimates<T>>> estimatesMatrix(n, vector<estimates<T>>(m, estimates<T>(INF, INF))); f_queue.insert({input.get_weight(start.x, start.y), start}); estimatesMatrix[start.x][start.y] = estimates<T>( input.get_weight(start.x, start.y), input.get_weight(start.x, start.y)); long long expanded_cells_count = 0; while (!f_queue.empty()) { auto v = f_queue.begin()->second; f_queue.erase(f_queue.begin()); if (v == finish) { used[finish.x][finish.y] = true; ++expanded_cells_count; std::clock_t c_end = std::clock(); vector <Cell> path; Cell current = finish; while (current != start) { path.push_back(current); current = parent[current.x][current.y]; } path.push_back(start); reverse(path.begin(), path.end()); return Result_Type<T>(estimatesMatrix[finish.x][finish.y].g, path, used, 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC, expanded_cells_count); } if (!used[v.x][v.y]) { ++expanded_cells_count; } used[v.x][v.y] = true; for (const Cell& u : g.get_neighbours(v)) { auto relaxedCost = estimatesMatrix[v.x][v.y].g + input.get_weight(u.x, u.y); if (relaxedCost < estimatesMatrix[u.x][u.y].g) { parent[u.x][u.y] = v; estimatesMatrix[u.x][u.y].g = relaxedCost; } auto relaxedF = estimatesMatrix[u.x][u.y].g + h(u, start, finish, input.h_key()); if (!used[u.x][u.y] || relaxedF < estimatesMatrix[u.x][u.y].f) { estimatesMatrix[u.x][u.y].f = relaxedF; f_queue.insert({relaxedF, u}); if (used[u.x][u.y]) { --expanded_cells_count; } used[u.x][u.y] = false; } } } std::clock_t c_end = std::clock(); return Result_Type<T>(-1, {}, used, 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC, expanded_cells_count); } static Result_Type<T> Dijkstra(Input_Type<T> input) { input.change_h_key("0"); return A_star(input); } }; #endif //DRAFT_2_ALGO_H <file_sep>// // Created by ipakhalko on 9/6/19. // #ifndef DRAFT_2_GRAPH_H #define DRAFT_2_GRAPH_H #include <vector> #include "Cell.h" #include "Input_Type.h" using namespace std; template <typename T, typename container_type> class Graph { container_type contents; public: Graph() = default; Graph(Input_Type<T> input) { contents = input.get_weights(); } vector<Cell> get_neighbours(const Cell& c) { vector<Cell> neighbours; if (c.x > 0 && contents[c.x - 1][c.y] != -1) { neighbours.push_back(Cell(c.x - 1, c.y)); } if (c.y > 0 && contents[c.x][c.y - 1] != -1) { neighbours.push_back(Cell(c.x, c.y - 1)); } if (c.x < contents.size() - 1 && contents[c.x + 1][c.y] != -1) { neighbours.push_back(Cell(c.x + 1, c.y)); } if (c.y < contents[c.x].size() - 1 && contents[c.x][c.y + 1] != -1) { neighbours.push_back(Cell(c.x, c.y + 1)); } return neighbours; } }; #endif //DRAFT_2_GRAPH_H <file_sep>// // Created by ipakhalko on 9/8/19. // #ifndef DRAFT_2_PRINTER_H #define DRAFT_2_PRINTER_H #include <fstream> #include "Input_Type.h" #include "Result_Type.h" using namespace std; ofstream out("output.txt"); template<typename T> class Printer { public: static const void print_main_info(const Input_Type<T>& input, const Result_Type<T>& res) { if (input.h_key() != "0") { out << "A* algorithm - \n"; } else { out << "Dijkstra algorithm - \n"; } out << "path cost: " << res.total_cost << "\n"; out << "time taken: " << res.exec_time << endl; out << endl; } static const void print_map(const Input_Type<T>& input, const Result_Type<T>& res) { vector<vector<char>> cell_status(input.get_field_size().first, vector<char>(input.get_field_size().second, '.')); for (int i = 0; i < res.m_explored.size(); ++i) { for (int j = 0; j < res.m_explored.back().size(); ++j) { if (res.m_explored[i][j]) { cell_status[i][j] = '\''; } else if (input.get_weight(i, j) == -1) { cell_status[i][j] = '#'; } } } for (const auto& elem : res.m_path) { cell_status[elem.x][elem.y] = 'o'; } cell_status[input.get_start().x][input.get_start().y] = 'S'; cell_status[input.get_finish().x][input.get_finish().y] = 'F'; for (int i = 0; i < res.m_explored.size(); ++i) { for (int j = 0; j < res.m_explored.back().size(); ++j) { out << cell_status[i][j] << " "; } out << endl; } } }; #endif //DRAFT_2_PRINTER_H <file_sep> // // Created by ipakhalko on 9/6/19. // #include "Algo.h" #include <string> double h(const Cell& current, const Cell& start, const Cell& goal, string h_type) { if (h_type == "0") { return 0; } auto dx1 = current.x - goal.x; auto dy1 = current.y - goal.y; auto dx2 = start.x - goal.x; auto dy2 = start.y - goal.y; auto cross_product = abs(dx1*dy2 - dx2*dy1); return abs(dx1) + abs(dy1) + cross_product * 1e-3; } <file_sep>// // Created by ipakhalko on 9/1/19. // #ifndef DRAFT_2_CELL_H #define DRAFT_2_CELL_H class Cell { public: int x; int y; Cell() = default; Cell(int x, int y) : x(x), y(y) {} }; bool operator==(const Cell& lhs, const Cell& rhs); /* { return lhs.x == rhs.x && lhs.y == rhs.y; }*/ bool operator!=(const Cell& lhs, const Cell& rhs); /*{ return !(lhs == rhs); }*/ bool operator<(const Cell& lhs, const Cell& rhs);/* { return lhs.x < rhs.x || (lhs.x == rhs.x && lhs.y < rhs.y); }*/ #endif //DRAFT_2_CELL_H <file_sep>/* // // Created by ipakhalko on 9/6/19. // #include "Result_Type.h" */ <file_sep>// // Created by ipakhalko on 9/1/19. // #ifndef DRAFT_2_INPUT_TYPE_H #define DRAFT_2_INPUT_TYPE_H #include <cstddef> #include <utility> #include <vector> #include <string> #include <fstream> #include "Cell.h" #include "Generator.h" using namespace std; template <typename T> class Input_Type { string field_type; pair <int, int> field_size; // it is easier that way in terms of subtraction Cell start; Cell finish; vector<vector<T>> weights; string heuristic_key; string optimization; T max_weight; public: Input_Type() = default; ~Input_Type() = default; void read_input() { ifstream in("input.txt"); in >> field_size.first >> field_size.second; weights = vector<vector<T>> (field_size.first, vector<T>(field_size.second, 1)); in >> start.x >> start.y; in >> finish.x >> finish.y; string manual_input; in >> manual_input; if (manual_input == "yes") { for (int i = 0; i < field_size.first; ++i) { for (int j = 0; j < field_size.second; ++j) { in >> weights[i][j]; } } } else { in >> max_weight; in >> field_type; // snakes, segments, rectangles or rooms double congestion_rate; in >> congestion_rate; Generator<T> gen(field_type, congestion_rate); gen.make_field(start, finish, weights, max_weight); } in >> heuristic_key; in >> optimization; } vector<vector<T>> get_weights() const { return weights; } T get_weight(int i, int j) const { return weights[i][j]; } T get_weight(const Cell& c) const { return weights[c.x][c.y]; } T get_max_weight() const { return max_weight; } string get_field_type() const { return field_type; } pair<int, int> get_field_size() const { return field_size; } Cell get_start() const { return start; } Cell get_finish() const { return finish; } string h_key() const { return heuristic_key; } void change_h_key(string new_key) { heuristic_key = new_key; } }; #endif //DRAFT_2_INPUT_TYPE_H <file_sep>// // Created by ipakhalko on 9/1/19. // #include "Cell.h" using namespace std; bool operator==(const Cell& lhs, const Cell& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } bool operator!=(const Cell& lhs, const Cell& rhs) { return !(lhs == rhs); } bool operator<(const Cell& lhs, const Cell& rhs) { return lhs.x < rhs.x || (lhs.x == rhs.x && lhs.y < rhs.y); }<file_sep>// // Created by ipakhalko on 9/8/19. // //#include "Printer.h" <file_sep>cmake_minimum_required(VERSION 3.12) project(Draft_2) set(CMAKE_CXX_STANDARD 14) add_executable(Draft_2 main.cpp Input_Type.cpp Input_Type.h Cell.cpp Cell.h Generator.cpp Generator.h Result_Type.cpp Result_Type.h Algo.cpp Algo.h Graph.cpp Graph.h Printer.cpp Printer.h)<file_sep>/* // // Created by ipakhalko on 9/1/19. // #include "Input_Type.h" */
80f0e97d28da1bad1633b0c16dabd27d09c2b981
[ "CMake", "C++" ]
16
C++
ilyaphlk/A_star
99f4310646825ce919d404e0a96468dbb4a67a82
3fd5c49f3042dab4afc844fa9593309ec961b3fe
refs/heads/master
<file_sep># orrery Modeling the physics of our very own solar system <file_sep>package model; import vector.Vector; import processing.core.PApplet; /** * @author chadnislow */ public class Planet extends PApplet{ public double mass; public Vector position; public Vector velocity; public Vector acceleration; public float radius; public float r; public float g; public float b; //planet object based on real values public Planet (double mass, Vector position, Vector velocity, Vector acceleration, float radius, float r, float g, float b){ this.mass = mass; this.position = position; this.velocity = velocity; this.acceleration = acceleration; this.radius = radius; this.r = r; this.g = g; this.b = b; } }
fdd7af04fac3b44217ad40142fdab457102308e5
[ "Markdown", "Java" ]
2
Markdown
cnislow/orrery
31241689c9b199c3b4e00c93882cf001d5506417
7b0a85df49c6556bfe3e84da18e235a277d65967
HEAD
<repo_name>yangjiaronga/Witcoder<file_sep>/application/vjudge/hdoj/__init__.py # -*- coding:utf-8 -*- from .attribute import * from .crawler import * from .agent import * from .tools import * from .supervision import * from vjudge import httpclient <file_sep>/application/social/conf.py # coding: utf-8 from tornado.web import url urls = [ url(r"/user/(?P<username>\w+)", "social.views.UserHomepageHandler", name="user-home") ] ui_methods = {} ui_modules = {} <file_sep>/application/social/views.py # -*- coding: utf-8 -*- from sqlalchemy import func from tornado.web import HTTPError from common.web import BaseHandler from db.models.account import User class UserHomepageHandler(BaseHandler): """用户主页视图""" def get(self, username): user = self.db.session.query(User).filter( func.lower(User.username) == username.lower() ).one_or_none() if user is None: raise HTTPError(404) self.render("user/home.html", user=user) pass <file_sep>/application/assets/src/vjudge/exercise/index.js import React from 'react' import { render } from 'react-dom' import { Router, Route, IndexRoute, Link, IndexLink } from 'react-router' /** * 训练进度条组件 */ const ExerciseProgressBar = React.createClass({ getInitialState: function() { return {currenttime: Date.now()}; }, updateTime: function() { this.setState({currenttime: Date.now()}); }, componentDidMount: function() { if (this.state.currenttime > this.props.endtime) { this.interval = setInterval(this.updateTime, 86400000); } else { this.interval = setInterval(this.updateTime, 1000); } }, componentWillUnmount: function() { clearInterval(this.interval); }, render: function() { let rate = (this.state.currenttime - this.props.starttime) / (this.props.endtime - this.props.starttime) * 100; let progressStyle = {width: (rate > 100 ? 100 : (rate < 0 ? 0 : rate)) + '%'}; let progressStatus = "progress-bar progress-bar-striped active "; if (rate <= 50) { progressStatus += "progress-bar-success"; } else if (rate <= 90) { progressStatus += "progress-bar-warning"; } else { progressStatus += "progress-bar-danger"; } return ( <div className="progress"> <div className={progressStatus} role="progressbar" aria-valuemin="0" aria-valuemax="100" style={progressStyle}></div> </div> ); }, }); /** * 训练基础信息表组件 */ const ExerciseBasicInfo = React.createClass({ render: function() { return ( <table className="table table-bordered exercise-info"> <thead className="hidden"> <tr><th width="15%"></th><th width="35%"></th><th width="15%"></th><th width="35%"></th></tr> </thead> <tbody> <tr> <th>训练模式</th><td><span className="label label-default">默认模式</span></td> <th>训练类型</th><td><span className="label label-success">公开</span></td> </tr> <tr> <th>开始时间</th><td>{"2015-11-11 12:00:00"}</td> <th>训练状态</th><td><span className="label label-primary">进行中</span></td> </tr> <tr> <th>结束时间</th><td>{"2015-11-11 12:00:00"}</td> <th>创建者</th><td>{"JZQT"}</td> </tr> </tbody> </table> ); } }); /** * 训练题目列表组件 */ const ExerciseProblemList = React.createClass({ render: function() { return ( <table className="table table-striped table-bordered table-center"> <thead> <tr> <th width="5%"></th> <th width="10%">编号</th> <th width="50%">标题</th> <th width="15%">通过/提交</th> <th width="20%">来源</th> </tr> </thead> <tbody> <tr> <td></td> <td><a href="#"><b>{"A"}</b></a></td> <td><a href="#">{"A + B Problem"}</a></td> <td>{1} / {3}</td> <td><a href="#">{"HDOJ-1000"}</a></td> </tr> <tr> <td></td> <td><a href="#"><b>{"B"}</b></a></td> <td><a href="#">{"Sum Problem"}</a></td> <td>{14} / {23}</td> <td><a href="#">{"HDOJ-1001"}</a></td> </tr> <tr> <td></td> <td><a href="#"><b>{"C"}</b></a></td> <td><a href="#">{"A + B Problem II"}</a></td> <td>{3} / {45}</td> <td><a href="#">{"HDOJ-1002"}</a></td> </tr> <tr> <td></td> <td><a href="#"><b>{"D"}</b></a></td> <td><a href="#">{"Max Sum"}</a></td> <td>{8} / {9}</td> <td><a href="#">{"HDOJ-1003"}</a></td> </tr> </tbody> </table> ); } }); /** * 训练公告板组件 */ const ExerciseBulletin = React.createClass({ render: function() { return ( <div className="well text-danger"> <p>呵呵,这就是个React测试!</p> <p>这是一个训练的公告演示而已!</p> <p>训练的创建者可以在这里写下公告。</p> <p>比如</p> <p>请大家不要乱点链接!</p> </div> ); } }); /** * 训练应用首页路由组件 */ const ExerciseIndex = React.createClass({ render: function() { return ( <div className="row"> <div className="col-md-9"> <ExerciseBasicInfo /> <ExerciseProblemList /> </div> <div className="col-md-3"> <ExerciseBulletin /> </div> </div> ); } }); /** * 训练题目路由组件 */ ExerciseProblems = React.createClass({ render: function() { return ( <div className="row"> <div className="col-md-12"> <ExerciseProblemButtonGroup /> </div> </div> ); } }); /** * 训练题目按钮组组件 */ ExerciseProblemButtonGroup = React.createClass({ render: function() { return ( <div className="btn-group" role="group"> </div> ); } }); /** * 训练应用主路由组件 */ const Exercise = React.createClass({ render: function() { let currentPath = this.props.location.pathname; return ( <div className="container"> <div className="row"> <div className="col-md-12"> <h1 className="text-center">{"第一周周训 - 测试"}</h1> <ExerciseProgressBar starttime={Date.now()} endtime={Date.now() + 1000 * 100} /> <ul className="nav nav-tabs"> <li className={currentPath === "/" ? "active" : ""} role="presentation"> <IndexLink to="/" activeClassName="disabled">训练总览</IndexLink> </li> <li className={currentPath === "/problem/" ? "active" : ""} role="presentation"> <Link to="/problem/" activeClassName="disabled">题目信息</Link> </li> <li className={currentPath === "/submission/" ? "active" : ""} role="presentation"> <Link to="/submission/" activeClassName="disabled">提交信息</Link> </li> <li className={currentPath === "/ranklist/" ? "active" : ""} role="presentation"> <Link to="/ranklist/" activeClassName="disabled">排行榜</Link> </li> </ul><br/> </div> </div> {this.props.children} </div> ); }, }); render(( <Router history={ReactRouter.hashHistory}> <Route path="/" component={Exercise}> <IndexRoute component={ExerciseIndex} /> <Route path="/problem/" /> <Route path="/submission/" /> <Route path="/ranklist/" /> </Route> </Router> ), document.getElementById("exercise")); <file_sep>/application/db/tools.py #-*- coding: utf-8 -*- """ Witcoder 数据库工具模块 包含数据库操作相关的功能。 """ from .connector import get_engine from .models import BaseModel __all__ = ['init_all_tables', 'create_all_tables', 'drop_all_tables'] def init_all_tables(): """ 初始化所有数据表 相当于先删除所有数据表再创建所有数据表。 """ drop_all_tables() create_all_tables() def drop_all_tables(): """ 删除所有数据表 """ BaseModel.metadata.drop_all(bind=get_engine()) def create_all_tables(): """ 创建所有数据表 已经创建的数据表不会再创建。 """ BaseModel.metadata.create_all(bind=get_engine()) <file_sep>/application/db/connector.py # -*- coding: utf-8 -*- from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base class SQLAlchemy(object): _db_uri = "{dbms}+{driver}://{username}:{password}@{host}/{db}" def __init__(self, *args, **kwargs): """ :param dbms str: The name of database management system. Such as ``postgresql``, ``mysql``, ``oracle``, etc. :param driver str: The name of Database API library. Such as ``psycopg2``, ``pyodbc``, ``cx_oracle``, etc. :param username str: Database management system user name. :param password str: Database management system user password. :param host str: The address of database host. :param db str: The name of database. """ self._url = self._db_uri.format(**kwargs) self._engine = create_engine(self._url, echo=False) self._metadata = MetaData(self._engine) self._session = sessionmaker(bind=self._engine)() self.Model = declarative_base(self._engine, self._metadata) @property def engine(self): return self._engine @property def metadata(self): return self._metadata @property def session(self): return self._session @property def url(self): return self._url pass <file_sep>/application/migrations/versions/8c01cf7715ab_init.py """init Revision ID: <KEY> Revises: Create Date: 2016-05-19 22:45:48.137171 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = None branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('tb_user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=20), nullable=False), sa.Column('password', sa.CHAR(length=32), nullable=False), sa.Column('nickname', sa.String(length=50), server_default='', nullable=False), sa.Column('email', sa.String(length=50), nullable=False), sa.Column('avatar', sa.String(length=200), server_default='', nullable=False), sa.Column('register_time', sa.DateTime(), server_default=sa.text('NOW()'), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('username') ) op.create_table('tb_virtual_judge_problem', sa.Column('id', sa.Integer(), nullable=False), sa.Column('remote_oj', sa.String(length=20), nullable=False), sa.Column('remote_pid', sa.String(length=20), nullable=False), sa.Column('url', sa.String(length=500), nullable=False), sa.Column('title', sa.String(length=100), nullable=False), sa.Column('special_judge', sa.Boolean(), server_default=sa.text('FALSE'), nullable=False), sa.Column('time_limit', sa.Integer(), server_default=sa.text('0'), nullable=False), sa.Column('memory_limit', sa.Integer(), server_default=sa.text('0'), nullable=False), sa.Column('description', sa.Text(), server_default='', nullable=False), sa.Column('input', sa.Text(), server_default='', nullable=False), sa.Column('output', sa.Text(), server_default='', nullable=False), sa.Column('sample_input', sa.Text(), server_default='', nullable=False), sa.Column('sample_output', sa.Text(), server_default='', nullable=False), sa.Column('hint', sa.Text(), server_default='', nullable=False), sa.Column('source', sa.Text(), server_default='', nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('remote_oj', 'remote_pid'), sa.UniqueConstraint('url') ) op.create_table('tb_user_info', sa.Column('id', sa.Integer(), nullable=False), sa.Column('_gender', sa.SmallInteger(), server_default='0', nullable=False), sa.Column('school', sa.String(length=50), server_default='', nullable=False), sa.Column('major', sa.String(length=50), server_default='', nullable=False), sa.Column('url', sa.String(length=100), server_default='', nullable=False), sa.Column('about', sa.String(length=200), server_default='', nullable=False), sa.ForeignKeyConstraint(['id'], ['tb_user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('tb_virtual_judge_problem_statistics', sa.Column('id', sa.Integer(), nullable=False), sa.Column('total', sa.Integer(), server_default=sa.text('0'), nullable=False), sa.Column('ac', sa.Integer(), server_default=sa.text('0'), nullable=False), sa.ForeignKeyConstraint(['id'], ['tb_virtual_judge_problem.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('tb_virtual_judge_submission', sa.Column('id', sa.Integer(), nullable=False), sa.Column('submitter_id', sa.Integer(), nullable=False), sa.Column('problem_id', sa.Integer(), nullable=False), sa.Column('_status', sa.SmallInteger(), server_default='0', nullable=False), sa.Column('time_cost', sa.Integer(), server_default='0', nullable=False), sa.Column('memory_cost', sa.Integer(), server_default='0', nullable=False), sa.Column('language', sa.String(length=50), nullable=False), sa.Column('code_length', sa.Integer(), nullable=False), sa.Column('submit_time', sa.DateTime(), server_default=sa.text('NOW()'), nullable=False), sa.Column('shared', sa.Boolean(), server_default=sa.text('false'), nullable=False), sa.Column('remote_key', sa.String(length=20), server_default='', nullable=False), sa.Column('remote_status', sa.String(length=100), server_default='', nullable=False), sa.ForeignKeyConstraint(['problem_id'], ['tb_virtual_judge_problem.id'], ), sa.ForeignKeyConstraint(['submitter_id'], ['tb_user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_tb_virtual_judge_submission_id'), 'tb_virtual_judge_submission', ['id'], unique=False) op.create_table('tb_virtual_judge_submission_compile_info', sa.Column('id', sa.Integer(), nullable=False), sa.Column('info', sa.Text(), nullable=False), sa.ForeignKeyConstraint(['id'], ['tb_virtual_judge_submission.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_tb_virtual_judge_submission_compile_info_id'), 'tb_virtual_judge_submission_compile_info', ['id'], unique=False) op.create_table('tb_virtual_judge_submission_source_code', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.Text(), nullable=False), sa.ForeignKeyConstraint(['id'], ['tb_virtual_judge_submission.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_tb_virtual_judge_submission_source_code_id'), 'tb_virtual_judge_submission_source_code', ['id'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_tb_virtual_judge_submission_source_code_id'), table_name='tb_virtual_judge_submission_source_code') op.drop_table('tb_virtual_judge_submission_source_code') op.drop_index(op.f('ix_tb_virtual_judge_submission_compile_info_id'), table_name='tb_virtual_judge_submission_compile_info') op.drop_table('tb_virtual_judge_submission_compile_info') op.drop_index(op.f('ix_tb_virtual_judge_submission_id'), table_name='tb_virtual_judge_submission') op.drop_table('tb_virtual_judge_submission') op.drop_table('tb_virtual_judge_problem_statistics') op.drop_table('tb_user_info') op.drop_table('tb_virtual_judge_problem') op.drop_table('tb_user') ### end Alembic commands ### <file_sep>/application/db/models/vjudge/base.py # -*- coding: utf-8 -*- from sqlalchemy import text from sqlalchemy.schema import Column from sqlalchemy.types import Integer, SmallInteger, String, DateTime, Boolean from db.models.base import BaseModel class SubmissionModel(BaseModel): __abstract__ = True status2id = {"Pending": 0, "Accepted": 1, "Wrong Answer": 2, "Runtime Error": 3, "Compilation Error": 4, "Presentation Error": 5, "Time Limit Exceeded": 6, "Memory Limit Exceeded": 7, "Output Limit Exceeded": 8, "Online Judge Error": 9, "Virtual Judge Error": 10, "Dangerous Code": 11, "Unknown Error": 12, "Submit Error": 13, "Fetch Error": 14} id2status = {value: key for key, value in status2id.items()} # 表结构 _status = Column(SmallInteger, nullable=False, default=status2id["Pending"], server_default=str(status2id["Pending"])) time_cost = Column(Integer, nullable=False, default=0, server_default='0') memory_cost = Column(Integer, nullable=False, default=0, server_default='0') language = Column(String(50), nullable=False) code_length = Column(Integer, nullable=False) submit_time = Column(DateTime, nullable=False, server_default=text("NOW()")) shared = Column(Boolean, nullable=False, default=False, server_default=text("false")) remote_key = Column(String(20), nullable=False, default="", server_default="") remote_status = Column(String(100), nullable=False, default="", server_default="") @property def status(self): if not hasattr(self, "_status_"): self._status_ = self.id2status[self._status] return self._status_ @status.setter def status(self, value): if isinstance(value, int) and value in self.id2status: self._status = value self._status_ = self.id2status[value] elif isinstance(value, str) and value in self.status2id: self._status = self.status2id[value] self._status_ = value else: raise ValueError("Error value: '{}'!".format(value)) pass <file_sep>/application/db/models/vjudge/exercise.py # -*- coding: utf-8 -*- """Witcoder Virtual Judge 训练相关数据表Model""" from datetime import timedelta from sqlalchemy.orm import relationship from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint from sqlalchemy.types import (Integer, String, DateTime, Text, SmallInteger, Interval) from db.models.base import BaseModel from db.models.vjudge.base import SubmissionModel class Exercise(BaseModel): """ Virtual Judge 训练主表Model 训练表被设置为**可删除的表**,删除训练后会级联删除该训练下的训练信息, 题目,提交答案以及榜单记录等。 数据表关系: `info`: 与`ExerciseInfo`的一对一关系 `creater`: 与`User`的多对一关系,参见`tb_user`数据表 `problems`: 与`ExerciseProblem`的一对多关系 `submissions`: 与`ExerciseSubmission`的一对多关系 `ranklist_records`: 与`ExerciseRanklistRecord`的一对多关系 索引: `id`: 主键上的索引 """ type2id = {"public": 0, "private": 1} id2type = {value: key for key, value in type2id.items()} mode2id = {"default": 0} id2mode = {value: key for key, value in mode2id.items()} __tablename__ = 'tb_virtual_judge_exercise' # 表结构 id = Column(Integer, primary_key=True, index=True) title = Column(String(50), nullable=False) creater_id = Column(Integer, ForeignKey("tb_user.id"), nullable=False, index=True) _type = Column(SmallInteger, nullable=False, default=type2id["public"], server_default=str(type2id["public"])) _mode = Column(SmallInteger, nullable=False, default=mode2id["default"], server_default=str(mode2id["default"])) starttime = Column(DateTime, nullable=False) endtime = Column(DateTime, nullable=False) password = Column(String(32), nullable=False, default='', server_default='') # 关系 info = relationship("ExerciseInfo", backref="exercise", cascade="all", uselist=False) creater = relationship("User", uselist=False) problems = relationship("ExerciseProblem", backref="exercise", cascade="all") submissions = relationship("ExerciseSubmission", backref="exercise", cascade="all") ranklist_records = relationship("ExerciseRanklistRecord", backref="exercise", cascade="all") def __repr__(self): return "<Exercise(id={})>".format(self.id) @property def type(self): if not hasattr(self, "_type_"): self._type_ = self.id2type[self._type] return self._type_ @type.setter def type(self, value): if isinstance(value, int) and value in self.id2type: self._type_ = self.id2type[value] self._type = value elif isinstance(value, str) and value in self.type2id: self._type_ = value self._type = self.type2id[value] else: raise ValueError("Exercise `type` value error! " "value: '{}'".format(value)) @property def mode(self): if not hasattr(self, "_mode_"): self._mode_ = self.id2mode[self._mode] return self._mode_ @mode.setter def mode(self, value): if isinstance(value, int) and value in self.id2mode: self._mode_ = self.id2mode[value] self._mode = value elif isinstance(value, str) and value in self.mode2id: self._mode_ = value self._mode = self.mode2id[value] else: raise ValueError("Submission `mode` value error! " "value: '{}'".format(value)) @classmethod def new(cls, *, problem_id_list, problem_title_list, **kwargs): assert len(problem_id_list) == len(problem_title_list) exercise = cls(**kwargs) exercise.info = ExerciseInfo() exercise.problems = [ ExerciseProblem(problem_id=problem_id_list[i], order=i, title=problem_title_list[i]) for i in range(len(problem_id_list))] return exercise pass class ExerciseInfo(BaseModel): """ Virtual Judge 训练基础信息表Model 数据表关系: `exercise`: 与`Exercise`的一对一关系,参见`tb_virtual_judge_exercise`表 索引: `id`: 主键上的索引 """ __tablename__ = "tb_virtual_judge_exercise_info" # 表结构 id = Column(Integer, ForeignKey("tb_virtual_judge_exercise.id"), primary_key=True, index=True) bulletin = Column(Text, nullable=False, default='', server_default='') def __repr__(self): return "<ExerciseInfo(id={})>".format(self.id) pass class ExerciseProblem(BaseModel): """ Virtual Judge 训练题目表Model 数据表关系: `exercise`: 与`Exercise`的多对一关系,参见`tb_virtual_judge_exercise`表 `submissions`: 与`ExerciseSubmission`的一对多关系 `problem`: 与`Problem`的一对一关系,单向关系 索引: `id`: 主键上的索引 `exercise_problem`: `exercise_id`与`problem_order`的组合唯一索引 """ __tablename__ = 'tb_virtual_judge_exercise_problem' # 表结构 id = Column(Integer, primary_key=True, index=True) exercise_id = Column(Integer, ForeignKey("tb_virtual_judge_exercise.id"), nullable=False, index=True) problem_id = Column(Integer, ForeignKey("tb_virtual_judge_problem.id"), nullable=False, index=True) order = Column(SmallInteger, nullable=False) title = Column(String(100), nullable=False, default='', server_default='') # 关系 submissions = relationship( "ExerciseSubmission", backref="problem", order_by=lambda: ExerciseSubmission.submit_time.desc()) origin = relationship("Problem", uselist=False) # 其他约束 UniqueConstraint(exercise_id, order) def __repr__(self): return "<ExerciseProblem({})>".format(self.id) pass class ExerciseSubmission(SubmissionModel): """ Virtual Judge 训练提交答案主表Model 数据表关系: `exercise`: 与`Exercise`的多对一关系,参见`tb_virtual_judge_exercise` `problem`: 与`ExerciseProblem`的多对一关系,参见`tb_exercise_problem` `submitter`: 与`User`的多对一关系,单向关系 `source`: 与`ExerciseSubmissionSourceCode`的一对一关系 `compilation`: 与`ExerciseSubmissionCompilationInfo`的一对一关系 索引: `id`: 主键上的索引 """ __tablename__ = "tb_virtual_judge_exercise_submission" # 表结构 id = Column(Integer, primary_key=True, index=True) exercise_id = Column(Integer, ForeignKey("tb_virtual_judge_exercise.id"), nullable=False, index=True) submitter_id = Column(Integer, ForeignKey("tb_user.id"), nullable=False, index=True) exercise_problem_id = Column( Integer, ForeignKey("tb_virtual_judge_exercise_problem.id"), nullable=False, index=True) # 关系 submitter = relationship("User") source = relationship("ExerciseSubmissionSourceCode", backref="submission", uselist=False) compilation = relationship("ExerciseSubmissionCompilationInfo", backref="submission", uselist=False) def __repr__(self): return "<ExerciseSubmission(id={})>".format(self.id) pass class ExerciseSubmissionSourceCode(BaseModel): """ Virtual Judge 训练提交答案源代码表Model 数据表关系: `submission`: 与`ExerciseSubmission`的一对一关系,参见`tb_exercise_submission`表 索引: `id`: 主键上的索引 """ __tablename__ = "tb_virtual_judge_exercise_submission_source_code" # 表结构 id = Column(Integer, ForeignKey("tb_virtual_judge_exercise_submission.id"), primary_key=True, index=True) code = Column(Text, nullable=False) def __repr__(self): return "<ExerciseSubmissionSourceCode(id={})".format(self.id) pass class ExerciseSubmissionCompilationInfo(BaseModel): """ Virtual Judge 训练提交答案编译信息表Model 数据表关系: `submission`: 与`ExerciseSubmission`的一对一关系, 参见`tb_exercise_submission`表 索引: `id`: 主键上的索引 """ __tablename__ = "tb_virtual_judge_exercise_submission_compile_info" # 表结构 id = Column(Integer, ForeignKey("tb_virtual_judge_exercise_submission.id"), primary_key=True, index=True) info = Column(Text, nullable=False) def __repr__(self): return "<ExerciseSubmissionCompilationInfo(id={})>".format(self.id) pass class ExerciseRanklistRecord(BaseModel): """ Virtual Judge 训练排行榜记录表Model 数据表关系: `exercise`: 与`Exercise`的多对一关系,参见`tb_virtual_judge_exercise`表 `problem`: 与`ExerciseProblem`的多对一关系,单向关系 """ __tablename__ = "tb_virtual_judge_exercise_ranklist_record" # 表结构 id = Column(Integer, primary_key=True, index=True) exercise_id = Column(Integer, ForeignKey("tb_virtual_judge_exercise.id"), nullable=False, index=True) exercise_problem_id = Column( Integer, ForeignKey("tb_virtual_judge_exercise_problem.id"), nullable=False, index=True) submitter_id = Column(Integer, ForeignKey("tb_user.id"), nullable=False, index=True) time_cost = Column(Interval, nullable=False, default=timedelta(-1)) failed_count = Column(Integer, nullable=False, default=0, server_default='0') # 关系 exercise_problem = relationship(ExerciseProblem) # 其他约束 UniqueConstraint(submitter_id, exercise_problem_id) def __repr__(self): return "<ExerciseRanklistRecord(id={})>".format(self.id) @property def solved(self): """判断是否题目是否已经解决""" return self.time_cost > timedelta(0) pass <file_sep>/doc/vjudge/README.md # Virtual Judge 模块文档 该文档主要内容为描述Witcoder Virtual Judge模块的功能介绍,开发要求以及规范等。 ## 模块简介 Virtual Judge(虚拟评测,简称VJ)系统是**Witcoder**的重要核心功能(没有之一)。 Virtual Judge 不同于Online Judge(在线评测,简称OJ),但它依赖于Online Judge。 因为Virtual Judge没有本地题库,没有评测核心,所以它不会完成评测的任务, 它的任务是作为用户在Online Judge上做题的一个**中介代理**。 Virtual Judge主要包含以下**两大核心功能**。 1. **远端OJ题目查看功能** 该功能为将各大OJ上的题目爬取到本地的数据库中,在VJ上展示。 也就是说,用户可以在VJ上查看各大OJ的题目而不用辗转于不同的OJ中。 2. **远端OJ题目提交功能** 该功能为将VJ用户提交的的题目答案转发给各大OJ评测并获取其评测结果。 获取到的评测结果一方面存储在本地VJ数据库中,另一方面在VJ上展示供用户查看。 因此,该功能实现的是用户不需要辗转与不同的OJ中做题,在VJ上就可以实现做各大OJ的题目。 Virtual Judge的以上两大核心功能分别对应两大程序模块,**爬虫模块**和**代理模块**。 其中,爬虫获取远端OJ的相关信息,而代理作为用户与远端OJ信息交互的中介,也兼具一些爬虫爬取信息的功能。 Virtual Judge还衍生出了一些基于以上两大核心功能的其他**扩展功能**(比如训练、比赛功能)。 * **训练功能** Witcoder Virtual Judge的该功能实际上是其他Virtual Judge的比赛功能。 只是大部分情况下很多人使用的时候实则是作为训练来使用,所以Witcoder将其一分为二以做区分。 训练功能主要实现的是一套题目的绑定,比如用户想做某一类型的题目, 找出该类型题目的题集之后就可以创建一个训练,比之对照着题集一个个的做要好很多。 另外训练也可作为不那么严肃正式的比赛来使用,它和比赛功能的主要区别之一是创建的严格程度和场合的正式程度。 训练的比赛模式可以让训练的计分方案达到和比赛一样,同样可以实现小型比赛功能。 * **比赛功能** 比赛功能作为一个比较正式严肃功能,在可创建比赛的权限上会对用户做一定的限制, 比如必须是认证过的组织、学校、企业机构等。 相比之下,比赛因为较严肃正式,结束后会做对应的比赛相关信息的统计分析等。 另外,比赛一经创建不可被删除。 ## 开发要求及规范 该部分只讨论对Witcoder Virtual Judge添加远端Online Judge支持的开发规范。 ### 目录文件结构 下面讲述Virtual Judge中远程OJ模块的目录结构,以`HDOJ`为例。 ``` vjudge/ ├── __init__.py ├── tools │   ├── ... │   └── ... ├── urls.py ├── views.py ├── hdoj HDOJ模块包 │   ├── __init__.py │   ├── attribute.py HDOJ属性模块 │   ├── crawler.py HDOJ爬虫模块 │   └── agent.py HDOJ代理模块 └── ... ``` 要向Virtual Judge添加对一个Online Judge的支持,则应该在`vjudge/`下对应的对应地创建一个模块。 该模块以及下层模块命名应符合`pep8`风格,即**模块和包名必须以小写字母加下划线的方式命名,不应该使用大写字母**。 ### 向VJ添加一个OJ支持模块 对于一个OJ模块,其下至少应该包含五个文件,分别为`__init__.py`,`attribute.py`,`crawler.py`,`agent.py`和`supervision.py`。 对于每一个文件都有其确定的用途,下面对每一个文件都做一个详细的介绍。 * `__init__.py` 该文件实际上是**作为OJ内部模块与外部模块交互的接口文件**,**所有模块内部需要被外部引用的代码都应该被引入到该文件中**。 因此,该文件实际上仅做模块导入之用,不书写任何代码的定义等。 对于VJ下的每一个OJ模块,OJ内部的模块文件可互相使用相对导入引用,而外部导入OJ模块最多只能导入OJ模块顶层, 即导入到`__init__.py`这里。 以前面的HDOJ模块的目录结构图示例 ```python from vjudge import hdoj # 外部导入,正确 from vjudge.hdoj import get_problem_url # 外部导入,正确 from vjudge.hdoj import crawler # 外部导入,错误 import vjudge.hdoj.cralwer # 外部导入,错误 from .crawler import * # 内部导入,正确 from .attribute import HOST_URL # 内部导入,正确 ``` 所有在`hdoj/`以下的文件互相导入都算内部导入,从`hdoj/*`以外的文件中导入`hdoj/*`都算作外部导入,包括`vjudge/*`里的导入。 比如`vjudge/views.py`导入`hdoj/crawler.py`就算是从外部导入,并且这是被不允许的,它只能导入到`hdoj`这里, 即`from . import hdoj`或`import vjudge.hdoj`这样的。 * `attribute.py` 该文件为OJ的**属性模块**,里面主要书写关于OJ的一些常量数据信息,比如`HOST_URL`,`NAMESET`,`CHARSET`等。 对于该文件应该写哪些数据的定义是有些基本的要求的,一些关于OJ的基础必要信息对于每一个OJ的属性模块来说都应该有, 而对于其他一些OJ独有的信息也可以按照情况写在里面,一般来说模块内部引用主要是爬虫和代理模块会引用该模块中的数据。 下面对于一些OJ基本上必不可少的常量信息列一个基本的清单和备注。 |常量名 |备注 | |:-------------:|:------------------------------------------------------| |`HOST_URL` |远端OJ主页的url | |`STD_NAME` |远端OJ在Witcoder Virtual Judge下的标准名 | |`NAME_SET` |远端OJ常用名集合,全部使用大写,使用时不会做大小写区分 | |`CHARSET` |远端OJ的网页编码 | |`LOGIN_URL` |远端OJ账号登录的url | 上面表格所列的常量是基本每一个OJ都必要的信息,实际上每一个OJ都必要的属性模块信息不仅限于此,上面表格只是部分示例。 如有必要,可根据OJ实际情况或为编写代码方便来添加或修改。 * `crawler.py` * `agent.py` * `supervision.py` <file_sep>/application/vjudge/poj/crawler.py #-*- coding:utf-8 -*- """ Virtual Judge POJ 爬虫模块 """ import re from tornado.gen import coroutine,Task from utils.httpclient import AsyncHTTPClient from .attribute import CHARSET, HOST_URL from ..tools.problem import problem_info_refine __all__ = ['get_problem_url','from_html_get_problem_info','get_problem_info', 'get_problem_list_url','from_html_get_problem_list', 'get_problem_list','from_html_get_problem_volumes', 'get_problem_volumes'] client = AsyncHTTPClient() def get_problem_url(origin_pid): """ 获取POJ题目的url """ if not isinstance(origin_pid,(int,str)): raise TypeError("The type of 'origin'_pid' is {}.".format( str(type(origin_pid)) )) origin_pid = str(origin_pid).strip() if not str(origin_pid).isdigit(): raise ValueError("'{}' isn't a regular value of " "`origin_pid`.".format(origin_pid)) return ''.join([HOST_URL,'/problem?id=',str(origin_pid)]) def from_html_get_problem_info(htmltext,origin_pid): """从HTML文本和POJ题目编号中获取POJ题目信息 """ # 检查 `htmltext` if isinstance(htmltext,bytes): htmltext = htmltext.decode(CHARSET,'ignore') elif not isinstance(htmltext,str): raise TypeError("The type of `htmltext` is " "{}".format(str(type(htmltext)))) # 检查 `origin_pid` if not isinstance(origin_pid,(int,str)): raise TypeError("The type of 'origin'_pid' is {}.".format( str(type(origin_pid)) )) if not str(origin_pid).isdigit(): raise ValueError("'{}' isn't a regular value of " "`origin_pid`.".format(origin_pid)) #处理 `htmltext` htmltext = htmltext.strip().replace('\r\n','\n') print(htmltext) # 获取未处理过的原始信息 raw_info = { "origin_oj":"POJ", "origin_pid":str(origin_pid), "url":get_problem_url(origin_pid), "title":_get_problem_title(htmltext), "time_limit":_get_problem_time_limit(htmltext), "memory_limit":_get_problem_memory_limit(htmltext), "special_judge":_get_problem_special_judge(htmltext), "description":_get_problem_description(htmltext), "input":_get_problem_input(htmltext), "output":_get_problem_output(htmltext), "sample_input":_get_problem_sample_input(htmltext), "sample_output":_get_problem_sample_output(htmltext), "hint":_get_problem_hint(htmltext), "source":_get_problem_source(htmltext) } # 返回处理后的题目信息 #return raw_info return problem_info_refine(raw_info) @coroutine def get_problem_info(remote_pid): url = get_problem_url(remote_pid) response = yield Task(client.get,url) return from_html_get_problem_info(response.body, remote_pid) def get_problem_list_url(vol=1): """ 获取指定页的题目列表的url `vol`参数的类型必须为`str`或`int`,否则会抛出`TypeError`。 `vol`将会被转换成`str`类型并使用`strip()`方法处理, 处理后的结果会使用`isdigit()`方法检验,检验失败抛出`ValueError`异常。 """ if not isinstance(vol, (int, str)): raise TypeError("The type of `vol` is {}.".format(str(type(vol)))) vol = str(vol).strip() if not vol.isdigit(): raise ValueError("'{}' isn't a regular value of `vol`.".format(vol)) return ''.join([HOST_URL, '/problemlist?volume=', vol]) def from_html_get_problem_list(htmltext): """从HTML文本字符串中解析出POJ题目列表 """ if isinstance(htmltext,bytes): htmltext = htmltext.decode(CHARSET,'ignote') elif not isinstance(htmltext,str): raise TypeError("The type of `htmltext` is " "{}".format(str(type(htmltext)))) htmltext = htmltext.strip() problist = [ (remote_pid.strip(), title.strip()) for remote_pid,title in _problist_problem_re.findall(htmltext) ] return problist @coroutine def get_problem_list(vol=1): url = get_problem_list_url(vol) response = yield Task(client.get,url) return from_html_get_problem_list(response.body) def from_html_get_problem_volumes(htmltext): """从HTML文本字符串中获取POJ的题目列表页的索引列表 """ if isinstance(htmltext,bytes): htmltext = htmltext.decode(CHARSET,'ignore') elif not isinstance(html,str): raise TypeError("The type of `htmltext` is " "{}".format(str(type(htmltext)))) htmltext = htmltext.strip() vollist = list(set(map(int ,_problist_vol_re.findall(htmltext)))) vollist.sort() return vollist @coroutine def get_problem_volumes(): url = get_problem_list_url(1) response = yield Task(client.get,url) return from_html_get_problem_volumes(response.body) def _get_problem_title(string): """从题目的HTML文本 字符串中匹配`title`信息 """ res_list = _probinfo_title_re.findall(string) if len(res_list) == 0: #没有匹配到信息 return None elif len(res_list) > 1: #匹配信息数大于一 pass return res_list[0].strip() def _get_problem_time_limit(string): """从题目中的HTML文本字符串中匹配`time_limit`信息 """ res_list = _probinfo_time_limit_re.findall(string) if len(res_list) == 0: return None elif len(res_list) > 1: pass return res_list[0] def _get_problem_memory_limit(string): """从题目的HTML文本字符串中匹配`memory_limit`信息 """ res_list = _probinfo_memory_limit_re.findall(string) if len(res_list) == 0: return None elif len(res_list) > 1: pass return res_list[0] def _get_problem_special_judge(string): """ 从题目HTML文本字符串中匹配`special_judge`信息 返回`bool`类型 """ res_list = _probinfo_special_judge_re.findall(string) if len(res_list) > 1: pass return bool(res_list) def _get_problem_description(string): """ 从题目HTML文本字符串中匹配`description`信息 """ res_list = _probinfo_description_re.findall(string) if len(res_list) == 0: return "" elif len(res_list) > 1: pass return res_list[0].strip() def _get_problem_input(string): """ 从题目的HTML文本字符串中匹配`input`信息 题目信息中可能没有Input,因此如果未匹配成功将返回字符串. """ res_list = _probinfo_input_re.findall(string) if len(res_list) == 0: return "" elif len(res_list) > 1: pass return res_list[0].strip() def _get_problem_output(string): """ 从题目的HTML文本字符串中匹配`output`信息 """ res_list = _probinfo_output_re.findall(string) if len(res_list) == 0: return "" elif len(res_list) > 1: pass return res_list[0].strip() def _get_problem_sample_input(string): """从题目的HTML文本字符串中匹配`sample_input`信息 """ res_list = _probinfo_sample_input_re.findall(string) if len(res_list) == 0: return "" elif len(res_list) > 1: pass return res_list[0] def _get_problem_sample_output(string): """从题目的HTML文本字符串中匹配`sample_input`信息 """ res_list = _probinfo_sample_output_re.findall(string) if len(res_list) == 0: return "" elif len(res_list) > 1: pass return res_list[0] def _get_problem_source(string): """从题目的HTML文本字符串中匹配`source`信息 用strip()处理 """ res_list = _probinfo_source_re.findall(string) if len(res_list) == 0: return "" elif len(res_list) > 1: pass return res_list[0].strip() def _get_problem_hint(string): """从题目的HTML文本字符串中匹配`hint`信息 """ res_list = _probinfo_hint_re.findall(string) if len(res_list) == 0: return "" elif len(res_list) > 1: pass return res_list[0].strip() _probinfo_title_re = re.compile(r'<title>\d{3,} -- ([\s\S]*?)</title>') _probinfo_time_limit_re = re.compile(r'<b>Time Limit:</b> (\d{3,})MS</td>') _probinfo_memory_limit_re = re.compile(r'<b>Memory Limit:</b> (\d{3,})K</td>') _probinfo_special_judge_re = re.compile(r'<td style="font-weight:bold; color:red;">Special Judge</td>') _probinfo_description_re = re.compile(r'<p class="pst">Description</p><div class="ptx" lang="en-US">([\s\S]*?)</div>') _probinfo_input_re = re.compile(r'<p class="pst">Input</p><div class="ptx" lang="en-US">([\s\S]*?)</div>') _probinfo_output_re = re.compile(r'<p class="pst">Output</p><div class="ptx" lang="en-US">([\s\S]*?)</div>') _probinfo_sample_input_re = re.compile(r'<p class="pst">Sample Input</p><pre class="sio">([\s\S]*?)</pre>') _probinfo_sample_output_re = re.compile(r'<p class="pst">Sample Output</p><pre class="sio">([\s\S]*?)</pre>') _probinfo_source_re = re.compile(r'<p class="pst">Source</p><div class="ptx" lang="en-US">([\s\S]*?)</div>') _probinfo_hint_re = re.compile(r'<p class="pst">Hint</p><div class="ptx" lang="en-US">([\s\S]*?)</div>') _problist_problem_re = re.compile(r'<a lang="en-US" href=problem\?id=(?P<remote_id>\d{4})>(?P<title>.*?)</a>') _problist_problem_id_re = re.compile(r'<a lang="en-US" href=problem?id=(\d{1,})>') _problist_problem_title_re = re.compile(r'<a lang="en-US" href=problem?id=\d{1,}>([\s\S]*?)</a>') _problist_vol_re = re.compile(r'<a href=problemlist\?volume=\d+><font[^<>].*?>(\d+)</font></a>') <file_sep>/application/vjudge/poj/tools.py #-*- coding:utf-8 -*- """ Virtual Judge POJ 内部工具模块 """ from ..tools import stdinfo from ..tools.agent import AsyncAgent from .attribute import (CHARSET,SUBMISSION_CODE_LANGUAGE_ID_TABLE, JUDGE_INFO_CODE_LANGUAGE_ID_TABLE, JUDGE_INFO_JUDGE_STATUS_ID_TABLE) __all__ = ['get_submission_origin_code_language_id', 'get_judge_info_origin_code_language_id', 'is_finished','get_judge_info_origin_judge_status_id', 'check_and_handle_htmltext'] client = AsyncAgent() def get_submission_origin_code_language_id(origin_code_language): """将poj提交代码选择语言转换成提交表单所使用的ID """ origin_code_language_id = SUBMISSION_CODE_LANGUAGE_ID_TABLE.get( origin_code_language,None) """ if origin_code_language_id is None: errstr = ("The `origin_code_language` '{}' not in the " "`poj.SUBMISSION_CODE_LANGUAGE_ID_TABLE`.") raise ValueError(errstr.format(origin_code_language)) """ return origin_code_language_id def get_judge_info_origin_code_language_id(origin_code_language): """将筛选POJ评测信息时选择的编程语言转换成查询字符串对应的ID """ origin_code_language_id = JUDGE_INFO_CODE_LANGUAGE_ID_TABLE.get( origin_code_language,None) if origin_code_language_id is None: errstr = ("The `origin_code_language`'{}'not int the " "`poj.JUDGE_INFO_LANGUAGE_ID_TABLE`.") raise ValueError(errstr.format(origin_code_language)) return origin_code_language_id def is_finished(status): """ 判断POJ评测状态是否为评测完成 """ return status not in {"Running & Judging", "Compiling", "Waiting"} def get_judge_info_origin_judge_status_id(origin_judge_status=""): """将筛选POJ评测信息时的评测状态转换为查询字符串中对应的ID """ origin_judge_status_id = JUDGE_INFO_JUDGE_STATUS_ID_TABLE.get( origin_judge_status,None) if origin_judge_status_id is None: errstr = ("The `origin_judge_status`'{}' not in the " "poj.JUDGE_INFO_JUDGE_STATUS_ID_TABLE.") raise ValueError(errstr.format(origin_judge_status_id)) return origin_judge_status_id def check_and_handle_htmltext(htmltext): """ 检查并处理POJ的html文本字符串`htmltext` 返回处理后的`htmltext` 对`htmltext`参数会进行类型检查,必须为'bytes'或'str'类型 把window的换行改成linux的换行 """ if isinstance(htmltext,bytes): htmltext = htmltext.decode(CHARSET,'ignore') elif not isinstance(htmltext,str): raise TypeError("The type of `htmltext` is " "{}.".format(type(htmltext))) return htmltext.replace('\r\n','\n') def is_compilation_error(status): """ 判断OJ评测状态是否为编译错误 """ return to_judge_status(status) == stdinfo.CE def to_judge_status(origin_judge_status): """ 将POJ爬下来的评测状态转换成标准评测状态 """ if origin_judge_status in stdinfo.JUDGE_STATUS_SET: return origin_judge_status elif origin_judge_status == "Compile Error": return stdinfo.CE elif origin_judge_status == "System Error": return stdinfo.OJE elif origin_judge_status == "Validator Error": return stdinfo.RC else: # TODO: error: 未知的评测状态 raise ValueError('POJ Unknown origin judge status `{}`.'.format( origin_judge_status )) #TODO 语言的转换 def to_judge_result(judge_info): judge_result = { "origin_oj": "POJ", "origin_pid": judge_info['origin_pid'], "judge_status": to_judge_status(judge_info['origin_judge_status']), "time_cost": judge_info['origin_time_cost'] if judge_info['origin_time_cost'] else '0', "memory_cost": judge_info['origin_memory_cost'] if judge_info['origin_memory_cost'] else '0', "code_language": judge_info['origin_code_language'], "origin_judge_key": judge_info['origin_judge_key'], "origin_judge_status": judge_info['origin_judge_status'], "compilation_info": judge_info.get('compilation_info') } return judge_result <file_sep>/application/account/views.py # coding: utf-8 import logging from sqlalchemy.orm import joinedload, load_only from tornado.web import HTTPError, authenticated from common.web import BaseHandler from db.models import User from account.utils.mixins import UserResourceAPIMixin logger = logging.getLogger("witcoder.account") class UserSettingHandler(BaseHandler, UserResourceAPIMixin): """用户设置视图""" @authenticated def get(self, setting: str): if setting == "basic": user = self.db.session.query(User).options( joinedload("info") ).get(self.current_user.id) if user is None: self.clear_session_cookie(redirect="/index") else: self.render("user/setting/basic.html", user=user) elif setting == "password": self.render("user/setting/password.html") elif setting == "account": user = self.db.session.query(User).options( joinedload("info") ).get(self.current_user.id) if user is None: self.clear_session_cookie(redirect="/index") else: self.render("user/setting/basic.html", user=user) else: raise HTTPError(404) @authenticated def post(self, setting: str): call = { "basic": self.basic_setting, "password": self.password_setting, }.get(setting) if call is None: raise HTTPError(404) return call() def get_basic_setting_form(self): return {"nickname": self.get_body_argument("nickname", ""), "gender": self.get_body_argument("gender", ""), "school": self.get_body_argument("school", ""), "major": self.get_body_argument("major", ""), "url": self.get_body_argument("url", ""), "about": self.get_body_argument("about", "")} def basic_setting(self): """ 个人信息设置 """ form = self.get_basic_setting_form() user = self.db.session.query(User).options( load_only("id", "username", "nickname"), joinedload("info") ).get(self.current_user.id) if user is None: raise HTTPError(500) result = self.user_info_check(form) if result["status"] >= 400: self.write(result) else: user.nickname = form["nickname"] user.info.gender = form["gender"] user.info.school = form["school"] user.info.major = form["major"] user.info.url = form["url"] user.info.about = form["about"] self.db.session.merge(user) try: self.db.session.commit() except: self.db.session.rollback() logger.error("Update user info failed! " "userid: {}".format(user.id), exc_info=True) raise HTTPError(500) else: self.update_current_user(nickname=user.nickname) self.write(result) def get_password_setting_form(self): return {"oldpassword": self.get_body_argument("oldpassword", ""), "newpassword": self.get_body_argument("newpassword", ""), "renewpassword": self.get_body_argument("renewpassword", "")} def password_setting(self): form = self.get_password_setting_form() result = {"status": 400, "message": "Failed", "data": {}} if not 4 <= len(form["oldpassword"]) <= 20: result["data"] = {"field": "oldpassword", "message": "密码长度必须为4到20!"} elif not 4 <= len(form["newpassword"]) <= 20: result["data"] = {"field": "newpassword", "message": "密码长度必须为4到20!"} elif form["newpassword"] != form["renewpassword"]: result["data"] = {"field": "renewpassword", "message": "重复新密码不匹配!"} else: user = self.db.session.query(User).options( load_only("id", "password") ).get(self.current_user.id) if user is None: self.clear_session_cookie() raise HTTPError(500) elif user.verify_password(form["oldpassword"]): user.change_password(form["newpassword"]) self.db.session.merge(user) try: self.db.session.commit() except: self.db.session.rollback() logger.error("Change password failed! " "user id: {}".format(user.id), exc_info=True) raise HTTPError(500) else: result = {"status": 200, "message": "OK"} else: result["data"] = {"field": "oldpassword", "message": "密码错误!"} self.write(result) pass <file_sep>/application/basesite/conf.py # coding: utf-8 from tornado.web import url urls = [ url(r"/", "basesite.views.MainHandler"), url(r"/index", "basesite.views.IndexHandler"), ] ui_methods = {} ui_modules = { "MarkdownEditor": "basesite.ui.MarkdownEditor", } <file_sep>/application/witcoder/settings/local.py # coding: utf-8 from tornado.util import ObjectDict # Tornado settings. debug = True cookie_secret = "<KEY> login_url = '/login' xsrf_cookies = True template_path = 'templates' static_path = 'static' static_url_prefix = "/static/" # Tornext settings. installed_apps = ('common', 'basesite', 'account', 'auth', 'social', 'media', 'vjudge') # Custom settings. SQLALCHEMY = { 'dbms': 'postgresql', 'driver': 'psycopg2', 'host': '127.0.0.1:5432', 'db': 'witcoder', 'username': 'postgres', 'password': '<PASSWORD>', } REDIS = { 'host': 'localhost', 'port': 6379, 'autoconnect': True, } QINIU = { "access_key": "<KEY>", "secret_key": "<KEY>", } UI = ObjectDict({ "cdn": ObjectDict({ "css": ObjectDict({ "bootstrap": "//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css", "fontawesome": "//cdn.bootcss.com/font-awesome/" "4.4.0/css/font-awesome.min.css", "jcrop": "//cdn.bootcss.com/jquery-jcrop/" "0.9.12/css/jquery.Jcrop.min.css", "bootstrap_datetimepicker": "//cdn.bootcss.com/bootstrap-datetimepicker/4.17.37/css" "/bootstrap-datetimepicker.min.css", }), "js": ObjectDict({ "babel": "//cdn.bootcss.com/babel-core/5.8.32/browser.min.js", "react": "//cdn.bootcss.com/react/15.1.0/react-with-addons.min.js", "react_dom": "//cdn.bootcss.com/react/15.1.0/react-dom.min.js", "react_router": "//cdn.bootcss.com/react-router/2.4.1/ReactRouter.min.js", "jquery": "//cdn.bootcss.com/jquery/2.1.4/jquery.min.js", "bootstrap": "//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js", "jquery_pin": "//cdn.bootcss.com/jquery.pin/1.0.1/jquery.pin.min.js", "jcrop": "//cdn.bootcss.com/jquery-jcrop/0.9.12/js/jquery.Jcrop.min.js", "bootstrap_datetimepicker": "//cdn.bootcss.com/bootstrap-datetimepicker/4.17.37/js" "/bootstrap-datetimepicker.min.js", "moment": "//cdn.bootcss.com/moment.js/2.13.0/moment.min.js", "moment_locale": "//cdn.bootcss.com/moment.js/2.13.0" "/moment-with-locales.min.js", }), }), }) <file_sep>/application/common/conf.py # coding: utf-8 urls = [] ui_methods = {} ui_modules = { "BasicUI": "common.ui.BasicUI", "ReactJS": "common.ui.ReactJS", "ReactRouter": "common.ui.ReactRouter", } <file_sep>/application/vjudge/tools/agent.py #-*- coding: utf-8 -*- """ Virtual Judge 代理工具模块 """ from tornext.httpclient import TornextHTTPClient as AsyncHTTPClient __all__ = ['AsyncAgent'] class AsyncAgent(AsyncHTTPClient): """ Virtual Judge 异步代理类 """ pass <file_sep>/application/account/conf.py # coding: utf-8 from tornado.web import url urls = [ url(r"/setting/user/(?P<setting>\w+)", "account.views.UserSettingHandler", name="user-setting"), ] ui_methods = {} ui_modules = { "UserSettingList": "account.ui.UserSettingList", "UserBasicSettingForm": "account.ui.UserBasicSettingForm", "UserPasswordSettingForm": "account.ui.UserPasswordSettingForm", "AvatarChange": "account.ui.AvatarChange", } <file_sep>/application/vjudge/ui.py # -*- coding: utf-8 -*- from tornado.web import UIModule from witcoder.settings import UI class VjudgeNavtabs(UIModule): def render(self, active="index"): return self.render_string("ui/vjudge_navtabs.html", active=active) pass class JQueryPin(UIModule): _js_files = (UI.cdn.js.jquery, UI.cdn.js.jquery_pin) def render(self): return "" def javascript_files(self): return self._js_files def embedded_javascript(self): return '$("#other-info").pin({containerSelector:".container"});' pass class CreateExerciseUI(UIModule): _css_files = (UI.cdn.css.bootstrap_datetimepicker,) _js_files = (UI.cdn.js.jquery, UI.cdn.js.moment, UI.cdn.js.moment_locale, UI.cdn.js.bootstrap_datetimepicker) def render(self): return "" def css_files(self): return self._css_files def javascript_files(self): return self._js_files def embedded_javascript(self): return self.render_string("ui/vjudge/create-exercise.js") pass class ExerciseUI(UIModule): _js_files = (UI.cdn.js.jquery, UI.cdn.js.react, UI.cdn.js.react_dom, UI.cdn.js.babel, UI.cdn.js.react_router, "dist/vjudge_exercise.js") def render(self): return "" def javascript_files(self): return self._js_files pass <file_sep>/application/vjudge/views/exercise.py # -*- coding: utf-8 -*- import logging from tornado.web import authenticated from sqlalchemy.orm import joinedload from common.web import BaseHandler from common.utils import paginate from db.models.vjudge.exercise import Exercise from vjudge.utils.mixins import ExerciseAPIMixin logger = logging.getLogger("witcoder.vjudge") class ExerciseListHandler(BaseHandler): def get(self): # TODO: 参数没有判断非法类型 page = int(self.get_query_argument("page", 1)) count = int(self.get_query_argument("count", 20)) query_clause = self.get_exercises_query_clause() total_page = ((query_clause.count() + count - 1) // count) or 1 # 非法取值范围处理 page = page if page in range(1, total_page + 1) else 1 exercises = query_clause.limit(count).offset( count * (page - 1)).all() self.tplkw.update({"curr_page": page, "total_page": total_page, "page_list": paginate(page, total_page, 10), "exercises": exercises}) self.render("vjudge/exercise-list.html") def get_exercises_query_clause(self): query_clause = self.db.session.query(Exercise).options( joinedload("creater").load_only("id", "username", "nickname") ) return query_clause pass class ExerciseInfoHandler(BaseHandler): @authenticated def get(self, exercise_id): self.render("vjudge/exercise-info.html") pass class CreateExerciseHandler(BaseHandler, ExerciseAPIMixin): @authenticated def get(self): self.render("vjudge/create-exercise.html") @authenticated def post(self): form = self.get_exercise_form() result = self.create_exercise_check(form) if result.get("status") == 200: exercise = Exercise.new(**form) self.db.session.add(exercise) try: self.db.session.commit() except: self.db.session.rollback() logger.error("Create exercise error!", exc_info=True) result = {"status": 500, "message": "Server Error"} self.write(result) def get_exercise_form(self): return { "title": self.get_body_argument("title", ""), "type": self.get_body_argument("type", ""), "mode": self.get_body_argument("mode", ""), "starttime": self.get_body_argument("starttime", ""), "endtime": self.get_body_argument("endtime", ""), "password": self.get_body_argument("password", ""), "problem_id_list": self.get_body_arguments("problem_id"), "problem_title_list": self.get_body_arguments("problem_title"), "creater_id": self.current_user.id, } pass <file_sep>/setup.sh #!/bin/bash pip3 install --allow-all-external -r requirements.txt -i http://pypi.douban.com/simple/ <file_sep>/application/db/models/blog/article.py # -*- coding: utf-8 -*- from sqlalchemy import text from sqlalchemy.orm import relationship from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import String, Integer, Text, DateTime, SmallInteger from db.models import BaseModel class Article(BaseModel): """文章主表Model""" status2id = { "published": 0, # 已发布 "deleted": 1, # 已删除 "draft": 2, # 草稿 "shielded": 3, # 已屏蔽 } id2status = {value: key for key, value in status2id.items()} __tablename__ = "tb_blog_article" # 表结构 id = Column(Integer, primary_key=True, index=True) author_id = Column(Integer, ForeignKey("tb_user.id"), nullable=False, index=True) title = Column(String(100), nullable=False) markdown = Column(Text, nullable=False) htmltext = Column(Text, nullable=False) create_time = Column(DateTime, nullable=False, server_default=text("NOW()")) _status = Column(SmallInteger, nullable=False, default=0, server_default=text("0")) # 关系 author = relationship("User", backref="articles") @property def status(self): return self._status pass class Comment(BaseModel): """文章评论主表Model""" status2id = { "published": 0, # 已发布 "deleted": 1, # 已删除 "draft": 2, # 草稿 "shielded": 3, # 已屏蔽 } id2status = {value: key for key, value in status2id.items()} __tablename__ = "tb_blog_article_comment" # 表结构 id = Column(Integer, primary_key=True, index=True) author_id = Column(Integer, ForeignKey("tb_user.id"), nullable=False, index=True) reply_id = Column(Integer, ForeignKey("tb_blog_article_comment.id"), default=0, server_default=text("0"), index=True) markdown = Column(Text, nullable=False) htmltext = Column(Text, nullable=False) create_time = Column(DateTime, nullable=False, server_default=text("NOW()")) _status = Column(SmallInteger, nullable=False, default=0, server_default=text("0")) # 关系 author = relationship("User", backref="article_comments") @property def status(self): return self._status pass <file_sep>/application/vjudge/zoj/supervision.py import re import time from tornado.ioloop import IOLoop from tornado.gen import Task, coroutine from tornext.tasks import period from utils.log.loggers import vjudge as logger from ..tools.supervision import OnlineJudgeStatus from .attribute import HOST_URL, CHARSET, LOGIN_URL, CHECK_TIME_INTERVAL from .tools import client, check_and_handle_htmltext __all__ = ['status', 'check_status', 'login', 'from_html_verify_login_status'] status = OnlineJudgeStatus() @period(CHECK_TIME_INTERVAL) @coroutine def check_status(): """ ZOJ网络状态检测 """ logger.info("Check ZOJ status") global status response = yield Task(client.get, HOST_URL) if (not response.error) and from_html_verify_login_status(response.body, "WitcoderKayle"): logger.info("Check ZOJ status: Normal.") status.set_normal() return logger.warning("Check ZOJ status: Error.") status.set_error() for _ in range(5): result = yield login("WitcoderKayle", "witcoderkayle") print(result) if result: logger.info("Check ZOJ status: Normal.") status.set_normal() break @coroutine def login(username, password): """ ZOJ 代理登陆 参数: 用户名 username, 密码 <PASSWORD> """ form_data = { 'handle': username, 'password': <PASSWORD>, 'rememberMe': 'on', } client.username = username client.pasword = password response = yield Task(client.post, LOGIN_URL, form_data) response = yield Task(client.get, HOST_URL) return from_html_verify_login_status(response.body, username) def from_html_verify_login_status(htmltext, username): """ return True Or False """ htmltext = check_and_handle_htmltext(htmltext) res_list = _login_verify_re.findall(htmltext) return bool(res_list and res_list[0] == username) _login_verify_re = re.compile(r'class="user_name">(.*?)</span>') <file_sep>/application/media/conf.py # coding: utf-8 from tornado.web import url urls = [ url(r"/media/upload/avatar", "media.views.UploadAvatarHandler"), ] ui_methods = {} ui_modules = {} <file_sep>/application/vjudge/views/problem.py # coding: utf-8 from sqlalchemy.orm import joinedload from tornado.web import HTTPError from db.models.vjudge import Problem from common.utils import paginate from vjudge.views import VjudgeHandler class ProblemListHandler(VjudgeHandler): """题目列表视图""" def get(self): # TODO: 参数没有判断非法类型 page = int(self.get_query_argument("page", 1)) count = int(self.get_query_argument("count", 100)) total_page = int( (self.db.session.query(Problem).count() + count - 1) // count ) or 1 # 非法取值范围处理 page = page if page in range(1, total_page + 1) else 1 problems = self.db.session.query(Problem).options( joinedload("statistics") ).order_by( Problem.remote_oj.asc(), Problem.remote_pid.asc() ).limit(count).offset(count * (page - 1)).all() self.tplkw.update({ "curr_page": page, "total_page": total_page, "page_list": paginate(page, total_page, 10), "problems": problems, }) self.render("vjudge/problem-list.html") pass class ProblemInfoHandler(VjudgeHandler): """题目信息视图""" def get(self, pid, kind): problem = self.db.session.query(Problem).get(pid) if problem is None: raise HTTPError(404) if kind == "": self.tplkw["problem"] = problem self.render("vjudge/problem-info.html") else: raise HTTPError(404) def write_error(self, status_code, **kwargs): pass pass <file_sep>/application/common/regex.py # -*- coding: utf-8 -*- import re # 用户名为长度2到20的单词字符 username_re = re.compile(r'^[A-Za-z0-9_]{2,20}$') # 密码长度必须为4~20,任意字符 password_re = re.compile(r'^.{4,20}$') # 昵称长度为1~15个字符 nickname_re = re.compile(r'^\w{1,15}$') # Email正则表达式 email_re = re.compile(r'^[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+$') # 换行符正则表达式 linesep_re = re.compile(r'(?:\r\n|\n|\r)') <file_sep>/application/vjudge/generic.py # -*- coding: utf-8 -*- """ Virtual Judge 通用模块 该模块提供一个通用的对支持的 Online Judge 进行虚拟评测的接口。 """ from vjudge.remote import hdoj SUPPORTED_ONLINE_JUDGE = (hdoj, ) def get_online_judge(name: str): name = name.upper() for oj in SUPPORTED_ONLINE_JUDGE: if name in oj.COMMON_NAMES: return oj return None <file_sep>/application/vjudge/utils/mixins.py # -*- coding: utf-8 -*- from datetime import datetime from sqlalchemy.orm import load_only from db.models.vjudge.exercise import Exercise from db.models.vjudge.problem import Problem from common.utils import DATETIME_FORMAT, DAYS, HOURS class ExerciseAPIMixin(object): def create_exercise_check(self, data): result = {"status": 400, "message": "Failed", "data": {}} try: # 处理开始时间类型 data["starttime"] = datetime.strptime(data["starttime"], DATETIME_FORMAT) except: result["data"] = {"field": "starttime", "message": "时间格式错误!"} return result try: # 处理结束时间类型 data["endtime"] = datetime.strptime(data["endtime"], DATETIME_FORMAT) except: result["data"] = {"field": "endtime", "message": "时间格式错误!"} return result if not data["title"]: result["data"] = {"field": "title", "message": "训练标题不能为空!"} elif len(data["title"]) > Exercise.title.type.length: result["data"] = {"field": "title", "message": "训练标题太长!"} elif (not data["type"].isdigit() or int(data["type"]) not in Exercise.id2type): result["data"] = {"field": "type", "message": "训练类型错误!"} elif (not data["mode"].isdigit() or int(data["mode"]) not in Exercise.id2mode): result["data"] = {"field": "mode", "message": "训练模式错误!"} elif data["starttime"] <= datetime.now(): result["data"] = {"field": "starttime", "message": "开始时间不能早于当前时间!"} elif not (HOURS <= data["endtime"] - data["starttime"] <= 60 * DAYS): result["data"] = {"field": "endtime", "message": "训练时间必须在1小时和60天之间!"} elif (int(data["type"]) == Exercise.type2id.get("private") and not data["password"]): result["data"] = {"field": "password", "message": "私有类型训练请设置密码!"} else: try: self.exercise_problem_check(data, result) except: result["data"] = {"field": "problem", "message": "题目设置有误!"} else: data["type"] = int(data["type"]) data["mode"] = int(data["mode"]) return result if result["data"] else {"status": 200, "message": "OK"} def exercise_problem_check(self, data, result): data["problem_id_list"] = list(map(int, data["problem_id_list"])) data["problem_title_list"] = list(map(str.strip, data["problem_title_list"])) assert len(data["problem_id_list"]) == len(data["problem_title_list"]) problem_list = [] for index, problem_id in enumerate(data["problem_id_list"], 1): problem = self.db.session.query(Problem).options( load_only("id", "title") ).get(problem_id) if problem is None: result["data"] = {"field": "problem", "message": "第{}题验证失败!".format(index)} return problem_list.append(problem) for index, problem_title in enumerate(data["problem_title_list"]): if len(problem_title) > Problem.title.type.length: result["data"] = {"field": "problem", "message": "第{}题题目标题太长!".format(index + 1)} return if problem_list[index].title == problem_title: data["problem_title_list"] = "" pass <file_sep>/application/common/ui.py # -*- coding: utf-8 -*- from tornado.web import UIModule from witcoder.settings import UI class BasicUI(UIModule): _css_files = (UI.cdn.css.bootstrap, UI.cdn.css.fontawesome, "/static/style.css") _js_files = (UI.cdn.js.jquery, UI.cdn.js.bootstrap, "/static/js/witcoder.js") def render(self): return "" def css_files(self): return self._css_files def javascript_files(self): return self._js_files pass class ReactJS(UIModule): _js_files = (UI.cdn.js.react, UI.cdn.js.react_dom, UI.cdn.js.babel) def render(self): return "" def javascript_files(self): return self._js_files pass class ReactRouter(UIModule): _js_files = (UI.cdn.js.react, UI.cdn.js.react_dom, UI.cdn.js.babel, UI.cdn.js.react_router) def render(self): return "" def javascript_files(self): return self._js_files pass <file_sep>/application/vjudge/remote/poj.py import re import time import base64 import logging from urllib.parse import urlencode from html.parser import unescape from tornado.gen import coroutine, sleep from tornado.httpclient import AsyncHTTPClient from common.utils import convert_linesep, HTMLFormatter from vjudge.exceptions import (ProblemNotFound, SubmitError, FetchError) from vjudge.utils import CommonClient logger = logging.getLogger() config = logging.FileHandler('log.txt') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') config.setFormatter(formatter) logger.addHandler(config) logger.setLevel(logging.DEBUG) # 网页编码 CHARSET = 'utf-8' # 网址 HOST_URL = 'http://poj.org' # 标准名 NAME = 'POJ' # 常用名 COMMON_NAMES = {'POJ', 'PKU'} class POJMixin(object): """ POJ 虚拟评测基础类 """ _problem_info_url = HOST_URL + "/problem?id={}" _problem_list_url = HOST_URL + "/problemlist?volume={}" _submitcode_url = HOST_URL + "/submit" _submission_list_url = HOST_URL + ("/status?problem_id={}&user_id={}" "&result={}&language={}") _submission_info_url = HOST_URL + "/showsource?solution_id={}" _submission_compilation_info_url = HOST_URL + ("/showcompileinfo?" "solution_id={}") _login_url = HOST_URL + "/login" # POJ的Submission查询表单时使用 # 用于将编程语言字符串转换成对应提交表单时使用的value _submission_language_id = { "All": "", "G++": 0, "GCC": 1, "Java": 2, "Pascal": 3, "C++": 4, "C": 5, "Fortran": 6, } # POJ的Submission查询表单时使用 # 用于将评测状态字符串转换成对应提交表单时使用的value # 并不是所有的评测状态都在这个表里,有些评测状态不提供筛选 # 比如等待状态以及`System Error` _judge_status_id = { "All": "", "Accepted": 0, "Presentation Error": 1, "Time Limit Exceeded": 2, "Memory Limit Exceeded": 3, "Wrong Answer": 4, "Runtime Error": 5, "Output Limit Exceeded": 6, "Compile Error": 7, } # POJ提交代码表单时使用 # 用于将编程语言字符串转换成对应提交表单时使用的value _submitcode_language_id = { 'G++': 0, 'GCC': 1, 'Java': 2, 'Pascal': 3, 'C++': 4, 'C': 5, 'Fortran': 6, } def get_problem_info_url(self, remote_pid: str) -> str: """ 获取题目URL :param remote_pid str :POJ题目编号, 纯数字 ,1000以上为有效 """ return self._problem_info_url.format(remote_pid) def get_problem_list_url(self, volume=1) -> str: """ 获取题目列表URL :param volume int :POJ题目页码的页数,默认是第一页 """ return self._problem_list_url.format(volume) def get_submitcode_url(self): """ 获取POJ提交代码的URL """ return self._submitcode_url def get_submission_info_url(self, remote_key) -> str: """ 查看提交信息 :param remote_key str: POJ提交列表中的RUN ID,是submission的唯一标识符 """ return self._submission_info_url.format(remote_key) def get_submission_list_url(self, remote_pid="", username="", language="All", remote_status="All") -> str: """ 获取提交列表的信息 :param remote_pid str: POJ题目编号,是POJ题目的唯一标识符 :param username str: POJ的submission提交者的用户名 :param language str: POJ的submission的编程语言 :param remote_status str: POJ的submission的评测状态 """ language_id = self._submission_language_id[language] remote_status_id = self._judge_status_id[remote_status] return self._submission_list_url.format( remote_pid, username, remote_status_id, language_id ) def refine_html(self, htmltext) -> str: if isinstance(htmltext, bytes): htmltext = htmltext.decode(CHARSET, 'ignore') return convert_linesep(htmltext) class POJSpidef(POJMixin): """ POJ爬虫类""" _httpclient = AsyncHTTPClient() _problem_title_re = re.compile(r'<title>\d{3,} -- ([\s\S]*?)</title>') _problem_time_limit_re = re.compile(r'<b>Time Limit:</b> (\d{3,})MS</td>') _problem_memory_limit_re = re.compile( r'<b>Memory Limit:</b> (\d{3,})K</td>' ) _problem_special_judge_re = re.compile( r'<td style="font-weight:bold; color:red;">Special Judge</td>' ) _problem_description_re = re.compile( r'<p class="pst">Description</p><div class=' '"ptx" lang="en-US">([\s\S]*?)</div>' ) _problem_input_re = re.compile( r'<p class="pst">Input</p><div class="' 'ptx" lang="en-US">([\s\S]*?)</div>' ) _problem_output_re = re.compile( r'<p class="pst">Output</p><div class' '="ptx" lang="en-US">([\s\S]*?)</div>' ) _problem_sample_input_re = re.compile( r'<p class="pst">Sample Input</p>' '<pre class="sio">([\s\S]*?)</pre>' ) _problem_sample_output_re = re.compile( r'<p class="pst">Sample Output</p>' '<pre class="sio">([\s\S]*?)</pre>' ) _problem_source_re = re.compile( r'<p class="pst">Source</p><div class=' '"ptx" lang="en-US">([\s\S]*?)</div>' ) _problem_hint_re = re.compile( r'<p class="pst">Hint</p><div class=' '"ptx" lang="en-US">([\s\S]*?)</div>' ) _problem_volume_re = re.compile( r'<a href=problemlist\?volume=\d+>' '<font[^<>].*?>(\d+)</font></a>' ) _problem_list_re = re.compile( r'<td>(\d+)</td><td align=left><a lang="en-US" href=' 'problem\?id=\d+>([\s\S]*?)</a></td>' ) @coroutine def fetch_problem_volumes(self) -> str: """ 获取POJ题目页列表 """ url = self.get_problem_list_url() try: response = yield self._httpclient.fetch(url) except Exception: logger.error("GET {} error".format(url), exc_info=True) raise else: htmltext = self.refine_html(response.body) return self.match_problem_volumes(htmltext) @coroutine def fetch_problem_list(self, volume=1) -> list: """ 获取POJ题目列表 默认为1""" url = self.get_problem_list_url(volume) print(url) try: response = yield self._httpclient.fetch(url) except Exception: logger.error("GET {} error".format(url), exc_info=True) raise else: htmltext = self.refine_html(response.body) return self._problem_list_re.findall(htmltext) def match_problem_volumes(self, htmltext) -> list: volumes = map(int, set(self._problem_volume_re.findall(htmltext))) volumes = list(volumes) volumes.sort() return volumes def match_problem_list(self, htmltext) -> list: """ 从HTML中匹配出题目的信息""" htmltext = self.refine_html(htmltext) return [ (remote_pid.strip(), title.strip().replace('\"', '"')) for remote_pid, title in self._problem_list_re.findall(htmltext) ] @coroutine def fetch_problem_info(self, remote_pid: str) -> dict: """ 获取题目标准信息 """ remote_pid = str(remote_pid) url = self.get_problem_info_url(remote_pid) try: response = yield self._httpclient.fetch(url) except Exception: logger.error("GET {} error".format(url), exc_info=True) raise htmltext = self.refine_html(response.body) try: raw_info = self.match_problem_raw_info(htmltext) except: logger.error("Matching `POJ-{}` info error!".format(remote_pid), exc_info=True) raise else: raw_info['remote_pid'] = remote_pid raw_info['url'] = url return self.refine_problem_raw_info(raw_info) def match_problem_raw_info(self, htmltext) -> dict: if htmltext.find('Can not find problem') > -1: raise ProblemNotFound('Problem Not Found') try: raw_info = { "remote_oj": NAME, "title": self._match_problem_title(htmltext), "time_limit": self._match_problem_time_limit(htmltext), "memory_limit": self._match_problem_memory_limit(htmltext), "special_judge": self._match_problem_special_judge(htmltext), "description": self._match_problem_description(htmltext), "input": self._match_problem_input(htmltext), "output": self._match_problem_output(htmltext), "sample_input": self._match_problem_sample_input(htmltext), "sample_output": self._match_problem_sample_output(htmltext), "hint": self._match_problem_hint(htmltext), "source": self._match_problem_source(htmltext), } except: raise return raw_info def refine_problem_raw_info(self, raw_info: dict) -> dict: formatter = HTMLFormatter(joinurl=True, url=raw_info['url']) for key in ("description", "input", "output", "sample_input", "sample_output", "source"): # 清空在其他地方的Hint文本 raw_info[key] = self._problem_hint_re.sub("", raw_info[key]) # 相对URL转换处理 TODO 下划线不见 raw_info[key] = formatter.format_html(raw_info[key]) # 单独处理Hint raw_info["hint"] = formatter.format_html(raw_info["hint"]) return raw_info def _match_problem_title(self, htmltext: str) -> str: results = self._problem_title_re.findall(htmltext) if len(results) == 0: raise Exception("Can't match problem `title`!") elif len(results) > 1: raise Exception("Problem `title` of the matching not unique!") return results[0].strip() def _match_problem_time_limit(self, htmltext: str) -> int: results = self._problem_time_limit_re.findall(htmltext) if len(results) == 0: raise Exception("Can't match problem `time_limit`!") elif len(results) > 1: raise Exception("Problem `time_limit` of the matching not unique!") return int(results[0]) def _match_problem_memory_limit(self, htmltext: str) -> int: results = self._problem_memory_limit_re.findall(htmltext) if len(results) == 0: raise Exception("Can't match problem `memory_limit`!") elif len(results) > 1: raise Exception("Problem `memory_limit` of the matching" " not unique!") return int(results[0]) def _match_problem_special_judge(self, htmltext: str) -> bool: results = self._problem_special_judge_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `special_judge` of the matching" " not unique!") return bool(len(results)) def _match_problem_description(self, htmltext: str) -> str: results = self._problem_description_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `description` of the matching" " not unique!") return results[0].strip() if len(results) else "" def _match_problem_input(self, htmltext: str) -> str: results = self._problem_input_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `input` of the matching not unique!") return results[0].strip() if len(results) else "" def _match_problem_output(self, htmltext: str) -> str: results = self._problem_output_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `output` of the matching not unique!") return results[0].strip() if len(results) else "" def _match_problem_sample_input(self, htmltext: str) -> str: results = self._problem_sample_input_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `sample_input` of the matching" " not unique!") return results[0].strip() if len(results) else "" def _match_problem_sample_output(self, htmltext: str) -> str: results = self._problem_sample_output_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `sample_output` of the matching" " not unique!") return results[0].strip() if len(results) else "" def _match_problem_hint(self, htmltext: str) -> str: results = self._problem_hint_re.findall(htmltext) return '<br>'.join(results) if len(results) else "" def _match_problem_source(self, htmltext: str) -> str: results = self._problem_source_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `source` of the matching not unique!") return results[0].strip() if len(results) else "" pass class POJClient(CommonClient, POJMixin): _submission_info_re = re.compile( r'<tr align=center><td>(?P<remote_key>\d+?)</td>' '<td><a href=userstatus\?user_id=(?P<username>.+?)>.*?' '</a></td><td><a href=problem\?id=(?P<remote_pid>\d{4,})>\d{4,}</a>' '</td><td>.*?<font color=.+?>(?P<remote_status>.+?)' '</font>.*?</td><td>(?P<memory_cost>\d+?K|\d*?)</td>' '<td>(?P<time_cost>\d+?MS|\d*?)</td>' '<td><a href=showsource\?solution_id=\d{1,} target=_blank>' '(?P<language>GCC|G\+\+|C|C\+\+|Java|Pascal|Fortran)</a>' '</td><td>(?P<length>\d+?)B</td><td>' '(?P<submit_time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})</td></tr>' ) _submission_source_code_re = re.compile( r'<pre .*?style="font-family:Courier New,Courier,monospace">' '(?P<source_code>[\s\S]*?)</pre>' ) _submission_compilation_info_re = re.compile( r'<pre>(?P<compilation_info>[\s\S]*?)</pre>' ) # POJ 时间格式 _POJ_TIME_FORMAT = '%Y-%m-%d %X' # 登录重试次数 LOGIN_RETRY_TIMES = 3 # 状态检查周期,20分钟 PERIOD_OF_CHECK = 20 * 60 def __init__(self, username=None, password=<PASSWORD>, *args, **kwargs): super(POJClient, self).__init__() self.username = username self.password = <PASSWORD> @coroutine def login(self, username=None, password=None, *args, **kwargs): self.username = username or self.username self.password = <PASSWORD> or <PASSWORD> if not self.username or not self.password: raise ValueError("`POJClient.login` require `username` and" " `password`!") body = urlencode({ 'user_id1': self.username, 'password1': <PASSWORD>, 'B1': 'login', 'url': '.', }) response = yield self.httpclient.fetch( self._login_url, method="POST", body=body, raise_error=False ) response = yield self.httpclient.fetch( HOST_URL, raise_error=False ) htmltext = self.refine_html(response.body) if htmltext.find('{}'.format(self.username)) > -1: logger.info("POJClient `{}` login success!".format(self.username)) self.set_status("Normal") else: log_list = ['POJ login error!'] if response.error: log_list.extend(( "{} {}.".format(response.code, response.reason), "url: {}.".format(response.effective_url), "headers:" )) log_list.extend( [" {}: {}".format(k, v) for k, v in sorted(response.headers.get_all())] ) logger.error('\n'.join(log_list)) self.set_status("Error") return self.status @coroutine def check_status(self): """ 检查POJ的登陆状态,必要是需要重新登陆 """ response = yield self.httpclient.fetch(HOST_URL, raise_error=False) htmltext = self.refine_html(response.body) if htmltext.find('{}'.format(self.username)) > -1: self.set_status('Normal') logger.info("POJClient check status :Normal.") else: self.set_status("Error") logger.info("HDOJClient check status: Error.") for i in range(self.LOGIN_RETRY_TIMES): login_status = yield self.login() logger.info("HDOJClient retry login, the {} time: " "{}.".format(i + 1, login_status)) if login_status == "Normal": break yield sleep(5) # 5秒重试 @coroutine def submit_code(self, remote_pid, source_code: str, language: str, *args, **kwargs): """ POJ提交代码 """ form_data = urlencode({ "problem_id": remote_pid, "language": self._submitcode_language_id.get(language), "source": base64.b64encode(source_code.encode('utf-8')).decode(), "submit": 'Submit', "encoded": '1', }) response = yield self.httpclient.fetch( self._submitcode_url, method="POST", body=form_data ) result = (response.effective_url, response.code) if result != ('http://poj.org/status', 200): log_list = ['Submit result error!'] log_list.extend([ "{} {}.".format(response.code, response.reason), "url: {}.".format(response.effective_url), "headers:" ]) log_list.extend( [" {}: {}".format(k, v) for k, v in sorted(response.headers.get_all())] ) raise SubmitError('\n'.join(log_list)) @coroutine def fetch_result(self, remote_pid, source_code, language, time_limit='1000'): """ 爬取提交结果 """ raw_info_list = yield self._fetch_submission_list( remote_pid=remote_pid, source_code=source_code, language=language ) raw_info = yield self._find_result(raw_info_list, source_code=source_code) time_limit = int(time_limit) for waittime in (3*time_limit, time_limit, time_limit, time_limit): wait_futrue = sleep(waittime) if self.judge_finished(raw_info['remote_status']): break yield wait_futrue raw_info = self._fetch_submission(raw_info['remote_key']) else: if not self.judge_finished(raw_info['remote_status']): pass if self.is_compilation_error(raw_info['remote_status']): raw_info['compilation_info'] = yield self.get_compilation_info( raw_info['remote_key'] ) return raw_info @coroutine def get_compilation_info(self, remote_key): url = self._submission_compilation_info_url.format(remote_key) try: response = yield self.httpclient.fetch(url) except: pass else: htmltext = self.refine_html(response.body) return self.match_compilation_info(htmltext) def is_compilation_error(self, remote_status): return True if remote_status == 'Compile Error' else False def judge_finished(self, remote_status): return remote_status not in { "Running & Judging", "Compiling", "Waiting" } @coroutine def _fetch_submission_list(self, remote_pid, source_code, language): url = self.get_submission_list_url( remote_pid=remote_pid, username=self.username, language=language ) response = yield self.httpclient.fetch(url, raise_error=False) htmltext = self.refine_html(response.body) return self.match_submission_raw_info_list(htmltext) def match_submission_raw_info_list(self, htmltext: str) -> list: """从HTML文本中匹配出提交列表 该函数返回元素类型为字典的列表。 元素样例如下:: { "remote_key": ..., # RunID,评测信息key "username": ..., # HDOJ代码提交者的用户名 "remote_pid": ..., # 远程OJ的题目编号 "remote_status": ..., # 远程OJ的评测状态,HTML "memory_cost": ..., # 程序的内存消耗 "time_cost": ..., # 程序的时间消耗 "language": ..., # 编程语言,HDOJ的数据 "length": ..., # 代码长度,HDOJ的数据 "submit_time": ..., # 远程OJ的提交时间 } """ results = self._submission_info_re.findall(htmltext) for index, value in enumerate(results): results[index] = { k: value[i-1] for k, i in self._submission_info_re.groupindex.items() } return results @coroutine def _find_result(self, raw_info_list: list, source_code: str): source_code = convert_linesep(source_code) current_time = time.time() for raw_info in raw_info_list: raw_info_time = time.mktime(time.strptime( raw_info['submit_time'], self._POJ_TIME_FORMAT )) if abs((current_time-raw_info_time)) <= 3600: url = self.get_submission_info_url(raw_info['remote_key']) response = yield self.httpclient.fetch(url, raise_error=False) if response.error is not None: logger.error("GET {} error".format(response.effective_url)) continue htmltext = self.refine_html(response.body) remote_code = self._submission_source_code_re.findall(htmltext) if source_code == unescape(remote_code[0]): return raw_info raise FetchError("Remote submission not found!") def match_compilation_info(self, htmltext: str) -> str: results = self._submission_compilation_info_re.findall(htmltext) if len(results) == 0: raise FetchError("Compilation info not found") return results[0] spider = POJSpidef() pojclient = POJClient("yangjiaronga", '123456789') <file_sep>/application/account/ui.py # -*- coding: utf-8 -*- from tornado.web import UIModule from witcoder.settings import UI class UserSettingList(UIModule): _css_files = (UI.cdn.css.bootstrap,) def render(self, setting): return self.render_string("ui/account/user_setting_list.html", setting=setting) def css_files(self): return self._css_files pass class UserBasicSettingForm(UIModule): _js_files = (UI.cdn.js.jquery,) def render(self, user): return self.render_string("ui/account/user_basic_setting_form.html", user=user) def embedded_javascript(self): return self.render_string("ui/account/user_basic_setting_form.js") pass class UserPasswordSettingForm(UIModule): _js_files = (UI.cdn.js.jquery,) def render(self): return self.render_string("ui/account/user_password_setting_form.html") def embedded_javascript(self): return self.render_string("ui/account/user_password_setting_form.js") pass class AvatarChange(UIModule): _js_files = (UI.cdn.js.jquery, UI.cdn.js.jcrop,) _css_files = (UI.cdn.css.jcrop,) def render(self): return "" def javascript_files(self): return self._js_files def css_files(self): return self._css_files def embedded_javascript(self): return self.render_string("ui/account/change_avatar.js") pass <file_sep>/application/vjudge/tools/stdinfo.py #-*- coding: utf-8 -*- """ Virtual Judge 标准信息模块 """ __all__ = ['JUDGE_STATUS_SET', 'AC', 'WA', 'RE', 'TLE', 'MLE', 'OLE', 'CE', 'PE', 'SE', 'RC', 'FE', 'VE', 'S', 'OJE'] # 标准评测状态简写 AC = "Accepted" # 提交通过 WA = "Wrong Answer" # 答案错误 RE = "Runtime Error" # 运行时错误 CE = "Compilation Error" # 编译错误 PE = "Presentation Error" # 答案格式错误 TLE = "Time Limit Exceeded" # 运行时间超过限制 MLE = "Memory Limit Exceeded" # 运行内存超过限制 OLE = "Output Limit Exceeded" # 程序输出超过限制 OJE = "Online Judge Error" # 远端评测系统故障 RC = "Restricted Code" # 受限代码 SE = "Submit Error" # 提交错误 FE = "Fetch Error" # 爬取结果错误 VE = "Vjudge Error" # 虚拟评测故障 S = "Submitting" # 提交中 # 标准评测状态集合 JUDGE_STATUS_SET = {AC, WA, RE, CE, PE, TLE, MLE, OLE, OJE, RC, SE, FE, VE, S} <file_sep>/application/vjudge/conf.py # coding: utf-8 from tornado.web import url urls = [ url(r'/vjudge/', 'vjudge.views.index.IndexHandler'), url(r'/vjudge/problem/', 'vjudge.views.problem.ProblemListHandler'), url(r'/vjudge/problem/(?P<pid>\d+)/(?P<kind>\w*)', 'vjudge.views.problem.ProblemInfoHandler'), url(r'/vjudge/exercise/', 'vjudge.views.exercise.ExerciseListHandler'), url(r'/vjudge/exercise/(\d+)/', 'vjudge.views.exercise.ExerciseInfoHandler'), url(r'/vjudge/exercise/create', 'vjudge.views.exercise.CreateExerciseHandler'), url(r'/vjudge/submission/', 'vjudge.views.submission.SubmissionListHandler'), url(r'/vjudge/submission/(\d+)', 'vjudge.views.submission.SubmissionInfoHandler'), url(r'/vjudge/submit/(problem|exercise|contest)', 'vjudge.views.submit.SubmitHandler'), # RESTful API url(r'/api/vjudge/problem(?:|/(\d+))', 'vjudge.views.api.ProblemRESTfulAPIHandler'), url(r'/api/vjudge/submission(?:|/(\d+))', 'vjudge.views.api.SubmissionRESTfulAPIHandler'), ] ui_methods = {} ui_modules = { 'VjudgeNavtabs': 'vjudge.ui.VjudgeNavtabs', 'JQueryPin': 'vjudge.ui.JQueryPin', 'CreateExerciseUI': 'vjudge.ui.CreateExerciseUI', 'ExerciseUI': 'vjudge.ui.ExerciseUI', } <file_sep>/application/vjudge/hdoj/attribute.py #-*- coding: utf-8 -*- """ Virtual Judge HDOJ 属性模块 """ # HDOJ 主页的url HOST_URL = 'http://acm.hdu.edu.cn' # HDOJ标准名 STD_NAME = "HDOJ" # HDOJ 的常用名集合,全部使用大写 NAME_SET = {"HDOJ", "HDU"} # 网页编码 CHARSET = 'gbk' # 账号登录URL LOGIN_URL = HOST_URL + '/userloginex.php?action=login' # 账号登录HTTP方法 LOGIN_METHOD = 'POST' # 代码提交URL SUBMIT_CODE_URL = HOST_URL + '/submit.php?action=submit' # 代码查看URL VIEW_CODE_URL = HOST_URL + '/viewcode.php' # 编译信息查看URL VIEW_COMPILATION_INFO_URL = HOST_URL + '/viewerror.php' # 评测信息URL VIEW_JUDGE_STATUS_URL = HOST_URL + '/status.php' # 代码提交编程语言编号表 SUBMISSION_CODE_LANGUAGE_ID_TABLE = { } # 评测信息编程语言编号表 JUDGE_INFO_CODE_LANGUAGE_ID_TABLE = { "All": 0, "G++": 1, "GCC": 2, "C++": 3, "C": 4, "Pascal": 5, "Java": 6, "C#": 7, } # 评测信息评测状态编号表 JUDGE_INFO_JUDGE_STATUS_ID_TABLE = { "All": 0, "Accepted": 5, "Wrong Answer": 6, "Runtime Error": 7, "Compilation Error": 12, "Presentation Error": 8, "Time Limit Exceeded": 9, "Memory Limit Exceeded": 10, "Output Limit Exceeded": 11, } # HDOJ检查代理情况的时间间隔,单位为秒 CHECK_TIME_INTERVAL = 20 * 60 # 20分钟检查一次 <file_sep>/application/vjudge/remote/utils.py # -*- coding: utf-8 -*- from datetime import datetime from tornext.httpclient import TornextHTTPClient from tornext.tasks import PeriodTask class CommonClient(object): """虚拟评测通用客户端类""" _httpclient = TornextHTTPClient(cookiejar="/tmp/witcoder-vjudge.cookiejar") def __init__(self): self._status = "Unknown" self._last_check_time = None @property def httpclient(self): return self._httpclient @property def status(self): return self._status def set_status(self, status: str): """设置虚拟评测客户端的状态""" if status not in {"Unknown", "Normal", "Error"}: raise ValueError("Wrong value '{}'!".format(status)) self._status = status t = datetime.now() self.last_check_time = datetime(t.year, t.month, t.day, t.hour, t.minute, t.second) def check_status(self): """检查虚拟评测客户端状态 由子类实现该方法,作为一个循环任务来启动。 该方法的功能为维持虚拟评测客户端的登录状态以及探测在线评测网站的状态。 """ raise NotImplementedError def start(self): """开始虚拟评测客户端状态的检查任务""" self.task = PeriodTask(self.check_status, self.PERIOD_OF_CHECK).register() pass def stop(self): """停止虚拟评测客户端状态的检查任务""" pass pass <file_sep>/application/vjudge/hdoj/agent.py #-*- coding: utf-8 -*- """ Virtual Judge HDOJ代理模块 """ import re from html import unescape from tornado.gen import coroutine, Task, sleep from utils.log.loggers import vjudge as logger from ..exc import FetchError, VjudgeError, SubmitError from .attribute import (SUBMIT_CODE_URL, VIEW_JUDGE_STATUS_URL, CHARSET, VIEW_CODE_URL, VIEW_COMPILATION_INFO_URL) from .tools import (check_and_handle_htmltext, client, is_compilation_error, get_judge_info_origin_judge_status_id, judge_finished, get_judge_info_origin_code_language_id, to_judge_result, get_submission_origin_code_language_id, to_origin_code_language) __all__ = ['submit_code', 'get_judge_info_list_url', 'get_judge_info', 'from_html_get_judge_info_list', 'get_source_code_url', 'get_source_code', 'from_html_get_source_code', 'from_origin_judge_key_get_judge_info', 'get_compilation_info_url', 'get_compilation_info', 'from_html_get_compilation_info'] @coroutine def submit_code(origin_pid, code_language, source_code): """ HDOJ代理提交题目代码 参数: `origin_pid`: 源OJ的题目编号 `code_language`: Virtual Judge 标准格式编程语言 `source_code`: 提交的源代码 异常: `vjudge.exc.FetchError`: 爬取失败 """ origin_code_language = to_origin_code_language(code_language) form_data = { "check": 0, "problemid": origin_pid, "language": get_submission_origin_code_language_id( origin_code_language ), "usercode": source_code.encode(CHARSET) } response = yield Task(client.post, SUBMIT_CODE_URL, form_data) logger.info('Submit code: response time {}.'.format(response.request_time)) if response.error: logger.error('Submit Error: submit response error -> {}.'.format( response.error )) return SubmitError(response.error) elif response.code != 200 or response.effective_url != VIEW_JUDGE_STATUS_URL: logger.error('Submit Error: ???.') return SubmitError('HTTPResponse `code` error, `code` is {}.'.format( response.code )) judge_info = yield get_judge_info( username=client.username, origin_pid=origin_pid, origin_code_language=origin_code_language, source_code=source_code ) if isinstance(judge_info, VjudgeError): return judge_info return to_judge_result(judge_info) def get_judge_info_list_url(origin_judge_key='', username='', origin_pid='', origin_code_language="All", origin_judge_status="All"): """ 获取HDOJ评测信息列表url """ item = [VIEW_JUDGE_STATUS_URL, '?first=', origin_judge_key, '&pid=', origin_pid, '&user=', username] item += ['&lang=', get_judge_info_origin_code_language_id( origin_code_language )] item += ['&status=', get_judge_info_origin_judge_status_id( origin_judge_status )] return ''.join(map(str, item)) @coroutine def get_judge_info(username=None, origin_pid=None, origin_code_language=None, source_code=None, origin_judge_key=None): """ HDOJ代理获取提交后的评测信息 异常: `vjudge.exc.FetchError`: 爬取错误 """ if origin_judge_key is not None: judge_info = yield from_origin_judge_key_get_judge_info( origin_judge_key ) else: judge_info = yield from_other_info_get_judge_info( username=username, origin_pid=origin_pid, source_code=source_code, origin_code_language=origin_code_language ) if isinstance(judge_info, VjudgeError): return judge_info # 确保得到评测完成时的状态 while True: if judge_finished(judge_info['origin_judge_status']): break yield sleep(1) judge_info = yield from_origin_judge_key_get_judge_info( judge_info['origin_judge_key'] ) # 如果评测结果为编译错误,将编译错误信息一并爬取 if is_compilation_error(judge_info['origin_judge_status']): compilation_info = yield get_compilation_info( judge_info['origin_judge_key'] ) judge_info['compilation_info'] = compilation_info return judge_info @coroutine def from_origin_judge_key_get_judge_info(origin_judge_key): """ 根据RunID直接定位获取HDOJ代理提交后的评测信息 """ url = get_judge_info_list_url(origin_judge_key=origin_judge_key) response = yield Task(client.get, url) if response.error: # TODO: 错误处理 pass htmltext = response.body res_list = from_html_get_judge_info_list(htmltext) if len(res_list) == 0: # error: 可能错误的key,无法定位 # TODO: raise pass return res_list[0] @coroutine def from_other_info_get_judge_info(username, origin_pid, origin_code_language, source_code): """ 根据非key信息获取相关评测信息列表 """ url = get_judge_info_list_url(username=username, origin_pid=origin_pid, origin_code_language=origin_code_language) response = yield Task(client.get, url) # TODO: 访问url失败的处理 judge_info_list = from_html_get_judge_info_list(response.body) # 逐一匹配源代码 for judge_info in judge_info_list: origin_source_code = yield get_source_code(judge_info['origin_judge_key']) if origin_source_code.strip() == source_code.strip(): return judge_info # 逐一匹配依旧没有找到对应的,Fetch Error # 暂时这样处理了只能 return FetchError("Can't find remote submission.") def from_html_get_judge_info_list(htmltext): """ 从HTML文本中匹配出评测状态列表 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 该函数返回值为字典类型的列表。 字典的结构如下: { "origin_judge_key": ..., # RunID,评测信息的key "origin_submit_time": ..., # 提交时间 "origin_judge_status": ..., # 评测状态,HTML形式 "origin_pid": ..., # 题目编号 "origin_time_cost": ..., # 花费时间,单位为MS "origin_memory_cost": ..., # 花费内存,单位为KB "origin_code_length": ..., # 代码长度,单位为B "origin_code_language": ..., # 编程语言,HDOJ标准的 "origin_username": ..., # HDOJ代理的账号 } """ htmltext = check_and_handle_htmltext(htmltext) tuple_list = _judge_info_re.findall(htmltext) # 获取值为字典的列表 res_list = [] for val_tuple in tuple_list: res_list.append({ key: val_tuple[index-1] for key, index in _judge_info_groupdict }) return res_list def get_source_code_url(origin_judge_key): """ 根据RunID获取提交HDOJ评测的的源代码字符串 example: >>> from vjudge.hdoj import get_source_code_url >>> get_source_code_url(234) 'http://acm.hdu.edu.cn/viewcode.php?rid=234' """ return ''.join([VIEW_CODE_URL, '?rid=', str(origin_judge_key)]) @coroutine def get_source_code(origin_judge_key): """ 获取HDOJ代理提交的源代码信息 """ url = get_source_code_url(origin_judge_key) response = yield Task(client.get, url) # TODO: 获取失败处理 return from_html_get_source_code(response.body) def from_html_get_source_code(htmltext): """ 从HTML文本字符串中获取提交HDOJ评测的源代码字符串 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 对于匹配出来的结果会做`html.unescape`处理再返回。 """ htmltext = check_and_handle_htmltext(htmltext) res_list = _source_code_re.findall(htmltext) if len(res_list) == 0: # error: 没有找到源代码 return "" elif len(res_list) > 1: # error: 未分辨出源代码 return "" return unescape(res_list[0]) def get_compilation_info_url(origin_judge_key): """ 根据RunID获取源OJ评测后得到的编译错误信息 example: >>> from vjudge.hdoj import get_compilation_info_url >>> get_compilation_info_url(15796273) 'http://acm.hdu.edu.cn/viewerror.php?rid=15796273' """ return ''.join([VIEW_COMPILATION_INFO_URL, '?rid=', str(origin_judge_key)]) @coroutine def get_compilation_info(origin_judge_key): """ 根据源OJ评测信息的key获取评测信息的编译错误信息 """ url = get_compilation_info_url(origin_judge_key) response = yield Task(client.get, url) # TODO: 检查爬取是否失败 return from_html_get_compilation_info(response.body) def from_html_get_compilation_info(htmltext): """ 从HTML文本字符串中匹配出源OJ提交代码的编译信息 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 对于匹配出来的结果会做`html.unescape`处理再返回。 """ htmltext = check_and_handle_htmltext(htmltext) res_list = _compilation_info_re.findall(htmltext) if len(res_list) == 0: # error: 没有匹配出编译信息 return "" elif len(res_list) > 1: # error: 匹配出多个编译信息 return "" return unescape(res_list[0]) _judge_info_re = re.compile( r'<tr.*?>' '<td height=22px>(?P<origin_judge_key>\d+?)</td>' '<td>(?P<origin_submit_time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})</td>' '<td>[\s\S]*?<font.*?>(?P<origin_judge_status>.+?)</font>[\s\S]*?</td>' '<td><a href="/showproblem\.php\?pid=\d+?">(?P<origin_pid>\d{4,})</a></td>' '<td>(?P<origin_time_cost>\d+?)MS</td>' '<td>(?P<origin_memory_cost>\d+?)K</td>' '<td>.*?(?P<origin_code_length>\d+)[ ]?B.*?</td>' '<td>(?P<origin_code_language>.+?)</td>' '<td.*?><a href="/userstatus\.php\?user=(?P<origin_username>.+?)">.*?' '</a></td>' '</tr>' ) # _judge_info_re 的分组索引字典 _judge_info_groupdict = _judge_info_re.groupindex.items() _source_code_re = re.compile( r'<textarea[^<>]*?>(?P<source_code>[\s\S]*?)</textarea>' ) _compilation_info_re = re.compile( r'<pre>(?P<compilation_info>[\s\S]*?)</pre>' ) <file_sep>/application/vjudge/tools/problem.py #-*- coding: utf-8 -*- """ vjudge 题目工具库 """ from .url import img_url_relative_to_absolute __all__ = ['problem_info_refine'] def problem_info_refine(raw_info): """ 对匹配得到的题目原始信息进行加工。 目前功能: * 将题目中的img标签中的url转换成绝对url。 处理字段: * `description` * `input` * `output` * `hint` * `source` """ for key in ('description', 'input', 'output', 'hint', 'source'): raw_info[key] = img_url_relative_to_absolute(raw_info[key], raw_info['url']) return raw_info <file_sep>/application/db/models/tag.py # -*- coding: utf-8 -*- from sqlalchemy.orm import relationship from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String from db.models import BaseModel class Tag(BaseModel): """标签主表Model""" __tablename__ = "tb_tag" # 表结构 id = Column(Integer, primary_key=True, index=True) redirect_id = Column(Integer, ForeignKey("tb_tag.id"), nullable=False, index=True, default=0, server_default="0") title = Column(String(50), nullable=False, unique=True) # 关系 redirect = relationship("Tag", uselist=False) info = relationship("TagInfo", uselist=False) def __repr__(self): return "<Tag(title={})>".format(self.title) def __str__(self): return self.__repr__() pass class TagInfo(BaseModel): """标签信息表Model""" __tablename__ = "tb_tag_info" # 表结构 id = Column(Integer, ForeignKey("tb_tag.id"), primary_key=True, index=True) pass <file_sep>/application/vjudge/poj/supervision.py # -*- coding:utf-8 -*- """ Virtual Judge POJ 监控模块 """ import re import time from tornado.ioloop import IOLoop from tornado.gen import Task, coroutine from tornext.tasks import period from utils.log.loggers import vjudge as logger from ..tools.supervision import OnlineJudgeStatus from .attribute import HOST_URL,CHARSET, LOGIN_URL from .tools import check_and_handle_htmltext, client __all__ = ['login', 'from_html_verify_login_status', 'check_status', 'status'] status = OnlineJudgeStatus() @period(60 * 5) @coroutine def check_status(): pass """ 检查POJ的网站状态 参数: 'retry' 出错后重复登录的次数 默认为1 """ logger.info("start Check POJ status.") global status response = yield Task(client.get, HOST_URL) if from_html_verify_login_status(response.body,"WitcoderKayle"): logger.info("Check POJ status:Normal") status.set_normal() return logger.warning("Check POJ status:Error.") status.set_error() for _ in range(5): if login("WitcoderKayle","witcoderkayle"): logger.info("Check POJ status:Normal") status.set_normal() break @coroutine def login(username,password): """POJ代理帐号登录 """ form_data = { "user_id1":username, "<PASSWORD>1":<PASSWORD>, "B1":"login", } client.username = username client.password = <PASSWORD> response = yield Task(client.post,LOGIN_URL,form_data) response = yield Task(client.get,HOST_URL) return from_html_verify_login_status(response.body,username) def from_html_verify_login_status(htmltext,username): """根据登录后重定向的HTML文本及用户名来检查是否登录成功 成功为'true',否则为'False' """ htmltext = check_and_handle_htmltext(htmltext) res_list = _login_verify_re.findall(htmltext) return bool(res_list and res_list[0] == username) _login_verify_re = re.compile(r'<a href=userstatus\?user_id=.*? target=_parent><b>(.*?)</b></a>') <file_sep>/application/vjudge/hdoj/tools.py #-*- coding: utf-8 -*- """ Virtual Judge HDOJ内部工具模块 """ from ..tools.agent import AsyncAgent from ..tools import stdinfo from .attribute import (CHARSET, SUBMISSION_CODE_LANGUAGE_ID_TABLE, JUDGE_INFO_CODE_LANGUAGE_ID_TABLE, JUDGE_INFO_JUDGE_STATUS_ID_TABLE) client = AsyncAgent() def get_submission_origin_code_language_id(origin_code_language): """ 将HDOJ的代码提交时选择的编程语言转换成代码提交时表单使用的ID """ origin_code_language_id = SUBMISSION_CODE_LANGUAGE_ID_TABLE.get( origin_code_language, None ) if origin_code_language_id is None: errstr = ("The `origin_code_language` '{}' not in the " "`hdoj.SUBMISSION_CODE_LANGUAGE_ID_TABLE`.") raise ValueError(errstr.format(origin_code_language)) return origin_code_language_id def get_judge_info_origin_code_language_id(origin_code_language="All"): """ 将筛选HDOJ评测信息时选择的编程语言转换成查询字符串中对应的ID 默认`origin_code_language`为`All`,即不做编程语言筛选。 """ origin_code_language_id = JUDGE_INFO_CODE_LANGUAGE_ID_TABLE.get( origin_code_language, None ) if origin_code_language_id is None: errstr = ("The `origin_code_language` '{}' not in the " "`hdoj.JUDGE_INFO_CODE_LANGUAGE_ID_TABLE`.") raise ValueError(errstr.format(origin_code_language)) return origin_code_language_id def judge_finished(status): """ 根据源OJ的评测状态判断评测是否完成 """ if status in {"Queuing", "Running", "Compiling"}: return False return True def is_compilation_error(status): """ 判断源OJ的评测状态是否为编译错误 返回布尔值。 """ return to_judge_status(status) == stdinfo.CE def get_judge_info_origin_judge_status_id(origin_judge_status="All"): """ 将筛选HDOJ评测信息时的评测状态转换为查询字符串中对应的ID """ origin_judge_status_id = JUDGE_INFO_JUDGE_STATUS_ID_TABLE.get( origin_judge_status ) if origin_judge_status_id is None: errstr = ("The `origin_judge_status` '{}' not in the " "`hdoj.JUDGE_INFO_JUDGE_STATUS_ID_TABLE`.") raise ValueError(errstr.format(origin_judge_status)) return origin_judge_status_id def check_and_handle_htmltext(htmltext): """ 检查并处理HDOJ的HTML文本字符串`htmltext` 返回处理后的`htmltext` 对`htmltext`参数会进行类型检查,必须为`bytes`或`str`类型, 否则会抛出`TypeError`异常; 对于`bytes`类型的`htmltext`,将会按HDOJ的网页编码转码成`str`类型。 因为HDOJ的换行符是Windows格式的,因此,`htmltext`中的'\r\n'也会被'\n'替换。 """ # 检查 `htmltext` if isinstance(htmltext, bytes): htmltext = htmltext.decode(CHARSET, 'ignore') elif not isinstance(htmltext, str): raise TypeError("The type of `htmltext` is " "{}.".format(type(htmltext))) return htmltext.replace('\r\n', '\n') def to_origin_code_language(code_language): """ Virtual Judge 标准格式编程语言转换HDOJ格式编程语言 """ return code_language def to_code_language(origin_code_language): """ HDOJ 格式的编程语言转换成Virtual Judge标准格式的编程语言 """ return origin_code_language def to_judge_status(origin_judge_status): """ 将HDOJ爬取下来的评测状态转换成标准评测状态 HDOJ的评测状态除了`Runtime Error`非标准,其他都是标准信息。 """ if origin_judge_status in stdinfo.JUDGE_STATUS_SET: return origin_judge_status elif origin_judge_status.find("Runtime Error") != -1: return stdinfo.RE elif origin_judge_status == "System Error": return stdinfo.OJE else: # TODO: error: 未知的评测状态 raise ValueError('HDOJ Unknown origin judge status `{}`.'.format( origin_judge_status )) def to_judge_result(judge_info): """ 将HDOJ的评测信息转换成Virtual Judge提交后的标准化评测结果 用于讲HDOJ爬取的源匹配信息转换成Virtual Judge格式的,有效的评测结果。 """ judge_result = { "origin_oj": "HDOJ", "origin_pid": judge_info['origin_pid'], "judge_status": to_judge_status(judge_info['origin_judge_status']), "time_cost": judge_info['origin_time_cost'], "memory_cost": judge_info['origin_memory_cost'], "code_language": to_code_language(judge_info['origin_code_language']), "origin_judge_key": judge_info['origin_judge_key'], "origin_judge_status": judge_info['origin_judge_status'], "compilation_info": judge_info.get('compilation_info'), } return judge_result <file_sep>/application/vjudge/poj/agent.py #-*- coding: utf-8 -*- """ Virtual Judge POJ 代理模块 """ import re import base64 # poj字符转换 from html import unescape, escape # 处理字符串转义 from tornado.gen import coroutine, Task, sleep from utils.log.loggers import vjudge as logger from ..exc import FetchError, VjudgeError, SubmitError from .attribute import (SUBMIT_CODE_URL, JUDGE_STATUS_URL, CHARSET, VIEW_COMPILATION_INFO_URL, VIEW_CODE_URL, VIEW_JUDGE_STATUS_URL) from .tools import (check_and_handle_htmltext, client, is_finished, get_judge_info_origin_judge_status_id, to_judge_result, get_judge_info_origin_code_language_id, is_compilation_error, get_submission_origin_code_language_id) __all__ = ['submit_code', 'get_judge_info_list_url', 'get_judge_info', 'from_html_get_judge_info_list', 'get_source_code_url', 'get_source_code', 'from_html_get_source_code', 'from_key_info_get_judge_info', 'get_compilation_info_url', 'get_compilation_info', 'from_html_get_compilation_info'] @coroutine def submit_code(origin_pid,origin_code_language,source_code): """代理提交POJ题目代码 """ form_data = { "problem_id": origin_pid, "language": get_submission_origin_code_language_id(origin_code_language), "source": base64.b64encode(source_code.encode('utf-8')).decode(), "submit": 'Submit', "encoded": '1', } response = yield Task(client.post, SUBMIT_CODE_URL, form_data) if response.error: logger.error('Submit Error: submit response error -> {}.'.format( response.error )) return SubmitError(response.error) elif response.code != 200 or response.effective_url != VIEW_JUDGE_STATUS_URL: logger.error('Submit Error: ???.') return SubmitError('HTTPResponse `code` error, `code` is {}.'.format( response.code )) judge_info = yield get_judge_info( username=client.username,origin_pid=origin_pid, origin_code_language=origin_code_language,source_code=source_code ) if isinstance(judge_info, VjudgeError): return judge_info return to_judge_result(judge_info) def get_judge_info_list_url(username='',origin_pid='',origin_judge_status="", origin_code_language=""): """获取POJ评测状态列表URL """ item = [JUDGE_STATUS_URL] item.extend(['?problem_id=',origin_pid]) item.extend(['&user_id=',username]) item.extend(['&result=','']) item.extend(['&language=',get_judge_info_origin_code_language_id( origin_code_language)]) return ''.join(map(str,item)) def from_key_get_judge_info_list_url(origin_judge): """通过key获取评测状态 """ item = [JUDGE_STATUS_URL] item.extend(['?top=',origin_judge]) return ''.join(map(str,item)) @coroutine def get_judge_info(username=None,origin_pid=None,origin_code_language=None, source_code=None): judge_info = yield from_other_info_get_judge_info( username=username, origin_pid=origin_pid, source_code=source_code, origin_code_language=origin_code_language ) if isinstance(judge_info, VjudgeError): return judge_info # 确保完成 while not is_finished(judge_info['origin_judge_status']): yield sleep(1) judge_info = yield from_key_info_get_judge_info( judge_info['origin_judge_key'] ) # 如果评测结果为编译错误,将编译错误信息一并爬取 if is_compilation_error(judge_info['origin_judge_status']): compilation_info = yield get_compilation_info( judge_info['origin_judge_key'] ) judge_info['compilation_info'] = compilation_info return judge_info @coroutine def from_key_info_get_judge_info(origin_judge_key): """根据Run ID直接定位获取POJ代理提交后的评测信息 """ url = from_key_get_judge_info_list_url(int(origin_judge_key)+1) response = yield Task(client.get,url) #TODO htmltext = response.body res_list = from_html_get_judge_info_list(htmltext) if len(res_list) == 0: pass return res_list[0] @coroutine def from_other_info_get_judge_info(username, origin_pid, origin_code_language, source_code): """ 根据非key信息获取相关评测信息列表 可能需要解决并发冲突。 """ url = get_judge_info_list_url(username=username, origin_pid=origin_pid, origin_code_language=origin_code_language) response = yield Task(client.get,url) #TODO:提交失败的处理 print(response.body) judge_info_list = from_html_get_judge_info_list(response.body) print(judge_info_list) for judge_info in judge_info_list: origin_source_code = yield get_source_code(judge_info['origin_judge_key']) if origin_source_code.strip() == source_code.strip(): print("111") return judge_info # 逐一匹配依旧没有找到对应的,Fetch Error # 暂时这样处理了只能 return FetchError("Can't find remote submission.") def from_html_get_judge_info_list(htmltext): """从HTML文本中匹配出测评状态列表 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理 该函数返回值为字典类型的列表 字典的结构如下: { "origin_judge_key":.... #Run ID,评测信息的key "origin_agent_username":... #POJ代理的帐号 “origin_pid":... #题目编号 "origin_judge_status":... #评测状态 "origin_memory_cost":... #花费内存,单位为KB "origin_time_cost":... #花费时间,单位为MS "origin_code_language":... #编程语言,POJ的标准 "origin_code_length":... #代码长度,单位为B "origin_submit_time":... #提交时间 } """ htmltext = check_and_handle_htmltext(htmltext) tuple_list = _judge_info_re.findall(htmltext) #获取值为字典的列表 res_list = [] for val_tuple in tuple_list: res_list.append({ key:val_tuple[index-1] for key,index in _judge_info_groupdict }) return res_list def get_source_code_url(origin_judge_key): """根据Run ID获取提交哦奥POJ评测的源代码字符串 """ return ''.join([VIEW_CODE_URL, '?solution_id=', origin_judge_key]) @coroutine def get_source_code(origin_judge_key): url = get_source_code_url(origin_judge_key) response = yield Task(client.get,url) #TODO :获取失败处理 return from_html_get_source_code(response.body) def from_html_get_source_code(htmltext): """从网页htmltext中获取代码 """ htmltext = check_and_handle_htmltext(htmltext) res_list = _source_code_re.findall(htmltext) if len(res_list) == 0: #没有找到源代码 return "1" elif len(res_list) > 1: #找到多个源代码 return "2" return unescape(res_list[0]) def get_compilation_info_url(origin_judge_key): """ 根据RunID获取源OJ评测后得到的编译错误信息 example: >>> from vjudge.hdoj import get_compilation_info_url >>> get_compilation_info_url(15796273) 'http://acm.hdu.edu.cn/viewerror.php?rid=15796273' """ return ''.join([VIEW_COMPILATION_INFO_URL,'?solution_id=',origin_judge_key]) @coroutine def get_compilation_info(origin_judge_key): """根据源OJ评测信息的key获取评测信息的编译错误的信息 """ url = get_compilation_info_url(origin_judge_key) response = yield Task(client.get,url) #print(response) #print(response.body) #print(response.body.decode()) #response = urlopen(url).read() return from_html_get_compilation_info(response.body) def from_html_get_compilation_info(htmltext): """ 从HTML文本字符串中匹配出源OJ提交代码的编译信息 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 对于匹配出来的结果会做`html.unescape`处理再返回。 """ htmltext = check_and_handle_htmltext(htmltext) res_list = _compilation_info_re.findall(htmltext) if len(res_list) == 0: #没找到 pass elif len(res_list) > 1: return "" return unescape(res_list[0]) #查看用户是否已经登录 _login_verify_re = re.compile(r'<a href=userstatus\?user_id=.*? target=_parent><b>(.*?)</b></a>') #匹配代码re _source_code_re = re.compile(r'<pre .*?style="font-family:Courier New,Courier,monospace">(?P<source_code>[\s\S]*?)</pre>') _judge_info_re = re.compile( r'<tr align=center><td>(?P<origin_judge_key>\d+?)</td>' '<td><a href=userstatus\?user_id=(?P<origin_agent_username>.+?)>.*?</a></td>' '<td><a href=problem\?id=(?P<origin_pid>\d{4,})>\d{4,}</a></td>' '<td>.*?<font color=.+?>(?P<origin_judge_status>.+?)</font>.*?</td>' '<td>(?P<origin_memory_cost>\d+?K|\d*?)</td>' '<td>(?P<origin_time_cost>\d+?MS|\d*?)</td>' '<td><a href=showsource\?solution_id=\d{1,} target=_blank>' '(?P<origin_code_language>GCC|G\+\+|C|C\+\+|Java|Pascal|Fortran)</a></td>' '<td>(?P<origin_code_length>\d+?)B</td>' '<td>(?P<origin_submit_time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})</td></tr>' ) _compilation_info_re = re.compile(r'<pre>(?P<compilation_info>[\s\S]*?)</pre>') _judge_info_groupdict = _judge_info_re.groupindex.items() <file_sep>/application/vjudge/tools/supervision.py #-*- coding: utf-8 -*- """ Virtual Judge 监控工具模块 """ import time from utils.time import TIME_FORMAT_STR __all__ = ['OnlineJudgeStatus'] class OnlineJudgeStatus(object): """ 源OJ网站的状态类 """ status_set = {"Unknown", "Normal", "Error"} def __init__(self): self._status = "Unknown" self._last_check_time = time.strftime(TIME_FORMAT_STR) def __repr__(self): return self._status def __str__(self): return self._status def set_normal(self): self._status = "Normal" self._last_check_time = time.strftime(TIME_FORMAT_STR) def set_error(self): self._status = "Error" self._last_check_time = time.strftime(TIME_FORMAT_STR) def set_unknown(self): self._status = "Unknown" self._last_check_time = time.strftime(TIME_FORMAT_STR) @property def last_check_time(self): return self._last_check_time def equal(self, status): return self._status == status def normal(self): """ 判断状态是否正常 """ return self._status == "Normal" pass <file_sep>/application/static/js/auth.js $("#register-form button").click(function() { $(this).button("loading"); $.ajax({ url: "/register", type: "POST", data: $("#register-form").serialize(), success: function(response) { var obj = response; if (obj.status === 200) { window.location.reload(); } else if (obj.status === 400) { $("#register-" + obj.data.field).parent().addClass("has-error"); $("#register-" + obj.data.field + "-message").text(obj.data.errmsg); $("#register-form button").button("reset"); } else { // 服务器错误 } }, }); return false; }); $("#login-form button").click(function() { $(this).button("loading"); $.ajax({ url: "/login", type: "POST", data: $("#login-form").serialize(), success: function(response) { var obj = response; if (obj.status === 200) { window.location.reload(); } else if (obj.status === 400) { $("#login-" + obj.data.field).parent().addClass("has-error"); $("#login-" + obj.data.field + "-message").text(obj.data.errmsg); $("#login-form button").button("reset"); } else { // 服务器错误 } }, }); return false; }); $("#auth-modal input").change(function() { $(this).parent().removeClass("has-error"); $(this).next().text(""); }); <file_sep>/application/common/tests/test_utils.py #-*- coding: utf-8 -*- from nose.tools import assert_equal, assert_sequence_equal import common.utils from common.tests.case import CommonTestCase def test_urljoin(): test_obj = common.utils.urljoin assert_equal(test_obj("http://www.witcoder.com", "../../../../home/"), "http://www.witcoder.com/home/") assert_equal(test_obj("http://witcoder.com/1/2/3/", "../../../4/"), "http://witcoder.com/4/") assert_equal(test_obj("http://witcoder.com/home", "../../../../index"), "http://witcoder.com/index") assert_equal(test_obj("http://witcoder.com/a", "http://api.witcoder.com"), "http://api.witcoder.com") assert_equal(test_obj("https://www.witcoder.com/", "//api.witcoder.com/1"), "https://api.witcoder.com/1") assert_equal(test_obj("https://www.witcoder.com", "//witcoder.com/1?a=1"), "https://witcoder.com/1?a=1") def test_convert_linesep(): test_obj = common.utils.convert_linesep assert_equal(test_obj("a\r\nb\r\n"), "a\nb\n") assert_equal(test_obj("a\r\nb\r\n", "\n"), "a\nb\n") assert_equal(test_obj("a\r\nb\r\n", "\r"), "a\rb\r") assert_equal(test_obj("a\r\nb\r\n", "\r\n"), "a\r\nb\r\n") assert_equal(test_obj("a\rb\rc\n"), "a\nb\nc\n") assert_equal(test_obj("a\rb\rc\n", "\r\n"), "a\r\nb\r\nc\r\n") assert_equal(test_obj("a\rb\rc\n", "\r\n"), "a\r\nb\r\nc\r\n") assert_equal(test_obj("a\rb\n\rc\n", "\r\n"), "a\r\nb\r\n\r\nc\r\n") def test_paginate(): test_obj = common.utils.paginate assert_sequence_equal(test_obj(1, 1), [1], seq_type=list) assert_sequence_equal(test_obj(2, 3, 2), [2, 3], seq_type=list) assert_sequence_equal(test_obj(5, 9), [3, 4, 5, 6, 7], seq_type=list) assert_sequence_equal(test_obj(2, 10), [1, 2, 3, 4, 5], seq_type=list) assert_sequence_equal(test_obj(16, 17), [13, 14, 15, 16, 17], seq_type=list) assert_sequence_equal(test_obj(4, 10, 6), [2, 3, 4, 5, 6, 7], seq_type=list) assert_sequence_equal(test_obj(7, 10, 6), [5, 6, 7, 8, 9, 10], seq_type=list) assert_sequence_equal(test_obj(9, 20, 6), [7, 8, 9, 10, 11, 12], seq_type=list) class TestHTMLFormatter(CommonTestCase): def test_format_html(self): self.test_obj = common.utils.HTMLFormatter() assert_equal(self.test_obj.format_html("<hr/>"), "<hr />") assert_equal(self.test_obj.format_html("<img src=/static/1.jpg>"), '<img src="/static/1.jpg">') assert_equal(self.test_obj.format_html("<img src='/static/1.jpg'>"), '<img src="/static/1.jpg">') string = '&lt;&gt;&#1234;<img src="/static/1.jpg"><hr />' assert_equal(self.test_obj.format_html(string), string) self.test_obj = common.utils.HTMLFormatter(joinurl=True) assert_equal(self.test_obj.format_html("<img src=/static/1.jpg>", url="http://witcoder.com"), '<img src="http://witcoder.com/static/1.jpg">') assert_equal(self.test_obj.format_html("<img src=/static/1.jpg><br>", autoclose=True, url="http://a.io"), '<img src="http://a.io/static/1.jpg" /><br />') pass <file_sep>/doc/vjudge/poj.md # POJ Virtual Judge 文档 ## 账号登录 * url: `http://poj.org/login` * method: `POST` * form data: * user_id1: <username> * password1: <<PASSWORD>> * B1: "login" * url: "/" <file_sep>/requirements.txt Tornado sqlalchemy psycopg2 pycurl <file_sep>/application/db/models/vjudge/__init__.py # -*- coding: utf-8 -*- """ Witcoder Virtual Judge 数据表Model """ from .problem import * from .submission import * from .exercise import * <file_sep>/application/migrations/versions/1a466ad9fab1_add_index.py """add index Revision ID: 1a466ad9fab1 Revises: <KEY> Create Date: 2016-05-19 23:00:23.457665 """ # revision identifiers, used by Alembic. revision = '1a466ad9fab1' down_revision = '<KEY>' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_index(op.f('ix_tb_user_id'), 'tb_user', ['id'], unique=False) op.create_index(op.f('ix_tb_user_info_id'), 'tb_user_info', ['id'], unique=False) op.create_index(op.f('ix_tb_virtual_judge_problem_id'), 'tb_virtual_judge_problem', ['id'], unique=False) op.create_index(op.f('ix_tb_virtual_judge_problem_statistics_id'), 'tb_virtual_judge_problem_statistics', ['id'], unique=False) op.create_index(op.f('ix_tb_virtual_judge_submission_problem_id'), 'tb_virtual_judge_submission', ['problem_id'], unique=False) op.create_index(op.f('ix_tb_virtual_judge_submission_submitter_id'), 'tb_virtual_judge_submission', ['submitter_id'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_tb_virtual_judge_submission_submitter_id'), table_name='tb_virtual_judge_submission') op.drop_index(op.f('ix_tb_virtual_judge_submission_problem_id'), table_name='tb_virtual_judge_submission') op.drop_index(op.f('ix_tb_virtual_judge_problem_statistics_id'), table_name='tb_virtual_judge_problem_statistics') op.drop_index(op.f('ix_tb_virtual_judge_problem_id'), table_name='tb_virtual_judge_problem') op.drop_index(op.f('ix_tb_user_info_id'), table_name='tb_user_info') op.drop_index(op.f('ix_tb_user_id'), table_name='tb_user') ### end Alembic commands ### <file_sep>/application/basesite/views.py # coding: utf-8 from common.web import BaseHandler class MainHandler(BaseHandler): """主页(宣传页)请求处理器""" def get(self): self.render("main.html") pass class IndexHandler(BaseHandler): """首页请求处理器""" def get(self): kwargs = { 'user': self.current_user } self.render("index.html", **kwargs) pass <file_sep>/application/runserver.py #!/usr/bin/env python3 # coding: utf-8 import tornado.ioloop from witcoder import app if __name__ == '__main__': app.configure() app.listen(8000) tornado.ioloop.IOLoop.current().start() <file_sep>/application/static/js/witcoder.js // 导航条下拉菜单的插件 $(".onhover-dropdown").mouseover(function() {$(this).addClass("open");}); $(".onhover-dropdown").mouseout(function() {$(this).removeClass("open");}); // 登录注册表单验证 //function set_error_message(obj, text) { //obj.html(text); //obj.show(); //event.preventDefault(); //} //$('#register-modal-form').submit(function() { //var msgobj = $('#register-modal .message'); //var username = $("#register-modal [name='username']").val(); //if (/[\w\d_]{2,20}/.test(username) === false) { //set_error_message(msgobj, username === "" ? '用户名为空!' : '用户名必须是由英文字母,数字或下划线构成的2到20个字符!'); //return; //} //var password = $("#register-modal [name='password']").val(); //if (/.{4,20}/.test(password) === false) { //set_error_message(msgobj, password === "" ? '密码为空!' : '密码长度必须在4到20个字符之间!'); //return; //} //var repassword = $("#register-modal [name='repassword']").val(); //if (repassword !== password) { //set_error_message(msgobj, "两次输入的密码不一致!"); //return; //} //var email = $("#register-modal [name='email']").val(); //if (/([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(email) === false) { //set_error_message(msgobj, email === "" ? "电子邮箱为空!" : "不规范的电子邮箱账号!"); //return; //} //}); <file_sep>/application/auth/ui.py # coding: utf-8 from tornado.web import UIModule from witcoder.settings import UI class AuthForm(UIModule): _js_files = (UI.cdn.js.jquery, "/static/js/auth.js") def render(self, form_type=None): if form_type == "modal": return self.render_string("ui/auth_modal_form.html") else: return "" def javascript_files(self): return self._js_files pass <file_sep>/application/auth/conf.py # coding: utf-8 from tornado.web import url urls = [ url(r"/(login|register)", "auth.views.AuthHandler"), url(r"/logout", "auth.views.LogoutHandler"), ] ui_methods = {} ui_modules = { "AuthForm": "auth.ui.AuthForm", } <file_sep>/doc/vjudge/hdoj.md # HDOJ Virtual Judge 文档 ## 账号登录 * url: `http://acm.hdu.edu.cn/userloginex.php?action=login` * method: `POST` * 提交表单数据格式: * username: <username> * userpass: <<PASSWORD>> * login: "Sign In" ## 题目代码提交 * url: `http://acm.hdu.edu.cn/submit.php?action=submit` * method: `POST` * 提交表单数据格式: * check: 0 * problemid: <problemid> * language: <languageid> * usercode: <usercode> * languageid |id |language | |:-----:|:----------| |`0` |G++ | |`1` |GCC | |`2` |C++ | |`3` |C | |`4` |Pascal | |`5` |Java | |`6` |C# | <file_sep>/application/assets/src/vjudge/exercise/problem.js import React from 'react' /** * 训练题目路由组件 */ ExerciseProblems = React.createClass({ render: function() { return ( <div className="row"> <div className="col-md-12"> <ExerciseProblemButtonGroup /> </div> </div> ); } }); /** * 训练题目按钮组组件 */ ExerciseProblemButtonGroup = React.createClass({ render: function() { return ( <div className="btn-group" role="group"> </div> ); } }); <file_sep>/application/admin/__init__.py #-*- coding: utf-8 -*- from tornext.web import Blueprint admin = Blueprint(__name__, url_prefix=r"/admin") <file_sep>/application/db/models/vjudge/submission.py # -*- coding: utf-8 -*- """Witcoder Virtual Judge 提交答案相关数据表Model""" from sqlalchemy.orm import relationship from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, Text from db.models.base import BaseModel from db.models.vjudge.base import SubmissionModel __all__ = ['Submission', 'SubmissionSourceCode', 'SubmissionCompilationInfo'] class Submission(SubmissionModel): """ Virtual Judge 提交答案主表Model 数据表关系: `submitter`: 与`User`的多对一关系 `problem`: 与`Problem`的多对一关系,参见`tb_problem`表 `source`: 与`SubmissionSourceCode`的一对一关系 `compilation`: 与`SubmissionCompilationInfo`的一对一关系 索引: `id`: 主键上的索引 """ __tablename__ = 'tb_virtual_judge_submission' # 表结构,包含SubmissionModel定义的字段 id = Column(Integer, primary_key=True, index=True) problem_id = Column(Integer, ForeignKey("tb_virtual_judge_problem.id"), nullable=False, index=True) submitter_id = Column(Integer, ForeignKey("tb_user.id"), nullable=False, index=True) # 关系 submitter = relationship("User", backref="submissions") source = relationship("SubmissionSourceCode", backref="submission", cascade="all", uselist=False) compilation = relationship("SubmissionCompilationInfo", backref="submission", cascade="all", uselist=False) def __repr__(self): return "<Submission(id={})>".format(self.id) @classmethod def get_field_dict(cls): return {"id": "id", "problem_id": "problem_id", "submitter_id": "submitter_id", "status": "_status", "time_cost": "time_cost", "memory_cost": "memory_cost", "language": "language", "code_length": "code_length", "shared": "shared"} @classmethod def register(cls, **kwargs): source_code = kwargs.pop("source_code") submission = cls(**kwargs) submission.source = SubmissionSourceCode(code=source_code) return submission def to_dict(self, *fields): """转换成数据字典 不安全,没有检查字段是否存在。 使用虚拟字段,非真实字段。 忽略'remote_key'和'remote_status'这两个字段。 """ if not fields: fields = self.get_field_dict().keys() return {field: getattr(self, field) for field in fields} def update(self, result: dict): if result["status"] == "Compilation Error": self.compilation = SubmissionCompilationInfo( info=result["compilation_info"] ) self.status = result["status"] self.time_cost = result["time_cost"] self.memory_cost = result["memory_cost"] self.remote_key = result["remote_key"] self.remote_status = result["remote_status"] pass class SubmissionSourceCode(BaseModel): """ Virtual Judge 提交答案源代码表Model 数据表关系: `submission`: 与`Submission`的一对一关系,参见`tb_submission`表 索引: `id`: 主键上的索引 """ __tablename__ = "tb_virtual_judge_submission_source_code" # 表结构 id = Column(Integer, ForeignKey("tb_virtual_judge_submission.id"), primary_key=True, index=True) code = Column(Text, nullable=False) _fields = ('id', 'code') def __repr__(self): return "<SubmissionSourceCode(id={})>".format(self.id) pass class SubmissionCompilationInfo(BaseModel): """ Virtual Judge 提交答案编译信息表Model 数据表关系: `submission`: 与`Submission`的一对一关系,参见`tb_submission`表 索引: `id`: 主键上的索引 """ __tablename__ = 'tb_virtual_judge_submission_compilation_info' # 表结构 id = Column(Integer, ForeignKey("tb_virtual_judge_submission.id"), primary_key=True, index=True) info = Column(Text, nullable=False) _fields = ('id', 'info') def __repr__(self): return "<SubmissionCompilationInfo(id={})>".format(self.id) pass <file_sep>/application/vjudge/tests/case.py #-*- coding: utf-8 -*- import unittest import nose.case class CommonTestCase(unittest.TestCase): pass <file_sep>/application/templates/ui/account/user_password_setting_form.js $("#user-password-setting-form button").click(function() { $(this).button("loading"); $.ajax({ url: "/setting/user/password", type: "POST", data: $("#user-password-setting-form").serialize(), success: function(response) { var obj = response; if (obj.status === 200) { $("#user-password-setting-form input").val(""); $("#user-password-setting-form").after('<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><i class="fa fa-warning"></i> 密码修改成功!</div>'); $("#user-password-setting-form button").button("reset"); } else if (obj.status === 400) { $("#setting-" + obj.data.field).parent().addClass("has-error"); $("#setting-" + obj.data.field + "-message").text(obj.data.message); $("#user-password-setting-form button").button("reset"); } else { // Server error! alert("抱歉,服务器出现错误!"); } }, }); return false; }); $("#user-password-setting-form input").change(function() { $(this).parent().removeClass("has-error"); $(this).next().text(""); }); <file_sep>/application/vjudge/zoj/crawler.py #!/usr/bin/env python3 #coding=utf-8 import re from tornado.gen import coroutine, Task from .attribute import CHARSET, HOST_URL from .tools import client, check_and_handle_htmltext from ..tools.problem import problem_info_refine __all__ = ['get_problem_url', 'from_html_get_problem_info', 'get_problem_info', 'get_problem_list_url', 'from_html_get_problem_list', 'get_problem_list', 'from_html_get_problem_volumes', 'get_problem_volumes'] def get_problem_url(origin_pid): if not isinstance(origin_pid, (int, str)): raise TypeError("The type of `origin_pid` is {}.".format( type(origin_pid) )) origin_pid = str(origin_pid).strip() if not str(origin_pid).isdigit(): raise ValueError("'{}' isn't a regular value of " "`origin_pid`.".format(origin_pid)) return ''.join([HOST_URL, '/showProblem.do?problemCode=', str(origin_pid)]) def from_html_get_problem_info(htmltext, origin_pid): ''' ''' htmltext = check_and_handle_htmltext(htmltext).strip() if not isinstance(origin_pid, (str, int)): raise TypeError("The type of `origin_pid` is {}.".format( type(origin_pid))) elif not str(origin_pid).isdigit(): raise ValueError("'{}' isn't regular value of " "`origin_pid`.".format(str(origin_pid))) raw_info = { "origin_oj": 'ZOJ', "origin_pid": str(origin_pid), "url": get_problem_url(origin_pid), "title": _get_problem_title(htmltext), "time_limit": _get_problem_time_limit(htmltext), "memory_limit": _get_problem_memory_limit(htmltext), "special_judge": _get_problem_special_judge(htmltext), "description": _get_problem_description(htmltext), "input": _get_problem_input(htmltext), "output": _get_problem_output(htmltext), "sample_input": _get_problem_sample_input(htmltext), "sample_output": _get_problem_sample_output(htmltext), "hint": _get_problem_hint(htmltext), "source": _get_problem_source(htmltext), } return problem_info_refine(raw_info) @coroutine def get_problem_info(origin_pid): url = get_problem_url(origin_pid) response = yield Task(client.get, url) return from_html_get_problem_info(response.body, origin_pid) def get_problem_list_url(vol=1): if not isinstance(vol, (int, str)): raise TypeError("The type of `vol` is {}.".format(type(vol))) vol = str(vol).strip() if not vol.isdigit(): raise ValueError("'{}' isn't a regular value of `vol`.".format(vol)) return ''.join([HOST_URL, '/showProblems.do?contestId=1&pageNumber=', vol]) def from_html_get_problem_list(htmltext): ''' ''' htmltext = check_and_handle_htmltext(htmltext).strip() problist = [ (origin_pid.strip(), title.strip().replace(r'\"', '"')) for origin_pid, title in _problist_problem_re.findall(htmltext) ] return problist @coroutine def get_problem_list(vol=1): url = get_problem_list_url(vol) response = yield Task(client.get, url) return from_html_get_problem_list(response.body) def from_html_get_problem_volumes(htmltext): ''' ''' htmltext = check_and_handle_htmltext(htmltext).strip() vollist = list(set(map(int, _problist_vol_re.findall(htmltext)))) vollist.sort() return vollist @coroutine def get_problem_volumes(): url = get_problem_list_url(1) response = yield Task(client.get, url) return from_html_get_problem_volumes(response.body) def _get_problem_title(string): res_list = _probinfo_title_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return None elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_time_limit(string): res_list = _probinfo_time_limit_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return None elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_memory_limit(string): res_list = _probinfo_memory_limit_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return None elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_special_judge(string): res_list = _probinfo_special_judge_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return False elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return True def _get_problem_description(string): res_list = _probinfo_description_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return '' elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_input(string): res_list = _probinfo_input_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return '' elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_output(string): res_list = _probinfo_output_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return '' elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_sample_input(string): res_list = _probinfo_sample_input_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return '' elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_sample_output(string): res_list = _probinfo_sample_output_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return '' elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_source(string): res_list = _probinfo_source_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return '' elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_hint(string): res_list = _probinfo_hint_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return '' elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() __font_re_str= '(?:</h4>|</font></tt></h1>|</B>|</H4>|</b></p>){1}' __back_re_str = '(?:<h4>|<P><B>|<h1>[\s\S]*|<H4>|<p><b>|<b>){1}' _probinfo_url = "http://acm.zju.edu.cn/onlinejudge/showProblem.do" _probinfo_title_re = re.compile(r'<center><span class="bigProblemTitle">(.*)</span></center>') _probinfo_time_limit_re = re.compile(r'<font color="green">Time Limit: </font> (\d+) Second') _probinfo_memory_limit_re = re.compile(r'<font color="green">Memory Limit: </font> (\d+) KB') _probinfo_special_judge_re = re.compile(r'<font color="blue">Special Judge</font>') _probinfo_description_re = re.compile(r'KB[\s\S]*</center>[\s]*<hr>[\s]*([\s\S]*)' '(?:<h4>|<H4>|<p><b>|<p><strong>|<P><b>|<P><B>|<tt><font size="\+1">|<b>Sample){1}' '[\s\S]*Input<') _probinfo_input_re = re.compile(r'>[\s]*Input' + __font_re_str + '([\s\S]*)' + __back_re_str + 'Output<') _probinfo_output_re = re.compile(r'>[\s]*Output' + __font_re_str + '([\s\S]*)' + __back_re_str + 'Sample Input<') _probinfo_sample_input_re = re.compile(r'>[\s]*Sample Input' + __font_re_str + '([\s\S]*)' + __back_re_str + 'Sample Output<') _probinfo_sample_output_re = re.compile(r'>[\s]*Sample Output'+__font_re_str+'([\s\S]+?)' '(?:</pre>|</PRE>|<hr>)') _probinfo_hint_re = re.compile(r'[<h4>|<H4>]+Hint' + __font_re_str + '([\s\S]*)<hr>') _probinfo_source_re = re.compile(r'Source: <strong>([\s\S]*)</strong>') _prolist_url = "http://acm.zju.edu.cn/onlinejudge/showProblems.do?contestId=1&pageNumber=" _problist_problem_re = re.compile(r'<td class="problemTitle"><a href="/onlinejudge/showProblem.do\?problemCode=(\d\d\d\d)"><font color="blue">([\ \S]+)</font></a></td>') _problist_vol_re = re.compile(r'/onlinejudge/showProblems\.do\?contestId=1&pageNumber=(\d+)">Vol') <file_sep>/application/vjudge/tests/remote/test_hdoj.py # -*- coding: utf-8 -*- import tornado.ioloop from nose.tools import (assert_equal, assert_is_instance, assert_regex, assert_is, assert_raises, assert_not_equal) from vjudge.remote import hdoj from vjudge.exceptions import ProblemNotFound from vjudge.tests.case import CommonTestCase def setup(): pass def teardown(): pass class HDOJMixinTest(CommonTestCase): test_obj = hdoj.HDOJMixin() def test_get_problem_info_url(self): assert_equal(self.test_obj.get_problem_info_url(1000), "http://acm.hdu.edu.cn/showproblem.php?pid=1000") assert_equal(self.test_obj.get_problem_info_url("1012"), "http://acm.hdu.edu.cn/showproblem.php?pid=1012") def test_get_problem_list_url(self): assert_equal(self.test_obj.get_problem_list_url(1), "http://acm.hdu.edu.cn/listproblem.php?vol=1") assert_equal(self.test_obj.get_problem_list_url("10"), "http://acm.hdu.edu.cn/listproblem.php?vol=10") def test_get_submitcode_url(self): assert_equal(self.test_obj.get_submitcode_url(), "http://acm.hdu.edu.cn/submit.php?action=submit") def test_get_submission_info_url(self): assert_equal(self.test_obj.get_submission_info_url(15991423), "http://acm.hdu.edu.cn/viewcode.php?rid=15991423") def test_get_submission_list_url(self): assert_equal(self.test_obj.get_submission_list_url(), "http://acm.hdu.edu.cn/status.php?" "first=&pid=&user=&lang=0&status=0") assert_equal(self.test_obj.get_submission_list_url(language="GCC"), "http://acm.hdu.edu.cn/status.php?" "first=&pid=&user=&lang=2&status=0") assert_equal(self.test_obj.get_submission_list_url( 21, 1001, "JZQT", "Java", "Accepted" ), ("http://acm.hdu.edu.cn/status.php?first=21" "&pid=1001&user=JZQT&lang=6&status=5")) def test_refine_html(self): assert_equal(self.test_obj.refine_html('hello\r\nhdoj'.encode('GBK')), 'hello\nhdoj') assert_equal(self.test_obj.refine_html('skjfd\r\nsdfljk\r\n'), 'skjfd\nsdfljk\n') pass class HDOJSpiderTest(CommonTestCase): test_obj = hdoj.HDOJSpider() ioloop = tornado.ioloop.IOLoop.current() def test_fetch_problem_volumes(self): problem_volumes = self.ioloop.run_sync( lambda: self.test_obj.fetch_problem_volumes() ) assert_is_instance(problem_volumes, list) for volume in problem_volumes: assert_is_instance(volume, int) assert_equal(problem_volumes[0], 1) for i in range(len(problem_volumes)): assert_equal(problem_volumes[i], i + 1) def test_fetch_problem_list(self): problem_list = self.ioloop.run_sync( lambda: self.test_obj.fetch_problem_list(1) ) assert_is_instance(problem_list, list) assert_equal(problem_list[0], ('1000', 'A + B Problem')) def test_fetch_problem_info(self): problem_info = self.ioloop.run_sync( lambda: self.test_obj.fetch_problem_info(1000) ) assert_equal(problem_info["remote_oj"], "HDOJ") assert_equal(problem_info["remote_pid"], "1000") assert_equal(problem_info["url"], "http://acm.hdu.edu.cn/showproblem.php?pid=1000") assert_equal(problem_info["title"], "A + B Problem") assert_equal(problem_info["time_limit"], 1000) assert_equal(problem_info["memory_limit"], 32768) assert_is(problem_info["special_judge"], False) problem_info = self.ioloop.run_sync( lambda: self.test_obj.fetch_problem_info(1012) ) assert_regex(problem_info["description"], r'src="http://acm\.hdu\.edu\.cn/data/images/1012-1\.gif"') with assert_raises(ProblemNotFound): self.ioloop.run_sync( lambda: self.test_obj.fetch_problem_info(1125) ) pass class HDOJClientTest(CommonTestCase): test_obj = hdoj.HDOJClient() ioloop = tornado.ioloop.IOLoop.current() def setup(self): self.test_login() def test_login(self): self.test_obj.username = self.test_obj.password = None with assert_raises(ValueError): status = self.ioloop.run_sync( lambda: self.test_obj.login() ) status = self.ioloop.run_sync( lambda: self.test_obj.login("JZQT", "tjyjzqt") ) assert_equal(status, self.test_obj.status) assert_equal(status, "Normal") htmltext = self.ioloop.run_sync( lambda: self.test_obj.httpclient.fetch(hdoj.HOST_URL) ).body.decode(hdoj.CHARSET, "ignore") assert_not_equal(htmltext.find("JZQT"), -1) pass <file_sep>/application/vjudge/views/index.py # coding: utf-8 from common.web import BaseHandler from vjudge.generic import SUPPORTED_ONLINE_JUDGE class IndexHandler(BaseHandler): def get(self): self.tplkw["SUPPORTED_ONLINE_JUDGE"] = SUPPORTED_ONLINE_JUDGE self.render('vjudge/index.html') pass <file_sep>/application/test.py #!/usr/bin/env python3 #-*- coding: utf-8 -*- from pprint import pprint import json from sqlalchemy import or_, func from sqlalchemy.orm import load_only, joinedload from tornado.gen import coroutine, sleep import logging import tornado.ioloop from witcoder import orm from vjudge.remote import hdoj import db.models from db.models import User, UserInfo from db.models.vjudge import Problem, Submission, ProblemStatistics #submissions = orm.session.query(Submission).options(joinedload("submitter")).filter( #func.lower(User.username) == "jzqt" #).all() #input("create all") #input() #for submission in submissions: ##pprint(type(submission.submitter)) ##pprint(dir(submission.submitter)) #print(submission.submitter) def drop_all_table(): input("drop all table") db.models.BaseModel.metadata.drop_all() def create_all_table(): input("create all table") db.models.BaseModel.metadata.create_all() def load_problem(filename): input("load problem") with open(filename) as f: problems = json.load(f) for problem in problems: p = Problem.register(**problem) orm.session.add(p) print(p) try: orm.session.commit() except: orm.session.rollback() raise if __name__ == "__main__": drop_all_table() create_all_table() load_problem("/home/jzqt/problems.json") #jzqt = orm.session.query(User).filter_by(username="JZQT").one() #timilong = orm.session.query(User).filter_by(username='timilong').one() #yangjiaronga = orm.session.query(User).filter_by(username='yangjiaronga').one() #input() #pprint(type(timilong.followees)) #pprint(jzqt.followers) #print(yangjiaronga.followers) #print(yangjiaronga.followees) #input("OK") """ problems = orm.session.query(Problem).order_by(Problem.id.asc()).all() prev = "0999" for problem in problems: if not (problem.remote_pid > prev): print("Orz!") print(problem.remote_pid, prev) break prev = problem.remote_pid print(len(problems), problems[-1].id) input("Please input") with open("/tmp/problems.json", "w") as f: problems = [problem.to_dict() for problem in orm.session.query(Problem).order_by(Problem.id.asc()).all()] f.write(json.dumps(problems)) print("OK") @coroutine def func(): volumes = yield hdoj.spider.fetch_problem_volumes() problem_list_futures = [ hdoj.spider.fetch_problem_list(volume) for volume in volumes ] problem_list = [] for future in problem_list_futures: results = yield future problem_list.extend(results) for remote_pid, title in problem_list: wait_future = sleep(1) problem = orm.session.query(Problem).filter_by( remote_oj="HDOJ", remote_pid=remote_pid ).one_or_none() if problem is not None: print("Problem HDOJ-{} exists!".format(remote_pid)) continue print("Start crawling HDOJ-{} ...".format(remote_pid), end=" ") problem_info = yield hdoj.spider.fetch_problem_info(remote_pid) print("End!") print("Add problem HDOJ-{} to database ...".format(remote_pid), end=" ") problem = Problem.register(**problem_info) try: orm.session.add(problem) orm.session.commit() except: orm.session.rollback() print("Error!") raise else: print("End!") yield wait_future tornado.ioloop.IOLoop.current().run_sync(lambda: func()) """ <file_sep>/application/vjudge/hdoj/supervision.py #-*- coding: utf-8 -*- """ Virtual Judge HDOJ监控模块 该模块主要包含监控HDOJ网站状态的一些功能。 """ import re import time from tornado.gen import Task, coroutine from tornext.tasks import period from utils.log.loggers import vjudge as logger from ..tools.supervision import OnlineJudgeStatus from .attribute import HOST_URL, CHARSET, LOGIN_URL, CHECK_TIME_INTERVAL from .tools import client, check_and_handle_htmltext __all__ = ['status', 'check_status', 'login', 'from_html_verify_login_status'] status = OnlineJudgeStatus() @period(CHECK_TIME_INTERVAL) @coroutine def check_status(): """ 检查HDOJ的网站状态 目前只检查代理是否为登录状态。 出错后会重试登录,最多尝试`5`次。 """ logger.info("start Check HDOJ status.") global status response = yield Task(client.get, HOST_URL) # TODO: 未处理response错误情况 if from_html_verify_login_status(response.body, "WitcoderKayle"): logger.info("Check HDOJ status: Normal.") status.set_normal() return logger.warning("Check HDOJ status: Error.") status.set_error() for _ in range(5): if login("WitcoderKayle", "witcoderkayle"): logger.info("Check HDOJ status: Normal.") status.set_normal() break @coroutine def login(username, password): """ HDOJ代理账号登录 传入参数`username`和`password`进行账号登录, 登录的过程为异步的,该函数使用`tornado.gen.coroutine`装饰器装饰。 登录表单提交后会根据重定向的HTML页面进行登录状态检查, 如果登录成功该函数返回`True`,否则返回`False`。 """ form_data = { "username": username, "userpass": <PASSWORD>, "login": "Sign In", } client.username = username client.password = <PASSWORD> response = yield Task(client.post, LOGIN_URL, form_data) response = yield Task(client.get, HOST_URL) return from_html_verify_login_status(response.body, username) def from_html_verify_login_status(htmltext, username): """ 根据HTML文本字符串以及用户名来检查登录是否成功 登录成功返回`True`,否则为`False`。 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 """ htmltext = check_and_handle_htmltext(htmltext) res_list = _login_verify_re.findall(htmltext) return bool(res_list and res_list[0] == username) _login_verify_re = re.compile(r'<a href="/userstatus.php\?user=(.*?)" style=') <file_sep>/application/templates/ui/account/change_avatar.js function get_object_url(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createObjectURL(file); } else if (window.URL != undefined) { url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { url = window.webkitURL.createObjectURL(file); } return url; } function updateCoords(c) { $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); } function checkCoords(){ if (parseInt($('#w').val())) { return true; }; return true alert('请先选择要裁剪的区域后,再提交。'); return false; }; $("#input-avatar-button").click(function () { $("#input-avatar").click(); }); $("#input-avatar").change(function () { var imgurl = get_object_url(document.getElementById("input-avatar").files[0]); $("#img-container").html( '<img class="img-responsive block-center" id="input-avatar-modal-img" src="" alt="图片">' ); $("#input-avatar-modal-img").attr("src", imgurl); //$("#input-avatar-modal-img").Jcrop({ //aspectRatio: 1 / 1, //onSelect: updateCoords, //onRelease: function() { //$("#w").val(""); //}, //}); $("#input-avatar-modal").modal("toggle"); }); $("#input-avatar-modal").on("hidden.bs.modal", function(e) { $("#input-avatar-modal .modal-body").html('<div id="img-container"></div>'); $("#input-avatar").val(""); $('#w').val(""); }); <file_sep>/application/vjudge/hdoj/crawler.py #-*- coding: utf-8 -*- """ Virtual Judge HDOJ 爬虫模块 """ import re from tornado.gen import coroutine, Task from .attribute import HOST_URL from .tools import client, check_and_handle_htmltext from ..tools.problem import problem_info_refine __all__ = ['get_problem_url', 'from_html_get_problem_info', 'get_problem_info', 'get_problem_list_url', 'from_html_get_problem_list', 'get_problem_list', 'from_html_get_problem_volumes', 'get_problem_volumes'] def get_problem_url(origin_pid): """ 获取HDOJ题目的url 根据HDOJ的题目编号参数`origin_pid`获取该题目的url并返回。 会验证`origin_pid`参数是否为整数或者字符串类型,验证失败会抛出`TypeError`异常; 验证类型成功的`origin_pid`会被转换成字符串类型并做`strip()`方法处理, 处理后的字符串会使用`isdigit()`方法检验,检验失败抛出`ValueError`异常。 目前暂且无法验证前缀为'0'的数字字符串。 example: >>> from vjudge.hdoj import get_problem_url >>> get_problem_url(1000) 'http://acm.hdu.edu.cn/showproblem.php?pid=1000' >>> get_problem_url('4988') 'http://acm.hdu.edu.cn/showproblem.php?pid=4988' >>> get_problem_url(' 2222 ') 'http://acm.hdu.edu.cn/showproblem.php?pid=2222' >>> get_problem_url('0001') # 错误使用方式 'http://acm.hdu.edu.cn/showproblem.php?pid=0001' """ if not isinstance(origin_pid, (int, str)): raise TypeError("The type of `origin_pid` is {}.".format( type(origin_pid) )) origin_pid = str(origin_pid).strip() if not str(origin_pid).isdigit(): raise ValueError("'{}' isn't a regular value of " "`origin_pid`.".format(origin_pid)) return ''.join([HOST_URL, '/showproblem.php?pid=', str(origin_pid)]) def from_html_get_problem_info(htmltext, origin_pid): """ 从HTML文本和HDOJ题目编号中获取HDOJ题目的信息 根据HDOJ的题目HTML文本参数`htmltext` 以及题目编号`origin_pid`获取该题目的信息并返回。 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 参数`origin_pid`也会进行检查,非`str`和`int`类型会抛出`TypeError`异常, 转换为`str`类型后会使用`isdigit()`方法进行检查,失败抛出`ValueError`异常。 """ htmltext = check_and_handle_htmltext(htmltext).strip() # 检查 `origin_pid` if not isinstance(origin_pid, (str, int)): raise TypeError("The type of `origin_pid` is {}.".format( type(origin_pid) )) elif not str(origin_pid).isdigit(): raise ValueError("'{}' isn't regular value of " "`origin_pid`.".format(str(origin_pid))) # 获取未处理过的原始信息 raw_info = { "origin_oj": "HDOJ", "origin_pid": str(origin_pid), "url": get_problem_url(origin_pid), "title": _get_problem_title(htmltext), "time_limit": _get_problem_time_limit(htmltext), "memory_limit": _get_problem_memory_limit(htmltext), "special_judge": _get_problem_special_judge(htmltext), "description": _get_problem_description(htmltext), "input": _get_problem_input(htmltext), "output": _get_problem_output(htmltext), "sample_input": _get_problem_sample_input(htmltext), "sample_output": _get_problem_sample_output(htmltext), "hint": _get_problem_hint(htmltext), "source": _get_problem_source(htmltext), } # 返回处理后的题目信息 return problem_info_refine(raw_info) @coroutine def get_problem_info(origin_pid): url = get_problem_url(origin_pid) response = yield Task(client.get, url) return from_html_get_problem_info(response.body, origin_pid) def get_problem_list_url(vol=1): """ 获取指定页的题目列表的url `vol`参数的类型必须为`str`或`int`,否则会抛出`TypeError`。 `vol`将会被转换成`str`类型并使用`strip()`方法处理, 处理后的结果会使用`isdigit()`方法检验,检验失败抛出`ValueError`异常。 """ if not isinstance(vol, (int, str)): raise TypeError("The type of `vol` is {}.".format(type(vol))) vol = str(vol).strip() if not vol.isdigit(): raise ValueError("'{}' isn't a regular value of `vol`.".format(vol)) return ''.join([HOST_URL, '/listproblem.php?vol=', vol]) def from_html_get_problem_list(htmltext): """ 从HTML文本字符串中解析出HDOJ题目列表 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 返回值是由二元组组成的题目列表。 二元组的第一个元素是`origin_pid`,第二个元素是题目的`title`,应该是按照`origin_pid`的升序排序的。 >>> from vjudge import hdoj >>> from urllib.request import urlopen >>> url = hdoj.get_problem_list_url(1) >>> htmltext = urlopen(url).read() >>> problist = hdoj.from_html_get_problem_list(htmltext) >>> for value in problist: ... print(value) ... pass ('1000', 'A + B Problem') ('1001', 'Sum Problem') ('1002', 'A + B Problem II') ('1003', 'Max Sum') ('1004', 'Let the Balloon Rise') ('1005', 'Number Sequence') ... 会对匹配到的`title`信息使用`strip()`和`replace(r'\"', '"')`方法进行处理。 比如,对于HDOJ-1177题,它的title为'"Accepted today?"', 因此匹配到的字符串为r'\"Accepted today?\"', 处理后的字符串才是正常的'"Accepted today?"'。 """ htmltext = check_and_handle_htmltext(htmltext).strip() problist = [ (origin_pid.strip(), title.strip().replace(r'\"', '"')) for origin_pid, title in _problist_problem_re.findall(htmltext) ] return problist @coroutine def get_problem_list(vol=1): url = get_problem_list_url(vol) response = yield Task(client.get, url) return from_html_get_problem_list(response.body) def from_html_get_problem_volumes(htmltext): """ 从HTML文本字符串中获取HDOJ的题目列表页的索引列表 该HTML文本字符串`htmltext`应该来自于HDOJ的题目列表页, 从`get_problem_list_url()`获取的url就是题目列表页url。 对于`htmltext`会调用`check_and_handle_htmltext`函数进行处理。 返回一个有序的整数列表,为解析出来的题目列表页的索引列表。 >>> from vjudge import hdoj >>> from urllib.request import urlopen >>> htmltext = urlopen(hdoj.get_problem_list_url()) >>> hdoj.from_html_get_problem_volumes() [1, 2, 3, 4, 5, ...] """ htmltext = check_and_handle_htmltext(htmltext).strip() vollist = list(set(map(int, _problist_vol_re.findall(htmltext)))) vollist.sort() return vollist @coroutine def get_problem_volumes(): url = get_problem_list_url(1) response = yield Task(client.get, url) return from_html_get_problem_volumes(response.body) def _get_problem_title(string): """ 从题目的HTML文本字符串中匹配`title`信息 """ res_list = _probinfo_title_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return None elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_time_limit(string): """ 从题目的HTML文本字符串中匹配`time_limit`信息 """ res_list = _probinfo_time_limit_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return None elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0] def _get_problem_memory_limit(string): """ 从题目的HTML文本字符串中匹配`memory_limit`信息 """ res_list = _probinfo_memory_limit_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到信息 return None elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0] def _get_problem_special_judge(string): """ 从题目的HTML文本字符串中匹配`special_judge`信息 返回`bool`类型 """ res_list = _probinfo_special_judge_re.findall(string) if len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return bool(res_list) def _get_problem_description(string): """ 从题目的HTML文本字符串中匹配`description`信息 """ res_list = _probinfo_description_re.findall(string) if len(res_list) == 0: # TODO: error, 没有匹配到题目描述信息 return "" elif len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass return res_list[0].strip() def _get_problem_input(string): """ 从题目的HTML文本字符串中匹配`input`信息 题目信息中可能没有Input,因此如果未匹配成功将返回空字符串。 """ res_list = _probinfo_input_re.findall(string) if len(res_list) > 1: # TODO: warn, 匹配的信息个数大于一 pass elif len(res_list) == 0: # TODO: info, 没有匹配到题目输入描述信息 return "" return res_list[0].strip() def _get_problem_output(string): """ 从题目的HTML文本字符串中匹配`output`信息 """ res_list = _probinfo_output_re.findall(string) if len(res_list) > 1: # TODO: warn, 匹配到的信息个数大于一 pass elif len(res_list) == 0: # TODO: info, 没有匹配到题目输出描述信息 return "" return res_list[0].strip() def _get_problem_sample_input(string): """ 从题目的HTML文本字符串中匹配`sample_input`信息 题目可能没有Sample Input信息,因此如果未匹配成功将返回空字符串。 """ res_list = _probinfo_sample_input_re.findall(string) if len(res_list) > 1: # TODO: warn, 匹配到的信息个数大于一 pass elif len(res_list) == 0: # TODO: info, 没有匹配到题目样例输入的信息 return "" return res_list[0] def _get_problem_sample_output(string): """ 从题目的HTML文本字符串中匹配`sample_output`信息 """ res_list = _probinfo_sample_output_re.findall(string) if len(res_list) > 1: # TODO: warn, 匹配到的信息个数大于一 pass elif len(res_list) == 0: # TODO: warn, 没有匹配到题目样例输出信息 return "" return res_list[0] def _get_problem_source(string): """ 从题目的HTML文本字符串中匹配`source`信息 匹配成功后会对结果字符串做`strip()`方法处理。 """ res_list = _probinfo_source_re.findall(string) if len(res_list) > 1: # TODO: warn, 匹配到的信息个数大于一 pass elif len(res_list) == 0: # TODO: info, 没有匹配到题目来源信息 return "" return res_list[0].strip() def _get_problem_hint(string): """ 从题目的HTML文本字符串中匹配`hint`信息 """ res_list = _probinfo_hint_re.findall(string) if len(res_list) > 1: # TODO: warn, 匹配到的信息个数大于一 pass elif len(res_list) == 0: # TODO: info, 没有匹配到题目提示信息 return "" return res_list[0].strip() _probinfo_title_re = re.compile(r"<h1 style='color:#1A5CC8'>(.*)</h1>") _probinfo_time_limit_re = re.compile(r">Time Limit:[\s\S]*?(\d+) MS") _probinfo_memory_limit_re = re.compile(r"Memory Limit:[\s\S]*?(\d+) K") _probinfo_special_judge_re = re.compile( r"<font color=red>Special Judge</font>" ) _probinfo_description_re = re.compile( r">Problem Description</div> <div class=panel_content>(.*?)</div><div " "class=panel_bottom>&nbsp;</div><br><div class=panel_title align=left>" ) _probinfo_input_re = re.compile( r">Input</div> <div class=panel_content>(.*?)</div><div " "class=panel_bottom>&nbsp;</div><br><div class=panel_title align=left>" ) _probinfo_output_re = re.compile( r">Output</div> <div class=panel_content>(.*?)</div><div " "class=panel_bottom>&nbsp;</div><br><div class=panel_title align=left>" ) _probinfo_sample_input_re = re.compile( r'>Sample Input</div><div class=panel_content><pre><div ' 'style="font-family:Courier New,Courier,monospace;">' '([\s\S]*?)</div></pre></div><div class=panel_bottom>' '&nbsp;</div><br><div class=panel_title align=left>' ) _probinfo_sample_output_re = re.compile( r'>Sample Output</div><div class=panel_content><pre><div ' 'style="font-family:Courier New,Courier,monospace;">' '([\s\S]*?)</div></pre></div><div class=panel_bottom>' '&nbsp;</div><br><div class=panel_title align=left>' ) _probinfo_source_re = re.compile( r">Source</div> <div class=panel_content>" "\s*?(?:<a[^<>]*?>)?([^<>]*?)(?:</a>)?\s*?" "</div>\s*?<[^<>]*?panel_[^<>]*?>" ) _probinfo_hint_re = re.compile(r'<i>Hint</i></div>([\s\S]*?)</div>') _problist_problem_re = re.compile( r'p\([01],(?P<origin_id>\d+),[-\d]+?,"(?P<title>.*?)",\d+,\d+\);' ) _problist_vol_re = re.compile(r'href=listproblem\.php\?vol=(\d+)') <file_sep>/application/db/models/base.py #-*- coding: utf-8 -*- from witcoder import orm class BaseModel(orm.Model): __abstract__ = True pass <file_sep>/application/media/views.py # -*- coding: utf-8 -*- import json import time import logging import hashlib import requests from tornado.web import authenticated, HTTPError from tornado.httpclient import HTTPRequest from tornado.gen import coroutine from tornado.curl_httpclient import CurlAsyncHTTPClient from witcoder import qiniu from db.models.account import User from common.web import BaseHandler logger = logging.getLogger("witcoder.media") class UploadAvatarHandler(BaseHandler): httpclient = CurlAsyncHTTPClient() @authenticated @coroutine def post(self): # x = self.get_argument("x") # y = self.get_argument("y") # w = self.get_argument("w") # h = self.get_argument("h") avatar = self.request.files["avatar"][0] res = yield self.upload_avatar(avatar) if res.get("key") != "avatar/" + self.current_user.username: logger.error("Upload avatar error! " "response info: {}".format(res)) raise HTTPError(500) user = self.db.session.query(User).get(self.current_user.id) if user is None: logger.error("Current user not exists! " "current user: {}".format(self.current_user)) raise HTTPError(500) user.avatar = hashlib.md5(str(time.time()).encode()).hexdigest() self.db.session.merge(user) try: self.db.session.commit() except: self.db.session.rollback() logger.exception("Avatar database update error! " "user: {}".format(user.username)) raise HTTPError(500) self.set_secure_cookie("session", json.dumps({ "id": self.current_user.id, "username": self.current_user.username, "nickname": self.current_user.nickname, "avatar": user.avatar, })) self.redirect(self.reverse_url("user-setting", "basic")) @coroutine def upload_avatar(self, avatar): upload_url = "http://upload.qiniu.com" key = "avatar/" + self.current_user.username token = qiniu.upload_token("wit<PASSWORD>", key, 3600) preq = requests.Request( url=upload_url, method="POST", data={"token": token, "key": key}, files={"file": (avatar["filename"], avatar["body"], "application/octet-stream", {"Content-Transfer-Encoding": "binary"})} ).prepare() request = HTTPRequest(url=upload_url, method="POST", headers=preq.headers, body=preq.body) response = yield self.httpclient.fetch(request) res = json.loads(response.body.decode()) return res pass <file_sep>/application/templates/ui/vjudge/create-exercise.js problem_list_template = ['<tr><td><b>1</b></td><td class="form-inline input-problem-origin">', '<select class="form-control remote_oj"><option value="HDOJ">HDOJ</option>', '</select> <input class="form-control remote_pid" type="text" placeholder="题目编号,如1000">', '<input class="form-control problem_id" form="new-exercise" type="hidden" name="problem_id" value=""></td><td>', '<input class="form-control problem_title" form="new-exercise" type="text" name="problem_title" placeholder="可在此设置自定义题目标题,默认原标题">', '</td><td><span class="label label-default check-status">未验证</span></td><td>', '<a class="btn btn-primary handle" role="button">确认</a> <a class="btn btn-danger delete" role="button">删除</a></td></tr>'].join('\n'); datetimepicker_config = { locale: "zh-CN", format: "YYYY-MM-DD HH:mm:ss", } function alert_server_error() { $("#title").append( '<div class="alert alert-danger alert-dismissible" role="alert">' + '<button class="close" type="button" data-dismiss="alert">' + '<span aria-hidden="true">&times;' + '</span></button> 服务器出现错误!</div>'); } $(function() { $("#input-starttime").datetimepicker(datetimepicker_config); $("#input-endtime").datetimepicker(datetimepicker_config); }); function update_problem_order() { problem_list = $("#problem-list>tbody").children(); for (var i=0; i<problem_list.length; ++i) { id = i + 1; tr_obj = $(problem_list[i]); tr_obj.find("b").text(id); tr_obj.find("a.handle").unbind("click", handle_problem); tr_obj.find("a.delete").unbind("click", delete_problem); tr_obj.find("a.handle").bind("click", handle_problem); tr_obj.find("a.delete").bind("click", delete_problem); } } function delete_problem() { $(this).parent().parent().remove(); update_problem_order(); } function handle_problem() { var tr_obj = $(this).parent().parent(); var remote_oj = tr_obj.find(".remote_oj").val(); var remote_pid = tr_obj.find(".remote_pid").val(); var check_status = tr_obj.find(".check-status"); var problem_title = tr_obj.find(".problem_title"); var problem_id = tr_obj.find(".problem_id"); btn = $(this); btn.toggleClass("btn-primary btn-success"); if (btn.text() === "确认") { btn.text("编辑"); tr_obj.find(".remote_oj").attr("disabled", ""); tr_obj.find(".remote_pid").attr("readonly", ""); tr_obj.find(".problem_title").attr("readonly", ""); if (remote_pid === "") { check_status.removeClass("label-default label-success label-danger"); check_status.addClass("label-danger"); check_status.text("验证失败"); } else { $.ajax({ url: "/api/vjudge/problem?remote_oj=" + remote_oj + "&remote_pid=" + remote_pid, type: "GET", success: function(response) { var obj = response; if (obj.status === 200) { check_status.removeClass("label-default label-success label-danger"); check_status.addClass("label-success"); check_status.text("验证成功"); problem_id.val(obj.data.id); if (!$.trim(problem_title.val())) { problem_title.val(obj.data.title); } } else { check_status.removeClass("label-default label-success label-danger"); check_status.addClass("label-danger"); check_status.text("验证失败"); } }, error: function(response) { check_status.removeClass("label-default label-success label-danger"); check_status.addClass("label-danger"); check_status.text("验证失败"); }, }); } } else { // Edit btn.text("确认"); tr_obj.find(".remote_oj").attr("disabled", null); tr_obj.find(".remote_pid").attr("readonly", null); tr_obj.find(".problem_title").attr("readonly", null); check_status.removeClass("label-default label-success label-danger"); check_status.addClass("label-default"); check_status.text("未验证"); }; } $("a.handle").click(handle_problem); $("a.delete").click(delete_problem); $("#add-problem").click(function() { problem_list = $("#problem-list>tbody").children(); if (problem_list.length >= 26) { } else { $("#problem-list>tbody").append(problem_list_template); } update_problem_order(); }); $("#create-exercise").click(function() { btn = $(this); btn.button("loading"); $.ajax({ url: "/vjudge/exercise/create", type: "POST", data: $("#new-exercise").serialize(), success: function(response) { var obj = response; if (obj.status === 200) { window.location("/vjudge/exercise/"); } else if (obj.status === 400) { if (obj.data.field === "problem") { $("#problem-setting-link").tab("show"); $("#problem-setting").prepend('<div class="alert alert-danger alert-dismissible" role="alert">' + '<button class="close" type="button" data-dismiss="alert"><span aria-hidden="true">&times;' + '</span></button> ' + obj.data.message + '</div>'); } else { $("#basic-setting-link").tab("show"); $("#input-" + obj.data.field + "-message").parent().addClass("has-error"); $("#input-" + obj.data.field + "-message").text(obj.data.message); } } else { alert_server_error(); } btn.button("reset"); }, error: function() { alert_server_error(); btn.button("reset"); }, }); return false; }); $(".form-group input").change(function() { $(this).parent().removeClass("has-error"); $(this).next().text(""); }); <file_sep>/application/templates/ui/account/user_basic_setting_form.js $("#user-basic-setting-form button").click(function() { $(this).button("loading"); $.ajax({ url: "/setting/user/basic", type: "POST", data: $("#user-basic-setting-form").serialize(), success: function(response) { var obj = response; if (obj.status === 200) { window.location.reload(); } else if (obj.status === 400) { $("#setting-" + obj.data.field).parent().addClass("has-error"); $("#setting-" + obj.data.field + "-message").text(obj.data.message); $("#user-basic-setting-form button").button("reset"); } else { // 服务器错误 } }, }); return false; }); $("#user-basic-setting-form input,textarea").change(function() { $(this).parent().removeClass("has-error"); $(this).next().text(""); }); <file_sep>/application/auth/utils/algorithm.py # -*- coding: utf-8 -*- import hashlib def auth_md5(password): """MD5加密算法,返回加密后的字符串""" bytes_string = password.encode() return hashlib.md5(bytes_string).hexdigest() <file_sep>/Dockerfile FROM daocloud.io/library/python:3.4.3 MAINTAINER JZQT <<EMAIL>> ADD requirements.txt /Witcoder/requirements.txt ADD witcoder /Witcoder/witcoder RUN pip install -r /Witcoder/requirements.txt <file_sep>/application/vjudge/zoj/attribute.py #!/usr/bin/env python3 #coding=utf-8 """ Virtual Judge ZOJ 属性模块 """ STD_NAME = "ZOJ" # ZOJ 常用名 NAME_SET = {"ZOJ", "ZJU"} # ZOJ 主页url HOST_URL = "http://acm.zju.edu.cn/onlinejudge" # 网页编码 CHARSET = 'utf-8' # 账号登陆url LOGIN_URL = HOST_URL + '/login.do' # 账号登陆HTTP方法 LOGIN_METHOD = 'POST' # 代码提交url SUBMIT_CODE_URL = HOST_URL + '/submit.do' #编译错误信息 url VIEW_COMPILATION_INFO_URL = HOST_URL + '/showJudgeComment.do' # 评测信息 url VIEW_JUDGE_STATUS_URL = HOST_URL + '/showRuns.do' # 代码提交编程语言编号 SUBMISSION_CODE_LANGUAGE_ID_TABLE = { 'C (gcc 4.7.2)': 1, 'C++ (g++ 4.7.2)': 2, 'FPC (fpc 2.6.0)': 3, 'Java (java 1.7.0)': 4, 'Python (Python 2.7.3)': 5, 'Perl (Perl 5.14.2)': 6, 'Scheme (Guile 1.8.8)': 7, 'PHP (PHP 5.4.4)': 8, 'C++0x (g++ 4.7.2)': 9, } #标准编程语言碓应的ZOJ编程语言 STD_CODE_LANGUAGE_ZOJ_CODE_LANGUAGE = { #'G++': 'C++ (g++ 4.7.2)', #'GCC': 'C (gcc 4.7.2)', #'JAVA': 'Java (java 1.7.0)', #'C': 'C (gcc 4.7.2)', #'C++': 'C++ (g++ 4.7.2)', 'C (gcc 4.7.2)': 1, 'C++ (g++ 4.7.2)': 2, 'FPC (fpc 2.6.0)': 3, 'Java (java 1.7.0)': 4, 'Python (Python 2.7.3)': 5, 'Perl (Perl 5.14.2)': 6, 'Scheme (Guile 1.8.8)': 7, 'PHP (PHP 5.4.4)': 8, 'C++0x (g++ 4.7.2)': 9, } # 评测信息编程语言编号 JUDGE_INFO_CODE_LANGUAGE_ID_TABLE = { 'C': 1, 'C++': 2, 'FPC': 3, 'Java': 4, 'Python': 5, 'Perl': 6, 'Scheme': 7, 'PHP': 8, 'C++0x': 9, } # 评测信息结果编号 JUDGE_INFO_JUDGE_STATUS_ID_TABLE = { 'All': '', 'WA': 4, 'AC': 5, 'TLE': 6, 'MLE': 7, 'OLE': 10, 'CE': 12, 'PE': 13, 'Floating Point Error': 15, 'Segmentation Fault': 16, 'Non-zero Exit Code': 21, } #评测结果 格式化 JUDGE_STATUS_FORMAT = { 'Accepted': 'Accepted', 'Presentation Error': 'Presentation Error', 'Wrong Answer': 'Wrong Answer', 'Time Limit Exceeded': 'Time Limit Exceeded', 'Memory Limit Exceeded': 'Memory Limit Exceeded', 'Compilation Error': 'Compilation Error', 'Non-zero Exit Code': 'Runtime Error', 'Floating Point Error': 'Runtime Error', 'Segmentation Fault': 'Runtime Error', 'Output Limit Exceeded': 'Output Limit Exceeded', } JUDGE_STATUS_FORMAT_SHORT = { 'Accepted': 'AC', 'Presentation Error': 'PE', 'Wrong Answer': 'WA', 'Time Limit Exceeded': 'TLE', 'Memory Limit Exceeded': 'MLE', 'Compilation Error': 'CE', 'Non-zero Exit Code': 'RE', 'Floating Point Error': 'RE', 'Segmentation Fault': 'RE', 'Output Limit Exceeded': 'OLE', } ZOJ_CE = "Compilation Error" # 编译错误信息 url CE_url = 'http://acm.zju.edu.cn/onlinejudge/showJudgeComment.do' # ZOJ检查代理情况的时间间隔,单位为秒 CHECK_TIME_INTERVAL = 25 * 60 # 30分钟Cookie失效,故25分钟检查一次吧 <file_sep>/application/db/models/vjudge/problem.py # coding: utf-8 """Witcoder Virtual Judge 题目相关数据表Model""" from sqlalchemy import text from sqlalchemy.orm import relationship from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint from sqlalchemy.types import Integer, String, Text, Boolean from sqlalchemy.dialects.postgresql import JSONB from db.models.base import BaseModel class Problem(BaseModel): """ Virtual Judge 题目主表Model 数据表关系: `submissions`: 与`Submission`的一对多关系 `statistics`: 与`ProblemStatistics`的一对一关系 索引: `id`: 主键上的索引 `url`: 用来替代`remote_oj`和`remote_pid`的组合唯一索引 """ __tablename__ = 'tb_virtual_judge_problem' # 表结构 id = Column(Integer, primary_key=True, index=True) remote_oj = Column(String(20), nullable=False) remote_pid = Column(String(20), nullable=False) url = Column(String(500), nullable=False, unique=True) title = Column(String(100), nullable=False) special_judge = Column(Boolean, nullable=False, default=False, server_default=text('FALSE')) time_limit = Column(Integer, nullable=False, default=0, server_default=text('0')) memory_limit = Column(Integer, nullable=False, default=0, server_default=text('0')) description = Column(Text, nullable=False, default="", server_default="") input = Column(Text, nullable=False, default="", server_default="") output = Column(Text, nullable=False, default="", server_default="") sample_input = Column(Text, nullable=False, default="", server_default="") sample_output = Column(Text, nullable=False, default="", server_default="") hint = Column(Text, nullable=False, default="", server_default="") source = Column(Text, nullable=False, default="", server_default="") extra = Column(JSONB, nullable=False, default={}, server_default="{}") # 关系 submissions = relationship("Submission", backref="problem", cascade="all") statistics = relationship("ProblemStatistics", backref="problem", cascade="all", uselist=False) # 其他约束 UniqueConstraint(remote_oj, remote_pid) def __iter__(self): for key in self._fields: yield (key, getattr(self, key)) def __repr__(self): return "<Problem({}-{})>".format(self.remote_oj, self.remote_pid) def __str__(self): return repr(self) @classmethod def get_field_dict(cls): """获取字段字典,key为公开字段,value为真实字段""" return {"id": "id", "remote_oj": "remote_oj", "remote_pid": "remote_pid", "url": "url", "title": "title", "special_judge": "special_judge", "time_limit": "time_limit", "memory_limit": "memory_limit", "description": "description", "input": "input", "output": "output", "sample_input": "sample_input", "sample_output": "sample_output", "hint": "hint", "source": "source", "extra": "extra"} @property def name(self): """ 题目名称属性 题目名称格式为`remote_oj`-`remote_pid`。 """ if not hasattr(self, "_name"): self._name = ''.join((self.remote_oj, '-', self.remote_pid)) return self._name @classmethod def register(cls, **kwargs): """在数据库中注册一个`Problem`对象 会自动创建相关联的数据库对象比如`ProblemStatistics`等。 """ problem = cls(**kwargs) problem.statistics = ProblemStatistics() return problem def to_dict(self, *fields): """返回数据字典 不安全,不检查字段是否存在。 :params fields: 虚拟字段列表。 """ if not fields: fields = self.get_field_dict().keys() return {field: getattr(self, field) for field in fields} pass class ProblemStatistics(BaseModel): """ Virtual Judge 题目统计信息表Model 统计题目的提交信息。 数据表关系: `problem`: 与`Problem`的一对一关系,参见`tb_problem`表 索引: `id`: 主键上的索引 """ __tablename__ = "tb_virtual_judge_problem_statistics" # 表结构 id = Column(Integer, ForeignKey("tb_virtual_judge_problem.id"), primary_key=True, index=True) total = Column(Integer, nullable=False, default=0, server_default=text('0')) ac = Column(Integer, nullable=False, default=0, server_default=text('0')) _fields = ('id', 'total', 'ac') def __repr__(self): return "<ProblemStatistics(id={})>".format(self.id) pass <file_sep>/application/common/tests/case.py #-*- coding: utf-8 -*- import unittest class CommonTestCase(unittest.TestCase): pass <file_sep>/application/vjudge/views/__init__.py # -*- coding: utf-8 -*- from common.web import BaseHandler from vjudge.generic import get_online_judge class VjudgeHandler(BaseHandler): def initialize(self, *args, **kwargs): super(VjudgeHandler, self).initialize(*args, **kwargs) self.tplkw.update({ "get_online_judge": get_online_judge }) pass <file_sep>/application/db/models/__init__.py #-*- coding: utf-8 -*- """ Witcoder 数据表Model """ from .base import BaseModel from .account.user import User, UserInfo from . import vjudge <file_sep>/application/admin/views.py #-*- coding: utf-8 -*- from common.web import BaseHandler from admin import admin @admin.route(r'') class IndexHandler(BaseHandler): def get(self): self.render("admin/index.html") pass <file_sep>/doc/bug.md |题目 |备注 | |:----------|:----------------------| |`HDOJ-1226`|Sample Output中有Hint | |`HDOJ-2195`|Sample Output中有Hint | |`HDOJ-2207`|Description中有Hint | |`HDOJ-3602`|Sample Output有多余换行| |`HDOJ-4300`|Input中有Hint | `HDOJ-3420`题意坑爹 当数据库没有题目的时候题目页面依然显示多少多少页vol。 从VJ提交HDOJ代码,添加`// 中文`到代码末尾会编译错误?! 注册功能有bug,没有检验表单 <file_sep>/application/vjudge/views/submit.py # -*- coding: utf-8 -*- import logging # import sqlalchemy.orm.exc from sqlalchemy.orm import load_only from tornado.web import HTTPError, authenticated from tornado.gen import coroutine from db.models.vjudge import Problem, Submission from common.web import BaseHandler from common.utils import convert_linesep from vjudge.generic import get_online_judge logger = logging.getLogger("witcoder.vjudge") class SubmitHandler(BaseHandler): """ 代码提交视图 """ @authenticated @coroutine def post(self, submit_type): submit = { "problem": self.general_submit, "exercise": self.exercise_submit, "contest": self.contest_submit }.get(submit_type) if submit is None: raise HTTPError(404) pass yield submit() @coroutine def general_submit(self): form = self.get_general_submit_form() submission = Submission.register(**form) submission.problem = self.db.session.query(Problem).options( load_only("id", "remote_oj", "remote_pid") ).get(submission.problem_id) if submission.problem is None: raise HTTPError(400) try: self.db.session.add(submission) self.db.session.commit() except Exception: self.db.session.rollback() logger.error("Add submission error.", exc_info=True) raise else: self.redirect("/vjudge/submission/") yield self.submit(submission) try: self.db.session.merge(submission) self.db.session.commit() except Exception: self.db.session.rollback() logger.error("Submission `{}` update error!".format(submission.id), exc_info=True) try: submission.status = "Virtual Judge Error" self.db.session.commit() except Exception: self.db.session.rollback() self.fatal("Can't set submission `{}` status to " "'Virtual Judge Error'.".format(submission.id), exc_info=True) pass @coroutine def submit(self, submission): oj = get_online_judge(submission.problem.remote_oj) try: info = yield oj.client.submit_code( remote_pid=submission.problem.remote_pid, language=submission.language, source_code=submission.source.code ) except Exception: logger.error("Submit submission error!", exc_info=True) submission.status = "Submit Error" try: result = yield oj.client.fetch_result(**info) except Exception: logger.error("Fetch submission error!", exc_info=True) submission.status = "Fetch Error" else: submission.update(result) def get_general_submit_form(self): form = { "problem_id": int(self.get_query_argument("pid")), "language": self.get_body_argument("language"), "shared": bool(self.get_body_argument("shared")), "source_code": self.get_body_argument("source_code").strip() } form["source_code"] = convert_linesep(form["source_code"]) form["source_code"] = form["source_code"].replace("\t", " ") form["submitter_id"] = self.current_user.id form["code_length"] = len(form["source_code"].encode()) return form @coroutine def exercise_submit(self): pass @coroutine def contest_submit(self): pass pass <file_sep>/application/vjudge/zoj/tools.py #!/usr/bin/env python3 #coding=utf-8 from ..tools.agent import AsyncAgent from .attribute import (CHARSET, SUBMISSION_CODE_LANGUAGE_ID_TABLE, JUDGE_INFO_CODE_LANGUAGE_ID_TABLE, JUDGE_INFO_JUDGE_STATUS_ID_TABLE, JUDGE_STATUS_FORMAT, ZOJ_CE, STD_CODE_LANGUAGE_ZOJ_CODE_LANGUAGE,) client = AsyncAgent() def get_submission_origin_code_language_id(remote_codelang): """ 将ZOJ的代码提交编程语言转换成提交表单使用的ID """ #origin_code_language_id = SUBMISSION_CODE_LANGUAGE_ID_TABLE.get(remote_codelang, None) #if origin_code_language_id is None: #raise ValueError("The `remote_code_language` '{}' not in the ZOJ " #"`CODE_LANGUAGE_ID_TABLE`.".format(remote_codelang)) return remote_codelang def get_judge_info_origin_code_language_id(origin_code_language="All"): """ 将筛选ZOJ评测信息时选择的编程语言转换成查询字符串中对应的ID 默认`origin_code_language`为`All`,即不做编程语言筛选。 此功能ZOJ暂不需要 """ pass def get_judge_info_origin_judge_status_id(origin_judge_status="All"): """ 将筛选HDOJ评测信息时的评测状态转换为查询字符串中对应的ID ZOJ不需要 """ pass def judge_finished(status): """ 根据源OJ的评测状态判断评测是否完成 """ if status in {"Queuing", "Running", "Compiling", ""}: return False return True def get_origin_pid(remote_pid): origin_pid = int(remote_pid) - 1000 return str(origin_pid) def is_compilation_error(status): """ 判断源OJ的评测状态是否为编译错误 返回布尔值。 """ if status.find(ZOJ_CE) < 0: return False return True def check_and_handle_htmltext(htmltext): # 检查 `htmltext` if isinstance(htmltext, bytes): htmltext = htmltext.decode(CHARSET, 'ignore') elif not isinstance(htmltext, str): raise TypeError("The type of `htmltext` is " "{}.".format(type(htmltext))) return htmltext.replace('\r\n', '\n') def to_origin_code_language(code_language): """ Virtual Judge 标准格式编程语言转ZOJ格式编程语言 """ print(code_language) return STD_CODE_LANGUAGE_ZOJ_CODE_LANGUAGE[code_language] def to_judge_status(origin_code_language): """ ZOJ 格式的编程语言转换成Virtual Judge标准格式的编程语言 """ return JUDGE_STATUS_FORMAT.get(origin_code_language, "Fetch Error") def to_judge_result(judge_info): """ 将ZOJ的评测信息转换成Virtual Judge提交后的标准化评测结果 用于讲ZOJ爬取的源匹配信息转换成Virtual Judge格式的,有效的评测结果。 """ judge_result = { "origin_oj": "ZOJ", "origin_pid": judge_info['origin_pid'], "judge_status": to_judge_status(judge_info['origin_judge_status']), "time_cost": judge_info['origin_time_cost'], "memory_cost": judge_info['origin_memory_cost'], "code_language": to_judge_status(judge_info['origin_code_language']), "origin_judge_key": judge_info['origin_judge_key'], "origin_judge_status": judge_info['origin_judge_status'], "compilation_info": judge_info.get('compilation_info'), } return judge_result <file_sep>/application/auth/views.py # coding: utf-8 import logging from db.models import User from common.web import BaseHandler from auth.utils.mixins import UserAuthenticationAPIMixin logger = logging.getLogger("witcoder.auth") class AuthHandler(BaseHandler, UserAuthenticationAPIMixin): """用户登录注册认证视图""" def get(self, auth_type): if self.current_user: # 已登录用户重定向到首页 self.redirect(self.get_query_argument("next", "/index")) self.render("auth.html") def post(self, auth_type): """提交登录或注册表单请求的处理 请求最终会返回JSON类型为主体的响应,供前端ajax使用。 关于返回的JSON具体内容,请查看 `UserAuthenticationAPIMixin.user_login_check`方法。 """ if auth_type == "login": self.user_login({ "user": self.get_body_argument("user", ""), "password": self.get_body_argument("password", ""), }) else: self.user_register({ "username": self.get_body_argument("username", ""), "password": self.get_body_argument("password", ""), "repassword": self.get_body_argument("repassword", ""), "email": self.get_body_argument("email", ""), }) def user_login(self, form_data): result = self.user_login_check(form_data) if result["status"] == 200: self.set_session_cookie(result.pop("data")) self.write(result) def user_register(self, form_data): result = self.user_register_check(form_data) if result["status"] == 200: new_user = User.register(form_data["username"], form_data["password"], form_data["email"]) assert new_user.verify_password(form_data["password"]) try: self.db.session.add(new_user) self.db.session.commit() except: log = "Add new user failed. form data: {}.".format(form_data) logger.error(log, exc_info=True) self.db.session.rollback() result = {"status": 500, "message": "Server Error"} else: self.set_session_cookie(new_user.get_session()) self.write(result) pass class LogoutHandler(BaseHandler): """用户注销视图""" def get(self): self.clear_session_cookie(redirect="/index") pass <file_sep>/application/common/utils.py # coding: utf-8 from datetime import timedelta import html.parser import urllib.parse from common.regex import linesep_re DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DAYS = timedelta(1) MINUTES = timedelta(0, 60) HOURS = timedelta(0, 60 * 60) def urljoin(baseurl: str, relaurl: str) -> str: """将相对url转换为绝对url并返回,`urllib.parse.urljoin`增强版 解决`urllib.parse.urljoin`合并url后还会出现"../"以及"./"路径的问题。 :param str baseurl: 当前位置绝对URL。 :param str relaurl: 基于当前位置URL的相对URL。 示例:: >>> urljoin('http://www.witcoder.com/hehe', ... '../../../../heheda') 'http://www.witcoder.com/heheda' >>> urljoin('https://www.witcoder.com/hehe', ... 'http://code.witcoder.com') 'http://code.witcoder.com' >>> urljoin('https://www.witcoder.com/', ... '//api.witcoder.com') 'https://api.witcoder.com' """ joinurl = urllib.parse.urljoin(baseurl, relaurl) return joinurl.replace("../", "").replace("./", "") def convert_linesep(string, linesep='\n'): """转换字符串的行间隔符风格 将字符串行间隔符转换为指定的格式,比如'\n','\r'和'\r\n'。 默认转换成Unix系统风格的行间隔符。 各种系统平台的行间隔符风格: * Unix, Linux等 '\n' * MacOS '\r' * Windows '\r\n' :param str string: 待转换的字符串。 :param str linesep: 转换后的行间隔符,默认是'\n'。 示例:: >>> convert_linesep('\n\n\n\n\n\n', '\r') '\r\r\r\r\r\r' >>> convert_linesep('hello\r\nworld\r\n') 'hello\nworld\n' """ return linesep_re.sub(linesep, string) class HTMLFormatter(html.parser.HTMLParser): """HTML格式器 HTML格式器根据配置项来选择HTML格式化的方式。 初始化`HTMLFormatter`时可设置固定配置项,在调用`.format_html()`方法时可 设置临时配置项,也就是说调用`.format_html()`方法时会使用固定配置和临时配 置合并后的配置项(即`.fixed_settings.update(temp_settings)`)。配置项以关 键字参数的形式提供(比如`HTMLFormatter(autoclose=True)`)。 相关配置项参数请查看`.__init__()`方法。 示例:: >>> HTMLFormatter().format_html("<img src=./static/1.jpg>") '<img src="./static/1.jpg">' >>> HTMLFormatter().format_html("<br/>") '<br />' """ # 值为url的属性 _url_attrs = ("src", "href", "action") # 自闭合标签 _self_closing_tags = ("area", "base", "br", "hr", "img", "input", "link", "meta") def __init__(self, *, convert_charrefs=False, **fixed_settings): """初始化HTML格式器 除了`convert_charrefs`这个参数是`html.parser.HTMLParser`初 始化需要的,其他关键字参数都是配置项参数。 :param bool convert_charrefs: HTML字符实体转换Unicode字符。 如果为`True`,会转换HTML字符实体为对应的Unicode字符,比如'&lt;'转 换成'<','&#123;'转换成'{'。默认为`False`,不转换HTML字符实体。 :param bool joinurl: 转换相对URL为绝对URL。如果为`True`,格式化HTML时会 将HTML中的所有url(包括src属性值,href属性值等)转换成绝对url。设置 该配置项为`True`的同时也需要设置`url`配置项参数作为格式化的HTML文本 的url。默认该配置项为`False`。 :param str url: 设置HTML的url。 :param bool autoclose: 自动闭合自闭合标签。如果为`True`,那么遇到没有 自闭和的自闭和标签,会格式化成自闭和的标签。如果为`False`,那么不 做额外处理。默认为`False`。 """ super(HTMLFormatter, self).__init__(convert_charrefs=convert_charrefs) self.fixed_settings = fixed_settings self.temp_settings = {} def format_html(self, string: str, **temp_settings) -> str: """返回格式化后的HTML字符串 该方法会调用`._check_settings()`检查合并配置项的关键字参数,如果有不 规范的地方会抛出异常。比如配置项设置`joinurl`为`True`,那么配置项中没 有`url`会抛出异常。 :param str string: 要格式化的HTML字符串。 :param temp_settings: 临时配置项,相关配置项参数查看`.__init__()`方法。 """ self.temp_settings = temp_settings self._check_settings() self.buffer_list = [] self.feed(string) self.temp_settings = {} result = ''.join(self.buffer_list) self.buffer_list = None return result def get_setting(self, key, default=None): """从合并后的配置项中获取配置 如果临时配置项有设置该`key`,返回临时配置项的配置,否则返回固定配置项 的配置,如果固定配置项也没有则返回`default`参数设定的值。 """ if key in self.temp_settings: return self.temp_settings[key] return self.fixed_settings.get(key, default) def _check_settings(self): if self.get_setting("joinurl") and not self.get_setting("url"): raise Exception("Setting 'url' cannot be empty " "when `joinurl` is set to `True`.") def handle_starttag(self, tag, attrs): self.buffer_list.append("<{}".format(tag)) for name, value in attrs: if value is None: self.buffer_list.append(" {}".format(name)) continue if self.get_setting("joinurl") and name in self._url_attrs: # 转换成绝对url value = urljoin(self.get_setting("url"), value) # 下面的if-else处理在极端情况下可能有bug # 比如 <tag name='a"b'></tag> if value.find('"') > -1: self.buffer_list.append(" {}='{}'".format(name, value)) else: self.buffer_list.append(' {}="{}"'.format(name, value)) if self.get_setting("autoclose") and tag in self._self_closing_tags: self.buffer_list.append(" />") else: self.buffer_list.append(">") def handle_endtag(self, tag): self.buffer_list.append("</{}>".format(tag)) def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) self.buffer_list[-1] = " />" def handle_data(self, data): self.buffer_list.append(data) def handle_comment(self, data): self.buffer_list.extend(("<!--", data, "-->")) def handle_entityref(self, name): self.buffer_list.append("&{};".format(name)) def handle_charref(self, name): self.buffer_list.append("&#{};".format(name)) pass def paginate(current, total, display=5): """ 分页算法 `current`: 当前页 `total`:总页数 `display`:显示页数 用于智能显示分页,返回一个元素为整数的列表表示显示页列表。 当总页数不大于显示页数时,全部显示。 当总页数大于显示页数时,尽可能将当前页居中显示,如果显示页数为偶数,那么当前页可以偏左居中。 如果当前页无法居中显示,即当前页处于靠近`0`或总页数的情况下,则只需要最前或最后的`dispaly`页。 如果`total`等于`0`,那么返回`[1]` example: >>> paginate(5, 9) [3, 4, 5, 6, 7] >>> paginate(1, 1) [1] >>> paginate(2, 10) [1, 2, 3, 4, 5] >>> paginate(16, 17) [13, 14, 15, 16, 17] >>> paginate(4, 10, 6) [2, 3, 4, 5, 6, 7] >>> paginate(7, 10, 6) [5, 6, 7, 8, 9, 10] >>> paginate(2, 3, 2) [2, 3] """ if total <= 0: return [1] elif display >= total: # 显示页数不小于总页数的情况 return [i for i in range(1, total + 1)] elif current <= display // 2: # 应该显示前`display`页的情况 return [i for i in range(1, display + 1)] elif current >= total - display // 2: # 应该显示后`display`页的情况 return [i for i in range(total + 1 - display, total + 1)] elif display % 2 == 0: return [i for i in range(current - display // 2 + 1, current + display // 2 + 1)] else: return [i for i in range(current - display // 2, current + display // 2 + 1)] <file_sep>/application/vjudge/views/submission.py # coding: utf-8 # import sqlalchemy.orm.exc from sqlalchemy import func from sqlalchemy.orm import joinedload from tornado.web import HTTPError, authenticated from db.models.account import User from db.models.vjudge import Submission from common.web import BaseHandler from common.utils import paginate class SubmissionListHandler(BaseHandler): def get(self): # TODO: page参数没有判断非法类型 page = int(self.get_query_argument("page", "1") or "1") count = int(self.get_query_argument("count", 20)) query_clause = self.get_submissions_query_clause() total_page = ((query_clause.count() + count - 1) // count) or 1 # 非法取值范围处理 page = page if page in range(1, total_page + 1) else 1 submissions = query_clause.limit(count).offset( count * (page - 1)).all() self.tplkw.update({"curr_page": page, "total_page": total_page, "page_list": paginate(page, total_page, 10), "submissions": submissions}) self.render("vjudge/submission-list.html") def get_submissions_query_clause(self): """获取根据表单数据过滤后的查询子句""" query_clause = self.db.session.query(Submission).options( joinedload("submitter").load_only("id", "username", "nickname"), joinedload("problem").load_only("id", "remote_oj", "remote_pid") ).order_by(Submission.id.desc()) form = self.get_form_data() if form["sid"] > 0: query_clause = query_clause.filter(Submission.id <= form["sid"]) if form["username"]: # 忽略大小写筛选用户名 query_clause = query_clause.filter( func.lower(User.username) == form["username"].lower() ) if form["status"]: query_clause = query_clause.filter( Submission._status == Submission.status2id.get(form["status"]) ) return query_clause def get_form_data(self): form = { "sid": int(self.get_query_argument("sid", "0") or 0), "username": self.get_query_argument("username", None), "status": self.get_query_argument("status", None), } return form pass class SubmissionInfoHandler(BaseHandler): @authenticated def get(self, submission_id): submission = self.db.session.query(Submission).options( joinedload("source"), joinedload("compilation"), joinedload("problem").load_only("id", "remote_oj", "remote_pid"), joinedload("submitter").load_only("id", "username", "nickname"), ).get(submission_id) if submission is None: raise HTTPError(404) if not submission.shared and (submission.submitter_id != self.current_user.id): raise HTTPError(403) self.render("vjudge/submission-info.html", submission=submission) pass <file_sep>/application/vjudge/exceptions.py # -*- coding: utf-8 -*- """Virtual Judge 异常模块""" class ProblemNotFound(Exception): """题目不存在或没有找到""" pass class VirtualJudgeError(Exception): """VirtualJudge内部异常""" pass class SubmitError(Exception): """VirtualJudge提交代码异常""" pass class FetchError(Exception): """VirtualJudge爬取代码异常""" pass <file_sep>/application/basesite/ui.py # coding: utf-8 from tornado.web import UIModule from witcoder.settings import UI class MarkdownEditor(UIModule): _js_files = [UI.cdn.js.jquery, "/static/editor/editormd.min.js"] def render(self): return "" def javascript_files(self): return self._js_files def embedded_javascript(self): return self.render_string("ui/editormd.js") pass <file_sep>/application/templates/admin/vjudge/editorproblem.html {% extends "../../base.html" %} {% block self_head %} <title>Vjudge - Witcoder</title> {% end %} {% block body_navbar %} {% end %} {% block body_content %} <div class="container"> <form method="POST"> {% raw xsrf_form_html() %} {% if problem.error == 1 %} <p class="bg-danger text-center">时间限制或者内存限制格式错误</p> {% end %} <div class="row"> <div class="col-md-6 col-md-offset-3"><h3 class="problem-text-title text-center">Title</h3><input type="text" value="{{ problem.title }}" class="form-control" name="title"></div> </div> <div class="row"> <div class="col-md-4 col-md-offset-1"> <div class="form-group"> <h4 class="problem-text-title text-center">时间限制(ms)<h4> <input class="form-control" value="{{ problem.time_limit }}" name="time_limit"> </div> </div> <div class="col-md-4 col-md-offset-1"> <div class="form-group"> <h4 class="problem-text-title text-center">内存限制(kb)<h4> <input class="form-control" value="{{ problem.memory_limit }}" name="memory_limit"> </div> </div> </div> <div class="row"> <div class="col-md-12"> <h3 class="problem-text-title">Description</h3> <div class="well well-sm"> <textarea class="form-control" name="description">{% raw problem.description %}</textarea> </div> <h3 class="problem-text-title">Input</h3> <div class="well well-sm"> <textarea class="form-control" name="input">{% raw problem.input %}</textarea> </div> <h3 class="problem-text-title">Output</h3> <div class="well well-sm"> <textarea class="form-control" name="output">{% raw problem.output %}</textarea> </div> <h3 class="problem-text-title">Sample Input</h3> <pre><code><textarea class="form-control" name="sample_input">{% raw problem.sample_input %}</textarea></code></pre> <h3 class="problem-text-title">Sample Output</h3> <pre><code><textarea class="form-control" name="sample_output">{% raw problem.sample_output %}</textarea></code></pre> <h3 class="problem-text-title">Hint</h3> <div class="well well-sm"> <textarea class="form-control" name="hint">{% raw problem.hint %}</textarea> </div> <h3 class="problem-text-title">Source</h3> <div class="well well-sm"> <textarea class="form-control" name="source">{% raw problem.source %}</textarea> </div> </div> </div> <div class="row"> <div class="col-md-1 col-md-offset-5"> <button class="btn btn-primary" type="submit">提交更改</button> </div> <div class="col-md-1"> <a href="/admin/vjudge/problem" class="btn btn-danger" role="button">取消更改</a> </div> </div> </div> </form> </div> {% end %} {% block self_body_js %} <script src="//cdn.bootcss.com/jquery.pin/1.0.1/jquery.pin.min.js"></script> <script> $("#other-info").pin({containerSelector:".container"}); </script> {% end %} <file_sep>/application/vjudge/views/contest.py #-*- coding: utf-8 -*- #import re #from tornado.web import HTTPError #from vjudge import vjudge #from utils.web import BaseHandler #__all__ = ['ContestHandler'] #<EMAIL>(r'/contest(.*?)') #class ContestHandler(BaseHandler): #view_detail_re = re.compile(r'^$') #view_list_re = re.compile(r'^[/]?$') #def get(self, sub_url): #if self.view_list_re.match(sub_url): #self.view_list() #else: #raise HTTPError(404) #def view_list(self): #self.render('vjudge/contest_list.html') #pass <file_sep>/README.md # Witcoder ## 文件目录结构 ``` Witcoder 主目录 ├── setup.sh 构建开发环境的脚本 ├── README.md 自述文件 ├── requirements.txt Python的第三方库依赖 ├── Procfile Coding演示平台所需文件 ├── runtime.txt Coding演示平台所需文件 └── witcoder Web服务目录 ├── config.py 服务配置文件 ├── server.py 服务启动脚本 ├── utils 工具模块 ├── db 数据库模块 ├── website 基础网站模块 ├── auth 认证模块 ├── vjudge 虚拟评测模块(Virtual Judge) ├── admin 后台管理模块 ├── tests 测试模块 ├── statics HTML静态文件目录 └── templates HTML模板目录 ``` ## 运行环境介绍 Witcoder的Web后台开发语言为`Python3`,使用`pip3`作为包管理器。 Debian,Ubuntu等Linux系统使用`apt-get`作为软件包管理工具的Linux系统可使用以下命令安装`Python3`以及`pip3`。 ```bash $ sudo apt-get install python3 python3-pip # 安装Python3,pip3 ``` 接下来构建该项目的运行环境,可在该项目主目录下运行以下命令 ```bash $ sudo ./setup.sh ``` ## 演示平台 该项目使用Coding的演示平台部署,仅作内部演示功能之用。 Witcoder演示平台地址: [http://witcoder.coding.io](http://witcoder.coding.io) <file_sep>/application/vjudge/tests/test_generic.py # -*- coding: utf-8 -*- from nose.tools import assert_equal, assert_true import vjudge.generic def setup(): pass def teardown(): pass def test_generic_online_judge_interface(): for oj in vjudge.generic.SUPPORTED_ONLINE_JUDGE: assert_true(hasattr(oj, "NAME")) assert_true(hasattr(oj, "COMMON_NAMES")) assert_true(hasattr(oj, "HOST_URL")) assert_true(hasattr(oj, "CHARSET")) assert_true(hasattr(oj, "spider")) assert_true(hasattr(oj, "client")) assert_true(hasattr(oj, "get_supported_language")) def test_get_online_judge(): test_obj = vjudge.generic.get_online_judge assert_equal(test_obj("hdoj").NAME, "HDOJ") assert_equal(test_obj("HdOj").NAME, "HDOJ") assert_equal(test_obj("HDU").NAME, "HDOJ") assert_equal(test_obj("hdu").NAME, "HDOJ") <file_sep>/application/auth/utils/mixins.py # -*- coding: utf-8 -*- from sqlalchemy import or_, func from db.models import User from common.regex import username_re, email_re class UserAuthenticationAPIMixin(object): """为请求处理器类提供用户认证的API 要求宿主类实现了`.db.session`来访问SQLAlchemy的数据库session。 提供`.user_login_check`和`.user_register_check`方法来验证用户登录和 注册时的数据。详细信息看下面的方法。 """ _register_data_field_zh_CN = ( ("username", "用户名"), ("password", "密码"), ("repassword", "重复密码"), ("email", "电子邮箱"), ) _login_data_field_zh_CN = (("user", "用户名/邮箱"), ("password", "密码")) def user_login_check(self, data): """检查用户登录数据并返回字典类型的验证结果 :param data dict: 拥有"user"和"password"这两个key的字典。 返回的字典数据样例:: # 验证成功 { "status": 200, "message": "OK", "data": { "id": ..., "username": ..., "nickname": ..., "avatar": ..., ..., }, # 登录成功返回用户模型对象 } # 验证失败 { "status": 400, "message": "Failed", "data": { "field": "user", # 错误字段 "errmsg": "不存在的用户!", # 登录失败的错误提示信息 }, } """ result = {"status": 400, "message": "Failed", "data": {}} # 检查空字段 for field, field_zh_CN in self._login_data_field_zh_CN: if not data.get(field): result["data"] = {"field": field, "errmsg": field_zh_CN + "不能为空!"} return result # 检查用户名/邮箱及密码 if username_re.match(data["user"]) or email_re.match(data["user"]): # 用户名登录不区分大小写 user = self.db.session.query(User).filter( or_(func.lower(User.username) == data["user"].lower(), User.email == data["user"]) ).one_or_none() if user is None: result["data"] = {"field": "user", "errmsg": "不存在的用户!"} elif user.verify_password(data["password"]): result = {"status": 200, "message": "OK", "data": user.get_session()} else: result["data"] = {"field": "password", "errmsg": "密码错误!"} else: result["data"] = {"field": "user", "errmsg": "用户名/邮箱格式有误!"} return result def user_register_check(self, data): """检查注册数据并返回字典类型的验证结果 这个方法只会验证用户的注册数据,不会注册用户。 :param data dict: 拥有"username", "password", "<PASSWORD>", "email" 这些key的字典。 返回结果样例:: # 验证成功 { "status": 200, "message": "OK", } # 验证失败 { "status": 400, "message": "Failed", "data": { "field": "password", "errmsg": "密码长度至少为4个字符!" }, } """ result = {"status": 400, "message": "Failed", "data": {}} # 检查空字段 for field, field_zh_CN in self._register_data_field_zh_CN: if not data.get(field): result["data"] = {"field": field, "errmsg": field_zh_CN + "不能为空!"} return result # 检查用户名长度 if len(data["username"]) not in range(4, 21): result["data"] = {"field": "username", "errmsg": "用户名长度范围为4到20个字符!"} # 检查用户名格式 elif not username_re.match(data["username"]): result["data"] = {"field": "username", "errmsg": "用户名格式有误!"} # 检查密码长度 elif len(data["password"]) < 4: result["data"] = {"field": "password", "errmsg": "密码长度至少为4个字符!"} # 检查重复密码 elif data["repassword"] != data["password"]: result["data"] = {"field": "repassword", "errmsg": "两次输入密码不一致!"} # 检查Email格式 elif not email_re.match(data["email"]): result["data"] = {"field": "email", "errmsg": "电子邮箱格式有误!"} # 检查是否已经有仅大小写不同的用户名被注册, elif self.db.session.query(User.username).filter( func.lower(User.username) == data["username"].lower() ).one_or_none() is not None: result["data"] = {"field": "username", "errmsg": "已经注册过的用户名!"} # 检查Email是否已经被注册 elif self.db.session.query(User.email).filter_by( email=data["email"]).one_or_none() is not None: result["data"] = {"field": "email", "errmsg": "已经注册过的电子邮箱!"} else: result = {"status": 200, "message": "OK"} return result pass <file_sep>/application/vjudge/poj/attribute.py #-*- coding:utf-8 -*- """ Virtual Judge POJ 属性模块 """ # POJ 主页的url HOST_URL = 'http://poj.org' # POJ 的常用名,全部使用大写 NAME_SET = {"POJ", "PKU"} # POJ 的标准名 STD_NAME = "POJ" # 网页编码 CHARSET = 'utf-8' # 帐号登录的URL LOGIN_URL = 'http://poj.org/login' # 帐号登录的HTTP方法 LOGIN_METHOD = 'POST' #代码提交的URL SUBMIT_CODE_URL = 'http://poj.org/submit' #查看源代码的URL VIEW_CODE_URL = 'http://poj.org/showsource' # 查看评测状态的URL VIEW_JUDGE_STATUS_URL = 'http://poj.org/status' #查看编译错误信息URL VIEW_COMPILATION_INFO_URL = 'http://poj.org/showcompileinfo' # 代码提交编程语言编号表 SUBMISSION_CODE_LANGUAGE_ID_TABLE = { 'G++' : 0, 'GCC' : 1, 'Java' : 2, 'Pascal' : 3, 'C++' : 4, 'C' : 5, 'Fortran': 6, } # 评测信息的URL JUDGE_STATUS_URL = 'http://poj.org/status' #评测信息编程语言编号 JUDGE_INFO_CODE_LANGUAGE_ID_TABLE = { "All":"", "G++":0, "GCC":1, "Java":2, "Pascal":3, "C++":4, "C":5, "Fortran":6, } #评测信息评测结果编号 JUDGE_INFO_JUDGE_STATUS_ID_TABLE = { "All":"", "Accepted":0, "Presentation Error":1, "Time Limit Exceeded":2, "Memory Limit Exceeded":3, "Wrong Answer":4, "Runtime Error":5, "Output Limit Exceeded":6, "Compile Error":7, } <file_sep>/application/db/types.py #-*- coding: utf-8 -*- from sqlalchemy.types import Enum from common.types import Gender as gender Gender = Enum(gender.male, gender.female, gender.unknown, name="Gender") <file_sep>/application/vjudge/remote/hdoj.py # -*- coding: utf-8 -*- import re import html import logging from urllib.parse import urlencode from tornado.gen import coroutine, sleep from tornado.httpclient import AsyncHTTPClient from db.models.vjudge.submission import Submission from common.utils import convert_linesep, HTMLFormatter from vjudge.exceptions import (ProblemNotFound, VirtualJudgeError, SubmitError, FetchError) from vjudge.remote.utils import CommonClient logger = logging.getLogger("witcoder.vjudge") # 网页编码 CHARSET = "GB2312" # 网址 HOST_URL = "http://acm.hdu.edu.cn" # 标准名 NAME = "HDOJ" # 常用名,全大写表示 COMMON_NAMES = {"HDOJ", "HDU"} class HDOJMixin(object): """HDOJ虚拟评测基础类""" _problem_info_url = HOST_URL + "/showproblem.php?pid={}" _problem_list_url = HOST_URL + "/listproblem.php?vol={}" _submitcode_url = HOST_URL + "/submit.php?action=submit" _submission_list_url = HOST_URL + ("/status.php?first={}&pid={}&user={}" "&lang={}&status={}") _submission_info_url = HOST_URL + "/viewcode.php?rid={}" _submission_compilation_info_url = HOST_URL + "/viewerror.php?rid={}" _login_url = HOST_URL + "/userloginex.php?action=login" # HDOJ的Submission查询表单时使用 # 用于将编程语言字符串转换成对应提交表单时使用的value _submission_language_id = {"All": 0, "G++": 1, "GCC": 2, "C++": 3, "C": 4, "Pascal": 5, "Java": 6, "C#": 7} # HDOJ的Submission查询表单时使用 # 用于将评测状态字符串转换成对应提交表单时使用的value # 并不是所有的评测状态都在这个表里,有些评测状态不提供筛选 # 比如等待状态以及`System Error` _judge_status_id = {"All": 0, "Accepted": 5, "Wrong Answer": 6, "Presentation Error": 8, "Compilation Error": 12, "Runtime Error": 7, "Memory Limit Exceeded": 10, "Time Limit Exceeded": 9, "Output Limit Exceeded": 11} # HDOJ提交代码表单时使用 # 用于将编程语言字符串转换成对应提交表单时使用的value _submitcode_language_id = {"G++": 0, "GCC": 1, "C++": 2, "C": 3, "Pascal": 4, "Java": 5, "C#": 6} def get_problem_info_url(self, remote_pid: str) -> str: """获取题目URL :param remote_pid str: HDOJ题目编号,纯数字,1000以上为有效编号。 """ return self._problem_info_url.format(remote_pid) def get_problem_list_url(self, volume=1) -> str: """获取题目列表URL :param volume int: 题目列表的页数,默认是第一页的题目列表。 """ return self._problem_list_url.format(volume) def get_submitcode_url(self) -> str: """获取提交代码URL""" return self._submitcode_url def get_submission_info_url(self, remote_key: str) -> str: """获取代码提交详细信息URL :param remote_key str: HDOJ的Submission的RunID,HDOJ的Submission的 唯一标识符,纯数字。 """ return self._submission_info_url.format(remote_key) def get_submission_list_url(self, remote_key="", remote_pid="", username="", language="All", remote_status="All") -> str: """获取评测信息列表URL 根据参数来获取评测信息URL,相关参数起到筛选作用,没有相关参数即表示 不做相关的筛选。 :param remote_key str: HDOJ的Submission的RunID,HDOJ的Submission的 唯一标识符,纯数字。 :param remote_pid str: HDOJ题目的编号,是HDOJ题目的唯一标识符。 :param username str: HDOJ的Submission的提交者用户名。 :param language str: HDOJ的Submission的编程语言,比如`G++`,`GCC`等。 :param remote_status str: HDOJ的Submission的评测状态,比如`Accepted`, `Wrong Answer`等。 """ language_id = self._submission_language_id[language] remote_status_id = self._judge_status_id[remote_status] return self._submission_list_url.format( remote_key, remote_pid, username, language_id, remote_status_id ) def refine_html(self, htmltext) -> str: """处理从HDOJ获取的HTML,转换成可用的字符串 如果`htmltext`是`bytes`类型,那么按照HDOJ网页编码转化成字符串。 并且将字符串的换行符格式转换成Unix的'\n'格式。 """ if isinstance(htmltext, bytes): htmltext = htmltext.decode(CHARSET, 'ignore') return convert_linesep(htmltext) pass class HDOJSpider(HDOJMixin): """HDOJ爬虫类""" _httpclient = AsyncHTTPClient() _problem_title_re = re.compile(r"<h1 style='color:#1A5CC8'>(.*?)</h1>") _problem_time_limit_re = re.compile(r">Time Limit:[\s\S]*?(\d+) MS") _problem_memory_limit_re = re.compile(r"Memory Limit:[\s\S]*?(\d+) K") _problem_special_judge_re = re.compile( r"<font color=red>Special Judge</font>" ) _problem_description_re = re.compile( r">Problem Description</div> <div class=panel_content>(.*?)</div><div " "class=panel_bottom>&nbsp;</div><br><div class=panel_title align=left>" ) _problem_input_re = re.compile( r">Input</div> <div class=panel_content>(.*?)</div><div " "class=panel_bottom>&nbsp;</div><br><div class=panel_title align=left>" ) _problem_output_re = re.compile( r">Output</div> <div class=panel_content>(.*?)</div><div " "class=panel_bottom>&nbsp;</div><br><div class=panel_title align=left>" ) _problem_sample_input_re = re.compile( r'>Sample Input</div><div class=panel_content><pre><div ' 'style="font-family:Courier New,Courier,monospace;">' '([\s\S]*?)</div></pre></div><div class=panel_bottom>' '&nbsp;</div><br><div class=panel_title align=left>' ) _problem_sample_output_re = re.compile( r'>Sample Output</div><div class=panel_content><pre><div ' 'style="font-family:Courier New,Courier,monospace;">' '([\s\S]*?)</div></pre></div><div class=panel_bottom>' '&nbsp;</div><br><div class=panel_title align=left>' ) _problem_hint_re = re.compile(r'<div.*?><i>Hint</i></div>([\s\S]*?)</div>') _problem_source_re = re.compile( r">Source</div> <div class=panel_content>" "\s*?(?:<a[^<>]*?>)?([^<>]*?)(?:</a>)?\s*?" "</div>\s*?<[^<>]*?panel_[^<>]*?>" ) # 题目列表正则表达式,用于获取题目列表中的(题目编号,题目标题)二元组列表 _problem_list_re = re.compile( r'p\([01],(?P<remote_pid>\d+),[-\d]+?,"(?P<title>.*?)",\d+,\d+\);' ) # 题目页正则表达式,用于获取题目页列表 _problem_volume_re = re.compile(r'href=listproblem\.php\?vol=(\d+)') @coroutine def fetch_problem_volumes(self) -> list: """获取题目页列表""" url = self.get_problem_list_url() try: response = yield self._httpclient.fetch(url) except Exception: logger.error("GET {} error!".format(url), exc_info=True) raise else: htmltext = self.refine_html(response.body) return self.match_problem_volumes(htmltext) @coroutine def fetch_problem_list(self, volume=1): """获取题目列表 获取失败抛出异常。 """ url = self.get_problem_list_url(volume) try: response = yield self._httpclient.fetch(url) except Exception: logger.error("GET {} error!".format(url), exc_info=True) raise else: htmltext = self.refine_html(response.body) return self.match_problem_list(htmltext) def match_problem_volumes(self, htmltext) -> list: """从HTML中匹配出题目页列表""" volumes = map(int, set(self._problem_volume_re.findall(htmltext))) volumes = list(volumes) volumes.sort() return volumes def match_problem_list(self, htmltext) -> list: """从HTML中匹配出题目信息列表 返回由`remote_pid`,`title`构成的二元组列表。 :param htmltext: HTML字符串或字节码。 """ htmltext = self.refine_html(htmltext) return [ (remote_pid.strip(), title.strip().replace(r'\"', '"')) for remote_pid, title in self._problem_list_re.findall(htmltext) ] @coroutine def fetch_problem_info(self, remote_pid: str) -> dict: """获取题目标准信息 所谓题目标准信息`std_info`与原始信息`raw_info`的差别是,标准信息含有 `remote_pid`和`url`这两个key以及对应的value。 """ remote_pid = str(remote_pid) url = self.get_problem_info_url(remote_pid) try: response = yield self._httpclient.fetch(url) except Exception: logger.error("GET {} error!".format(url), exc_info=True) raise htmltext = self.refine_html(response.body) try: raw_info = self.match_problem_raw_info(htmltext) except: logger.error("Matching `HDOJ-{}` info error!".format(remote_pid), exc_info=True) raise else: raw_info["remote_pid"] = remote_pid raw_info["url"] = self.get_problem_info_url(remote_pid) return self.refine_problem_raw_info(raw_info) def match_problem_raw_info(self, htmltext) -> dict: """从HTML中匹配出题目原始信息""" # 题目不存在 if htmltext.find("No such problem - ") > -1: raise ProblemNotFound("Problem not found!") try: raw_info = { "remote_oj": NAME, "title": self._match_problem_title(htmltext), "time_limit": self._match_problem_time_limit(htmltext), "memory_limit": self._match_problem_memory_limit(htmltext), "special_judge": self._match_problem_special_judge(htmltext), "description": self._match_problem_description(htmltext), "input": self._match_problem_input(htmltext), "output": self._match_problem_output(htmltext), "sample_input": self._match_problem_sample_input(htmltext), "sample_output": self._match_problem_sample_output(htmltext), "hint": self._match_problem_hint(htmltext), "source": self._match_problem_source(htmltext), } except: raise return raw_info def refine_problem_raw_info(self, raw_info: dict) -> dict: """处理匹配出的题目原始信息""" formatter = HTMLFormatter(joinurl=True, url=raw_info["url"]) for key in ("description", "input", "output", "sample_input", "sample_output", "source"): # 清空在其他地方的Hint文本 raw_info[key] = self._problem_hint_re.sub("", raw_info[key]) # 相对URL转换处理 raw_info[key] = formatter.format_html(raw_info[key]) # 单独处理Hint raw_info["hint"] = formatter.format_html(raw_info["hint"]) return raw_info def _match_problem_title(self, htmltext: str) -> str: results = self._problem_title_re.findall(htmltext) if len(results) == 0: raise Exception("Can't match problem `title`!") elif len(results) > 1: raise Exception("Problem `title` of the matching not unique!") return results[0].strip() def _match_problem_time_limit(self, htmltext: str) -> int: results = self._problem_time_limit_re.findall(htmltext) if len(results) == 0: raise Exception("Can't match problem `time_limit`!") elif len(results) > 1: raise Exception("Problem `time_limit` of the matching not unique!") return int(results[0]) def _match_problem_memory_limit(self, htmltext: str) -> int: results = self._problem_memory_limit_re.findall(htmltext) if len(results) == 0: raise Exception("Can't match problem `memory_limit`!") elif len(results) > 1: raise Exception("Problem `memory_limit` of the matching" " not unique!") return int(results[0]) def _match_problem_special_judge(self, htmltext: str) -> bool: results = self._problem_special_judge_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `special_judge` of the matching" " not unique!") return bool(len(results)) def _match_problem_description(self, htmltext: str) -> str: results = self._problem_description_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `description` of the matching" " not unique!") return results[0].strip() if len(results) else "" def _match_problem_input(self, htmltext: str) -> str: results = self._problem_input_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `input` of the matching not unique!") return results[0].strip() if len(results) else "" def _match_problem_output(self, htmltext: str) -> str: results = self._problem_output_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `output` of the matching not unique!") return results[0].strip() if len(results) else "" def _match_problem_sample_input(self, htmltext: str) -> str: results = self._problem_sample_input_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `sample_input` of the matching" " not unique!") return results[0].strip() if len(results) else "" def _match_problem_sample_output(self, htmltext: str) -> str: results = self._problem_sample_output_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `sample_output` of the matching" " not unique!") return results[0].strip() if len(results) else "" def _match_problem_hint(self, htmltext: str) -> str: results = self._problem_hint_re.findall(htmltext) return '<br>'.join(results) if len(results) else "" def _match_problem_source(self, htmltext: str) -> str: results = self._problem_source_re.findall(htmltext) if len(results) > 1: raise Exception("Problem `source` of the matching not unique!") return results[0].strip() if len(results) else "" pass class HDOJClient(CommonClient, HDOJMixin): _submission_info_re = re.compile( r'<tr.*?><td height=22px>(?P<remote_key>\d+?)</td>' '<td>(?P<submit_time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})</td>' '<td>[\s\S]*?<font.*?>(?P<remote_status>.+?)</font>[\s\S]*?</td>' '<td><a href="/showproblem\.php\?pid=\d+">(?P<remote_pid>\d+)</a></td>' '<td>(?P<time_cost>\d+?)MS</td><td>(?P<memory_cost>\d+?)K</td>' '<td>.*?(?P<length>\d+)[ ]?B.*?</td><td>(?P<language>.+?)</td>' '<td.*?><a href="/userstatus\.php\?user=(?P<username>.+?)">.*?' '</a></td></tr>' ) _submission_source_code_re = re.compile( r'<textarea[^<>]*?>(?P<source_code>[\s\S]*?)</textarea>' ) _submission_compilation_info_re = re.compile( r'<pre>(?P<compilation_info>[\s\S]*?)</pre>' ) # 登录重试次数 LOGIN_RETRY_TIMES = 3 # 状态检查周期,20分钟 PERIOD_OF_CHECK = 20 * 60 def __init__(self, username=None, password=None, *args, **kwargs): super(HDOJClient, self).__init__() self.username = username self.password = <PASSWORD> @coroutine def login(self, username=None, password=None, *args, **kwargs) -> str: """HDOJ客户端登录 :param str username: HDOJ用户名,设置了该参数的话会将其赋值给 `.username`并使用,否则默认使用已有的`.username`。 :param str password: <PASSWORD>用户密码,设置了该参数的话会将其赋值给 `.password`并使用,否则默认使用已有的`.password`。 登录是否成功通过登录后访问HDOJ主页看是否有用户名的链接来决定。 登录成功会设置状态为"Normal",否则为"Error",然后返回这个状态。 .. 如果登录时`.username`或`.password`为空值,将抛出`ValueError`。 """ self.username = username or self.username self.password = <PASSWORD> or <PASSWORD> if not self.username or not self.password: raise ValueError("`HDOJClient.login` require `username` and" " `password`!") body = urlencode({"username": self.username, "userpass": <PASSWORD>, "login": "Sign In"}) yield self.httpclient.fetch(self._login_url, method="POST", body=body, raise_error=False) response = yield self.httpclient.fetch(HOST_URL, raise_error=False) htmltext = self.refine_html(response.body) if htmltext.find("/userstatus.php?user={}".format(self.username)) > -1: # 登录成功 logger.info("HDOJClient `{}` login success!".format(self.username)) self.set_status("Normal") else: log_list = ["HDOJ login error!"] if response.error: log_list.append(response.error) else: log_list.extend(( "{} {}.".format(response.code, response.reason), "url: {}.".format(response.effective_url), "headers:" )) log_list.extend( [" {}: {}".format(k, v) for k, v in sorted(response.headers.get_all())] ) logger.error('\n'.join(log_list)) self.set_status("Error") return self.status @coroutine def check_status(self): """检查HDOJClient的登录状态,必要时重新登录维持登录状态""" response = yield self.httpclient.fetch(HOST_URL) htmltext = response.body.decode(CHARSET, "ignore") if htmltext.find(self.username) > -1: self.set_status("Normal") logger.info("HDOJClient check status: Normal.") else: self.set_status("Error") logger.info("HDOJClient check status: Error.") for i in range(self.LOGIN_RETRY_TIMES): login_status = yield self.login() logger.info("HDOJClient retry login, the {} time: " "{}.".format(i + 1, login_status)) if login_status == "Normal": break yield sleep(5) # 5秒重试 @coroutine def submit_code(self, remote_pid, source_code: str, language: str, *args, **kwargs) -> dict: """提交代码 可能抛出`VirtualJudgeError`异常或者其他异常,如果抛出的异常是 `VirtualJudgeError`那么表示这个代码的提交结果为"VirtualJudgeError", 否则为"SubmitError"。 """ if language not in self._submitcode_language_id: # TODO: 提交不存在的编程语言而导致VirtualJudgeError异常 # 可能不妥,因为人为选择错误的编程语言而导致这个异常可能会 # 让人觉得虚拟评测系统做得不好,待完善 raise VirtualJudgeError("Nonexistent language: `{}`.".format( language )) form_data = { "check": 0, "problemid": remote_pid, "language": self._submitcode_language_id[language], "usercode": source_code.encode(CHARSET) } response = yield self.httpclient.fetch(self._submitcode_url, method="POST", body=urlencode(form_data)) result = (response.effective_url, response.code) if result != ("http://acm.hdu.edu.cn/status.php", 200): log_list = ["Submit result error!"] log_list.extend([ "{} {}.".format(response.code, response.reason), "url: {}.".format(response.effective_url), "headers:" ]) log_list.extend( [" {}: {}".format(k, v) for k, v in sorted(response.headers.get_all())] ) raise SubmitError('\n'.join(log_list)) return {"remote_pid": remote_pid, "language": language, "source_code": source_code} @coroutine def fetch_result(self, remote_pid, source_code, language) -> dict: """爬取提交结果 该OJ的爬取结果思路如下,根据题目编号,提交者用户名以及编程语言筛选 提交列表,获取第一页的提交信息,按照顺序取出这些信息并依次访问并获 取其源代码,根据提交的源代码匹配出对应的提交,然后根据其评测状态来 判断评测是否完成,完成则直接转换成标准信息返回,否则根据key获取完成 后的信息并转换成标准信息返回。 如果没有匹配出提交,那么抛除`FetchError`异常。 编译错误相关信息在匹配提交源代码时可以匹配出来。 """ raw_info_list = yield self._fetch_submission_list( remote_pid=remote_pid, language=language, source_code=source_code ) raw_info = yield self._find_result(raw_info_list, source_code=source_code) for waittime in (1, 2, 3, 4, 5, 5, 5, 5, 5): # 由于获取的提交可能没有评测完毕,所以需要等待以获取评测完毕的信息 # TODO: 待改进,需要根据题目时间限制来设定等待时间 wait_future = sleep(waittime) if judge_finished(raw_info["remote_status"]): break yield wait_future raw_info = yield self._fetch_submission(raw_info["remote_key"]) else: if not judge_finished(raw_info["remote_status"]): raise FetchError("Fetch timeout! remote key: " "'{}'".format(raw_info["remote_key"])) if is_compilation_error(raw_info["remote_status"]): raw_info["compilation_info"] = yield self.fetch_compilation_info( raw_info["remote_key"] ) return self.standardize_result(raw_info) def standardize_result(self, result): """将评测结果转换成标准化形式""" return { "remote_key": result["remote_key"], "remote_status": result["remote_status"], "status": self.standardize_judge_status( result["remote_status"] ), "time_cost": int(result["time_cost"] or 0), "memory_cost": int(result["memory_cost"] or 0), "compilation_info": result.get("compilation_info"), } def standardize_judge_status(self, status: str) -> str: if status in Submission.status2id: return status elif status.find("Runtime Error") != -1: return "Runtime Error" elif status == "System Error": return "Online Judge Error" else: # TODO: error: 未知的评测状态 raise ValueError('Unknown judge status `{}`.'.format(status)) @coroutine def _fetch_submission_list(self, remote_pid, source_code, language): """爬取提交信息列表""" url = self.get_submission_list_url( remote_pid=remote_pid, language=language, username=self.username ) response = yield self.httpclient.fetch(url) htmltext = self.refine_html(response.body) return self.match_submission_raw_info_list(htmltext) @coroutine def _fetch_submission(self, remote_key): """根据remote_key获取提交信息""" url = self.get_submission_list_url(remote_key=remote_key) response = yield self.httpclient.fetch(url) htmltext = self.refine_html(response.body) raw_info = self.match_submission_raw_info_list(htmltext)[0] if raw_info["remote_key"] != remote_key: raise FetchError("Lost `remote_key`: '{}'.".format(remote_key)) return raw_info @coroutine def _find_result(self, raw_info_list: list, source_code: str) -> dict: """查找对应提交信息""" for raw_info in raw_info_list: key = raw_info["remote_key"] # TODO: 还有比较和筛选时间 submission_url = self.get_submission_info_url(key) response = yield self.httpclient.fetch(submission_url, raise_error=False) if response.error is not None: logger.error("response.error: {}.".format(response.error)) continue htmltext = self.refine_html(response.body) remote_source_code = self.match_source_code(htmltext) if remote_source_code != source_code: continue return raw_info raise FetchError("Remote submission not found!") @coroutine def fetch_compilation_info(self, remote_key): url = self._submission_compilation_info_url.format(remote_key) response = yield self.httpclient.fetch(url) htmltext = self.refine_html(response.body) return self.match_compilation_info(htmltext) def match_submission_raw_info_list(self, htmltext: str) -> list: """从HTML文本中匹配出提交列表 该函数返回元素类型为字典的列表。 元素样例如下:: { "remote_key": ..., # RunID,评测信息key "remote_pid": ..., # 远程OJ的题目编号 "submit_time": ..., # 远程OJ的提交时间 "remote_status": ..., # 远程OJ的评测状态,HTML "time_cost": ..., # 程序的时间消耗 "memory_cost": ..., # 程序的内存消耗 "language": ..., # 编程语言,HDOJ的数据 "length": ..., # 代码长度,HDOJ的数据 "username": ..., # HDOJ代码提交者的用户名 } """ results = self._submission_info_re.findall(htmltext) for index, value in enumerate(results): results[index] = { k: value[i-1] for k, i in self._submission_info_re.groupindex.items() } return results def match_source_code(self, htmltext: str) -> str: results = self._submission_source_code_re.findall(htmltext) # TODO: 没有匹配到数据的处理 return html.unescape(results[0]) def match_compilation_info(self, htmltext: str) -> str: results = self._submission_compilation_info_re.findall(htmltext) if len(results) == 0: raise FetchError("Compilation info not found!") return results[0] pass # 通用接口 spider = HDOJSpider() client = HDOJClient("WitcoderKayle", "witcoderkayle") # 启动 client.start() def get_supported_language(remote_pid=None) -> list: return [key for key in HDOJMixin._submitcode_language_id] def judge_finished(remote_status: str) -> bool: """根据远程OJ的评测状态来判断评测是否完成""" if remote_status in {"Queuing", "Running", "Compiling"}: return False return True def is_compilation_error(remote_status: str) -> bool: """判断评测状态是否为编译错误""" return remote_status == "Compilation Error" <file_sep>/application/vjudge/views/api.py # coding: utf-8 from sqlalchemy.orm import load_only, lazyload from common.web import RESTfulAPIHandler from db.models.account.user import User from db.models.vjudge import Submission, Problem class ProblemRESTfulAPIHandler(RESTfulAPIHandler): """Virtual Judge Problem RESTful API 使用示例: GET /vjudge/problem # 获取题目列表 GET /vjudge/problem/{id} # 获取指定{id}的题目 """ # 默认的查询字符串参数 default_query_params = { "limit": 10, "offset": 0, "remote_oj": None, "remote_pid": None, "fields": set(Problem.get_field_dict().keys()), } def get(self, id=None): if id is None: self.get_problem_list() else: self.get_problem(id) def get_problem_list(self): """获取题目列表 默认按照题目ID升序排列。 URL查询字符串示例: ?limit=100 # 指定返回的数量,默认100,取值范围(0, 100] ?offset=10 # 指定偏移的数量,默认0,取值范围[0, ∞) ?remote_oj=HDOJ # 指定题目的远端OJ名,默认不做筛选 ?remote_pid=1001 # 指定题目的远端题目编号,默认不做筛选 """ params = self.get_problem_list_params() query_clause = self.db.session.query(Problem).order_by(Problem.id) filter_dict = {param: params[param] for param in ("remote_oj", "remote_pid") if params[param]} query_clause = query_clause.filter_by(**filter_dict) problem_list = query_clause.limit( params["limit"]).offset(params["offset"]).all() problem_list = [problem.to_dict() for problem in problem_list] data = {"problem_list": problem_list, "count": len(problem_list)} if data["problem_list"]: self.write_result(data) else: self.write_result(data, status=404) def get_problem_list_params(self): """获取验证处理之后的题目列表的查询字符串参数""" params = { "limit": self.get_query_argument( "limit", self.default_query_params["limit"]), "offset": self.get_query_argument( "offset", self.default_query_params["offset"]), "remote_oj": self.get_query_argument( "remote_oj", self.default_query_params["remote_oj"]), "remote_pid": self.get_query_argument( "remote_pid", self.default_query_params["remote_pid"]), } # 处理'limit' try: params["limit"] = int(params["limit"]) except: params["limit"] = self.default_query_params["limit"] if not 0 < params["limit"] <= 100: params["limit"] = self.default_query_params["limit"] # 处理'offset' try: params["offset"] = int(params["offset"]) except: params["offset"] = self.default_query_params["offset"] if not params["offset"] >= 0: params["offset"] = self.default_query_params["offset"] return params def get_problem(self, problem_id): """获取指定{id}的题目 URL查询字符串参数示例: ?fields=id&fields=title # 虚拟字段,可以获取多个,默认是全部字段 """ try: problem_id = int(problem_id) except: self.write_result(status=400, reason="`problem_id` error!") return params = self.get_problem_params() field_dict = Problem.get_field_dict() problem = self.db.session.query(Problem).options( # 加载真实字段 load_only(*(field_dict[field] for field in params["fields"])) ).get(problem_id) if problem is None: self.write_result(status=404) else: self.write_result(problem.to_dict(*params["fields"])) def get_problem_params(self): """获取验证处理之后的题目的查询字符串参数""" params = { "fields": set(self.get_query_arguments("fields")), } if not any(params["fields"]): params["fields"] = self.default_query_params["fields"] else: params["fields"] = tuple(self.default_query_params[ "fields"].intersection(params["fields"])) return params pass class SubmissionRESTfulAPIHandler(RESTfulAPIHandler): """Virtual Judge Submission RESTful API 使用示例: GET /vjudge/submission # 获取提交列表 GET /vjudge/submission/{id} # 获取指定{id}的提交 暂不支持通过该API查询提交的源代码以及编译信息。 TODO: GET /vjudge/submission/{id}/source_code # 获取指定{id}的提交的源代码 GET /vjudge/submission/{id}/compilation_info # 获取指定{id}的提交的编译信息 """ default_query_params = { "limit": 10, "offset": 0, } def get(self, id=None): if id is None: self.get_submission_list() else: self.get_submission(id) def get_submission_list(self): """获取提交列表 默认按照提交ID降序排列。 URL查询字符串参数示例: ?limit=10 # 指定返回的数量,默认10,取值范围(0, 100] ?offset=10 # 指定偏移的数量,默认0,取值范围[0, ∞) ?username=JZQT # 指定提交用户的用户名,默认不做筛选 ?user_id=1 # 指定提交用户的ID,默认不做筛选 ?remote_oj=HDOJ # 指定题目的远端OJ名,默认不做筛选 ?remote_pid=1001 # 指定题目的远端题目编号,默认不做筛选 ?problem_id=536 # 指定题目ID,默认不做筛选 """ params = self.get_submission_list_params() query_clause = self.db.session.query(Submission).join( Problem, User).options(lazyload("problem"), lazyload("submitter")) if params["username"] is not None: query_clause = query_clause.filter( User.username == params["username"]) if params["user_id"] is not None: query_clause = query_clause.filter(User.id == params["user_id"]) if params["remote_oj"] is not None: query_clause = query_clause.filter( Problem.remote_oj == params["remote_oj"]) if params["remote_pid"] is not None: query_clause = query_clause.filter( Problem.remote_pid == params["remote_pid"]) if params["problem_id"] is not None: query_clause = query_clause.filter( Submission.problem_id == params["problem_id"]) submission_list = query_clause.limit( params["limit"]).offset(params["offset"]).all() submission_list = [submission.to_dict() for submission in submission_list] data = {"submission_list": submission_list, "count": len(submission_list)} if data["submission_list"]: self.write_result(data) else: self.write_result(data, status=404) def get_submission_list_params(self): """获取验证处理之后的提交列表的查询字符串参数""" params = { "limit": self.get_query_argument( "limit", self.default_query_params["limit"]), "offset": self.get_query_argument( "offset", self.default_query_params["offset"]), "username": self.get_query_argument("username", None), "user_id": self.get_query_argument("user_id", None), "remote_oj": self.get_query_argument("remote_oj", None), "remote_pid": self.get_query_argument("remote_pid", None), "problem_id": self.get_query_argument("problem_id", None), } # 处理'limit' try: params["limit"] = int(params["limit"]) except: params["limit"] = self.default_query_params["limit"] if not 0 < params["limit"] <= 100: params["limit"] = self.default_query_params["limit"] # 处理'offset' try: params["offset"] = int(params["offset"]) except: params["offset"] = self.default_query_params["offset"] if not params["offset"] >= 0: params["offset"] = self.default_query_params["offset"] # 处理'user_id' try: params["user_id"] = int(params["user_id"]) except: params["user_id"] = None # 处理'problem_id' try: params["problem_id"] = int(params["problem_id"]) except: params["problem_id"] = None return params def get_submission(self, submission_id: str): """获取指定{id}的提交 URL查询字符串参数示例: 暂且不提供URL查询字符串参数 返回结果示例: { "id": 1, "submitter_id": 1, "problem_id": 1, "status": "Compilation Error", "time_cost": 0, "memory_cost": 0, "language": "C++", "code_length": 238, "submit_time": "2016-06-07 14:23:55", "shared": true } """ # params = self.get_submission_params() submission = self.db.session.query(Submission).get(submission_id) if submission is None: self.write_result(status=404) else: self.write_result(submission.to_dict()) def get_submission_params(self): """获取验证处理之后的提交的查询字符串参数""" params = {} return params pass class ExerciseRESTfulAPIHandler(RESTfulAPIHandler): """Virtual Judge Exercise RESTful API 使用示例: TODO: GET /vjudge/exercise # 获取训练列表 GET /vjudge/exercise/{id} # 获取指定{id}的训练 GET /vjudge/exercise/{id}/problem # 获取指定{id}的训练题目列表 GET /vjudge/exercise/{id}/problem/{id} # 获取指定{id}的训练的指定{id}的题目 GET /vjudge/exercise/{id}/submission # 获取指定{id}的训练提交列表 GET /vjudge/exercise/{id}/submission/{id} # 获取指定{id}的训练的指定{id}的提交 # 获取指定{id}的训练的指定{id}的提交 GET /vjudge/exercise/{id}/submission/{id}/source_code # 获取指定{id}的训练的指定{id}的提交 GET /vjudge/exercise/{id}/submission/{id}/compilation_info """ pass <file_sep>/application/common/web.py # coding: utf-8 import pickle import http.client import tornado.gen from tornado.util import ObjectDict from tornext.web import TornextRequestHandler import witcoder class BaseHandler(TornextRequestHandler): """Witcoder Web RequestHandler 基础类""" @tornado.gen.coroutine def prepare(self): pass def get_current_user(self): """从session中取出当前用户信息""" try: # 解析Cookie session = pickle.loads(self.get_secure_cookie("session")) except: return None # 判断解析出的信息是否规范,否则认为是伪造的Cookie if not session or not isinstance(session, dict): return None return ObjectDict(session) def update_current_user(self, **kwargs): self.current_user.update(kwargs) self.set_secure_cookie("session", pickle.dumps(self.current_user)) def set_session_cookie(self, session): self.set_secure_cookie("session", pickle.dumps(session), expires_days=None) def clear_session_cookie(self, redirect=None): self.clear_cookie("session") if redirect: self.redirect(redirect) @property def db(self): return witcoder.orm @property def cache(self): return witcoder.cache def write_error(self, status_code, **kwargs): pass def render(self, *args, **kwargs): self.tplkw.update({ "get_avatar_url": self.get_avatar_url, }) return super(BaseHandler, self).render(*args, **kwargs) def get_avatar_url(self, *, username=None, version=None, host=None): host = host or "http://media.witcoder.com" if self.current_user and username is None: username = self.current_user.username if not version: return host + "/avatar" return ''.join([host, "/avatar/", username, "?v=", version]) pass class RESTfulAPIHandler(BaseHandler): """实现RESTful API的请求处理器基类""" def write_result(self, data=None, status=200, reason=None): """输出调用API的结果 :param dict data: 自定义的调用结果数据,默认为None。 :param int status: 返回的调用结果状态码,默认200。 :param str reason: 自定义的状态码消息,默认跟随HTTP状态码对应的消息。 默认输出的JSON结果示例: { "status": 200, "message": "OK", "data": null, } """ reason = reason or http.client.responses.get(status) self.write({"status": status, "message": reason, "data": data}) pass <file_sep>/application/vjudge/zoj/agent.py #-*- coding:utf-8 -*- import re from html import unescape from time import strptime, mktime from tornado.gen import coroutine, Task, sleep from utils.time import TIME_FORMAT_STR from utils.log.loggers import vjudge as logger from urllib.request import urlopen from .crawler import (get_problem_url,) from ..exc import FetchError, VjudgeError, SubmitError from .attribute import (LOGIN_URL, SUBMIT_CODE_URL, VIEW_JUDGE_STATUS_URL, CHARSET, HOST_URL, VIEW_COMPILATION_INFO_URL) from .tools import (check_and_handle_htmltext, client, is_compilation_error, get_judge_info_origin_judge_status_id, judge_finished, get_judge_info_origin_code_language_id, to_judge_result, get_submission_origin_code_language_id, get_origin_pid, to_origin_code_language) __all__ = ['submit_code', 'get_judge_info', 'from_origin_judge_key_get_judge_info', 'from_html_get_judge_info', 'get_compilation_info', 'get_remote_id',] @coroutine def submit_code(remote_pid, code_language, source_code): """ 提交代码,返回提交信息 """ origin_pid = yield get_remote_id(remote_pid) origin_code_language = to_origin_code_language(code_language) form_data = { 'problemId': origin_pid, 'languageId': get_submission_origin_code_language_id(origin_code_language), 'source': source_code, } response = yield Task(client.post, SUBMIT_CODE_URL, form_data) logger.info('Submit code: response time {}.'.format(response.request_time)) if response.error: logger.error('Submit Error: submit response error -> {}.'.format( response.error )) return SubmitError(response.error) elif response.code != 200: logger.error('Submit Error: ???.') return SubmitError('HTTPResponse `code` error, `code` is {}.'.format( response.code )) #获得评测信息 judge_info = yield get_judge_info( username=client.username, origin_pid=origin_pid, origin_code_language=origin_code_language, source_code=source_code, htmltext=response.body, ) if isinstance(judge_info, VjudgeError): return judge_info return to_judge_result(judge_info) @coroutine def get_judge_info(username=None, origin_pid=None, origin_code_language=None, source_code=None, htmltext=None): """ ZOJ 获取提交代码后的评测信息 """ htmltext = check_and_handle_htmltext(htmltext) runId = _from_return_runid_id.findall(htmltext)[0] judge_info = yield from_origin_judge_key_get_judge_info(runId) while True: if(judge_finished(judge_info['origin_judge_status'])): break yield sleep(1) #获得RunId后,调用此函数获取评测信息 judge_info = yield from_origin_judge_key_get_judge_info(runId) #虽然这种可能极不可能发生 if(runId != judge_info["origin_judge_key"]): logger.info("啊啊啊啊啊,zoj爬虫的两次runid不同啊") judge_info["origin_code_language"] = origin_code_language judge_info["origin_pid"] = origin_pid judge_info["origin_agent_username"] = username # 如果评测结果为编译错误,将编译错误信息一并爬取 if is_compilation_error(judge_info['origin_judge_status']): submissionId = _compile_error_url_re.findall(judge_info['origin_judge_status'])[0] judge_info['origin_judge_status'] = 'Compilation Error' compilation_info = yield get_compilation_info(submissionId) judge_info['compilation_info'] = compilation_info logger.info("ZOJ---judge_info:" + str(judge_info)) return judge_info @coroutine def from_origin_judge_key_get_judge_info(origin_judge_key): """ 获得RunId后,调用此函数获取评测信息, 有了RunId就可以找到相应的网址,在从网页数据获得评测信息 """ params = get_judge_info_list_url_params(origin_judge_key) response = yield Task(client.get, VIEW_JUDGE_STATUS_URL, params) htmltext = response.body judge_info = from_html_get_judge_info(htmltext) return judge_info def from_html_get_judge_info(htmltext): """ 从网页数据获取评测信息 有了RunId就可以找到相应的网址,在从网页数据获得评测信息 """ htmltext = check_and_handle_htmltext(htmltext) run_id = _judge_runid_re.findall(htmltext) run_time = _judge_runtime_re.findall(htmltext) judge_status = _judge_status_re.findall(htmltext) run_memory = _judge_runmemory_re.findall(htmltext) judge_info = {} judge_info["origin_judge_status"] = "" if(len(run_id) != 1 or len(run_time) != 1 or len(run_memory) != 1 or len(judge_status) != 1): logger.info("zoj错误啦, runid->" + str(run_id) + "#run_time->" + str(run_time) + "#judge_status->" + str(judge_status) + "#judge_mmory->" + str(run_memory)) judge_info["origin_judge_key"] = run_id[0].strip() judge_info["origin_submit_time"] = "" judge_info["origin_judge_status"] = judge_status[0].strip() judge_info["origin_time_cost"] = run_time[0].strip() judge_info["origin_memory_cost"] = run_memory[0].strip() judge_info["origin_code_length"] = "" return judge_info def get_judge_info_list_url_params(origin_judge_key=''): """ 根据RunId生成相应网址参数 """ params = {} params['contestId'] = '1' params['idStart'] = origin_judge_key params['idEnd'] = origin_judge_key return params @coroutine def get_compilation_info(runId): """ ZOJ 获取编译错误的信息 """ form_data = { 'submissionId': runId, } response = yield Task(client.get, VIEW_COMPILATION_INFO_URL, form_data) htmltext = check_and_handle_htmltext(response.body) return htmltext @coroutine def get_remote_id(origin_pid): """ 根据题目id获得提交代码的id """ problem_url = get_problem_url(origin_pid) response = yield Task(client.get, problem_url) htmltext = check_and_handle_htmltext(response.body) remote_pid = _remote_id_re.findall(htmltext) if(len(remote_pid) < 1): return SubmitError("get ZOJ remote pid Error") else: return remote_pid[0] _login_verify_re = re.compile(r'class="user_name">(.*?)</span>') _from_return_runid_id = re.compile(r"font color='red'>(\d+?)</font") _judge_status_re =re.compile(r'class="judgeReply[AC|Other]+">[\s]*(.*?)[\s]*</span></td>') _judge_runtime_re = re.compile(r'class="runTime">(\d+)</td>') _judge_runmemory_re = re.compile(r'class="runMemory">(\d+)</td') _judge_runid_re = re.compile(r'class="runId">(\d+)</td>') _compile_error_url_re = re.compile(r'<a href="/onlinejudge/showJudgeComment.do\?submissionId=(\d+)">Compilation Error') _remote_id_re = re.compile(r'<a href="/onlinejudge/submit.do\?problemId=(\d+)"><font color="blue">Submit</font></a>') <file_sep>/application/admin/ui.py #-*- coding: utf-8 -*- from tornado.web import UIModule from admin import admin @admin.ui_module("AdminUI") class AdminUI(UIModule): _js_files = ("/static/js/admin.js") def render(self): return "" def javascript_files(self): return self._js_files pass <file_sep>/application/assets/webpack.config.js var webpack = require('webpack'); module.exports = { entry: { vjudge_exercise: './src/vjudge/exercise/index.js', // 项目第三方模块 // vendor: [], }, output: { path: './dist/', filename: '[name].js', }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['es2015', 'stage-0', 'react'], } }], }, plugins: [ // new webpack.optimize.CommonsChunkPlugin(/*chunkName=*/"vendor", /*filename=*/"vendor.bundle.js"), new webpack.optimize.UglifyJsPlugin({ output: { comments: false, // remove all comments. }, compress: { warnings: false, }, }), ], externals: { 'jquery': 'jQuery', 'react': 'React', 'react-dom': 'ReactDOM', 'react-router': 'ReactRouter', }, }; <file_sep>/application/db/models/account/user.py # -*- coding: utf-8 -*- """ Witcoder 用户相关数据表Model """ from sqlalchemy import text from sqlalchemy.orm import relationship from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String, DateTime, CHAR, SmallInteger from auth.utils.algorithm import auth_md5 from db.models import BaseModel class User(BaseModel): """ 用户主表Model 数据表关系: `info`: 与`UserInfo`的一对一关系 `submissions`: 与`Submission`的一对多关系 `exercises`: 与`Exercise`的一对多关系 索引: `id`: 主键上的索引 """ __tablename__ = "tb_user" # 表结构 id = Column(Integer, primary_key=True, index=True) username = Column(String(20), nullable=False) password = Column(CHAR(32), nullable=False) nickname = Column(String(50), nullable=False, default='', server_default='') email = Column(String(50), nullable=False) avatar = Column(String(200), nullable=False, default="", server_default="") register_time = Column(DateTime, nullable=False, server_default=text("NOW()")) # 关系 info = relationship("UserInfo", backref="user", cascade="all", uselist=False) followers = relationship('User', secondary='tb_user_follow_association', primaryjoin="User.id==UserToUser.followee_id", secondaryjoin="User.id==UserToUser.follower_id", lazy='dynamic') followees = relationship('User', secondary='tb_user_follow_association', primaryjoin="User.id == UserToUser.follower_id", secondaryjoin="User.id==UserToUser.followee_id", lazy='dynamic') def __repr__(self): return "<User(id={}, username={})>".format(self.id, self.username) @classmethod def register(cls, username, password, email, *args, **kwargs): """根据已经验证过的数据进行用户注册,返回一个用户对象 注册时会自动创建相关的数据对象,比如`UserInfo`。 """ encrypted_password = auth_md5("witcoder".join(tuple(password))) # 创建用户对象 user = cls(username=username, password=<PASSWORD>, email=email, nickname=username) # 创建用户信息对象 user.info = UserInfo() return user def get_session(self): return {"id": self.id, "username": self.username, "nickname": self.nickname, "avatar": self.avatar} def verify_password(self, password): """验证给定的密码是否与该用户密码匹配""" return auth_md5("witcoder".join(tuple(password))) == self.password def change_password(self, newpassword): """更改密码""" self.password = auth_md5("witcoder".join(tuple(newpassword))) pass class UserToUser(BaseModel): __tablename__ = "tb_user_follow_association" follower_id = Column(Integer, ForeignKey(User.id), primary_key=True) followee_id = Column(Integer, ForeignKey(User.id), primary_key=True) follow_time = Column(DateTime, nullable=False, server_default=text("NOW()")) pass class UserInfo(BaseModel): """ 用户社交信息表Model 数据表关系: `user`: 与`User`的一对一关系,参见`tb_user`表 索引: `id`: 主键上的索引 """ gender2id = {"": 0, "male": 1, "female": 2} id2gender = {value: key for key, value in gender2id.items()} __tablename__ = "tb_user_info" # 表结构 id = Column(Integer, ForeignKey("tb_user.id"), primary_key=True, index=True) _gender = Column(SmallInteger, nullable=False, default=0, server_default="0") school = Column(String(50), nullable=False, default="", server_default="") major = Column(String(50), nullable=False, default="", server_default="") url = Column(String(100), nullable=False, default="", server_default="") about = Column(String(200), nullable=False, default="", server_default="") @property def gender(self): if not hasattr(self, "_gender_"): self._gender_ = self.id2gender[self._gender] return self._gender_ @gender.setter def gender(self, value): if isinstance(value, int) and value in self.id2gender: self._gender = value self._gender_ = self.id2gender[value] elif isinstance(value, str): # 非法字符串值作为空字符串对待 if self.gender2id.get(value) is None: value = "" self._gender = self.gender2id[value] self._gender_ = value else: raise ValueError("Error value '{}'!".format(value)) def __repr__(self): return "<UserInfo(id={})>".format(self.id) pass <file_sep>/application/witcoder/__init__.py # coding: utf-8 from tornext.web import Tornext from qiniu import Auth import tornadis from db.connector import SQLAlchemy app = Tornext(settings='witcoder.settings.local') orm = SQLAlchemy(**app.settings.SQLALCHEMY) cache = tornadis.Client(**app.settings.REDIS) qiniu = Auth(app.settings.QINIU["access_key"], app.settings.QINIU["secret_key"]) <file_sep>/application/account/utils/mixins.py # -*- coding: utf-8 -*- from db.models.account import User, UserInfo class UserResourceAPIMixin(object): """为请求处理器提供操作用户资源的API 要求宿主类实现`.db.session`来访问SQLAlchemy的数据库session。 要求宿主类实现`.current_user`来访问当前用户登录的session。 """ def user_info_check(self, form): """用户个人信息检查""" result = {"status": 400, "message": "Failed", "data": {}} if form["url"]: if not (form["url"].startswith("http://") or form["url"].startswith("https://")): form["url"] = "http://" + form["url"] form["nickname"] = form["nickname"] or self.current_user.username if len(form["nickname"]) > User.nickname.type.length: result["data"] = { "field": "nickname", "message": "昵称不能超过{}个字符!".format( User.nickname.type.length) } elif len(form["school"]) > UserInfo.school.type.length: result["data"] = { "field": "school", "message": "学校不能超过{}个字符!".format( UserInfo.school.type.length) } elif len(form["major"]) > UserInfo.major.type.length: result["data"] = { "field": "major", "message": "专业不能超过{}个字符!".format( UserInfo.major.type.length) } elif len(form["url"]) > UserInfo.url.type.length: result["data"] = { "field": "url", "message": "个人网址不能超过{}个字符!".format( UserInfo.url.type.length) } elif len(form["about"]) > UserInfo.about.type.length: result["data"] = { "field": "about", "message": "个人简介不能超过{}个字符!".format( UserInfo.about.type.length) } else: return {"status": 200, "message": "OK"} return result pass
147bdd497787afbcc3d41144253e037fa9339e4e
[ "HTML", "JavaScript", "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
102
Python
yangjiaronga/Witcoder
2f7891326af884ba4831ce79c6492591c1149237
1f874492feeedbc7f86279f2f12d7d77386041d3
refs/heads/master
<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.core.*; import ch.zhaw.ba.anath.pki.core.interfaces.CertificateConstraintProvider; import ch.zhaw.ba.anath.pki.core.interfaces.CertificateSerialProvider; import ch.zhaw.ba.anath.pki.core.interfaces.CertificateValidityProvider; import ch.zhaw.ba.anath.pki.core.interfaces.SignatureNameProvider; import ch.zhaw.ba.anath.pki.entities.CertificateEntity; import ch.zhaw.ba.anath.pki.entities.CertificateStatus; import ch.zhaw.ba.anath.pki.entities.UseEntity; import ch.zhaw.ba.anath.pki.exceptions.CertificateAlreadyExistsException; import ch.zhaw.ba.anath.pki.exceptions.SigningException; import ch.zhaw.ba.anath.pki.repositories.UseRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.*; import java.sql.Timestamp; import java.util.Date; import java.util.Optional; /** * Sign a CSR and store the certificate. The {@link CertificateAuthority} is created on first use and kept in memory. * Thus be careful when changing the CA private key and certificate, you need to restart the application. * * @author <NAME> */ @Service @Slf4j @Transactional(transactionManager = "pkiTransactionManager") public class SigningService { private final CertificateAuthorityService certificateAuthorityService; private final ConfirmableCertificatePersistenceLayer confirmableCertificatePersistenceLayer; private final UseRepository useRepository; private final CertificateConstraintProvider certificateConstraintProvider; private final SignatureNameProvider signatureNameProvider; private final CertificateValidityProvider certificateValidityProvider; private final CertificateSerialProvider certificateSerialProvider; private final CertificateUniquenessService certificateUniquenessService; private final ConfirmationNotificationService confirmationNotificationService; private CertificateAuthority certificateAuthority = null; private CertificateSigner certificateSigner = null; public SigningService(CertificateAuthorityService certificateAuthorityService, ConfirmableCertificatePersistenceLayer confirmableCertificatePersistenceLayer, UseRepository useRepository, CertificateConstraintProvider certificateConstraintProvider, SignatureNameProvider signatureNameProvider, CertificateValidityProvider certificateValidityProvider, CertificateSerialProvider certificateSerialProvider, CertificateUniquenessService certificateUniquenessService, ConfirmationNotificationService confirmationNotificationService) { this.certificateAuthorityService = certificateAuthorityService; this.confirmableCertificatePersistenceLayer = confirmableCertificatePersistenceLayer; this.useRepository = useRepository; this.certificateConstraintProvider = certificateConstraintProvider; this.signatureNameProvider = signatureNameProvider; this.certificateValidityProvider = certificateValidityProvider; this.certificateSerialProvider = certificateSerialProvider; this.certificateUniquenessService = certificateUniquenessService; this.confirmationNotificationService = confirmationNotificationService; } /** * Initializes the {@link CertificateSigner} instance. It first initializes the {@link CertificateAuthority}. * It can be called multiple times. Once the {@link CertificateSigner} has been initialized, it won't be * initialized again. */ private void initializeCertificateSigner() { if (certificateSigner != null) { return; } initializeCertificateAuthority(); certificateSigner = new CertificateSigner(signatureNameProvider, certificateAuthority); certificateSigner.setCertificateConstraintProvider(certificateConstraintProvider); certificateSigner.setCertificateSerialProvider(certificateSerialProvider); certificateSigner.setValidityProvider(certificateValidityProvider); log.info("Initialized and cached certificate signer"); } /** * Initialize the CertificateAuthority. It can be called multiple times. Once the {@link CertificateAuthority} * has been initialized, it won't be initialized again. */ private void initializeCertificateAuthority() { if (certificateAuthority != null) { return; } log.info("Load and cache certificate authority"); certificateAuthority = certificateAuthorityService.getCertificateAuthority(); } /** * Sign a CSR. * <p> * The CSR will be signed and tentatively added to a store. If the subject of the CSR already exists and the * certificate is non-revoked and non-expired, the signing process will be aborted and an exception thrown. * <p> * Besides exception mentioned below, {@link ch.zhaw.ba.anath.pki.core.exceptions.PKIException} may be thrown. * * @param certificateSigningRequest the {@link Reader} providing the CSR. * @param userId the user id of the user the certificate belongs to. * @param use the use. If the use cannot be found in the database, the {@value * UseEntity#DEFAULT_USE} is used. * * @return Confirmation token. This is used to confirm the certificate. * * @throws CertificateAlreadyExistsException when a non-revoked, non-expired for the given subject already * exists, or the serial number is taken. * @throws SigningException if no default certificate use can be found. */ public String tentativelySignCertificate(CertificateSigningRequest certificateSigningRequest, String userId, String use) { initializeCertificateSigner(); final String subject = certificateSigningRequest.getSubject().toString(); log.info("Test uniqueness of certificate '{}'", subject); certificateUniquenessService.testCertificateUniquenessInCertificateRepositoryOrThrow(subject); log.info("Sign certificate signing request '{}'", subject); final Certificate certificate = certificateSigner.signCertificate(certificateSigningRequest); log.info("Signed certificate '{}'", subject); log.info("Store signed certificate '{}'", subject); final String token = storeCertificate(certificate, userId, use); confirmationNotificationService.sendMail(token, userId); return token; } /** * Confirm a tentatively signed certificate. * * @param token token as received by {@link #tentativelySignCertificate(CertificateSigningRequest, String, String)} * @param userId the user id the token belongs to. * * @return the {@link Certificate} instance. */ public Certificate confirmTentativelySignedCertificate(String token, String userId) { final CertificateEntity confirmedCertificate = confirmableCertificatePersistenceLayer.confirm(token, userId); final InputStream memoryStream = new ByteArrayInputStream(confirmedCertificate.getX509PEMCertificate()); try (Reader pemCertificateStreamReader = new InputStreamReader(memoryStream)) { final PEMCertificateReader pemCertificateReader = new PEMCertificateReader(pemCertificateStreamReader); return pemCertificateReader.certificate(); } catch (IOException e) { log.error("Error reading certificate from PEM: {}", e.getMessage()); throw new SigningException("Error reading certificate"); } } private String storeCertificate(Certificate certificate, String userId, String use) { final UseEntity useEntity = fetchUseEntity(use); final CertificateEntity certificateEntity = new CertificateEntity(); certificateEntity.setStatus(CertificateStatus.VALID); certificateEntity.setUserId(userId); certificateEntity.setSubject(certificate.getSubject().toString()); certificateEntity.setSerial(certificate.getSerial()); certificateEntity.setNotValidBefore(dateToTimestamp(certificate.getValidFrom())); certificateEntity.setNotValidAfter(dateToTimestamp(certificate.getValidTo())); certificateEntity.setX509PEMCertificate(certificateToByteArray(certificate)); certificateEntity.setUse(useEntity); return confirmableCertificatePersistenceLayer.store(certificateEntity); } private UseEntity fetchUseEntity(String use) { final Optional<UseEntity> useOptional = useRepository.findOne(use); return useOptional.orElseGet(() -> { final Optional<UseEntity> defaultUseOptional = useRepository.findOne(UseEntity.DEFAULT_USE); return defaultUseOptional.orElseThrow(() -> { log.error("Default use '{}' not found", UseEntity.DEFAULT_USE); return new SigningException("Default use not found"); }); }); } private Timestamp dateToTimestamp(Date date) { return new Timestamp(date.getTime()); } private byte[] certificateToByteArray(Certificate certificate) { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream)) { final PEMCertificateWriter pemCertificateWriter = new PEMCertificateWriter(outputStreamWriter); pemCertificateWriter.writeCertificate(certificate); return byteArrayOutputStream.toByteArray(); } catch (IOException e) { log.error("Cannot write certificate to byte array: {}", e.getMessage()); throw new SigningException("Cannot store certificate"); } } } <file_sep>The password of ca\_encrypted.pkcs12 is '<PASSWORD>.' <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.users.controllers; import ch.zhaw.ba.anath.AnathExtensionMediaType; import ch.zhaw.ba.anath.pki.services.RevocationService; import ch.zhaw.ba.anath.users.dto.*; import ch.zhaw.ba.anath.users.services.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.hateoas.Link; import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.Resources; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.util.List; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /** * @author <NAME> */ @RestController @RequestMapping(path = "/users", consumes = AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON_VALUE, produces = AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON_VALUE) @Api(tags = {"User Management"}) public class UserController { private final UserService userService; private final RevocationService revocationService; public UserController(UserService userService, RevocationService revocationService) { this.userService = userService; this.revocationService = revocationService; } @GetMapping( consumes = MediaType.ALL_VALUE ) @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "Get All Users") public Resources<UserLinkDto> getAll() { final List<UserLinkDto> all = userService.getAll(); all.stream().forEach(x -> x.add(linkTo(UserController.class).slash(x.getUserId()).withSelfRel())); return new Resources<>(all); } @GetMapping( path = "/{id}", consumes = MediaType.ALL_VALUE ) @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('ADMIN') or (hasRole('USER') and hasPermission(#id,'user','get'))") @ApiOperation(value = "Get a User") public UserDto getUser(@PathVariable long id) { final UserDto user = userService.getUser(id); user.add(linkTo(methodOn(UserController.class).getUser(id)).withSelfRel()); return user; } @PutMapping(path = "/{id}") @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "Update a User") public UserLinkDto updateUser(@PathVariable long id, @RequestBody @Validated UpdateUserDto updateUserDto) { final UserLinkDto userLinkDto = userService.updateUser(id, updateUserDto); userLinkDto.add(linkTo(methodOn(UserController.class).getUser(id)).withSelfRel()); return userLinkDto; } @DeleteMapping( path = "/{id}", consumes = MediaType.ALL_VALUE ) @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "Delete a User") public ResourceSupport deleteUser(@PathVariable long id) { final UserDto userInformation = userService.getUser(id); userService.deleteUser(id); revocationService.revokeAllCertificatesByUser(userInformation.getEmail(), "User deleted"); final ResourceSupport resourceSupport = new ResourceSupport(); resourceSupport.add(linkTo(methodOn(UserController.class).getAll()).withRel("list")); return resourceSupport; } @PutMapping(path = "/{id}/password") @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('USER') and hasPermission(#id,'user','changePassword')") @ApiOperation(value = "Change Password of a User") public UserLinkDto changePassword(@PathVariable long id, @RequestBody @Validated ChangePasswordDto changePasswordDto) { final UserLinkDto userLinkDto = userService.changePassword(id, changePasswordDto); userLinkDto.add(linkTo(methodOn(UserController.class).getUser(id)).withSelfRel()); return userLinkDto; } @PostMapping @ResponseStatus(HttpStatus.CREATED) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "Create a New User") public HttpEntity<Void> createUser(@RequestBody @Validated CreateUserDto createUserDto) { final UserLinkDto user = userService.createUser(createUserDto); final Link link = linkTo(methodOn(UserController.class).getUser(user.getUserId())).withSelfRel(); return ResponseEntity.created(URI.create(link.getHref())).build(); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.config.spring; import ch.zhaw.ba.anath.config.properties.AnathProperties; import ch.zhaw.ba.anath.users.entities.UserEntitiesMarkerInterface; import ch.zhaw.ba.anath.users.repositories.UserRepositoriesMarkerInterface; import lombok.extern.slf4j.Slf4j; import org.flywaydb.core.Flyway; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; /** * Spring datasource for user store. * * @author <NAME> */ @Configuration @EnableJpaRepositories( basePackageClasses = UserRepositoriesMarkerInterface.class, entityManagerFactoryRef = "userEntityManagerFactory", transactionManagerRef = "userTransactionManager") @Slf4j public class UserDatasourceConfiguration { private static final String USER_DATASOURCE_CONFIGURATION_PROPERTIES_PREFIX = AnathProperties .CONFIGURATION_PREFIX + ".users.datasource"; @Bean @ConfigurationProperties(prefix = USER_DATASOURCE_CONFIGURATION_PROPERTIES_PREFIX) public DataSourceProperties userDataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties(prefix = USER_DATASOURCE_CONFIGURATION_PROPERTIES_PREFIX) public DataSource userDataSource() { DataSource userDS = userDataSourceProperties().initializeDataSourceBuilder().build(); log.info("Initialize Flyway for Users"); final Flyway usersFlyway = new Flyway(); usersFlyway.setDataSource(userDS); usersFlyway.setLocations("/flyway/users"); log.info("Start Flyway migration for Users"); usersFlyway.migrate(); log.info("End Flyway migration for Users"); return userDS; } @Bean() public LocalContainerEntityManagerFactoryBean userEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(userDataSource()) .packages(UserEntitiesMarkerInterface.class) .persistenceUnit("users") .build(); } @Bean public PlatformTransactionManager userTransactionManager( @Qualifier("userEntityManagerFactory") EntityManagerFactory userEntityManagerFactory) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(userEntityManagerFactory); return transactionManager; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2018, <NAME>, <NAME> ~ All rights reserved. ~ ~ Redistribution and use in source and binary forms, with or without ~ modification, are permitted provided that the following conditions are ~ met: ~ ~ 1. Redistributions of source code must retain the above copyright ~ notice, this list of conditions and the following disclaimer. ~ ~ 2. Redistributions in binary form must reproduce the above copyright ~ notice, this list of conditions and the following disclaimer in the ~ documentation and/or other materials provided with the ~ distribution. ~ ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ~ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ~ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ~ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ~ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ~ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ~ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ~ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ~ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ~ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ~ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.13.RELEASE</version> </parent> <groupId>ch.zhaw.ba</groupId> <artifactId>anath-server</artifactId> <version>1.1.0</version> <packaging>jar</packaging> <name>anath-server</name> <url>https://github.com/AnathPKI/anath-server</url> <licenses> <license> <name>The 2-Clause BSD License</name> </license> </licenses> <developers> <developer> <id>rafi</id> <name><NAME></name> <email><EMAIL></email> </developer> <developer> <id>martin</id> <name><NAME></name> </developer> </developers> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <java.version>1.8</java.version> <!-- We need a plugin newer than 3.1 to use selma sucessfuly --> <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version> <sonar.junit.reportPaths>target/surefire-reports,target/failsafe-reports</sonar.junit.reportPaths> <sonar.jacoco.reportPaths>target/jacoco.exec,target/jacoco-it.exec</sonar.jacoco.reportPaths> <sonar.import_unknown_files>true</sonar.import_unknown_files> <sonar.coverage.exclusions> **/*Exception.java,**/*Dto.java,**/*Entity.java,**/*Repository.java,**/*SelmaGeneratedClass.java,**/nonproduction/*.java,**/configuration/**.java,**/dto/**.java,**/Application.java </sonar.coverage.exclusions> <sonar.exclusions>**/*SelmaGeneratedClass.java,**/nonproduction/*.java</sonar.exclusions> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> <!-- https://mvnrepository.com/artifact/de.mkammerer/argon2-jvm --> <dependency> <groupId>de.mkammerer</groupId> <artifactId>argon2-jvm</artifactId> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.flywaydb/flyway-core --> <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>5.0.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.59</version> </dependency> <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk15on --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk15on</artifactId> <version>1.59</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok-maven --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/fr.xebia.extras/selma --> <dependency> <groupId>fr.xebia.extras</groupId> <artifactId>selma</artifactId> <version>1.0</version> </dependency> <!-- scope provided because the processor is only needed at compile time--> <dependency> <groupId>fr.xebia.extras</groupId> <artifactId>selma-processor</artifactId> <version>1.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-all --> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.h2database/h2 --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.197</version> <scope>test</scope> </dependency> <!-- Swagger docu --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-bean-validators</artifactId> <version>2.8.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>build-info</goal> </goals> </execution> </executions> </plugin> <!-- Generate git information that can be queried via actuators. --> <plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <annotationProcessors> <!-- Lombok is required to run before selma --> <annotationProcessor>lombok.launch.AnnotationProcessorHider$AnnotationProcessor </annotationProcessor> <annotationProcessor>fr.xebia.extras.selma.codegen.MapperProcessor</annotationProcessor> </annotationProcessors> </configuration> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.9</version> <executions> <execution> <id>default-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> <configuration> <excludes> <exclude>*Exception</exclude> <exclude>*Dto</exclude> </excludes> </configuration> </execution> <execution> <id>default-prepare-agent-integration</id> <goals> <goal>prepare-agent-integration</goal> </goals> <configuration> <excludes> <exclude>*Exception</exclude> <exclude>*Dto</exclude> </excludes> </configuration> </execution> <execution> <id>default-report</id> <goals> <goal>report</goal> </goals> <configuration> <excludes> <exclude>**/*Exception.class</exclude> <exclude>**/*Dto.class</exclude> </excludes> </configuration> </execution> <execution> <id>default-report-integration</id> <goals> <goal>report-integration</goal> </goals> <configuration> <excludes> <exclude>**/*Exception.class</exclude> <exclude>**/*Dto.class</exclude> </excludes> </configuration> </execution> </executions> </plugin> <plugin> <!-- Do not specify a </version>. Spring boot is taking care of that --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> </plugin> <!-- Integration Testing --> <plugin> <!-- Do not specify a </version>. Spring boot is taking care of that. If you use the wrong version, you'll most likely f*** up things --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> <id>default</id> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> <!-- JavaDoc --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.4</version> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> </plugin> </plugins> </reporting> </project><file_sep>#!/bin/sh # The script expects the jar to be placed in /application/application.jar and # # # Arguments passed to this script will be relayed as arguments to java. set -eu JAVA=java JAVA_OPTS=${JAVA_OPTS:-} JAR="-jar application.jar" exec ${JAVA} ${JAVA_OPTS} ${JAR} <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.controllers; import ch.zhaw.ba.anath.AnathExtensionMediaType; import ch.zhaw.ba.anath.TestSecuritySetup; import ch.zhaw.ba.anath.pki.dto.CreateSelfSignedCertificateAuthorityDto; import ch.zhaw.ba.anath.pki.dto.ImportCertificateAuthorityDto; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityAlreadyInitializedException; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityInitializationException; import ch.zhaw.ba.anath.pki.repositories.CertificateRepository; import ch.zhaw.ba.anath.pki.services.CertificateAuthorityInitializationService; import ch.zhaw.ba.anath.users.repositories.UserRepository; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.startsWith; import static org.mockito.BDDMockito.then; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * @author <NAME> */ @RunWith(SpringRunner.class) @WebMvcTest(CertificateAuthorityInitializationController.class) @ActiveProfiles("tests") @TestSecuritySetup public class CertificateAuthorityInitializationControllerIT { private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Autowired private MockMvc mvc; @MockBean private CertificateAuthorityInitializationService certificateAuthorityInitializationService; // Required to satisfy injection dependency @MockBean private UserRepository userRepository; // Required to satisfy injection dependency @MockBean private CertificateRepository certificateRepository; @Test @WithMockUser(username = "admin", roles = {"ADMIN"}) public void importCaAsAdmin() throws Exception { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword(""); importCertificateAuthorityDto.setPkcs12("bla"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(importCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isCreated()) .andExpect(header().string("Content-Type", startsWith(AnathExtensionMediaType .APPLICATION_VND_ANATH_EXTENSION_V1_JSON_VALUE))) .andExpect(header().string("Location", "http://localhost/ca.pem")); then(certificateAuthorityInitializationService).should().importPkcs12CertificateAuthority (importCertificateAuthorityDto); } @Test @WithMockUser(username = "admin", roles = {"ADMIN"}) public void importCaAlreadyExistingAsAdmin() throws Exception { doThrow(new CertificateAuthorityAlreadyInitializedException("already initialized")) .when(certificateAuthorityInitializationService).importPkcs12CertificateAuthority(any()); final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword(""); importCertificateAuthorityDto.setPkcs12("bla"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(importCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isConflict()); } @Test @WithMockUser(username = "admin", roles = {"ADMIN"}) public void importCaImportExceptionAsAdmin() throws Exception { doThrow(new CertificateAuthorityInitializationException("import exception")) .when(certificateAuthorityInitializationService).importPkcs12CertificateAuthority(any()); final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword(""); importCertificateAuthorityDto.setPkcs12("bla"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(importCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isInternalServerError()); } @Test @WithMockUser(username = "user", roles = {"USER"}) public void importCaAsUser() throws Exception { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword(""); importCertificateAuthorityDto.setPkcs12("bla"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(importCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isForbidden()); then(certificateAuthorityInitializationService).should(never()).importPkcs12CertificateAuthority(any()); } @Test public void importCaAsUnauthenticated() throws Exception { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword(""); importCertificateAuthorityDto.setPkcs12("bla"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(importCertificateAuthorityDto)) ) .andExpect(unauthenticated()) .andExpect(status().isUnauthorized()); then(certificateAuthorityInitializationService).should(never()).importPkcs12CertificateAuthority(any()); } @Test @WithMockUser(username = "admin", roles = {"ADMIN"}) public void createSelfSignedWithInvalidDtoAsAdmin() throws Exception { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = new CreateSelfSignedCertificateAuthorityDto(); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(createSelfSignedCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isBadRequest()); } @Test @WithMockUser(username = "admin", roles = {"ADMIN"}) public void createSelfSignedValidationErrorAsDto() throws Exception { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = new CreateSelfSignedCertificateAuthorityDto(); createSelfSignedCertificateAuthorityDto.setBits(512); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(createSelfSignedCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isBadRequest()); } @Test @WithMockUser(username = "admin", roles = {"ADMIN"}) public void createSelfSignedWithMinimumDtoAsAdmin() throws Exception { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = new CreateSelfSignedCertificateAuthorityDto(); createSelfSignedCertificateAuthorityDto.setBits(1024); createSelfSignedCertificateAuthorityDto.setValidDays(180); createSelfSignedCertificateAuthorityDto.setOrganization("o"); createSelfSignedCertificateAuthorityDto.setCommonName("cn"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(createSelfSignedCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isCreated()) .andExpect(header().string("Content-Type", startsWith(AnathExtensionMediaType .APPLICATION_VND_ANATH_EXTENSION_V1_JSON_VALUE))) .andExpect(header().string("Location", "http://localhost/ca.pem")); then(certificateAuthorityInitializationService).should().createSelfSignedCertificateAuthority (createSelfSignedCertificateAuthorityDto); } @Test @WithMockUser(username = "user", roles = {"USER"}) public void createSelfSignedAsUser() throws Exception { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = new CreateSelfSignedCertificateAuthorityDto(); createSelfSignedCertificateAuthorityDto.setBits(1024); createSelfSignedCertificateAuthorityDto.setValidDays(180); createSelfSignedCertificateAuthorityDto.setOrganization("o"); createSelfSignedCertificateAuthorityDto.setCommonName("cn"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(createSelfSignedCertificateAuthorityDto)) ) .andExpect(authenticated()) .andExpect(status().isForbidden()); then(certificateAuthorityInitializationService).should(never()).createSelfSignedCertificateAuthority(any()); } @Test public void createSelfSignedAsUnauthenticated() throws Exception { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = new CreateSelfSignedCertificateAuthorityDto(); createSelfSignedCertificateAuthorityDto.setBits(1024); createSelfSignedCertificateAuthorityDto.setValidDays(180); createSelfSignedCertificateAuthorityDto.setOrganization("o"); createSelfSignedCertificateAuthorityDto.setCommonName("cn"); mvc.perform( put("/") .contentType(AnathExtensionMediaType.APPLICATION_VND_ANATH_EXTENSION_V1_JSON) .content(OBJECT_MAPPER.writeValueAsBytes(createSelfSignedCertificateAuthorityDto)) ) .andExpect(unauthenticated()) .andExpect(status().isUnauthorized()); then(certificateAuthorityInitializationService).should(never()).createSelfSignedCertificateAuthority(any()); } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.controllers; import ch.zhaw.ba.anath.AnathException; import ch.zhaw.ba.anath.authentication.AnathSecurityHelper; import ch.zhaw.ba.anath.pki.core.Certificate; import ch.zhaw.ba.anath.pki.core.CertificateSigningRequest; import ch.zhaw.ba.anath.pki.core.PEMCertificateSigningRequestReader; import ch.zhaw.ba.anath.pki.dto.SigningRequestDto; import ch.zhaw.ba.anath.pki.services.SigningService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.URI; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /** * Non-Confirming Signing Controller. * * @author <NAME> */ @RestController("SigningWithoutConfirmation") @Profile("!confirm") @RequestMapping(value = "/certificates", consumes = AnathMediaType.APPLICATION_VND_ANATH_V1_JSON_VALUE, produces = AnathMediaType.APPLICATION_VND_ANATH_V1_JSON_VALUE) @Api(tags = {"Certificate Authority"}) @Slf4j public class SigningControllerWithoutConfirmation { private static final String ERROR_READING_PEM_OBJECT_FROM_REQUEST = "Error reading PEM object from request"; private final SigningService signingService; public SigningControllerWithoutConfirmation(SigningService signingService) { this.signingService = signingService; log.info("Non-Confirming Signing Controller loaded"); } public static CertificateSigningRequest readCertificateSigningRequest(InputStream byteArrayInputStream) { CertificateSigningRequest certificateSigningRequest; try (Reader reader = new InputStreamReader(byteArrayInputStream)) { final PEMCertificateSigningRequestReader pemCertificateSigningRequestReader = new PEMCertificateSigningRequestReader(reader); certificateSigningRequest = pemCertificateSigningRequestReader .certificationRequest(); } catch (IOException e) { log.error(ERROR_READING_PEM_OBJECT_FROM_REQUEST); throw new AnathException(ERROR_READING_PEM_OBJECT_FROM_REQUEST); } return certificateSigningRequest; } @PostMapping @ResponseStatus(HttpStatus.CREATED) @PreAuthorize("hasRole('USER')") @ApiOperation(value = "Sign a PKCS#10 Certificate Signing Request", notes = "Only users may call this endpoint.") public HttpEntity<Void> signCertificateRequest(@RequestBody @Validated SigningRequestDto signingRequestDto, HttpServletRequest httpServletRequest) { final InputStream byteArrayInputStream = new ByteArrayInputStream( signingRequestDto .getCsr() .getPem().getBytes()); CertificateSigningRequest certificateSigningRequest; certificateSigningRequest = readCertificateSigningRequest(byteArrayInputStream); final String username = AnathSecurityHelper.getUsername(); final String token = signingService.tentativelySignCertificate(certificateSigningRequest, username, signingRequestDto.getUse()); final Certificate certificate = signingService.confirmTentativelySignedCertificate(token, httpServletRequest.getUserPrincipal().getName()); final URI uri = linkTo(methodOn(CertificatesController.class).getCertificate(certificate.getSerial())) .toUri(); return ResponseEntity .created(uri) .contentType(AnathMediaType.APPLICATION_VND_ANATH_V1_JSON) .build(); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.users.services; import ch.zhaw.ba.anath.users.dto.*; import ch.zhaw.ba.anath.users.entities.UserEntity; import ch.zhaw.ba.anath.users.exceptions.PasswordMismatchException; import ch.zhaw.ba.anath.users.exceptions.UserDoesNotExistException; import ch.zhaw.ba.anath.users.exceptions.UserPasswordException; import ch.zhaw.ba.anath.users.mappers.UserEntityMapper; import ch.zhaw.ba.anath.users.repositories.UserRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @author <NAME> */ @Service @Slf4j @Transactional(transactionManager = "userTransactionManager") public class UserService { private final UserRepository userRepository; private final UserEntityMapper userEntityMapper; private final PasswordEncoder passwordEncoder; public UserService(UserRepository userRepository, UserEntityMapper userEntityMapper, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.userEntityMapper = userEntityMapper; this.passwordEncoder = passwordEncoder; } public UserLinkDto createUser(CreateUserDto createUserDto) { log.info("Create new user '{}'", createUserDto.getEmail()); final UserEntity newUserEntity = userEntityMapper.asEntity(createUserDto); if (newUserEntity.getPassword() == null || newUserEntity.getPassword().isEmpty()) { log.error("User '{}' must not have empty password", newUserEntity.getEmail()); throw new UserPasswordException("User must not have empty password"); } log.info("Encoding password for new user '{}'", newUserEntity.getEmail()); newUserEntity.setPassword(passwordEncoder.encode(newUserEntity.getPassword())); log.info("Saving new user '{}'", newUserEntity.getEmail()); userRepository.save(newUserEntity); return userEntityMapper.asUserLinkDto(newUserEntity); } public void deleteUser(long id) { final UserEntity userEntity = findUserEntityByIdOrThrow(id); log.info("Delete user '{}' with id '{}'", userEntity.getEmail(), id); userRepository.deleteById(id); } private UserEntity findUserEntityByIdOrThrow(long id) { final Optional<UserEntity> optionalUserEntity = userRepository.findOne(id); return optionalUserEntity.orElseThrow(() -> { log.error("Unable to find user with id '{}'", id); return new UserDoesNotExistException("Unable to find user"); }); } public UserLinkDto updateUser(long id, UpdateUserDto updateUserDto) { final UserEntity userEntity = findUserEntityByIdOrThrow(id); log.info("Update user '{}' with id '{}'", userEntity.getEmail(), id); userEntityMapper.updateEntity(updateUserDto, userEntity); userRepository.save(userEntity); return userEntityMapper.asUserLinkDto(userEntity); } public UserLinkDto changePassword(long id, ChangePasswordDto changePasswordDto) { final UserEntity userEntity = findUserEntityByIdOrThrow(id); log.info("Updating password of user '{}' with id '{}'", userEntity.getEmail(), id); if (!passwordEncoder.matches(changePasswordDto.getOldPassword(), userEntity.getPassword())) { log.info("Cannot updated password of user '{}'. Old password incorrect", userEntity.getEmail()); throw new PasswordMismatchException("Old password incorrect"); } userEntity.setPassword(passwordEncoder.encode(changePasswordDto.getNewPassword())); return userEntityMapper.asUserLinkDto(userEntity); } public UserDto getUser(long id) { log.info("Looking up user with id '{}'", id); final Optional<UserEntity> userEntityOptional = userRepository.findOne(id); final UserEntity userEntity = userEntityOptional.orElseThrow(() -> { log.error("User with id '{}' not found", id); return new UserDoesNotExistException("User not found"); }); return userEntityMapper.asUserDto(userEntity); } public UserDto getUser(String emailAdress) { log.info("Looking up user with email address '{}'", emailAdress); final Optional<UserEntity> userEntityOptional = userRepository.findOneByEmail(emailAdress); final UserEntity userEntity = userEntityOptional.orElseThrow(() -> { log.error("User with email address '{}' not found", emailAdress); return new UserDoesNotExistException("User not found"); }); return userEntityMapper.asUserDto(userEntity); } public List<UserLinkDto> getAll() { return userRepository.findAll().stream() .map(userEntityMapper::asUserLinkDto) .collect(Collectors.toList()); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.authentication.users; import ch.zhaw.ba.anath.users.entities.UserEntity; import ch.zhaw.ba.anath.users.repositories.UserRepository; import org.junit.Before; import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import java.util.Collections; import java.util.Optional; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author <NAME> */ public class UserPermissionEvaluatorTest { private final static Set<SimpleGrantedAuthority> DEFAULT_USER_ROLES = Collections.singleton(new SimpleGrantedAuthority("USER")); private static final String TEST_USER_NAME = "testuser"; private static final String TARGET_TYPE = "user"; private UserRepository userRepositoryMock; private UserPermissionEvaluator userPermissionEvaluator; @Before public void setUp() { this.userRepositoryMock = mock(UserRepository.class); this.userPermissionEvaluator = new UserPermissionEvaluator(userRepositoryMock); } @Test(expected = UnsupportedOperationException.class) public void hasPermission3() { userPermissionEvaluator.hasPermission(null, null, null); } @Test public void hasPermission4ChangePassword() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = userPermissionEvaluator.hasPermission(authentication, 1L, TARGET_TYPE, "changePassword"); assertThat(result, is(true)); result = userPermissionEvaluator.hasPermission(authentication, 2L, TARGET_TYPE, "changePassword"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 3L, TARGET_TYPE, "changePassword"); assertThat(result, is(false)); } @Test public void hasPermission4GetPermissions() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = userPermissionEvaluator.hasPermission(authentication, 1L, TARGET_TYPE, "get"); assertThat(result, is(true)); result = userPermissionEvaluator.hasPermission(authentication, 2L, TARGET_TYPE, "get"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 3L, TARGET_TYPE, "get"); assertThat(result, is(false)); } @Test public void hasPermission4UnknownPermission() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = userPermissionEvaluator.hasPermission(authentication, 1L, TARGET_TYPE, "should not exist"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 2L, TARGET_TYPE, "should not exist"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 3L, TARGET_TYPE, "should not exist"); assertThat(result, is(false)); } @Test public void hasPermission4UnknownTargetType() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = userPermissionEvaluator.hasPermission(authentication, 1L, "should not exist", "get"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 2L, "should not exist", "get"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 3L, "should not exist", "get"); assertThat(result, is(false)); } @Test public void hasPermission4InvalidTargetIdType() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = userPermissionEvaluator.hasPermission(authentication, "id", TARGET_TYPE, "get"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, "id", TARGET_TYPE, "get"); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, "id", TARGET_TYPE, "get"); assertThat(result, is(false)); } @Test public void hasPermission4InvalidPermissionType() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = userPermissionEvaluator.hasPermission(authentication, 1L, TARGET_TYPE, 1); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 2L, TARGET_TYPE, 1); assertThat(result, is(false)); result = userPermissionEvaluator.hasPermission(authentication, 3L, TARGET_TYPE, 1); assertThat(result, is(false)); } private UsernamePasswordAuthenticationToken setUpTest() { final UsernamePasswordAuthenticationToken authentication = setUpTestUser(); final UserEntity testUserEntity = new UserEntity(); testUserEntity.setEmail(TEST_USER_NAME); final UserEntity otherUserEntity = new UserEntity(); otherUserEntity.setEmail(TEST_USER_NAME + "other"); given(userRepositoryMock.findOne(1L)).willReturn(Optional.of(testUserEntity)); given(userRepositoryMock.findOne(2L)).willReturn(Optional.of(otherUserEntity)); given(userRepositoryMock.findOne(3L)).willReturn(Optional.empty()); return authentication; } private UsernamePasswordAuthenticationToken setUpTestUser() { final User testUser = new User(TEST_USER_NAME, "", DEFAULT_USER_ROLES); final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(testUser, "", DEFAULT_USER_ROLES); return authentication; } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.dto.UseDto; import ch.zhaw.ba.anath.pki.dto.UseItemDto; import ch.zhaw.ba.anath.pki.entities.UseEntity; import ch.zhaw.ba.anath.pki.exceptions.UseCreationException; import ch.zhaw.ba.anath.pki.exceptions.UseDeleteException; import ch.zhaw.ba.anath.pki.exceptions.UseNotFoundException; import ch.zhaw.ba.anath.pki.exceptions.UseUpdateException; import ch.zhaw.ba.anath.pki.repositories.UseRepository; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.ArrayUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @author <NAME> */ @Service @Slf4j @Transactional(transactionManager = "pkiTransactionManager") public class UseService { private static final String CANNOT_DELETE_PLAIN_USE_MESSAGE = "Cannot delete 'plain' use"; private static final String CANNOT_UPDATE_PLAIN_USE_MESSAGE = "Must not update 'plain' use"; private static final String PLAIN_USE = "plain"; private final UseRepository useRepository; public UseService(UseRepository useRepository) { this.useRepository = useRepository; } public UseItemDto create(UseDto useDto) { final Optional<UseEntity> existingUseEntity = useRepository.findOne(useDto.getUse()); if (existingUseEntity.isPresent()) { log.error("Cannot create use '{}'. Already exists", useDto.getUse()); throw new UseCreationException("Use already exists"); } final UseEntity useEntity = useDtoToUseEntity(useDto); useRepository.save(useEntity); log.info("Create new use '{}'", useDto.getUse()); return useEntityToUseItemDto(useEntity); } private UseItemDto useEntityToUseItemDto(UseEntity useEntity) { final UseItemDto useItemDto = new UseItemDto(); useItemDto.setUse(useEntity.getUse()); return useItemDto; } private UseEntity useDtoToUseEntity(UseDto useDto) { final UseEntity useEntity = new UseEntity(); useEntity.setUse(useDto.getUse()); if (useDto.getConfiguration() == null) { useEntity.setConfig(null); } else { useEntity.setConfig(ArrayUtils.toObject(useDto.getConfiguration().getBytes())); } return useEntity; } public List<UseItemDto> getAll() { final List<UseEntity> all = useRepository.findAll(); return all .stream() .map(this::useEntityToUseItemDto) .collect(Collectors.toList()); } public void delete(String key) { if (key.equals(PLAIN_USE)) { log.error(CANNOT_DELETE_PLAIN_USE_MESSAGE); throw new UseDeleteException(CANNOT_DELETE_PLAIN_USE_MESSAGE); } final Optional<UseEntity> optionalUseEntity = useRepository.findOne(key); if (!optionalUseEntity.isPresent()) { log.error("Cannot delete non-existing use '{}'", key); throw new UseNotFoundException("Cannot delete non-existing use"); } useRepository.deleteByUse(key); log.error("Delete use '{}'", key); } public UseDto getUse(String key) { final UseEntity useEntity = getUseEntityOrThrow(key); log.info("Retrieve use '{}'", key); return useEntityToUseDto(useEntity); } private UseEntity getUseEntityOrThrow(String key) { final Optional<UseEntity> useEntityOptional = useRepository.findOne(key); return useEntityOptional.orElseThrow(() -> { log.error("Cannot find use '{}'", key); return new UseNotFoundException("Use not found"); }); } private UseDto useEntityToUseDto(UseEntity useEntity) { final UseDto useDto = new UseDto(); useDto.setUse(useEntity.getUse()); if (useEntity.getConfig() == null) { useDto.setConfiguration(null); } else { final byte[] configuration = ArrayUtils.toPrimitive(useEntity.getConfig()); useDto.setConfiguration(new String(configuration)); } return useDto; } public UseItemDto updateUse(String key, String newConfiguration) { if (key.equals(PLAIN_USE)) { log.error(CANNOT_UPDATE_PLAIN_USE_MESSAGE); throw new UseUpdateException(CANNOT_UPDATE_PLAIN_USE_MESSAGE); } final UseEntity useEntity = getUseEntityOrThrow(key); if (newConfiguration == null) { useEntity.setConfig(null); } else { useEntity.setConfig(ArrayUtils.toObject(newConfiguration.getBytes())); } useRepository.save(useEntity); log.info("Updated use '{}'", key); return useEntityToUseItemDto(useEntity); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.config.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; /** * See https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/ * * @author <NAME> */ // Exclude this configuration when tests are ran. @Profile("!tests") @Configuration @EnableSwagger2 @Import({BeanValidatorPluginsConfiguration.class}) public class SwaggerConfiguration { @Bean public Docket productApi() { final List<SecurityContext> securityContexts = new ArrayList<>(); securityContexts.add(securityContext()); return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("ch.zhaw.ba.anath")) .build() .apiInfo(apiInfo()) .securitySchemes(securitySchemes()) .securityContexts(securityContexts) .tags( new Tag("Certificate Authority", "Certificate Authority and User Certificate API"), new Tag("User Management", "User Management API"), new Tag("Misc", "Miscellaneous") ) .useDefaultResponseMessages(false); } private List<SecurityScheme> securitySchemes() { final List<SecurityScheme> schemes = new ArrayList<>(); schemes.add(new ApiKey("jwt", "Authorization", "header")); return schemes; } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("/.*")) .build(); } private List<SecurityReference> defaultAuth() { final AuthorizationScope defaultScope = new AuthorizationScope("global", "Access"); final AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = defaultScope; final List<SecurityReference> securityReferences = new ArrayList<>(); securityReferences.add(new SecurityReference("jwt", authorizationScopes)); return securityReferences; } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Anath Server") .description("Self-Service PKI Server.") .version("1") .build(); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.core; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; /** * @author <NAME> */ public class CertificateRevocationListCreatorTest { public static final long ARBITRARY_DATE_IN_MILLIS = 100000000L; private static final long TEN_SECONDS_IN_MILLIS = 10 * 1000L; private File crlFile; @Before public void setUp() throws IOException { crlFile = File.createTempFile("crl", null); } @After public void tearDown() { if (crlFile != null) { crlFile.delete(); } } @Test public void create() throws IOException, InterruptedException { final Certificate certificate = readCertificate(); final Date revocationDate = new Date(ARBITRARY_DATE_IN_MILLIS); final RevokedCertificate revokedCertificate = new RevokedCertificate(certificate, revocationDate); final List<RevokedCertificate> revokedCertificates = new ArrayList<>(); revokedCertificates.add(revokedCertificate); final CertificateAuthority certificateAuthority = readCertificateAuthority(); final CertificateRevocationListCreator certificateRevocationListCreator = createCertificateRevocationListCreater(certificateAuthority); final CertificateRevocationList certificateRevocationList = certificateRevocationListCreator.create (revokedCertificates); assertEquals(certificateRevocationList.getIssuer(), certificateAuthority.getCASubjectName()); assertThat(certificateRevocationList.getNextUpdate().after(new Date()), is(true)); assertThat(certificateRevocationList.getThisUpdate().before(new Date()), is(true)); try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(crlFile))) { final PEMCertificateRevocationListWriter pemCertificateRevocationListWriter = new PEMCertificateRevocationListWriter(outputStreamWriter); pemCertificateRevocationListWriter.writeRevocationList(certificateRevocationList); } testCrlFileWithOpenSsl(crlFile); } @Test public void createEmptyList() throws IOException, InterruptedException { final List<RevokedCertificate> revokedCertificates = new ArrayList<>(); final CertificateAuthority certificateAuthority = readCertificateAuthority(); final CertificateRevocationListCreator certificateRevocationListCreator = createCertificateRevocationListCreater(certificateAuthority); final Date nextUpdate = new Date(ARBITRARY_DATE_IN_MILLIS + ARBITRARY_DATE_IN_MILLIS); // Used later to compare to thisUpdate. final Date now = new Date(); final CertificateRevocationList certificateRevocationList = certificateRevocationListCreator.create (revokedCertificates); assertEquals(certificateRevocationList.getIssuer(), certificateAuthority.getCASubjectName()); assertThat(certificateRevocationList.getNextUpdate().after(new Date()), is(true)); assertThat(certificateRevocationList.getThisUpdate().before(new Date()), is(true)); try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(crlFile))) { final PEMCertificateRevocationListWriter pemCertificateRevocationListWriter = new PEMCertificateRevocationListWriter(outputStreamWriter); pemCertificateRevocationListWriter.writeRevocationList(certificateRevocationList); } testCrlFileWithOpenSsl(crlFile); } private void testCrlFileWithOpenSsl(File crlFile) throws IOException, InterruptedException { final Process exec = Runtime.getRuntime().exec( new String[]{ "openssl", "crl", "-verify", "-noout", "-in", crlFile.getAbsolutePath(), "-CAfile", TestConstants.CA_CERT_FILE_NAME } ); final int returnValue = exec.waitFor(); try (InputStream errorStream = exec.getErrorStream(); InputStream stdoutStream = exec.getInputStream()) { int b; while ((b = errorStream.read()) != -1) { System.out.print((char) b); } while ((b = stdoutStream.read()) != -1) { System.out.print((char) b); } } assertEquals(0, returnValue); } private CertificateRevocationListCreator createCertificateRevocationListCreater(CertificateAuthority certificateAuthority) { return new CertificateRevocationListCreator( new Sha512WithRsa(), certificateAuthority, new ConfigurablePeriodCRLValidity(2)); } private CertificateAuthority readCertificateAuthority() throws IOException { try ( InputStreamReader caKey = new InputStreamReader(new FileInputStream(TestConstants.CA_KEY_FILE_NAME)); InputStreamReader caCert = new InputStreamReader(new FileInputStream(TestConstants.CA_CERT_FILE_NAME)) ) { final PEMCertificateAuthorityReader pemCertificateAuthorityReader = new PEMCertificateAuthorityReader (caKey, caCert); return pemCertificateAuthorityReader.certificateAuthority(); } } private Certificate readCertificate() throws IOException { try (InputStreamReader caCert = new InputStreamReader(new FileInputStream(TestConstants.CA_CERT_FILE_NAME))) { final PEMCertificateReader pemCertificateReader = new PEMCertificateReader(caCert); return pemCertificateReader.certificate(); } } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.core.*; import ch.zhaw.ba.anath.pki.core.interfaces.CertificateRevocationListValidityProvider; import ch.zhaw.ba.anath.pki.core.interfaces.SignatureNameProvider; import ch.zhaw.ba.anath.pki.entities.CertificateEntity; import ch.zhaw.ba.anath.pki.entities.CertificateStatus; import ch.zhaw.ba.anath.pki.entities.CrlEntity; import ch.zhaw.ba.anath.pki.exceptions.*; import ch.zhaw.ba.anath.pki.repositories.CertificateRepository; import ch.zhaw.ba.anath.pki.repositories.CrlRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.*; import java.math.BigInteger; import java.sql.Timestamp; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; /** * Revoke Certificates and maintain the Certificate Revocation List. Updating the Certificate Revocation List must be * done atomically. Only use the locked operations {@link #cleanAndPersistLocked(CrlEntity)} and * {@link #getCrlEntityLocked()} to store and retrieve the CRL. * * TODO: Is an application lock realy necessary, can't handle the database this and why using locks in the first place * * @author <NAME> */ @Slf4j @Service @Transactional(transactionManager = "pkiTransactionManager") public class RevocationService { private final CertificateAuthorityService certificateAuthorityService; private final CertificateRepository certificateRepository; private final SignatureNameProvider signatureNameProvider; private final CertificateRevocationListValidityProvider certificateRevocationListValidityProvider; private final CrlRepository crlRepository; private final ReentrantLock reentrantLock; private CertificateAuthority certificateAuthority = null; private CertificateRevocationListCreator certificateRevocationListCreator = null; public RevocationService(CertificateAuthorityService certificateAuthorityService, CertificateRepository certificateRepository, SignatureNameProvider signatureNameProvider, CertificateRevocationListValidityProvider certificateRevocationListValidityProvider, CrlRepository crlRepository) { this.certificateAuthorityService = certificateAuthorityService; this.certificateRepository = certificateRepository; this.signatureNameProvider = signatureNameProvider; this.certificateRevocationListValidityProvider = certificateRevocationListValidityProvider; this.crlRepository = crlRepository; reentrantLock = new ReentrantLock(); } /** * Revoke the certificate with a given serial number. This will also update the Certificate Revocation List. * * @param serial serial of the certificate * @param reason the reason. Must not be empty or null. */ public void revokeCertificate(BigInteger serial, String reason) { if (reason == null) { throwEmptyReasonException(serial); return; } String trimmedReason = reason.trim(); if (trimmedReason.isEmpty()) { throwEmptyReasonException(serial); return; } final CertificateEntity certificateEntity = getCertificateEntityOrThrow(serial); if (certificateEntity.getStatus() == CertificateStatus.REVOKED) { log.error("Cannot revoke already revoked certificate with serial {}", serial); throw new CertificateAlreadyRevokedException("Certificate already revoked"); } certificateEntity.setRevocationReason(trimmedReason); certificateEntity.setStatus(CertificateStatus.REVOKED); certificateEntity.setRevocationTime(new Timestamp(System.currentTimeMillis())); certificateRepository.save(certificateEntity); log.info("Revoked certificate with serial {} with reason '{}'", serial.toString(), trimmedReason); updateCertificateRevocationList(); } /** * Revoke all non-revoked, non-expired certificates for a given user. * * @param user user id * @param reason revocation reason. */ public void revokeAllCertificatesByUser(String user, String reason) { final List<CertificateEntity> allByUserWithStatusValid = certificateRepository.findAllByUserIdAndStatus(user, CertificateStatus.VALID); allByUserWithStatusValid .stream() .filter(x -> !CertificateValidityUtils.isExpired(x)) .forEach(x -> revokeCertificate(x.getSerial(), reason)); } /** * Update the Revocation List with all revoked certificates. This method can be called to regenerate the * certificate revocation list, when it is nearing it's next update. */ public void updateCertificateRevocationList() { initializeCertificateRevocationListCreator(); final List<RevokedCertificate> revokedCertificates = certificateRepository .findAllRevoked() .stream() .map(x -> { final Certificate certificate = certificateEntityToCertificate(x); return new RevokedCertificate(certificate, x.getRevocationTime()); }) .collect(Collectors.toList()); final CertificateRevocationList certificateRevocationList = certificateRevocationListCreator.create (revokedCertificates); log.info("Create X.509 Certificate Revocation List"); persistCertificateRevocationList(certificateRevocationList); } public Date getNextUpdate() { final CrlEntity crlEntity = getCrlEntityLocked(); return crlEntity.getNextUpdate(); } public String getCrlPemEncoded() { final CrlEntity crlEntity = getCrlEntityLocked(); return new String(crlEntity.getX509PEMCrl()); } /** * Convert a {@link CertificateRevocationList} instance to an {@link CrlEntity}. * * @param certificateRevocationList {@link CertificateRevocationList} instance. * * @return {@link CrlEntity} instance. */ private CrlEntity certificateRevocationListToCrlEntity(CertificateRevocationList certificateRevocationList) { try (ByteArrayOutputStream pemEncodedCrl = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(pemEncodedCrl)) { final PEMCertificateRevocationListWriter pemCertificateRevocationListWriter = new PEMCertificateRevocationListWriter(writer); pemCertificateRevocationListWriter.writeRevocationList(certificateRevocationList); final CrlEntity crlEntity = new CrlEntity(); crlEntity.setNextUpdate(new Timestamp(certificateRevocationList.getNextUpdate().getTime())); crlEntity.setThisUpdate(new Timestamp(certificateRevocationList.getThisUpdate().getTime())); crlEntity.setX509PEMCrl(pemEncodedCrl.toByteArray()); return crlEntity; } catch (IOException e) { log.info("Error converting Certificate Revocation List to database entity: {}", e.getMessage()); throw new RevocationListCreationException("Error converting Certificate Revocation List to database " + "entity", e); } } /** * Persist the Certificate Revocation List. * * @param certificateRevocationList {@link CertificateRevocationList} instance to be persisted to the database. */ private void persistCertificateRevocationList(CertificateRevocationList certificateRevocationList) { final CrlEntity crlEntity = certificateRevocationListToCrlEntity(certificateRevocationList); cleanAndPersistLocked(crlEntity); } /** * Clears the Certificate Revocation List table and stores a new Certificate Revocation List. It locks the * {@link #reentrantLock} before performing the operation. * * @param crlEntity {@link CrlEntity} crlEntity; */ private void cleanAndPersistLocked(CrlEntity crlEntity) { try { log.info("Acquiring CRL lock"); reentrantLock.lock(); log.info("CRL lock acquired"); // We always clean out the entire table. crlRepository .findAllOrderByThisUpdateDesc() .stream() .forEach(x -> crlRepository.deleteById(x.getId())); log.info("Purged all previous CRLs from the database"); crlRepository.save(crlEntity); log.info("Persisted X.509 Certificate Revocation List to database"); } finally { log.info("Release CRL lock"); reentrantLock.unlock(); log.info("CRL lock released"); } } private Certificate certificateEntityToCertificate(CertificateEntity certifcateEntity) { try (ByteArrayInputStream pemEncodedCertificate = new ByteArrayInputStream(certifcateEntity .getX509PEMCertificate()); InputStreamReader inputStreamReader = new InputStreamReader(pemEncodedCertificate)) { final PEMCertificateReader pemCertificateReader = new PEMCertificateReader(inputStreamReader); return pemCertificateReader.certificate(); } catch (IOException e) { log.error("Error reading certificate from database: {}", e.getMessage()); throw new RevocationListCreationException("Error reading certificate", e); } } private void initializeCertificateRevocationListCreator() { if (certificateRevocationListCreator != null) { return; } initializeCertificateAuthority(); certificateRevocationListCreator = new CertificateRevocationListCreator(signatureNameProvider, certificateAuthority, certificateRevocationListValidityProvider); log.info("Initialized and cached certificate revocation list creator"); } private void initializeCertificateAuthority() { if (certificateAuthority != null) { return; } certificateAuthority = certificateAuthorityService.getCertificateAuthority(); log.info("Loaded and cached certificate authority"); } private void throwEmptyReasonException(BigInteger serial) { log.error("Cannot revoke certificate with serial {}. No reason provided", serial); throw new RevocationNoReasonException("No reason provided"); } private CertificateEntity getCertificateEntityOrThrow(BigInteger serial) { final Optional<CertificateEntity> certificateEntityOptional = certificateRepository.findOneBySerial(serial); return certificateEntityOptional.orElseThrow(() -> { log.error("Certificate with serial {} not found", serial.toString()); return new CertificateNotFoundException("Certificate not found"); }); } private CrlEntity getCrlEntityLocked() { try { log.info("Acquire CRL lock"); reentrantLock.lock(); log.info("CRL lock acquired"); final List<CrlEntity> allOrderByThisUpdateDesc = crlRepository.findAllOrderByThisUpdateDesc(); final Optional<CrlEntity> firstCrlEntity = allOrderByThisUpdateDesc.stream().findFirst(); return firstCrlEntity.orElseThrow(() -> { log.error("No Certificate Revocation List found. CA not initialized?"); return new CertificateAuthorityNotInitializedException("No Certificate Revocation List found"); }); } finally { log.info("Release CRL lock"); reentrantLock.unlock(); log.info("CRL lock released"); } } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.controllers; import ch.zhaw.ba.anath.authentication.AnathSecurityHelper; import ch.zhaw.ba.anath.config.properties.AnathProperties; import ch.zhaw.ba.anath.pki.core.Certificate; import ch.zhaw.ba.anath.pki.core.CertificateSigningRequest; import ch.zhaw.ba.anath.pki.dto.ConfirmationDto; import ch.zhaw.ba.anath.pki.dto.SigningRequestDto; import ch.zhaw.ba.anath.pki.services.SigningService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.util.Date; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; /** * Signing Controller which requires Confirmation. It exposes {@code POST /certificates} and {@code PUT * /certificates/confirm/{token}}. * * @author <NAME> */ @RestController("SigningWithConfirmation") @Profile("confirm") @RequestMapping(value = "/certificates", consumes = AnathMediaType.APPLICATION_VND_ANATH_V1_JSON_VALUE, produces = AnathMediaType.APPLICATION_VND_ANATH_V1_JSON_VALUE) @Api(tags = {"Certificate Authority"}) @Slf4j public class SigningControllerWithConfirmation { private static final long MILLIS_PER_MINUTE = 60 * 1000L; private final SigningService signingService; private final AnathProperties.Confirmation confirmationProperties; public SigningControllerWithConfirmation(SigningService signingService, AnathProperties anathProperties) { this.signingService = signingService; confirmationProperties = anathProperties.getConfirmation(); log.info("Confirming Signing Controller loaded"); } @PostMapping @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('USER')") @ApiOperation(value = "Sign a PKCS#10 Certificate Signing Request with confirmation", notes = "Only users may " + "call this endpoint.") public ConfirmationDto signCertificateRequestWithConfirmation( @RequestBody @Validated SigningRequestDto signingRequestDto, HttpServletRequest httpServletRequest) { final InputStream byteArrayInputStream = new ByteArrayInputStream( signingRequestDto .getCsr() .getPem().getBytes()); CertificateSigningRequest certificateSigningRequest = SigningControllerWithoutConfirmation .readCertificateSigningRequest(byteArrayInputStream); final String username = AnathSecurityHelper.getUsername(); String token = signingService.tentativelySignCertificate(certificateSigningRequest, username, signingRequestDto.getUse()); log.info("Expect confirmation for certificate signing request for user {}. Token: {}", username, token); return confirmationDto(); } @PutMapping("/confirm/{token:[a-zA-Z0-9]+}") @ResponseStatus(HttpStatus.CREATED) @PreAuthorize("hasRole('USER')") @ApiOperation(value = "Confirm a PKCS#10 Certificate Signing Request", notes = "Only users may call this endpoint.") public HttpEntity<Void> confirmSigningRequest(@PathVariable String token, HttpServletRequest httpServletRequest) { final Certificate certificate = signingService.confirmTentativelySignedCertificate(token, httpServletRequest.getUserPrincipal().getName()); final URI uri = linkTo(methodOn(CertificatesController.class).getCertificate(certificate.getSerial())) .toUri(); return ResponseEntity .created(uri) .contentType(AnathMediaType.APPLICATION_VND_ANATH_V1_JSON) .build(); } private ConfirmationDto confirmationDto() { final ConfirmationDto confirmationDto = new ConfirmationDto(); confirmationDto.setNoLaterThan(noLatherThan()); return confirmationDto; } private Date noLatherThan() { long minutesInMillis = minutesToMillis(confirmationProperties.getTokenValidity()); return new Date(System.currentTimeMillis() + minutesInMillis); } private long minutesToMillis(int tokenValidityInMinutes) { return tokenValidityInMinutes * MILLIS_PER_MINUTE; } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityNotInitializedException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Before; import org.junit.Test; import java.util.Optional; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; /** * @author <NAME>ag */ public class ConfigurationTemplateServiceTest { private static final String TEST_TEMPLATE = "The CA Cert: ${caCertificate}. The user cert: ${userCertificate}."; private SecureStoreService secureStoreServiceMock; private ConfigurationTemplateService configurationTemplateService; @Before public void setUp() { secureStoreServiceMock = mock(SecureStoreService.class); configurationTemplateService = new ConfigurationTemplateService(secureStoreServiceMock); } @Test(expected = CertificateAuthorityNotInitializedException.class) public void processWithNoCa() { given(secureStoreServiceMock.get(CertificateAuthorityService.SECURE_STORE_CA_CERTIFICATE)).willReturn (Optional.empty()); configurationTemplateService.process("bla", TEST_TEMPLATE); } @Test public void process() { final Byte[] testCa = ArrayUtils.toObject("CA CERT".getBytes()); given(secureStoreServiceMock.get(CertificateAuthorityService.SECURE_STORE_CA_CERTIFICATE)).willReturn (Optional.of(testCa)); final String expandedTemplate = configurationTemplateService.process("USER CERT", TEST_TEMPLATE); final String expected = "The CA Cert: CA CERT. The user cert USER CERT"; assertThat(expandedTemplate, is(expandedTemplate)); } @Test public void processMany() { final Byte[] testCa = ArrayUtils.toObject("CA CERT".getBytes()); given(secureStoreServiceMock.get(CertificateAuthorityService.SECURE_STORE_CA_CERTIFICATE)).willReturn (Optional.of(testCa)); String expandedTemplate = configurationTemplateService.process("USER CERT", TEST_TEMPLATE); String expected = "The CA Cert: CA CERT. The user cert USER CERT"; assertThat(expandedTemplate, is(expandedTemplate)); expandedTemplate = configurationTemplateService.process("USER CERT 2", TEST_TEMPLATE); expected = "The CA Cert: CA CERT. The user cert USER CERT 2"; assertThat(expandedTemplate, is(expandedTemplate)); then(secureStoreServiceMock).should().get(anyString()); } }<file_sep>CREATE TABLE users ( id BIGSERIAL, firstname VARCHAR(512) NOT NULL, lastname VARCHAR(512) NOT NULL, email VARCHAR(1024) NOT NULL UNIQUE, password VARCHAR(1024) NOT NULL, admin BOOLEAN NOT NULL DEFAULT 'f' ); <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.config.spring; import ch.zhaw.ba.anath.config.properties.AnathProperties; import ch.zhaw.ba.anath.pki.core.*; import ch.zhaw.ba.anath.pki.core.extensions.CertificateExtensionsActionsFactoryInterface; import ch.zhaw.ba.anath.pki.core.extensions.Rfc5280CAExtensionsActionsFactory; import ch.zhaw.ba.anath.pki.core.interfaces.*; import ch.zhaw.ba.anath.pki.corecustomizations.OrganizationAndEmailCertificateConstraint; import ch.zhaw.ba.anath.users.services.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** * @author <NAME> */ @Configuration @Slf4j public class PKICore { private final AnathProperties anathProperties; public PKICore(AnathProperties anathProperties) { this.anathProperties = anathProperties; } @Bean public CertificateSerialProvider certificateSerialProvider() { return new UuidCertificateSerialProvider(); } @Bean public SecureRandomProvider secureRandomProvider() { return new SecureRandomProviderImpl(); } @Bean public SignatureNameProvider signatureNameProvider() { return new Sha512WithRsa(); } @Bean public CertificateValidityProvider certificateValidityProvider() { int days = anathProperties.getCertificateValidity(); log.info("Use ConfigurablePeriodValidity with a value of {} day(s)", days); return new ConfigurablePeriodValidity(days); } @Bean public CertificateRevocationListValidityProvider certificateRevocationListValidityProvider() { int days = anathProperties.getCrlValidity(); log.info("Use ConfigurablePeriodCRLValidity with a value of {} days(s)", days); return new ConfigurablePeriodCRLValidity(days); } @Bean public CertificateExtensionsActionsFactoryInterface certificateExtensionsActionsFactory() { return new Rfc5280CAExtensionsActionsFactory(); } @Bean @Profile("tests") public CertificateConstraintProvider testCertificateConstraintProvider() { log.warn("Tests enabled, use OrganizationCertificateConstraint"); return new OrganizationCertificateConstraint(); } @Bean @Profile("!tests") public CertificateConstraintProvider certificateConstraintProvider(UserService userService) { log.info("Use production OrganizationAndEmailCertificateConstraint()"); return new OrganizationAndEmailCertificateConstraint(userService); } } <file_sep>-- -- The secure store -- CREATE TABLE secure ( id BIGSERIAL, key VARCHAR(512) NOT NULL UNIQUE, encrypted_data BYTEA NOT NULL, iv BYTEA, algo VARCHAR(128) NOT NULL ); -- -- Certificate uses -- CREATE TABLE certificate_uses ( certificate_use VARCHAR(256) PRIMARY KEY, config BYTEA ); -- -- Certificates -- CREATE TABLE certificates ( id BIGSERIAL, serial_number NUMERIC(48) NOT NULL UNIQUE, not_valid_before TIMESTAMP NOT NULL, not_valid_after TIMESTAMP NOT NULL, -- The subject may not be UNIQUE, since uniqueness is only required for non-expired, non-revoked certificates subject VARCHAR(2048) NOT NULL, status VARCHAR(32) NOT NULL, revocation_reason VARCHAR(1024), revocation_time TIMESTAMP, -- The id from a foreign system identifying the user the certificate belongs to user_id VARCHAR(128) NOT NULL, x509_cert_pem BYTEA NOT NULL, certificate_use VARCHAR(256) NOT NULL REFERENCES certificate_uses (certificate_use) ); CREATE TABLE crl ( id BIGSERIAL, this_update TIMESTAMP NOT NULL, next_update TIMESTAMP NOT NULL, x509_crl_pem BYTEA NOT NULL ); INSERT INTO certificate_uses (certificate_use, config) VALUES ('plain', null);<file_sep>FROM openjdk:8-jre-alpine WORKDIR / RUN adduser -h /application \ -g "Application user" \ -D \ app ADD docker/docker-entrypoint.sh . WORKDIR application COPY target/*.jar application.jar USER app EXPOSE 8080 EXPOSE 8443 ENTRYPOINT ["/docker-entrypoint.sh"]<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.core.TestConstants; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * @author <NAME> */ public class CertificateAuthorityInitializer { @PersistenceContext(unitName = "pki") private EntityManager entityManager; @Autowired private SecureStoreService secureStoreService; protected void initializeCa() throws IOException { initializeCaCertificate(); initializeCaPrivateKey(); } protected void initializeCaPrivateKey() throws IOException { try (InputStream privateKeyInputStream = new FileInputStream(TestConstants.CA_KEY_FILE_NAME)) { final byte[] privateKey = IOUtils.toByteArray(privateKeyInputStream); secureStoreService.put(CertificateAuthorityService.SECURE_STORE_CA_PRIVATE_KEY, privateKey); flushAndClear(); } } protected void initializeCaCertificate() throws IOException { try (InputStream certificateInputStream = new FileInputStream(TestConstants.CA_CERT_FILE_NAME)) { final byte[] certificate = IOUtils.toByteArray(certificateInputStream); secureStoreService.put(CertificateAuthorityService.SECURE_STORE_CA_CERTIFICATE, certificate); flushAndClear(); } } protected void flushAndClear() { entityManager.flush(); entityManager.clear(); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.authentication.pki; import ch.zhaw.ba.anath.pki.dto.CertificateListItemDto; import ch.zhaw.ba.anath.pki.entities.CertificateEntity; import ch.zhaw.ba.anath.pki.repositories.CertificateRepository; import org.junit.Before; import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import java.math.BigInteger; import java.util.Collections; import java.util.Optional; import java.util.Set; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author <NAME> */ public class CertificatePermissionEvaluatorTest { private static final String TARGET_TYPE = "certificate"; private final static Set<SimpleGrantedAuthority> DEFAULT_USER_ROLES = Collections.singleton(new SimpleGrantedAuthority(TARGET_TYPE)); private static final String TEST_USER_NAME = "testuser"; private CertificateRepository certificateRepositoryMock; private CertificatePermissionEvaluator certificatePermissionEvaluator; @Before public void setUp() { this.certificateRepositoryMock = mock(CertificateRepository.class); this.certificatePermissionEvaluator = new CertificatePermissionEvaluator(certificateRepositoryMock); } @Test public void hasPermission3AnyObject() { final boolean result = certificatePermissionEvaluator.hasPermission(null, new Object(), null); assertThat(result, is(false)); } @Test public void hasPermission3PermissionNonString() { final boolean result = certificatePermissionEvaluator.hasPermission(null, new CertificateListItemDto(), 3); assertThat(result, is(false)); } @Test public void hasPermission3UnknownPermission() { final boolean result = certificatePermissionEvaluator.hasPermission(null, new CertificateListItemDto(), "should not exist"); assertThat(result, is(false)); } @Test public void hasPermission3NullUserId() { final boolean result = certificatePermissionEvaluator.hasPermission(null, new CertificateListItemDto(), "get"); assertThat(result, is(false)); } @Test public void hasPermission3GetAndUserIdMatch() { final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = setUpTest(); final CertificateListItemDto certificateListItemDto = new CertificateListItemDto(); certificateListItemDto.setUserId(TEST_USER_NAME); final boolean result = certificatePermissionEvaluator.hasPermission(usernamePasswordAuthenticationToken, certificateListItemDto, "get"); assertThat(result, is(true)); } @Test public void hasPermission3RevokeAndUserIdMatch() { final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = setUpTest(); final CertificateListItemDto certificateListItemDto = new CertificateListItemDto(); certificateListItemDto.setUserId(TEST_USER_NAME); final boolean result = certificatePermissionEvaluator.hasPermission(usernamePasswordAuthenticationToken, certificateListItemDto, "revoke"); assertThat(result, is(true)); } @Test public void hasPermission3GetAndUserIdNonMatch() { final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = setUpTest(); final CertificateListItemDto certificateListItemDto = new CertificateListItemDto(); certificateListItemDto.setUserId(TEST_USER_NAME + " another"); final boolean result = certificatePermissionEvaluator.hasPermission(usernamePasswordAuthenticationToken, certificateListItemDto, "get"); assertThat(result, is(false)); } @Test public void hasPermission3RevokeAndUserIdNonMatch() { final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = setUpTest(); final CertificateListItemDto certificateListItemDto = new CertificateListItemDto(); certificateListItemDto.setUserId(TEST_USER_NAME + " another"); final boolean result = certificatePermissionEvaluator.hasPermission(usernamePasswordAuthenticationToken, certificateListItemDto, "revoke"); assertThat(result, is(false)); } @Test public void hasPermission4Revoke() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ZERO, TARGET_TYPE, "revoke"); assertThat(result, is(true)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ONE, TARGET_TYPE, "revoke"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.TEN, TARGET_TYPE, "revoke"); assertThat(result, is(false)); } @Test public void hasPermission4GetPermissions() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ZERO, TARGET_TYPE, "get"); assertThat(result, is(true)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ONE, TARGET_TYPE, "get"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.TEN, TARGET_TYPE, "get"); assertThat(result, is(false)); } @Test public void hasPermission4UnknownPermission() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ZERO, TARGET_TYPE, "should not exist"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ONE, TARGET_TYPE, "should " + "not exist"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.TEN, TARGET_TYPE, "should " + "not exist"); assertThat(result, is(false)); } @Test public void hasPermission4UnknownTargetType() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ZERO, "should not " + "exist", "get"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ONE, "should not exist", "get"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.TEN, "should not exist", "get"); assertThat(result, is(false)); } @Test public void hasPermission4InvalidTargetIdType() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = certificatePermissionEvaluator.hasPermission(authentication, "id", TARGET_TYPE, "get"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, "id", TARGET_TYPE, "get"); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, "id", TARGET_TYPE, "get"); assertThat(result, is(false)); } @Test public void hasPermission4InvalidPermissionType() { final UsernamePasswordAuthenticationToken authentication = setUpTest(); boolean result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ZERO, TARGET_TYPE, 1); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.ONE, TARGET_TYPE, 1); assertThat(result, is(false)); result = certificatePermissionEvaluator.hasPermission(authentication, BigInteger.TEN, TARGET_TYPE, 1); assertThat(result, is(false)); } private UsernamePasswordAuthenticationToken setUpTest() { final UsernamePasswordAuthenticationToken authentication = setUpTestUser(); final CertificateEntity testCertificateEntity = new CertificateEntity(); testCertificateEntity.setUserId(TEST_USER_NAME); final CertificateEntity otherCertificateEntity = new CertificateEntity(); otherCertificateEntity.setUserId(TEST_USER_NAME + "other"); given(certificateRepositoryMock.findOneBySerial(BigInteger.ZERO)).willReturn(Optional.of (testCertificateEntity)); given(certificateRepositoryMock.findOneBySerial(BigInteger.ONE)).willReturn(Optional.of (otherCertificateEntity)); given(certificateRepositoryMock.findOneBySerial(BigInteger.TEN)).willReturn(Optional.empty()); return authentication; } private UsernamePasswordAuthenticationToken setUpTestUser() { final User testUser = new User(TEST_USER_NAME, "", DEFAULT_USER_ROLES); final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(testUser, "", DEFAULT_USER_ROLES); return authentication; } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.core.*; import ch.zhaw.ba.anath.pki.core.interfaces.SecureRandomProvider; import ch.zhaw.ba.anath.pki.dto.CreateSelfSignedCertificateAuthorityDto; import ch.zhaw.ba.anath.pki.dto.ImportCertificateAuthorityDto; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityAlreadyInitializedException; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityImportException; import org.apache.commons.io.IOUtils; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.RFC4519Style; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Base64; import java.util.Optional; import static ch.zhaw.ba.anath.pki.services.CertificateAuthorityService.SECURE_STORE_CA_CERTIFICATE; import static ch.zhaw.ba.anath.pki.services.CertificateAuthorityService.SECURE_STORE_CA_PRIVATE_KEY; import static org.hamcrest.CoreMatchers.both; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; /** * @author <NAME> */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @ActiveProfiles("tests") @TestPropertySource(properties = { "anath.secret-key=<KEY>" }) @Transactional(transactionManager = "pkiTransactionManager") public class CertificateAuthorityInitializationServiceIT { private static final String EXPECTED_IMPORT_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n" + "MIID/jCCAuagAwIBAgIJAPQj6jMYDszkMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\n" + "VQQGEwJDSDEQMA4GA1UECAwHVGh1cmdhdTEQMA4GA1UEBwwHS2VmaWtvbjEYMBYG\n" + "A1UECgwPUmFmYWVsIE9zdGVydGFnMQwwCgYDVQQLDANkZXYxGDAWBgNVBAMMD1Jh\n" + "ZmFlbCBPc3RlcnRhZzEeMBwGCSqGSIb3DQEJARYPcmFmaUBndWVuZ2VsLmNoMB4X\n" + "DTE4MDIyNDE4NDQ1N1oXDTE5MDIyNDE4NDQ1N1owgZMxCzAJBgNVBAYTAkNIMRAw\n" + "DgYDVQQIDAdUaHVyZ2F1MRAwDgYDVQQHDAdLZWZpa29uMRgwFgYDVQQKDA9SYWZh\n" + "ZWwgT3N0ZXJ0YWcxDDAKBgNVBAsMA2RldjEYMBYGA1UEAwwPUmFmYWVsIE9zdGVy\n" + "dGFnMR4wHAYJKoZIhvcNAQkBFg9yYWZpQGd1ZW5nZWwuY2gwggEiMA0GCSqGSIb3\n" + "DQEBAQUAA4IBDwAwggEKAoIBAQDe9/4o6/YCQ7h3uuepDzJOGu7YmSFjJJ8hE6BH\n" + "SckqaNLaqHkSvKmTzPt+CG2ZDaHeH6WhCfUWf8VL8gwt4QCEAjsM8Zs82+BT1HRg\n" + "tkaCaBeugLVWreG34clHcBnJgzoCRHFS92WXm16EmLU3ZVCy5ySgrDF0yNfPPWkr\n" + "hDFEtqIZ11t2pLNcdUsVnmP+68FEEo0B5zriUcbXUzE9NZLOzyaTWyWr/iipmBxv\n" + "D9BSQVx1NP3q3SBkDvNQIagjTxJtSg3ZYm2uzxUkOfSNsIC4yk35ySUL7470WCkF\n" + "MQQW4ZCE+KmvlmE+FfD7XIAVOYb7k2uPmO44AclQGjdxMNfZAgMBAAGjUzBRMB0G\n" + "A1UdDgQWBBQnZHOL8Uz4l8XpNZ0x/n2QJpTYyzAfBgNVHSMEGDAWgBQnZHOL8Uz4\n" + "l8XpNZ0x/n2QJpTYyzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IB\n" + "AQCrNT5IwcDNWkdkvnGZzDIPqNvd5Sr/WQeRRCUJ8tM1wYRP+/beilekmaWl3mAl\n" + "0x5zGwUxBSgGv45q6j9FJu9rbwgk2x8/rVWycUCdGQJDzciGKUycE9bA4W8nV9dE\n" + "89nXXIo6aB2CC6+jiILTEHIiLoSIUeJTECe1tGh+fW4K7zdbVvmgxwEmP5oGwy13\n" + "uKpMYjUOaKZGgIjlN5+q+YCZIcwnC+iNma3/re3iNPyyRz5eX5/8h07R7EhL4bvr\n" + "ZDg7YsEg4AwLsuuIEz1W3ff+OQu6O4/Qe1PTc+/TDJgKd8wq5Nc1oOIMI6J8Ij21\n" + "3Pdg9DnfsOnW5/jb/3/ix9zA\n" + "-----END CERTIFICATE-----\n"; private static final long TEN_SECONDS_IN_MILLIS = 10 * 1000L; @Autowired private CertificateAuthorityInitializationService certificateAuthorityInitializationService; @Autowired private CertificateAuthorityService certificateAuthorityService; @Autowired private RevocationService revocationService; @Autowired private SecureStoreService secureStoreService; @Test(expected = CertificateAuthorityImportException.class) public void importPkcs12CertificateAuthorityNonBase64Encoded() { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword("bla"); importCertificateAuthorityDto.setPkcs12("bla"); certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); } @Test(expected = CertificateAuthorityImportException.class) public void importPkcs12CertificateAuthorityNonMimeBase64Encoding() { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword("bla"); final String s = Base64.getMimeEncoder().encodeToString("blablabla".getBytes()); importCertificateAuthorityDto.setPkcs12(s + "a"); certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); } @Test(expected = CertificateAuthorityImportException.class) public void importPkcs12CertificateAuthorityBase64EncodedGarbage() { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword("bla"); importCertificateAuthorityDto.setPkcs12(Base64.getEncoder().encodeToString("bla".getBytes())); certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); } @Test public void importPkcs12CertificateAuthorityBase64Encoded() throws IOException { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword("<PASSWORD>."); try (FileInputStream pkcs12File = new FileInputStream(TestConstants.PKCS12_ENCRYPTED_FILE_NAME)) { importCertificateAuthorityDto.setPkcs12(Base64.getEncoder().encodeToString(IOUtils.toByteArray (pkcs12File))); } certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); final Optional<Byte[]> optionalCaCert = secureStoreService.get(SECURE_STORE_CA_CERTIFICATE); assertThat(optionalCaCert.isPresent(), is(true)); final Optional<Byte[]> optionalCaKey = secureStoreService.get(SECURE_STORE_CA_PRIVATE_KEY); assertThat(optionalCaKey.isPresent(), is(true)); final String crlPemEncoded = revocationService.getCrlPemEncoded(); assertThat(crlPemEncoded, is(notNullValue())); final String certificate = certificateAuthorityService.getCertificate(); assertThat(certificate, is(EXPECTED_IMPORT_CERTIFICATE)); } @Test public void importPkcs12CertificateAuthorityBase64MimeEncoded() throws IOException { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword("<PASSWORD>."); try (FileInputStream pkcs12File = new FileInputStream(TestConstants.PKCS12_ENCRYPTED_FILE_NAME)) { importCertificateAuthorityDto.setPkcs12(Base64.getMimeEncoder().encodeToString(IOUtils.toByteArray (pkcs12File))); } certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); final Optional<Byte[]> optionalCaCert = secureStoreService.get(SECURE_STORE_CA_CERTIFICATE); assertThat(optionalCaCert.isPresent(), is(true)); final Optional<Byte[]> optionalCaKey = secureStoreService.get(SECURE_STORE_CA_PRIVATE_KEY); assertThat(optionalCaKey.isPresent(), is(true)); final String crlPemEncoded = revocationService.getCrlPemEncoded(); assertThat(crlPemEncoded, is(notNullValue())); final String certificate = certificateAuthorityService.getCertificate(); assertThat(certificate, is(EXPECTED_IMPORT_CERTIFICATE)); } @Test public void importPkcs12CertificateAuthorityEmptyPassword() throws IOException { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword(""); try (FileInputStream pkcs12File = new FileInputStream(TestConstants .PKCS12_ENCRYPTED_EMPTY_PASSWORD_FILE_NAME)) { importCertificateAuthorityDto.setPkcs12(Base64.getMimeEncoder().encodeToString(IOUtils.toByteArray (pkcs12File))); } certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); final Optional<Byte[]> optionalCaCert = secureStoreService.get(SECURE_STORE_CA_CERTIFICATE); assertThat(optionalCaCert.isPresent(), is(true)); final Optional<Byte[]> optionalCaKey = secureStoreService.get(SECURE_STORE_CA_PRIVATE_KEY); assertThat(optionalCaKey.isPresent(), is(true)); final String crlPemEncoded = revocationService.getCrlPemEncoded(); assertThat(crlPemEncoded, is(notNullValue())); final String certificate = certificateAuthorityService.getCertificate(); assertThat(certificate, is(EXPECTED_IMPORT_CERTIFICATE)); } @Test(expected = CertificateAuthorityImportException.class) public void importPkcs12CertificateAuthorityWrongPassword() throws IOException { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword("<PASSWORD>"); try (FileInputStream pkcs12File = new FileInputStream(TestConstants.PKCS12_ENCRYPTED_FILE_NAME)) { importCertificateAuthorityDto.setPkcs12(Base64.getMimeEncoder().encodeToString(IOUtils.toByteArray (pkcs12File))); } certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); } @Test(expected = CertificateAuthorityAlreadyInitializedException.class) public void importCaTwice() throws IOException { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword("<PASSWORD>."); try (FileInputStream pkcs12File = new FileInputStream(TestConstants.PKCS12_ENCRYPTED_FILE_NAME)) { importCertificateAuthorityDto.setPkcs12(Base64.getMimeEncoder().encodeToString(IOUtils.toByteArray (pkcs12File))); } certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); } @Test public void makeSelfSignedNameBuilder() { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = makeCreateSelfSignedCADto(); final SelfSignedCANameBuilder selfSignedCANameBuilder = certificateAuthorityInitializationService .makeSelfSignedNameBuilder (createSelfSignedCertificateAuthorityDto); final X500Name expected = expectedX500Name(); final X500Name actual = selfSignedCANameBuilder.toX500Name(); assertThat(actual, is(equalTo(expected))); } private X500Name expectedX500Name() { return new X500NameBuilder() .addRDN(RFC4519Style.c, "c") .addRDN(RFC4519Style.o, "o") .addRDN(RFC4519Style.cn, "cn") .addRDN(RFC4519Style.l, "l") .addRDN(RFC4519Style.st, "st") .addRDN(RFC4519Style.ou, "ou") .build(); } private CreateSelfSignedCertificateAuthorityDto makeCreateSelfSignedCADto() { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = new CreateSelfSignedCertificateAuthorityDto(); createSelfSignedCertificateAuthorityDto.setCommonName("cn"); createSelfSignedCertificateAuthorityDto.setCountry("c"); createSelfSignedCertificateAuthorityDto.setLocation("l"); createSelfSignedCertificateAuthorityDto.setOrganization("o"); createSelfSignedCertificateAuthorityDto.setOrganizationalUnit("ou"); createSelfSignedCertificateAuthorityDto.setState("st"); return createSelfSignedCertificateAuthorityDto; } @Test public void createSelfSignedCertificateAuthority() { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = makeCreateSelfSignedCADto(); createSelfSignedCertificateAuthorityDto.setValidDays(180); createSelfSignedCertificateAuthorityDto.setBits(1024); certificateAuthorityInitializationService.createSelfSignedCertificateAuthority (createSelfSignedCertificateAuthorityDto); final String certificate = certificateAuthorityService.getCertificate(); final ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(certificate.getBytes()); final PEMCertificateReader pemCertificateReader = new PEMCertificateReader(new InputStreamReader (certificateInputStream)); final Certificate actualCertificate = pemCertificateReader.certificate(); final X500Name subject = actualCertificate.getSubject(); final X500Name expectedX500Name = expectedX500Name(); assertThat(subject, is(equalTo(expectedX500Name))); final long actualValidity = actualCertificate.getValidTo().getTime() - actualCertificate.getValidFrom() .getTime(); final long expectedValidity = 180 * 24 * 60 * 60 * 1000L; assertThat(actualValidity, is(both(greaterThan(expectedValidity - TEN_SECONDS_IN_MILLIS)).and(lessThan (expectedValidity + TEN_SECONDS_IN_MILLIS)))); } @Test(expected = CertificateAuthorityAlreadyInitializedException.class) public void createSelfSignedCertificateAuthorityTwice() { final CreateSelfSignedCertificateAuthorityDto createSelfSignedCertificateAuthorityDto = makeCreateSelfSignedCADto(); createSelfSignedCertificateAuthorityDto.setValidDays(180); createSelfSignedCertificateAuthorityDto.setBits(1024); certificateAuthorityInitializationService.createSelfSignedCertificateAuthority (createSelfSignedCertificateAuthorityDto); certificateAuthorityInitializationService.createSelfSignedCertificateAuthority (createSelfSignedCertificateAuthorityDto); } @TestConfiguration static class TestNonBlockingSecureRandomProviderConfiguration { @Bean public SecureRandomProvider secureRandomProvider() { return new SelfSignedCertificateAuthorityTest.TestNonBlockingSecureRandomProvider(); } } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.core.CertificateSigningRequest; import ch.zhaw.ba.anath.pki.core.PEMCertificateSigningRequestReader; import ch.zhaw.ba.anath.pki.core.TestConstants; import ch.zhaw.ba.anath.pki.entities.UseEntity; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityNotInitializedException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.io.FileInputStream; import java.io.InputStreamReader; /** * {@link SigningService} caches the CA. Thus we simply create a dedicated test. * * @author <NAME> */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @ActiveProfiles("tests") @TestPropertySource(properties = { "anath.secret-key=<KEY>" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @Transactional(transactionManager = "pkiTransactionManager") public class SigningServiceUninitializedCaCertificateIT extends CertificateAuthorityInitializer { @PersistenceContext(unitName = "pki") private EntityManager entityManager; @Autowired private SigningService signingService; @Test(expected = CertificateAuthorityNotInitializedException.class) public void signWithUninitializedCACertificate() throws Exception { initializeCaPrivateKey(); try (InputStreamReader csr = new InputStreamReader(new FileInputStream(TestConstants.CLIENT_CSR_FILE_NAME))) { final PEMCertificateSigningRequestReader pemCertificateSigningRequestReader = new PEMCertificateSigningRequestReader(csr); final CertificateSigningRequest certificateSigningRequest = pemCertificateSigningRequestReader .certificationRequest(); signingService.tentativelySignCertificate(certificateSigningRequest, "test id", UseEntity.DEFAULT_USE); } } }<file_sep>[![Build Status](https://travis-ci.org/AnathPKI/anath-server.svg?branch=master)](https://travis-ci.org/AnathPKI/anath-server) [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=ch.zhaw.ba%3Aanath-server&metric=alert_status)](https://sonarcloud.io/dashboard?id=ch.zhaw.ba%3Aanath-server) [![Latest Release](https://github-basic-badges.herokuapp.com/release/AnathPKI/anath-server.svg)](https://github.com/AnathPKI/anath-server/releases/latest) Bsc Thesis Reference Implementation === Anath is the BSc Thesis reference implementation of a self-service PKI. Anath features: * Import of Root CA * Creation of self-signed CA certificate * User management * Configuration templates * Certificate creation and revocation Images --- JAR files can be found on the [GitHub Releases](https://github.com/AnathPKI/anath-server/releases) page. Alternatively, the [Demo repository](https://github.com/AnathPKI/demo) provides Docker Compose files to run Docker images. Requirements --- * Java 1.8 * PostgreSQL 9 or later * Maven (build) * Redis (optional) * Docker (optional) Build Docker Image --- When docker is installed and running, a docker image can be built locally: mvn clean package docker build -t anathpki/server:test . Start Server in Staging Mode Without Redis --- This mode will sign certificates _without_ confirmation. Staging mode expects a running PostgreSQL instance listening on `localhost:5432` with two empty databases `anath` and `anathusers`, and a user `anath` with password `<PASSWORD>` having full access to both databases. 1. Checkout sources 1. Run mvn -Dspring.profiles.active=staging spring-boot:run Start Server in Staging Mode With Redis --- This mode will sign certificates _with_ confirmation. Staging mode expects a running PostgreSQL instance listening on `localhost:5432` with two empty databases `anath` and `anathusers`, and a user `anath` with password `<PASSWORD>` having full access to both databases. This mode also expects a local Redis instance to be running listening on `localhost:6379`. 1. Checkout sources 1. Run mvn -Dspring.profiles.active=staging,confirm spring-boot:run <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.authentication.users; import ch.zhaw.ba.anath.authentication.AnathSecurityHelper; import ch.zhaw.ba.anath.users.entities.UserEntity; import ch.zhaw.ba.anath.users.repositories.UserRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.HashSet; import java.util.Optional; import java.util.Set; /** * @author <NAME> */ @Component @Transactional(transactionManager = "userTransactionManager") @Slf4j public class UserPermissionEvaluator implements PermissionEvaluator { public static final String TARGET_TYPE = "user"; private final UserRepository userRepository; private final Set<String> userPermissions; public UserPermissionEvaluator(UserRepository userRepository) { this.userRepository = userRepository; userPermissions = new HashSet<>(); userPermissions.add("changePassword"); userPermissions.add("get"); } @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { throw new UnsupportedOperationException("hasPermission(Authentication,Object,Object) unsupported"); } @Override public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { if (targetType.equals(TARGET_TYPE)) { log.info("Start evaluating permission for user object"); return handleUserObject(authentication, targetId, permission); } log.info("Unknown target received: {}. Denying", targetType); return false; } private boolean handleUserObject(Authentication authentication, Serializable targetId, Object permission) { if (!(targetId instanceof Long)) { log.error("Cannot evaluate permission for user object, target id is not of type Long. Denying"); return false; } if (!(permission instanceof String)) { log.error("Cannot evaluate permission for user object, permission is not of type String. Denying"); return false; } Long realId = (Long) targetId; String realPermission = (String) permission; if (!userPermissions.contains(realPermission)) { log.info("User permission '{}' unknown. Denying", realPermission); return false; } final Optional<UserEntity> optionalUserEntity = userRepository.findOne(realId); if (!optionalUserEntity.isPresent()) { log.info("Cannot evaluate permission for non-existing user with id {}. Denying", realId); return false; } final UserEntity userEntity = optionalUserEntity.get(); final String username = AnathSecurityHelper.getUsername(authentication); boolean result = userEntity.getEmail().equals(username); log.info("User '{}' has {} to user object '{}'. {}", username, result ? "access" : "no access", userEntity .getEmail(), result ? "Allowing" : "Denying"); return result; } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.config.properties.AnathProperties; import ch.zhaw.ba.anath.pki.entities.SecureEntity; import ch.zhaw.ba.anath.pki.exceptions.SecureStoreException; import ch.zhaw.ba.anath.pki.repositories.SecureRepository; import lombok.Value; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.Charset; import java.security.*; import java.util.Optional; /** * Service providing abstraction to the {@link SecureRepository}. It takes care of encrypting and decrypting data * upon store or retrieval. The password provided is hashed using SHA256, to provide the maximum key size for AES. * * @author <NAME> */ @Slf4j @Service @Transactional(transactionManager = "pkiTransactionManager") public class SecureStoreService { private static final String CIPHER = "AES/CBC/PKCS5Padding"; private static final String SECURITY_PROVIDER = "BC"; private static final String DIGEST_ALGORITHM = "SHA256"; static { Security.insertProviderAt(new BouncyCastleProvider(), 1); } private final SecureRepository secureRepository; private final AnathProperties anathProperties; public SecureStoreService(SecureRepository secureRepository, AnathProperties anathProperties) { this.secureRepository = secureRepository; this.anathProperties = anathProperties; } /** * Store data encrypted in the {@link SecureRepository}. It assumes the data provided to be uncrypted. * * @param key the key to store the data under. If the key exists, its value will be replaced. * @param data unencrypted data to be stored. */ public void put(String key, byte[] data) { final Optional<SecureEntity> secureEntityOptional = secureRepository.findOneByKey(key); final SecureEntity secureEntity = secureEntityOptional.orElseGet(() -> { final SecureEntity newSecureEntity = new SecureEntity(); newSecureEntity.setKey(key); return newSecureEntity; }); final EncryptedData encryptedData = encryptData(data); secureEntity.setData(encryptedData.data); secureEntity.setIV(encryptedData.getIv()); secureEntity.setAlgorithm(CIPHER); secureRepository.save(secureEntity); } /** * Encrypt the data. It creates a new IV. * * @param data data to be encrypted. * * @return a {@link EncryptedData} instance. The {@link EncryptedData#data} field contains the encrypted data. * The {@link EncryptedData#iv} field contains the IV. */ private EncryptedData encryptData(byte[] data) { final Cipher cipher = instantiateCipher(); final SecretKeySpec secretKeySpec = initializeSecretKeySpec(CIPHER); final IvParameterSpec ivParameterSpec = initializeRandomIV(cipher.getBlockSize()); initializeCipherForEncryption(cipher, secretKeySpec, ivParameterSpec); final byte[] encryptedData = encryptWithCipher(cipher, data); return new EncryptedData(encryptedData, cipher.getIV()); } private byte[] encryptWithCipher(Cipher cipher, byte[] data) { try { return cipher.doFinal(data); } catch (IllegalBlockSizeException e) { return wrapIllegalBlockSizeException(e); } catch (BadPaddingException e) { return wrapBadPaddingException(e); } } private byte[] wrapBadPaddingException(BadPaddingException e) { log.error("Bad padding while encrypting/decrypting data for secure store: {}", e.getMessage()); throw new SecureStoreException("Bad padding", e); } private byte[] wrapIllegalBlockSizeException(IllegalBlockSizeException e) { log.error("Illegal block size while encrypting data for secure store: {}", e.getMessage()); throw new SecureStoreException("Illegal block size", e); } private void initializeCipherForEncryption(Cipher cipher, SecretKeySpec secretKeySpec, IvParameterSpec ivParameterSpec) { try { cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); } catch (InvalidKeyException e) { wrapInvalidKeyException(cipher, e); } catch (InvalidAlgorithmParameterException e) { wrapInvalidAlgorithmParameterException(cipher, e); } } private void initializeCipherForDecryption(Cipher cipher, SecretKeySpec secretKeySpec, IvParameterSpec ivParameterSpec) { try { cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); } catch (InvalidKeyException e) { wrapInvalidKeyException(cipher, e); } catch (InvalidAlgorithmParameterException e) { wrapInvalidAlgorithmParameterException(cipher, e); } } private void wrapInvalidAlgorithmParameterException(Cipher cipher, InvalidAlgorithmParameterException e) { log.error("Invalid algorithm parameters for cipher '{}': {}", cipher, e.getMessage()); throw new SecureStoreException("Invalid algorithm parameters", e); } private void wrapInvalidKeyException(Cipher cipher, InvalidKeyException e) { log.error("Invalid key for cipher '{}': {}", cipher, e.getMessage()); throw new SecureStoreException("Invalid key", e); } private SecretKeySpec initializeSecretKeySpec(String cipher) { byte[] hashedPassword = <PASSWORD>Password(); return new SecretKeySpec(hashedPassword, cipher); } private byte[] hashPassword() { try { final MessageDigest messageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); messageDigest.update(anathProperties.getSecretKey().getBytes(Charset.defaultCharset())); return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { wrapNoSuchAlgorithmExceptionAndThrow(DIGEST_ALGORITHM, e); // Won't be reached return new byte[0]; } } private IvParameterSpec initializeRandomIV(int blockSize) { try { final SecureRandom strongRNG = SecureRandom.getInstanceStrong(); final byte[] randomIv = new byte[blockSize]; strongRNG.nextBytes(randomIv); return new IvParameterSpec(randomIv); } catch (NoSuchAlgorithmException e) { log.error("Unable to initialize strong RNG: {}", e.getMessage()); throw new SecureStoreException("Unable to initialize strong RNG", e); } } private IvParameterSpec initializeIV(byte[] iv) { return new IvParameterSpec(iv); } /** * Instantiate default cipher using {@value #CIPHER} and provider {@value #SECURITY_PROVIDER}, * * @return {@link Cipher} instance. */ private Cipher instantiateCipher() { return instantiateCipher(CIPHER, SECURITY_PROVIDER); } /** * Instantiate cipher. * * @param cipherSpec cipher specfification * @param provider provider * * @return {@link Cipher} instance. */ private Cipher instantiateCipher(String cipherSpec, String provider) { try { return Cipher.getInstance(cipherSpec, provider); } catch (NoSuchAlgorithmException e) { return wrapNoSuchAlgorithmExceptionAndThrow(cipherSpec, e); } catch (NoSuchProviderException e) { return wrapNoSuchProviderExceptionAndThrow(provider,e); } catch (NoSuchPaddingException e) { log.error("Unsupported padding in cipher '%s': ", cipherSpec, e.getMessage()); throw new SecureStoreException("Unsupported padding", e); } } private Cipher wrapNoSuchProviderExceptionAndThrow(String provider, NoSuchProviderException e) { log.error("Security provider '{}' not found: {}", provider, e.getMessage()); throw new SecureStoreException(String.format("Security provider not found '%s'", provider), e); } private Cipher wrapNoSuchAlgorithmExceptionAndThrow(String cipher, NoSuchAlgorithmException e) { log.error("Cannot initialize cipher '{}': {}", cipher, e.getMessage()); throw new SecureStoreException(String.format("Unable to initialize cipher '%s'", cipher), e); } /** * Retrieve data from {@link SecureRepository}. The data will be decrypted before returned. * * @param key the key to lookup the data. * * @return non-empty {@link Optional} if the key has been found, otherwise empty {@link Optional}. */ public Optional<Byte[]> get(String key) { final Optional<SecureEntity> secureEntityOptional = secureRepository.findOneByKey(key); if (!secureEntityOptional.isPresent()) { return Optional.empty(); } final SecureEntity secureEntity = secureEntityOptional.get(); final Cipher cipher = instantiateCipher(secureEntity.getAlgorithm(), SECURITY_PROVIDER); final SecretKeySpec secretKeySpec = initializeSecretKeySpec(secureEntity.getAlgorithm()); final IvParameterSpec ivParameterSpec = initializeIV(secureEntity.getIV()); initializeCipherForDecryption(cipher, secretKeySpec, ivParameterSpec); return Optional.of(ArrayUtils.toObject(decryptData(cipher, secureEntity.getData()))); } private byte[] decryptData(Cipher cipher, byte[] data) { try { return cipher.doFinal(data); } catch (BadPaddingException e) { return wrapBadPaddingException(e); } catch (IllegalBlockSizeException e) { return wrapIllegalBlockSizeException(e); } } @Value private class EncryptedData { private byte[] data; private byte[] iv; } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.nio.charset.Charset; /** * Adapter for {@link Argon2PasswordEncoder}. * * @author <NAME> */ @Component("passwordEncoder") public class Argon2PasswordEncoderAdapter implements PasswordEncoder { private final Argon2PasswordEncoder argon2PasswordEncoder; private final Charset utf8Charset; public Argon2PasswordEncoderAdapter(Argon2PasswordEncoder argon2PasswordEncoder) { this.argon2PasswordEncoder = argon2PasswordEncoder; this.utf8Charset = Charset.forName("UTF-8"); } @Override public String encode(CharSequence rawPassword) { return argon2PasswordEncoder.hash(rawPassword.toString().toCharArray(), utf8Charset); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return argon2PasswordEncoder.verify(encodedPassword, rawPassword.toString().toCharArray(), utf8Charset); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.entities.CertificateEntity; import ch.zhaw.ba.anath.pki.exceptions.CertificateAlreadyExistsException; import ch.zhaw.ba.anath.pki.exceptions.CertificateNotFoundException; import ch.zhaw.ba.anath.pki.repositories.CertificateRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.validation.ConstraintViolationException; import java.math.BigInteger; import java.util.Optional; /** * @author <NAME> */ @Service @Profile("!confirm") @Slf4j @Transactional(transactionManager = "pkiTransactionManager") public class ImmediateCertificatePersistence implements ConfirmableCertificatePersistenceLayer { private final CertificateRepository certificateRepository; public ImmediateCertificatePersistence(CertificateRepository certificateRepository) { this.certificateRepository = certificateRepository; log.info("Immediate Certificate Persistence Layer initialized"); } @Override public String store(CertificateEntity certificateEntity) { try { certificateRepository.save(certificateEntity); log.info("Stored signed certificate '{}'", certificateEntity.getSubject()); return certificateEntity.getSerial().toString(); } catch (ConstraintViolationException e) { final String subjectString = certificateEntity.getSubject(); log.error("Error persisting certificate '{}' with serial '{}': {}", subjectString, certificateEntity.getSerial().toString(), e.getMessage()); throw new CertificateAlreadyExistsException(String.format("Certificate already exists: %s", subjectString)); } } @Override public CertificateEntity confirm(String token, String userId) { BigInteger serial; try { serial = new BigInteger(token); } catch (NumberFormatException e) { log.error("Cannot parse '{}' as BigInteger: {}", token, e.getMessage()); throw new CertificateNotFoundException("Certificate not found"); } final Optional<CertificateEntity> optionalCertificateEntity = certificateRepository.findOneBySerial(serial); return optionalCertificateEntity.orElseThrow(() -> { log.error("Cannot find certificate with serial {}", serial.toString()); return new CertificateNotFoundException("Certificate not found"); }); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.core.CertificateAuthority; import ch.zhaw.ba.anath.pki.core.TestConstants; import ch.zhaw.ba.anath.pki.dto.ImportCertificateAuthorityDto; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityNotInitializedException; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.io.FileInputStream; import java.io.IOException; import java.util.Base64; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; /** * @author <NAME> */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @ActiveProfiles("tests") @TestPropertySource(properties = { "anath.secret-key=<KEY>" }) @Transactional(transactionManager = "pkiTransactionManager") public class CertificateAuthorityServiceIT { private static final String EXPECTED_IMPORT_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n" + "MIID/jCCAuagAwIBAgIJAPQj6jMYDszkMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\n" + "VQQGEwJDSDEQMA4GA1UECAwHVGh1cmdhdTEQMA4GA1UEBwwHS2VmaWtvbjEYMBYG\n" + "A1UECgwPUmFmYWVsIE9zdGVydGFnMQwwCgYDVQQLDANkZXYxGDAWBgNVBAMMD1Jh\n" + "ZmFlbCBPc3RlcnRhZzEeMBwGCSqGSIb3DQEJARYPcmFmaUBndWVuZ2VsLmNoMB4X\n" + "DTE4MDIyNDE4NDQ1N1oXDTE5MDIyNDE4NDQ1N1owgZMxCzAJBgNVBAYTAkNIMRAw\n" + "DgYDVQQIDAdUaHVyZ2F1MRAwDgYDVQQHDAdLZWZpa29uMRgwFgYDVQQKDA9SYWZh\n" + "ZWwgT3N0ZXJ0YWcxDDAKBgNVBAsMA2RldjEYMBYGA1UEAwwPUmFmYWVsIE9zdGVy\n" + "dGFnMR4wHAYJKoZIhvcNAQkBFg9yYWZpQGd1ZW5nZWwuY2gwggEiMA0GCSqGSIb3\n" + "DQEBAQUAA4IBDwAwggEKAoIBAQDe9/4o6/YCQ7h3uuepDzJOGu7YmSFjJJ8hE6BH\n" + "SckqaNLaqHkSvKmTzPt+CG2ZDaHeH6WhCfUWf8VL8gwt4QCEAjsM8Zs82+BT1HRg\n" + "tkaCaBeugLVWreG34clHcBnJgzoCRHFS92WXm16EmLU3ZVCy5ySgrDF0yNfPPWkr\n" + "hDFEtqIZ11t2pLNcdUsVnmP+68FEEo0B5zriUcbXUzE9NZLOzyaTWyWr/iipmBxv\n" + "D9BSQVx1NP3q3SBkDvNQIagjTxJtSg3ZYm2uzxUkOfSNsIC4yk35ySUL7470WCkF\n" + "MQQW4ZCE+KmvlmE+FfD7XIAVOYb7k2uPmO44AclQGjdxMNfZAgMBAAGjUzBRMB0G\n" + "A1UdDgQWBBQnZHOL8Uz4l8XpNZ0x/n2QJpTYyzAfBgNVHSMEGDAWgBQnZHOL8Uz4\n" + "l8XpNZ0x/n2QJpTYyzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IB\n" + "AQCrNT5IwcDNWkdkvnGZzDIPqNvd5Sr/WQeRRCUJ8tM1wYRP+/beilekmaWl3mAl\n" + "0x5zGwUxBSgGv45q6j9FJu9rbwgk2x8/rVWycUCdGQJDzciGKUycE9bA4W8nV9dE\n" + "89nXXIo6aB2CC6+jiILTEHIiLoSIUeJTECe1tGh+fW4K7zdbVvmgxwEmP5oGwy13\n" + "uKpMYjUOaKZGgIjlN5+q+YCZIcwnC+iNma3/re3iNPyyRz5eX5/8h07R7EhL4bvr\n" + "ZDg7YsEg4AwLsuuIEz1W3ff+OQu6O4/Qe1PTc+/TDJgKd8wq5Nc1oOIMI6J8Ij21\n" + "3Pdg9DnfsOnW5/jb/3/ix9zA\n" + "-----END CERTIFICATE-----\n"; @Autowired private CertificateAuthorityService certificateAuthorityService; @Autowired private CertificateAuthorityInitializationService certificateAuthorityInitializationService; @Autowired private SecureStoreService secureStoreService; private void importTestCertificateAuthority() throws IOException { final ImportCertificateAuthorityDto importCertificateAuthorityDto = new ImportCertificateAuthorityDto(); importCertificateAuthorityDto.setPassword(""); try (FileInputStream pkcs12File = new FileInputStream(TestConstants .PKCS12_ENCRYPTED_EMPTY_PASSWORD_FILE_NAME)) { importCertificateAuthorityDto.setPkcs12(Base64.getMimeEncoder().encodeToString(IOUtils.toByteArray (pkcs12File))); } certificateAuthorityInitializationService.importPkcs12CertificateAuthority(importCertificateAuthorityDto); } @Test(expected = CertificateAuthorityNotInitializedException.class) public void getCertificateNonExistingCa() { certificateAuthorityService.getCertificate(); } @Test(expected = CertificateAuthorityNotInitializedException.class) public void getCertificateAuthorityNonExistingCa() { certificateAuthorityService.getCertificateAuthority(); } @Test public void getCertificate() throws IOException { importTestCertificateAuthority(); final String pemEncodedCertificate = certificateAuthorityService.getCertificate(); assertThat(pemEncodedCertificate, is(EXPECTED_IMPORT_CERTIFICATE)); } @Test public void getCertificateAuthority() throws IOException { importTestCertificateAuthority(); final CertificateAuthority certificateAuthority = certificateAuthorityService.getCertificateAuthority(); assertThat(certificateAuthority.getCertificate(), is(not(nullValue()))); assertThat(certificateAuthority.getPrivateKey(), is(not(nullValue()))); } }<file_sep>INSERT INTO certificate_uses (certificate_use, config) VALUES ('plain', null);<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.authentication; import ch.zhaw.ba.anath.config.properties.AnathProperties; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; import org.springframework.stereotype.Component; import java.nio.charset.Charset; /** * Argon password encoder. Implementation taken from * <a href="https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet">OWASP Password Storage Cheat Sheet</a> * (2018-03-27). * * @author Rafael Ostertag */ @Component public class Argon2PasswordEncoder { private final AnathProperties.Authentication.Argon2 argon2Properies; public Argon2PasswordEncoder(AnathProperties anathProperties) { this.argon2Properies = anathProperties.getAuthentication().getArgon2(); } /** * Compute a hash of a password. * Password provided is wiped from the memory at the end of this method * * @param password Password to hash * @param charset Charset of the password * * @return the hash in format "$argon2i$v=19$m=128000,t=3, * p=4$sfSe5MewORVlg8cDtxOTbg$uqWx4mZvLI092oJ8ZwAjAWU0rrBSDQkOezxAuvrE5dM" */ public String hash(char[] password, Charset charset) { String hash; Argon2 argon2Hasher = null; try { argon2Hasher = createInstance(); int iterationsCount = argon2Properies.getIterations(); int memoryAmountToUse = argon2Properies.getMemory(); int threadToUse = argon2Properies.getParallelism(); //Compute and return the hash hash = argon2Hasher.hash(iterationsCount, memoryAmountToUse, threadToUse, password, charset); } finally { //Clean the password from the memory if (argon2Hasher != null) { argon2Hasher.wipeArray(password); } } return hash; } /** * Verifies a password against a hash * Password provided is wiped from the memory at the end of this method * * @param hash Hash to verify * @param password Password to which hash must be verified against * @param charset Charset of the password * * @return True if the password matches the hash, false otherwise. */ public boolean verify(String hash, char[] password, Charset charset) { Argon2 argon2Hasher = null; boolean isMatching; try { // Create instance argon2Hasher = createInstance(); //Apply the verification (hash computation options are included in the hash itself) isMatching = argon2Hasher.verify(hash, password, charset); } finally { //Clean the password from the memory if (argon2Hasher != null) { argon2Hasher.wipeArray(password); } } return isMatching; } /** * Create and configure an Argon2 instance * * @return The Argon2 instance */ private Argon2 createInstance() { // Create and return the instance return Argon2Factory.create(Argon2Factory.Argon2Types.ARGON2i); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.authentication.spring; import ch.zhaw.ba.anath.authentication.AnathSecurityHelper; import ch.zhaw.ba.anath.authentication.LoginDto; import ch.zhaw.ba.anath.config.properties.AnathProperties; import ch.zhaw.ba.anath.exceptions.AnathAuthenticationException; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Date; /** * Spring security authentication filter. Takes care of issuing JWT. * * @author <NAME> */ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { public static final int SECONDS_PER_MINUTE = 60; public static final long MILLISECONDS_PER_SECOND = 1000L; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final AuthenticationManager authenticationManager; private final AnathProperties.Authentication.JWT jwtProperties; public JWTAuthenticationFilter(AuthenticationManager authenticationManager, AnathProperties anathProperties) { this.authenticationManager = authenticationManager; this.jwtProperties = anathProperties.getAuthentication().getJwt(); this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login/jwt")); } @Override public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) { try { final LoginDto credentials = OBJECT_MAPPER.readValue(req.getInputStream(), LoginDto.class); return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( credentials.getUsername(), credentials.getPassword(), new ArrayList<>()) ); } catch (IOException e) { throw new AnathAuthenticationException("Cannot read document", e); } } @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) { final long expirationTime = convertMinutesToMillis(jwtProperties.getExpirationTime()); final byte[] secret = AnathSecurityHelper.getJwtSecretAsByteArrayOrThrow(jwtProperties); String token = Jwts.builder() .setSubject(((User) auth.getPrincipal()).getUsername()) .setExpiration(new Date(System.currentTimeMillis() + expirationTime)) .signWith(SignatureAlgorithm.HS512, secret) .compact(); res.addHeader(JWTConstants.JWT_HEADER, JWTConstants.TOKEN_PREFIX + token); } private long convertMinutesToMillis(int expirationTime) { return expirationTime * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND; } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.TestHelper; import ch.zhaw.ba.anath.pki.entities.CertificateEntity; import ch.zhaw.ba.anath.pki.entities.CertificateStatus; import ch.zhaw.ba.anath.pki.entities.UseEntity; import ch.zhaw.ba.anath.pki.exceptions.CertificateAlreadyExistsException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.math.BigInteger; /** * @author <NAME> */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @ActiveProfiles("tests") @Transactional(transactionManager = "pkiTransactionManager") public class CertificateUniquenessServiceIT { @Autowired private CertificateUniquenessService certificateUniquenessService; @PersistenceContext(unitName = "pki") private EntityManager entityManager; @Test(expected = CertificateAlreadyExistsException.class) public void nonUniqueCertificate() { final CertificateEntity certificateEntity = makeValidCertificate(); entityManager.persist(certificateEntity); entityManager.flush(); entityManager.clear(); certificateUniquenessService.testCertificateUniquenessInCertificateRepositoryOrThrow("subject"); } @Test public void uniqueCertificateDueToStatus() { final CertificateEntity certificateEntity = makeValidCertificate(); certificateEntity.setStatus(CertificateStatus.REVOKED); entityManager.persist(certificateEntity); entityManager.flush(); entityManager.clear(); certificateUniquenessService.testCertificateUniquenessInCertificateRepositoryOrThrow("subject"); // Not throwing an exception is the test } @Test public void uniqueCertificateDueToValidity() { final CertificateEntity certificateEntity = makeValidCertificate(); certificateEntity.setNotValidBefore(TestHelper.timeEvenMoreInPast()); certificateEntity.setNotValidAfter(TestHelper.timeInPast()); entityManager.persist(certificateEntity); entityManager.flush(); entityManager.clear(); certificateUniquenessService.testCertificateUniquenessInCertificateRepositoryOrThrow("subject"); // Not throwing an exception is the test } @Test public void uniqueCertificateDueToUniqueSubject() { final CertificateEntity certificateEntity = makeValidCertificate(); certificateEntity.setSubject("another subject"); entityManager.persist(certificateEntity); entityManager.flush(); entityManager.clear(); certificateUniquenessService.testCertificateUniquenessInCertificateRepositoryOrThrow("subject"); // Not throwing an exception is the test } public CertificateEntity makeValidCertificate() { final CertificateEntity certificateEntity = new CertificateEntity(); certificateEntity.setNotValidBefore(TestHelper.timeEvenMoreInPast()); certificateEntity.setNotValidAfter(TestHelper.timeEvenFurtherInFuture()); certificateEntity.setSubject("subject"); certificateEntity.setX509PEMCertificate("cert".getBytes()); certificateEntity.setStatus(CertificateStatus.VALID); certificateEntity.setUserId("userid"); certificateEntity.setSerial(BigInteger.TEN); final UseEntity useEntity = new UseEntity(); useEntity.setUse("plain"); certificateEntity.setUse(useEntity); return certificateEntity; } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.config.properties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author <NAME> */ @Component @ConfigurationProperties(AnathProperties.CONFIGURATION_PREFIX) @Data public class AnathProperties { public static final String CONFIGURATION_PREFIX = "anath"; /** * The secret key used to encrypt data in the {@link ch.zhaw.ba.anath.pki.services.SecureStoreService}. */ private String secretKey; /** * Validity of certificates in days. */ private int certificateValidity = 180; /** * Validity of CRL in days */ private int crlValidity = 30; private Authentication authentication = new Authentication(); private Confirmation confirmation = new Confirmation(); @Data public static class Authentication { private JWT jwt = new JWT(); private Argon2 argon2 = new Argon2(); @Data public static class JWT { /** * The JWT Secret. */ private String secret; /** * Expiration time in minutes. */ private int expirationTime = 60; } /** * Configuration taken from https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet (April 2018) * * <pre> * Configuration to define Argon2 options * See https://github.com/P-H-C/phc-winner-argon2#command-line-utility * See https://github.com/phxql/argon2-jvm/blob/master/src/main/java/de/mkammerer/argon2/Argon2.java * See https://github.com/P-H-C/phc-winner-argon2/issues/59 * </pre> */ @Data public static class Argon2 { /** * Configuration taken from https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet (April 2018) * * <pre> * Number of iterations, here adapted to take at least 2 seconds * Tested on the following environments: * ENV NUMBER 1: LAPTOP - 15 Iterations is enough to reach 2 seconds processing time * CPU: Intel Core i7-2670QM 2.20 GHz with 8 logical processors and 4 cores * RAM: 24GB but no customization on JVM (Java8 32 bits) * OS: Windows 10 Pro 64 bits * ENV NUMBER 2: TRAVIS CI LINUX VM - 15 Iterations is NOT enough to reach 2 seconds processing * time (processing time take 1 second) * See details on https://docs.travis-ci * .com/user/reference/overview/#Virtualisation-Environment-vs-Operating-System * "Ubuntu Precise" and "Ubuntu Trusty" using infrastructure "Virtual machine on GCE" were used * (GCE = Google Compute Engine) * </pre> */ private int iterations = 40; /** * Configuration taken from https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet (April 2018) * * <pre> * The memory usage of 2^N KiB, here set to recommended value from Issue n°9 of PHC project (128 MB) * (April 2018) * </pre> */ private int memory = 128000; /** * Configuration taken from https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet (April 2018) * * <pre> * Parallelism to N threads here set to recommended value from Issue n°9 of PHC project * </pre> */ private int parallelism = 4; } } @Data public static class Confirmation { /** * Token validity in minutes */ private int tokenValidity = 60; private String mailServer = "localhost"; private int mailPort = 25; private String sender = "<EMAIL>"; } } <file_sep>1.1.0 === * Prefix of Spring properties is `anath` instead of `ch.zhaw.ba.anath`. * Use Spring Boot 1.5.13.RELEASE. 1.0.6 === * Send correct `Content-Type` when clients retrieve PEM encoded certificates and CRL. * Send `Content-Disposition` header when clients retrieve PEM encoded certificates and CRL. 1.0.5 === * Use proper Ant path matcher for `/public` allowing to retrieve all files and subdirectories. 1.0.4 === * Make initial admin creation stand out in log. 1.0.3 === * Changed the default sender address to `<EMAIL>` for confirmation mails. * Respect `spring.redis.*` properties. * Respect `ch.zhaw.ba.anath.confirmation.mail-port` property. 1.0.2 === * Use Spring Boot 1.5.12.RELEASE. 1.0.1 === * Allow unauthenticated access to `/public/**`. 1.0.0 === * Initial release.<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.core; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x500.style.RFC4519Style; import java.math.BigInteger; /** * @author <NAME> */ public final class TestConstants { public static final String PKCS12_ENCRYPTED_FILE_NAME = "src/test/resources/ca_encrypted.pkcs12"; public static final String PKCS12_ENCRYPTED_EMPTY_PASSWORD_FILE_NAME = "src/test/resources/ca_encrypted_empty_password.pkcs12"; public static final String CA_KEY_FILE_NAME = "src/test/resources/cakey.pem"; public static final String CA_CERT_FILE_NAME = "src/test/resources/cacert.pem"; public static final String CLIENT_CSR_FILE_NAME = "src/test/resources/client.csr"; public static final String CLIENT_INVALID_CSR_FILE_NAME = "src/test/resources/client_invalid.csr"; public static final String CLIENT_CSR_NON_MATCHING_ORG_FILE_NAME = "src/test/resources/client_non_matching_org.csr"; // The content of cacert.pem with a random line removed public static final String INVALID_CA_CERT = "-----BEGIN CERTIFICATE-----\n" + "<KEY>n" + "VQQGEwJDSDEQMA4GA1UECAwHVGh1cmdhdTEQMA4GA1UEBwwHS2VmaWtvbjEYMBYG\n" + "A1UECgwPUmFmYWVsIE9zdGVydGFnMQwwCgYDVQQLDANkZXYxGDAWBgNVBAMMD1Jh\n" + "ZmFlbCBPc3RlcnRhZzEeMBwGCSqGSIb3DQEJARYPcmFmaUBndWVuZ2VsLmNoMB4X\n" + "DTE4MDIyNDE4NDQ1N1oXDTE5MDIyNDE4NDQ1N1owgZMxCzAJBgNVBAYTAkNIMRAw\n" + "DgYDVQQIDAdUaHVyZ2F1MRAwDgYDVQQHDAdLZWZpa29uMRgwFgYDVQQKDA9SYWZh\n" + "ZWwgT3N0ZXJ0YWcxDDAKBgNVBAsMA2RldjEYMBYGA1UEAwwPUmFmYWVsIE9zdGVy\n" + "DQEBAQUAA4IBDwAwggEKAoIBAQDe9/4o6/YCQ7h3uuepDzJOGu7YmSFjJJ8hE6BH\n" + "SckqaNLaqHkSvKmTzPt+CG2ZDaHeH6WhCfUWf8VL8gwt4QCEAjsM8Zs82+BT1HRg\n" + "tkaCaBeugLVWreG34clHcBnJgzoCRHFS92WXm16EmLU3ZVCy5ySgrDF0yNfPPWkr\n" + "hDFEtqIZ11t2pLNcdUsVnmP+68FEEo0B5zriUcbXUzE9NZLOzyaTWyWr/iipmBxv\n" + "D9BSQVx1NP3q3SBkDvNQIagjTxJtSg3ZYm2uzxUkOfSNsIC4yk35ySUL7470WCkF\n" + "MQQW4ZCE+KmvlmE+FfD7XIAVOYb7k2uPmO44AclQGjdxMNfZAgMBAAGjUzBRMB0G\n" + "A1UdDgQWBBQnZHOL8Uz4l8XpNZ0x/n2QJpTYyzAfBgNVHSMEGDAWgBQnZHOL8Uz4\n" + "l8XpNZ0x/n2QJpTYyzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IB\n" + "AQCrNT5IwcDNWkdkvnGZzDIPqNvd5Sr/WQeRRCUJ8tM1wYRP+/beilekmaWl3mAl\n" + "0x5zGwUxBSgGv45q6j9FJu9rbwgk2x8/rVWycUCdGQJDzciGKUycE9bA4W8nV9dE\n" + "89nXXIo6aB2CC6+jiILTEHIiLoSIUeJTECe1tGh+fW4K7zdbVvmgxwEmP5oGwy13\n" + "uKpMYjUOaKZGgIjlN5+q+YCZIcwnC+iNma3/re3iNPyyRz5eX5/8h07R7EhL4bvr\n" + "ZDg7YsEg4AwLsuuIEz1W3ff+OQu6O4/Qe1PTc+/TDJgKd8wq5Nc1oOIMI6J8Ij21\n" + "3Pdg9DnfsOnW5/jb/3/ix9zA\n" + "-----END CERTIFICATE-----"; // The content of cakey.pem with a random line removed public static final String INVALID_CA_KEY = "-----BEGIN PRIVATE KEY-----\n" + "<KEY>" + "<KEY>" + "<KEY>\n" + "mLU3ZVCy5ySgrDF0yNfPPWkrhDFEtqIZ11t2pLNcdUsVnmP+68FEEo0B5zriUcbX\n" + "UzE9NZLOzyaTWyWr/iipmBxvD9BSQVx1NP3q3SBkDvNQIagjTxJtSg3ZYm2uzxUk\n" + "OfSNsIC4yk35ySUL7470WCkFMQQW4ZCE+KmvlmE+FfD7XIAVOYb7k2uPmO44AclQ\n" + "GjdxMNfZAgMBAAECggEACGx+IbWoebVtRri8/9ofIGxMEcrXRBOiH3HKYGcdPojv\n" + "TmuHB3oxPfBEoCJZYaruLqIrc8YYiF0Taycd5q3VgydCa97E6quz8fbY3r6EM3ET\n" + "U/hw4XF4UaYqIJTPpJlcm7FSRrwqDmxESeYrEoi1X8zzyU44IB1maeH8EzTPV7Us\n" + "hy/XZ+f+mDUnmJC9h0hcuD3qqM37CnzrcC/LvXCXhDmaAYEBlVbXQ6S8HyF0Op2z\n" + "umq9UHyxuZWB3qEC3ln5aM0bqFpSpgowbaeNFL9a8QKBgQD/pl4+nd9lJ3oncjwx\n" + "p4oN4yiOMfp8cFZXarwTX3JGBc2qLTLz3LQ+NR6zERx3jdIDLyPXygmib0P4bWX9\n" + "G0PIPvYPWB8fSHTSyE3YlNRkkSWhHJvAdmpmqL99NgVvyp5R5boBCcdvZhgzBW9V\n" + "xlF7HQ3+oa4TcWPs+DwErhId7wKBgQDfRiqhiGl1pAD4yjd/xjJy87s6qEiRLYzG\n" + "L+tlJ+GE+70JpmO7aHuCKfEoyIaz9pT4eZ8mJ4FYtsiE1x5LfosVLngWn80Khp14\n" + "1gE1fFdBSq5eyqs2b22FgVxQbJPdfhrizBGbfk+/+s96iNwN1nhoONUydwSZZO1s\n" + "sgdFwWuutwKBgHW/Qb8jZaYodZm/grv4B5z32FEN8enor8vZjEB8AJ0BxUUxRjuN\n" + "lrLkMnyVUAA8oNL4nlCgbKmVB8BfWs8mBKUxYpGUq9jzvWLsAPbVLbIYLDW1gIM3\n" + "xy/7Xx8jh4OC1kKwRWh/AY1sf47YXPwruJG0wyJZg1zPKBAYEUSyjAOfAoGBAMHk\n" + "vEbVIMhBqXpkmbfDlbIQCWsSExrIVLUTjjelX4pN10dXEMsCHCfYZo5FPf1wyMPT\n" + "UqseqYwyB4adDbj/5qZ5WV5EXhqi9oOmTRx2o4uW4EB/fhniwFitE07gS7SQu6Zz\n" + "E2NWWMledOlziq4VrzDLEhImG39ej3TSUdB4/RuXAoGAOnfEOetnL01ZiObA19kt\n" + "J4jRlu1hjapxsdph1pOJfOlkOIo7iNqTlbUAWiAcGOzmaA9nhaWyw6v3fVx7gTwo\n" + "XJldBre0qE+25GKQD5gQRLk44jq2d8DlkJfsNQL5S9veSst8tab84RlwInlZ9asX\n" + "1F/PgrpGOgiDauXLaXTtLmQ=\n" + "-----END PRIVATE KEY-----\n"; public static final X500Name CA_CERT_X500_NAME = new X500NameBuilder() .addRDN(RFC4519Style.c, "CH") .addRDN(RFC4519Style.o, "<NAME>") .addRDN(RFC4519Style.cn, "<NAME>") .addRDN(RFC4519Style.l, "Kefikon") .addRDN(RFC4519Style.st, "Thurgau") .addRDN(RFC4519Style.ou, "dev") .addRDN(BCStyle.E, "<EMAIL>") .build(); public static final BigInteger CA_CERT_SERIAL = new BigInteger("17592162074607144164"); private TestConstants() { // intentionally empty } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.users; import ch.zhaw.ba.anath.users.entities.UserEntity; import ch.zhaw.ba.anath.users.repositories.UserRepository; import org.junit.Before; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.Collections; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; /** * @author <NAME> */ public class InitialAdministratorCreatorTest { private static final String TEST_APPLICATION_ID = "theid"; private ApplicationContext applicationContextMock; private UserRepository userRepositoryMock; private PasswordEncoder passwordEncoderMock; private InitialAdministratorCreator initialAdministratorCreator; @Before public void setUp() { this.applicationContextMock = mock(ApplicationContext.class); this.userRepositoryMock = mock(UserRepository.class); this.passwordEncoderMock = mock(PasswordEncoder.class); this.initialAdministratorCreator = new InitialAdministratorCreator(userRepositoryMock, applicationContextMock, passwordEncoderMock); } @Test public void noPreviousAdministrator() { given(applicationContextMock.getId()).willReturn(TEST_APPLICATION_ID); given(userRepositoryMock.findAllByAdmin(true)).willReturn(Collections.emptyList()); given(passwordEncoderMock.encode(anyString())).willReturn("encoded_password"); UserEntity expectedUserEntity = makeExpectedUserEntity(); expectedUserEntity.setPassword("<PASSWORD>"); initialAdministratorCreator.processApplicationPreparedEvent(makeApplicationReadyEvent()); then(userRepositoryMock).should().save(expectedUserEntity); } @Test public void withPreviousAdministrator() { given(applicationContextMock.getId()).willReturn(TEST_APPLICATION_ID); given(userRepositoryMock.findAllByAdmin(true)).willReturn(Collections.singletonList(makeExpectedUserEntity())); given(passwordEncoderMock.encode(anyString())).willReturn("encoded_password"); initialAdministratorCreator.processApplicationPreparedEvent(makeApplicationReadyEvent()); then(userRepositoryMock).should(never()).save(any()); } @Test public void nonMatchingApplicationId() { given(applicationContextMock.getId()).willReturn("another_id"); initialAdministratorCreator.processApplicationPreparedEvent(makeApplicationReadyEvent()); then(userRepositoryMock).should(never()).findAllByAdmin(anyBoolean()); then(userRepositoryMock).should(never()).save(any()); } private ApplicationReadyEvent makeApplicationReadyEvent() { final ConfigurableApplicationContext configurableApplicationContextMock = mock(ConfigurableApplicationContext .class); given(configurableApplicationContextMock.getId()).willReturn(TEST_APPLICATION_ID); return new ApplicationReadyEvent(mock(SpringApplication.class), new String[]{}, configurableApplicationContextMock); } private UserEntity makeExpectedUserEntity() { final UserEntity userEntity = new UserEntity(); userEntity.setEmail(InitialAdministratorCreator.INITIAL_USER_USERNAME); userEntity.setFirstname(InitialAdministratorCreator.INITIAL_USER_FIRSTNAME); userEntity.setLastname(InitialAdministratorCreator.INITIAL_USER_LASTNAME); userEntity.setAdmin(true); return userEntity; } }<file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.users; import ch.zhaw.ba.anath.users.entities.UserEntity; import ch.zhaw.ba.anath.users.repositories.UserRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Profile; import org.springframework.context.event.EventListener; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID; /** * Create an initial administrator if no administrator exists in the user database. * <p> * It listens on {@link ApplicationReadyEvent}. * * @author <NAME> */ @Component @Profile("!tests") @Transactional(transactionManager = "userTransactionManager") @Slf4j public class InitialAdministratorCreator { private static final int ASSUMED_LINE_LENGTH = 78; private static final char NULL_CHARACTER = '\0'; private static final char EYE_CATCHER_CHARACTER = '>'; public static final String INITIAL_USER_FIRSTNAME = "Initial"; public static final String INITIAL_USER_LASTNAME = "Administrator"; public static final String INITIAL_USER_USERNAME = "<EMAIL>"; private final UserRepository userRepository; private final ApplicationContext applicationContext; private final PasswordEncoder passwordEncoder; public InitialAdministratorCreator(UserRepository userRepository, ApplicationContext applicationContext, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.applicationContext = applicationContext; this.passwordEncoder = passwordEncoder; } @EventListener public void processApplicationPreparedEvent(ApplicationReadyEvent event) { if (!event.getApplicationContext().getId().equals(applicationContext.getId())) { return; } final List<UserEntity> allByAdmin = userRepository.findAllByAdmin(true); if (!allByAdmin.isEmpty()) { log.info("Admin user(s) found. Not going to create initial administrator user"); return; } log.info("No admin user found in database, going to create initial administrator"); createInitialAdministrator(); } private void createInitialAdministrator() { final UserEntity initialAdminUser = new UserEntity(); initialAdminUser.setAdmin(true); initialAdminUser.setFirstname(INITIAL_USER_FIRSTNAME); initialAdminUser.setLastname(INITIAL_USER_LASTNAME); initialAdminUser.setEmail(INITIAL_USER_USERNAME); final String initialPassword = UUID.randomUUID().toString(); initialAdminUser.setPassword(passwordEncoder.encode(initialPassword)); userRepository.save(initialAdminUser); final String eyeCatcher = new String(new char[ASSUMED_LINE_LENGTH]) .replace(NULL_CHARACTER, EYE_CATCHER_CHARACTER); final String logMessage = "\n" + eyeCatcher + "\n\n" + "Created initial administrator\n\tusername: {}\n\tpassword: {}" + "\n\n" + eyeCatcher; log.info(logMessage, initialAdminUser.getEmail(), initialPassword); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.core.CertificateAuthority; import ch.zhaw.ba.anath.pki.core.PEMCertificateAuthorityReader; import ch.zhaw.ba.anath.pki.exceptions.CertificateAuthorityNotInitializedException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.util.Optional; /** * Get the CA as {@link CertificateAuthority} or the CA Certificate in PEM encoding. * @author <NAME> */ @Service @Slf4j @Transactional(transactionManager = "pkiTransactionManager") public class CertificateAuthorityService { public static final String SECURE_STORE_CA_PRIVATE_KEY = "ca.key"; public static final String SECURE_STORE_CA_CERTIFICATE = "ca.cert"; private final SecureStoreService secureStoreService; public CertificateAuthorityService(SecureStoreService secureStoreService) { this.secureStoreService = secureStoreService; } /** * Retrieve the CA certificate. * * @return return the PEM encoded certificate as string. */ public String getCertificate() { final Optional<Byte[]> optionalCaCertificate = secureStoreService.get(SECURE_STORE_CA_CERTIFICATE); final Byte[] caCertificate = optionalCaCertificate.orElseThrow(() -> { log.error("Unable to get Certificate Authority certificate, Certificate Authority not initialized"); return new CertificateAuthorityNotInitializedException("Not initialized"); }); return new String(ArrayUtils.toPrimitive(caCertificate)); } public CertificateAuthority getCertificateAuthority() { log.info("Load certificate authority"); Byte[] pemCaCertificateObject = retrieveCaCertificateFromSecureStoreOrThrow(); Byte[] pemCaPrivateKeyObject = retrieveCaPrivateKeyFromSecureStoreOrThrow(); final ByteArrayInputStream pemCaCertificateInputStream = pemByteArrayObjectToByteArrayInputStream (pemCaCertificateObject); final ByteArrayInputStream pemCaPrivateKeyInputStream = pemByteArrayObjectToByteArrayInputStream (pemCaPrivateKeyObject); final PEMCertificateAuthorityReader pemCertificateAuthorityReader = new PEMCertificateAuthorityReader( new InputStreamReader(pemCaPrivateKeyInputStream), new InputStreamReader(pemCaCertificateInputStream) ); log.info("Initialized certificate authority"); return pemCertificateAuthorityReader.certificateAuthority(); } private ByteArrayInputStream pemByteArrayObjectToByteArrayInputStream(Byte[] pemObject) { return new ByteArrayInputStream(ArrayUtils.toPrimitive(pemObject)); } private Byte[] retrieveCaPrivateKeyFromSecureStoreOrThrow() { final Optional<Byte[]> caPrivateKeyOptional = secureStoreService.get(CertificateAuthorityService .SECURE_STORE_CA_PRIVATE_KEY); return caPrivateKeyOptional.orElseThrow(() -> { log.error("Unable to retrieve certificate authority private key from secure storage"); return new CertificateAuthorityNotInitializedException("No CA private key found"); }); } private Byte[] retrieveCaCertificateFromSecureStoreOrThrow() { final Optional<Byte[]> caCertificateOptional = secureStoreService.get(CertificateAuthorityService .SECURE_STORE_CA_CERTIFICATE); return caCertificateOptional.orElseThrow(() -> { log.error("Unable to retrieve certificate authority certificate from secure storage"); return new CertificateAuthorityNotInitializedException("No CA certificate found"); }); } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.core; import ch.zhaw.ba.anath.pki.core.exceptions.PrivateKeyReaderException; import ch.zhaw.ba.anath.pki.core.interfaces.PrivateKeyReader; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.openssl.PEMException; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import java.io.Reader; import java.security.PrivateKey; /** * Read the PEM encoded private key from a file. The {@link PrivateKey} can be obtained by calling * {@link #privateKey()}. * * @author <NAME> */ public final class PEMPrivateKeyReader implements PrivateKeyReader { private final PrivateKey privateKey; /** * Read PEM encoded private key. * * @param keyReader {@link Reader} instance pointing to the private key file. */ public PEMPrivateKeyReader(Reader keyReader) { final Object privateKeyObject = readPrivateKey(keyReader); final PrivateKeyInfo privateKeyInfo = getPrivateKeyInfoFromPrivateKeyObject (privateKeyObject); privateKey = getPrivateKeyFromPrivateKeyInfo(privateKeyInfo); } private PrivateKey getPrivateKeyFromPrivateKeyInfo(PrivateKeyInfo privateKeyInfo) { final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter(); try { return jcaPEMKeyConverter.getPrivateKey(privateKeyInfo); } catch (PEMException e) { throw new PrivateKeyReaderException("Cannot convert to PrivateKey: " + e.getMessage(), e); } } private PrivateKeyInfo getPrivateKeyInfoFromPrivateKeyObject(Object privateKeyObject) { if (privateKeyObject instanceof PrivateKeyInfo) { return (PrivateKeyInfo) privateKeyObject; } if (privateKeyObject instanceof PEMKeyPair) { final PEMKeyPair pemKeyPair = (PEMKeyPair) privateKeyObject; return pemKeyPair.getPrivateKeyInfo(); } throw new PrivateKeyReaderException("Don't know how to handler private key of type: " + privateKeyObject .getClass() .getName()); } private Object readPrivateKey(Reader privateKeyReader) { try (PEMParser pemParser = new PEMParser(privateKeyReader)) { return pemParser.readObject(); } catch (Exception e) { throw new PrivateKeyReaderException("Error reading private key: " + e.getMessage(), e); } } @Override public PrivateKey privateKey() { return privateKey; } } <file_sep>/* * Copyright (c) 2018, <NAME>, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.zhaw.ba.anath.pki.services; import ch.zhaw.ba.anath.pki.entities.CertificateEntity; import ch.zhaw.ba.anath.pki.exceptions.CertificateNotFoundException; import ch.zhaw.ba.anath.pki.repositories.CertificateRepository; import org.junit.Before; import org.junit.Test; import java.math.BigInteger; import java.util.Optional; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; /** * @author <NAME> */ public class ImmediateCertificatePersistenceTest { private static final String TEST_USER_ID = "test id"; private CertificateRepository certificateRepositoryMock; private ConfirmableCertificatePersistenceLayer immediateCertificatePersistence; @Before public void setUp() { this.certificateRepositoryMock = mock(CertificateRepository.class); this.immediateCertificatePersistence = new ImmediateCertificatePersistence(certificateRepositoryMock); } @Test public void store() { final CertificateEntity certificateEntity = new CertificateEntity(); certificateEntity.setSerial(BigInteger.TEN); final String storeToken = immediateCertificatePersistence.store(certificateEntity); then(certificateRepositoryMock).should().save(certificateEntity); assertThat(storeToken, is(BigInteger.TEN.toString())); } @Test public void confirmExistingCertificate() { final CertificateEntity certificateEntity = new CertificateEntity(); certificateEntity.setSerial(BigInteger.TEN); given(certificateRepositoryMock.findOneBySerial(BigInteger.TEN)).willReturn( Optional.of(certificateEntity) ); final CertificateEntity confirmedEntity = immediateCertificatePersistence.confirm(BigInteger.TEN.toString(), TEST_USER_ID); assertThat(confirmedEntity, is(certificateEntity)); } @Test(expected = CertificateNotFoundException.class) public void confirmNonExistingCertificate() { given(certificateRepositoryMock.findOneBySerial(any())).willReturn(Optional.empty()); immediateCertificatePersistence.confirm(BigInteger.TEN.toString(), TEST_USER_ID); } @Test(expected = CertificateNotFoundException.class) public void testCoercingOfNumberFormatException() { immediateCertificatePersistence.confirm("don't care about non numers", TEST_USER_ID); } }
b516ec8bee7efa91928c7a0840005f3ac0eee549
[ "SQL", "Markdown", "Maven POM", "Java", "Dockerfile", "Shell" ]
42
Java
AnathPKI/anath-server
1c35816ac693528eea16470d41151b44ce65f77a
f13841f48fff7dcd585beecf1a017cc57c5b6495
refs/heads/master
<file_sep># print("Bithy") # # #Variable # # x=12 # print(x+3) # # x= "Hi world..." # print(x + " I Love Apple") #user_input = input("Enter your Birth Year: ") #age = 2018 - int(user_input) #print ("You are " + str(age) + " years old !") #inpleis operator # a=5 # a *= 3 # print(a) # # Language = "Python" # Language += " Java" # # print(Language) #Control_structural # x = 12 # if x > 5: # print("Greater than 5") # if x <= 47: # print ("Between 6 and 47") # # # # x = 4 # if x == 5: # print("It's 5") # else: # print("It's not 5") # # # num = 7 # if num == 5: # print("Number is 5") # else: # if num == 11: # print("Number is 11") # else: # if num == 7: # print("Number is 7") # else: # print("Number isn't 5, 11 or 7") # # # status = 5 # msg = "Logout" if status == 5 else "Login" # print(msg) # # for i in range (12): # print(i) # else: # print("Done") # # i = 1 # while i <= 20: # print (i) # i = i + 2 # # while 1 == 1: # print("In the Loop") # # # i = 1 # while 1 == 1: # print(i) # i = i+1 # if i>=5: # print("Breaking") # break # # print("Finished") # i = 0 # while True: # i = i + 1 # if i == 2: # print("Skipping 2") # continue # # if i == 5: # print("Breaking") # break # print(i) # # print ("Finished") # #LIST # words = ["Shammi","Nitu","Monisha","!"] # # print(words[0]) # print(words[1]) # print(words[2]) # print(words[3]) # # Number = 1 # My_numbers = [Number,2,3] # # things = ["Numbers", 0, My_numbers, 4.56 ] # # print(things[0]) # print(things[1]) # print(things[2]) # print(things[2][2]) # # # str = "Hello world !" # print(str[8]) # # my_numbers = [1,2,4,4,5] # my_numbers[2] = 3 # # print (my_numbers) # # # list = [1, 2, 3] # print (list + [4, 5, 6]) # print (list * 3) # # Fruits = ["apple", "orange", "pineappe", "grape"] # print("orange" in Fruits) # print("rice" in Fruits) # print("apple" not in Fruits) # num = [1, 2, 3, 4] # num.append(5) # print(num) # # # words = ["A", "C"] # index = 1 # words.insert(index, "B") # print(words) # # letters = ['p', 'q', 'r', 's', 'p', 'u'] # print(letters.index('r')) # print(letters.index('p')) # print(letters.index('z')) ###note = help(list.METHOD_NAME) ###dir(list) # nums = [1, 2, 4, 20, 50, 3, 4] # max(nums) # # # my_numbers = list(range(10)) # # print(my_numbers) # fruits = ["Apple", "Orange", "Pineapple", "Grape"] # # Lets make juice with these fruits # start_index = 0 # max_index = len(fruits) - 1 # while start_index <= max_index: # Work until this condition is True # fruit = fruits[start_index] # print(fruit + " Juice!") # start_index = start_index + 1 # # fruits = ["Apple", "Orange", "Pineapple", "Grape"] # # Lets make juice with these fruits # for fruit in fruits: # print(fruit + " Juice!") # #for letter in 'Python': # #print(letter) # # for letter in 'Trisha' + ' Touhid': # # print (letter) # for i in range(20): # if i == 5: # continue # if i > 9: # break # print(i) # print ("Printed first 10 numbers except 5!") # # def my_func(x=None): # if x: # return x * x # else: # return 0 # print(my_func()) # print(my_func(5)) #"Dictionary" # my_marks = {"Bengali": 80, "English": 85, "Math": 90} # print(my_marks ["Math"]) # # my_marks = {"Bengali" : [30, 35, 32], "English" : [45, 52, 33], "Math": [60, 74, 58]} # print(my_marks["Math"]) # my_nums = {1 : 1, 2 : 4, 3 : 9, 4 : "What?"} # my_nums[4] = 16 # print(my_nums) #"Tuple" # permissions = (("Admin", "Operator", "Customer"), ("Developer", "Tester"), [1, 2, 3], { # "Stage": "Development"}) # print(permissions[3]["Stage"]) ##....Function # def hello(): # print("Hello World !") # def show_double(x): # print(x*2) # # show_double(2) # show_double(100) # # # def make_sum(x,y): # z = x+y # print(z) # # make_sum(5,10) # make_sum(500,500) # # def print_dict(**kwargs): # for args in kwargs: # print("{0} : {1}". format(args, kwargs[args])) # # print_dict(a=1, b=2, c=3) # def print_all(a, *args, **kwargs): # print(a) # print(args) # print(kwargs) # # print_all(10,20,30,50, b=5, c=10) # def get_larger(x, y): # if x > y: # return x # else: # return y # # value = get_larger(23, 32) # # print(value) # def larger(x, y): # # if x > y: # return x # else: # return y # # value = larger(50, 40) # # print(value) # def beautify(text): # return text + '!!!' # # def make_line(func, words): # return "Hello " + func(words) # # print (make_line(beautify, "word")) # # import random # # value = random.randint(1, 100) # print(value) <file_sep> Country="Bangladesh is a beautiful country" print(Country) print(type("Country")) print(len(Country)) print(Country[8]) print(Country.find("is")) print(Country.strip()) Country1=" Bangladesh is a beautiful country " print(Country1) print(Country1.lstrip()) print(Country1.rstrip()) print(Country.upper()) print(Country.lower()) #print(Country,Country1=Country1,Country) print(Country) print(Country[::-1]) print(Country,Country1=Country1,Country) <file_sep>Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> List=['Laptop','pc','mobile','phone','pen'] >>> type(List) <class 'list'> >>> len(List) 5 >>> List[4] 'pen' >>> List[o:5] Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> List[o:5] NameError: name 'o' is not defined >>> List[0:5] ['Laptop', 'pc', 'mobile', 'phone', 'pen'] >>> List[0:4:2] ['Laptop', 'mobile'] >>> List[::-1] ['pen', 'phone', 'mobile', 'pc', 'Laptop'] >>> List[2]='Disk' >>> List ['Laptop', 'pc', 'Disk', 'phone', 'pen'] >>> List=List >>> >>> List=List+['pencil'] >>> List ['Laptop', 'pc', 'Disk', 'phone', 'pen', 'pencil'] >>> <file_sep>def main(): print( "PrintDiamond_Demo" ) print height = 5 printDiamond( height ) def printDiamond( height ): width = height * 2 - 1 for i in range( 0, height ): for j in xrange( width + 1 ): if j >= height - i and j <= height + i: print "a", else: print " ", print for i in reversed( range( 0, height - 1 ) ): for j in xrange( width + 1 ): if j >= height - i and j <= height + i: print "a", else: print " ", print main()<file_sep># Learn Python with practise This is Basic Tutorial series in Python <file_sep> #num = int (input("Enter the number of rows:")) # # num = [5] # for n in num: # for i in range(0,n): # for j in range(0,n-i-1): # print(end=" ") # for j in range(0,i+1): # print("*",end=" ") # print() # num = int(input("Enter the number of rows:")) # for i in range(0, num): # for j in range(0, num - i - 1): # print(end=" ") # for j in range(0, i + 1): # print("*", end=" ") # print() for row in range(6): for col in range(7): if (row==0 and col%3!=0) or (row==1 and col%3==0) or (row-col==2) or (row + col==8): print("*", end=" ") else: print(end=" ") print()<file_sep>Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> Bithy="Alu" >>> print(Bithy) Alu >>> Bithy[2] 'u' >>> len(Bithy) 3 >>> Bithy='Alu'+'Me' >>> print(bithy) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> print(bithy) NameError: name 'bithy' is not defined >>> print(Bithy) AluMe >>> Bithy.replace('Alu','Apple') 'AppleMe' >>> <file_sep>Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: D:/Programming Tutorial/Python/p.3.py =============== >>> =============== RESTART: D:/Programming Tutorial/Python/p.3.py =============== >>> >>> if a<0: print('a negative') else: print('a not negative') a not negative >>> i=1 >>> while i<=10: print i SyntaxError: Missing parentheses in call to 'print' >>> i=1 >>> while i<=10: print ('i') i=i+1 i i i i i i i i i i >>> i=1 >>> while i<=10: print(' i ') i= i+1 i i i i i i i i i i >>> i = 1 >>> while i<=10: print('i') i = i + 1 SyntaxError: unexpected indent >>> i=1 >>> while i<=10: print('i') i=i+1 i i i i i i i i i i >>> fib_1=0 >>> fib_2=1 >>> while fib_2<20: print('fib_2') fib_1,fib_2=fib_2,fib_1+fib_2 fib_2 fib_2 fib_2 fib_2 fib_2 fib_2 fib_2 >>> i=1 >>> while i<=10: print('i') i = i + 1 i i i i i i i i i i >>> i=1 >>> while i<=10: print ('i') i+=1 i i i i i i i i i i >>> i=1 >>> while i<=10: print(i) i=i+1 1 2 3 4 5 6 7 8 9 10 >>> fib_1=0 >>> fib_2=1 >>> while fib_2<20: print (fib_2) fib_1,fib_2=fib_2,fib_1+fib_2 1 1 2 3 5 8 13 >>> while fib_2<20: print (fib_2) fib_1, fib_2 = fib_2, fib_1+fib_2 >>> >>> >>> fib_1,fib_2=0,1 >>> while fib_2<20: print (fib_2) fib_1, fib_2 =fib_2, fib_1+fib_2 1 1 2 3 5 8 13 >>> while fib_2<20: print(fib_2), fib_1,fib_2=fib_2,fib_1+fib_2 >>> >>> fib1,fib2=0,1 >>> while fib2<20: print(fib2), fib1,fib2=fib2,fib1+fib2 1 (None,) 1 (None,) 2 (None,) 3 (None,) 5 (None,) 8 (None,) 13 (None,) >>> fib_1,fib_2=0,1 >>> while fib_2<20: print(fib_2), fib_1,fib_2=fib_2,fib_1+fib_2 1 (None,) 1 (None,) 2 (None,) 3 (None,) 5 (None,) 8 (None,) 13 (None,) >>> fib_1=0 >>> fib_2=1 >>> while fib_2<20: print fib_2, SyntaxError: Missing parentheses in call to 'print' >>> fib_1=0 >>> fib_2=1 >>> while fib_2<20: print(' fib_2'), fib_1,fib_2=fib_2,fib_1+fib_2 fib_2 (None,) fib_2 (None,) fib_2 (None,) fib_2 (None,) fib_2 (None,) fib_2 (None,) fib_2 (None,) >>> fib_1=0 >>> fib_2=1 >>> while fib_2<20: print (fib_2) , fib_1,fib_2=fib_2,fib_1+fib_2 1 (None,) 1 (None,) 2 (None,) 3 (None,) 5 (None,) 8 (None,) 13 (None,) >>> fib_1=0 >>> fib_2=1 >>> while fib_2<20: print(fib_2,) fib_1,fib_2=fib_2,fib_1+fib_2 1 1 2 3 5 8 13 >>> fib1,fib2=0,1 >>> while fib2<20: print(fib2,) fib1,fib2=fib2,fib1+fib2 1 1 2 3 5 8 13 >>> fib1,fib2=0,1 >>> while fib2<20: print (fib2), fib1,fib2=fib2,fib1+fib2 1 (None,) 1 (None,) 2 (None,) 3 (None,) 5 (None,) 8 (None,) 13 (None,) >>> for i in range(10): print(i) 0 1 2 3 4 5 6 7 8 9 >>> for i in range(50,2): print(i) >>> >>> for i in range(50): print(i) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 >>> for i in range(10): print(i) if i>5: break 0 1 2 3 4 5 6 >>> stack=[] >>> >>> stack.append (2) >>> stack.append (3) >>> stack.append (5) >>> >>> stack.pop() 5 >>> >>> <file_sep>#x = input('Please enter your age \n') x = 21 print('You are ' str( x) ' years old.') <file_sep># def sum(x, y): # z = x + y # print(z) # # sum(5, 6) # x = (1, 2, 3, 4, 5) # y = [1, 2, 3, 4, 5] # z = 1, 2, 3, 4, 5 # print(x, y, z, type(x), type(y), type(z)) # # # def make_twice(func, arg): # return func(func(arg)) # # def add_five(x): # return x + 5 # # print(make_twice(add_five, 10)) # # # # def my_pure_function(a, b): # c = ( 2 * a ) + ( 2 * b ) # return c # # my_pure_function(5, 10) # my_list = [] # def my_impure_function(arg): # my_list.append(arg) # # my_impure_function(10) # print(my_list) # def make_double(x): # return x * 2 # my_marks = [10, 12, 20, 30] # result = map(make_double, my_marks) # print(list(result)) # # # def my_list(x): # return x * 3 # marks = [2, 3, 5, 4] # result = map(my_list, marks) # print(list(result)) # # # nums = [11, 22, 33, 44, 55] # res = list(filter(lambda x: x % 2 == 0, nums)) # print(res) # # def my_iterable(): # i = 5 # while i > 0: # yield i # i -= 1 # # for i in my_iterable(): # print(i) # # # def my_decorator(func): # def decorate(): # print("------------") # func() # print("------------") # return decorate # # def print_raw(): # print("Clear Text") # # decorated_function = my_decorator(print_raw) # decorated_function() # # # # def my(x): # def decorate(): # # print("------------") # x() # print("------------") # # return decorate # # def print_raw(): # print("Touhid") # # decorated_function = my(print_raw) # decorated_function() # # # @my_decorator # def print_text(): # print("Hello World") # # for row in range(6): # for col in range(7): # if (row==0 and col%3!=0) or (row==1 and col%3==0) or (row-col==2) or (row+col)==8: # print("*",end="") # else: # print(end=" ") # print() # # for row in range(7): # for col in range(5): # if col==2 or (row==0 and col !=2): # print("*",end="") # else: # print(end=" ") # print() # # userInput = int(input("Please input side length of diamond: ")) # # if userInput > 0: # for i in range(userInput): # for s in range(userInput -3, -2, -1): # print(" ", end="") # for j in range(i * 2 -1): # print("*", end="") # print() # for i in range(userInput, -1, -1): # for j in range(i * 2 -1): # print("*", end="") # print()<file_sep>Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> Bithy=" T o u h i d " >>> print(Bithy) T o u h i d >>> Bithy.upper() ' T O U H I D ' >>> Bithy.lower() ' t o u h i d ' >>> Bithy.strip() 'T o u h i d' >>> Bithy.rstrip() ' T o u h i d' >>> Bithy.ltrip() Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> Bithy.ltrip() AttributeError: 'str' object has no attribute 'ltrip' >>> Bithy.lstrip() 'T o u h i d ' >>> Bithy="Touhid" >>> Bithy2="Shuvo" >>> Bithy,Bithy2=Bithy2,Bithy >>> print(Bithy) Shuvo >>> printBithy2) SyntaxError: invalid syntax >>> print(Bithy2) Touhid >>> <file_sep>Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> >>> from tkinter import * >>> a=TK() Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> a=TK() NameError: name 'TK' is not defined >>> from tkinter import * >>> a = tk() Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> a = tk() NameError: name 'tk' is not defined >>> from tkinter import * >>> a = Tk() >>> a.title ("My First window") '' >>> >>> import tkinter >>> root = tkinter.Tk() >>> root.title("My second window") '' >>>
1387b9b549bc3e1f69753b7816c80138ff4a0afe
[ "Markdown", "Python" ]
12
Python
Zahidsqldba07/Learn-Python-with-practise
b3ae921ad91d4d707fbda3183af1fc89cc9eb0c6
29ac08c9b844492cf39bfe2515b19f17793c46b5
refs/heads/master
<repo_name>Ghurfa/ComputerVisionCamp<file_sep>/CVIntro/CVIntro/Program.cs using System; using System.IO; using FRC.CameraServer; using FRC.CameraServer.OpenCvSharp; using OpenCvSharp; namespace CVIntro { class Program { static void Main(string[] args) { UsbCamera camera = new UsbCamera("Cam", 0); string cameraConfigJson = File.ReadAllText(@"\\GMRDC1\Folder Redirection\Lorenzo.Lopez\Documents\Computer Vision Camp\Camera Settings.json"); camera.SetConfigJson(cameraConfigJson); MjpegServer webServer = new MjpegServer("Server", 10700); CvSink sink = new CvSink("Sink"); webServer.Source = camera; sink.Source = camera; camera.SetExposureAuto(); camera.SetWhiteBalanceAuto(); Mat foreground = Cv2.ImRead(@"C:\Users\Lorenzo.Lopez\Pictures\godzilla 1280x720.jpg"); //Mat background = Cv2.ImRead(@"C:\Users\Lorenzo.Lopez\Pictures\city 1280x720.jpg"); //background = background.Resize(new OpenCvSharp.Size(foreground.Width, foreground.Height)); Mat foregroundHsv = foreground.CvtColor(ColorConversionCodes.BGR2HSV); Mat mask = foregroundHsv.InRange(new Scalar(45, 40, 40), new Scalar(64, 255, 255)); Mat invertedMask = new Mat(); Cv2.BitwiseNot(mask, invertedMask); Mat finalForeground = new Mat(); foreground.CopyTo(finalForeground, invertedMask); //Mat finalBackground = new Mat(); //background.CopyTo(finalBackground, mask); Cv2.NamedWindow("Display", WindowMode.AutoSize); Cv2.SetMouseCallback("Display", (@event, x, y, flags, _userData) => { if (x < 0 || x >= foregroundHsv.Width || y < 0 || y >= foregroundHsv.Height) { return; } Vec3b hsv = foregroundHsv.At<Vec3b>(y, x); Console.WriteLine($"H: {hsv.Item0}, S: {hsv.Item1}, V:{hsv.Item2}"); }); Mat background = new Mat(); Mat background2 = new Mat(); Mat finalBackground = new Mat(); Mat finalImage = new Mat(); while (true) { if(sink.GrabFrame(background) == 0) { continue; } background.CopyTo(finalBackground, mask); Cv2.BitwiseOr(finalForeground, finalBackground, finalImage); Cv2.Laplacian(finalImage, finalImage, finalImage.Type()); Cv2.ImShow("Display", finalImage); if(Cv2.WaitKey(1) != -1) { break; } } /*Mat finalImage = new Mat(); Cv2.BitwiseOr(finalForeground, finalBackground, finalImage); Cv2.ImShow("Display", finalImage); Cv2.WaitKey(0);*/ } } } <file_sep>/BluescreenWarmup/BluescreenWarmup/Program.cs using System; using OpenCvSharp; namespace BluescreenWarmup { class Program { static void Main(string[] args) { string pictures = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); Mat foreground = Cv2.ImRead(pictures + @"\bluescreen.jpg"); Mat background = Cv2.ImRead(pictures + @"\forest.jpg"); Cv2.NamedWindow("Display"); Cv2.ResizeWindow("Display", foreground.Width, foreground.Height); Mat foregroundHsv = foreground.CvtColor(ColorConversionCodes.BGR2HSV); Mat mask = foregroundHsv.InRange(new Scalar(90, 90, 80), new Scalar(140, 255, 255)); Mat invertedMask = new Mat(); Cv2.BitwiseNot(mask, invertedMask); Mat finalForeground = new Mat(); foreground.CopyTo(finalForeground, invertedMask); Mat finalBackground = new Mat(); background.CopyTo(finalBackground, mask); Cv2.SetMouseCallback("Display", (@event, x, y, flags, _userData) => { Vec3b color = foreground.At<Vec3b>(y, x); Console.WriteLine($"H: {color.Item0}, S: {color.Item1}, V:{color.Item2}"); }); Mat finalImage = new Mat(); Cv2.BitwiseOr(finalForeground, finalBackground, finalImage); Cv2.ImShow("Display", finalImage); Cv2.WaitKey(0); } } } <file_sep>/CVPong/CVPong/Ball.cs using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CVPong { class Ball { public Rectangle Position; public Point Velocity; public int Score; private Random random; private Point bounds; public Ball(Rectangle position, Point velocity, Point bounds) { Position = position; Velocity = velocity; this.bounds = bounds; random = new Random(); } public void Update() { Position.Location += Velocity; if (Position.X < 0) { Velocity.X = Math.Abs(Velocity.X); Position.Location = new Point(random.Next(100, 200), random.Next(100, 200)); Score++; } else if (Position.Y < 0) { Velocity.Y = Math.Abs(Velocity.Y); } else if (Position.Right > bounds.X) { Velocity.X = -Math.Abs(Velocity.X); } else if(Position.Bottom > bounds.Y) { Velocity.Y = -Math.Abs(Velocity.Y); } } } } <file_sep>/CVTracking/CVTracking/Paddle.cs using OpenCvSharp; using System; using System.Collections.Generic; using System.Text; namespace CVTracking { class Paddle { private Mat image; public RotatedRect Position; public RotatedRect LastPosition; public double Angle; private Point[] points; private bool isLeft; public Point Velocity => new Point(Position.Center.X - LastPosition.Center.X, Position.Center.Y - LastPosition.Center.Y); public Paddle(Mat image) { LastPosition = new RotatedRect(); points = new Point[4]; this.image = image; } public void Update(RotatedRect position, Ball ball) { LastPosition = Position; Position = position; isLeft = Position.Center.X < image.Width / 2; computeAngle(isLeft); bool hit = false; for (int i = 0; i < 3 && !hit; i++) { Point corner1 = points[i]; for (int j = i + 1; j < 4; j++) { Point corner2 = points[j]; double cornerAngle = corner1.AngleTo(corner2); double angleDiff = cornerAngle - Angle; if (angleDiff < -Math.PI) angleDiff += Math.PI; else if (angleDiff > Math.PI) angleDiff -= Math.PI; if (Math.Abs(angleDiff) < 0.1 || Math.Abs(Math.Abs(angleDiff) - Math.PI / 2) < 0.1 || Math.Abs(Math.Abs(angleDiff) - Math.PI) < 0.1) { if(ball.CalculateIntersection(corner1, corner2)) { hit = true; break; } } } } } private void computeAngle(bool isLeft) { Point2f[] points2F = Position.Points(); for (int i = 0; i < 4; i++) { points[i] = (Point)points2F[i]; } //find closest other corner - direction to it is the paddle orientation Point point = points[0]; double closestDistance = point.DistanceTo(points[1]); Point distDiff = point - points[1]; for (int i = 2; i < 4; i++) { double distance = point.DistanceTo(points[i]); if (distance < closestDistance) { closestDistance = distance; distDiff = point - points[i]; } } Angle = Math.Atan(((double)distDiff.Y) / ((double)distDiff.X)); /*double angle = rect.Angle; double angleRads = angle * Math.PI /180;*/ if (!isLeft) Angle += Math.PI; } private bool checkIntersection(Ball ball) { RotatedRect ballHitbox = new RotatedRect(ball.Center, new Size2f(ball.Radius * 2, ball.Radius * 2), (float)Angle); Cv2.RotatedRectangleIntersection(Position, ballHitbox, out var output); return output.Length > 0; } public void Draw() { if (isLeft) { //Position.Draw(image, Scalar.Red, 1); //Cv2.FillConvexPoly(image, points, Scalar.Red); } else { //Position.Draw(image, Scalar.Blue, 1); //Cv2.FillConvexPoly(image, points, Scalar.Blue); } float lineLength = 100; Cv2.Line(image, (Point)Position.Center, new Point(Position.Center.X + lineLength * Math.Cos(Angle), Position.Center.Y + lineLength * Math.Sin(Angle)), Scalar.AliceBlue); } } } <file_sep>/CVFeatureDetection/CVLaneDetection/Program.cs using OpenCvSharp; using System; namespace CVLaneDetection { class Program { static void Main(string[] args) { Mat image = Cv2.ImRead(@"C:\Users\Lorenzo.Lopez\Pictures\road nz.jpg"); Mat gray = image.CvtColor(ColorConversionCodes.BGR2GRAY); Mat blur = gray.GaussianBlur(new Size(5, 5), 0); Mat canny = blur.Canny(50, 150); Mat mask = new Mat(); canny.CopyTo(mask); Cv2.BitwiseXor(mask, mask, mask); Cv2.FillPoly(mask, new Point[][]{ new Point[] { new Point(mask.Width/2, mask.Height * 21/32), new Point(0, mask.Height), new Point(mask.Width, mask.Height), } }, Scalar.White); Cv2.BitwiseAnd(canny, mask, canny); Mat invertedMask = new Mat(); Cv2.BitwiseNot(mask, invertedMask); Mat final = new Mat(); image.CopyTo(final, invertedMask); //canny.CopyTo(final, mask); Mat cannyConverted = canny.CvtColor(ColorConversionCodes.GRAY2BGR); canny.ConvertTo(cannyConverted, final.Type()); Cv2.BitwiseOr(final, cannyConverted, final); var lines = Cv2.HoughLinesP(canny, 2, Math.PI / 180, 100, 100, 50); Cv2.NamedWindow("Display", WindowMode.AutoSize); Cv2.NamedWindow("Raw", WindowMode.AutoSize); Cv2.ImShow("Display", canny); Cv2.ImShow("Raw", final); Cv2.WaitKey(0); } } } <file_sep>/CVTracking/CVTracking/Extensions.cs using OpenCvSharp; using System; using System.Collections.Generic; using System.Text; namespace CVTracking { public static class Extensions { public static void Draw(this RotatedRect rect, Mat image, Scalar color, int thickness) { if (thickness< 0) { Point[] points = new Point[4]; Point2f[] points2F = rect.Points(); for (int i = 0; i < 4; i++) { points[i] = (Point)points2F[i]; } Cv2.FillConvexPoly(image, points, color); } else { foreach(Point2f point in rect.Points()) { foreach (Point2f point2 in rect.Points()) { Cv2.Line(image, (Point)point, (Point)point2, color, thickness); } } } } public static double AngleTo(this Point point1, Point point2) { Point distDiff = point2 - point1; return Math.Atan(((double)distDiff.Y) / ((double)distDiff.X)); } } } <file_sep>/CVFeatureDetection/CVFeatureDetection/Program.cs using FRC.CameraServer; using FRC.CameraServer.OpenCvSharp; using OpenCvSharp; using System; using System.Linq; namespace CVFeatureDetection { class Program { static void eyesInFaceDetection(Mat image, Rect[] faces, CascadeClassifier eyeClassifier) { foreach (var face in faces) { Cv2.Rectangle(image, face, Scalar.ForestGreen, 1); using var faceArea = image[face]; var faceColor = image[face]; var eyes = eyeClassifier.DetectMultiScale(faceArea, 1.1, 4); foreach (var eye in eyes) { Cv2.Rectangle(faceColor, eye, Scalar.Fuchsia, 1); } } } static void faceswap(Mat image, Rect[] faces) { //Store face images before switching //Before switching so that you have the original image instead of a swapped one Mat[] faceRegions = new Mat[faces.Length]; for (int i = 0; i < faces.Length; i++) { Rect face = faces[i]; faceRegions[i] = new Mat(); image[face].CopyTo(faceRegions[i]); Cv2.Rectangle(image, face, Scalar.Green); } //Swap around faces for (int i = 0; i < faces.Length; i++) { Rect nextFace = faces[(i + 1) % faces.Length]; Mat stretched = faceRegions[i].Resize(nextFace.Size); image[nextFace] = stretched; } } static void flipFaces(Mat image, Rect[] faces) { foreach(Rect face in faces) { Mat faceImage = image[face]; Cv2.Flip(faceImage, faceImage, FlipMode.X); } } static void Main(string[] args) { UsbCamera camera = new UsbCamera("Camera", 0); //camera.SetResolution(160, 120); CvSink sink = new CvSink("Sink"); sink.Source = camera; MjpegServer server = new MjpegServer("Server", 10700); server.Source = camera; Cv2.NamedWindow("Display", WindowMode.AutoSize); int minsize = 2; Cv2.CreateTrackbar("Minsize (k)", "Display", ref minsize, 10); Mat image = new Mat(); Mat grayscale = new Mat(); string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); CascadeClassifier faceClassifier = new CascadeClassifier(documents + @"\Computer Vision Camp\haarcascade_frontalface_default.xml"); CascadeClassifier eyeClassifier = new CascadeClassifier(documents + @"\Computer Vision Camp\haarcascade_eye_tree_eyeglasses.xml"); while (true) { if (sink.GrabFrame(image) == 0) continue; Cv2.Flip(image, image, FlipMode.Y); Cv2.CvtColor(image, grayscale, ColorConversionCodes.BGR2GRAY); //Grab faces - filter by area var faces = faceClassifier.DetectMultiScale(grayscale, 1.1, 4).Where(rect => rect.Width * rect.Height > minsize * 1000).ToArray(); //flipFaces(image, faces); faceswap(image, faces); Cv2.ImShow("Display", image); if (Cv2.WaitKey(1) != -1) break; } } } } <file_sep>/FormCV/FormCV/Form1.cs using FRC.CameraServer; using FRC.CameraServer.OpenCvSharp; using OpenCvSharp; using OpenCvSharp.Extensions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormCV { public partial class Form1 : Form { UsbCamera camera; MjpegServer server; CvSink sink; Mat frame; public Form1() { InitializeComponent(); camera = new UsbCamera("Camera", 0); camera.SetResolution(320, 240); string configPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Computer Vision Camp\Camera Settings.json"; string cameraConfig = File.ReadAllText(configPath); camera.SetConfigJson(cameraConfig); sink = new CvSink("Sink"); sink.Source = camera; server = new MjpegServer("Server", 10700); server.Source = camera; frame = new Mat(); } private void Form1_Load(object sender, EventArgs e) { _ = FrameLoop(); } private async Task<bool> GrabFrame() { return await Task.Run(() => { return sink.GrabFrame(frame) != 0; }); } private async Task FrameLoop() { while(true) { if (await GrabFrame()) { pictureBoxIpl1.ImageIpl = frame; } } } private void button1_Click(object sender, EventArgs e) { //pictureBox1 = BitmapConverter.ToBitmap(frame); } } } <file_sep>/CVTracking/CVTracking/Ball.cs using OpenCvSharp; using System; using System.Collections.Generic; using System.Text; namespace CVTracking { class Ball { public Point Center; public double Speed; private double angle; public double Angle { get { return angle; } set { double val = value; double clamped = val % (2 * Math.PI); if (clamped < -Math.PI) clamped += 2 * Math.PI; else if (clamped > Math.PI) clamped -= 2 * Math.PI; angle = clamped; } } public int Radius; private Random random; private double baseSpeed; private Point velocity; private Mat image; public Ball(Mat image, double speed, int radius) { this.image = image; Center = new Point(image.Width / 2, image.Height / 2); Speed = speed; Radius = radius; random = new Random(); Angle = (random.NextDouble() - 0.5) * 2 * Math.PI; baseSpeed = speed; calculateVelocity(); } public void Update() { Center += velocity; /* Corner vertices: * 110 38 * 108 581 * 1210 52 * 1191 611 */ CalculateIntersection(new Point(110, 38), new Point(1210, 52)); CalculateIntersection(new Point(1210, 52), new Point(1191, 611)); CalculateIntersection(new Point(1191, 611), new Point(108, 581)); CalculateIntersection(new Point(108, 581), new Point(110, 38)); } public bool CalculateIntersection(Point endPoint1, Point endPoint2) { double lineAngle = endPoint1.AngleTo(endPoint2); /*Point2f center = new Point2f((endPoint1.X + endPoint2.X) / 2, (endPoint1.Y + endPoint2.Y) / 2); Size2f size; if ((lineAngle > Math.PI / 4 && lineAngle < 3 * Math.PI / 4) || (-lineAngle > Math.PI / 4 && -lineAngle < 3 * Math.PI / 4)) { size = new Size2f(1, (float)endPoint1.DistanceTo(endPoint2)); } else { size = new Size2f((float)endPoint1.DistanceTo(endPoint2), 1); } RotatedRect lineHitbox = new RotatedRect(center, size, -(float)lineAngle); lineHitbox.Draw(image, Scalar.Green, -1);*/ Cv2.Line(image, endPoint1, endPoint2, Scalar.Red); /*Cv2.RotatedRectangleIntersection(lineHitbox, GetHitbox(lineAngle), out var intersection); bool intersects = intersection.Length > 0;*/ if (Intersects(endPoint1, endPoint2)) { Angle = lineAngle - (Angle - lineAngle); calculateVelocity(); Center += velocity; return true; } return false; } public RotatedRect GetHitbox(double angle) { return new RotatedRect(Center, new Size2f(Radius * 2, Radius * 2), (float)Angle); } private void calculateVelocity() { velocity = new Point(Math.Cos(Angle) * Speed, Math.Sin(Angle) * Speed); } private bool Intersects(Point point1, Point point2) { Point d = point1 - point2; Point f = point2 - Center; double a = d.DotProduct(d); double b = 2 * f.DotProduct(d); double c = f.DotProduct(f) - Radius * Radius; double discriminant = b * b - 4 * a * c; if (discriminant < 0) { // no intersection return false; } else { // ray didn't totally miss sphere, // so there is a solution to // the equation. discriminant = Math.Sqrt(discriminant); // either solution may be on or off the ray so need to test both // t1 is always the smaller value, because BOTH discriminant and // a are nonnegative. double t1 = (-b - discriminant) / (2 * a); double t2 = (-b + discriminant) / (2 * a); // 3x HIT cases: // -o-> --|--> | | --|-> // Impale(t1 hit,t2 hit), Poke(t1 hit,t2>1), ExitWound(t1<0, t2 hit), // 3x MISS cases: // -> o o -> | -> | // FallShort (t1>1,t2>1), Past (t1<0,t2<0), CompletelyInside(t1<0, t2>1) if (t1 >= 0 && t1 <= 1) { // t1 is the intersection, and it's closer than t2 // (since t1 uses -b - discriminant) // Impale, Poke return true; } // here t1 didn't intersect so we are either started // inside the sphere or completely past it if (t2 >= 0 && t2 <= 1) { // ExitWound return true; } // no intn: FallShort, Past, CompletelyInside return false; } } } } <file_sep>/CVIntro/CVImageDetection/Program.cs using System; using System.IO; using System.Linq; using FRC.CameraServer; using FRC.CameraServer.OpenCvSharp; using OpenCvSharp; namespace CVImageDetection { class Program { static void Main(string[] args) { UsbCamera camera = new UsbCamera("Cam", 0); string cameraConfigJson = File.ReadAllText(@"\\GMRDC1\Folder Redirection\Lorenzo.Lopez\Documents\Computer Vision Camp\Camera Settings.json"); camera.SetConfigJson(cameraConfigJson); MjpegServer webServer = new MjpegServer("Server", 10700); CvSink sink = new CvSink("Sink"); webServer.Source = camera; sink.Source = camera; camera.SetExposureAuto(); camera.SetWhiteBalanceAuto(); camera.SetResolution(640, 480); Cv2.NamedWindow("Display", WindowMode.AutoSize); int lastX; int lastY; Cv2.SetMouseCallback("Display", (@event, x, y, flags, _userdata) => { lastX = x; lastY = y; }); int hLow = 6; int hHigh = 58; int sLow = 75; int sHigh = 255; int vLow = 100; int vHigh = 255; Cv2.CreateTrackbar("H_Low", "Display", ref hLow, 180); Cv2.CreateTrackbar("H_High", "Display", ref hHigh, 180); Cv2.CreateTrackbar("S_Low", "Display", ref sLow, 255); Cv2.CreateTrackbar("S_High", "Display", ref sHigh, 255); Cv2.CreateTrackbar("V_Low", "Display", ref vLow, 255); Cv2.CreateTrackbar("V_High", "Display", ref vHigh, 255); Mat inputImage = new Mat(); Mat imageHSV = new Mat(); Mat imageMask = new Mat(); Mat finalImage = new Mat(); Scalar lowScalar = new Scalar(); Scalar highScalar = new Scalar(); while (true) { if (sink.GrabFrame(inputImage) == 0) { continue; } lowScalar.Val0 = hLow; lowScalar.Val1 = sLow; lowScalar.Val2 = vLow; highScalar.Val0 = hHigh; highScalar.Val1 = sHigh; highScalar.Val2 = vHigh; Cv2.CvtColor(inputImage, imageHSV, ColorConversionCodes.BGR2HSV); Cv2.InRange(imageHSV, lowScalar, highScalar, imageMask); Cv2.FindContours(imageMask, out Point[][] contours, out var hierarchy, RetrievalModes.List, ContourApproximationModes.ApproxSimple); var filtered = contours.Select(x => Cv2.ConvexHull(x)) .Where(x => Cv2.ContourArea(x) > 500) //Area filter .Where(x => { int angle = (int)Cv2.MinAreaRect(x).Angle; if (angle < -45) angle += 90; else if (angle > 45) angle -= 90; return Math.Abs(angle) < 15; }) //Angle filter .Where(x => { var boundingRect = Cv2.BoundingRect(x); return boundingRect.Width > boundingRect.Height; }); //Orientation filter var rightMost = filtered.Select(x => Cv2.BoundingRect(x)).OrderBy(x => x.X).LastOrDefault(); if(rightMost != default) { //60 = measured inches //144 = measured pixels double distance = 60 * 144 / rightMost.Width; //inputImage.PutText(distance.ToString(), new Point(0, 0), HersheyFonts.HersheyPlain, 10, new Scalar(0, 0, 200)); Console.WriteLine(distance); } var boundingRects = contours.Select(x => Cv2.BoundingRect(x)); inputImage.DrawContours(filtered, -1, new Scalar(0, 200, 0), -1); inputImage.Rectangle(rightMost, new Scalar(0, 0, 200), 3); //Cv2.GaussianBlur(inputImage, inputImage, new Size(5, 5), 2); Cv2.ImShow("Display", inputImage); if (Cv2.WaitKey(1) != -1) { break; } } } } } <file_sep>/CVTracking/CVTracking/Program.cs using FRC.CameraServer; using FRC.CameraServer.OpenCvSharp; using OpenCvSharp; using System; using System.Diagnostics; using System.Linq; namespace CVTracking { class Program { static void Main(string[] args) { HttpCamera camera = new HttpCamera("Camera", "http://192.168.1.121:1181/stream.mjpg"); CvSink sink = new CvSink("Sink"); sink.Source = camera; Cv2.NamedWindow("Display", WindowMode.AutoSize); int x = 11; int screen = 0; Cv2.CreateTrackbar("X", "Display", ref x, 20); Cv2.CreateTrackbar("Screen", "Display", ref screen, 2); //Cv2.NamedWindow("Display2", WindowMode.AutoSize); Mat image = new Mat(); Mat hsvImage = new Mat(); Mat paddleMask = new Mat(); Mat paddleSmooth = new Mat(); while (sink.GrabFrame(image) == 0) ; Ball ball = new Ball(image, 20, 20); Paddle leftPaddle = new Paddle(image); Paddle rightPaddle = new Paddle(image); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (true) { if (sink.GrabFrame(image) == 0) { continue; } //Walls /*Cv2.Line(image, new Point(110, 38), new Point(1210, 52), Scalar.Red, 2); Cv2.Line(image, new Point(1210, 52), new Point(1191, 611), Scalar.Red, 2); Cv2.Line(image, new Point(1191, 611), new Point(108, 581), Scalar.Red, 2); Cv2.Line(image, new Point(108, 581), new Point(110, 38), Scalar.Red, 2);*/ //Print stopwatch Cv2.PutText(image, stopwatch.ElapsedTicks.ToString(), new Point(0, 20), HersheyFonts.HersheyPlain, 1, Scalar.Red); stopwatch.Restart(); //Paddle filter Cv2.CvtColor(image, hsvImage, ColorConversionCodes.BGR2HSV); Cv2.InRange(hsvImage, new Scalar(70, 100, 140), new Scalar(100, 255, 255), paddleMask); //Smooth paddles using Mat structure = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(x + 1, x + 1)); Cv2.MorphologyEx(paddleMask, paddleSmooth, MorphTypes.Close, structure); //Draw paddles Cv2.FindContours(paddleSmooth, out var contours, out var _, RetrievalModes.List, ContourApproximationModes.ApproxTC89KCOS); var minAreaRects = contours.Where(x => Cv2.ContourArea(x) > 1000).Select(x => Cv2.MinAreaRect(x)).OrderBy(x => x.Center.X); leftPaddle.Update(minAreaRects.First(), ball); rightPaddle.Update(minAreaRects.Last(), ball); leftPaddle.Draw(); rightPaddle.Draw(); ball.Update(); //Draw ball Cv2.Circle(image, ball.Center, ball.Radius, Scalar.White, -1); if (screen == 0) { Cv2.ImShow("Display", image); } else if (screen == 1) { Cv2.ImShow("Display", paddleSmooth); } else if (screen == 2) { Cv2.ImShow("Display", paddleMask); } Cv2.WaitKey(1); } } } } <file_sep>/CVPong/CVPong/Paddle.cs using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CVPong { class Paddle { public Rectangle Position; public object PositionLock; public Paddle(Point position, Point size) { Position = new Rectangle(position, size); PositionLock = new object(); } public void Update(Ball ball) { if (ball.Position.Intersects(Position)) { if(ball.Position.X < Position.X) { ball.Velocity.X = -Math.Abs(ball.Velocity.X); } else { ball.Velocity.X = Math.Abs(ball.Velocity.X); } } } public void SetY(int y) { Position.Y = y; } } } <file_sep>/CVPong/CVPong/Game1.cs using FRC.CameraServer; using FRC.CameraServer.OpenCvSharp; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using OpenCvSharp; using System; using System.IO; using System.Linq; using System.Threading; namespace CVPong { /// <summary> /// This is the main type for your game. /// </summary> public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; UsbCamera camera; CvSink sink; MjpegServer server; Mat grabFrame; bool grabbedFrame; object frameLock; Mat processedFrame; bool processed; object processedLock; Texture2D texture; object textureLock; Thread grabFrameThread; Thread processFrameThread; Thread convertFrameThread; Ball ball; Paddle paddle; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; camera = new UsbCamera("Camera", 0); string configPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Computer Vision Camp\Camera Settings.json"; string config = File.ReadAllText(configPath); camera.SetConfigJson(config); //camera.SetResolution(320, 480); sink = new CvSink("Sink"); sink.Source = camera; grabFrame = new Mat(); server = new MjpegServer("Server", 10700); server.Source = camera; ball = new Ball(new Rectangle(Microsoft.Xna.Framework.Point.Zero, new Microsoft.Xna.Framework.Point(20, 20)), new Microsoft.Xna.Framework.Point(5, 5), new Microsoft.Xna.Framework.Point(640, 480)); paddle = new Paddle(new Microsoft.Xna.Framework.Point(50, 0), new Microsoft.Xna.Framework.Point(20, 100)); frameLock = new object(); textureLock = new object(); processedLock = new object(); startGrabFrameLoop(); startProcessFrameLoop(); startConvertFrameLoop(); } private void startGrabFrameLoop() { Mat tempFrame = new Mat(); grabFrameThread = new Thread(() => { while (true) { if (sink.GrabFrame(tempFrame) != 0) { lock (frameLock) { grabFrame = tempFrame; grabbedFrame = true; } } } }); grabFrameThread.Start(); } private void startProcessFrameLoop() { Mat tempFrame = new Mat(); Mat hsvFrame = new Mat(); Mat mask = new Mat(); OpenCvSharp.Point[][] contours; processFrameThread = new Thread(() => { while (true) { if (grabbedFrame) { lock (frameLock) { tempFrame = grabFrame; grabbedFrame = false; } Cv2.CvtColor(tempFrame, hsvFrame, ColorConversionCodes.BGR2HSV); Cv2.InRange(hsvFrame, new Scalar(0, 30, 50), new Scalar(40, 255, 255), mask); mask.FindContours(out contours, out var hierarchy, RetrievalModes.List, ContourApproximationModes.ApproxSimple); var filtered = contours.Select(x => Cv2.ConvexHull(x)). Where(x => { return Cv2.ContourArea(x) > 2000; }); //Cv2.DrawContours(tempFrame, filtered, -1, Scalar.Red, -1); Cv2.Circle(tempFrame, ball.Position.Location.X + ball.Position.Width/2, ball.Position.Location.Y+ ball.Position.Height / 2, ball.Position.Height / 2, Scalar.Red, -1); if(filtered.Count() > 0) { OpenCvSharp.Point position = filtered.Select(x=> { return Cv2.BoundingRect(x); }).OrderBy(x => { return x.Y; }).First().TopLeft; paddle.SetY(position.Y); } Cv2.Rectangle(tempFrame, new Rect(paddle.Position.X, paddle.Position.Y, paddle.Position.Width, paddle.Position.Height), Scalar.ForestGreen, -1); Cv2.PutText(tempFrame, ball.Score.ToString(), new OpenCvSharp.Point(200, 0), HersheyFonts.HersheyPlain, 20, Scalar.Bisque); lock (processedLock) { processed = true; processedFrame = tempFrame; } } } }); processFrameThread.Start(); } private void startConvertFrameLoop() { Mat tempFrame = new Mat(); Texture2D tempTexture; convertFrameThread = new Thread(() => { while(graphics == null || graphics.GraphicsDevice == null) { } while (true) { if (processed) { lock (processedLock) { processed = false; tempFrame = processedFrame; } tempTexture = Texture2D.FromStream(graphics.GraphicsDevice, tempFrame.ToMemoryStream()); lock (textureLock) { texture = tempTexture; } } } }); convertFrameThread.Start(); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); // TODO: Add your update logic here ball.Update(); paddle.Update(ball); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here spriteBatch.Begin(); lock (textureLock) { if (texture != null) { spriteBatch.Draw(texture, Vector2.Zero, Color.White); } } spriteBatch.End(); base.Draw(gameTime); } } }
7e814818b71eedea206d21e7ebe6d00524dea7fc
[ "C#" ]
13
C#
Ghurfa/ComputerVisionCamp
22abdb40a79bbb0b7d2f68c7abe50bf05856eb41
52b1cea84454ea72d97b67c306a1a7007389480f
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerOneMirrorMovement : MonoBehaviour { // Initialized public variables for use inside of the inspector public PlayerOneCharacterController2D controller; // Initialized variables // Variable for player run speed public float runSpeed = 100f; // Variable used for player movement left and right float horizontalMove = 0f; // Booleans for Jumping bool jump = false; // Boolean for Triple Speed Event public bool tripleSpeed = false; // Update is called once per frame void Update() { // Uses players input of A and D keys to move character in FixedUpdate horizontalMove = Input.GetAxisRaw("p1Horizontal") * -runSpeed; // Uses players input of SpaceBar to make the character Jump if (Input.GetButtonDown("P1Jump")) { jump = true; } // EVENTS TRIGGERED WHEN PLAYER SCORES A POINT // Triple Speed Event switch (tripleSpeed) { case false: runSpeed = 100f; break; case true: runSpeed = 300f; break; } } void FixedUpdate() { // Move our character controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump); // Disables jump so player cannot jump twice jump = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class currentPlatCol : MonoBehaviour { public PlatformManager PlatformManagerScript; bool playerOneGoal = false; bool playerTwoGoal = false; // Function makes booleans true when Player One or Player Two is colliding with the goal void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.tag == "PlayerOne") { playerOneGoal = true; } if (col.gameObject.tag == "PlayerTwo") { playerTwoGoal = true; } } // Function makes booleans false when Player One or Player Two stops colliding with goal void OnTriggerExit2D(Collider2D col) { if (col.gameObject.tag == "PlayerOne") { playerOneGoal = false; } if (col.gameObject.tag == "PlayerTwo") { playerTwoGoal = false; } } // If both the players are colliding with the goal, a new platform is selected and the player must reach that goal void Update() { if (playerTwoGoal == true && playerOneGoal == true) { PlatformManagerScript.NewPlatform(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformDrop : MonoBehaviour { float countDownTimer = 2f; bool playerEnter = false; public void StartOver() { countDownTimer = 0f; } // Update is called once per frame void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "PlayerOne") { playerEnter = true; } if (col.gameObject.tag == "PlayerTwo") { playerEnter = true; } } void OnCollisionExit2D(Collision2D collision) { countDownTimer = 0f; } void Update() { if (countDownTimer < -2f) { playerEnter = false; countDownTimer = 2f; } if (countDownTimer < 0f) { GetComponent<Renderer>().enabled = false; GetComponent<BoxCollider2D>().enabled = false; } if (playerEnter == true) { countDownTimer -= 1 * Time.deltaTime; } if (playerEnter == false) { GetComponent<Renderer>().enabled = true; GetComponent<BoxCollider2D>().enabled = true; } print(countDownTimer); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFlip : MonoBehaviour { public bool flipCamera = false; void Update() { switch (flipCamera) { case false: transform.eulerAngles = new Vector3(0, 0, 0f); break; case true: transform.eulerAngles = new Vector3(0, 0, 180f); break; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManagerScript : MonoBehaviour { public int points; // Start is called before the first frame update void Start() { points = 0; } public void AddPoint() { points += 1; print(points); } void Update() { switch (points) { case 0: break; case 1: print("Random Event Engaged"); break; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SlowMotion : MonoBehaviour { public float timeScale = 0.5f; public bool frozen = false; Rigidbody2D rb2d; float startMass; float startGravityScale; bool slowMoBool = true; void Awake() { rb2d = GetComponent<Rigidbody2D>(); startGravityScale = rb2d.gravityScale; startMass = rb2d.mass; } void FixedUpdate() { if (frozen) { SlowMo(); } else { StopSlowMo(); } } void SlowMo() { rb2d.gravityScale = 0.15f; if (slowMoBool) { rb2d.mass /= timeScale; rb2d.velocity *= timeScale; rb2d.angularVelocity *= timeScale; } slowMoBool = false; float dt = Time.fixedDeltaTime * timeScale; rb2d.velocity += Physics2D.gravity / rb2d.mass * dt; } void StopSlowMo() { if (!slowMoBool) { rb2d.gravityScale = startGravityScale; rb2d.mass = startMass; rb2d.velocity /= timeScale; rb2d.angularVelocity /= timeScale; } slowMoBool = true; } }<file_sep> using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class ClickSceneChange : MonoBehaviour { public float delay = 440; public string NewLevel= "TitleScreen"; void Start() { StartCoroutine(LoadLevelAfterDelay(delay)); } IEnumerator LoadLevelAfterDelay(float delay) { yield return new WaitForSeconds(delay); SceneManager.LoadScene(NewLevel); } void Update() { if(Input.anyKey) SceneManager.LoadScene(NewLevel); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformManager : MonoBehaviour { // Array setup for platforms GameObject[] platforms; GameObject currentPlatform; int index; public bool DropEvent = false; // GameObject for the collision of currently selected platform public GameObject currentPlatCol; // Start is called before the first frame update void Start() { platforms = GameObject.FindGameObjectsWithTag("platform"); // Creates an array of all objects with the tag platform index = Random.Range(0, platforms.Length); // randomly selects one platform currentPlatform = platforms[index]; // registers random platform as the one the player must get to print(currentPlatform.name); // Prints name for debug purposes currentPlatCol.transform.position = new Vector2 (currentPlatform.transform.position.x, currentPlatform.transform.position.y + .45f); // Moves collission to platform and adds height // to make it only reachable from the top } // Function repeats the process above public void NewPlatform() { index = Random.Range(0, platforms.Length); currentPlatform = platforms[index]; currentPlatCol.transform.position = new Vector2(currentPlatform.transform.position.x, currentPlatform.transform.position.y + .45f); } void Update() { switch (DropEvent) { case false: DropEventToggleOff(); break; case true: DropEventToggleOn(); break; } } void DropEventToggleOn() { platforms = GameObject.FindGameObjectsWithTag("platform"); // Creates an array of all objects with the tag platform for (int i = 0; i < platforms.Length; i++) { platforms[i].GetComponent<PlatformDrop>().enabled = true; } } void DropEventToggleOff() { platforms = GameObject.FindGameObjectsWithTag("platform"); // Creates an array of all objects with the tag platform for (int i = 0; i < platforms.Length; i++) { platforms[i].GetComponent<PlatformDrop>().StartOver(); platforms[i].GetComponent<Renderer>().enabled = true; platforms[i].GetComponent<BoxCollider2D>().enabled = true; platforms[i].GetComponent<PlatformDrop>().enabled = false; } } } <file_sep># GMTK-Jam-2020 Git for GMTK Game Jam 2020
29c0220af491ce4527e0288841ec2c6242003eed
[ "Markdown", "C#" ]
9
C#
OwenJAYEH/GMTK-Jam-2020
f1bad29e11414ec127ff50da12ab0383665dcabe
018284904780637a0f6f81347ecd0b2ad395a570
refs/heads/master
<file_sep># Tavla konsol oyun uygulamasi ## Projem hakkında ![resim](https://user-images.githubusercontent.com/52275789/123220159-57704f00-d4d6-11eb-89a3-1bb84de5aaf2.png) * İlk kimin başlayacağını öğrenmek için placement zarı atılır. (Zarlar aynı gelirse sistem otomatik olarak tekrar zar atar.) * Oyuncular ister zarın toplamını, ister tek tek zar oynayabilir. * Oyun tahtası sıra kimdeyse ona göre dönmektedir. ![resim](https://user-images.githubusercontent.com/52275789/123219727-e466d880-d4d5-11eb-953b-caead5ec8ad1.png) ![resim](https://user-images.githubusercontent.com/52275789/123222459-a5865200-d4d8-11eb-9e5f-d198f26d1251.png) <br/> Kırık taşlar "(#)" kolonunda saklanmaktadır. Kırık taşın varsa, kırık taşını oynamak zorundasın, # işaretiyle buradaki taşı oynayabilirsin. Eğer oynayamıyorsan geçerli hamlen yok deyip sırayı atlar.<br/> Toplanan taşlar "0" hanesinde toplanır. 0 yazarak oynayabilirsin. Eğer oyuncu 15 tane toplanan taşa sahip olursa oyunu kazanır.<br/> Projenin en önemli noktası, kayıt özelliği: * Atılan her zar text dosyasında kayıt altındadır. (**diceLog.txt**) * Oyun tahtasının şekli her tur hamlede kayıt altına alınmaktadır. (**Table.dat** // notepad ile açılabilmektedir.) Oyunun her hamlesi kayıt altına alındığından oyuncu dilediği gibi programı kapatsa da, tekrar oyunu açtığında, oyun kaldığı yerden devam eder. Yeni oyuna başlamak istenirse bunun için 999 yazması yeterlidir. Oyun standart tavla başlangıcına döner ve kayıt dosyaları sıfırlanarak yeni oyun kayıt edilmeye başlar. Devam edecek. <file_sep>package com.oguzcan.backgammon.controller; import java.io.FileWriter; import java.io.IOException; public class WriteFile { public static void writeBoard(String inputText) { try { FileWriter myWriter = new FileWriter("Table.dat"); myWriter.write(inputText); myWriter.close(); //System.out.println("Successfully wrote to the Table.dat file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } // isFirstTurn decides recreate file or append exiting file public static void writeDice(String inputText, boolean isFirstTurn) { try { FileWriter myWriter = new FileWriter("diceLog.txt", !isFirstTurn); myWriter.write(inputText); myWriter.close(); //System.out.println("Successfully wrote to the diceLog.text file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } <file_sep>package com.oguzcan.backgammon.models; import com.oguzcan.backgammon.controller.ReadFile; import java.util.ArrayList; import java.util.List; public class Board { public static final int MAX_LINES = 28; private List<Line> lines; public Board() { lines = new ArrayList<>(MAX_LINES); // 0 = black, 25 = white, 26 = white, 27 = black for (int i = 0; i < MAX_LINES; i++) { lines.add(new Line()); } } /** * Setup New Game * * @param player0 white * @param player1 black */ public void initNewGame(Player player0, Player player1) { for(int i=0; i<28; i++) { getLines().get(i).removeAllCheckersLine(); } // Player 0 White getLines().get(6).addCheckers(player0, 5); getLines().get(8).addCheckers(player0, 3); getLines().get(13).addCheckers(player0, 5); getLines().get(24).addCheckers(player0, 2); // Player 1 Black getLines().get(1).addCheckers(player1, 2); getLines().get(12).addCheckers(player1, 5); getLines().get(17).addCheckers(player1, 3); getLines().get(19).addCheckers(player1, 5); } public boolean initLoadGame(Player player0, Player player1) { List<String[]> list = ReadFile.readBoardFile(); // corrupted table file if(list.get(0)[0].equals("-999")) { return false; } System.out.println(); System.out.println(); System.out.println(); System.out.println(); System.out.println(); try { int[] whiteLines = convertToInt(list.get(0)); int[] blackLines = convertToInt(list.get(1)); addLiners(player0, whiteLines); addLiners(player1, blackLines); } catch (NumberFormatException e) { return false; } return true; } public Dice initLoadDice() { int[] dices = ReadFile.readDiceFile(); Dice tempDice = new Dice(); int playerId = ReadFile.getIsWhiteTurn() ? 0 : 1; tempDice.loadRoll(dices, playerId); return tempDice; } private int[] convertToInt(String[] list) { int[] iList = new int[list.length]; for (int i=0; i<list.length; i++) { iList[i] = Integer.parseInt(list[i]); } return iList; } // warning private void addLiners(Player player, int[] iList) { for (int j : iList) { getLines().get(j).addCheckersOneByOne(player); } } public List<Line> getLines() { return lines; } } <file_sep>package com.oguzcan.backgammon.models; import java.util.ArrayList; import java.util.List; public class Dice { private List<Integer> dice; // Contains 4 dice private boolean isDouble; // is double dice private boolean isFirstTurn; // Placement roll private int dicePoint; // Total playable dice point private String[] diceText; // Store dice // 0 = white // 1 = black public Dice() { dice = new ArrayList<>(); diceText = new String[]{"0 0", "0 0"}; } public void firstRoll() { int dice1, dice2; do { dice1 = (int) (6 * Math.random() + 1); dice2 = (int) (6 * Math.random() + 1); } while (dice1 == dice2); dice.add(dice1); dice.add(dice2); setDiceText(0); } public void loadRoll(int[] dices, int playerId) { dice.clear(); int dice1 = dices[0]; int dice2 = dices[1]; isDouble = dice1 == dice2; dicePoint = dice1 + dice2; dice.add(dice1); dice.add(dice2); if (isDouble) { dice.add(dice1); dice.add(dice2); } setDiceText(playerId); setDicePoint(); } // Standard Roll public void roll(int playerId) { dice.clear(); int dice1 = (int) (6 * Math.random() + 1); int dice2 = (int) (6 * Math.random() + 1); isDouble = dice1 == dice2; dicePoint = dice1 + dice2; dice.add(dice1); dice.add(dice2); if (isDouble) { dice.add(dice1); dice.add(dice2); } setDiceText(playerId); setDicePoint(); } private void setDiceText(int playerId) { if (isFirstTurn) { diceText[0] = dice.get(0) + " 0"; diceText[1] = dice.get(1) + " 0"; } else { diceText[playerId] = dice.get(0) + " " + dice.get(1); } } // Set sum of Player's dice public void setDicePoint() { dicePoint = 0; for (int temp : dice) dicePoint += temp; } public String getDiceText(int playerId) { return diceText[playerId]; } public int getDicePoint() { return dicePoint; } public int getDiceCount() { return dice.size(); } // Return List of Dice public List<Integer> getDice() { return dice; } public int[] getArrayDice() { int[] dices = new int[dice.size()]; for (int i = 0; i < dice.size(); i++) { dices[i] = dice.get(i); } return dices; } public boolean isDouble() { return isDouble; } public boolean isFirstTurn() { return isFirstTurn; } public void setFirstTurn(boolean isIt) { isFirstTurn = isIt; } }
c170ab11abbca0a9c3cbb14956baa3398f4241e8
[ "Markdown", "Java" ]
4
Markdown
Grotders/Backgammon
41fecdabf1f22b3cc287d271babceac6cd577f64
4393efc994d713a0dabeb90e5cbaef71eae6bbe1
refs/heads/master
<repo_name>laihaylike/nodejs-blog<file_sep>/src/app/controllers/ContentsController.js const Auth = require('../models/Auth'); const Content = require('../models/Content'); const { mutipleMongooseToObject, mongooseToObject } = require('../../util/mongoose'); class ContentsController { index(req, res, next) { var username; Auth.find( { _id: req.cookies.userId} ).lean() .then(auth => { if (auth){ username = auth } }) .catch() Content.find().sort({ '_id':-1 }).lean() .then(contents => { res.render('home', { contents: contents, username: username }); }) .catch(next) } upload(req, res, next){ res.render('upload'); } lupload(req, res, next){ req.body.avatar = req.file.path.split("\\").slice(1).join("/"); var i = { name: req.body.name, author: req.body.author, con: req.body.con, avatar: req.body.avatar, poster: req.cookies.userId } const content = Content(i); content.save() .then(() => res.redirect('/auths/show')) } estored(req, res, next){ Content.find({ poster: req.cookies.userId }).sort({ '_id':-1 }) .then(contents => res.render('estored', { contents: mutipleMongooseToObject(contents) })) .catch(next); } edit(req, res, next){ Content.findById(req.params.id) .then(contents => res.render('edit', { contents: mongooseToObject(contents) })) .catch(next); } update(req, res, next){ var ii = {}; if (req.files){ req.body.avatar = req.file.path.split("\\").slice(1).join("/"); ii = { name: req.body.name, author: req.body.author, con: req.body.con, avatar: req.body.avatar, poster: req.cookies.userId } }else { ii = { name: req.body.name, author: req.body.author, con: req.body.con, avatar: req.body.ii, poster: req.cookies.userId } } Content.updateOne({ _id: req.params.id }, ii) .then(() => res.redirect('estored')) .catch(next); } destroy(req, res, next){ Content.delete({ _id: req.params.id }) .then(() => res.redirect('back')) .catch(next); } trash(req, res, next){ Content.findDeleted({ poster: req.cookies.userId }).sort({ '_id':-1 }) .then(contents => res.render('trash', { contents: mutipleMongooseToObject(contents) })) .catch(next); } restore(req, res, next){ Content.restore({ _id: req.params.id }) .then(() => res.redirect('back')) .catch(next); } forceDestroy(req, res, next){ Content.deleteOne({ _id: req.params.id }) .then(() => res.redirect('back')) .catch(next); } showDetail(req, res, next){ Content.findOne( { slug: req.params.slug }) .then(content => res.render('showDetail', { content: mongooseToObject(content) })) } } module.exports = new ContentsController;<file_sep>/src/app/models/Content.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const mongooseDelete = require('mongoose-delete'); const slug = require('mongoose-slug-generator'); const Content = new Schema({ name: { type: String }, author: { type: String }, con: {type: String}, avatar: { type: String }, poster: { type: String }, slug: { type: String, slug:"name", unique: true} }, { timestamps: true, }); Content.plugin(mongooseDelete, { deleteAt: true, overrideMethods: 'all', }); module.exports = mongoose.model('Content', Content);<file_sep>/src/routes/auths.js const express = require('express'); const router = express.Router(); const authsController = require('../app/controllers/AuthsController'); const authsMiddleware = require('../app/middlewares/AuthsMiddleware'); router.get('/signup', authsController.signup); router.post('/store', authsController.store); router.get('/login', authsController.login); router.post('/lstore', authsController.lstore); router.get('/logout', authsController.logout); router.get('/show', authsMiddleware.requireAuth, authsController.show); module.exports = router;<file_sep>/src/routes/contents.js const express = require('express'); const multer = require('multer'); const router = express.Router(); const authsMiddleware = require('../app/middlewares/AuthsMiddleware'); const contentsController = require('../app/controllers/ContentsController'); var upload = multer({ dest: './public/uploads/' }) router.get('/upload', authsMiddleware.requireAuth, contentsController.upload); router.post('/lupload', upload.single('avatar'), contentsController.lupload); router.get('/estored', authsMiddleware.requireAuth, contentsController.estored); router.get('/:id/edit', authsMiddleware.requireAuth, contentsController.edit); router.put('/:id', upload.single('avatar'), contentsController.update); router.delete('/:id', contentsController.destroy); router.delete('/:id/force', contentsController.forceDestroy); router.patch('/:id/restore', contentsController.restore); router.get('/trash', authsMiddleware.requireAuth, contentsController.trash); router.get('/:slug', contentsController.showDetail); router.get('/', contentsController.index); module.exports = router;<file_sep>/public/javascripts/Home.js // //Thông báo hộp // window.alert("Welcome to the Book website -Thiên Bảo-"); // var x = myFunction(4,3); // function myFunction(a,b){ // return a + b; // } // BackToTop window.onscroll = function() { scrollFunction() }; function scrollFunction() { if ( document.documentElement.scrollTop > 400) { // document.getElementById("content").style.top = "0"; document.getElementById("BackToTop").style.opacity = "1"; document.getElementById("BackToTop").style.transition = "0.5s"; } else { // document.getElementById("content").style.top = "-70px"; document.getElementById("BackToTop").style.opacity = "0"; } } function topFunction() { // document.documentElement.scrollIntoView({block:'start', behavior: 'smooth'}); var currentScroll = document.documentElement.scrollTop || document.body.scrollTop; if (currentScroll > 0) { window.requestAnimationFrame(topFunction); window.scrollTo(0, currentScroll - (currentScroll / 5)); } // document.body.scrollTop = '0'; // document.documentElement.scrollTop = '0'; }<file_sep>/src/app/middlewares/AuthsMiddleware.js const Auth = require('../models/Auth'); const { mutipleMongooseToObject } = require('../../util/mongoose'); module.exports.requireAuth = function(req, res, next) { if (!req.cookies.userId) { res.redirect('/auths/login'); return; } Auth.find({ _id: req.cookies.userId }) .exec() .then(auth => { if (!auth) { res.redirect('/auths/login'); return; } next(); }) .catch() }<file_sep>/src/routes/index.js const contentsRouter = require('./contents'); const authsRouter = require('./auths'); function route(app) { app.use('/auths', authsRouter); app.use('/', contentsRouter); } module.exports = route;
b44106863de7afc699213fd2a726d778d5010fa7
[ "JavaScript" ]
7
JavaScript
laihaylike/nodejs-blog
7a35ded978747f6b3086999ac9b9a5159da6bd77
29114c55984073428e9b4f700a6265d342ee0c6b
refs/heads/master
<file_sep># mortargrind91.github.io hosting <file_sep><? if(isset($_POST['name'])){ $name = clean($_POST['name']); } if(isset($_POST['phone'])){ $phone = clean($_POST['phone']); } if(isset($_POST['mail'])){ $mail = clean($_POST['mail']); $mail = filter_var($mail, FILTER_VALIDATE_EMAIL); } if(isset($_POST['descr'])){ $descr = $_POST['descr']; } $to = "<EMAIL>"; $sendfrom = "<EMAIL>"; $headers = "From: " . strip_tags($sendfrom) . "\r\n"; $headers .= "Reply-To: ". strip_tags($sendfrom) . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html;charset=utf-8 \r\n"; $subject = "Заявка с сайта"; $message = "$formData <br> <b>Имя пославшего:</b> $name<br> <b>Email:</b> $mail<br> <b>Телефон:</b> $phone<br> <b>Сообщение:</b> $descr"; $send = mail ($to, $subject, $message, $headers); if ($send == 'true'){ echo '<center> <b class="send_msg">Спасибо, сообщение отправлено успешно!</b> </center>'; }else{ echo '<center> <b class="send_msg">Ошибка. Сообщение не отправлено!</b> </center>'; } function clean($val){ $val = trim($val); $val = stripslashes($val); $val = strip_tags($value); $val = htmlspecialchars($val); return $val; } ?> <file_sep>$(function () { /*reviews slider*/ $(".reviews-slider__box").slick({ slidesToShow: 1, slidesToScroll: 1, asNavFor: ".reviews-nav__box", fade: true, arrows: true, prevArrow: '<a id="prev" class="review-prew review-arr"><svg width="33" height="23" viewBox="0 0 33 23" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.834778 12.7623C0.248989 12.1765 0.248989 11.2268 0.834778 10.641L10.3807 1.09506C10.9665 0.509272 11.9163 0.509272 12.502 1.09506C13.0878 1.68085 13.0878 2.63059 12.502 3.21638L4.01676 11.7017L12.502 20.1869C13.0878 20.7727 13.0878 21.7225 12.502 22.3083C11.9163 22.894 10.9665 22.894 10.3807 22.3083L0.834778 12.7623ZM32.2802 13.2017H1.89544V10.2017H32.2802V13.2017Z"/></svg></a>', nextArrow: '<a id="next" class="review-next review-arr"><svg width="33" height="23" viewBox="0 0 33 23" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M32.3408 12.7623C32.9265 12.1765 32.9265 11.2268 32.3408 10.641L22.7948 1.09506C22.209 0.509272 21.2593 0.509272 20.6735 1.09506C20.0877 1.68085 20.0877 2.63059 20.6735 3.21638L29.1588 11.7017L20.6735 20.1869C20.0877 20.7727 20.0877 21.7225 20.6735 22.3083C21.2593 22.894 22.209 22.894 22.7948 22.3083L32.3408 12.7623ZM0.895386 13.2017H31.2801V10.2017H0.895386V13.2017Z"/></svg></a>' }); $(".reviews-nav__box").slick({ slidesToShow: 3, slidesToScroll: 1, asNavFor: ".reviews-slider__box", focusOnSelect: true, arrows: false }); /*end reviews slider*/ /*add red start & validate input*/ let $find_input = $(".placeinput input"); $find_input.on("focus", function () { let placeHolder = $(this).parent(".placeinput").find(".place_holder"); placeHolder.addClass("deletePlaceholder"); }); $find_input.on("blur", function () { let input_val = $(this).val(); let placeHolder = $(this).parent(".placeinput").find(".place_holder"); if (input_val.length == "") { placeHolder.removeClass("deletePlaceholder"); } }); /*end add red start & validate input*/ /*show more btn*/ let btn_read_more = $(".r-more"); let content = $(".r-content"); btn_read_more.on("click", function (e) { e.preventDefault(); let find_cotent = $(this).parent().siblings(content); find_cotent.toggleClass("show-content"); if (find_cotent.hasClass("show-content")) { let reducedHeight = find_cotent.height(); find_cotent.css('height', 'auto'); let fullHeight = find_cotent.height(); find_cotent.height(reducedHeight); find_cotent.animate({ height: fullHeight }, 500); $(this).text("Свернуть"); } else { find_cotent.animate({ height: "12.5vmax" }, 500); $(this).text("Читать еще"); } }); $(".review-arr, .reviews-slider__control").on("click", function () { let find_block = $(".review-content"); let btn = $(".show-more_reviews"); if (find_block.hasClass("show-content")) { btn.text("Читать еще"); find_block.removeClass("show-content"); find_block.animate({ height: "12.5vmax" }, 500); } }); /*end show more btn*/ // content.each(function () { // console.log($(this).height()); // if ($(this).height() > 240) { // $(this).parent().find(btn_read_more).show(); // } else { // $(this).parent().find(btn_read_more).hide(); // } // }); /*ajax send form*/ $('form').submit(function () { var formID = $(this).attr('id'); var formNm = $('#' + formID); console.log(formID); $.ajax({ type: 'POST', url: 'send.php', data: formNm.serialize(), success: function (data) { $(formNm).html(data); }, error: function (jqXHR, text, error) { $(formNm).html(error); } }); return false; }); /*end ajax send form*/ });<file_sep>function loaderCanvas(el, bubbleFillColor) { var blob = new paper.PaperScope(); blob.setup(el); var view = blob.view, Point = blob.Point, Path = blob.Path, Group = blob.Group; function Bacterium(center, radius, bubbleFillColor) { this.build(center, radius, bubbleFillColor); } Bacterium.prototype = { build: function (center, radius, bubbleFillColor) { var padding = Math.min(view.size.width, view.size.height) * 0.1; var timeScale = 1; var maxWidth = view.size.width - padding; var maxHeight = view.size.height - padding; var w = maxWidth * timeScale; var h = maxHeight * timeScale; this.fitRect = new Path.Rectangle({ point: [ view.size.width / 2 - w / 2, view.size.height / 2 - h / 2 ], size: [w, h] }); this.circlePath = new Path.Circle(center, radius); this.group = new Group([this.circlePath]); this.group.position = view.center; this.circlePath.fillColor = bubbleFillColor; this.circlePath.fullySelected = false; var rotationMultiplicator = radius / 200; this.threshold = radius; this.center = center; this.controlCircle = this.circlePath.clone(); this.controlCircle.fullySelected = false; this.controlCircle.visible = false; this.circlePath.flatten(radius * 0.5); this.circlePath.smooth(); this.circlePath.fitBounds(this.fitRect.bounds); this.settings = []; for (var i = 0; i < this.circlePath.segments.length; i++) { var segment = this.circlePath.segments[i]; this.settings[i] = { relativeX: segment.point.x - this.center.x, relativeY: segment.point.y - this.center.y, offsetX: rotationMultiplicator, offsetY: rotationMultiplicator, momentum: new Point(0, 0) }; } }, clear: function () { this.circlePath.remove(); this.fitRect.remove(); }, animate: function (event) { this.group.rotate(-1, view.center); for (var i = 0; i < this.circlePath.segments.length; i++) { var segment = this.circlePath.segments[i]; var settings = this.settings[i]; var controlPoint = new Point(settings.relativeX + this.center.x, settings.relativeY + this.center.y); controlPoint = this.controlCircle.segments[i].point; var newOffset = new Point(0, 0); newOffset = new Point(this.center._owner.width / this.center._owner.height * Math.floor(Math.random() * (2 - 1 + 1) + 1), this.center._owner.width / this.center._owner.height * Math.floor(Math.random() * (2 - 1 + 1) + 1)); var newPosition = controlPoint.add(newOffset); var distanceToNewPosition = segment.point.subtract(newPosition); settings.momentum = settings.momentum.subtract(distanceToNewPosition.divide(5)); settings.momentum = settings.momentum.multiply(0.2); var amountX = settings.offsetX; var amountY = settings.offsetY; var sinus = Math.sin(event.time + i * 1); var cos = Math.cos(event.time + i * 1); settings.momentum = settings.momentum.add(new Point(cos * -amountX * 2, sinus * -amountY * 2)); segment.point = segment.point.add(settings.momentum); } } }; var radius = Math.min(view.size.width, view.size.height) / 2.5; var bacterium = new Bacterium(view.bounds.center, radius, bubbleFillColor); view.onFrame = function (event) { bacterium.animate(event); }; } function loadBubbles(bubbles) { for (var i = 0; i < bubbles.length; i++) { var bubble = bubbles[i]; var bubbleFillColor = bubble.getAttribute('data-fill'); bubble.setAttribute('id', 'bubble-' + i); loaderCanvas(bubble.id, bubbleFillColor); } } window.onload = function () { loadBubbles(document.querySelectorAll('.bubble')); };
6489b90aeca115bba7436eb4908c03148c7487e8
[ "Markdown", "JavaScript", "PHP" ]
4
Markdown
MortarGrind91/mortargrind91.github.io
092d790eb7ec5fa574ea5488b521d7fc0a8cb76a
5a779dbebf94fcf00b476c602f5f284e7ab1e044
refs/heads/master
<file_sep> /* *Name:<NAME> *Project: 3 *Deadline: Mon Nov 17,2014 *Objective: To develop a floppy mini unix shell to mount and access floppy disk. *Class: (System Programing Unix/C/C++) CIS340 *University: Cleveland State university */ #include <stdio.h> #include <stdbool.h> #include "parentF.h" #include "minsc.h" #include "flshell.h" #include "flop.h" int main(int args, char *argv[]){ wipeTerminalScreen(); welcomeMessage(); char *cmd; char line[MAX_LENGTH]; char line2[MAX_LENGTH]; //char *floppyLoc; char floppyLoc[MAX_LENGTH] =""; bool isMounted = false; const char* fmloc; const char *arg; const char * ty; FILE * oImg; FILE *in; while (1) { char *p; // printf("flop: "); shellLabel(); if (!fgets(line, MAX_LENGTH, stdin)) break; strncpy(line2,line,MAX_LENGTH); // Parse and execute command if ((cmd = strtok(line, DELIMS))) { // Clear errors errno = 0; if (strcmp(cmd, "path") == 0 ) { execPath(line2); }else if (strcmp(cmd, "cd") == 0 ) { execchangeDir(line2); } else if (strcmp(cmd, "exit") == 0) { break; } else if(strcmp(line, "|") == 0) { exepipeParent(isMounted,line2,floppyLoc,in); } else{ // if command not in parent search child if (strcmp(cmd, "help") == 0) { help(line2); } else if (strcmp(cmd, "fmount") == 0) { if(isMounted){ printf("Mounted %s already, please unmount first to mount new floppy\n" ,floppyLoc); }else{ isMounted = true; char *fm; fm = strtok(line2," "); while(fm !=NULL){ if(strcmp(fm, "fmount") != 0){ //floppyLoc[0]='\0'; //strncat(floppyLoc,fm,sizeof(floppyLoc)); // floppyLoc =(char *)malloc(strlen(fm) + 1); strcpy(floppyLoc,fm); int i =0; sscanf (fm,"%s %*s %d",floppyLoc,&i); } fm= strtok(NULL," "); } printf("Mounting %s\n" ,floppyLoc); in = OpenFile(floppyLoc); load(in); floppyShell(isMounted,floppyLoc,in); } }else if (strcmp(cmd, "fumount") == 0) { if(isMounted && floppyLoc[0] !='\0'){ printf("UnMounted %s\n" ,floppyLoc); // *floppyLoc=0; isMounted = false; fclose(in); }else{ printf("Error:- Floppy Cannot UnMount because its not Mounted in the first place "); printf("\n"); } }else if (strcmp(cmd, "showsector") == 0) { printError(); }else if (strcmp(cmd, "traverse") == 0) { printError(); }else if (strcmp(cmd, "showfat") == 0) { printError(); }else if (strcmp(cmd, "showfile") == 0) { printError(); }else if (strcmp(cmd, "structure") == 0) { printError(); }else{ if(system(line2)!=0){ printf("Command does not exist, type help for available commands for floppy. Also only path and cd exist because this is Parent process"); if (errno) { perror("command failed"); } } printf("\n"); } } } } return 0; } <file_sep>#ifndef minsc_H_ /* Include guard */ #define minsc_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> void welcomeMessage() { printf("\n*******WELCOME TO SHELL(parent)*******\n"); printf("\nPlease go over the read me before using this shell\n"); } void welcomeMessageFlop() { printf("\n//*******WELCOME TO FLOPPY SHELL(child)*******\n"); printf("\nPlease go over the read me before using this shell\n"); } void shellLabel() { char cwd[1024]; if((getcwd(cwd, sizeof(cwd)))!=NULL){ getcwd(cwd, sizeof(cwd)); printf("[%s]shell$ ", cwd); } else{ perror("command failed"); } } void wipeTerminalScreen() { printf("\033[H\033[J"); } void printError() { printf("Error:- Please Mount Floppy first"); printf("\n"); } int equals(char * str1, char *str2) { int i; for (i = 0; i < strlen(str1); i++) { if (str1[i] != str2[i]) return 0; } return 1; } void help(char * line2){ if(strstr(line2,">") != NULL){ char *fm; fm = strtok(line2,"help >"); while(fm !=NULL){ // printf("test4 %s\n",fm ); if (fork() == 0) { // child int fd = open(fm, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); //fflush(stdout); close(out); //fflush(stderr); close(err); dup2(fd, 1); // make stdout go to file dup2(fd, 2); // make stderr go to file - you may choose to not do this printf("\n\nClient Environment Floppy Console\n\n"); printf("help: shows the commands supported in the floppy shell\n\n"); printf("fmount argument: mount a local floppy disk, where arguments is the floppy device path name, e.g, /dev/floppy\n\n"); printf("fumount: unmount the mounted floppy disk.\n\n"); printf("structure: to list the structure of the floppy disk.\n\n"); printf("traverse: list the content in the root directory.\n\n"); printf("showfat: show the content of the FAT tables.\n\n"); printf("showsector [sector number]: show the content of the specified sector number(516 bytes for each sector).\n\n"); printf("show file [filename]: show the content of the target file(in the hex dump)\n\n"); printf("Addtional Commands Path + , Path -\n\n"); close(fd); // fd no longer needed - the dup'ed handles are sufficient } fm= strtok(NULL," "); //showsector(fm); } }else if(strstr(line2,"<") != NULL){ }else{ printf("\n\nClient Environment Floppy Console\n\n"); printf("help: shows the commands supported in the floppy shell\n\n"); printf("fmount argument: mount a local floppy disk, where arguments is the floppy device path name, e.g, /dev/floppy\n\n"); printf("fumount: unmount the mounted floppy disk.\n\n"); printf("structure: to list the structure of the floppy disk.\n\n"); printf("traverse: list the content in the root directory.\n\n"); printf("showfat: show the content of the FAT tables.\n\n"); printf("showsector [sector number]: show the content of the specified sector number(516 bytes for each sector).\n\n"); printf("show file [filename]: show the content of the target file(in the hex dump)\n\n"); printf("(Parent) Addtional Commands Path,Path +(add path) , Path -(remove path)\n\n"); printf("(Parent) Addtional Commands Change directory cd \n\n"); } } #endif <file_sep>Project2: A Floppy Disk Shell (Due at 11:59:59pm on 11/15/2014 (EST)) New Group Arrangment. Questions? Please first check our FAQ link before you submit your inquiries. Based on the floppy disk program you have developed in project, you are asked to change the program to a floppy shell that supports Linux shell commands in addition to your existing floppy disk related commands. You are expected to use either C or C++ programming language. Your implementation must work on Linux machine in BU004b lab. Required Modules: (20 points) Your shell should repeatedly display a prompt and allow the user to enter a command to run. Your shell is supposed to read the input from system standard input, parse the line with command and arguments, and execute. You may want to use fork() and exec*() system calls. Your shell should find the build-in command (see part2) in your current working directory first. If not found, it should search the directories in the shell's pathname environment (see part2). You are not allowed to use system(), as it invokes the system's /bin/sh shell. You should not use execlp() or execvp(), because your shell has its own path variable (explained in part2). By convention, the command arguments are seperated by white spaces. Please describe your customized argument seperation rules in your README document if you have special arrangement (not recommended though). Your shell does not need to handle special characters, like ",", "?", "\", except the redirection operators (<, >) in part3 and the pipeline operator (|) required in part4. (30 points) In addition to those built-in commands you implemented in project2, implement the following two additional build-in commands (running in the main process rather than the child process) . cd: is a command, obviously, to change directories. You may want to use the chdir system call. path: is not only a command to show the current command searching pathnames (if no argument is provided), but also a utility to modify (either add or remove) the command searching pathnames. path (without arguments) displays the pathnames currently set. e.g., "/bin:/sbin" path + /abc/def appends the pathname "/abc/def" to the "path" variable. e.g., "/bin:/sbin:/abc/def". path - /abc/def removes the pathname "/abc/def" from the "path" variable. (30 points) Extend your shell with I/O redirection (<, >) You may want to use open(), close(), dup2() system calls. Please refer to Unix file descriptors for the mapping of stdin, stdout and stderr to 0, 1, 2. Your shell does not need to handle rediction for build-in commands: exit, cd, path. (20 points) Extend you shell with pipeline (|). Given the following command, $ cmd1 | cmd2 | cmd3 the standard output of cmd1 is connected to the standard input of cmd2, and the standard output of cmd2 is connected to the standard input of cmd3. You may want to use pipe() system call. You may assume at most two pipeline operators (|) in my test command while grading. Actually, it is easy to remove this assumption and your shell should handle unlimited number of "|"s. (10 points) This is optional (as a bonus) for undergrads, but is required for grads. Further extend your shell to support a mixture of pipelines and redirections like the following examples: $ cmd1 | cmd2 > file1 $ cmd1 < file1 | cmd2 > file2 Provide a Makefile so make command would produce the executable. Readme: you are required to write a README document (TXT only) that describes your project design detail and the execution sequence (with the commands). In particular, please explicitly state which part, if there is any, does not work and the possible reasons why that module does not work. For those working modules, please give a brief (in short) sample output. Submission: Create a folder with the name of your assigned group name, e.g., Group_A. Copy all source code files/directories into the created folder. Make sure you have sshed to grail.cba.csuohio.edu, and then type: $ turnin -c cis340w -p proj3 Group_A NOTES: Objective : To create a flop shell with commands to read from a floppy disk. Shell should have help, Fmount, Fumount, Structure,traverse,showfat,showsector,showfile, Output Redirection and quit. The Shell - uses a while(1) loop, then uses fgets to read chracters from stream, when it see a new line it stops reading. Fmount- mounts the floppy by assinging the variable to 'floppyLoc' Fumount- it clears out the 'floppyloc' Showsector- show the content of the specified sector number, so it uses the open function the read the interger contents into fseek then i used the while loop to arrange the content. Help - Show the help information to use the shell Structure - show the list of structure of floppydisk using fseek and fread to get the number of bytes of it s structure OutPut Redirection - works like Unix redirection. Path(parent) - to show the current command searching pathnames (if no argument is provided), but also a utility to modify (either add or remove) the command searching pathnames. cd(parent) - to change directories. pipe (| cmd | cmd |) - implement multiple commands at the sametime display their input . What Works: The Shell, Help, Fmount, Fumount, showsector, showfat, showfile, quit, OutPut and input Redirection , cd, *path, pipe (i.e | cmd | cmd |). What Work Partially: ** pipe question--> cmd | cmd does not work , you will have to this way--> | cmd | cmd | . What does not Work ** The Optional(bonus) question e.g cmd < file | cmd > file couldn't do this question. **Redirection does not work for fmount or fumount or quit. ** Pipe question won't work for quit, fmount , fumount. i.e quit | fmount -- won't work. How To Use It: **You have to fmount media/floppy.img for example before you can use any other commands, except help,path,cd,exit and quit. **Any other commands typed not given in class material will not work. <file_sep> #ifndef flop_H_ /* Include guard */ #define flop_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include "minsc.h" #include "parentF.h" #include <stdbool.h> //#include <sys/ #ifdef _WIN32 #include <windows.h> //#define chdir _chdir #else #include <unistd.h> #endif #define MAX_LENGTH 1024 #define DELIMS " \t\r\n" struct Fat12Entry *entry; struct Fat12Boot boot; char *finame = '\0'; FILE * OpenFile(char *name) { FILE * file; //finame = (char *)malloc(strlen(name) + 1); // strcpy(finame, name); if (!(file = fopen(name, "rb"))) { fprintf(stderr, "Unable to open %s. Exiting... \n", name); exit(1); } printf("Mounted %s\n" ,name); //fchmod(fileno(file), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH); return file; } struct Fat12Entry { unsigned char FILENAME[8]; unsigned char EXT[3]; unsigned char ATTRIBUTES[1]; unsigned char RESERVED[2]; unsigned short CREATION_TIME; unsigned short CREATION_DATE; unsigned short LAST_ACCESS_DATE; unsigned short MODIFY_TIME; unsigned short MODIFY_DATE; unsigned short START_CLUSTER; unsigned long FILE_SIZE; } Fat12Entry_t; struct Fat12Boot { unsigned int BYTES_PER_SECTOR; unsigned int SECTORS_PER_CLUSTER; unsigned int RESERVED_SECTORS; unsigned int NUM_OF_FATS; unsigned int MAX_ROOT_DIRS; unsigned int TOTAL_SECTORS; unsigned int SECTORS_PER_FAT; unsigned int SECTORS_PER_TRACK; unsigned int NUM_OF_HEADS; unsigned int VOLUME_ID; unsigned char VOLUME_LABEL; } Fat12Boot_t; void load(FILE * in) { fseek(in, 11, SEEK_SET); //skip 11 bytes //BYTES_PER_SECTOR (2 bytes) fread(&boot.BYTES_PER_SECTOR, 2, 1, in); //SECTORS_PER_CLUSTER (2 bytes) fread(&boot.SECTORS_PER_CLUSTER, 1, 1, in); //RESERVED_SECTORS (2 bytes) fread(&boot.RESERVED_SECTORS, 2, 1, in); //NUM_OF_FATS (1 byte) fread(&boot.NUM_OF_FATS, 1, 1, in); //MAX_ROOT_DIRS (2 bytes) fread(&boot.MAX_ROOT_DIRS, 2, 1, in); //Initialize 'entry' entry = (struct Fat12Entry *)malloc(sizeof(struct Fat12Entry) * boot.MAX_ROOT_DIRS); //TOTAL_SECTORS (2 bytes) fread(&boot.TOTAL_SECTORS, 2, 1, in); fseek(in, 1, SEEK_CUR); //skip 1 byte //SECTORS_PER_FAT (2 bytes) fread(&boot.SECTORS_PER_FAT, 2, 1, in); //SECTORS_PER_TRACK (2 bytes) fread(&boot.SECTORS_PER_TRACK, 2, 1, in); //NUM_OF_HEADS (2 bytes) fread(&boot.NUM_OF_HEADS, 2, 1, in); fseek(in, 11, SEEK_CUR); //skip 11 bytes //VOUME_ID (4 bytes) fread(&boot.VOLUME_ID, 4, 1, in); //VOLUME_LABEL fread(&boot.VOLUME_LABEL, 11, 1, in); //Move to beginning of ROOT DIRECTORY fseek(in, ((boot.NUM_OF_FATS * boot.SECTORS_PER_FAT) + 1) * boot.BYTES_PER_SECTOR, SEEK_SET); int i = 0; for (i = 0; i < boot.MAX_ROOT_DIRS; i++) { //FILENAME (8 bytes) fread(&entry[i].FILENAME, 8, 1, in); //EXT (3 bytes) fread(&entry[i].EXT, 3, 1, in); //ATTRIBUTES (1 byte) fread(&entry[i].ATTRIBUTES, 1, 1, in); //RESERVED (10 bytes) fread(&entry[i].RESERVED, 2, 1, in); //CREATION_TIME (2 bytes) fread(&entry[i].CREATION_TIME, 2, 1, in); //CREATION_DATE (2 bytes) fread(&entry[i].CREATION_DATE, 2, 1, in); //LAST_ACCESS_DATE (2 bytes) fread(&entry[i].LAST_ACCESS_DATE, 2, 1, in); fseek(in, 2, SEEK_CUR); //skip 2 bytes //MODIFY_TIME (2 bytes) fread(&entry[i].MODIFY_TIME, 2, 1, in); //MODIFY_DATE (2 bytes) fread(&entry[i].MODIFY_DATE, 2, 1, in); //START_CLUSTER (2 bytes) fread(&entry[i].START_CLUSTER, 2, 1, in); //FILE_SIZE (4 bytes) fread(&entry[i].FILE_SIZE, 4, 1, in); } } int num = 0; void showSector(FILE * in,char *line2) { if(strstr(line2,">") != NULL){ char *fm; fm = strtok(line2,"showsector"); while(fm !=NULL){ // printf("test4 %s\n",fm ); if (fork() == 0) { // child int fw = open(fm, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); //fflush(stdout); close(out); //fflush(stderr); close(err); dup2(fw, 1); // make stdout go to file dup2(fw, 2); // make stderr go to file - you may choose to not do this unsigned char in2; // Fat12BootSector pt; int i ; printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); char *sm; sm = strtok(line2," "); while(sm !=NULL){ if(strcmp(sm, "showsector") != 0){ int smi = atoi( sm ); fseek(in, boot.BYTES_PER_SECTOR * smi, SEEK_SET); for (i = 0; i < boot.BYTES_PER_SECTOR; i++) { if (i % 16 == 0 || i == 0) { printf("\n"); printf("%4x", i); } fread(&in2, 1, 1, in); printf("%5x", in2); } printf("\n"); } sm= strtok(NULL," "); } close(fw); // fd no longer needed - the dup'ed handles are sufficient } fm= strtok(NULL," "); } }else if(strstr(line2,"<") != NULL){ } else{ unsigned char in2; // Fat12BootSector pt; int i ; printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); char *sm; sm = strtok(line2," "); while(sm !=NULL){ if(strcmp(sm, "showsector") != 0){ int smi = atoi( sm ); fseek(in, boot.BYTES_PER_SECTOR * smi, SEEK_SET); for (i = 0; i < boot.BYTES_PER_SECTOR; i++) { if (i % 16 == 0 || i == 0) { printf("\n"); printf("%4x", i); } fread(&in2, 1, 1, in); printf("%5x", in2); } printf("\n"); } sm= strtok(NULL," "); } } } void structure(FILE * in,char * line2){ if(strstr(line2,">") != NULL){ char *fm; fm = strtok(line2,"structure -l >"); while(fm !=NULL){ //if(strcmp(fm, "") != 0){ // char fname[100]; // printf("Enter floppy Image Location: \n"); // scanf("%s", fname);// i used this because i could not get fopen to work with fmount media/floppy.img if (fork() == 0) { // child int fd = open(fm, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); //fflush(stdout); close(out); //fflush(stderr); close(err); dup2(fd, 1); // make stdout go to file dup2(fd, 2); // make stderr go to file - you may choose to not do this //FILE * in = fopen(fname, "rb"); // FILE *in; // in = OpenFile(floppyLoc); int i; for(i=0; i<boot.NUM_OF_FATS; i++) { printf("Number of Fat: %d\n", boot.NUM_OF_FATS); printf("Number of Sectors used by FAT: %d\n", boot.NUM_OF_FATS); printf("Number of Sector Per Clusters: %d\n", boot.SECTORS_PER_FAT); printf("Number of Root Entries: %d\n", boot.MAX_ROOT_DIRS); printf("Number of bytes Per sector: %d\n", boot.BYTES_PER_SECTOR); printf(" ---Sector #--- ---Sector Types---\n"); printf(" 0 BOOT\n"); printf(" %02d -- %02d FAT%d\n", (boot.SECTORS_PER_FAT * i) + 1,boot.SECTORS_PER_FAT * (i + 1), i); printf(" %02d -- %02d ROOT DIRECTORY\n", boot.SECTORS_PER_FAT * boot.NUM_OF_FATS, (boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS)); } close(fd); // fd no longer needed - the dup'ed handles are sufficient } // } fm= strtok(NULL," "); } }else{ // char fname[100]; // printf("Enter floppy Image Location: \n"); // scanf("%s", floppyLoc);// i used this because i could not get fopen to work with fmount media/floppy.img //FILE * in = fopen(fname, "rb"); // FILE *in; // in = OpenFile(floppyLoc); int i; for(i=0; i<boot.NUM_OF_FATS; i++) { printf("Number of Fat: %d\n", boot.NUM_OF_FATS); printf("Number of Sectors used by FAT: %d\n", boot.NUM_OF_FATS); printf("Number of Sector Per Clusters: %d\n", boot.SECTORS_PER_FAT); printf("Number of Root Entries: %d\n", boot.MAX_ROOT_DIRS); printf("Number of bytes Per sector: %d\n", boot.BYTES_PER_SECTOR); printf(" ---Sector #--- ---Sector Types---\n"); printf(" 0 BOOT\n"); printf(" %02d -- %02d FAT%d\n", (boot.SECTORS_PER_FAT * i) + 1,boot.SECTORS_PER_FAT * (i + 1), i); printf(" %02d -- %02d ROOT DIRECTORY\n", boot.SECTORS_PER_FAT * boot.NUM_OF_FATS, (boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS)); } } } void traverse(char * line2){ if(strstr(line2,">") != NULL){ char *fm; fm = strtok(line2,"traverse >"); while(fm !=NULL){ if (fork() == 0) { // child int fd = open(fm, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); //fflush(stdout); close(out); //fflush(stderr); close(err); dup2(fd, 1); // make stdout go to file dup2(fd, 2); // make stderr go to file - you may choose to not do this printf(" *****************************\n"); printf(" ** FILE ATTRIBUTE NOTATION **\n"); printf(" ** **\n"); printf(" ** R ------ READ ONLY FILE **\n"); printf(" ** S ------ SYSTEM FILE **\n"); printf(" ** H ------ HIDDEN FILE **\n"); printf(" ** A ------ ARCHIVE FILE **\n"); printf(" *****************************\n"); printf("\n"); int i=0; while(i < boot.MAX_ROOT_DIRS) { if (entry[i].FILENAME[0] != 0x00 && entry[i].START_CLUSTER != 0) { char attr[6] = {'-', '-', '-', '-', '-'}; unsigned char a = entry[i].ATTRIBUTES[0]; if (a == 0x01) attr[0] = 'R'; if (a == 0x02) attr[1] = 'H'; if (a == 0x04) attr[2] = 'S'; if (a == 0x20) attr[5] = 'A'; if (a == 0x10) { int j= 0; while(j < 6){ attr[j] = '-'; j++; } } if (entry[i].ATTRIBUTES[0] == 0x10) { printf("%.6s %d %d < DIR > /%.8s %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER); printf("%.6s %d %d < DIR > /%.8s/. %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER); printf("%.6s %d %d < DIR > /%.8s/.. %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, 0); } else { printf("%.6s %d %d %lu /%.8s.%.3s %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILE_SIZE, entry[i].FILENAME, entry[i].EXT, entry[i].START_CLUSTER); } } i++; } close(fd); // fd no longer needed - the dup'ed handles are sufficient } fm= strtok(NULL," "); } } else if(strstr(line2,"<") != NULL){ }else if(strstr(line2,"l") != NULL){ printf(" *****************************\n"); printf(" ** FILE ATTRIBUTE NOTATION **\n"); printf(" ** **\n"); printf(" ** R ------ READ ONLY FILE **\n"); printf(" ** S ------ SYSTEM FILE **\n"); printf(" ** H ------ HIDDEN FILE **\n"); printf(" ** A ------ ARCHIVE FILE **\n"); printf(" *****************************\n"); printf("\n"); int i=0; while(i < boot.MAX_ROOT_DIRS) { if (entry[i].FILENAME[0] != 0x00 && entry[i].START_CLUSTER != 0) { char attr[6] = {'-', '-', '-', '-', '-'}; unsigned char a = entry[i].ATTRIBUTES[0]; if (a == 0x01) attr[0] = 'R'; if (a == 0x02) attr[1] = 'H'; if (a == 0x04) attr[2] = 'S'; if (a == 0x20) attr[5] = 'A'; if (a == 0x10) { int j= 0; while(j < 6){ attr[j] = '-'; j++; } } if (entry[i].ATTRIBUTES[0] == 0x10) { printf("%.6s %d %d < DIR > /%.8s %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER); printf("%.6s %d %d < DIR > /%.8s/. %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER); printf("%.6s %d %d < DIR > /%.8s/.. %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, 0); } else { printf("%.6s %d %d %lu /%.8s.%.3s %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILE_SIZE, entry[i].FILENAME, entry[i].EXT, entry[i].START_CLUSTER); } } i++; } } else{ int i; char attr[6] = {'-', '-', '-', '-', '-'}; for (i = 0; i < boot.MAX_ROOT_DIRS; i++) { if (entry[i].FILENAME[0] != 0x00 && entry[i].START_CLUSTER != 0) { if (entry[i].ATTRIBUTES[0] == 0x10) { printf("/%.8s < DIR >\n", entry[i].FILENAME); printf("/%.8s/. < DIR >\n", entry[i].FILENAME); printf("/%.8s/.. < DIR >\n", entry[i].FILENAME); } else { printf("/%.8s.%.3s\n", entry[i].FILENAME, entry[i].EXT); } } } } } void showfat(char * floppyLoc,char * line2) { if(strstr(line2,">") != NULL){ char *fm; fm = strtok(line2,"showfat >"); while(fm !=NULL){ // printf("test4 %s\n",fm ); if (fork() == 0) { // child int fw = open(fm, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); //fflush(stdout); close(out); //fflush(stderr); close(err); dup2(fw, 1); // make stdout go to file dup2(fw, 2); // make stderr go to file - you may choose to not do this printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); unsigned char buff[512]; int fd = open(floppyLoc, O_RDONLY); lseek(fd,512*512,512*512); read(fd,buff,512); int i=0; int k=0; while(i<512){ int j=0; while (j<16){ printf("%02x ", buff[k]); j++; k++; } printf("\n"); i++; } close(fw); // fd no longer needed - the dup'ed handles are sufficient } fm= strtok(NULL," "); } }else if(strstr(line2,"<") != NULL){ }else{ printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); unsigned char buff[512]; int fd = open(floppyLoc, O_RDONLY); lseek(fd,512*512,512*512); read(fd,buff,512); int i=0; int k=0; while(i<512){ int j=0; while (j<16){ printf("%02x ", buff[k]); j++; k++; } printf("\n"); i++; } } } void showfile(FILE * in,char *line2) { if(strstr(line2,">") != NULL){ char *fm; fm = strtok(line2,"help >"); while(fm !=NULL){ // printf("test4 %s\n",fm ); if (fork() == 0) { // child int fd = open(fm, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); char *fm; fm = strtok(line2," "); while(fm !=NULL){ char *filename = '\0'; char *ext = '\0'; char *full_filename; char *p; //Parse filename p = strtok(fm, "."); if (p) filename = p; //Parse extension p = strtok(NULL, "."); if (p) ext = p; full_filename = (char *)malloc(strlen(filename) + strlen(ext) + 1); strcpy(full_filename, filename); strcat(full_filename, ext); int i; for (i = 0; i < boot.MAX_ROOT_DIRS; i++) { if (entry[i].FILENAME != 0x00 && entry[i].START_CLUSTER != 0) { //Ignore invalid files if(equals(full_filename, (char *)entry[i].FILENAME)) { unsigned char in2; //Move to the first byte of the file fseek(in, ((boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS) - 1) + (boot.BYTES_PER_SECTOR * entry[i].START_CLUSTER), SEEK_SET); int j; printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); for (j = 0; j < entry[i].FILE_SIZE; j++) { if (j % 16 == 0 || j == 0) { printf("\n"); printf("%4x", j); } fread(&in2, 1, 1, in); printf("%5x", in2); } printf("\n"); } } } fm= strtok(NULL," "); } close(fd); // fd no longer needed - the dup'ed handles are sufficient } fm= strtok(NULL," "); //showsector(fm); } }else if(strstr(line2,"<") != NULL){ }else{ char *fm; fm = strtok(line2," "); while(fm !=NULL){ char *filename = '\0'; char *ext = '\0'; char *full_filename; char *p; //Parse filename p = strtok(fm, "."); if (p) filename = p; //Parse extension p = strtok(NULL, "."); if (p) ext = p; full_filename = (char *)malloc(strlen(filename) + strlen(ext) + 1); strcpy(full_filename, filename); strcat(full_filename, ext); int i; for (i = 0; i < boot.MAX_ROOT_DIRS; i++) { if (entry[i].FILENAME != 0x00 && entry[i].START_CLUSTER != 0) { //Ignore invalid files if(equals(full_filename, (char *)entry[i].FILENAME)) { unsigned char in2; //Move to the first byte of the file fseek(in, ((boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS) - 1) + (boot.BYTES_PER_SECTOR * entry[i].START_CLUSTER), SEEK_SET); int j; printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\n"); for (j = 0; j < entry[i].FILE_SIZE; j++) { if (j % 16 == 0 || j == 0) { printf("\n"); printf("%4x", j); } fread(&in2, 1, 1, in); printf("%5x", in2); } printf("\n"); } } } fm= strtok(NULL," "); } } } void exepipelineChild(bool isMounted,char line2[],char * floppyLoc,FILE * in){ char *fm; fm = strtok(line2," | "); while(fm !=NULL){ if (strcmp(fm, "help") == 0) { help(line2); }else if (strcmp(fm, "showsector") == 0) { if(isMounted){ showSector(in,line2); }else{ printError(); } }else if (strcmp(fm, "structure") == 0 ) { if(isMounted){ structure(in,line2); }else{ printError(); } }else if (strcmp(fm, "traverse") == 0 ) { if(isMounted){ traverse(line2); }else{ printError(); } }else if (strcmp(fm, "showfat") == 0 ) { if(isMounted){ showfat(floppyLoc,line2); }else{ printError(); } }else if (strcmp(fm, "showfile") == 0 ) { if(isMounted){ structure(in,line2); }else{ printError(); } } fm= strtok(NULL," | "); } } #endif <file_sep>#ifndef parentF_H_ /* Include guard */ #define parentF_H_ #include <stdio.h> #include <stdbool.h> #include <string.h> #include "flop.h" void execPath(char * line2){ char *cwd_f; if (getenv("PATH") != NULL){ cwd_f = getenv("PATH"); if(strstr(line2,"+") != NULL){ char *fm; fm = strtok(line2,"+ "); while(fm !=NULL){ if(strcmp(fm, "path") != 0){ if(strstr(fm,"+") == NULL){ strcat(cwd_f, ":"); strcat(cwd_f,fm); } } fm= strtok(NULL," "); } setenv("PATH", cwd_f, 1); fprintf(stdout, "%s\n", cwd_f); }else if(strstr(line2,"-") != NULL){ char *fm; fm = strtok(line2,"- "); char *path; while(fm !=NULL){ if(strcmp(fm, "path") != 0){ if(strstr(fm,"-") == NULL){ path = (char *)malloc((sizeof(char) * strlen(getenv("PATH"))) - (sizeof(char) * strlen(fm))); printf("testminus%s\n",fm); int i = 0; char *p; for (i = 0, p = strtok(getenv("PATH"), ":"); p != NULL; i++, p = strtok(NULL, ":")) { if (strcmp(p, fm) == 0) { continue; } else { if (i != 0) { strcat(path, ":"); } strcat(path, p); } } } } fm= strtok(NULL," "); } setenv("PATH", path, 1); fprintf(stdout, "%s\n", path); }else{ printf("%s\n",getenv("PATH")); } } } void execchangeDir(char * line2){ //printf("Change Directory Command under construction\n"); if(strstr(line2," ") != NULL){ char *chgdir; char *fm; fm = strtok(line2," "); while(fm !=NULL){ chgdir = fm; int i =1; sscanf (fm,"%s %*s %d",chgdir,&i); fm= strtok(NULL," "); } //strcpy(chgdir,fm); int check; //printf("dirstuff%s\n", chgdir); check = chdir(chgdir); if(check !=0){ perror("Error:"); }else{ //setenv("PATH", chgdir, 1); } }else{ chdir(getenv("HOME")); } } void exepipeParent(bool isMounted,char line2[],char * floppyLoc,FILE * in){ char *fm; fm = strtok(line2," | "); while(fm !=NULL){ if (strcmp(fm, "help") == 0) { help(line2); }if (strcmp(fm, "path") == 0) { execPath(line2); }else if (strcmp(fm, "cd") == 0 ) { execchangeDir(line2); }else{ exepipelineChild(isMounted,line2,floppyLoc,in);// execute | | command for child if command not in parent } fm= strtok(NULL," | "); } } #endif <file_sep>#ifndef flshell_H_ /* Include guard */ #define flshell_H_ #include <stdio.h> #include <stdbool.h> #include "minsc.h" #include "flop.h" #include "parentF.h" void floppyShell(bool isMounted,char floppyLoc[MAX_LENGTH], FILE *in){ welcomeMessageFlop(); char *cmd; char line[MAX_LENGTH]; char line2[MAX_LENGTH]; //char *floppyLoc; //char floppyLoc[MAX_LENGTH] =""; //bool isMounted = false; const char* fmloc; const char *arg; const char * ty; // FILE *in; while (1) { char *p; printf("flop: "); if (!fgets(line, MAX_LENGTH, stdin)) break; strncpy(line2,line,MAX_LENGTH); // Parse and execute command if ((cmd = strtok(line, DELIMS))) { // Clear errors errno = 0; if (strcmp(cmd, "help") == 0) { help(line2); } if (strcmp(cmd, "fmount") == 0) { if(isMounted){ printf("Mounted %s already, please unmount first to mount new floppy\n" ,floppyLoc); }else{ isMounted = true; char *fm; fm = strtok(line2," "); while(fm !=NULL){ if(strcmp(fm, "fmount") != 0){ //floppyLoc[0]='\0'; //strncat(floppyLoc,fm,sizeof(floppyLoc)); // floppyLoc =(char *)malloc(strlen(fm) + 1); strcpy(floppyLoc,fm); int i =0; sscanf (fm,"%s %*s %d",floppyLoc,&i); } fm= strtok(NULL," "); } printf("Mounting %s\n" ,floppyLoc); in = OpenFile(floppyLoc); load(in); } } else if (strcmp(cmd, "fumount") == 0) { if(isMounted && floppyLoc[0] !='\0'){ printf("UnMounted %s\n" ,floppyLoc); // *floppyLoc=0; isMounted = false; fclose(in); break; }else{ printf("Error:- Floppy Cannot UnMount because its not Mounted in the first place "); printf("\n"); } }else if (strcmp(cmd, "showsector") == 0) { if(isMounted){ showSector(in,line2); }else{ printError(); } }else if (strcmp(cmd, "structure") == 0 ) { if(isMounted){ structure(in,line2); }else{ printError(); } }else if (strcmp(cmd, "traverse") == 0 ) { if(isMounted){ traverse(line2); }else{ printError(); } }else if (strcmp(cmd, "showfat") == 0 ) { if(isMounted){ showfat(floppyLoc,line2); }else{ printError(); } }else if (strcmp(cmd, "showfile") == 0 ) { if(isMounted){ structure(in,line2); }else{ printError(); } }else if(strstr(line,"|") != NULL) { exepipelineChild(isMounted,line2,floppyLoc,in);// execute | | command for child } else if (strcmp(cmd, "quit") == 0) { break; } else{ break; if (strcmp(cmd, "path") == 0 ) { execPath(line2); }else if (strcmp(cmd, "cd") == 0 ) { execchangeDir(line2); } printf("\n"); } } } } #endif
2be5391931ce7f5762539b8e91f8c91160502fad
[ "Markdown", "C" ]
6
C
ikp4success/Unix-and-FloppyShell
b3e59f9359b110fa7d65ddf550153d44f2124357
89df937b1057c807aebc42891ab98a0f914db943
refs/heads/master
<repo_name>thegreatshasha/analysis<file_sep>/temporal_plot.py import numpy as np import matplotlib.pyplot as plt from utilities import * from paircorrelation import pairCorrelationFunction_2D import numpy as np import matplotlib.pyplot as plt import glob """ Generic plotting stream code. Leave it like this """ plt.ion() fig = plt.figure(figsize=(5,15)) #plt.xlim( (0, 5) ) #plt.ylim( (0, 5))#1.05 * g_r.max()) ) ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) #ax = fig.add_subplot(111) plt.show() detection_files = sorted(glob.glob('detections_csv/*')) size_max = 2000.0 r_max = size_max/4 dr = 10.0 densities = range(10,2000,10) for data_file in detection_files: data = np.loadtxt(data_file, delimiter=',') ax1.text(200, 2200, 'density %s'%data_file, style='italic') x = data[:,0] y = data[:,1] g_r, r, reference_indices = pairCorrelationFunction_2D(x, y, size_max, r_max, dr) ax1.set_xlim((200,2500)) ax1.set_ylim((200,2500)) ax2.set_xlabel('r') ax2.set_ylabel('g(r)') ax2.set_xlim((0,r_max)) ax2.set_ylim((0,10)) #g_r, r, reference_indices = pairCorrelationFunction_2D(x, y, 20.0, 5, 0.1) #ax.scatter(x,y) ax1.scatter(x,y) ax2.plot(r, g_r, color='black') plt.pause(0.5) ax1.cla() ax2.cla() #plot_adsorbed_circles(x, y, 0.1, 20, reference_indices=reference_indices) <file_sep>/test_plotting.py import matplotlib.pyplot as plt import numpy as np plt.ion() fig = plt.figure() plt.show() data = np.loadtxt('detections_csv/vid15_3500.csv', delimiter=',') x = data[:,0] y = data[:,1] ax1 = fig.add_subplot(212) ax2 = fig.add_subplot(222) ax1.scatter(x,y, c='black') ax2.scatter(x,y, c='green') plt.pause(0.5) plt.cla()
6748c216696635879d655495859427c1df8aabb1
[ "Python" ]
2
Python
thegreatshasha/analysis
19d0548f77946f272be6f341c762e3022b74a7de
a970543df0af5da18ebd82ab15c214802bb19665
refs/heads/main
<file_sep># # ItemConditionPolicy ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category_id** | **string** | The category ID to which the item-condition policy applies. | [optional] **category_tree_id** | **string** | A value that indicates the root node of the category tree used for the response set. Each marketplace is based on a category tree whose root node is indicated by this unique category ID value. All category policy information returned by this call pertains to the categories included below this root node of the tree. A category tree is a hierarchical framework of eBay categories that begins at the root node of the tree and extends to include all the child nodes in the tree. Each child node in the tree is an eBay category that is represented by a unique categoryId value. Within a category tree, the root node has no parent node and leaf nodes are nodes that have no child nodes. | [optional] **item_condition_required** | **bool** | This flag denotes whether or not you must list the item condition in a listing for the specified category. If set to true, you must specify an item condition for the associated category. | [optional] **item_conditions** | [**\Ebay\Sell\Metadata\Model\ItemCondition[]**](ItemCondition.md) | The item-condition values allowed in the category. Note: In all eBay marketplaces, Condition ID 2000 now maps to an item condition of &#39;Certified Refurbished&#39;, and not &#39;Manufacturer Refurbished&#39;. To list an item as &#39;Certified Refurbished&#39;, a seller must be pre-qualified by eBay for this feature. Any seller who is not eligible for this feature will be blocked if they try to create a new listing or revise an existing listing with this item condition. Any active listings on any eBay marketplace that had &#39;Manufacturer Refurbished&#39; as the item condition should have been automatically updated by eBay to the &#39;Seller Refurbished&#39; item condition (Condition ID 2500). Any seller that is interested in eligibility requirements to list with &#39;Certified Refurbished&#39; should see the Certified refurbished program page in Seller Center. | [optional] [[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) <file_sep># Ebay\Sell\Metadata\MarketplaceApi All URIs are relative to https://api.ebay.com/sell/metadata/v1. Method | HTTP request | Description ------------- | ------------- | ------------- [**getAutomotivePartsCompatibilityPolicies()**](MarketplaceApi.md#getAutomotivePartsCompatibilityPolicies) | **GET** /marketplace/{marketplace_id}/get_automotive_parts_compatibility_policies | [**getItemConditionPolicies()**](MarketplaceApi.md#getItemConditionPolicies) | **GET** /marketplace/{marketplace_id}/get_item_condition_policies | [**getListingStructurePolicies()**](MarketplaceApi.md#getListingStructurePolicies) | **GET** /marketplace/{marketplace_id}/get_listing_structure_policies | [**getNegotiatedPricePolicies()**](MarketplaceApi.md#getNegotiatedPricePolicies) | **GET** /marketplace/{marketplace_id}/get_negotiated_price_policies | [**getProductAdoptionPolicies()**](MarketplaceApi.md#getProductAdoptionPolicies) | **GET** /marketplace/{marketplace_id}/get_product_adoption_policies | [**getReturnPolicies()**](MarketplaceApi.md#getReturnPolicies) | **GET** /marketplace/{marketplace_id}/get_return_policies | ## `getAutomotivePartsCompatibilityPolicies()` ```php getAutomotivePartsCompatibilityPolicies($marketplace_id, $filter): \Ebay\Sell\Metadata\Model\AutomotivePartsCompatibilityPolicyResponse ``` This method returns the eBay policies that define how to list automotive-parts-compatibility items in the categories of a specific marketplace. By default, this method returns the entire category tree for the specified marketplace. You can limit the size of the result set by using the filter query parameter to specify only the category IDs you want to review. Tip: This method can return a very large response payload and we strongly recommend you get the results from this call in a GZIP file by including the following HTTP header with your request: &nbsp;&nbsp;Accept-Encoding: application/gzip ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: Client Credentials $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); $apiInstance = new Ebay\Sell\Metadata\Api\MarketplaceApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $marketplace_id = 'marketplace_id_example'; // string | This path parameter specifies the eBay marketplace for which policy information is retrieved. Note: Only the following eBay marketplaces support automotive parts compatibility: EBAY_US EBAY_AU EBAY_CA EBAY_DE EBAY_ES EBAY_FR EBAY_GB EBAY_IT $filter = 'filter_example'; // string | This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character ('|'). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter=categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &nbsp;&nbsp;filter=categoryIds%3A%7B100%7C101%7C102%7D try { $result = $apiInstance->getAutomotivePartsCompatibilityPolicies($marketplace_id, $filter); print_r($result); } catch (Exception $e) { echo 'Exception when calling MarketplaceApi->getAutomotivePartsCompatibilityPolicies: ', $e->getMessage(), PHP_EOL; } ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **marketplace_id** | **string**| This path parameter specifies the eBay marketplace for which policy information is retrieved. Note: Only the following eBay marketplaces support automotive parts compatibility: EBAY_US EBAY_AU EBAY_CA EBAY_DE EBAY_ES EBAY_FR EBAY_GB EBAY_IT | **filter** | **string**| This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character (&#39;|&#39;). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter&#x3D;categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &amp;nbsp;&amp;nbsp;filter&#x3D;categoryIds%3A%7B100%7C101%7C102%7D | [optional] ### Return type [**\Ebay\Sell\Metadata\Model\AutomotivePartsCompatibilityPolicyResponse**](../Model/AutomotivePartsCompatibilityPolicyResponse.md) ### Authorization [Client Credentials](../../README.md#Client Credentials) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: `application/json` [[Back to top]](#) [[Back to API list]](../../README.md#endpoints) [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) ## `getItemConditionPolicies()` ```php getItemConditionPolicies($marketplace_id, $filter): \Ebay\Sell\Metadata\Model\ItemConditionPolicyResponse ``` This method returns item condition metadata on one, multiple, or all eBay categories on an eBay marketplace. This metadata consists of the different item conditions (with IDs) that an eBay category supports, and a boolean to indicate if an eBay category requires an item condition. The identifier of the eBay marketplace is passed in as a path parameter, and unless one or more eBay category IDs are passed in through the filter query parameter, this method will return metadata on every single category for the specified marketplace. If you only want to view item condition metadata for one eBay category or a select group of eBay categories, you can pass in up to 50 eBay category ID through the filter query parameter. Important!: Certified Refurbished-eligible sellers must use an OAuth token created with the authorization code grant flow and https://api.ebay.com/oauth/api_scope/sell.inventory scope in order to retrieve the 'Certified Refurbished' condition (condition ID 2000) for the relevant categories. The Certified Refurbished item condition will not be returned if an OAuth token created with the client credentials grant flow and https://api.ebay.com/oauth/api_scope scope is used, or if any seller is not eligible to list with that item condition. See the Specifying OAuth scopes topic for more information about specifying scopes. Tip: If you retrieve metadata on all eBay categories for a marketplace, the response payload can be quite large. For this reason, we suggest that you consider using the Accept-Encoding request header and set its value to application/gzip. By doing this, the response payload output will be compressed into a GZIP file. ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: Authorization Code $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); // Configure OAuth2 access token for authorization: Client Credentials $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); $apiInstance = new Ebay\Sell\Metadata\Api\MarketplaceApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $marketplace_id = 'marketplace_id_example'; // string | This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. $filter = 'filter_example'; // string | This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character ('|'). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter=categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &nbsp;&nbsp;filter=categoryIds%3A%7B100%7C101%7C102%7D try { $result = $apiInstance->getItemConditionPolicies($marketplace_id, $filter); print_r($result); } catch (Exception $e) { echo 'Exception when calling MarketplaceApi->getItemConditionPolicies: ', $e->getMessage(), PHP_EOL; } ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **marketplace_id** | **string**| This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. | **filter** | **string**| This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character (&#39;|&#39;). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter&#x3D;categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &amp;nbsp;&amp;nbsp;filter&#x3D;categoryIds%3A%7B100%7C101%7C102%7D | [optional] ### Return type [**\Ebay\Sell\Metadata\Model\ItemConditionPolicyResponse**](../Model/ItemConditionPolicyResponse.md) ### Authorization [Authorization Code](../../README.md#Authorization Code), [Client Credentials](../../README.md#Client Credentials) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: `application/json` [[Back to top]](#) [[Back to API list]](../../README.md#endpoints) [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) ## `getListingStructurePolicies()` ```php getListingStructurePolicies($marketplace_id, $filter): \Ebay\Sell\Metadata\Model\ListingStructurePolicyResponse ``` This method returns the eBay policies that define the allowed listing structures for the categories of a specific marketplace. The listing-structure policies currently pertain to whether or not you can list items with variations. By default, this method returns the entire category tree for the specified marketplace. You can limit the size of the result set by using the filter query parameter to specify only the category IDs you want to review. Tip: This method can return a very large response payload and we strongly recommend you get the results from this call in a GZIP file by including the following HTTP header with your request: &nbsp;&nbsp;Accept-Encoding: application/gzip ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: Client Credentials $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); $apiInstance = new Ebay\Sell\Metadata\Api\MarketplaceApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $marketplace_id = 'marketplace_id_example'; // string | This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. $filter = 'filter_example'; // string | This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character ('|'). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter=categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &nbsp;&nbsp;filter=categoryIds%3A%7B100%7C101%7C102%7D try { $result = $apiInstance->getListingStructurePolicies($marketplace_id, $filter); print_r($result); } catch (Exception $e) { echo 'Exception when calling MarketplaceApi->getListingStructurePolicies: ', $e->getMessage(), PHP_EOL; } ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **marketplace_id** | **string**| This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. | **filter** | **string**| This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character (&#39;|&#39;). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter&#x3D;categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &amp;nbsp;&amp;nbsp;filter&#x3D;categoryIds%3A%7B100%7C101%7C102%7D | [optional] ### Return type [**\Ebay\Sell\Metadata\Model\ListingStructurePolicyResponse**](../Model/ListingStructurePolicyResponse.md) ### Authorization [Client Credentials](../../README.md#Client Credentials) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: `application/json` [[Back to top]](#) [[Back to API list]](../../README.md#endpoints) [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) ## `getNegotiatedPricePolicies()` ```php getNegotiatedPricePolicies($marketplace_id, $filter): \Ebay\Sell\Metadata\Model\NegotiatedPricePolicyResponse ``` This method returns the eBay policies that define the supported negotiated price features (like &quot;best offer&quot;) for the categories of a specific marketplace. By default, this method returns the entire category tree for the specified marketplace. You can limit the size of the result set by using the filter query parameter to specify only the category IDs you want to review. Tip: This method can return a very large response payload and we strongly recommend you get the results from this call in a GZIP file by including the following HTTP header with your request: &nbsp;&nbsp;Accept-Encoding: application/gzip ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: Client Credentials $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); $apiInstance = new Ebay\Sell\Metadata\Api\MarketplaceApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $marketplace_id = 'marketplace_id_example'; // string | This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. $filter = 'filter_example'; // string | This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character ('|'). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter=categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &nbsp;&nbsp;filter=categoryIds%3A%7B100%7C101%7C102%7D try { $result = $apiInstance->getNegotiatedPricePolicies($marketplace_id, $filter); print_r($result); } catch (Exception $e) { echo 'Exception when calling MarketplaceApi->getNegotiatedPricePolicies: ', $e->getMessage(), PHP_EOL; } ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **marketplace_id** | **string**| This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. | **filter** | **string**| This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character (&#39;|&#39;). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter&#x3D;categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &amp;nbsp;&amp;nbsp;filter&#x3D;categoryIds%3A%7B100%7C101%7C102%7D | [optional] ### Return type [**\Ebay\Sell\Metadata\Model\NegotiatedPricePolicyResponse**](../Model/NegotiatedPricePolicyResponse.md) ### Authorization [Client Credentials](../../README.md#Client Credentials) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: `application/json` [[Back to top]](#) [[Back to API list]](../../README.md#endpoints) [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) ## `getProductAdoptionPolicies()` ```php getProductAdoptionPolicies($marketplace_id, $filter): \Ebay\Sell\Metadata\Model\ProductAdoptionPolicyResponse ``` This method retrieves a list of leaf categories for a marketplace and identifies the categories that require items to have an eBay product ID value in order to be listed in those categories. An eBay product ID value (known as an &quot;ePID&quot;) is a value that references a specific product in the eBay Catalog. Important: eBay catalog product adoption is not currently required for any product categories. If product adoption requirements change, they will be noted here. Use the marketplace_id path parameter to specify the marketplace you want to review and use the filter query parameter to limit the categories returned in the response. Tip: This method can return a very large response payload and we strongly recommend you get the results from this call in a GZIP file by including the following HTTP header with your request: &nbsp;&nbsp;Accept-Encoding: application/gzip ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: Client Credentials $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); $apiInstance = new Ebay\Sell\Metadata\Api\MarketplaceApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $marketplace_id = 'marketplace_id_example'; // string | This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. $filter = 'filter_example'; // string | This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character ('|'). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter=categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &nbsp;&nbsp;filter=categoryIds%3A%7B100%7C101%7C102%7D try { $result = $apiInstance->getProductAdoptionPolicies($marketplace_id, $filter); print_r($result); } catch (Exception $e) { echo 'Exception when calling MarketplaceApi->getProductAdoptionPolicies: ', $e->getMessage(), PHP_EOL; } ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **marketplace_id** | **string**| This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. | **filter** | **string**| This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character (&#39;|&#39;). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter&#x3D;categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &amp;nbsp;&amp;nbsp;filter&#x3D;categoryIds%3A%7B100%7C101%7C102%7D | [optional] ### Return type [**\Ebay\Sell\Metadata\Model\ProductAdoptionPolicyResponse**](../Model/ProductAdoptionPolicyResponse.md) ### Authorization [Client Credentials](../../README.md#Client Credentials) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: `application/json` [[Back to top]](#) [[Back to API list]](../../README.md#endpoints) [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) ## `getReturnPolicies()` ```php getReturnPolicies($marketplace_id, $filter): \Ebay\Sell\Metadata\Model\ReturnPolicyResponse ``` This method returns the eBay policies that define whether or not you must include a return policy for the items you list in the categories of a specific marketplace, plus the guidelines for creating domestic and international return policies in the different eBay categories. By default, this method returns the entire category tree for the specified marketplace. You can limit the size of the result set by using the filter query parameter to specify only the category IDs you want to review. Tip: This method can return a very large response payload and we strongly recommend you get the results from this call in a GZIP file by including the following HTTP header with your request: &nbsp;&nbsp;Accept-Encoding: application/gzip ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: Client Credentials $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); $apiInstance = new Ebay\Sell\Metadata\Api\MarketplaceApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $marketplace_id = 'marketplace_id_example'; // string | This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. $filter = 'filter_example'; // string | This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character ('|'). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter=categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &nbsp;&nbsp;filter=categoryIds%3A%7B100%7C101%7C102%7D try { $result = $apiInstance->getReturnPolicies($marketplace_id, $filter); print_r($result); } catch (Exception $e) { echo 'Exception when calling MarketplaceApi->getReturnPolicies: ', $e->getMessage(), PHP_EOL; } ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **marketplace_id** | **string**| This path parameter specifies the eBay marketplace for which policy information is retrieved. See the following page for a list of valid eBay marketplace IDs: Request components. | **filter** | **string**| This query parameter limits the response by returning policy information for only the selected sections of the category tree. Supply categoryId values for the sections of the tree you want returned. When you specify a categoryId value, the returned category tree includes the policies for that parent node, plus the policies for any leaf nodes below that parent node. The parameter takes a list of categoryId values and you can specify up to 50 separate category IDs. Separate multiple values with a pipe character (&#39;|&#39;). If you specify more than 50 categoryId values, eBay returns the policies for the first 50 IDs and a warning that not all categories were returned. Example: filter&#x3D;categoryIds:{100|101|102} Note that you must URL-encode the parameter list, which results in the following filter for the above example: &amp;nbsp;&amp;nbsp;filter&#x3D;categoryIds%3A%7B100%7C101%7C102%7D | [optional] ### Return type [**\Ebay\Sell\Metadata\Model\ReturnPolicyResponse**](../Model/ReturnPolicyResponse.md) ### Authorization [Client Credentials](../../README.md#Client Credentials) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: `application/json` [[Back to top]](#) [[Back to API list]](../../README.md#endpoints) [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) <file_sep># OpenAPIClient-php The Metadata API has operations that retrieve configuration details pertaining to the different eBay marketplaces. In addition to marketplace information, the API also has operations that get information that helps sellers list items on eBay. ## Installation & Usage ### Requirements PHP 7.2 and later. ### Composer To install the bindings via [Composer](https://getcomposer.org/), add the following to `composer.json`: ```json { "repositories": [ { "type": "vcs", "url": "https://github/zvps/ebay-sell-metadata-php-client.git" } ], "require": { "zvps/ebay-sell-metadata-php-client": "*@dev" } } ``` Then run `composer install` ### Manual Installation Download the files and include `autoload.php`: ```php <?php require_once('/path/to/OpenAPIClient-php/vendor/autoload.php'); ``` ## Getting Started Please follow the [installation procedure](#installation--usage) and then run the following: ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: Client Credentials $config = Ebay\Sell\Metadata\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); $apiInstance = new Ebay\Sell\Metadata\Api\CountryApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $country_code = 'country_code_example'; // string | This path parameter specifies the two-letter ISO 3166 country code for the country whose jurisdictions you want to retrieve. eBay provides sales tax jurisdiction information for Canada and the United States.Valid values for this path parameter are CA and US. try { $result = $apiInstance->getSalesTaxJurisdictions($country_code); print_r($result); } catch (Exception $e) { echo 'Exception when calling CountryApi->getSalesTaxJurisdictions: ', $e->getMessage(), PHP_EOL; } ``` ## API Endpoints All URIs are relative to *https://api.ebay.com/sell/metadata/v1* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *CountryApi* | [**getSalesTaxJurisdictions**](docs/Api/CountryApi.md#getsalestaxjurisdictions) | **GET** /country/{countryCode}/sales_tax_jurisdiction | *MarketplaceApi* | [**getAutomotivePartsCompatibilityPolicies**](docs/Api/MarketplaceApi.md#getautomotivepartscompatibilitypolicies) | **GET** /marketplace/{marketplace_id}/get_automotive_parts_compatibility_policies | *MarketplaceApi* | [**getItemConditionPolicies**](docs/Api/MarketplaceApi.md#getitemconditionpolicies) | **GET** /marketplace/{marketplace_id}/get_item_condition_policies | *MarketplaceApi* | [**getListingStructurePolicies**](docs/Api/MarketplaceApi.md#getlistingstructurepolicies) | **GET** /marketplace/{marketplace_id}/get_listing_structure_policies | *MarketplaceApi* | [**getNegotiatedPricePolicies**](docs/Api/MarketplaceApi.md#getnegotiatedpricepolicies) | **GET** /marketplace/{marketplace_id}/get_negotiated_price_policies | *MarketplaceApi* | [**getProductAdoptionPolicies**](docs/Api/MarketplaceApi.md#getproductadoptionpolicies) | **GET** /marketplace/{marketplace_id}/get_product_adoption_policies | *MarketplaceApi* | [**getReturnPolicies**](docs/Api/MarketplaceApi.md#getreturnpolicies) | **GET** /marketplace/{marketplace_id}/get_return_policies | ## Models - [AutomotivePartsCompatibilityPolicy](docs/Model/AutomotivePartsCompatibilityPolicy.md) - [AutomotivePartsCompatibilityPolicyResponse](docs/Model/AutomotivePartsCompatibilityPolicyResponse.md) - [Error](docs/Model/Error.md) - [ErrorParameter](docs/Model/ErrorParameter.md) - [Exclusion](docs/Model/Exclusion.md) - [ItemCondition](docs/Model/ItemCondition.md) - [ItemConditionPolicy](docs/Model/ItemConditionPolicy.md) - [ItemConditionPolicyResponse](docs/Model/ItemConditionPolicyResponse.md) - [ListingStructurePolicy](docs/Model/ListingStructurePolicy.md) - [ListingStructurePolicyResponse](docs/Model/ListingStructurePolicyResponse.md) - [NegotiatedPricePolicy](docs/Model/NegotiatedPricePolicy.md) - [NegotiatedPricePolicyResponse](docs/Model/NegotiatedPricePolicyResponse.md) - [ProductAdoptionPolicy](docs/Model/ProductAdoptionPolicy.md) - [ProductAdoptionPolicyResponse](docs/Model/ProductAdoptionPolicyResponse.md) - [ReturnPolicy](docs/Model/ReturnPolicy.md) - [ReturnPolicyDetails](docs/Model/ReturnPolicyDetails.md) - [ReturnPolicyResponse](docs/Model/ReturnPolicyResponse.md) - [SalesTaxJurisdiction](docs/Model/SalesTaxJurisdiction.md) - [SalesTaxJurisdictions](docs/Model/SalesTaxJurisdictions.md) - [TimeDuration](docs/Model/TimeDuration.md) ## Authorization ### Authorization Code - **Type**: `OAuth` - **Flow**: `accessCode` - **Authorization URL**: `https://auth.ebay.com/oauth2/authorize` - **Scopes**: - **https://api.ebay.com/oauth/api_scope/sell.inventory**: View and manage your inventory and offers ### Client Credentials - **Type**: `OAuth` - **Flow**: `application` - **Authorization URL**: `` - **Scopes**: - **https://api.ebay.com/oauth/api_scope**: View public data from eBay ## Tests To run the tests, use: ```bash composer install vendor/bin/phpunit ``` ## Author ## About this package This PHP package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - API version: `v1.4.1` - Package version: `5.0.0` - Build package: `org.openapitools.codegen.languages.PhpClientCodegen` <file_sep><?php /** * ReturnPolicyDetails * * PHP version 7.2 * * @category Class * @package Ebay\Sell\Metadata * @author OpenAPI Generator team * @link https://openapi-generator.tech */ /** * Metadata API * * The Metadata API has operations that retrieve configuration details pertaining to the different eBay marketplaces. In addition to marketplace information, the API also has operations that get information that helps sellers list items on eBay. * * The version of the OpenAPI document: v1.4.1 * Generated by: https://openapi-generator.tech * OpenAPI Generator version: 5.1.1 */ /** * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ namespace Ebay\Sell\Metadata\Model; use \ArrayAccess; use \Ebay\Sell\Metadata\ObjectSerializer; /** * ReturnPolicyDetails Class Doc Comment * * @category Class * @description This container defines the category policies that relate to domestic and international return policies (the return shipping is made via a domestic or an international shipping service, respectively). * @package Ebay\Sell\Metadata * @author OpenAPI Generator team * @link https://openapi-generator.tech * @implements \ArrayAccess<TKey, TValue> * @template TKey int|null * @template TValue mixed|null */ class ReturnPolicyDetails implements ModelInterface, ArrayAccess, \JsonSerializable { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $openAPIModelName = 'ReturnPolicyDetails'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $openAPITypes = [ 'policy_description_enabled' => 'bool', 'refund_methods' => 'string[]', 'return_methods' => 'string[]', 'return_periods' => '\Ebay\Sell\Metadata\Model\TimeDuration[]', 'returns_acceptance_enabled' => 'bool', 'return_shipping_cost_payers' => 'string[]' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] * @phpstan-var array<string, string|null> * @psalm-var array<string, string|null> */ protected static $openAPIFormats = [ 'policy_description_enabled' => null, 'refund_methods' => null, 'return_methods' => null, 'return_periods' => null, 'returns_acceptance_enabled' => null, 'return_shipping_cost_payers' => null ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function openAPITypes() { return self::$openAPITypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function openAPIFormats() { return self::$openAPIFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'policy_description_enabled' => 'policyDescriptionEnabled', 'refund_methods' => 'refundMethods', 'return_methods' => 'returnMethods', 'return_periods' => 'returnPeriods', 'returns_acceptance_enabled' => 'returnsAcceptanceEnabled', 'return_shipping_cost_payers' => 'returnShippingCostPayers' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'policy_description_enabled' => 'setPolicyDescriptionEnabled', 'refund_methods' => 'setRefundMethods', 'return_methods' => 'setReturnMethods', 'return_periods' => 'setReturnPeriods', 'returns_acceptance_enabled' => 'setReturnsAcceptanceEnabled', 'return_shipping_cost_payers' => 'setReturnShippingCostPayers' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'policy_description_enabled' => 'getPolicyDescriptionEnabled', 'refund_methods' => 'getRefundMethods', 'return_methods' => 'getReturnMethods', 'return_periods' => 'getReturnPeriods', 'returns_acceptance_enabled' => 'getReturnsAcceptanceEnabled', 'return_shipping_cost_payers' => 'getReturnShippingCostPayers' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$openAPIModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['policy_description_enabled'] = isset($data['policy_description_enabled']) ? $data['policy_description_enabled'] : null; $this->container['refund_methods'] = isset($data['refund_methods']) ? $data['refund_methods'] : null; $this->container['return_methods'] = isset($data['return_methods']) ? $data['return_methods'] : null; $this->container['return_periods'] = isset($data['return_periods']) ? $data['return_periods'] : null; $this->container['returns_acceptance_enabled'] = isset($data['returns_acceptance_enabled']) ? $data['returns_acceptance_enabled'] : null; $this->container['return_shipping_cost_payers'] = isset($data['return_shipping_cost_payers']) ? $data['return_shipping_cost_payers'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this->listInvalidProperties()) === 0; } /** * Gets policy_description_enabled * * @return bool|null */ public function getPolicyDescriptionEnabled() { return $this->container['policy_description_enabled']; } /** * Sets policy_description_enabled * * @param bool|null $policy_description_enabled If set to true, this flag indicates you can supply a detailed return policy description within your return policy (for example, by populating the returnInstructions field in the Account API's createReturnPolicy). User-supplied return policy details are allowed only in the DE, ES, FR, and IT marketplaces. * * @return self */ public function setPolicyDescriptionEnabled($policy_description_enabled) { $this->container['policy_description_enabled'] = $policy_description_enabled; return $this; } /** * Gets refund_methods * * @return string[]|null */ public function getRefundMethods() { return $this->container['refund_methods']; } /** * Sets refund_methods * * @param string[]|null $refund_methods A list of refund methods allowed for the associated category. * * @return self */ public function setRefundMethods($refund_methods) { $this->container['refund_methods'] = $refund_methods; return $this; } /** * Gets return_methods * * @return string[]|null */ public function getReturnMethods() { return $this->container['return_methods']; } /** * Sets return_methods * * @param string[]|null $return_methods A list of return methods allowed for the associated category. * * @return self */ public function setReturnMethods($return_methods) { $this->container['return_methods'] = $return_methods; return $this; } /** * Gets return_periods * * @return \Ebay\Sell\Metadata\Model\TimeDuration[]|null */ public function getReturnPeriods() { return $this->container['return_periods']; } /** * Sets return_periods * * @param \Ebay\Sell\Metadata\Model\TimeDuration[]|null $return_periods A list of return periods allowed for the associated category. Note that different APIs require you to enter the return period in different ways. For example, the Account API uses the complex TimeDuration type, which takes two values (a unit and a value), whereas the Trading API takes a single value (such as Days_30). * * @return self */ public function setReturnPeriods($return_periods) { $this->container['return_periods'] = $return_periods; return $this; } /** * Gets returns_acceptance_enabled * * @return bool|null */ public function getReturnsAcceptanceEnabled() { return $this->container['returns_acceptance_enabled']; } /** * Sets returns_acceptance_enabled * * @param bool|null $returns_acceptance_enabled If set to true, this flag indicates the seller can configure how they handle domestic returns. * * @return self */ public function setReturnsAcceptanceEnabled($returns_acceptance_enabled) { $this->container['returns_acceptance_enabled'] = $returns_acceptance_enabled; return $this; } /** * Gets return_shipping_cost_payers * * @return string[]|null */ public function getReturnShippingCostPayers() { return $this->container['return_shipping_cost_payers']; } /** * Sets return_shipping_cost_payers * * @param string[]|null $return_shipping_cost_payers A list of allowed values for who pays for the return shipping cost. Note that for SNAD returns, the seller is always responsible for the return shipping cost. * * @return self */ public function setReturnShippingCostPayers($return_shipping_cost_payers) { $this->container['return_shipping_cost_payers'] = $return_shipping_cost_payers; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed|null */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param int|null $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Serializes the object to a value that can be serialized natively by json_encode(). * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php * * @return mixed Returns data which can be serialized by json_encode(), which is a value * of any type other than a resource. */ public function jsonSerialize() { return ObjectSerializer::sanitizeForSerialization($this); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } /** * Gets a header-safe presentation of the object * * @return string */ public function toHeaderValue() { return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } } <file_sep># # ReturnPolicy ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category_id** | **string** | The category ID to which the return policies apply. | [optional] **category_tree_id** | **string** | A value that indicates the root node of the category tree used for the response set. Each marketplace is based on a category tree whose root node is indicated by this unique category ID value. All category policy information returned by this call pertains to the categories included below this root node of the tree. A category tree is a hierarchical framework of eBay categories that begins at the root node of the tree and extends to include all the child nodes in the tree. Each child node in the tree is an eBay category that is represented by a unique categoryId value. Within a category tree, the root node has no parent node and leaf nodes are nodes that have no child nodes. | [optional] **domestic** | [**\Ebay\Sell\Metadata\Model\ReturnPolicyDetails**](ReturnPolicyDetails.md) | | [optional] **international** | [**\Ebay\Sell\Metadata\Model\ReturnPolicyDetails**](ReturnPolicyDetails.md) | | [optional] **required** | **bool** | If set to true, this flag indicates that you must specify a return policy for items listed in the associated category. Note that not accepting returns (setting returnsAcceptedEnabled to false) is a valid return policy. | [optional] [[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md)
f048c8c1909c9a203d391cdd44eb0459255e6d9b
[ "Markdown", "PHP" ]
5
Markdown
zVPS/ebay-sell-metadata-php-client
fd9e1b6fd8ce91eadb32fc0027c09e431b529ce8
4a0edf2d3bfbaa6b190a6350923e7407f17c027b
refs/heads/master
<file_sep>#! /bin/bash apt-get install proftpd -y if [ "$?" != "0" ]; then echo "Error instlacion"; exit 1; fi cp proftpd.conf /etc/proftpd/ if [ "$?" != "0" ]; then echo "Copiadno Archivo de configuracion "; exit 1; fi addgroup ftp if [ "$?" != "0" ]; then echo "Creando Grupo de trabajo"; exit 1; fi adduser ftp ftp if [ "$?" != "0" ]; then echo "Creando usuario de trabajo y agregando a grupo"; exit 1; fi mkdir /home/ftp if [ "$?" != "0" ]; then echo "Creando directorio ftp"; exit 1; fi mkdir /home/ftp/up if [ "$?" != "0" ]; then echo "Creando directorio de subida"; exit 1; fi mkdir /home/ftp/down if [ "$?" != "0" ]; then echo "Creadno directorio de bajada"; exit 1; fi cd /home/ftp if [ "$?" != "0" ]; then echo "Moviendoce a carpeta de trabajo"; exit 1; fi chown ftp:ftp down if [ "$?" != "0" ]; then echo "Haciendo propietario directorio bajada"; exit 1; fi chown ftp:ftp up if [ "$?" != "0" ]; then echo "Haciendo propietario directorio subida"; exit 1; fi service proftpd restart if [ "$?" != "0" ]; then echo "Reiniciando Servidor"; exit 1; fi
ea3fa80261578eeb0e4d38d45e0b4dc1f1e767d4
[ "Shell" ]
1
Shell
ChristianBarrientos/Script_proftpd
ebb985547789cd024d51a0dc9e34b2877add7eee
b1268b793ce80d2fd363036d1d62940dff3a539e
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class Follow : MonoBehaviour { public GameObject target; // Use this for initialization void Start () { } // Update is called once per frame void Update () { var position = transform.position; position.x = target.transform.position.x + 3.04f; transform.position = position; } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; using DG.Tweening; public class GameManager : MonoBehaviour { public int stageNumbers = 0; public GameObject player; public SpriteRenderer info; public bool showInterstitialAds = true; List<GameObject> stages = new List<GameObject>(); float offset = 0; bool playing = false; // Use this for initialization void Start () { Application.targetFrameRate = 60; offset = Camera.main.orthographicSize * 2; player.GetComponent<Control>().OnCollide += GameOver; } // Update is called once per frame void Update() { if (!playing) { if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.touchCount > 0) { Play(); } else { return; } } var last = stages[stages.Count - 1]; if (last.transform.position.x - player.transform.position.x <= offset) { CreateStage(); } var first = stages[0]; var firstControl = first.GetComponent<StageControl>(); if (first.transform.position.x + firstControl.width - player.transform.position.x <= -offset) { stages.RemoveAt(0); DestroyObject(first); } } void FixedUpdate() { if (!playing) return; player.GetComponent<Control>().Move(); } void CreateStage() { var i = Random.Range(0, stageNumbers) + 1; GameObject go = Resources.Load("stage" + i) as GameObject; GameObject stage = Instantiate(go); var width = Camera.main.orthographicSize; if (this.stages.Count == 0) { stage.transform.position = new Vector3(width*3, 0, 0); } else { var last = stages[stages.Count - 1]; var lastStageControl = last.GetComponent<StageControl>(); stage.transform.position = new Vector3(last.transform.position.x + lastStageControl.width, 0); } stages.Add(stage); } void GameOver(object sender, System.EventArgs e) { playing = false; string zoneID = null; if (showInterstitialAds && UnityAdsHelper.IsReady (zoneID)) { UnityAdsHelper.ShowAd (zoneID, null, null, null, Reset); } else { Reset(); } } void Reset() { playing = false; player.GetComponent<Control>().Reset(); info.DOFade(1, 0); info.transform.DOScale(2, 0); for (var i = stages.Count-1; i>=0; i--) { var stage = stages[i]; DestroyObject(stage); stages.Remove(stage); } } void Play() { playing = true; info.DOFade(0, 0.5f); info.transform.DOScale(0, 0.5f); CreateStage(); } } <file_sep>using UnityEngine; using System.Collections; using System; public class Control : MonoBehaviour { public event EventHandler OnCollide; public float force = 40f; public float gravity = 40f; public float maxSpeed = 12f; public float fowardSpeed = 10.0f; float speed = 0.0f; float startRotation; float startX; void Start() { startRotation = transform.localEulerAngles.z; startX = transform.position.x; } // Update is called once per frame public void Move() { var up = false; if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow) || Input.touchCount > 0) { up = true; } var f = up ? force : gravity; speed += f * Time.deltaTime; if (Mathf.Abs(speed) > maxSpeed) speed = speed < 0 ? -maxSpeed : maxSpeed; var position = transform.position; var y = position.y + speed; if (y < -Camera.main.orthographicSize) { speed = 0; y = -Camera.main.orthographicSize; ; } else if (y > Camera.main.orthographicSize) { speed = 0; y = Camera.main.orthographicSize; ; } transform.rotation = Quaternion.Euler(0, 0, startRotation + speed * 400.0f); position.y = y; position.x += fowardSpeed; transform.position = position; } void OnTriggerEnter2D(Collider2D other) { if (OnCollide != null) OnCollide(this, EventArgs.Empty); } public void Reset() { speed = 0; transform.rotation = Quaternion.Euler(0, 0, startRotation); transform.position = new Vector3(startX, 0, 0); } } <file_sep>using UnityEditor; using UnityEngine; [CustomEditor(typeof(StageControl))] public class StageEditor : Editor { public void OnSceneGUI() { StageControl control = (StageControl)target; var width = control.width; var height = Camera.main.orthographicSize; if (Event.current.shift) { var mousePosition = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(Event.current.mousePosition); //var mousePosition = Camera.main.ScreenToWorldPoint(Event.current.mousePosition); control.width = mousePosition.x; var bg = GameObject.Find("bg"); if (bg) { var sprite = bg.GetComponent<SpriteRenderer>().sprite; var bgSize = sprite.textureRect.size; bg.transform.position = new Vector3(control.width / 2, 0, bg.transform.position.z); bg.transform.localScale = new Vector3(control.width / bgSize.x * sprite.pixelsPerUnit, height / bgSize.y * sprite.pixelsPerUnit * 2); } } Handles.DrawLine(new Vector3(0, -height, 0), new Vector3(0, height, 0)); Handles.DrawLine(new Vector3(0, height, 0), new Vector3(width, height, 0)); Handles.DrawLine(new Vector3(width, height, 0), new Vector3(width, -height, 0)); Handles.DrawLine(new Vector3(width, -height, 0), new Vector3(0, -height, 0)); } }
82b7ac98b4220867cabb8be2fffe8053e8203a45
[ "C#" ]
4
C#
2youyouo2/cf
3039f14c35803b70a6864df9e33117d17ad7e6c6
682079398bffe11afefde86f735df8ede98db033
refs/heads/master
<repo_name>wespatrocinio/programming_studies<file_sep>/tensorflow/text_classification/src/features.py import numpy as np import nltk from nltk.tokenize import RegexpTokenizer from collections import Counter nltk.download('stopwords') def get_tokens(text): tokenizer = RegexpTokenizer(r'\w+') tokens = tokenizer.tokenize(text.lower()) stopwords = nltk.corpus.stopwords.words("english") return [token for token in tokens if token not in stopwords] def get_vocab(data): """ Split a raw text into a Counter indexed by word. """ vocab = Counter() for text in data: for token in get_tokens(text): vocab[token] += 1 return vocab def get_len_vocab(text): return len(get_vocab(text)) def get_word_2_index(text): """ Generate an word:index dictionary. """ word2index = {} for i,word in enumerate(get_vocab(text)): word2index[word.lower()] = i return word2index def get_input_tensor(text): vocab = get_vocab(text) word2index = get_word_2_index(vocab) matrix = np.zeros(len(vocab), dtype=float) for word in text.split(): matrix[word2index[word.lower()]] += 1 return matrix def get_output_tensor(category, n_classes): output = np.zeros(n_classes, dtype=float) output[category] = 1.0 return output <file_sep>/tensorflow/text_classification/src/main_alt.py from data import get_train_test_data from features import * from settings import * from perceptron import * from classifier.nn import Perceptron import tensorflow as tf if __name__ == '__main__': train_text, test_text = get_train_test_data(DATA_CATEGORIES) vocab = get_vocab(train_text.data + test_text.data) n_input = len(vocab) word2index = get_word_2_index(vocab) input_tensor = tf.placeholder(tf.float32, [None, n_input], name="input") output_tensor = tf.placeholder(tf.float32, [None, len(DATA_CATEGORIES)], name="output") nn = Perceptron(n_input, len(DATA_CATEGORIES), N_HIDDEN, SIZE_HIDDEN) prediction = nn.predict(input_tensor) # Test model correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(output_tensor, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) total_test_data = len(test_text.target) batch_x_test, batch_y_test = get_batch(test_text.data, test_text.target, word2index, n_input, 0, total_test_data) print("Accuracy:", accuracy.eval({input_tensor: batch_x_test, output_tensor: batch_y_test}))<file_sep>/tensorflow/text_classification/src/main.py from classifier.nn import Perceptron from data import get_train_test_data from features import * from settings import * from perceptron import * import tensorflow as tf def get_batch(data, target, word2index, input_size, iteration, batch_size): """ Defines the size of each batch to be processed. """ batches = [] results = [] texts = data[iteration * batch_size : iteration * batch_size + batch_size] categories = target[iteration * batch_size : iteration * batch_size + batch_size] for text in texts: layer = np.zeros(input_size, dtype=float) for token in get_tokens(text): layer[word2index[token]] += 1 batches.append(layer) for category in categories: y = np.zeros(len(set(categories)), dtype=float) y[category] = 1.0 results.append(y) return np.array(batches), np.array(results) if __name__ == '__main__': train_text, test_text = get_train_test_data(DATA_CATEGORIES) vocab = get_vocab(train_text.data + test_text.data) n_input = len(vocab) word2index = get_word_2_index(vocab) input_tensor = tf.placeholder(tf.float32, [None, n_input], name="input") output_tensor = tf.placeholder(tf.float32, [None, len(DATA_CATEGORIES)], name="output") nn = Perceptron(n_input, len(DATA_CATEGORIES), N_HIDDEN, SIZE_HIDDEN) prediction = nn.predict(input_tensor) loss = get_entropy_loss(prediction, output_tensor) optimizer = get_optimizer(loss, LEARNING_RATE) # Initializing the variables init = tf.global_variables_initializer() training_epochs = 10 # Launch the graph with tf.Session() as session: session.run(init) # inits the variables # Training cycle for epoch in range(training_epochs): avg_cost = 0 BATCH_SIZE = len(train_text.data) total_batch = int(len(train_text.data) / BATCH_SIZE) # Loop over all batches for i in range(total_batch): batch_x, batch_y = get_batch(train_text.data, train_text.target, word2index, n_input, i, BATCH_SIZE) # Run optimization op (back propagation) and cost optimization c, _ = session.run( [loss, optimizer], feed_dict={ input_tensor: batch_x, output_tensor: batch_y } ) avg_cost += c / total_batch # Display logs per epoch step if epoch % DISPLAY_STEP == 0: print("Epoch", '%04d' % (epoch + 1), "loss=", "{:.9f}".format(avg_cost)) print("Optimization Finished!") # Test model correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(output_tensor, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) total_test_data = len(test_text.target) batch_x_test, batch_y_test = get_batch(test_text.data, test_text.target, word2index, n_input, 0, total_test_data) print("Accuracy:", accuracy.eval({input_tensor: batch_x_test, output_tensor: batch_y_test}))<file_sep>/tensorflow/text_classification/src/perceptron.py from settings import * import tensorflow as tf def get_weights(n_input, n_hidden_1, n_hidden_2, n_classes): """ Generate all weights based on the NN settings. """ return { 'h0': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h1': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } def get_biases(n_hidden_1, n_hidden_2, n_classes): """ Generate all biases based on the NN settings. """ return { 'h0': tf.Variable(tf.random_normal([n_hidden_1])), 'h1': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_classes])) } def multilayer_perceptron(input_tensor, weights, biases): """ Creates the multi-layer NN by applying weights and biases for each layer. input_tensor Input data (phrase) weights Weights for each layer biases Biases for each layer """ layer_1_multiplication = tf.matmul(input_tensor, weights['h0']) layer_1_addition = tf.add(layer_1_multiplication, biases['h0']) layer_1_activation = tf.nn.relu(layer_1_addition) # Hidden layer with RELU activation layer_2_multiplication = tf.matmul(layer_1_activation, weights['h1']) layer_2_addition = tf.add(layer_2_multiplication, biases['h1']) layer_2_activation = tf.nn.relu(layer_2_addition) # Output layer with linear activiation out_layer_multiplication = tf.matmul(layer_2_activation, weights['out']) out_layer_addition = out_layer_multiplication + biases['out'] return out_layer_addition def get_entropy_loss(prediction, output_tensor): """ Calculate the mean loss based in the difference between the prediction and the ground truth. """ entropy_loss = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=output_tensor) return tf.reduce_mean(entropy_loss) def get_optimizer(loss, learning_rate): """ Update all the variables bases on the Adaptive Moment Estimation (Adam) method. """ return tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)<file_sep>/ooo/vector.py """ Playing around with overload """ class Vector: """ Represent a vector in a multidimensional space. """ def __init__(self, d): """ Create a d-dimensional vector of zeros. d Dimension of th vctor space (int) """ self._coords = [0]*d def __len__(self): """ Return the dimension of the vector. """ return len(self._coords) def __getitem__(self, k): """ Return k-th coordinate of the vector """ return self._coords[k] def __setitem__(self, k, value): """ Set k-th coordinate of vector to given value. """ self._coords[k] = value def __add__(self, other): """ Return sum of two vectors. other Another Vector instance. Expected the same dimension. """ if len( self) != len(other): raise ValueError('Dimensions must match.') result = Vector(len(self)) for i in range(len(self)): result[i] = self[i] + other[i] return result def __eq__(self, other): """ Return True if vector has same coords as other. other Another Vector instance. """ return self._coords == other._coords def __ne__(self, other): """ Return True if vector differs from other. Rely on __eq__ method above. other Another Vector instance. """ return not self == other def __str__(self): """ Produce string representation of vector. """ return '< {coords} >'.format(coords=self._coords)<file_sep>/tensorflow/text_classification/src/model/model.py import tensorflow as tf import numpy as np class Model(object): def __init__(self, classifier, parameters, train_data, train_target, test_data, test_target): self.classifier = classifier self.parameters = parameters self.train_data = train_data self.train_target = train_target self.test_data = test_data self.test_target = test_target def train(self, input_tensor, output_tensor): loss = self.get_entropy_loss(self.classifier.predict(input_tensor), output_tensor) optimizer = self.get_optimizer(loss, self.parameters.get('learning_rate')) # Initializing the variables init = tf.global_variables_initializer() training_epochs = 10 # Launch the graph with tf.Session() as session: session.run(init) # inits the variables # Training cycle epoch = 0 cost = 1 # Any value bigger than the threshold while cost > 0.01 or epoch <= training_epochs: # TODO: parameterize the cost threshold cost, _ = session.run( [loss, optimizer], feed_dict={ input_tensor: np.array(self.train_data), output_tensor: np.array(self.train_target) } ) # Display logs per epoch step print("Epoch", '%04d' % (epoch + 1), "loss=", "{:.9f}".format(cost)) print("Optimization Finished!") return True def test(self): pass # def get_batch(data, target, word2index, input_size, iteration, batch_size): # """ Defines the size of each batch to be processed. """ # batches = [] # results = [] # texts = data[iteration * batch_size : iteration * batch_size + batch_size] # categories = target[iteration * batch_size : iteration * batch_size + batch_size] # for text in texts: # layer = np.zeros(input_size, dtype=float) # for token in get_tokens(text): # layer[word2index[token]] += 1 # batches.append(layer) # for category in categories: # y = np.zeros(len(set(categories)), dtype=float) # y[category] = 1.0 # results.append(y) # return np.array(batches), np.array(results) def get_entropy_loss(self, prediction, output_tensor): """ Calculate the mean loss based in the difference between the prediction and the ground truth. """ entropy_loss = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=output_tensor) return tf.reduce_mean(entropy_loss) def get_optimizer(self, loss, learning_rate): """ Update all the variables bases on the Adaptive Moment Estimation (Adam) method. """ return tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
6276848fc8d10ce99b958faded1410a09f382f24
[ "Python" ]
6
Python
wespatrocinio/programming_studies
ddae2ab9bf137db11139ba1d25f9fee76fc43dc3
4282c21b0d46eaca54f61747362bf53f70c4b3b2
refs/heads/master
<repo_name>sadubois/docker-images<file_sep>/redis/redis-slave/Dockerfile FROM redis:3.0.2 MAINTAINER <NAME> ENV REDIS_VERSION 3.0.2 ENV REDIS_DOWNLOAD_URL http://download.redis.io/releases/redis-3.0.2.tar.gz ENV REDIS_DOWNLOAD_SHA1 a38755fe9a669896f7c5d8cd3ebbf76d59712002 RUN buildDeps='gcc-c++ libc6-dev tar git unzip wget libevent clang libstdc++-static'; \ baseDeps='make gcc curl libffi-devel'; \ set -x \ && sed -i 's/bind 127.0.0.1/#bind 127.0.0.1/g' /etc/redis.conf \ && echo "slaveof 172.17.0.30 6379" >>/etc/redis.conf <file_sep>/redis/redis-master/build.sh #!/bin/bash docker build --rm -t redis-master:3.0.2 . <file_sep>/jboss-eap/6.3.0/start.sh #!/bin/bash #docker run -itd --name redis-slave-02 redis-slave:3.0.2 /usr/bin/redis-server /etc/redis.conf docker run -itd --name jboss-eap jboss/jboss-eap:6.3.0 /bin/bash <file_sep>/redis/redis-slave/build.sh #!/bin/bash docker build --rm -t redis-slave:3.0.2 . <file_sep>/redis/3.0.2/build.sh #!/bin/bash docker build --rm -t redis:3.0.2 . <file_sep>/jboss-eap/6.3.0/Dockerfile # Steps taken to create this image # docker build --rm -t jboss/jboss_eap:6.3.0 . # docker run -p 9990:9990 -p 9999:9999 -p 8080:8080 -it jboss/jboss-eap:6.3.0 # # Get required ZIP file from: https://access.redhat.com/jbossnetwork/restricted/softwareDownload.html?softwareId=32483&product=appplatform # # FROM jboss/base-jdk:7 ADD files/jboss-eap-6.3.0.zip /tmp/ RUN unzip /tmp/jboss-eap-6.3.0.zip -d /opt/jboss # Add EAP_HOME environment variable, to easily upgrade the script for different EAP versions ENV EAP_HOME /opt/jboss/jboss-eap-6.3 # Add default admin user RUN ${EAP_HOME}/bin/add-user.sh admin admin123! --silent # Enable binding to all network interfaces and debugging inside the EAP RUN echo "JAVA_OPTS=\"\$JAVA_OPTS -Djboss.bind.address=0.0.0.0 -Djboss.bind.address.management=0.0.0.0\"" >> ${EAP_HOME}/bin/standalone.conf # Add volume if you want to externalize logs VOLUME ${EAP_HOME}/standalone/logs EXPOSE 9990 9999 8080 8787 ENTRYPOINT ["/opt/jboss/jboss-eap-6.3/bin/standalone.sh"] CMD [] <file_sep>/redis/3.0.2/Dockerfile FROM registry.access.redhat.com/rhel MAINTAINER <NAME> ENV REDIS_VERSION 3.0.2 ENV REDIS_DOWNLOAD_URL http://download.redis.io/releases/redis-3.0.2.tar.gz ENV REDIS_DOWNLOAD_SHA1 a38755fe9a669896f7c5d8cd3ebbf76d59712002 RUN buildDeps='gcc-c++ libc6-dev tar git unzip wget libevent clang libstdc++-static'; \ baseDeps='make gcc curl libffi-devel'; \ set -x \ && rpm -i https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm \ && yum install -y $baseDeps $buildDeps \ && yum install -y redis \ && systemctl enable redis.service VOLUME /redis EXPOSE 5000 EXPOSE 6379 EXPOSE 16379 EXPOSE 8889 <file_sep>/redis/redis-standalone-start.sh #!/bin/bash REDIS_SERVER=`docker inspect --format='{{.NetworkSettings.IPAddress}}' redis-standalone` if [ "$REDIS_SERVER" != "" ]; then docker stop redis-standalone docker rm redis-standalone fi docker run -itd --name redis-standalone redis:3.0.2 /usr/bin/redis-server > /dev/null 2>&1 REDIS_SERVER=`docker inspect --format='{{.NetworkSettings.IPAddress}}' redis-standalone` #redis-cli -h $REDIS_SERVER ping #redis-benchmark -h $REDIS_SERVER -q -n 1000 -c 10 -P 5 <file_sep>/redis/load.sh #!/bin/bash REDIS_SERVER=`docker inspect --format='{{.NetworkSettings.IPAddress}}' redis-standalone` echo "REDIS_SERVER: $REDIS_SERVER" <file_sep>/redis/redis-cluster-start.sh #!/bin/bash docker_stop () { REDIS_SERVER=`docker inspect --format='{{.NetworkSettings.IPAddress}}' $1 2>/dev/null` if [ "$REDIS_SERVER" != "" ]; then echo "# Stoping/Deleting $1" docker stop $1 >/dev/null 2>&1 docker rm $1 >/dev/null 2>&1 fi docker images $1 > /dev/null 2>&1; ret=$? if [ "$ret" -eq 0 ]; then docker rm $1 >/dev/null 2>&1 fi } docker_stop redis-master docker_stop redis-slave-01 docker_stop redis-slave-02 docker run -itd --name redis-master redis-master:3.0.2 /usr/bin/redis-server >/dev/null 2>&1 REDIS_SERVER=`docker inspect --format='{{.NetworkSettings.IPAddress}}' redis-master` #/usr/bin/redis-cli/redis-cli -h $REDIS_SERVER ping #/usr/bin/redis-cli/redis-benchmark -h $REDIS_SERVER -q -n 1000 -c 10 -P 5 echo "# Build Redis Slave " cat redis-slave/Dockerfile.template | sed "s/REDISMASTER/$REDIS_SERVER/g" > redis-slave/Dockerfile (cd redis-slave; ./build.sh) docker run -itd --name redis-slave-01 redis-slave:3.0.2 /usr/bin/redis-server /etc/redis.conf > /dev/null 2>&1 docker run -itd --name redis-slave-02 redis-slave:3.0.2 /usr/bin/redis-server /etc/redis.conf > /dev/null 2>&1 REDIS_SLAVE_01=`docker inspect --format='{{.NetworkSettings.IPAddress}}' redis-slave-01` REDIS_SLAVE_02=`docker inspect --format='{{.NetworkSettings.IPAddress}}' redis-slave-02` echo "# REDIS MASTER ....: $REDIS_SERVER" echo "# REDIS SLAVE-01 ..: $REDIS_SLAVE_01" echo "# REDIS SLAVE-02 ..: $REDIS_SLAVE_02" echo "/usr/bin/redis-cli -h $REDIS_SERVER set hello world" echo "/usr/bin/redis-cli -h $REDIS_SLAVE_01 get hello" echo "/usr/bin/redis-cli -h $REDIS_SLAVE_02 get hello" <file_sep>/jboss-eap/README.md Docker images for JBoss EAP This docker images are layered on top of jboss-base images (which provide with java installation + jboss user). You can find them at jboss access portal
cfe60bc0f0368f85b341cb257bc7dc71a25848ec
[ "Markdown", "Dockerfile", "Shell" ]
11
Dockerfile
sadubois/docker-images
405eb8e5f77ec239c9468c07cbfe3b8db856e1dc
a60590c8e77695cf876b8e678321d91b3d07d0ef
refs/heads/master
<repo_name>bergbpb/backbone_app_practice<file_sep>/src/js/routes/main_nav_router.js // namespace the main navigation module var App = App || {}; // namespace the module App.mainNavigation = App.mainNavigation || {}; // namespace the data layer App.mainNavigation.router = App.mainNavigation.router || {}; App.mainNavigation.router.MainNavRouter = Backbone.Router.extend( { routes: { 'start' : '', 'home' : 'loadHome', 'news' : 'loadNews', 'about' : 'loadAbout', 'contact' : 'loadContact', 'work' : 'loadWork', '*default' : 'defaultRoute' }, home_page_main_content_collection: null, intialize: function() { location.replace("http://localhost:8080/"); }, start: function() { console.log( 'Initial route invoked' ); }, loadHome: function() { $('#article1').html(''); var homePagecontentView = new App.homePage.view.MainContentView(); $('#article1').append(homePagecontentView); }, loadNews: function() { console.log( 'News route invoked' ); $('#article1').html(''); var newsPageContentView = new App.newsPage.view.contentView(); $('#article1').append(newsPageContentView); }, loadAbout: function() { console.log( 'About route invoked' ); $('#article1').html(''); $('article').append('<p>About page view</p>'); }, loadContact: function() { console.log( 'Contact route invoked' ); $('#article1').html(''); $('article').append('<p>Contact page view</p>'); }, loadWork: function() { console.log( 'Work route invoked' ); $('#article1').html(''); $('article').append('<p>Work page view</p>'); }, defaultRoute: function() { console.log( 'Router error' ); } } ); <file_sep>/src/js/collections/main_nav_collection.js //namespace the App var App = App || {}; // namespace the module App.mainNavigation = App.mainNavigation || {}; // namespace the data layer App.mainNavigation.collection = App.mainNavigation.collection || {}; App.mainNavigation.collection.MainNavCollection = Backbone.Collection.extend( { //the model used by this collection model: App.mainNavigation.model.MainNavModel, //the url for the collection data url: '../json/main_nav.json', initialize: function( options ) { var self = this; console.log( 'main nav collection initialized' ); }, } ); <file_sep>/dist/index.php <!DOCTYPE html> <html lang="en"> <?php include 'includes/head.html' ?> <body class=> <div class="container mainContainer"> <?php include 'includes/header.html' ?> <nav class="mainNavigation" id="mainNav"> </nav><!--end nav --> <section class="section" id="section1"> <article class="article" id="article1"> <?php include 'templates/partials/news_page_content_template.html' ?> <?php include 'templates/partials/home_page_main_content_template.html' ?> </article> <aside class="aside" id="aside1"> <p>aside 1</p> </aside> <aside class="aside" id="aside2"> <p>aside 2</p> </aside> </section> <?php include 'includes/footer.html' ?> </div> <?php include 'templates/partials/main_nav_template.html' ?> <script src="vendor/js/jquery/jquery-3.1.1.js"></script> <script src="vendor/js/underscore/underscore.js"></script> <script src="vendor/js/backbone/backbone.js"></script> <script src="vendor/js/backbone/backbone.localStorage.js"></script> <script src="vendor/js/handlebars/handlebars-v4.0.5.js"></script> <script src="vendor/js/bootstrap/bootstrap.js"></script> <script src="vendor/js/require/require.js"></script> <!-- Model --> <script src="js/models/main_nav_model.js"></script> <script src="js/models/home_page_main_content_model.js"></script> <script src="js/models/news_page_content_model.js"></script> <!-- Collection --> <script src="js/collections/main_nav_collection.js"></script> <script src="js/collections/home_page_main_content_collection.js"></script> <script src="js/collections/news_page_content_collection.js"></script> <!-- View --> <script src="js/views/main_nav_view.js"></script> <script src="js/views/home_page_main_content_view.js"></script> <script src="js/views/news_page_content_view.js"></script> <!-- Router --> <script src="js/routes/main_nav_router.js"></script> <!-- Util --> <script src="js/util/feeds.js"></script> <!-- main --> <script src="js/app.js"></script> </body> </html><file_sep>/src/js/views/news_page_content_view.js //namespace the App var App = App || {}; // namespace the module App.newsPage = App.newsPage || {}; // namespace the data layer App.newsPage.view = App.newsPage.view || {}; App.newsPage.view.contentView = Backbone.View.extend( { // set the page element that the template will render to el: '#article1', // compile the template template: Handlebars.compile( $( '#news_page_content_template' ).html() ), // set the collection to null news_page_content_collection: null, initialize: function() { var self = this; // create a collection for this view to render self.news_page_content_collection = new App.newsPage.collection.contentCollection(); // initial render self.render(); // force the fetch to fire a reset event self.news_page_content_collection.fetch( { reset:true } ); // listen for changes in the collection and fire render when it changes self.listenTo( self.news_page_content_collection, 'reset', self.render ); }, events: { }, render: function() { var self = this; // if there is at least one model in the collection, output it to the template if( self.news_page_content_collection.length > 0 ) { // get the data from the navItems attribute in the first model in the collection // navItems corresponds to the navItems object that is nested in the payload object in the JSON var newsPageContentoutput = self.template( { pageContent: self.news_page_content_collection.models[0].attributes.payload.pageContent } ); // append the template to the element ($el) in the DOM // only if there is no content rendered already // (this is a solution for the content being rendered twice on page refresh) // if ( self.$el.html( '' ) ) { self.$el.append( newsPageContentoutput ); // } } // return the view so it can be accessed by other functions in the App return self; }, } );<file_sep>/src/js/models/news_page_content_model.js //namespace the App var App = App || {}; // namespace the module App.newsPage = App.newsPage || {}; // namespace the data layer App.newsPage.model = App.newsPage.model || {}; App.newsPage.model.contentModel = Backbone.Model.extend( { // set model defaults defaults: { newsPageTitle: "", newsPageImage: "", newsPageImageAltText: "", newsPageArticleText: "" }, initialize: function() { var self = this; console.log( 'news page content model initialized' ); //return the model so it is availabile to other functions in the App return this; } } );<file_sep>/src/js/models/home_page_main_content_model.js //namespace the App var App = App || {}; // namespace the module App.homePage = App.homePage || {}; // namespace the data layer App.homePage.model = App.homePage.model || {}; App.homePage.model.MainContentModel = Backbone.Model.extend( { // set model defaults defaults: { homePageTitle: "", homePageImage: "", homePageImageAltText: "" }, initialize: function() { var self = this; console.log( 'home page main content model initialized' ); //return the model so it is availabile to other functions in the App return this; } } );<file_sep>/dist/js/models/main_nav_model.js //namespace the App var App = App || {}; // namespace the module App.mainNavigation = App.mainNavigation || {}; // namespace the data layer App.mainNavigation.model = App.mainNavigation.model || {}; App.mainNavigation.model.MainNavModel = Backbone.Model.extend( { // set model defaults defaults: { navItemText: '', subNavItem: '', subNavItemText: '', navLink: '', subNavLink: '' }, initialize: function() { var self = this; console.log( 'main nav model initialized' ); //return the model so it is availabile to other functions in the App return this; } } );<file_sep>/src/js/app.js // - wrapping the module in an immediately invoking function // this scopes jQuery locally to this function (provides a closure). ( function( $ ) { $( function() { var main_Nav_collection = new App.mainNavigation.collection.MainNavCollection(); main_Nav_collection.fetch(); var home_Page_main_Content_collection = new App.homePage.collection.MainContentCollection(); home_Page_main_Content_collection.fetch(); var news_Page_Content_collection = new App.newsPage.collection.contentCollection(); news_Page_Content_collection.fetch(); var main_Nav_view = new App.mainNavigation.view.MainNavView(); var home_Page_main_Content_view = new App.homePage.view.MainContentView(); var news_Page_Content_view = new App.newsPage.view.contentView(); var main_Nav_router = new App.mainNavigation.router.MainNavRouter(); Backbone.history.start(); } ); } )( jQuery ); <file_sep>/README.md # backbone_app_practice # backbone_app_practice <file_sep>/dist/js/collections/news_page_content_collection.js //namespace the App var App = App || {}; // namespace the module App.newsPage = App.newsPage || {}; // namespace the data layer App.newsPage.collection = App.newsPage.collection || {}; App.newsPage.collection.contentCollection = Backbone.Collection.extend( { //the model used by this collection model: App.newsPage.model.contentModel, //the url for the collection data url: '../json/news_page_content.json', initialize: function( options ) { var self = this; console.log( 'news page content collection initialized' ); }, } );
e9d1ad5ada32deb7a2a01c9ced1a1dabe682024a
[ "JavaScript", "Markdown", "PHP" ]
10
JavaScript
bergbpb/backbone_app_practice
607f6b249e8e6482f4ea2a1443de2c2a5671f5b2
d50a9ac2e4b0f0047076cddfaf422bca27dff145
refs/heads/master
<repo_name>bmcscpp2016/objectsandclasses_3<file_sep>/fibonacci.h // // Created by valyria on 10/21/16. // #ifndef FIBONACCI_FIBONACCI_H // IGNORE THIS FOR NOW #define FIBONACCI_FIBONACCI_H // IGNORE THIS FOR NOW class fibonacci { private: int termsnumber; // the number of terms in the fibonacci public: int getnumber(int); // gets the number of terms int outputseries(); // outputs the number of terms }; #endif //FIBONACCI_FIBONACCI_H // IGNORE <file_sep>/main.cpp #include<iostream> #include "fibonacci.h" // INCLUDING THE CLASS/ HEADER FILE using namespace std; // THIS PROGRAM IS MEANT TO CALCULATE // THE FIBBONACI SERIES OF THE NTH NUMBER // WHICH WE INPUT IN THE MAIN FUNCTION // A FUNCTION IN THE CALCULATE.CPP // GETS THE VALUE/ NUMBER // AND ANOTHER FUNCTION OUTPUTS THE // SERIES IN ORDER int main() { int termsnumber; // THE NUMBER OF TERMS....NTH TERM cout << "Enter the number of terms of Fibonacci series you want" << endl; cin >> termsnumber; fibonacci example; //EXAMPLE IS OF CLASS FIBONACCI //FUNCTIONS OF THE EXAMPLE OBJECT BEING CALLED example.getnumber(termsnumber); // GETS THE NUMBER example.outputseries(); // OUTPUTS THE SERIES(FIBONNACI) return 0; // RETURNS 0 ECOZ ITS A MAIN FNX }<file_sep>/calculate.cpp // // Created by valyria on 10/21/16. // #include <iostream> #include "fibonacci.h" using namespace std; // THIS IS WHERE THE MAGIC HAPPENS // DEFINING THE GET NUMBER FUNCTION int fibonacci::getnumber(int n) { // WE ARE SIMPLY SAYING THAT N = TERMSNUMBER termsnumber = n; return 0; // BCOZ ITS AN INT FNX } // DEFINING THE OUTPUTSERIES FUNCTION int fibonacci::outputseries() { int next, c; int first = 0; // THE FIRST NUMBER int second = 1; // THE SECOND NUMBER cout << "First " << termsnumber << " terms of Fibonacci series are :- " << endl; // LOOP STARTS RUNNING WHEN: ===> // ----------------------------> C = 0. // STOPS WHEN: // ----------------------------> c IS LESS THAN THE TERMSNUMBER // INCREMENTATION: // -----------------------------> C IS INCREASED BY ONE EVERYTYM LOOP RUNS // -------------===========--------> USING A FOR LOOP // ------> BEGIN // for ( c = 0 ; c < termsnumber ; c++ ) // { // // NEXT DEFINES THE NEXT NUMBER IN THE SERIES // // IF C <= 1 THEN NEXT = 0; // if ( c <= 1 ) { // next = c; // } // // -------------> WHEN PROGRAM STARTS TO RUN NEXT = FIRST + SECOND === 1.. // // -------------> FIRST TAKES THE VALUE OF SECOND // // -------------> SECOND TAKES THE VALUE OF NEXT // // --------------> NEXT AGAIN TAKES THE SUM OF THE 2 NEW NUMBERS FIRST + SECOND // // --------------> THE LOOP GOES ON AND ON // // ---------------> UNTIL C BECOMES EQUAL OR GREATER THAN TERMSNUMBER.. LOOP THEN BREAKS // else // { // next = first + second; // first = second; // second = next; // } // cout << next << endl; // } // -----> END // ----=========--------->WHILE LOOP // ---> BEGIN // c = 0; // do // { // // NEXT DEFINES THE NEXT NUMBER IN THE SERIES // // IF C <= 1 THEN NEXT = 0; // if ( c <= 1 ) { // next = c; // ++c; // } // // -------------> WHEN PROGRAM STARTS TO RUN NEXT = FIRST + SECOND === 1.. // // -------------> FIRST TAKES THE VALUE OF SECOND // // -------------> SECOND TAKES THE VALUE OF NEXT // // --------------> NEXT AGAIN TAKES THE SUM OF THE 2 NEW NUMBERS FIRST + SECOND // // --------------> THE LOOP GOES ON AND ON // // ---------------> UNTIL C BECOMES EQUAL OR GREATER THAN TERMSNUMBER.. LOOP THEN BREAKS // else // { // next = first + second; // first = second; // second = next; // ++c; // } // cout << next << endl; // }while( c < termsnumber ); // ---> END // ------------============-----> WHILE LOOP // ---->>> BEGIN c = 0; while(c < termsnumber) { // NEXT DEFINES THE NEXT NUMBER IN THE SERIES // IF C <= 1 THEN NEXT = 0; if ( c <= 1 ) { next = c; ++c; } // -------------> WHEN PROGRAM STARTS TO RUN NEXT = FIRST + SECOND === 1.. // -------------> FIRST TAKES THE VALUE OF SECOND // -------------> SECOND TAKES THE VALUE OF NEXT // --------------> NEXT AGAIN TAKES THE SUM OF THE 2 NEW NUMBERS FIRST + SECOND // --------------> THE LOOP GOES ON AND ON // ---------------> UNTIL C BECOMES EQUAL OR GREATER THAN TERMSNUMBER.. LOOP THEN BREAKS else { next = first + second; first = second; second = next; ++c; } cout << next << endl; } // ----->> END return 0; }
76e7ef36063e40ac0b3852ab7aeb55135a472562
[ "C++" ]
3
C++
bmcscpp2016/objectsandclasses_3
92091b525b6e602ca2b79e660f90f4e59fe092be
211587f69cb5c4bbc49b5fbd1c497a278526985d
refs/heads/master
<repo_name>8bitpickle/abenia<file_sep>/app/gamestate-manager.js // error logging const error = require('./error.js') // global vars let gameWindow // game window let renderManager // manages screen let inputManager // manages user input // current state let currentState // each state is assigned a number const MainMenuState = 0 // const LoadingState = 1 // const PlayState = 2 // initializes the gamestate manager function initManager(win, render, input) { // assigns game.js objects gameWindow = win renderManager = render inputManager = input // makes sure current state is null currentState = null } // returns the current state // function getState() { // // if (currentState === null) { // // error.log('gamestate-manager.js', 'getState()', 'cannot get null state') // // } else { // // return currentState // // } // // } // sets current state function setState(state) { // if the previous state was not null, destroy it destroyState() // sets state to main menu if (state === MainMenuState) { currentState = require('./mainmenu-state.js') } // else if (state === LoadingState) { // sets state to loading // // currentState = require('./loading-state.js') // // } else if (state === PlayState) { // sets state to play // // currentState = require('./play-state.js') // // } // initializes the new state initState() } // initializes current state function initState() { if (currentState === null) { error.log('gamestate-manager.js', 'initState()', 'cannot init null state') } else { currentState.init(gameWindow, renderManager, inputManager) } } // resizes window of current state function resize() { if (currentState === null) { error.log('gamestate-manager.js', 'resize()', 'cannot resize window of null state') } else { currentState.resize() } } // calls update() method of current state function updateState() { if (currentState === null) { error.log('gamestate-manager.js', 'updateState()', 'cannot update null state') } else { currentState.update() } } // calls draw() method of current state function drawState() { if (currentState === null) { error.log('gamestate-manager.js', 'drawState()', 'cannot draw null state') } else { currentState.draw() } } // calls destroy method() of current state and then destroys that state function destroyState() { // only run this if the state is not null if (currentState !== null) { currentState.destroy() currentState = null } } // destroys gamestate manager vars and objects function destroy() { gameWindow = null renderManager = null inputManager = null currentState = null } module.exports = { MainMenuState, // LoadingState, // PlayState, initManager, setState, resize, updateState, drawState, destroy } <file_sep>/app/main.js // node files const nodepath = require('path') // node modules // node dev modules // core electron const electron = require('electron') // eslint-disable-line import/no-extraneous-dependencies // electron core modules const {app} = electron const {BrowserWindow} = electron // electron added modules // electron dev modules // js scripts let game // contains most main functions of game // window let gameWindow // main window object // creates game window function createGameWindow() { let win // sets some default window stuff win = new BrowserWindow({ // starting width of window width: 800, // minimum width of window minwidth: 800, // starting height of window height: 600, // minimum height of window minheight: 600, // sets false to create a frameless window frame: true }) // sets whether window menu should be shown or not // only works on windows and linux win.setMenu(null) // sets page of window win.loadURL(nodepath.join('file:/', __dirname, '/game.html')) // called when window is resized win.on('resize', () => { // resizes the canvas of the window game.resize() }) // called when window is closed win.on('closed', () => { // removes window object win = null }) return win } // called when app is ready app.on('ready', () => { // load js scripts here game = require('./game.js') // create game window gameWindow = createGameWindow() // init game game.init(gameWindow, app) // start game loop game.loop() }) // called before all windows have been closed app.on('before-quit', () => { // save anything here }) // called when all windows have been closed app.on('will-quit', () => { // destroy anything here gameWindow = null game = null }) <file_sep>/app/game.js // js scripts let gsm // manages gamestates let renderManager // draws stuff on the screen let inputManager // handles keyboard input // global vars let mainapp let gameWindow // var that tells when game is running let running // loads game saves // function load() {} // initializes game function init(win, app) { // load js scripts here gsm = require('./gamestate-manager.js') renderManager = require('./render-manager.js') inputManager = require('./input-Manager.js') // gets global vars mainapp = app gameWindow = win // init managers gsm.initManager(gameWindow, renderManager, inputManager) renderManager.initRenderer(gameWindow) inputManager.initManager(gameWindow, gsm, this) // must be called initially so the canvas is the correct size renderManager.resizeCanvas() // registers some debug keys inputManager.registerDebug() // sets starting state to main menu gsm.setState(gsm.MainMenuState) // tells game to start running running = true } // resizes game canvas and objects function resize() { // calls a specific states resize() method gsm.resize() } // updates game objects function update() { // calls a specific states update() method gsm.updateState() } // draws game objects function draw() { // calls a specific states draw() method gsm.drawState() } // saves game // function save() {} // destroys game function destroy() { // call specific destroy() methods here gsm.destroy() renderManager.destroy() inputManager.destroy() // destroy variables and objects here gameWindow = null gsm = null renderManager = null inputManager = null running = null } // quits application function quit() { // TODO: add check if user wants to save or not // stops main loop running = false // calls game destroy() method destroy() // calls app.quit() in main.js // invokes before-quit and will-quit events mainapp.quit() // cannot destrpy until quit() is called mainapp = null } // main game loop // updates and draws game function loop() { // TODO: update() and draw() need to loop at different intervals // what happens each frame function frame() { // only runs if init() has finished if (running) { // updates game objects update() // draws game objects to window draw() } } // how many times the frame method is called each second // measured in milliseconds so: 1000 milliseconds = 1 second // 1000 / 60 = ~60 frames a second let fps = 1000 // loops frame() method x(fps) amount of times setInterval(function () { frame() }, fps) } module.exports = { init, resize, loop, quit } <file_sep>/README.md # abenia Dwarf-Fortress-like game written in Javascript and run in Electron. <file_sep>/app/render-manager.js // global vars let gameWindow // game window // game window webContents Object let gameWebContents // simple way to get or update game webcontents function setGameWebContents() { // sets var equal to the game windows webContents gameWebContents = gameWindow.webContents } // inits the renderer code function initRenderer(win) { // gets global vars gameWindow = win // must be called to update webcontents setGameWebContents() // declares basic variables that will be used often here gameWebContents.executeJavaScript(` let c let ctx `) } // easy way to call renderer code function executejs(code) { // must be called to update webcontents setGameWebContents() // this code will usually always be needed gameWebContents.executeJavaScript(` c = document.getElementById('canvas') ctx = c.getContext('2d') ` + code + ` c = null ctx = null `) } // resizes canvas element to fit window function resizeCanvas() { // must be called to update webcontents setGameWebContents() // sets canvas size to inner window size executejs(` ctx.canvas.width = window.innerWidth ctx.canvas.height = window.innerHeight `) } // simple test function function drawToCanvas() { // must be called to update webcontents setGameWebContents() executejs(` ctx.fillStyle = 'black' ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height) `) } // destroys render vars and objects function destroy() { gameWebContents = null gameWindow = null } module.exports = { executejs, initRenderer, resizeCanvas, drawToCanvas, destroy } <file_sep>/app/input-manager.js // allows local electron shortcuts instead of global ones const inputManager = require('electron-localshortcut') // global vars let game // main game let gameWindow // game window let gsm // gamestate manager // key sets let debugKeys = ['1', 'q'] let mainMenuKeys = ['Up', 'w', 'Down', 's', 'e', 'Space', 'Enter'] // initializes input manager function initManager(win, gamestatemanager, g) { // gets global vars game = g gameWindow = win gsm = gamestatemanager } // simplifies key registering function reg(key, func) { inputManager.register(gameWindow, key, func) } // simplifies key unregistering function unReg(key) { inputManager.unregister(gameWindow, key) } // unregisters a set of keys function unRegSet(set) { // goes through the set and unregisters each key for (let i = 0; i < set.length; i++) { // unregisters the key unReg(set[i]) } } // registers some debug functions function registerDebug() { // sets state to main menu reg('1', () => { // sets state to main menu gsm.setState(gsm.MainMenuState) }) // quits reg('q', () => { // quits game.quit() }) } // unregisters debug key set function unRegisterDebug() { // unregisters debug key set unRegSet(debugKeys) } // registers main menu keys function registerMainMenu(state) { // moves up in main menu reg('Up', () => { // moves up in main menu state.moveUp() }) // moves up in main menu reg('w', () => { // moves up in main menu state.moveUp() }) // moves down in main menu reg('Down', () => { // moves down in main menu state.moveDown() }) // moves down in main menu reg('s', () => { // moves down in main menu state.moveDown() }) // selects an option in main menu reg('e', () => { // selects an option in main menu state.selectOption() }) // selects an option in main menu reg('Space', () => { // selects an option in main menu state.selectOption() }) // selects an option in main menu reg('Enter', () => { // selects an option in main menu state.selectOption() }) } // unregisters main menu key set function unRegisterMainMenu() { // unregisters main menu key set unRegSet(mainMenuKeys) } // unregisters all keys function unRegAll() { // unregisters all keys inputManager.unregisterAll(gameWindow) } // destroys input objects function destroy() { game = null gameWindow = null gsm = null } module.exports = { initManager, reg, unReg, unRegSet, registerDebug, unRegisterDebug, registerMainMenu, unRegisterMainMenu, unRegAll, destroy }
8b3dd191136bde572230227132d01a38e775e02f
[ "JavaScript", "Markdown" ]
6
JavaScript
8bitpickle/abenia
fbf60d8cc8f8b82566edcbc5fffabae04a1e2a5f
48d5089cfbd7a33ae63115c7eb3ef04ce7782073
refs/heads/master
<repo_name>jbwhite/todo<file_sep>/app/views/items/index.json.jbuilder json.array!(@items) do |item| json.extract! item, :id, :name, :description, :context, :priority, :deadline, :list_id json.url item_url(item, format: :json) end
d08d1691998eeec9a7d1f2519e8f38ad169d3396
[ "Ruby" ]
1
Ruby
jbwhite/todo
ef939c89015b5870f5389a2686572189b98dc33b
c2937cb99b8fec690b331bc90d001a698d195ac6
refs/heads/master
<file_sep><?php require_once __DIR__ . '/vendor/autoload.php'; class KirbyQRCode { public static function qrcode($page, $options = null) { $defaults = c::get('plugin.qrcode', array()); if (!$options) { $options = array(); } $settings = a::merge($defaults, $options); if (!a::get($settings, 'Text')) { $settings['Text'] = $page->url(); } if (!a::get($settings, 'Filename')) { $settings['Filename'] = $page->slug().'-qrcode'; } $qrCode = new Endroid\QrCode\QrCode(); foreach ($settings as $setter => $value) { $methodVariable = array($qrCode, 'set'.$setter); if (is_callable($methodVariable)) { $qrCode->{$methodVariable[1]}($value); } } $path = kirby()->roots()->thumbs().DS.$page->uri().DS; $url = kirby()->urls()->thumbs().DS.$page->uri().DS; $file = $settings['Filename'].'.'.$qrCode->getImageType(); dir::make($path); $qrCode->save($path.$file); return new Media($path.$file, $url.$file); } } $kirby->set( 'page::method', 'qrcode', function ($page, $options = null) { return KirbyQRCode::qrcode($page, $options); } ); $kirby->set('blueprint', 'fields/qrcode', __DIR__ . '/fields/qrcode/qrcode.yml'); $kirby->set('field', 'qrcode', __DIR__ . '/fields/qrcode'); <file_sep># Kirby QR Code ![GitHub release](https://img.shields.io/github/release/bnomei/kirby-qrcode.svg?maxAge=1800) ![License](https://img.shields.io/github/license/mashape/apistatus.svg) ![Kirby Version](https://img.shields.io/badge/Kirby-2.3%2B-red.svg) Kirby CMS Panel Field and Page-Method rendering a QR Code. This plugin is free but if you use it in a commercial project please consider to [make a donation 🍻](https://www.paypal.me/bnomei/5). Notes: - This plugin uses the [endroid/QrCode](https://github.com/endroid/QrCode) lib v1.9.3. - This plugin does not cache the image but recreate it on every request and will save it to the `/thumbs` folder (`kirby()->roots()->thumbs()`). ## Requirements - [**Kirby**](https://getkirby.com/) 2.3+ ## Installation ### [Kirby CLI](https://github.com/getkirby/cli) ``` kirby plugin:install bnomei/kirby-qrcode ``` ### Git Submodule ``` $ git submodule add https://github.com/bnomei/kirby-qrcode.git site/plugins/kirby-qrcode ``` ### Copy and Paste 1. [Download](https://github.com/bnomei/kirby-qrcode/archive/master.zip) the contents of this repository as ZIP-file. 2. Rename the extracted folder to `kirby-qrcode` and copy it into the `site/plugins/` directory in your Kirby project. ## Usage ### Field Add a kirby panel field to your blueprint to show a qrcode of the kirby `$page->url()` within the panel. This plugin uses a [global field definition](https://getkirby.com/docs/panel/blueprints/global-field-definitions) to cut some corners. Default paramters of QR code lib will be used to render the image or the parameters set in your `config.php`. ``` #fieldname: fieldtype qrcode: qrcode ``` ### Page Method The plugin also adds a `$page->qrcode()` function which returns an image as [Media object](https://github.com/getkirby/toolkit/blob/master/lib/media.php) to use in templates etc. You can use the default values, override them or set your own parameters on-the-fly using an associative array. Missing parameters will fallback to defaults of lib. ```php // DEFAULTS $qrcodeDefault = $page->qrcode(); // Kirby Toolkit Media Object // CUSTOM $allCustomParameters = [ 'Text' => $page->url(), // plugin default 'Size' => 300, 'Padding' => 10, 'ErrorCorrection' => 'high', 'ForegroundColor' => ['r' => 0, 'g' => 0, 'b' => 255, 'a' => 0], 'BackgroundColor' => ['r' => 255, 'g' => 255, 'b' => 255, 'a' =>0], 'Label' => 'You take the blue pill', 'LabelFontSize' => 16, 'ImageType' => Endroid\QrCode\QrCode::IMAGE_TYPE_PNG, // lib default 'Filename' => $page->slug().'-qrcode', // plugin default ]; // override defaults. this can be done in config.php as well. c::set('plugin.qrcode', $allCustomParameters); $qrcodeCustom = $page->qrcode(); // using new defaults now // or use them on-the-fly $qrcodeCustom = $page->qrcode([ 'Label' => 'You take the red pill', 'ForegroundColor' => ['r' => 255, 'g' => 0, 'b' => 0, 'a' => 0], 'ImageType' => Endroid\QrCode\QrCode::IMAGE_TYPE_JPEG, ]); // then use media object to get brick and echo the image // https://github.com/getkirby/toolkit/blob/master/lib/media.php#L539 echo $qrcodeCustom->html(); ``` ## Disclaimer This plugin is provided "as is" with no guarantee. Use it at your own risk and always test it yourself before using it in a production environment. If you find any issues, please [create a new issue](https://github.com/bnomei/kirby-qrcode/issues/new). ## License [MIT](https://opensource.org/licenses/MIT) It is discouraged to use this plugin in any project that promotes racism, sexism, homophobia, animal abuse, violence or any other form of hate speech. <file_sep><?php class QrcodeField extends BaseField { public static $fieldname = 'qrcode'; public static $assets = array( //'css' => array( // 'style.css', //) ); public function input() { $html = tpl::load(__DIR__ . DS . 'template.php', $data = array( 'page' => $this->page, 'fieldname' => self::$fieldname, )); return $html; } } <file_sep><?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit43d094404c78ddd222ae48dd01bec589 { public static $prefixLengthsPsr4 = array ( 'S' => array ( 'Symfony\\Component\\OptionsResolver\\' => 34, ), 'E' => array ( 'Endroid\\QrCode\\' => 15, ), ); public static $prefixDirsPsr4 = array ( 'Symfony\\Component\\OptionsResolver\\' => array ( 0 => __DIR__ . '/..' . '/symfony/options-resolver', ), 'Endroid\\QrCode\\' => array ( 0 => __DIR__ . '/..' . '/endroid/qrcode/src', ), ); public static $classMap = array ( 'Endroid\\QrCode\\Bundle\\Controller\\QrCodeController' => __DIR__ . '/..' . '/endroid/qrcode/src/Bundle/Controller/QrCodeController.php', 'Endroid\\QrCode\\Bundle\\DependencyInjection\\Configuration' => __DIR__ . '/..' . '/endroid/qrcode/src/Bundle/DependencyInjection/Configuration.php', 'Endroid\\QrCode\\Bundle\\DependencyInjection\\EndroidQrCodeExtension' => __DIR__ . '/..' . '/endroid/qrcode/src/Bundle/DependencyInjection/EndroidQrCodeExtension.php', 'Endroid\\QrCode\\Bundle\\EndroidQrCodeBundle' => __DIR__ . '/..' . '/endroid/qrcode/src/Bundle/EndroidQrCodeBundle.php', 'Endroid\\QrCode\\Bundle\\Twig\\Extension\\QrCodeExtension' => __DIR__ . '/..' . '/endroid/qrcode/src/Bundle/Twig/Extension/QrCodeExtension.php', 'Endroid\\QrCode\\Exceptions\\DataDoesntExistsException' => __DIR__ . '/..' . '/endroid/qrcode/src/Exceptions/DataDoesntExistsException.php', 'Endroid\\QrCode\\Exceptions\\FreeTypeLibraryMissingException' => __DIR__ . '/..' . '/endroid/qrcode/src/Exceptions/FreeTypeLibraryMissingException.php', 'Endroid\\QrCode\\Exceptions\\ImageFunctionFailedException' => __DIR__ . '/..' . '/endroid/qrcode/src/Exceptions/ImageFunctionFailedException.php', 'Endroid\\QrCode\\Exceptions\\ImageFunctionUnknownException' => __DIR__ . '/..' . '/endroid/qrcode/src/Exceptions/ImageFunctionUnknownException.php', 'Endroid\\QrCode\\Exceptions\\ImageSizeTooLargeException' => __DIR__ . '/..' . '/endroid/qrcode/src/Exceptions/ImageSizeTooLargeException.php', 'Endroid\\QrCode\\Exceptions\\ImageTypeInvalidException' => __DIR__ . '/..' . '/endroid/qrcode/src/Exceptions/ImageTypeInvalidException.php', 'Endroid\\QrCode\\Exceptions\\VersionTooLargeException' => __DIR__ . '/..' . '/endroid/qrcode/src/Exceptions/VersionTooLargeException.php', 'Endroid\\QrCode\\Factory\\QrCodeFactory' => __DIR__ . '/..' . '/endroid/qrcode/src/Factory/QrCodeFactory.php', 'Endroid\\QrCode\\QrCode' => __DIR__ . '/..' . '/endroid/qrcode/src/QrCode.php', 'Symfony\\Component\\OptionsResolver\\Debug\\OptionsResolverIntrospector' => __DIR__ . '/..' . '/symfony/options-resolver/Debug/OptionsResolverIntrospector.php', 'Symfony\\Component\\OptionsResolver\\Exception\\AccessException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/AccessException.php', 'Symfony\\Component\\OptionsResolver\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/ExceptionInterface.php', 'Symfony\\Component\\OptionsResolver\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/InvalidArgumentException.php', 'Symfony\\Component\\OptionsResolver\\Exception\\InvalidOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/InvalidOptionsException.php', 'Symfony\\Component\\OptionsResolver\\Exception\\MissingOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/MissingOptionsException.php', 'Symfony\\Component\\OptionsResolver\\Exception\\NoConfigurationException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/NoConfigurationException.php', 'Symfony\\Component\\OptionsResolver\\Exception\\NoSuchOptionException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/NoSuchOptionException.php', 'Symfony\\Component\\OptionsResolver\\Exception\\OptionDefinitionException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/OptionDefinitionException.php', 'Symfony\\Component\\OptionsResolver\\Exception\\UndefinedOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/UndefinedOptionsException.php', 'Symfony\\Component\\OptionsResolver\\Options' => __DIR__ . '/..' . '/symfony/options-resolver/Options.php', 'Symfony\\Component\\OptionsResolver\\OptionsResolver' => __DIR__ . '/..' . '/symfony/options-resolver/OptionsResolver.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit43d094404c78ddd222ae48dd01bec589::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit43d094404c78ddd222ae48dd01bec589::$prefixDirsPsr4; $loader->classMap = ComposerStaticInit43d094404c78ddd222ae48dd01bec589::$classMap; }, null, ClassLoader::class); } } <file_sep><?php // tpl(, $data) => $page, $fieldname // using lib defaults or config.php settings $qrcode = $page->qrcode()->html(); // media object to brick $div = brick('div') ->addClass('plugin-'.$fieldname) ->append($qrcode); echo $div;
afee69c88e67b30501ed184d13ab9689bd2a2abd
[ "Markdown", "PHP" ]
5
PHP
bnomei/kirby-qrcode
592ba7180ad15026a396cf1e17b43dc7c0aede61
b01eb292715e08bd07a9f468403167cb99711983
refs/heads/main
<file_sep>var webdriver = require("selenium-webdriver"); const LambdaTestRestClient = require('@lambdatest/node-rest-client'); const username = process.env.LT_USERNAME || '<EMAIL>'; const accessKey = process.env.LT_ACCESS_KEY || '<KEY>'; //set capabilities var caps = { name : 'Login Example', build : '1.0', version : '70', platform : 'Windows 10', screen_resolution : '1366x768', record_video : 'true', record_network : 'false', browserName : 'Chrome' }; const { By, until } = webdriver describe('webdriver', () => { let driver; beforeAll(async () => { driver = new webdriver.Builder() .usingServer( 'https://' + username + ':' + accessKey + '@hub.lambdatest.com/wd/hub' ) .withCapabilities(caps) .build(); await driver.get('https://prefeitura.pbh.gov.br/saude/licitacao/pregao-eletronico-151-2020'); },10000); afterAll(async () => { await driver.quit(); }, 10000); test('Successful Loading', async () => { output = await getElementByXpath(driver, "//html/body/div[1]/div/div[5]/div/div/div/div/div[1]/div/div/div/div[1]/div/h1" ); title = await output.getText(); expect(title).toEqual('Aviso de Intenção de Registro de Preços 151/2020 - SAÚDE'); test = await getElementByXpath(driver, "//html/body/div[1]/div/div[5]/div/div/div/div/div[1]/div/div/div/div[3]/div/div/div/div/div/div[2]/span/span[1]/span" ); publication = await test.getText(); expect(publication).toEqual('DATA DA PUBLICAÇÃO: ') testnew = await getElementByXpath(driver, "//html/body/div[1]/div/div[5]/div/div/div/div/div[1]/div/div/div/div[3]/div/div/div/div/div/div[2]/span/p[1]" ); object = await testnew.getText(); expect(object).toEqual('Registro de Preços pelo prazo de 12 meses, para aquisição de grampo galvanizado.') testbid = await getElementByXpath(driver, "/html/body/div[1]/div/div[5]/div/div/div/div/div[1]/div/div/div/div[3]/div/div/div/div/div/div[2]/span/span[6]/span" ); biddingdate = await testnew.getText(); expect(biddingdate).toEqual('DATA DA LICITAÇÃO: ') }); });
c559fbf5ae13160f8bbdce211ea03da31d065066
[ "JavaScript" ]
1
JavaScript
SriramRajasekaran/new
99d80ad8d4ed756cd7bdd18304e9216403c541ed
58b625a2c86dc433518b38c01c22be3c3290570a
refs/heads/master
<file_sep>#include<at89c51xd2.h> #include<stdio.h> void main() { int a=5,b=6; P0=a+b; }<file_sep>#include<at89c51xd2.h> #include<stdio.h> void main() { int a=5,b=6; P0=a+b; P1=b-a; P2=a*b; P3=b/a; }
89cc4dcf4760e6c1627549944398e2bc3343a3ee
[ "C" ]
2
C
mohan730/rep2
037ec9ed4dfdf7e22be395f5a68319037aa55d7c
cd0a9920d87342144f3bdcf1566835589d755a4b
refs/heads/master
<file_sep>public class GradeCalculatorException extends Exception { public GradeCalculatorException(String message) { super(message); } } <file_sep># myGrade Java FX application with clean user interface to help students calculate required grades needed on remaining assignments to achieve desired final grade in course
9bba4e36cf875407341ecc449fe74f43d511e247
[ "Markdown", "Java" ]
2
Java
atangent/myGrade
9936eb652eea573c2741aacd13c8257eb969491f
836f6628b6d3f8a8a669bb4370374fec443601b5
refs/heads/master
<file_sep># A = [10, 16, 8, 12, 15, 6, 3, 9,5] A = [16, 4, 2, 1, 17, 3] def swap(a, b): temp = A[a] A[a] = A[b] A[b] = temp def partition(i, j): pivot = i # i = 0 # j = len(A)-1 while(i < j): while(A[i] <= A[pivot]): i+=1 while(A[j] > A[pivot]): j-=1 #swap elements if (i<j): swap(i, j) swap(pivot, j) return j def quick_sort(i, j=len(A)-1): if (i < j): div = partition(i, j) quick_sort(i, div) quick_sort(div+1, j) else: return print(A) quick_sort(0) print(A)<file_sep># Algorithm 101 Here I try to list a number of popular algorithms starting with Sorting algos. Currently there is 3 sorting algirithm intregreted with the program and all of them sort in ascending order. These are- Merge Sort, Quick Sort, Insertion Sort. More is on the way... The program uses a plugin architecture, so that anyone can write an algorithm and easily integret it to the system. To run the program: >python main.py filename --sort_type algorithm name >python3 main.py filename --sort_type algorithm name >Current algorithm name as in program: - insertionSort - mergeSort - quickSort A sorted file will be placed with the sorted numbers in the sorted folder. The numbers should be placed in the data\ folder in txt format<file_sep>"QUICK SORT" class Plugin: def __init__(self, *args, **kwargs): print("Sort type: ", args) def swap(self, a, b, A): self.temp = A[a] A[a] = A[b] A[b] = self.temp def partition(self,i, j, A): self.pivot = i while (i < j): while (A[i] <= A[self.pivot]): i+=1 while (A[j] > A[self.pivot]): j-=1 # swap elements if (i<j): self.swap(i, j, A) self.swap(self.pivot, j, A) return j def quick_sort(self,i, j,A): if (i < j): div = self.partition(i, j,A) self.quick_sort(i, div,A) self.quick_sort(div+1, j, A) def Sort(self, A): j = len(A)-1 self.quick_sort(0, j,A)<file_sep>A = [1,6,7,8,4,20,44,30] """ Recursion""" "Here an array is divided in the middle recursively" def recursion(A): print("\t" + str(A)) n = len(A) if(n<2): print("\treturn = " + str(A)) return A else: mid = int(n/2) print("\t\tMid = " + str(mid)) left = [] right = [] for i in range(0,mid): left.append(A[i]) for i in range(mid,n): right.append(A[i]) print("\tLeft = " + str(left)) print("\t\t\tright = " + str(right)) recursion(left) recursion(right) recursion(A) <file_sep>import argparse import importlib import time """Commandline argument paser starts here""" parser = argparse.ArgumentParser(description='Process sorting data') parser.add_argument("file", type=str, help="Filename with data") parser.add_argument("--sort_type", type=str, help="Enter the type of sorting you want") args = parser.parse_args() """Commandline argument paser Ends here""" try: data = open('data/%s.txt'% args.file, encoding='utf-8').read().splitlines() print("Unsorted = " + str(data)) intdata = [int(item) for item in data] except IOError: print("File not found or path is incorrect") def sortResult(data, filename): f = open("sorted/%s.txt"% filename, "w") for item in data: f.write(str(item) + "\n") f.close() try: PLUGIN_NAME = 'sort.' + args.sort_type plugin_module = importlib.import_module(PLUGIN_NAME, '.') # print(plugin_module) plugin = plugin_module.Plugin(args.sort_type, key=123) print(plugin) except IOError: print("Wrong sorting algorithm or given name doesn not exits") start_time = time.time() plugin.Sort(intdata) print("Execution time: %s seconds" % (time.time() - start_time)) sortResult(intdata, args.sort_type) print("\nSorted = " + str(intdata)) <file_sep>A = [] "INSERTION SORT" print("Enter a list of number to be sorted. Enter 0 to quit input and start sorting") x = 1 while(x != "0"): x = input("Enter a number = ") A.append(int(x)) print(A) print("\n") for i in range(1,len(A)): marker = i checker = i-1 print("Checker = " + str(checker) + " Marker = " + str(marker) + "\n") while (checker>=0): if(A[checker] > A[marker]): temp = A[checker] A[checker] = A[marker] A[marker] = temp checker -= 1 marker -= 1 print("Iteration " + str(i) + " = " + str(A)) print("Sorted result = " + str(A)) <file_sep>A = [] "MERGE SORT" print("Enter a list of number to be sorted. Enter 0 to quit input and start sorting") x = 1 while(x != "0"): x = input("Enter a number = ") A.append(int(x)) print(A) print("\n") def merge(left,right,sorted): nL = len(left) nR = len(right) left_index = 0 right_index = 0 sort_index = 0 while(left_index < nL and right_index < nR): if (left[left_index] < right[right_index]): sorted[sort_index] = left[left_index] sort_index += 1 left_index += 1 else: sorted[sort_index] = right[right_index] sort_index += 1 right_index += 1 while(left_index < nL): sorted[sort_index] = left[left_index] sort_index += 1 left_index += 1 while(right_index < nR): sorted[sort_index] = right[right_index] sort_index += 1 right_index += 1 def merge_sort(A): # print(A) n = len(A) if(n<2): return A else: mid = int(n/2) # print("Mid = " + str(mid)) left = [] right = [] for i in range(0,mid): # print("i = " + str(i)) left.append(A[i]) for i in range(mid,n): right.append(A[i]) # print("Left = " + str(left)) # print("right = " + str(right)) merge_sort(left) merge_sort(right) merge(left, right,A) print("Unsorted = " + str(A)) merge_sort(A) print("Sorted = " + str(A)) <file_sep># A = [] "MERGE SORT" class Plugin: def __init__(self, *args, **kwargs): print("Sort type: ", args) def merge(self,left,right,sorted): nL = len(left) nR = len(right) left_index = 0 right_index = 0 sort_index = 0 while(left_index < nL and right_index < nR): if (left[left_index] < right[right_index]): sorted[sort_index] = left[left_index] sort_index += 1 left_index += 1 else: sorted[sort_index] = right[right_index] sort_index += 1 right_index += 1 while(left_index < nL): sorted[sort_index] = left[left_index] sort_index += 1 left_index += 1 while(right_index < nR): sorted[sort_index] = right[right_index] sort_index += 1 right_index += 1 def Sort(self, A): # print(A) n = len(A) if(n<2): return A else: mid = int(n/2) left = [] right = [] for i in range(0,mid): left.append(A[i]) for i in range(mid,n): right.append(A[i]) self.Sort(left) self.Sort(right) self.merge(left, right,A) # print("Unsorted = " + str(A)) # merge_sort(A) # print("Sorted = " + str(A))
34fdb2234ee59c9785bbfd0470f9d46bd05c9cd5
[ "Markdown", "Python" ]
8
Python
sayeedk06/algo-101
c988ed8587ab5561ee9903099458b24a3f05d928
c8234b4085c94eb1338d67b57d7abbccc85def0b
refs/heads/master
<repo_name>killerrin/Battle-of-Tyril-Android<file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/GameView.java package killerrinstudios.andrewgodfroy.battleoftyril; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.media.MediaPlayer; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; @SuppressWarnings("unused") public class GameView extends SurfaceView { public static SurfaceHolder holder; private GameLoopThread gameLoopThread; private GameTime gameTime; private float splashScreenTimer = 0; private float SPLASH_SCREEN_TIMER = 500f; // 1000 = 1 second // statics public static boolean developmentMode = true; public static boolean isMusicCurrentlyPlaying = false; public static boolean fixedthumbstick = false; public static boolean AdAdd = true; // Only here to delete errors public static String debugtext = ""; public static Random random; public static Touchpoints touchPoints; public static GameState gameState; public static MainMenu mainMenu; //public static ArcadeModeMenu arcadeModeMenu; public static PlayGameMenu playGameMenu; public static GameOverMenu gameOverMenu; public static Level arcadeLevel001; //public static Level arcadeLevel002; public GameView(Context context) { super(context); LoadContent(); gameLoopThread = new GameLoopThread(this); holder = getHolder(); holder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; gameLoopThread.setRunning(false); while (retry) { try { gameLoopThread.join(); retry = false; } catch (InterruptedException e) { } } } @Override public void surfaceCreated(SurfaceHolder holder) { gameLoopThread.setRunning(true); gameLoopThread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); } public void LoadContent() { Assets.TouchPointsTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.touch)); Assets.ThumbsticksTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.thumbstick)); Assets.KillerrinStudiosLogo = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.killerrinstudios)); Assets.KillerrinStudiosLogo.Position = Vector2.Subtract(Screen.GetCenter(), Assets.KillerrinStudiosLogo.GetOrigin()); Assets.PlayerShip01Texture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.ship001)); Assets.PlayerShip02Texture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.ship002)); Assets.EnemyShip01Texture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.enemy001)); Assets.PlasmaBoltTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.plasma)); //Assets.Level001BackgroundTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level1)); //Assets.Level001GameoverTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level1gameoverdeath)); //Assets.Level001WinTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level1gameovertimeup)); //Assets.Level002BackgroundTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level2)); //Assets.Level002GameoverTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level2gameoverdeath)); //Assets.Level002WinTexture = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level2gameovertimeup)); //------------------------------------------------- //------------------------------------------------- random = new Random(); gameTime = new GameTime(0.33f); gameState = GameState.MainMenu; touchPoints = new Touchpoints(Assets.TouchPointsTexture); //touchPoints = new Touchpoints(new XNAPaint(255,0,255,0), new Vector2(50,50)); VirtualThumbsticks.Texture = Assets.ThumbsticksTexture; VirtualThumbsticks._Paint = XNAPaint.White(); //--Levels--\\ arcadeLevel001 = new Level("Tyril", new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level1)), new Vector2(0, 0), XNAPaint.White()); arcadeLevel001.GameOverBackground = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level1gameoverdeath)); arcadeLevel001.GameWinBackground = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level1gameovertimeup)); //arcadeLevel001.ThumbOutline = blankTexture; //arcadeLevel002 = new Level("Sal'Dero", new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level2)), new Vector2(0, 0), XNAPaint.White()); //arcadeLevel002.GameOverBackground = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level2gameoverdeath)); //arcadeLevel002.GameWinBackground = new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.level2gameovertimeup));; //arcadeLevel002.ThumbOutline = blankTexture; System.out.println("LoadContent: Assets Loaded"); //--Menus--\\ mainMenu = new MainMenu(new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.titlescreen))); System.out.println("LoadContent: MainMenu Loaded"); playGameMenu = new PlayGameMenu(); System.out.println("LoadContent: PlayGameMenu Loaded"); //arcadeModeMenu = new ArcadeModeMenu(new Texture2D(BitmapFactory.decodeResource(getResources(), R.drawable.playerselection))); System.out.println("LoadContent: ArcadeModeMenu Loaded"); gameOverMenu = new GameOverMenu(); System.out.println("LoadContent: GameOverMenu Loaded"); } @SuppressLint("WrongCall") @Override protected void onDraw(Canvas canvas) { Update(gameTime); Draw(canvas); } @Override public boolean onTouchEvent(MotionEvent event) { synchronized(getHolder()) { if (gameState == GameState.SplashScreen) { gameState = GameState.MainMenu; } int numberOfTouches = event.getPointerCount(); int ctr = 0; //Clear the coordinates touchPoints.RectCoords.clear(); // Loop through every touch event and process it for (int i = 0; i < numberOfTouches; i++) { int xTouch = (int) event.getX(event.getPointerId(i)); int yTouch = (int) event.getY(event.getPointerId(i)); Vector2 touch = new Vector2(xTouch, yTouch); touchPoints.Update(touch); } VirtualThumbsticks.Update(event); } return true; } protected void Update(GameTime _gameTime) { synchronized(getHolder()) { if (gameState == GameState.None) {} else if (gameState == GameState.SplashScreen) { UpdateSplash(); } else if (gameState == GameState.MainMenu) { //if (mainMenu.CloseGame) { } mainMenu.Update(gameTime); } //else if (gameState == GameState.ArcadeSelection) { // arcadeModeMenu.Update(gameTime); //} else if (gameState == GameState.PlayGame) { //if (playGameMenu.CloseGame) { } playGameMenu.Update(gameTime); } else if (gameState == GameState.GameOver) { gameOverMenu.Update(gameTime); } if (developmentMode == true) { } } } protected void Draw(Canvas canvas) { synchronized(getHolder()) { // Clear the screen canvas.drawColor(Color.BLACK); //canvas.rotate(90); if (gameState == GameState.None) {} else if (gameState == GameState.SplashScreen) { DrawSplash(canvas); } else if (gameState == GameState.MainMenu) { mainMenu.Draw(canvas); } //else if (gameState == GameState.ArcadeSelection) { // arcadeModeMenu.Draw(canvas); //} else if (gameState == GameState.PlayGame) { playGameMenu.Draw(canvas); } else if (gameState == GameState.GameOver) { gameOverMenu.Draw(canvas); } if (developmentMode) { touchPoints.Draw(canvas); RenderText.Draw(canvas, "Touch X: "+ touchPoints.LastTappedX + " Touch Y: " + touchPoints.LastTappedY, new Vector2(10,10), new XNAPaint(255,255,0,0)); if (VirtualThumbsticks.LeftThumbstickCenter != null) { RenderText.Draw(canvas, "Left Thumbstick ID: "+ VirtualThumbsticks.leftId, new Vector2(10,30), new XNAPaint(255,255,0,0)); RenderText.Draw(canvas, " Left Touch Center: " + VirtualThumbsticks.LeftThumbstickCenter.X + " , " + VirtualThumbsticks.LeftThumbstickCenter.Y , new Vector2(10,40), new XNAPaint(255,255,0,0)); RenderText.Draw(canvas, "Left Touch Location: " + VirtualThumbsticks.LeftThumbstick().X + " , " + VirtualThumbsticks.LeftThumbstick().Y, new Vector2(10,50), new XNAPaint(255,255,0,0)); } if (VirtualThumbsticks.RightThumbstickCenter != null) { RenderText.Draw(canvas, "Right Thumbstick ID: "+ VirtualThumbsticks.rightId, new Vector2(10,70), new XNAPaint(255,255,0,0)); RenderText.Draw(canvas, " Right Touch Center: " + VirtualThumbsticks.RightThumbstickCenter.X + " , " + VirtualThumbsticks.RightThumbstickCenter.Y, new Vector2(10,80), new XNAPaint(255,255,0,0)); RenderText.Draw(canvas, " Right Touch Location: " + VirtualThumbsticks.RightThumbstick().X + " , " + VirtualThumbsticks.RightThumbstick().Y, new Vector2(10,90), new XNAPaint(255,255,0,0)); } } } } public void UpdateSplash () { synchronized(getHolder()) { splashScreenTimer += 0.33f; //gameTime.ElapsedGameTime.Milliseconds; if (splashScreenTimer >= SPLASH_SCREEN_TIMER) { gameState = GameState.None; splashScreenTimer = 0; } } } public void DrawSplash (Canvas spriteBatch) { synchronized(getHolder()) { Assets.KillerrinStudiosLogo.Draw(spriteBatch); //Vector2 position = Vector2.Subtract(Screen.GetCenter(),Assets.KillerrinStudiosLogo.GetOrigin()); //spriteBatch.drawBitmap(Assets.KillerrinStudiosLogo.bitmap, position.X, position.Y, XNAPaint.White().paint); } } }<file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/Rectangle.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Rect; public class Rectangle { int X; int Y; int Width; int Height; public Rectangle() { X = 0; Y = 0; Width = 0; Height = 0; } public Rectangle(Rect rect) { X = rect.left; Y = rect.top; Width = rect.right; Height = rect.bottom; } public Rectangle(int x, int y, int w, int h) { X = x; Y = y; Width = w; Height = h; } public Vector2 GetVectorXY() { return new Vector2(X, Y); } public Vector2 GetVectorWH() { return new Vector2(Width, Height); } public Rect GetRect() { return new Rect(X, Y, Width, Height); } boolean Intersects(Rectangle r) { return (GetRect().intersect(r.GetRect())); } boolean Intersects(Rect r) { return (GetRect().intersect(r)); } boolean Contains(Rectangle r) { return (GetRect().contains(r.GetRect())); } boolean Contains(Rect r) { return (GetRect().contains(r)); } } <file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/XNAPaint.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Paint; import android.graphics.Rect; public class XNAPaint { int a; int r; int g; int b; Paint paint; public XNAPaint(int a, int r, int g, int b) { paint = new Paint(); paint.setARGB(a, r, g, b); } public XNAPaint(Paint p) { a = p.getAlpha(); paint = p; } public Rectangle GetTextBounds(String text) { Rect rect = new Rect(); paint.getTextBounds(text, 0, text.length(), rect); return new Rectangle(rect.left, rect.top, rect.right, rect.bottom); } public static XNAPaint White() { return new XNAPaint(255,255,255,255); } public static XNAPaint Black() { return new XNAPaint(255,0,0,0); } public static XNAPaint Silver() { return new XNAPaint(255,192,192,192); } public static XNAPaint Red() { return new XNAPaint(255,255,0,0); } public static XNAPaint Green() { return new XNAPaint(255,0,255,0); } public static XNAPaint Blue() { return new XNAPaint(255,0,0,255); } public static XNAPaint LimeGreen() { return new XNAPaint(255,50,205,50); } public static XNAPaint DarkRed() { return new XNAPaint(255,139,0,0); } public static XNAPaint Sienna() { return new XNAPaint(255,160,82,45); } public static XNAPaint BlanchedAlmond() { return new XNAPaint(255,255,235,205); } } <file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/VirtualThumbsticks.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Canvas; import android.view.MotionEvent; public class VirtualThumbsticks { public static Texture2D Texture; public static XNAPaint _Paint; // the distance in screen pixels that represents a thumbstick value of 1f. private static float maxThumbstickDistance = 50f; // the current positions of the physical touches private static Vector2 leftPosition; private static Vector2 rightPosition; // the IDs of the touches we are tracking for the thumbsticks public static int leftId = -1; public static int rightId = -1; /// <summary> /// Gets the center position of the left thumbstick. /// </summary> public static Vector2 LeftThumbstickCenter; /// <summary> /// Gets the center position of the right thumbstick. /// </summary> public static Vector2 RightThumbstickCenter; public static int LeftID() { return leftId; } /// <summary> /// Gets the value of the left thumbstick. /// </summary> public static Vector2 LeftThumbstick() { // if there is no left thumbstick center, return a value of (0, 0) if (LeftThumbstickCenter == null) //!LeftThumbstickCenter.HasValue) return Vector2.Zero(); // calculate the scaled vector from the touch position to the center, // scaled by the maximum thumbstick distance Vector2 l = Vector2.Divide(Vector2.Subtract(leftPosition, LeftThumbstickCenter), maxThumbstickDistance); // if the length is more than 1, normalize the vector if (l.LengthSquared() > 1f) l.Normalize(); return l; } /// <summary> /// Gets the value of the right thumbstick. /// </summary> public static Vector2 RightThumbstick() { // if there is no left thumbstick center, return a value of (0, 0) if (RightThumbstickCenter == null) //!RightThumbstickCenter.HasValue) return Vector2.Zero(); // calculate the scaled vector from the touch position to the center, // scaled by the maximum thumbstick distance Vector2 r = Vector2.Divide(Vector2.Subtract(rightPosition, RightThumbstickCenter), maxThumbstickDistance); // if the length is more than 1, normalize the vector if (r.LengthSquared() > 1f) r.Normalize(); return r; } /// <summary> /// Updates the virtual thumbsticks based on current touch state. This must be called every frame. /// </summary> @SuppressWarnings({ "static-access", "unused" }) public static void Update(MotionEvent e) { Vector2 leftTouch = null; Vector2 rightTouch = null; Vector2 earliestTouch = null; int lID = -999; int rID = -999; int ctr = 0; int numberOfTouches = e.getPointerCount(); if (e.getAction() == e.ACTION_UP) { if (e.getY(e.getActionIndex()) < (Screen.Width / 2 )) { LeftThumbstickCenter = null; leftId = -1; } else if (e.getY(e.getActionIndex()) >= (Screen.Width / 2)) { // otherwise reset our values to not track any touches // for the right thumbstick RightThumbstickCenter = null; rightId = -1; } } else { for (int i = 0; i < numberOfTouches; i++) { try { if (e.getPointerId(i) == leftId) { leftTouch = new Vector2(e.getX(e.getPointerId(i)), e.getY(e.getPointerId(i))); lID = i; continue; } if (e.getPointerId(i) == rightId) { rightTouch = new Vector2(e.getX(e.getPointerId(i)), e.getY(e.getPointerId(i))); rID = i; continue; } // Get earliest touch earliestTouch = new Vector2(e.getX(e.getPointerId(i)), e.getY(e.getPointerId(i))); // Create new touch if (leftId == -1) { // if we are not currently tracking a left thumbstick and this touch is on the left // half of the screen, start tracking this touch as our left stick if (earliestTouch.Y < (Screen.Width / 2)) { leftTouch = earliestTouch; lID = i; continue; } } if (rightId == -1) { // if we are not currently tracking a right thumbstick and this touch is on the right // half of the screen, start tracking this touch as our right stick if (earliestTouch.Y >= (Screen.Width / 2)) { rightTouch = earliestTouch; rID = i; continue; } } ++ctr; } catch (IndexOutOfBoundsException ex) { break; } } //if we have a left touch if (leftTouch != null) { // if we have no center, this position is our center if (LeftThumbstickCenter == null) //!LeftThumbstickCenter.HasValue) LeftThumbstickCenter = leftTouch; // save the position of the touch leftPosition = leftTouch; // save the ID of the touch leftId = lID; } else { // otherwise reset our values to not track any touches // for the left thumbstick LeftThumbstickCenter = null; leftId = -1; } // if we have a right touch if (rightTouch != null) { // if we have no center, this position is our center if (RightThumbstickCenter == null) //!RightThumbstickCenter.HasValue) RightThumbstickCenter = rightTouch; // save the position of the touch rightPosition = rightTouch; // save the ID of the touch rightId = rID; } else { // otherwise reset our values to not track any touches // for the right thumbstick RightThumbstickCenter = null; rightId = -1; } } } public static void Draw(Canvas spriteBatch) { if (LeftThumbstickCenter != null) { Vector2 position = Vector2.Subtract(LeftThumbstickCenter, Texture.GetOrigin()); spriteBatch.drawBitmap(Texture.bitmap, position.X, position.Y, _Paint.paint); } if (RightThumbstickCenter != null) { Vector2 position = Vector2.Subtract(RightThumbstickCenter, Texture.GetOrigin()); spriteBatch.drawBitmap(Texture.bitmap, position.X, position.Y, _Paint.paint); } } }<file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/RenderText.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Canvas; import android.graphics.Rect; public class RenderText { public String Text; public Vector2 Location; public Rectangle CollideRectangle; public XNAPaint _Paint; //public SpriteFont Font; public RenderText(String text, Vector2 location, XNAPaint _paint) { Text = text; Location = location; _Paint = _paint; //Font = font; CollideRectangle = _paint.GetTextBounds(text); //Rect bounds = new Rect(); //_Paint.paint.getTextBounds(Text, 0, Text.length(), bounds); //CollideRectangle = new Rectangle((int)Location.X, (int)Location.Y, (int)bounds.width(), (int)bounds.height()); } public boolean Collides(Rectangle rect) { return CollideRectangle.Intersects(rect); } public boolean Collides(Rect rect) { return CollideRectangle.Intersects(rect); } public void Draw(Canvas spriteBatch) { spriteBatch.drawText(Text, Location.X, Location.Y, _Paint.paint); } public static void Draw(Canvas spriteBatch, String customText, Vector2 location, XNAPaint _paint) { spriteBatch.drawText(customText, location.X, location.Y, _paint.paint); } }<file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/OptionsMenu.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Canvas; public class OptionsMenu { private Texture2D optionsTexture; public Menu optionScreen; public OptionsMenu(Texture2D tex) { optionsTexture = tex; //Assets.OptionsMenuTexture; optionScreen = new Menu("Options", optionsTexture); } public void Update(GameTime gameTime) { int i = 0; if (i == 2)//(GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { GameView.gameState = GameState.MainMenu; GameView.touchPoints.ResetTouchpoints(); } } public void Draw (Canvas spriteBatch) { optionScreen.Draw(spriteBatch); } } <file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/Ship.java package killerrinstudios.andrewgodfroy.battleoftyril; import java.util.Random; import android.graphics.Canvas; import android.graphics.Matrix; public class Ship { //public Rectangle ScreenSize; public Rectangle CollideRectangle; public Texture2D Texture; public XNAPaint _Paint; public double MaxSpeed = 10.0; public float Rotation; public float Acceleration; public Vector2 Velocity; public Vector2 Position; public Vector2 SpriteOrigin; public Weapon MainWeapon; public double Health; public Random random; public Ship(Texture2D texture) { Texture = texture; //ScreenSize = new Rectangle(0, 0, MainActivity.width, MainActivity.height); Rotation = 0.0f; SpriteOrigin = new Vector2(Texture.Width / 2, Texture.Height / 2); } public Ship(Vector2 location, Texture2D texture) { Position = location; Texture = texture; Acceleration = 0.75f; //ScreenSize = new Rectangle(0, 0, MainActivity.width, MainActivity.height); _Paint = XNAPaint.White(); SpriteOrigin = new Vector2(Texture.Width / 2, Texture.Height / 2); Rotation = 0.0f; CollideRectangle = new Rectangle((int)location.X, (int)location.Y, texture.Width, texture.Height); } public Ship(Vector2 location, float acceletation, Texture2D texture) { Position = location; Texture = texture; Acceleration = acceletation; //ScreenSize = new Rectangle(0, 0, MainActivity.width, MainActivity.height); _Paint = XNAPaint.White(); SpriteOrigin = new Vector2(Texture.Width / 2, Texture.Height / 2); Rotation = 0.0f; CollideRectangle = new Rectangle((int)location.X, (int)location.Y, texture.Width, texture.Height); } // public Ship(Vector2 location, float acceletation, Texture2D texture, Rectangle screensize) // { // Position = location; // Texture = texture; // Acceleration = acceletation; // ScreenSize = screensize; // _Paint = XNAPaint.White(); // // SpriteOrigin = new Vector2(Texture.Width / 2, Texture.Height / 2); // // Rotation = 0.0f; // CollideRectangle = new Rectangle((int)location.X, (int)location.Y, texture.Width, texture.Height); // } public Ship(Vector2 location, float acceletation, Texture2D texture, XNAPaint _paint) { Position = location; Texture = texture; Acceleration = acceletation; //ScreenSize = screensize; _Paint = _paint; SpriteOrigin = new Vector2(Texture.Width / 2, Texture.Height / 2); Rotation = 0.0f; CollideRectangle = new Rectangle((int)location.X, (int)location.Y, texture.Width, texture.Height); } public boolean CheckCollision(Rectangle rect) { //UpdateCollisionRectangle(); if (CollideRectangle.Intersects(rect)) { return true; } else { return false; } } public void UpdateCollisionRectangle() { // Update the position CollideRectangle.X = (int)Position.X; CollideRectangle.Y = (int)Position.Y; } public void ClampToScreen() { if (Position.X < 0) { //Position.X = -ScreenSize.Width / 2f; Position = new Vector2(0, Position.Y); if (Velocity.X < 0f) { //Velocity.X = 0f; Velocity = new Vector2(0f, Velocity.Y); } } if (Position.X > Screen.Width) { //Position.X = ScreenSize.Width / 2f; Position = new Vector2(Screen.Width, Position.Y); if (Velocity.X > 0f) { //Velocity.X = 0f; Velocity = new Vector2(0f, Velocity.Y); } } if (Position.Y < 0) { //Position.Y = -ScreenSize.Height / 2f; Position = new Vector2(Position.X, 0); if (Velocity.Y < 0f) { //Velocity.Y = 0f; Velocity = new Vector2(Velocity.X, 0f); } } if (Position.Y > Screen.Height) { //Position.Y = ScreenSize.Height / 2f; Position = new Vector2(Position.X, Screen.Height); if (Velocity.Y > 0f) { //Velocity.Y = 0f; Velocity = new Vector2(Velocity.X, 0f); } } } public void Update(GameTime gameTime)//GameTime gameTime) { // add our velocity to our position to move the ship Position = Vector2.Multiply(Velocity, gameTime.Time);//gameTime.ElapsedGameTime.Milliseconds; UpdateCollisionRectangle(); } public Bullet Shoot() { return (new Bullet()); } public void Draw(Canvas spriteBatch) { Matrix matrix = new Matrix(); matrix.postRotate(Rotation); matrix.postTranslate(Position.X, Position.Y); spriteBatch.drawBitmap(Texture.bitmap, matrix, _Paint.paint); //spriteBatch.Draw(Texture, Position, null, Colour, Rotation, new Vector2(Texture.Width / 2f, Texture.Height / 2f), 1f, SpriteEffects.None, 0f); //texture, //Position, //null, //Color.White, //Rotation, //new Vector2(texture.Width / 2f, texture.Height / 2f), //1f, //SpriteEffects.None, //0f); } public void Draw(Canvas spriteBatch, XNAPaint _paint) { spriteBatch.drawBitmap(Texture.bitmap, Position.X, Position.Y, _paint.paint); } } <file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/MainActivity.java package killerrinstudios.andrewgodfroy.battleoftyril; import java.util.Random; import android.media.MediaPlayer; import android.os.Bundle; import android.app.Activity; import android.content.pm.ActivityInfo; import android.util.DisplayMetrics; import android.view.Menu; import android.view.Window; public class MainActivity extends Activity { static Random random = new Random(); static int Width; static int Height; @Override public void onCreate(Bundle savedInstanceState) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); Assets.MainMenuMusic = MediaPlayer.create(getApplicationContext(), R.raw.risetotheking); Assets.GameMusic = MediaPlayer.create(getApplicationContext(), R.raw.flightofthecrow); Assets.PauseSoundEffect = MediaPlayer.create(getApplicationContext(), R.raw.pauseambience); DisplayMetrics dimension = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dimension); Width = dimension.widthPixels; Height = dimension.heightPixels; Screen.SetScreen(Width, Height); setContentView(new GameView(this)); } @Override protected void onResume() { super.onResume(); Assets.MainMenuMusic = MediaPlayer.create(getApplicationContext(), R.raw.risetotheking); Assets.GameMusic = MediaPlayer.create(getApplicationContext(), R.raw.flightofthecrow); Assets.PauseSoundEffect = MediaPlayer.create(getApplicationContext(), R.raw.pauseambience); } @Override protected void onPause() { super.onPause(); //Assets.MainMenuMusic.release(); //Assets.GameMusic.release(); //Assets.PauseSoundEffect.release(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } <file_sep>/README.md # Battle-of-Tyril-Android A port of [Battle of Tyril](https://github.com/killerrin/Battle-of-Tyril-Python) to Android Final Project for the Android Development Class <file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/ModeSelectionMenu.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Canvas; public class ModeSelectionMenu { //private Texture2D modeSelectionTexture; private Menu modeScreen; private RenderText menuitem_modeselection_Arcade; public ModeSelectionMenu() { //modeSelectionTexture = tex; //Assets.ModeSelectionTexture; modeScreen = new Menu("Mode Selection", Assets.ArcadeModeTexture); menuitem_modeselection_Arcade = new RenderText("Arcade", new Vector2(80.0f, 220.0f), XNAPaint.LimeGreen()); // (80.0f, 220.0f) } public void Update(GameTime gameTime) { int i = 0; if (i == 2)//GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { GameView.gameState = GameState.MainMenu; GameView.touchPoints.ResetTouchpoints(); } if (menuitem_modeselection_Arcade.CollideRectangle.Contains(GameView.touchPoints.LastTapped)) { GameView.gameState = GameState.ArcadeSelection; GameView.touchPoints.ResetTouchpoints(); } } public void Draw (Canvas spriteBatch) { modeScreen.Draw(spriteBatch); menuitem_modeselection_Arcade.Draw(spriteBatch); } }<file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/Texture2D.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Bitmap; import android.graphics.Canvas; public class Texture2D { public Bitmap bitmap; public Vector2 Position; public XNAPaint _Paint; public int Width; public int Height; public Texture2D(Bitmap b) { bitmap = b; Width = b.getWidth(); Height = b.getHeight(); Position = new Vector2(0,0); _Paint = XNAPaint.White(); } public Texture2D(Bitmap b, Vector2 _position, XNAPaint _paint) { bitmap = b; Width = b.getWidth(); Height = b.getHeight(); Position = _position; _Paint = _paint; } public void Draw(Canvas spriteBatch) { spriteBatch.drawBitmap(bitmap, Position.X, Position.Y, _Paint.paint); } public void Draw(Canvas spriteBatch, Vector2 position) { spriteBatch.drawBitmap(bitmap, position.X, position.Y, _Paint.paint); } public void Draw(Canvas spriteBatch, Vector2 position, XNAPaint _paint) { spriteBatch.drawBitmap(bitmap, position.X, position.Y, _paint.paint); } // Wrapping Methods to allow for faster porting from Windows Phone public int GetWidth() { return Width; } public int getWidth() { return GetWidth(); } public int GetHeight() { return Height; } public int getHeight() { return GetHeight(); } public Vector2 GetWidthHeight() { return new Vector2((float)Width, (float)Height); } public Vector2 GetOrigin() { return new Vector2(Width / 2f, Height / 2f); } } <file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/ArcadeModeMenu.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Canvas; public class ArcadeModeMenu { //private Texture2D arcadeModeTexture; private Menu arcadeScreen; private RenderText menuitem_arcadeselection_StartGame; public ArcadeModeMenu(Texture2D arcTex) { //arcadeModeTexture = arcTex; //Assets.ArcadeModeTexture;//Content.Load<Texture2D>("Images/Backgrounds/Menus/Player Selection"); arcadeScreen = new Menu("Arcade", arcTex); menuitem_arcadeselection_StartGame = new RenderText("Start Game", new Vector2(350.0f, 400.0f), XNAPaint.Green()); GameView.playGameMenu.currentLevel = GameView.arcadeLevel001;// new Level("Tyril", level001Background, new Vector2(0, 0), Color.White, false); } public void Update(GameTime gameTime) { int i = 0; if (i == 2)//GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { GameView.gameState = GameState.MainMenu; // Put mode back to ModeSelect GameView.touchPoints.ResetTouchpoints(); } if (menuitem_arcadeselection_StartGame.CollideRectangle.Contains(GameView.touchPoints.LastTapped)) { GameView.gameState = GameState.PlayGame; GameView.touchPoints.ResetTouchpoints(); GameView.playGameMenu = new PlayGameMenu(); if (GameView.arcadeLevel001.Activated) { GameView.playGameMenu.currentLevel = GameView.arcadeLevel001; } //else if (GameView.arcadeLevel002.Activated) //{ // GameView.playGameMenu.currentLevel = GameView.arcadeLevel002; //} else// if (BoT.playGameMenu.currentLevel == null) { //Debug.WriteLine("No Level Selected... Defaulting."); GameView.playGameMenu.currentLevel = GameView.arcadeLevel001; } GameView.arcadeLevel001.Activated = false; //GameView.arcadeLevel002.Activated = false; //Debug.WriteLine("Loading Level: " + BoT.playGameMenu.currentLevel.Name.ToString()); GameView.mainMenu.isMusicPlaying = false; //if (GameView.isMusicCurrentlyPlaying) { song.Stop(); } //GameView.AdRemove = true; } else if (GameView.arcadeLevel001.ThumbRectangle.Contains(GameView.touchPoints.LastTapped)) { GameView.playGameMenu.currentLevel = GameView.arcadeLevel001; GameView.arcadeLevel001.Activated = true; //GameView.arcadeLevel002.Activated = false; //Debug.WriteLine(BoT.playGameMenu.currentLevel.Name.ToString() + " Selected"); } //else if (GameView.arcadeLevel002.ThumbRectangle.Contains(GameView.touchPoints.LastTapped)) //{ // GameView.playGameMenu.currentLevel = GameView.arcadeLevel002; // GameView.arcadeLevel001.Activated = false; // //GameView.arcadeLevel002.Activated = true; // //Debug.WriteLine(BoT.playGameMenu.currentLevel.Name.ToString() + " Selected"); //} } public void Draw (Canvas spriteBatch) { arcadeScreen.Draw(spriteBatch); GameView.arcadeLevel001.DrawThumbnail(spriteBatch, new Vector2(200, 200), 0.15f); //GameView.arcadeLevel002.DrawThumbnail(spriteBatch, new Vector2(400, 200), 0.15f); menuitem_arcadeselection_StartGame.Draw(spriteBatch); } }<file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/Level.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; public class Level { public String Name; public boolean Activated; public Texture2D Texture; public Texture2D GameBackground; public Texture2D GameOverBackground; public Texture2D GameWinBackground; public Texture2D ThumbOutline; public Vector2 Position; public XNAPaint _Paint; public Rectangle ThumbRectangle; public Level(String name, Texture2D texture, Vector2 position, XNAPaint paint) { Name = name; Texture = texture; GameBackground = texture; Position = position; _Paint = paint; Activated = false; ThumbRectangle = new Rectangle(0,0,0,0); } public Level(String name, Texture2D texture, Vector2 position, XNAPaint paint, boolean activated) { Name = name; Texture = texture; Position = position; _Paint = paint; Activated = activated; } public void Draw(Canvas spriteBatch) { spriteBatch.drawBitmap(Texture.bitmap, Position.X, Position.Y, _Paint.paint); //spriteBatch.Draw(Texture, Position, null, Colour, 0f, new Vector2(0,0), 0.63f, SpriteEffects.None, 0f); } public void DrawThumbnail(Canvas spriteBatch, Vector2 position, float scale) { ThumbRectangle = new Rectangle((int)position.X-96, (int)position.Y-58, (int)(Texture.GetWidth() * scale), (int)(Texture.GetHeight() * scale)); if (Activated == true) { Paint p = new Paint(); p.setColor(Color.GREEN); //spriteBatch.drawBitmap(ThumbOutline, // new Rect((int)(ThumbRectangle.left - 2), (int)(ThumbRectangle.top - 2), (int)ThumbRectangle.width() + 4, (int)ThumbRectangle.height() + 4), // Position.get // p); spriteBatch.drawRect(new Rect((int)(ThumbRectangle.X - 2), (int)(ThumbRectangle.Y - 2), (int)ThumbRectangle.Width + 4, (int)ThumbRectangle.Height + 4), p); } else { Paint p = new Paint(); p.setColor(Color.GRAY); //spriteBatch.drawBitmap(ThumbOutline, new Rect((int)(ThumbRectangle.left - 2), (int)(ThumbRectangle.top - 2), (int)ThumbRectangle.width() + 4, (int)ThumbRectangle.height() + 4), p); spriteBatch.drawRect(new Rect((int)(ThumbRectangle.X - 2), (int)(ThumbRectangle.Y - 2), (int)ThumbRectangle.Width + 4, (int)ThumbRectangle.Height + 4), p); } Matrix matrix = new Matrix(); matrix.preTranslate(position.X, position.Y); matrix.setScale(scale, scale); spriteBatch.drawBitmap(Texture.bitmap, matrix, _Paint.paint); //spriteBatch.Draw(Texture, position, null, Colour, 0f, new Vector2(Texture.Width/2, Texture.Height/2), scale, SpriteEffects.None, 0f); } }<file_sep>/src/killerrinstudios/andrewgodfroy/battleoftyril/Bullet.java package killerrinstudios.andrewgodfroy.battleoftyril; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Color; public class Bullet { public Weapon MainWeapon; public Vector2 Position; public Vector2 Direction; public Rectangle CollideRectangle; public int DeathCounter; public Bullet() { DeathCounter = 1; } public Bullet(Weapon weapon, Vector2 position, Vector2 direction) { MainWeapon = weapon; Position = position; Direction = direction; DeathCounter = 0; CollideRectangle = new Rectangle((int)position.X, (int)position.Y, weapon.Texture.getWidth(), weapon.Texture.getHeight()); } public boolean CheckCollision(Rect rect) { if (CollideRectangle.Intersects(rect)) { return true; } else { return false; } } public void UpdateCollisionRectangle() { // Update the position CollideRectangle.X = (int)Position.X; CollideRectangle.Y = (int)Position.Y; } public void Update(GameTime gameTime) { if (DeathCounter == 0) { Position = new Vector2((Position.X + Direction.X * (float)MainWeapon.Speed), (Position.Y + Direction.Y * (float)MainWeapon.Speed)); //CollideRectangle = new Rectangle((int)Position.X, (int)Position.Y, //(int)MainWeapon.Texture.getWidth(), (int)MainWeapon.Texture.getHeight()); UpdateCollisionRectangle(); } } public void Draw(Canvas spriteBatch) { Paint paint = new Paint(); paint.setColor(Color.GREEN); //paint.setARGB(255, 0, 255, 0); //spriteBatch.drawBitmap(MainWeapon.Texture, Position, Color.Green); spriteBatch.drawBitmap(MainWeapon.Texture.bitmap, Position.X, Position.Y, paint); } }
a2d5debf09597307fb7825843cad9105c980c9af
[ "Markdown", "Java" ]
14
Java
killerrin/Battle-of-Tyril-Android
35d3c8085bb96426f82e47fb7250a81f7673c1b0
27a5e3f1be08db9f0b6b939d89769f5043e43cb3
refs/heads/master
<file_sep>#!/usr/bin/python # # What is this? # This Lambda function will probe (via HTTP or HTTPS) remote destinations and # if all of them are unavailable it will bring stand up a VPN connection so # that connectivity can be restored. It will then send a notification via SNS # with the config details. # # WARNING: # If you do not define a preshared key for the tunnel (see below) then this # code will send the auto-generated preshared key for each IPSEC tunnel via # SNS which could well be via an unencrypted transport. Please be careful. # # Why would I do this? # Just in case everything falls apart and you need an automatic network # backdoor to your environment. # # How do I run it? # Set up a CloudWatch Event to run this Lambda function. You might run it # every 5 minutes or so. # # What IAM permissions does it need? # In addition to the basic Lambda permissions (so that CloudWatch Logs can be # created and written) you'll also need the following: # ec2:AttachVpnGateway # ec2:CreateTags # ec2:CreateVpnGateway # ec2:CreateCustomerGateway # ec2:CreateVpnConnectionRoute # ec2:DescribeVpnGateways # ec2:CreateVpnConnection # sns:Publish (which can be restricted to your topic ARN) # # How do I configure it? # There are a bunch of environment variables you can set to control the way # this function operates. They are shown below. # Make sure that you set the function timeout to a long enough time for # network operations to time out. So perhaps 60 seconds or so depending on # how many remote targets you're checking as the timeout for each target is # 10 seconds so it will take that long to discover that a remote host isn't # responding. # Make sure the Lambda function runs inside a VPC (preferably the VPC you're # going to put the VPN into) because checking connectivity outside the VPC # doesn't make a lot of sense. # Create a SNS topic as well - you'll need that. # # Is there anything I should know? # This code uses a static CIDR block for the tunnel inside address: # 169.254.169.248/30 - you can change it in the code if you like. # # Troubleshooting # You can run this at the command line of any Linux instance with Python and # boto3 installed. Set the environment variables by doing "export TARGET=xxx" # and so on. That way you can check that everything is working without having # to work within the constraints of debugging on Lambda. You should probably # do this on an Amazon Linux instance for compatibiltiy reasons. # # Environment variables: # TARGETS # Mandatory - must be set. # Comma separated list of IP address/hosts and port numbers to be polled. # Target port must be 80 (HTTP) or 443 (HTTPS). # If any one target responds, we consider the link in question up and no VPN will be created. # Example: 192.168.1.1:80,192.168.2.2:443 # # REMOTEIP # Mandatory - must be set. # This is the remote public IP address of your VPN server. # Example: 169.254.4.5 # (yes, I'm aware that isn't a real public IP address) # # PRESHAREDKEY # Optional - use this to set up a preshared key that you will use. This is # quite useful because it means your firewall/VPN termination endpoint can # be preconfigured. If you do not set this the AWS service will generate a # preshared key for you and you will need to configure the VPN endpoint # before traffic will flow. # # VPCID # Mandatory - must be set. # This is the VPC that the VPN will be attached to. # Example: vpc-0b8c227ad264f7bb3 # # DESTINATIONCIDR # Mandatory - must be set. # This is a comma-separated list of CIDR blocks that will be added as static # routes to the VPN connection. # Example: 192.168.1.0/24,192.168.2.0/24 # # SNSTOPIC # Optional but you should set it otherwise what's the point? # This is the SNS topic that the VPN configuration will be sent to. If this # isn't set you won't get a notification. # Example: arn:aws:sns:ap-southeast-2:111122223333:NetworkBreakGlass # # FORCEVPN # Optional. # If this environment variable is present (i.e. with any setting in it) it # forces the Lambda function to bring up the VPN. This is useful for # testing that it works. # Example: TRUE # import boto3 import logging import os from xml.dom import minidom from botocore.vendored import requests Logger = None MyTag = 'BreakGlass' ConnectionTimeout = 10 # Only wait for 10 seconds for each target CustomerConfig = None def CheckTargets(Targets): global Logger,ConnectionTimeout TargetStates = [] Schemas = {} Schemas['80'] = 'http' Schemas['443'] = 'https' TargetList = Targets.split(',') Logger.debug('Working with %d targets' % len(TargetList)) for Target in TargetList: Logger.debug('Checking %s' % Target) try: (Address, Port) = Target.split(':') except: Logger.error('Failed to extract ADDRESS:PORT from %s' % Target) continue if Port not in Schemas: Logger.error('Port not listed in schemas for this to work - ignoring %s' % Target) continue Logger.info('Connecting to %s://%s' % (Schemas[Port],Address)) try: Response = requests.head(Schemas[Port]+'://'+Address, timeout=ConnectionTimeout) Logger.info('Connect succeeded') # We actually don't care what the response is TargetStates.append(True) except Exception as e: Logger.info('Connect failed: %s' % str(e)) TargetStates.append(False) return any(TargetStates) def NotifyViaSNS(PreSharedKey): global Logger,CustomerConfig SNSTopic = os.getenv('SNSTOPIC') if SNSTopic == None: Logger.error('SNSTOPIC not set - cannot send notification') return Logger.debug('SNSTOPIC: %s' % SNSTopic) # # First, let's extract the pertinent information from the XML (!) # configuration that was passed to us when we created the VPN # connection. Yes this is a little ugly but it means we don't have # to import any libraries that aren't shipped with Lambda by default. # Logger.debug('CustomerConfig (XML): %s' % CustomerConfig) PresharedKeys = [] AWSPublicAddresses = [] AWSInsideAddresses = [] CustomerInsideAddresses = [] CustomerPublicAddresses = [] CustomerPublicAddresses = [] Tunnels = minidom.parseString(CustomerConfig).getElementsByTagName('ipsec_tunnel') for T in Tunnels: try: PSK = T.getElementsByTagName('ike')[0].getElementsByTagName('pre_shared_key')[0].firstChild.wholeText CPA = T.getElementsByTagName('customer_gateway')[0].getElementsByTagName('tunnel_outside_address')[0].getElementsByTagName('ip_address')[0].firstChild.wholeText APA = T.getElementsByTagName('vpn_gateway')[0].getElementsByTagName('tunnel_outside_address')[0].getElementsByTagName('ip_address')[0].firstChild.wholeText CIA = T.getElementsByTagName('customer_gateway')[0].getElementsByTagName('tunnel_inside_address')[0].getElementsByTagName('ip_address')[0].firstChild.wholeText AIA = T.getElementsByTagName('vpn_gateway')[0].getElementsByTagName('tunnel_inside_address')[0].getElementsByTagName('ip_address')[0].firstChild.wholeText except Exception as e: Logger.warning('Did not extract configuration from XML: %s' % str(e)) continue Logger.debug('Preshared key: %s' % PSK) Logger.debug('Customer public IP: %s' % CPA) Logger.debug('AWS public IP: %s' % APA) Logger.debug('Customer inside IP: %s' % CIA) Logger.debug('AWS inside IP: %s' % AIA) PresharedKeys.append(PSK) CustomerPublicAddresses.append(CPA) AWSPublicAddresses.append(APA) CustomerInsideAddresses.append(CIA) AWSInsideAddresses.append(AIA) # # If the tunnel pre-shared key was specified externally then we won't bother # sending it via SNS - it's more secure this way. # if PreSharedKey is not None: PresharedKeys[0] = '<defined by user>' PresharedKeys[1] = '<defined by user>' # # Now we can tell someone what we've been doing. # if len(PresharedKeys) == 0: Logger.warning('Failed to extract any configuration details - notification will be empty') MessageText = 'No configuration details could be found - sorry about that!' else: MessageText = "Configuration details:\n\n" MessageText += 'Tunnel 1:\n Preshared key: %s\n AWS public IP: %s\n Your IP: %s\n AWS tunnel IP: %s\n Your tunnel IP: %s\n' % \ (PresharedKeys[0],AWSPublicAddresses[0],CustomerPublicAddresses[0],AWSInsideAddresses[0],CustomerInsideAddresses[0]) if len(PresharedKeys) > 1: MessageText += '\nTunnel 2:\n Preshared key: %s\n AWS public IP: %s\n Your IP: %s\n AWS tunnel IP: %s\n Your tunnel IP: %s\n' % \ (PresharedKeys[1],AWSPublicAddresses[1],CustomerPublicAddresses[1],AWSInsideAddresses[1],CustomerInsideAddresses[1]) Logger.info('Sending SNS notification to %s' % SNSTopic) Logger.debug('Message text: %s' % MessageText) SNS = boto3.client('sns') try: Response = SNS.publish(TopicArn=SNSTopic, Subject='Network Break Glass Activated', Message=MessageText) except Exception as e: Logger.warning('SNS notification failed: %s' % str(e)) return def TagResource(ResourceId): global Logger,MyTag EC2 = boto3.client('ec2') Logger.debug('Tagging resource %s' % ResourceId) try: Response = EC2.create_tags(Resources=[ResourceId], Tags=[{'Key':'Name','Value':MyTag}]) except Exception as e: Logger.error('Failed to tag resource %s' % ResourceId) # # Only one VPG can be attached to a VPC at a time. So we first check to see if # there is one there - if so, we return the resource id for it. If not, we # create one and tag it appropriately. # def CreateOrFindVPG(VPCId): global Logger EC2 = boto3.client('ec2') Logger.debug('Looking for existing VPG') Logger.debug('Looking for existing VPG with tag %s' % MyTag) try: VPG = EC2.describe_vpn_gateways(Filters=[{'Name':'attachment.vpc-id','Values':[VPCId]}]) except Exception as e: Logger.error('describe_vpn_gateways failed: %s' % str(e)) return '' # Something bad happend - let's not try and create a VPG Logger.debug('Number of VPGs found: %d' % len(VPG['VpnGateways'])) if len(VPG['VpnGateways']) > 0: for Gateway in VPG['VpnGateways']: if Gateway['State'] == 'available': VPGId = Gateway['VpnGatewayId'] Logger.info('Existing VPG found: %s' % VPGId) return VPGId # # No VPG for this VPC so let's create one and tag it to be nice # try: VPGCreate = EC2.create_vpn_gateway(Type='ipsec.1') except Exception as e: Logger.error('Failed to create VPG: %s' % str(e)) return '' VPGId = VPGCreate['VpnGateway']['VpnGatewayId'] Logger.info('Created VPG: %s' % VPGId) TagResource(VPGId) Logger.debug('Attaching VPG %s to VPC %s' % (VPGId,VPCId)) try: VPGAttach = EC2.attach_vpn_gateway(VpcId=VPCId, VpnGatewayId=VPGId) except Exception as e: Logger.error('Failed to attach VPG %s to VPC %s: %s' % (VPGId,VPCId,str(e))) return '' State = VPGAttach['VpcAttachment']['State'] Logger.debug('Attachment state: %s' % State) if State != 'attaching' and State != 'attached': Logger.error('VPG attachment state is odd: %s - aborting' % State) return '' return VPGId # # Create the customer gateway - note that if it already exists we don't # get an error, we are returned the id of the existing gateway. # def CreateCustomerGateway(RemoteIP): global Logger EC2 = boto3.client('ec2') Logger.debug('Creating customer gateway %s' % RemoteIP) try: CustomerGateway = EC2.create_customer_gateway(BgpAsn=65000, PublicIp=RemoteIP, Type='ipsec.1') except Exception as e: Logger.error('Failed to create customer gateway: %s' % str(e)) return '' CGWId = CustomerGateway['CustomerGateway']['CustomerGatewayId'] Logger.debug('Customer gateway id: %s' % CGWId) TagResource(CGWId) return CGWId def CreateVPNConnection(CGWId, VPGId, PreSharedKey): global Logger,SourceData,CustomerConfig CustomerConfig = None EC2 = boto3.client('ec2') ConnectionOptions = {'StaticRoutesOnly':True} if PreSharedKey is not None: ConnectionOptions['TunnelOptions'] = [{'PreSharedKey':PreSharedKey}] Logger.debug('Creating VPN connection') try: VPNConnection = EC2.create_vpn_connection(CustomerGatewayId=CGWId, Type='ipsec.1', VpnGatewayId=VPGId, Options=ConnectionOptions) except Exception as e: Logger.error('Failed to create VPN connection: %s' % str(e)) return '' VPNId = VPNConnection['VpnConnection']['VpnConnectionId'] Logger.debug('VPN connection id: %s' % VPNId) TagResource(VPNId) CustomerConfig = VPNConnection['VpnConnection']['CustomerGatewayConfiguration'] return VPNId def CreateVPN(): global Logger RemoteIP = os.getenv('REMOTEIP') if RemoteIP == None: Logger.error('REMOTEIP not set - cannot create VPN') return Logger.debug('REMOTEIP: %s' % RemoteIP) VPCId = os.getenv('VPCID') if VPCId == None: Logger.error('VPCID not set - cannot create VPN') return Logger.debug('VPCID: %s' % VPCId) DestinationCIDRRanges = os.getenv('DESTINATIONCIDR') if DestinationCIDRRanges == None: Logger.error('DESTINATIONCIDR not set - cannot create VPN') return Logger.debug('VPCID: %s' % VPCId) PreSharedKey = os.getenv('PRESHAREDKEY') if PreSharedKey == None: Logger.info('PRESHAREDKEY not set - one will be auto-generated') else: Logger.debug('PRESHAREDKEY: %s' % PreSharedKey) Logger.info('Creating VPN connection...') VPGId = CreateOrFindVPG(VPCId) if len(VPGId) == 0: Logger.info('Could not create or find a VPG - stopping') return CGWId = CreateCustomerGateway(RemoteIP) if len(CGWId) == 0: Logger.info('Could not create customer gateway - stopping') return VPNId = CreateVPNConnection(CGWId, VPGId, PreSharedKey) if len(VPNId) == 0: Logger.info('Could not create VPN connection - stopping') return EC2 = boto3.client('ec2') for Destination in DestinationCIDRRanges.split(','): Logger.debug('Adding static route %s' % Destination) try: StaticRoute = EC2.create_vpn_connection_route(DestinationCidrBlock=Destination, VpnConnectionId=VPNId) except Exception as e: Logger.error('Failed to add static route: %s' % str(e)) return Logger.info('Successfully created VPN connection %s' % VPNId) Logger.debug('Remote IP: %s' % RemoteIP) # # We're successful so notify people. # NotifyViaSNS(PreSharedKey) return def lambda_handler(event, context): global Logger logging.basicConfig() Logger = logging.getLogger() Logger.setLevel(logging.INFO) TargetList = os.getenv('TARGETS') if TargetList == None : Logger.error('TARGETS not set - stopping') return False Logger.info('Targets: %s' % TargetList) ForceVPN = os.getenv('FORCEVPN') if ForceVPN != None: Logger.info('FORCEVPN set - bringing up VPN') CreateVPN() else: Connectivity = CheckTargets(TargetList) Logger.debug('Overall connectivity is %s' % Connectivity) if not Connectivity: Logger.info('Connectivity check failed - bringing up VPN') CreateVPN() return True if __name__ == '__main__': lambda_handler('', '') <file_sep># NetworkBreakGlass AWS Lambda function to automatically bring up VPN connection in case of network connectivity loss. # What is this? This Lambda function will probe (via HTTP or HTTPS) remote destinations and if all of them are unavailable it will bring stand up a VPN connection so that connectivity can be restored. It will then send a notification via SNS with the config details. The intention is that if your Direct Connect (DX) fails and you don't want to have a permanent backup VPN connection this will create one for you. You would configure the probes to check for the reachability of services across your DX. ## WARNINGS: If you let the AWS VPN service generate a preshared key then this utility will send generated preshared key for the IPSEC tunnels via SNS which could well be via an unencrypted transport. Please be careful. You can avoid this by specifying the preshared key that you want to use. #### Why would I want to use this? Just in case everything falls apart and you need an automatic network backdoor to your environment. #### How do I run it? Set up a CloudWatch Event to run this Lambda function. You might run it every 5 minutes or so. #### What IAM permissions does it need? In addition to the basic Lambda permissions (so that CloudWatch Logs can be created and written) you'll also need the following: ec2:AttachVpnGateway ec2:CreateTags ec2:CreateVpnGateway ec2:CreateCustomerGateway ec2:CreateVpnConnectionRoute ec2:DescribeVpnGateways ec2:CreateVpnConnection sns:Publish (which can be restricted to your topic ARN) #### How do I configure it? There are a bunch of environment variables you can set to control the way this function operates. They are shown below. Make sure that you set the function timeout to a long enough time for network operations to time out. So perhaps 60 seconds or so depending on how many remote targets you're checking as the timeout for each target is 10 seconds so it will take that long to discover that a remote host isn't responding. Make sure the Lambda function runs inside a VPC (preferably the VPC you're going to put the VPN into) because checking connectivity outside the VPC doesn't make a lot of sense. Create a SNS topic as well - you'll need that. #### Is there anything I should know? This code uses a static CIDR block for the tunnel inside address: 169.254.169.248/30 - you can change it in the code if you like. #### Troubleshooting You can run this at the command line of any Linux instance running in AWS with Python and boto3 installed. Set the environment variables by doing "export TARGET=xxx" and so on. That way you can check that everything is working without having to work within the constraints of debugging on Lambda. You should probably do this on an Amazon Linux instance for compatibiltiy reasons. ## Environment variables: #### TARGETS Mandatory - must be set. Comma separated list of IP address/hosts and port numbers to be polled. Target port must be 80 (HTTP) or 443 (HTTPS). If any one target responds, we consider the link in question up and no VPN will be created. Example: 192.168.1.1:80,192.168.2.2:443 #### REMOTEIP Mandatory - must be set. This is the remote public IP address of your VPN server. Example: 169.254.4.5 (yes, I'm aware that isn't a real public IP address) #### PRESHAREDKEY Optional - use this to set up a preshared key that you will use. This is quite useful because it means your firewall/VPN termination endpoint can be preconfigured. If you do not set this the AWS service will generate a preshared key for you and you will need to configure the VPN endpoint before traffic will flow. #### VPCID Mandatory - must be set. This is the VPC that the VPN will be attached to. Example: vpc-0b8c227ad264f7bb3 #### DESTINATIONCIDR Mandatory - must be set. This is a comma-separated list of CIDR blocks that will be added as static routes to the VPN connection. Example: 192.168.1.0/24,192.168.2.0/24 #### SNSTOPIC Optional but you should set it otherwise what's the point? This is the SNS topic that the VPN configuration will be sent to. If this isn't set you won't get a notification. Example: arn:aws:sns:ap-southeast-2:111122223333:NetworkBreakGlass #### FORCEVPN Optional. If this environment variable is present (i.e. with any setting in it) it forces the Lambda function to bring up the VPN. This is useful for testing that it works. Example: TRUE
4143e1727ac9586319c2d85a1364e6b58bfe22dd
[ "Markdown", "Python" ]
2
Python
Brettles/NetworkBreakGlass
ef749dda0f20fe73a02b6b7b148f426d5587d880
afaeb1b1480f982c28cb21de78dfd50b58906d1e
refs/heads/main
<repo_name>PorkPies/ToHackHealth<file_sep>/hackathon.py import streamlit as st import pandas as pd import numpy as np import matplotlib.pyplot as plt from PIL import Image import seaborn as sns import plotly.express as px import json import os from urllib.request import urlopen import json sns.set_style("whitegrid") sns.set_palette("husl") st.set_option('deprecation.showPyplotGlobalUse', False) # insert at 1, 0 is the script path (or '' in REPL) def add_US(df): USA = df.groupby('Year',as_index= False).mean() USA['State Name'] = 'All States' df = pd.concat([USA,df]) df = df.set_index(['State Name','Year']) return df def space(): st.write("") st.write("") st.write("") st.write("") os.chdir(r"C:\Users\samal\OneDrive\Documents\Hackathon") df = pd.read_csv("combined.csv") state_names = df['State Name'].unique() df = add_US(df) future_df = pd.read_csv("future.csv") future_df = add_US(future_df) diseases = ['Asbestosis', 'Asthma', 'Chronic obstructive pulmonary disease', 'Chronic respiratory diseases', 'Coal workers pneumoconiosis', 'Interstitial lung disease and pulmonary sarcoidosis', 'Other chronic respiratory diseases', 'Other pneumoconiosis', 'Pneumoconiosis', 'Silicosis'] pollution =['Carbon monoxide', 'Nitrogen dioxide (NO2)', 'Outdoor Temperature', 'Ozone', 'PM10 Total 0-10um STP', 'Sulfur dioxide'] ############ Introduction ############# st.title("US Respiratory Illness Death Rate vs Air Quality Dashboard") st.write("Welcome! :grin:") st.write("This interactive website visualises the affect of air quality on respiratory health using data from the US.") st.write("<- To get started you can change which US State you want to look at on the left hand side.") space() #### line graph plots ######### st.write("COMPARISON") st.write("You can compare a range of different illnesses and air quality metrics and the correlation between the two will be calculated.") state_option = st.sidebar.selectbox("Which state do you want to look at?",df.reset_index()["State Name"].unique()) resp_illness = st.selectbox("Which illness do you want to focus on?", diseases ) air_quality = st.selectbox("Which air quality metric do you want to compare against?", pollution) comparison_df = df.loc[state_option][[resp_illness, air_quality]] corr_df = df.corr() correlation = corr_df .loc[resp_illness][air_quality] sns.lineplot(x=resp_illness, y=air_quality, data=comparison_df,legend = 'auto', label='Correlation = {:.2f}'.format(correlation)) st.pyplot() space() ##### correlation plot ######### # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr_df , dtype=bool)) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(230, 20, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr_df , mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) st.pyplot() space() ########## bar chart for the disease in a given year st.write("YEARLY") st.write("You can see how respiratory illness death rate has changed over the years by sliding the time bar.") #print(df.reset_index().Year.min()) #print(df.reset_index().Year.max()) year = st.slider('What year?', int(df.reset_index().Year.min()), int(df.reset_index().Year.max())) bar_df = pd.DataFrame() bar_df['Death Rate'] = df.loc[state_option,year][diseases].values bar_df['Respiratory Disease'] = diseases plt.figure() sns.barplot(x='Respiratory Disease', y='Death Rate', data=bar_df) plt.xticks(rotation=90) plt.ylim(0,60) st.pyplot() space() #### future line graph plots ######### st.write("FORECASTING") st.write("We forecasted future values using a temporal convolutional neural network that is trained on over thirty years of data to predict into 2025, the machine learning model architecture is seen below.") image = Image.open('TCN.png') st.image(image, caption='Sequence to sequence machine learning model used') st.write("By selecting different metrics you can see how respiratory illness death rate and air quality will change in the future.") air_quality_option = st.multiselect("Which future values would you like to see?", pollution + ['Chronic respiratory disease death rate'],default=['Chronic respiratory disease death rate']) future_df = future_df.rename(columns = {'Chronic respiratory diseases':'Chronic respiratory disease death rate'}) try: ## prevents errors if there is no option selected line_df = future_df.loc[state_option][air_quality_option] line_df.index = pd.to_datetime(line_df.index, format="%Y") sns.lineplot(data = line_df) st.pyplot() except: pass space() ####### map #### st.write("MAP") st.write("You can see how the death rate of respiratory illnesses changes over time.") with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response) code = {'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'District of Columbia': 'DC', 'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS', 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY'} map_option = st.selectbox("What would you like to map?", diseases + pollution ) map_year = st.slider('What year?', int(df.reset_index().Year.min()), int(df.reset_index().Year.max()), key="map") map_df = df.copy().reset_index() map_df['Code'] = map_df['State Name'].map(code) min_val = map_df[map_option].min() max_val = map_df[map_option].max() map_df = map_df.loc[map_df['Year'] == map_year] fig = px.choropleth(map_df, # locations='Code', #plot based on state code color=map_option, #chose a column to show values color_continuous_scale='spectral_r', #color scheme range_color=(min_val , max_val), hover_name='State Name', #label options locationmode='USA-states', #join on state scope='usa' # only show US map ) #fig.show() st.plotly_chart(fig) # # import geopandas as gpd # import geoplot # import pandas as pd # # # usa = gpd.read_file('states.shp') # usa = usa.rename(columns = {'STATE_NAME':'State Name'}) # usa = usa[['State Name','geometry']] # map_df = df.reset_index().set_index('Year').loc[year].set_index('State Name') # map_df = df.loc[state_names].merge(usa, on = 'State Name') # gdf = gpd.GeoDataFrame(map_df, geometry='geometry') # gdf.plot('Asthma') # st.pyplot() # import altair as alt # from vega_datasets import data # # import pandas as pd # import altair as alt # from vega_datasets import data # states = alt.topo_feature(data.us_10m.url, feature='states') # states # # #unemp_data = pd.read_csv('http://vega.github.io/vega-datasets/data/unemployment.tsv',sep='\t') # #unemp_data = unemp_data.head(50) # # df = df.reset_index() # # unemp_data = df.loc[df['State Name'] == state_names] # #unemp_data['rate'] = df['Ozone'].values # # US states background # coords = pd.read_csv('coords.csv') # coords.to_json('coords.json') # states = alt.topo_feature(data.us_10m.url, 'states') # states # capitals = data.us_state_capitals.url # capitals # # US states background # background = alt.Chart(states).mark_geoshape( # fill='lightgray', # stroke='white' # ).properties( # title='US State Capitols', # width=650, # height=400 # ).project('albersUsa') # # # Points and text # hover = alt.selection(type='single', on='mouseover', nearest=True, # fields=['lat', 'lon']) # # base = alt.Chart(coords).encode( # longitude='lon:Q', # latitude='lat:Q', # ) # # text = base.mark_text(dy=-5, align='right').encode( # alt.Text('city', type='nominal'), # opacity=alt.condition(~hover, alt.value(0), alt.value(1)) # ) # # points = base.mark_point().encode( # color=alt.value('black'), # size=alt.condition(~hover, alt.value(30), alt.value(100)) # ).add_selection(hover) # # background + points + text # # .transform_lookup( # # lookup='id', # # from_=alt.LookupData(unemp_data, 'State Name', ['Asthma']) # # ).project( # # type='albersUsa' # # ).properties( # # width=500, # # height=300, # # title='Unemployment by County') # # chart # from plotly.figure_factory._county_choropleth import create_choropleth # import pandas as pd # # NE_states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island', 'Vermont'] # df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv') # df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)] # # # values = df_sample_r['TOT_POP'].tolist() # fips = df_sample_r['FIPS'].tolist() # # colorscale = [ # 'rgb(68.0, 1.0, 84.0)', # 'rgb(66.0, 64.0, 134.0)', # 'rgb(38.0, 130.0, 142.0)', # 'rgb(63.0, 188.0, 115.0)', # 'rgb(216.0, 226.0, 25.0)' # ] # # fig = create_choropleth( # fips=fips, values=values, # scope=NE_states, county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, # legend_title='Population per county' # # ) # fig.update_layout( # legend_x = 0, # annotations = {'x': -0.12, 'xanchor': 'left'} # ) # # fig.layout.template = None # fig.show() <file_sep>/README.md # ToHackHealth Repository for IHI Hackathon 2021
cb2674afdb18afbd0ab57f2ed572932a15bcad83
[ "Markdown", "Python" ]
2
Python
PorkPies/ToHackHealth
819e15b1095ee25046a234af754ebff043b8cb02
f21d07f908bc452c698fcb13f9ca0929b630a846
refs/heads/master
<file_sep>package org.hw.sml.test; import java.util.List; import java.util.concurrent.Callable; import org.hw.sml.support.CallableHelper; import org.hw.sml.tools.MapUtils; import org.junit.Test; public class CallableDemo { //一台打印机打印一份文件需要0.2s class Print{ public void print(int i){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } //现在1000份文件需要多久打印完 @SuppressWarnings("unchecked") @Test public void test() { List<Callable<String>> e=MapUtils.newArrayList(); for(int i=1;i<=10;i++){ final int temp=i; Callable<String> callable=new Callable<String>() { public String call() throws Exception { new Print().print(temp); return temp+""; } }; e.add(callable); } //一台打印机花费 long start=System.currentTimeMillis(); CallableHelper.callresults(10,1,e.toArray(new Callable[e.size()])); System.out.println("一台打印机花费-->"+(System.currentTimeMillis()-start)); //五台打印机花费 start=System.currentTimeMillis(); CallableHelper.callresults(10,5,e.toArray(new Callable[e.size()])); System.out.println("五台打印机花费-->"+(System.currentTimeMillis()-start)); } } <file_sep># sml sql markup language(sql标记语言) 1、mybatis,ibatis书写sql的方便,但调整xml配置文件整体服务需要重新启动 2、一段完整的sql查询包括 查询sql+参数集 # example ## sql select * from table t where 1=1 <isNotEmpty property="a"> and t.a=#a#</isNotEmpty> <isNotEmpty property="b"> and t.b in(#b#)</isNotEmpty> ##code SqlResolvers sqlResolvers=new SqlResolvers(new JsEl()); sqlResolvers.init(); Rst rst=sqlResolvers.resolverLinks(sql,SMLParams.newSMLParams().add("a","v1") .add("b",new String[]{"v2","v3","v4"}).reinit()); System.out.println(rst.getSqlString());//print sqlString System.out.println(rst.getParamObjects());//print params ##result sqlString:select * from table t where 1=1 and t.a=? and t.b in(?,?,?) params :[v1, v2, v3, v4]
c4c7883fbd5620ac62d3772586ca4fe33d32267a
[ "Markdown", "Java" ]
2
Java
czn-github/sml
958e3174c7cc84c730373f072de7451ce3a9e7cc
d2461e24053ffde013b6c01c76a7b9b450c698f7
refs/heads/master
<file_sep>from .connection import * from .errors import * from .relation import * from .query import * from .schema import * import cmd version = "1.2-dev" <file_sep>Myria Python ============ [![Build Status](https://travis-ci.org/uwescience/myria-python.svg?branch=master)](https://travis-ci.org/uwescience/myria-python) [![Coverage Status](https://img.shields.io/coveralls/uwescience/myria-python.svg)](https://coveralls.io/r/uwescience/myria-python?branch=master) [![Latest Version](https://pypip.in/version/myria-python/badge.svg)](https://pypi.python.org/pypi/myria-python/) [![Downloads](https://pypip.in/download/myria-python/badge.svg)](https://pypi.python.org/pypi/myria-python/) [![Supported Python versions](https://pypip.in/py_versions/myria-python/badge.svg)](https://pypi.python.org/pypi/myria-python/) [![Development Status](https://pypip.in/status/myria-python/badge.svg)](https://pypi.python.org/pypi/myria-python/) [![License](https://pypip.in/license/myria-python/badge.svg)](https://pypi.python.org/pypi/myria-python/) A Python library for exercising Myria's REST interface. ## Installation Users can just install this using `pip install myria-python`. Developers should clone the repository and run `python setup.py develop`. ## Usage Myria python can either be used as a library for a python program. Check the source code for a list of available function. To use the myria uploader binary, run `myria_upload`. Append `-h` to see available commands.
bb0bf0e77d0805d750c4eafe031244308b70a796
[ "Markdown", "Python" ]
2
Python
BrandonHaynes/myria-python
35cc9f5cf143c2f1f5f697760d8aad7324aef056
8279eef4520461476213fa1219eb869f62b398ef
refs/heads/master
<repo_name>osascruz/beehive_monitor<file_sep>/better_beehive_monitor_v5.ino #include <DHT.h> //Version 4 of the beehive monitor //************************************************** //<NAME> 2014 - @exmonkey - <EMAIL> - //Uses Sleep_n0m1 Library - <NAME>, <NAME>, NoMi Design Ltd. http://n0m1.com https://github.com/n0m1/Sleep_n0m1 // #include <GSM.h> // Importing all appropriate libraries #include <HttpClient.h> #include <Xively.h> //#include <DHT22.h> #include <DHT.h> #include <Sleep_n0m1.h> #define PINNUMBER "" // SIM PIN (not required for GiffGaff #define GPRS_APN "giffgaff.com" // Access Point Name #define GPRS_LOGIN "giffgaff" // Username (phone number) #define GPRS_PASSWORD "<PASSWORD>" // Password (phone number) // Setup a DHT22 nstance #define DHTTYPE DHT22 // DHT 22 (AM2302) #define DHTPIN 5 DHT dht(DHTPIN, DHTTYPE); //#define DHT22_PIN 4 //DHT22 myDHT22(DHT22_PIN); float temperature = 0; float humidity = 0; int wait = 225; boolean notConnected = true; unsigned long time; int mins; boolean working; //sleep stuff Sleep sleep; unsigned long sleepTime; //how long you want the arduino to sleep //charger shield stuff const int analogInPin = A0; // Analog input pin that the VBAT pin is attached to int BatteryValue = 0; // value read from the VBAT pin double outputValue = 0; // variable for voltage calculation char myTempStream[] = "temperature"; // Set stream name (need to match Xively name) char myHumidityStream[] = "humidity"; // Set 2nd stream name char myBatteryValue[] = "battery"; // Set 3rd stream name //GSM shield objects GSMClient client; GPRS gprs; GSM gsmAccess; XivelyDatastream datastreams[] = { // Create the datasterams XivelyDatastream(myTempStream, strlen(myTempStream), DATASTREAM_FLOAT), XivelyDatastream(myHumidityStream, strlen(myHumidityStream), DATASTREAM_FLOAT), XivelyDatastream(myBatteryValue, strlen(myBatteryValue), DATASTREAM_FLOAT), }; #include "passwords.h" //unique Xively API key replace with below //#define FEED_ID XXXXXXXXXXXX //char xivelyKey[] = "<KEY>"; // Set the Xively API key XivelyFeed feed(FEED_ID, datastreams, 3); // Creating the feed, defining three datastreams XivelyClient xivelyclient(client); // Telling Xively to use the correct client void setup(void) { // Connecting to network, initiating GPRS connection Serial.begin(9600); sleepTime = 360000;//1 hour 10000;//7200000; //how long to sleep for - 2 hours boolean notConnected = true; //set connected value for GSM shield boolean working = false; dht.begin(); } void loop(void) { if(working==false){ working = true; Serial.print("allow the sensor to warm up"); delay(5000); Serial.print("\nVoltage: "); //get data from the charger shield BatteryValue = analogRead(analogInPin); // Calculate the battery voltage value outputValue = (float(BatteryValue)*5)/1023*2; Serial.print(outputValue); Serial.print("\n---------\n"); //connect the GSM to GPRS startConnection(); } } // Get the data from the DHT222 sensor void get_data(){ // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) boolean gotReading = 0; while (gotReading==0) { humidity = dht.readHumidity(); temperature = dht.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(humidity) || isnan(temperature) ){ Serial.println("Failed to read from DHT sensor!"); delay(1000); } else{ gotReading = 1; } } // Compute heat index // Must send in temp in Fahrenheit! //float hi = dht.computeHeatIndex(f, h); Serial.print("Humidity: "); Serial.print(humidity); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" *C "); processData(); } //connect to GPRS void startConnection(){ while (notConnected) { digitalWrite(3,HIGH); // Enable the RX pin if(gsmAccess.begin(PINNUMBER)==GSM_READY){ delay(3000); if(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY){ notConnected = false; Serial.println("connected..."); //Get the sensor data get_data(); } } else{ Serial.println("loop"); delay(1000); } } } void closeConnection(){ Serial.println("closing connection"); while(notConnected==false){ if(gsmAccess.shutdown()){ delay(1000); digitalWrite(3,LOW); // Disable the RX pin notConnected = true; Serial.println("GSM connection closed"); Serial.println("Entering Sleep Mode"); working = false; sleep.pwrDownMode(); //set sleep mode sleep.sleepDelay(sleepTime); //sleep for: sleepTime } else{ delay(1000); } } } void processData(){ Serial.println("process data"); //add the results to the xively stream datastreams[0].setFloat(temperature); datastreams[1].setFloat(humidity); datastreams[2].setFloat(outputValue); int ret = xivelyclient.put(feed, xivelyKey); // Send to Xively Serial.println("Ret: "); Serial.println(ret); if(ret == 200){ Serial.println(ret); delay(1000); } else{ delay(1000); Serial.println(ret); } delay(5000); Serial.println("call close connecttion"); closeConnection(); } <file_sep>/README.md beehive_monitor =============== Arduino script to gather sensor data from ardunio, DHT222 sensor and upload to Xively using GSM shield. Power management using solar shield <file_sep>/wifi-no-batt-v1.ino //Beehive monitor for wifi //Based on v4 of the beehive monitor by <NAME> @exmonkey https://github.com/exmonkey206/beehive_monitor //Importing various libraries #include <Sleep_n0m1.h> #include <CountingStream.h> #include <Xively.h> #include <XivelyClient.h> #include <XivelyDatastream.h> #include <XivelyFeed.h> #include <b64.h> #include <HttpClient.h> #include <DHT.h> #include <WiFi.h> #include <SPI.h> //Setup a DHT22 instance #define DHTTYPE DHT22 #define DHTPIN 5 DHT dht(DHTPIN, DHTTYPE); float temperature = 0; float humidity = 0; int wait = 225; boolean notConnected = true; unsigned long time; int mins; boolean working; //sleep stuff Sleep sleep; unsigned long sleepTime; //how long you wna the arduino to sleep char myTempStream[] = "temperature"; //Set stream name (need to match Xively name) char myHumidityStream[] = "humidity"; //Set 2nd stream name XivelyDatastream datastreams[] = { XivelyDatastream(myTempStream, strlen(myTempStream), DATASTREAM_FLOAT), XivelyDatastream(myHumidityStream, strlen(myHumidityStream), DATASTREAM_FLOAT), }; #define FEED_ID 1234 //Set Xively Feed ID char xivelyKey[] = "1234"; //Set Xively API key XivelyFeed feed(FEED_ID, datastreams, 2); //Creating the feed, definining the two datastreams WiFiClient client; XivelyClient xivelyclient(client); //connect to wifi char ssid[] = "name"; // your network SSID (name) char pass[] = "<PASSWORD>"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status void setup(void) { // dht sensor dht.begin(); // wifi // initialize serial: Serial.begin(9600); // attempt to connect using WPA2 encryption: Serial.println("Attempting to connect to WPA network..."); status = WiFi.begin(ssid, pass); // if you're not connected, stop here: if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print out info about the connection: else { Serial.println("Connected to network"); } } void loop() { if(working==false){ working = true; Serial.print("allow the sensor to warm up"); delay(5000); get_data(); } } // Get the data from the DHT222 sensor void get_data(){ // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) boolean gotReading = 0; while (gotReading==0) { humidity = dht.readHumidity(); temperature = dht.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(humidity) || isnan(temperature) ){ Serial.println("Failed to read from DHT sensor!"); delay(1000); } else{ gotReading = 1; Serial.println("Read data from DHT sensor"); } } // Compute heat index // Must send in temp in Fahrenheit! //float hi = dht.computeHeatIndex(f, h); Serial.print("Humidity: "); Serial.print(humidity); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" *C "); processData(); } void processData(){ Serial.println(temperature); Serial.println(humidity); Serial.println("process data"); //add the results to the xively stream datastreams[0].setFloat(temperature); datastreams[1].setFloat(humidity); //datastreams[2].setFloat(outputValue); int ret = xivelyclient.put(feed, xivelyKey); // Send to Xively Serial.println("Ret: "); Serial.println(ret); if(ret == 200){ Serial.println(ret); delay(1000); } else{ delay(1000); Serial.println(ret); } }
c566cf278efaa01ccc0892d1eca6e19914424be5
[ "Markdown", "C++" ]
3
C++
osascruz/beehive_monitor
baf11a841c159d143eaee8ad13484be9624ba0c6
58b71d326499f19d9dcd53314322c61241c388a4
refs/heads/master
<repo_name>ptxmac/figma-export<file_sep>/Sources/FigmaExportCore/Extensions/Double+fixFloatingPoint.swift public extension Double { var floatingPointFixed: Double { (self * 1000).rounded() / 1000 } } <file_sep>/Sources/XcodeExport/bundle_provider_swift_package.swift let bundleProviderSwiftPackage = """ private class BundleProvider { static let bundle = Bundle.module } """ <file_sep>/Tests/FigmaExportTests/AssetsProcessorTests.swift import XCTest import FigmaExportCore final class AssetsProcessorTests: XCTestCase { func testProcessCamelCase() throws { let images = [ ImagePack(image: Image(name: "ic_24_icon", url: URL(string: "1")!, format: "pdf")), ImagePack(image: Image(name: "ic_24_icon_name", url: URL(string: "2")!, format: "pdf")) ] let processor = ImagesProcessor( platform: .ios, nameStyle: .camelCase ) let icons = try processor.process(assets: images).get() XCTAssertEqual( icons.map { $0.name }, ["ic24Icon", "ic24IconName"] ) } func testProcessSnakeCase() throws { let images = [ ImagePack(image: Image(name: "ic/24/Icon", url: URL(string: "1")!, format: "pdf")), ImagePack(image: Image(name: "ic/24/icon/name", url: URL(string: "2")!, format: "pdf")), ] let processor = ImagesProcessor( platform: .android, nameStyle: .snakeCase ) let icons = try processor.process(assets: images).get() XCTAssertEqual( icons.map { $0.name }, ["ic_24_icon", "ic_24_icon_name"] ) } func testProcessWithValidateAndReplace() throws { let images = [ ImagePack(image: Image(name: "ic_24_icon", url: URL(string: "1")!, format: "pdf")), ImagePack(image: Image(name: "ic_24_icon_name", url: URL(string: "2")!, format: "pdf")), ] let processor = ImagesProcessor( platform: .ios, nameValidateRegexp: #"^(ic)_(\d\d)_([a-z0-9_]+)$"#, nameReplaceRegexp: #"icon_$2_$3"#, nameStyle: .camelCase ) let icons = try processor.process(assets: images).get() XCTAssertEqual( icons.map { $0.name }, ["icon24Icon", "icon24IconName"] ) } func testProcessWithReplaceImageNameInSnakeCase() throws { let images = [ ImagePack(image: Image(name: "32 - Profile", url: URL(string: "1")!, format: "pdf")) ] let processor = ImagesProcessor( platform: .ios, nameValidateRegexp: "^(\\d\\d) - ([A-Za-z0-9 ]+)$", nameReplaceRegexp: #"icon_$2_$1"#, nameStyle: .snakeCase ) let icons = try processor.process(assets: images).get() XCTAssertEqual( icons.map { $0.name }, ["icon_profile_32"] ) } func testProcessWithReplaceImageName() throws { let images = [ ImagePack(image: Image(name: "32 - Profile", url: URL(string: "1")!, format: "pdf")) ] let processor = ImagesProcessor( platform: .ios, nameValidateRegexp: "^(\\d\\d) - ([A-Za-z0-9 ]+)$", nameReplaceRegexp: #"icon_$2_$1"#, nameStyle: .snakeCase ) let icons = try processor.process(light: images, dark: nil).get() XCTAssertEqual( icons.map { $0.light.name }, ["icon_profile_32"] ) } func testProcessWithReplaceImageName2() throws { let images = [ ImagePack(image: Image(name: "32 - Profile", url: URL(string: "1")!, format: "pdf")) ] let processor = ImagesProcessor( platform: .ios, nameValidateRegexp: "^(\\d\\d) - ([A-Za-z0-9 ]+)$", nameReplaceRegexp: #"icon_$2_$1"#, nameStyle: .snakeCase ) let icons = try processor.process(light: images, dark: images).get() XCTAssertEqual( [icons.map { $0.light.name }, icons.map { $0.dark!.name }], [["icon_profile_32"], ["icon_profile_32"]] ) } func testProcessWithReplaceForInvalidAsssetName() throws { let images = [ ImagePack(image: Image(name: "ic24", url: URL(string: "1")!, format: "pdf")) ] let processor = ImagesProcessor( platform: .ios, nameValidateRegexp: #"^(ic)_(\d\d)_([a-z0-9_]+)$"#, nameReplaceRegexp: #"icon_$2_$3"#, nameStyle: .camelCase ) XCTAssertThrowsError(try processor.process(assets: images).get()) } // Light count can exceed dark count func testProcessWithUniversalAsset() throws { let lights = [ Color(name: "primaryText", platform: .ios, red: 0, green: 0, blue: 0, alpha: 0), Color(name: "primaryLink", platform: .ios, red: 0, green: 0, blue: 0, alpha: 0) ] let darks = [ Color(name: "primaryText", platform: .ios, red: 0, green: 0, blue: 0, alpha: 0) ] let processor = ColorsProcessor( platform: .ios, nameValidateRegexp: nil, nameReplaceRegexp: nil, nameStyle: .camelCase ) let colors = try processor.process(light: lights, dark: darks).get() XCTAssertEqual( [colors.compactMap { $0.light.name }, colors.compactMap { $0.dark?.name }], [["primaryLink", "primaryText"], ["primaryText"]] ) } // Dark count cannot exceed light count func testProcessWithUniversalAsset2() throws { let lights = [ Color(name: "primaryText", platform: .ios, red: 0, green: 0, blue: 0, alpha: 0), ] let darks = [ Color(name: "primaryText", platform: .ios, red: 0, green: 0, blue: 0, alpha: 0), Color(name: "primaryLink", platform: .ios, red: 0, green: 0, blue: 0, alpha: 0) ] let processor = ColorsProcessor( platform: .ios, nameValidateRegexp: nil, nameReplaceRegexp: nil, nameStyle: .camelCase ) XCTAssertThrowsError(try processor.process(light: lights, dark: darks).get()) } } <file_sep>/Sources/FigmaAPI/GitHubClient.swift import Foundation final public class GitHubClient: BaseClient { private let baseURL = URL(string: "https://api.github.com/")! public init() { let config = URLSessionConfiguration.ephemeral config.timeoutIntervalForRequest = 10 super.init(baseURL: baseURL, config: config) } } <file_sep>/Sources/FigmaExport/Input/FigmaExportOptions.swift import ArgumentParser import Foundation import Yams struct FigmaExportOptions: ParsableArguments { static let input = "figma-export.yaml" @Option(name: .shortAndLong, help: "An input YAML file with figma and platform properties.") var input: String = Self.input var accessToken: String! var params: Params! mutating func validate() throws { guard let token = ProcessInfo.processInfo.environment["FIGMA_PERSONAL_TOKEN"] else { throw FigmaExportError.accessTokenNotFound } self.accessToken = token self.params = try readParams(at: input) } private func readParams(at path: String) throws -> Params { let url = URL(fileURLWithPath: path) let data = try Data(contentsOf: url) let string = String(decoding: data, as: UTF8.self) let decoder = YAMLDecoder() return try decoder.decode(Params.self, from: string) } } <file_sep>/Sources/FigmaExport/Output/VectorDrawableConverter.swift import FigmaExportCore import Foundation import Logging /// SVG to XML converter final class VectorDrawableConverter { private static let notSupportedWarning = "is not supported" private let logger = Logger(label: "com.redmadrobot.figma-export.vector-drawable-converter") /// Converts SVG files to XML /// In case unsupported XML-Tags are reported, the converting command will be executed for each file for better logging. /// - Parameter inputDirectoryUrl: Url to directory with SVG files func convert(inputDirectoryUrl: URL) throws { let errorPipe = Pipe() let outputPipe = Pipe() let directoryTaskArguments = ["-c", "-in", inputDirectoryUrl.path] try runVdTool(with: directoryTaskArguments, errorPipe: errorPipe, outputPipe: outputPipe) let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile() let error = String(decoding: errorData, as: UTF8.self) let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile() let outputString = String(decoding: outputData, as: UTF8.self) // Only log last line out standard output outputString.lastLine.flatMap { logger.info("\($0)") } if error.contains(Self.notSupportedWarning) { logger.warning("vd-tool reported unsupported xml tags. Executing vd-tool for each file...") let enumerator = FileManager.default.enumerator(at: inputDirectoryUrl, includingPropertiesForKeys: nil) while let file = enumerator?.nextObject() as? URL { guard file.pathExtension == "svg" else { continue } let fileErrorPipe = Pipe() let fileTaskArguments = ["-c", "-in", file.path, "-out", inputDirectoryUrl.path] logger.info("Converting file: \(file.path)") try runVdTool(with: fileTaskArguments, errorPipe: fileErrorPipe) let fileErrorData = fileErrorPipe.fileHandleForReading.readDataToEndOfFile() let fileError = String(decoding: fileErrorData, as: UTF8.self) if fileError.contains(Self.notSupportedWarning) { logger.warning("Error in file: \(file.path)\n\(fileError)") } } } } private func runVdTool(with arguments: [String], errorPipe: Pipe?, outputPipe: Pipe? = nil) throws { let task = Process() task.executableURL = URL(fileURLWithPath: "/usr/local/bin/vd-tool") task.arguments = arguments task.standardOutput = outputPipe task.standardError = errorPipe do { try task.run() } catch { task.executableURL = URL(fileURLWithPath: "./vd-tool/bin/vd-tool") try task.run() } task.waitUntilExit() } } private extension String { var lastLine: String? { split { $0 == "\n" }.compactMap(String.init).last } } <file_sep>/Sources/AndroidExport/AndroidTypographyExporter.swift import Foundation import FigmaExportCore final public class AndroidTypographyExporter { private let outputDirectory: URL public init(outputDirectory: URL) { self.outputDirectory = outputDirectory } public func exportFonts(textStyles: [TextStyle]) throws -> [FileContents] { [makeFontsFile(textStyles: textStyles)] } private func makeFontsFile(textStyles: [TextStyle]) -> FileContents { let contents = prepareFontsDotXMLContents(textStyles) let directoryURL = outputDirectory.appendingPathComponent("values") let fileURL = URL(string: "typography.xml")! return FileContents( destination: Destination(directory: directoryURL, file: fileURL), data: contents ) } private func prepareFontsDotXMLContents(_ textStyles: [TextStyle]) -> Data { let resources = XMLElement(name: "resources") let xml = XMLDocument(rootElement: resources) xml.version = "1.0" xml.characterEncoding = "utf-8" textStyles.forEach { textStyle in let textStyleNode = XMLElement(name: "style") textStyleNode.addAttribute(XMLNode.attribute(withName: "name", stringValue: textStyle.name) as! XMLNode) resources.addChild(textStyleNode) let fontFamilyItem = XMLElement(name: "item", stringValue: androidFontName(from: textStyle.fontName)) fontFamilyItem.addAttribute(XMLNode.attribute(withName: "name", stringValue: "android:fontFamily") as! XMLNode) textStyleNode.addChild(fontFamilyItem) let fontSizeItem = XMLElement(name: "item", stringValue: androidFontSize(from: textStyle.fontSize)) fontSizeItem.addAttribute(XMLNode.attribute(withName: "name", stringValue: "android:textSize") as! XMLNode) textStyleNode.addChild(fontSizeItem) } return xml.xmlData(options: .nodePrettyPrint) } private func androidFontName(from postscriptName: String) -> String { "@font/\(postscriptName.lowercased().replacingOccurrences(of: "-", with: "_"))" } private func androidFontSize(from points: Double) -> String { "\(points)sp" } } <file_sep>/Examples/Example/UIComponents/Source/Typography/LabelStyle+extension.swift // // The code generated using FigmaExport — Command line utility to export // colors, typography, icons and images from Figma to Xcode project. // // https://github.com/RedMadRobot/figma-export // // Don’t edit this code manually to avoid runtime crashes // import UIKit public extension LabelStyle { static func body() -> LabelStyle { LabelStyle( font: UIFont.body(), fontMetrics: UIFontMetrics(forTextStyle: .body), lineHeight: 24.0 ) } static func caption() -> LabelStyle { LabelStyle( font: UIFont.caption(), fontMetrics: UIFontMetrics(forTextStyle: .footnote), lineHeight: 20.0 ) } static func header() -> LabelStyle { LabelStyle( font: UIFont.header() ) } static func largeTitle() -> LabelStyle { LabelStyle( font: UIFont.largeTitle(), fontMetrics: UIFontMetrics(forTextStyle: .largeTitle) ) } static func uppercased() -> LabelStyle { LabelStyle( font: UIFont.uppercased(), lineHeight: 20.0, textCase: .uppercased ) } }<file_sep>/Sources/FigmaExportCore/XcodeRenderMode.swift import Foundation public enum XcodeRenderMode: String, Decodable { case `default` case template case original } <file_sep>/Sources/FigmaExportCore/Processor/AssetResult.swift import Foundation public struct AssetResult<Success, Error> { public var result: Result<Success, Swift.Error> public var warning: AssetsValidatorWarning? public func get() throws -> Success { try result.get() } public static func failure(_ error: Swift.Error) -> AssetResult<Success, Error> { AssetResult(result: .failure(error), warning: nil) } public static func success(_ data: Success) -> AssetResult<Success, Error> { AssetResult(result: .success(data), warning: nil) } public static func success(_ data: Success, warning: AssetsValidatorWarning?) -> AssetResult<Success, Error> { AssetResult(result: .success(data), warning: warning) } } <file_sep>/Examples/ExampleSwiftUI/ExampleSwiftUI/View/Common/Font+extension.swift // // The code generated using FigmaExport — Command line utility to export // colors, typography, icons and images from Figma to Xcode project. // // https://github.com/RedMadRobot/figma-export // // Don’t edit this code manually to avoid runtime crashes // import SwiftUI public extension Font { static func body() -> Font { if #available(iOS 14.0, *) { return Font.custom("PTSans-Regular", size: 16.0, relativeTo: .body) } else { return Font.custom("PTSans-Regular", size: 16.0) } } static func caption() -> Font { if #available(iOS 14.0, *) { return Font.custom("PTSans-Regular", size: 14.0, relativeTo: .footnote) } else { return Font.custom("PTSans-Regular", size: 14.0) } } static func header() -> Font { Font.custom("PTSans-Bold", size: 20.0) } static func largeTitle() -> Font { if #available(iOS 14.0, *) { return Font.custom("PTSans-Bold", size: 34.0, relativeTo: .largeTitle) } else { return Font.custom("PTSans-Bold", size: 34.0) } } static func uppercased() -> Font { Font.custom("PTSans-Regular", size: 14.0).lowercaseSmallCaps() } } <file_sep>/Sources/FigmaExport/Subcommands/ExportTypography.swift import ArgumentParser import Foundation import FigmaAPI import XcodeExport import AndroidExport import FigmaExportCore extension FigmaExportCommand { struct ExportTypography: ParsableCommand { static let configuration = CommandConfiguration( commandName: "typography", abstract: "Exports typography from Figma", discussion: "Exports font styles from Figma to Xcode") @OptionGroup var options: FigmaExportOptions func run() throws { let client = FigmaClient(accessToken: options.accessToken, timeout: options.params.figma.timeout) logger.info("Using FigmaExport \(FigmaExportCommand.version) to export typography.") logger.info("Fetching text styles. Please wait...") let loader = TextStylesLoader(client: client, params: options.params.figma) let textStyles = try loader.load() if let ios = options.params.ios, let typographyParams = ios.typography { logger.info("Processing typography...") let processor = TypographyProcessor( platform: .ios, nameValidateRegexp: options.params.common?.typography?.nameValidateRegexp, nameReplaceRegexp: options.params.common?.typography?.nameReplaceRegexp, nameStyle: typographyParams.nameStyle ) let processedTextStyles = try processor.process(assets: textStyles).get() logger.info("Saving text styles...") try exportXcodeTextStyles(textStyles: processedTextStyles, iosParams: ios) logger.info("Done!") } if let android = options.params.android { logger.info("Processing typography...") let processor = TypographyProcessor( platform: .android, nameValidateRegexp: options.params.common?.typography?.nameValidateRegexp, nameReplaceRegexp: options.params.common?.typography?.nameReplaceRegexp, nameStyle: options.params.android?.typography?.nameStyle ) let processedTextStyles = try processor.process(assets: textStyles).get() logger.info("Saving text styles...") try exportAndroidTextStyles(textStyles: processedTextStyles, androidParams: android) logger.info("Done!") } } private func createXcodeOutput(from iosParams: Params.iOS) -> XcodeTypographyOutput { let fontUrls = XcodeTypographyOutput.FontURLs( fontExtensionURL: iosParams.typography?.fontSwift, swiftUIFontExtensionURL: iosParams.typography?.swiftUIFontSwift ) let labelUrls = XcodeTypographyOutput.LabelURLs( labelsDirectory: iosParams.typography?.labelsDirectory, labelStyleExtensionsURL: iosParams.typography?.labelStyleSwift ) let urls = XcodeTypographyOutput.URLs( fonts: fontUrls, labels: labelUrls ) return XcodeTypographyOutput( urls: urls, generateLabels: iosParams.typography?.generateLabels, addObjcAttribute: iosParams.addObjcAttribute ) } private func exportXcodeTextStyles(textStyles: [TextStyle], iosParams: Params.iOS) throws { let output = createXcodeOutput(from: iosParams) let exporter = XcodeTypographyExporter(output: output) let files = try exporter.export(textStyles: textStyles) try fileWriter.write(files: files) do { let xcodeProject = try XcodeProjectWriter(xcodeProjPath: iosParams.xcodeprojPath, target: iosParams.target) try files.forEach { file in if file.destination.file.pathExtension == "swift" { try xcodeProject.addFileReferenceToXcodeProj(file.destination.url) } } try xcodeProject.save() } catch { logger.error("Unable to add some file references to Xcode project") } } private func exportAndroidTextStyles(textStyles: [TextStyle], androidParams: Params.Android) throws { let exporter = AndroidTypographyExporter(outputDirectory: androidParams.mainRes) let files = try exporter.exportFonts(textStyles: textStyles) let fileURL = androidParams.mainRes.appendingPathComponent("values/typography.xml") try? FileManager.default.removeItem(atPath: fileURL.path) try fileWriter.write(files: files) } } } <file_sep>/Sources/FigmaExport/Subcommands/checkForUpdate.swift import ArgumentParser import Foundation import Logging import FigmaAPI extension ParsableCommand { func checkForUpdate(logger: Logger) { let client = GitHubClient() let endpoint = LatestReleaseEndpoint() guard let latestRelease = try? client.request(endpoint) else { return } let latestVersion = latestRelease.tagName if FigmaExportCommand.version != latestVersion { logger.info(""" ---------------------------------------------------------------------------- figma-export \(latestVersion) is available. You are on \(FigmaExportCommand.version). You should use the latest version. Please update using `brew upgrade figma-export` or `pod update FigmaExport`. To see what’s new, open https://github.com/RedMadRobot/figma-export/releases ---------------------------------------------------------------------------- """) } } } <file_sep>/Sources/FigmaExportCore/Processor/AssetsValidatorWarning.swift import Foundation public enum AssetsValidatorWarning: LocalizedError { case lightAssetsNotFoundInDarkPalette(assets: [String]) public var errorDescription: String? { var warning: String switch self { case .lightAssetsNotFoundInDarkPalette(let lights): warning = "The following assets will be considered universal because they are not found in the dark palette: \(lights.joined(separator: ", "))" } return "⚠️ \(warning)" } } <file_sep>/Sources/XcodeExport/Model/XcodeTypographyOutput.swift import Foundation public struct XcodeTypographyOutput { let urls: URLs let generateLabels: Bool let addObjcAttribute: Bool public struct FontURLs { let fontExtensionURL: URL? let swiftUIFontExtensionURL: URL? public init( fontExtensionURL: URL? = nil, swiftUIFontExtensionURL: URL? = nil ) { self.swiftUIFontExtensionURL = swiftUIFontExtensionURL self.fontExtensionURL = fontExtensionURL } } public struct LabelURLs { let labelsDirectory: URL? let labelStyleExtensionsURL: URL? public init( labelsDirectory: URL? = nil, labelStyleExtensionsURL: URL? = nil ) { self.labelsDirectory = labelsDirectory self.labelStyleExtensionsURL = labelStyleExtensionsURL } } public struct URLs { public let fonts: FontURLs public let labels: LabelURLs public init( fonts: FontURLs, labels: LabelURLs ) { self.fonts = fonts self.labels = labels } } public init( urls: URLs, generateLabels: Bool? = false, addObjcAttribute: Bool? = false ) { self.urls = urls self.generateLabels = generateLabels ?? false self.addObjcAttribute = addObjcAttribute ?? false } } <file_sep>/Sources/FigmaExportCore/Processor/AssetsValidatorError.swift import Foundation enum AssetsValidatorError: LocalizedError { case badName(name: String) case countMismatch(light: Int, dark: Int) case foundDuplicate(assetName: String) case darkAssetsNotFoundInLightPalette(assets: [String]) case descriptionMismatch(assetName: String, light: String, dark: String) var errorDescription: String? { var error: String switch self { case .badName(let name): error = "Bad asset name «\(name)»" case .countMismatch(let light, let dark): error = "The number of assets doesn’t match. Light theme contains \(light), and dark \(dark)." case .darkAssetsNotFoundInLightPalette(let darks): error = "Light theme doesn’t contains following assets: \(darks.joined(separator: ", ")), which exists in dark theme. Add these assets to light theme and publish to the Team Library." case .foundDuplicate(let assetName): error = "Found duplicates of asset with name \(assetName). Remove duplicates." case .descriptionMismatch(let assetName, let light, let dark): error = "Asset with name \(assetName) have different description. In dark theme «\(dark)», in light theme «\(light)»" } return "❌ \(error)" } } <file_sep>/Sources/FigmaAPI/Endpoint/LatestReleaseEndpoint.swift import Foundation public struct LatestReleaseEndpoint: BaseEndpoint { public typealias Content = LatestReleaseResponse public init() {} public func makeRequest(baseURL: URL) -> URLRequest { let url = baseURL.appendingPathComponent("repos/RedMadRobot/figma-export/releases/latest") return URLRequest(url: url) } } // MARK: - Response public struct LatestReleaseResponse: Decodable { public let tagName: String } <file_sep>/Scripts/increment_major_version.command cd "$( dirname "${BASH_SOURCE[0]}" )" cd .. perl -i -pe 's/\b(\d+)(?=.\d+")/$1+1/e' FigmaExport.podspec perl -i -pe 's/\b(\d+)(?=.\d+")/$1+1/e' ./Sources/FigmaExport/main.swift perl -i -pe 's/\b(\d+)(?=\D*$)/0/e' FigmaExport.podspec perl -i -pe 's/\b(\d+)(?=\D*$)/0/e' ./Sources/FigmaExport/main.swift <file_sep>/Sources/FigmaAPI/FigmaClient.swift import Foundation final public class FigmaClient: BaseClient { private let baseURL = URL(string: "https://api.figma.com/v1/")! public init(accessToken: String, timeout: TimeInterval?) { let config = URLSessionConfiguration.ephemeral config.httpAdditionalHeaders = ["X-Figma-Token": accessToken] config.timeoutIntervalForRequest = timeout ?? 30 super.init(baseURL: baseURL, config: config) } } <file_sep>/Sources/XcodeExport/Model/XcodeAssetContents.swift import FigmaExportCore enum XcodeAssetIdiom: String, Encodable { case universal case iphone case ipad case mac case tv case watch case car } struct XcodeAssetContents: Encodable { struct Info: Encodable { let version = 1 let author = "xcode" } struct DarkAppearance: Encodable { let appearance = "luminosity" let value = "dark" } struct Components: Encodable { var red: String var alpha: String var green: String var blue: String } struct ColorInfo: Encodable { enum CodingKeys: String, CodingKey { case colorSpace = "color-space" case components } let colorSpace = "srgb" let components: Components } struct ColorData: Encodable { let idiom = "universal" var appearances: [DarkAppearance]? var color: ColorInfo } struct ImageData: Encodable { let idiom: XcodeAssetIdiom var scale: String? var appearances: [DarkAppearance]? let filename: String } struct Properties: Encodable { let templateRenderingIntent: String? let preservesVectorRepresentation: Bool? enum CodingKeys: String, CodingKey { case templateRenderingIntent = "template-rendering-intent" case preservesVectorRepresentation = "preserves-vector-representation" } init?(preserveVectorData: Bool?, renderMode: XcodeRenderMode?) { preservesVectorRepresentation = preserveVectorData == true ? true : nil if let renderMode = renderMode, (renderMode == .original || renderMode == .template) { templateRenderingIntent = renderMode.rawValue } else { templateRenderingIntent = nil } if preservesVectorRepresentation == nil && templateRenderingIntent == nil { return nil } } } let info = Info() let colors: [ColorData]? let images: [ImageData]? let properties: Properties? init(colors: [ColorData]) { self.colors = colors self.images = nil self.properties = nil } init(images: [ImageData], properties: Properties? = nil) { self.colors = nil self.images = images self.properties = properties } } <file_sep>/Examples/Example/UIComponents/Source/Typography/LabelStyle.swift // // The code generated using FigmaExport — Command line utility to export // colors, typography, icons and images from Figma to Xcode project. // // https://github.com/RedMadRobot/figma-export // // Don’t edit this code manually to avoid runtime crashes // import UIKit public struct LabelStyle { enum TextCase { case uppercased case lowercased case original } let font: UIFont let fontMetrics: UIFontMetrics? let lineHeight: CGFloat? let tracking: CGFloat let textCase: TextCase init(font: UIFont, fontMetrics: UIFontMetrics? = nil, lineHeight: CGFloat? = nil, tracking: CGFloat = 0, textCase: TextCase = .original) { self.font = font self.fontMetrics = fontMetrics self.lineHeight = lineHeight self.tracking = tracking self.textCase = textCase } public func attributes( for alignment: NSTextAlignment = .left, lineBreakMode: NSLineBreakMode = .byTruncatingTail ) -> [NSAttributedString.Key: Any] { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = alignment paragraphStyle.lineBreakMode = lineBreakMode var baselineOffset: CGFloat = .zero if let lineHeight = lineHeight { let scaledLineHeight: CGFloat = fontMetrics?.scaledValue(for: lineHeight) ?? lineHeight paragraphStyle.minimumLineHeight = scaledLineHeight paragraphStyle.maximumLineHeight = scaledLineHeight baselineOffset = (scaledLineHeight - font.lineHeight) / 4.0 } return [ NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key.kern: tracking, NSAttributedString.Key.baselineOffset: baselineOffset, NSAttributedString.Key.font: font ] } public func attributedString( from string: String, alignment: NSTextAlignment = .left, lineBreakMode: NSLineBreakMode = .byTruncatingTail ) -> NSAttributedString { let attributes = attributes(for: alignment, lineBreakMode: lineBreakMode) return NSAttributedString(string: convertText(string), attributes: attributes) } private func convertText(_ text: String) -> String { switch textCase { case .uppercased: return text.uppercased() case .lowercased: return text.lowercased() default: return text } } } <file_sep>/Sources/FigmaAPI/Model/Node.swift // // Node.swift // FigmaColorExporter // // Created by <NAME> on 28.03.2020. // Copyright © 2020 <NAME>. All rights reserved. // public typealias NodeId = String public struct NodesResponse: Decodable { public let nodes: [NodeId: Node] } public struct Node: Decodable { public let document: Document } public enum LineHeightUnit: String, Decodable { case pixels = "PIXELS" case fontSize = "FONT_SIZE_%" case intrinsic = "INTRINSIC_%" } public struct TypeStyle: Decodable { public var fontPostScriptName: String public var fontWeight: Double public var fontSize: Double public var lineHeightPx: Double public var letterSpacing: Double public var lineHeightUnit: LineHeightUnit public var textCase: TextCase? } public enum TextCase: String, Decodable { case original = "ORIGINAL" case upper = "UPPER" case lower = "LOWER" case title = "TITLE" case smallCaps = "SMALL_CAPS" case smallCapsForced = "SMALL_CAPS_FORCED" } public struct Document: Decodable { public let id: String public let name: String public let fills: [Paint] public let style: TypeStyle? } // https://www.figma.com/plugin-docs/api/Paint/ public struct Paint: Decodable { public let type: PaintType public let opacity: Double? public let color: PaintColor? public var asSolid: SolidPaint? { return SolidPaint(self) } } public enum PaintType: String, Decodable { case solid = "SOLID" case image = "IMAGE" case rectangle = "RECTANGLE" case gradientLinear = "GRADIENT_LINEAR" case gradientRadial = "GRADIENT_RADIAL" case gradientAngular = "GRADIENT_ANGULAR" case gradientDiamond = "GRADIENT_DIAMOND" } public struct SolidPaint: Decodable { public let opacity: Double? public let color: PaintColor public init?(_ paint: Paint) { guard paint.type == .solid else { return nil } guard let color = paint.color else { return nil } self.opacity = paint.opacity self.color = color } } public struct PaintColor: Decodable { /// Channel value, between 0 and 1 public let r, g, b, a: Double } <file_sep>/Sources/FigmaAPI/Model/FigmaClientError.swift import Foundation struct FigmaClientError: Decodable, LocalizedError { let status: Int let err: String var errorDescription: String? { switch err { case "Not found": return "Figma file not found. Check lightFileId and darkFileId (if you project supports dark mode) in the yaml config file." default: return "Figma API: \(err)" } } } <file_sep>/Examples/ExampleSwiftUI/Podfile platform :ios, '11.0' target 'ExampleSwiftUI' do use_frameworks! pod 'FigmaExport' end <file_sep>/Sources/XcodeExport/Model/XcodeColorsOutput.swift import Foundation import FigmaExportCore public struct XcodeColorsOutput { public let assetsColorsURL: URL? public let assetsInMainBundle: Bool public let assetsInSwiftPackage: Bool public let addObjcAttribute: Bool public let colorSwiftURL: URL? public let swiftuiColorSwiftURL: URL? public let groupUsingNamespace: Bool public init( assetsColorsURL: URL?, assetsInMainBundle: Bool, assetsInSwiftPackage: Bool? = false, addObjcAttribute: Bool? = false, colorSwiftURL: URL? = nil, swiftuiColorSwiftURL: URL? = nil, groupUsingNamespace: Bool? = nil) { self.assetsColorsURL = assetsColorsURL self.assetsInMainBundle = assetsInMainBundle self.assetsInSwiftPackage = assetsInSwiftPackage ?? false self.addObjcAttribute = addObjcAttribute ?? false self.colorSwiftURL = colorSwiftURL self.swiftuiColorSwiftURL = swiftuiColorSwiftURL self.groupUsingNamespace = groupUsingNamespace ?? false } } <file_sep>/Sources/FigmaExport/Subcommands/ExportIcons.swift import Foundation import ArgumentParser import FigmaAPI import XcodeExport import FigmaExportCore import AndroidExport extension FigmaExportCommand { struct ExportIcons: ParsableCommand { static let configuration = CommandConfiguration( commandName: "icons", abstract: "Exports icons from Figma", discussion: "Exports icons from Figma to Xcode / Android Studio project") @OptionGroup var options: FigmaExportOptions @Argument(help: """ [Optional] Name of the icons to export. For example \"ic/24/edit\" \ to export single icon, \"ic/24/edit, ic/16/notification\" to export several icons and \ \"ic/16/*\" to export all icons of size 16 pt """) var filter: String? func run() throws { let client = FigmaClient(accessToken: options.accessToken, timeout: options.params.figma.timeout) if options.params.ios != nil { logger.info("Using FigmaExport \(FigmaExportCommand.version) to export icons to Xcode project.") try exportiOSIcons(client: client, params: options.params) } if options.params.android != nil { logger.info("Using FigmaExport \(FigmaExportCommand.version) to export icons to Android Studio project.") try exportAndroidIcons(client: client, params: options.params) } } private func exportiOSIcons(client: Client, params: Params) throws { guard let ios = params.ios, let iconsParams = ios.icons else { logger.info("Nothing to do. You haven’t specified ios.icons parameters in the config file.") return } logger.info("Fetching icons info from Figma. Please wait...") let loader = ImagesLoader(client: client, params: params, platform: .ios, logger: logger) let imagesTuple = try loader.loadIcons(filter: filter) logger.info("Processing icons...") let processor = ImagesProcessor( platform: .ios, nameValidateRegexp: params.common?.icons?.nameValidateRegexp, nameReplaceRegexp: params.common?.icons?.nameReplaceRegexp, nameStyle: iconsParams.nameStyle ) let icons = processor.process(light: imagesTuple.light, dark: imagesTuple.dark) if let warning = icons.warning?.errorDescription { logger.warning("\(warning)") } let assetsURL = ios.xcassetsPath.appendingPathComponent(iconsParams.assetsFolder) let output = XcodeImagesOutput( assetsFolderURL: assetsURL, assetsInMainBundle: ios.xcassetsInMainBundle, assetsInSwiftPackage: ios.xcassetsInSwiftPackage, addObjcAttribute: ios.addObjcAttribute, preservesVectorRepresentation: iconsParams.preservesVectorRepresentation, uiKitImageExtensionURL: iconsParams.imageSwift, swiftUIImageExtensionURL: iconsParams.swiftUIImageSwift, renderMode: iconsParams.renderMode, renderModeDefaultSuffix: iconsParams.renderModeDefaultSuffix, renderModeOriginalSuffix: iconsParams.renderModeOriginalSuffix, renderModeTemplateSuffix: iconsParams.renderModeTemplateSuffix) let exporter = XcodeIconsExporter(output: output) let localAndRemoteFiles = try exporter.export(icons: icons.get(), append: filter != nil) if filter == nil { try? FileManager.default.removeItem(atPath: assetsURL.path) } logger.info("Downloading remote files...") let localFiles = try fileDownloader.fetch(files: localAndRemoteFiles) logger.info("Writting files to Xcode project...") try fileWriter.write(files: localFiles) do { let xcodeProject = try XcodeProjectWriter(xcodeProjPath: ios.xcodeprojPath, target: ios.target) try localFiles.forEach { file in if file.destination.file.pathExtension == "swift" { try xcodeProject.addFileReferenceToXcodeProj(file.destination.url) } } try xcodeProject.save() } catch { logger.error("Unable to add some file references to Xcode project") } checkForUpdate(logger: logger) logger.info("Done!") } private func exportAndroidIcons(client: Client, params: Params) throws { guard let android = params.android, let androidIcons = android.icons else { logger.info("Nothing to do. You haven’t specified android.icons parameter in the config file.") return } // 1. Get Icons info logger.info("Fetching icons info from Figma. Please wait...") let loader = ImagesLoader(client: client, params: params, platform: .android, logger: logger) let imagesTuple = try loader.loadIcons(filter: filter) // 2. Proccess images logger.info("Processing icons...") let processor = ImagesProcessor( platform: .android, nameValidateRegexp: params.common?.icons?.nameValidateRegexp, nameReplaceRegexp: params.common?.icons?.nameReplaceRegexp, nameStyle: .snakeCase ) let icons = processor.process(light: imagesTuple.light, dark: imagesTuple.dark) if let warning = icons.warning?.errorDescription { logger.warning("\(warning)") } // Create empty temp directory let tempDirectoryLightURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let tempDirectoryDarkURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) // 3. Download SVG files to user's temp directory logger.info("Downloading remote files...") let remoteFiles = try icons.get().flatMap { asset -> [FileContents] in let lightFiles = asset.light.images.map { image -> FileContents in let fileURL = URL(string: "\(image.name).svg")! let dest = Destination(directory: tempDirectoryLightURL, file: fileURL) return FileContents(destination: dest, sourceURL: image.url) } let darkFiles = asset.dark?.images.map { image -> FileContents in let fileURL = URL(string: "\(image.name).svg")! let dest = Destination(directory: tempDirectoryDarkURL, file: fileURL) return FileContents(destination: dest, sourceURL: image.url, dark: true) } ?? [] return lightFiles + darkFiles } var localFiles = try fileDownloader.fetch(files: remoteFiles) // 4. Move downloaded SVG files to new empty temp directory try fileWriter.write(files: localFiles) // 5. Convert all SVG to XML files logger.info("Converting SVGs to XMLs...") try svgFileConverter.convert(inputDirectoryUrl: tempDirectoryLightURL) logger.info("Converting dark SVGs to XMLs...") try svgFileConverter.convert(inputDirectoryUrl: tempDirectoryDarkURL) // Create output directory main/res/custom-directory/drawable/ let lightDirectory = URL(fileURLWithPath: android.mainRes .appendingPathComponent(androidIcons.output) .appendingPathComponent("drawable", isDirectory: true).path) let darkDirectory = URL(fileURLWithPath: android.mainRes .appendingPathComponent(androidIcons.output) .appendingPathComponent("drawable-night", isDirectory: true).path) if filter == nil { // Clear output directory try? FileManager.default.removeItem(atPath: lightDirectory.path) try? FileManager.default.removeItem(atPath: darkDirectory.path) } // 6. Move XML files to main/res/drawable/ localFiles = localFiles.map { fileContents -> FileContents in let source = fileContents.destination.url .deletingPathExtension() .appendingPathExtension("xml") let fileURL = fileContents.destination.file .deletingPathExtension() .appendingPathExtension("xml") let directory = fileContents.dark ? darkDirectory : lightDirectory return FileContents( destination: Destination(directory: directory, file: fileURL), dataFile: source ) } logger.info("Writing files to Android Studio project...") try fileWriter.write(files: localFiles) try? FileManager.default.removeItem(at: tempDirectoryLightURL) try? FileManager.default.removeItem(at: tempDirectoryDarkURL) checkForUpdate(logger: logger) logger.info("Done!") } } } <file_sep>/Sources/FigmaExportCore/AssetPair.swift public struct AssetPair<AssetType> where AssetType: Asset { public let light: AssetType public let dark: AssetType? public init(light: AssetType, dark: AssetType?) { self.light = light self.dark = dark } } <file_sep>/Sources/XcodeExport/XcodeIconsExporter.swift import Foundation import FigmaExportCore final public class XcodeIconsExporter: XcodeImagesExporterBase { public func export(icons: [AssetPair<ImagePack>], append: Bool) throws -> [FileContents] { // Generate metadata (Assets.xcassets/Icons/Contents.json) let contentsFile = XcodeEmptyContents().makeFileContents(to: output.assetsFolderURL) // Generate assets let assetsFolderURL = output.assetsFolderURL let preservesVectorRepresentation = output.preservesVectorRepresentation // Filtering at suffixes let renderMode = output.renderMode ?? .template let defaultSuffix = renderMode == .template ? output.renderModeDefaultSuffix : nil let originalSuffix = renderMode == .template ? output.renderModeOriginalSuffix : nil let templateSuffix = renderMode != .template ? output.renderModeTemplateSuffix : nil let imageAssetsFiles = try icons.flatMap { imagePack -> [FileContents] in let preservesVector = preservesVectorRepresentation?.first(where: { $0 == imagePack.light.name }) != nil if let defaultSuffix = defaultSuffix, imagePack.light.name.hasSuffix(defaultSuffix) { return try imagePack.makeFileContents(to: assetsFolderURL, preservesVector: preservesVector, renderMode: .default) } else if let originalSuffix = originalSuffix, imagePack.light.name.hasSuffix(originalSuffix) { return try imagePack.makeFileContents(to: assetsFolderURL, preservesVector: preservesVector, renderMode: .original) } else if let templateSuffix = templateSuffix, imagePack.light.name.hasSuffix(templateSuffix) { return try imagePack.makeFileContents(to: assetsFolderURL, preservesVector: preservesVector, renderMode: .template) } return try imagePack.makeFileContents(to: assetsFolderURL, preservesVector: preservesVector, renderMode: renderMode) } // Generate extensions let imageNames = icons.map { $0.light.name } let extensionFiles = try generateExtensions(names: imageNames, append: append) return [contentsFile] + imageAssetsFiles + extensionFiles } } <file_sep>/Tests/AndroidExportTests/AndroidColorExporterTests.swift import XCTest import AndroidExport import FigmaExportCore final class AndroidColorExporterTests: XCTestCase { // MARK: - Properties private let outputDirectory = URL(string: "~/")! private let colorPair1 = AssetPair<Color>( light: Color(name: "colorPair1", red: 119.0/255.0, green: 3.0/255.0, blue: 1.0, alpha: 0.5), dark: nil ) private let colorPair2 = AssetPair<Color>( light: Color(name: "colorPair2", red: 1, green: 1, blue: 1, alpha: 1), dark: Color(name: "colorPair2", red: 0, green: 0, blue: 0, alpha: 1) ) // MARK: - Setup func testExport() throws { let exporter = AndroidColorExporter(outputDirectory: outputDirectory) let result = exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 2) XCTAssertEqual(result[0].destination.directory.lastPathComponent, "values") XCTAssertEqual(result[0].destination.file.absoluteString, "colors.xml") XCTAssertEqual(result[1].destination.directory.lastPathComponent, "values-night") XCTAssertEqual(result[1].destination.file.absoluteString, "colors.xml") let fileContentLight = try XCTUnwrap(result[0].data) let fileContentDark = try XCTUnwrap(result[1].data) let generatedCodeLight = String(data: fileContentLight, encoding: .utf8) let generatedCodeDark = String(data: fileContentDark, encoding: .utf8) let referenceCodeLight = """ <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPair1">#807703FF</color> <color name="colorPair2">#FFFFFF</color> </resources> """ let referenceCodeDark = """ <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPair1">#807703FF</color> <color name="colorPair2">#000000</color> </resources> """ XCTAssertEqual(generatedCodeLight, referenceCodeLight) XCTAssertEqual(generatedCodeDark, referenceCodeDark) } }
6843c16b5933ceb0562cca523df2275e360a6779
[ "Swift", "Ruby", "Shell" ]
29
Swift
ptxmac/figma-export
e14b9fa3a6bf3f6208669706a86cf45a8712f1f5
5f49bdc8898259339ec334057efe7a238b3df4f9
refs/heads/master
<file_sep>#!/usr/bin/env bash sudo apt install -y build-essential autoconf libtool curl <file_sep>[Google GRPC 1.11.0-pre2](https://github.com/grpc/grpc) headers, prebuilt libraries & prebuilt compilers. CFLAGS="-O3 -g -fPIC -Wno-implicit-fallthrough -Wno-maybe-uninitialized -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 ${CFLAGS}" CXXFLAGS="-O3 -g -fPIC -Wno-implicit-fallthrough -Wno-maybe-uninitialized -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 ${CXXFLAGS}" LDFLAGS="-O3 -g -fPIC -Wl,--unresolved-symbols=report-all -Wl,--gc-sections -Wl,-rpath,./ ${LDFLAGS}" <file_sep>#!/usr/bin/env bash cd ../grpc/third_party/protobuf ./autogen.sh CFLAGS="-O3 -g -fPIC -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 $CFLAGS" \ CXXFLAGS="-O3 -g -fPIC -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 $CXXFLAGS" \ LDFLAGS="-O3 -g -fPIC -Wl,--unresolved-symbols=report-all -Wl,--gc-sections -Wl,-rpath,./ $LDFLAGS" \ ./configure CFLAGS="-O3 -g -fPIC -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 $CFLAGS" \ CXXFLAGS="-O3 -g -fPIC -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 $CXXFLAGS" \ LDFLAGS="-O3 -g -fPIC -Wl,--unresolved-symbols=report-all -Wl,--gc-sections -Wl,-rpath,./ $LDFLAGS" \ make CFLAGS="-O3 -g -fPIC -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 $CFLAGS" \ CXXFLAGS="-O3 -g -fPIC -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 $CXXFLAGS" \ LDFLAGS="-O3 -g -fPIC -Wl,--unresolved-symbols=report-all -Wl,--gc-sections -Wl,-rpath,./ $LDFLAGS" \ make install <file_sep>#!/usr/bin/env bash cd ../grpc CFLAGS="-O3 -g -fPIC -Wno-implicit-fallthrough -Wno-maybe-uninitialized -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 ${CFLAGS}" \ CXXFLAGS="-O3 -g -fPIC -Wno-implicit-fallthrough -Wno-maybe-uninitialized -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 ${CXXFLAGS}" \ LDFLAGS="-O3 -g -fPIC -Wl,--unresolved-symbols=report-all -Wl,--gc-sections -Wl,-rpath,./ ${LDFLAGS}" \ make CFLAGS="-O3 -g -fPIC -Wno-implicit-fallthrough -Wno-maybe-uninitialized -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 ${CFLAGS}" \ CXXFLAGS="-O3 -g -fPIC -Wno-implicit-fallthrough -Wno-maybe-uninitialized -fdata-sections -ffunction-sections -fno-strict-aliasing -msse -msse2 -msse3 -mssse3 -msse4 -msse4.1 -msse4.2 -mf16c -mfma -mavx -mavx2 ${CXXFLAGS}" \ LDFLAGS="-O3 -g -fPIC -Wl,--unresolved-symbols=report-all -Wl,--gc-sections -Wl,-rpath,./ ${LDFLAGS}" \ make install
2f725571d1f7715fce0711f39570c9678f858a11
[ "Markdown", "Shell" ]
4
Shell
danek-kulik/grpc-prebuilt
49a93efae8502c7a368dceac42614dbbb2f6f7c6
a3611aacd7bc9cbe6476917516e5bdce1d2014b8
refs/heads/master
<file_sep>require 'view_elements/helper' module ViewElements class Railtie < ::Rails::Engine initializer 'view_elements.add_helpers' do ActionView::Base.send :include, ViewElements::Helper end initializer "view_elements.assets" do |app| Rails.application.config.assets.paths << ViewElements.configuration.components_path end end end <file_sep>module ViewElements class Component attr_reader :action_view, :components_path, :name, :locals def initialize(action_view, name, locals) @action_view = action_view @name = name @locals = locals @components_path = ViewElements.configuration.components_path end def layout ViewElements.configuration.layout end def render presenter.before_render if presenter.respond_to?(:before_render) if layout.present? && presenter.default_wrap? presenter.wrapper { _render } else _render end end def _render ViewElements::Renderer.new(action_view, template_path, build_locals).render end def presenter @presenter ||= presenter_class.constantize.new(action_view, locals, self) rescue NameError => e raise ComponentNotFound.new("Cannot load #{presenter_class}: #{e.message}") end def presenter_class @presenter_class ||= "#{name.to_s}/presenter".classify end def presenter_path component_path.join('presenter') end def template_path component_path.join('index') end def component_path components_path.join(name.to_s) end def include_partial(name, partial_locals = {}) ViewElements::Renderer.new(action_view, component_path.join("_#{name}"), build_locals.merge(partial_locals)).render end def cmp(cmp_name, cmp_locals) sub_cmp_name = "#{name}/#{cmp_name}" self.class.new(action_view, sub_cmp_name, cmp_locals).render end private def build_locals {}.tap do |new_locals| new_locals.merge!(presenter.locals) new_locals[:component] = self new_locals[:element] = presenter new_locals[:e] = presenter new_locals[:presenter] = presenter new_locals[:pr] = presenter temp = presenter.expose_locals new_locals.merge!(temp) if temp end end end class ComponentNotFound < StandardError ; end end <file_sep>module ViewElements class Configuration attr_accessor :components_path, :strict_properties, :layout def initialize @components_path = Rails.root.join('app','view_elements') @strict_properties = false @layout = true end def component_relative_dirs components_dirs.map { |dir| Pathname.new(dir).relative_path_from(components_path) } end def components_dirs Dir.glob(components_path.join('**/**')) .select { |dir| File.directory?(dir) } end def components_path=(path) @components_path = Pathname.new(path) end end end <file_sep>module ViewElements class Presenter module RailsSupport def method_missing(m, *args, &block) if action_view.respond_to?(m) action_view.public_send(m, *args, &block) else super end end end end end <file_sep>module ViewElements class Presenter module Lets def let(name, &block) @lets ||= {} @lets[name] = block define_method name do v = instance_variable_get("@#{name}") || instance_eval(&self.class.lets[name]) instance_variable_set("@#{name}", v) end end def lets @lets end end end end <file_sep>require 'spec_helper' describe ViewElements::Renderer, type: :helper do describe '#render' do it 'should render view' do action_view = helper.controller.view_context template = Rails.root.join('app', 'view_elements', 'some_element/some_element') presenter = SomeElement::SomeElement.new(action_view) renderer = ViewElements::Renderer.new(action_view, template, presenter) html = renderer.render expect(html).to include("some element content") end end end <file_sep>ViewElements.configuration.components_path = Rails.root.join('app','view_elements') <file_sep># ViewElements View partials structured as components inspired by all JavaScript frameworks out there (Angular2, Marko.js, Vue.js, React). ## Installation Add this line to your application's Gemfile: ```ruby gem 'view_elements' ``` And then execute: $ bundle Or install it yourself as: $ gem install view_elements ## Intro The whole purpose of this project is trying to fix the partial and helper madness. That is, one view folder having dozen of partials, other views from different controllers using partials from other views in a not so good predictable way, and helper methods as global methods everywhere. Also, each component can take care of loading the data/models that needs, removing the need for the controller to load the models. I never liked the controller loading models. I started noticing that every time I wanted to reuse a partial, I had to make sure I loaded the data it needs on the controller and that was creating a lot of duplication. I know it breaks the MVC paradigm, but I find it much easier loading that in the component. The idea is that each `partial` now becomes a `component` and stylesheet, Javascript, presenter and view goes into the same folder named as the partial. Also, component can have nested components, so it can be structured in a predictable way and the layout itself can be used for documenting how the partial works. ## Usage Run generator `rails generate view_elements:component shopping_cart/items_list` It will create this structure ``` /app /view_elements /shopping_cart /items_list /item index.html.erb presenter.rb component.js style.scss index.html.erb presenter.rb component.js style.scss ``` **In your existing view `app/views/cart/index.html.erb`** ```erb <%= cmp 'shopping_cart/items_list', items: @items %> ``` **Inside folder `app/view_elements/shopping_cart/items_list`** index.html.erb ```erb <%= presenter.title %> <ul class='item-list'> <% items.each do |item| %> <li class='item'><%= componet.cmp 'item', item: item %></li> <!--component.cmp looks for components in the current component directory --> <% end %> </ul> ``` presenter.rb ```ruby module ShoppingCart::ItemsList class Presenter < ViewElements::Presenter properties :items def title "Your cart with #{items.size}" end end end ``` component.js ```javascript $('.item-list li').on('click', function() { alert('Item clicked'); }); ``` style.scss ```scss .item-list { li { background-color: silver; } } ``` **Inside folder `app/view_elements/shopping_cart/items_list/item`** index.html.erb ```erb <div class='item'> <b><%= item %></b> <%= presenter.link_to_remove %> </div> ``` presenter.rb ```ruby module ShoppingCart::ItemsList::Item class Presenter < ViewElements::Presenter properties :item def link_to_remove h.link_to 'Remove', item_path(item), method: :destroy end end end ``` component.js ```javascript // Do something fancy with Javascript ``` style.scss ```scss .item { text-decoration: underline; } ``` **Assets** You have to add the following to your `application.js.erb` and `application.scss.erb` in order to have `component.js` and `style.scss` available. Both need to end with the `.erb` extension. application.scss.erb ```erb <% ViewElements::Assets.css_files.each do |f| %> @import '<%=f %>'; <% end %> ``` application.js.erb ```erb <% ViewElements::Assets.js_files.each do |f| %> <%= require_asset f %> <% end %> ``` ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/view_elements. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). <file_sep>module ViewElements module Helper def find_cmp(name,locals) ViewElements::Component.new(self.controller.view_context, name, locals) end def cmp(name, locals = {}) find_cmp(name, locals).render end alias_method :render_view_element, :cmp alias_method :el, :cmp end end <file_sep>require "view_elements/version" require 'view_elements/assets' require 'view_elements/renderer' # require 'view_elements/view_element' # require 'view_elements/component' require 'view_elements/component' require 'view_elements/presenter' require 'view_elements/railtie' require 'view_elements/configuration' module ViewElements # def self.components_map # @components_map ||= {} # end # def self.register(name, component) # components_map[name] = component # # define_component_helper name, component # end # def self.register_components_helpers(helper_module) # Dir.glob("#{Rails.root}/app/view_elements/**/*.rb").sort.each do |file| # p = Rails.root.join('app','view_elements/').to_s # e = file.gsub(p, '').gsub('.rb','') # # clazz = e.classify.constantize # clazz.define_helper(helper_module) if clazz.respond_to?(:define_helper) # end # end def self.require_presenters! Dir.glob("#{configuration.components_path}/**/*.rb").each do |file| require file end end def self.helper_names ViewElements::Registry.components_map.keys end def self.configuration @configuration ||= Configuration.new end def self.configure yield(configuration) end # def sefl.presenter(name) # Define.new(name).define # end end <file_sep>module ViewElements class Renderer attr_reader :action_view, :template, :locals def initialize(action_view, template, locals) @action_view = action_view @template = template @locals = locals end def render action_view.render file: template, locals: locals, formats: [:html] end end end <file_sep>module SayHi::SayHiHeader class Presenter < ViewElements::ViewElement def site_name "MySite" end end end <file_sep>module ViewElements class Presenter class Define attr_reader :name def initialize(name) @name = name end def define end end end end <file_sep>require 'view_elements/presenter/exposures' require 'view_elements/presenter/lets' require 'view_elements/presenter/locals' require 'view_elements/presenter/properties' require 'view_elements/presenter/rails_support' module ViewElements class Presenter include ViewElements::Presenter::Properties include ViewElements::Presenter::Exposures include ViewElements::Presenter::Locals extend ViewElements::Presenter::Lets # include ViewElements::Presenter::RailsSupport attr_reader :action_view, :locals, :component def initialize(action_view, locals = {}, component) @locals = locals @action_view = action_view @component = component validate_properties! define_locals_accessors! end def h action_view end def helper action_view end def wrapper_tag :div end def css wrapper_css_class end def jquery_selector @jquery_selector ||= begin s = ".#{component_css_class}" s << ".#{distinct_id_css_class}" if distinct_id s end end def wrapper_css_class @css_selector ||= "#{component_css_class} #{distinct_id_css_class}" end def distinct_id_css_class "distid-#{distinct_id}" if distinct_id.present? end def component_css_class component.name.split('/').join('--') end def distinct_id end def default_wrap? true end def wrapper(&block) action_view.content_tag(wrapper_tag, action_view.capture(&block), class: "view_elements_wrapper #{wrapper_css_class}") end end end <file_sep>module SayHi class Presenter < ViewElements::ViewElement def full_name "#{locals[:first_name]} #{locals[:last_name]}" end end end <file_sep>require "spec_helper" describe "home/index", type: :view do it "displays all the widgets" do render expect(rendered).to match /hello <NAME>/ expect(rendered).to match /Welcome/ expect(rendered).to match /MySite/ end end <file_sep>module <%= class_name %> class Presenter < ViewElements::Presenter let(:some_variable) { } properties :property1, :property2 end end <file_sep>module ViewElements module Assets def self.css_files components_path = ViewElements.configuration.components_path Dir.glob(components_path.join('**/style**')) .select { |dir| File.file?(dir) } .map { |dir| Pathname.new(dir).relative_path_from(components_path) } end def self.js_files components_path = ViewElements.configuration.components_path Dir.glob(components_path.join('**/component**')) .select { |dir| File.file?(dir) } .map { |dir| Pathname.new(dir).relative_path_from(components_path) } end end end <file_sep>module SomeElement class SomeElement < ViewElements::ViewElement end end <file_sep>module ViewElements class Presenter module Locals def define_locals_accessors! return unless locals.present? l = locals (class << self; self; end).class_eval do l.each do |k, v| define_method(k) { v } end end end end end end <file_sep>module ViewElements class Presenter module Exposures def self.included base base.send :include, InstanceMethods base.extend ClassMethods end module InstanceMethods def expose_locals {}.tap do |e| exposes = self.class.exposes if exposes exposes.each do |name, block| e[name] = instance_eval(&block) unless e[name].present? end end end end end module ClassMethods def expose(name, &block) @exposes ||= {} @exposes[name] = block end def exposes @exposes end end end end end <file_sep>class ViewElements::ElementGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) def generate_class template 'element_class.rb', "app/view_elements/#{file_path}.rb" end def generate_view template 'element_view.html.erb', "app/view_elements/#{file_path}.html.erb" end end <file_sep>module ViewElements class Presenter module Properties def self.included base base.send :include, InstanceMethods base.extend ClassMethods end module ClassMethods def properties_list @properties end def properties(*args) @properties = args end end module InstanceMethods def validate_properties! return unless self.class.properties_list.present? missing_properties = _calc_missing_properties(locals) raise "Missing #{missing_properties.to_sentence} propertie(s) for #{self.class} component." if missing_properties.present? if ViewElements.configuration.strict_properties not_properties = _calc_not_properties(locals) raise "Unknown propertie(s) #{not_properties.to_sentence} for #{self.class} component." if not_properties.present? end end private def _calc_not_properties(locals) if locals.present? locals.keys.map(&:to_s) - self.class.properties_list.map(&:to_s) end end def _calc_missing_properties(locals) if locals.present? self.class.properties_list.map(&:to_s) - locals.keys.map(&:to_s) else self.class.properties_list.map(&:to_s) end end end end end end <file_sep>class <%= class_name %> < ViewElements::ViewElement end <file_sep>require 'spec_helper' describe ViewElements::Components::Renderer, type: :helper do describe '#render' do it 'should render view' do ViewElements.configuration.components_path = Rails.root.join('app', 'view_elements') action_view = helper.controller.view_context # template = 'some_element/some_element' # presenter = SomeElement::SomeElement.new(action_view) renderer = ViewElements::Components::Renderer.new(action_view, :some_element) html = renderer.render expect(html).to include("some element content") end end end <file_sep>class ViewElements::ComponentGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) def generate_class template 'presenter.rb', "app/view_elements/#{file_path}/presenter.rb" end def generate_view template 'index.html.erb', "app/view_elements/#{file_path}/index.html.erb" end def generate_js template 'component.js', "app/view_elements/#{file_path}/component.js" end def generate_scss template 'style.scss', "app/view_elements/#{file_path}/style.scss" end def css_class file_path.split('/').join('--') end def view_wrapper <<-HEREDOC <%= presenter.wrapper do %> <% end %> HEREDOC end end <file_sep>source 'https://rubygems.org' group :development, :test do gem 'byebug' gem 'rails' end # Specify your gem's dependencies in view_elements.gemspec gemspec
201ce85b391064c48a07ce0dce6a3335722e29b0
[ "Markdown", "Ruby" ]
27
Ruby
fddayan/view_elements
17cefb95138dd03976e4eae0ce278bc64ba20bca
1909fa037be9d09be80d70d10a0906e3462f004a
refs/heads/master
<repo_name>dominikgaller/esentrimicroserviceexample<file_sep>/microserviceExample/src/main/java/com/esentri/microservice/example/StartUp.java package com.esentri.microservice.example; import io.vertx.core.Vertx; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * The class {@code StartUp} is used as common sense to * start the application within an IDE or as java package. * @author dominikgaller * */ public final class StartUp { /** Path to server verticle. */ private static final String SERVERPATH = "com.esentri.microservice.example.server.Server"; private static Logger l; /** private constructor for final classes makes everyone happy. */ private StartUp() { } /** * Main method to start the vert.x application. * @param args args */ public static void main(String[] args) { l = LoggerFactory.getLogger(StartUp.class); final Vertx vertx = Vertx.vertx(); l.info("Populating Databases"); populateDatabases(vertx); l.info("Starting server"); vertx.deployVerticle(SERVERPATH); } /** * Populate the database. * * @param vertx vertx instance. */ private static void populateDatabases(Vertx vertx) { EntryDatabasePopulator edp = new EntryDatabasePopulator(vertx, "entries"); edp.populateDatabase(); UserDatabasePopulator udp = new UserDatabasePopulator(vertx, "users"); udp.populateDatabase(); } } <file_sep>/clientUI/app/js/app.js 'use strict'; var app = angular.module('myApp', [ 'ngRoute', /* External Stuff */ 'knalli.angular-vertxbus', 'ui.bootstrap', /* Controller */ 'phonebookController', 'authController', 'editController' ]); app.config([ '$routeProvider', 'vertxEventBusProvider', function($routeProvider, vertxEventBusProvider) { console.log("Configurating routing.") $routeProvider.when('/phonebook', { templateUrl: 'partials/phonebook/phonebook.html', controller: 'PhonebookCtrl' }) .when('/edit', { templateUrl: 'partials/edit/edit.html', controller: 'EditCtrl', resolve: { factory: function ($rootScope, $location) { if (!$rootScope.loggedIn) { $rootScope.loginerr = "login wrong!"; $location.path('/phonebook'); } return $rootScope.loggedIn; } } }) .otherwise({ redirectTo: '/phonebook' }); console.log("Configurating EventBus."); vertxEventBusProvider .enable() .useReconnect() .useUrlServer('http://localhost:8080') .useUrlPath('/eventbus') .useDebug(true); }]); app.run(['$rootScope', function($rootScope) { $rootScope.sessionId = 0; console.log("WebApp is running."); }]); <file_sep>/microserviceExample/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.esentri.example</groupId> <artifactId>microserviceExample</artifactId> <version>0.0.1-SNAPSHOT</version> <name>microserviceExample</name> <properties> <vertx.version>3.2.0</vertx.version> <java.version>1.8</java.version> <mainclass>com.esentri.microservice.example.StartUp</mainclass> <mainverticle>com.esentri.microsercice.example.server.Server</mainverticle> </properties> <dependencies> <!-- Vert.x Dependencies --> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-core</artifactId> <version>${vertx.version}</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-unit</artifactId> <version>${vertx.version}</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web</artifactId> <version>${vertx.version}</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-jdbc-client</artifactId> <version>${vertx.version}</version> </dependency> <!-- JUnit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <optional>true</optional> </dependency> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.10</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <!-- We specify the Maven compiler plugin as we need to set it to Java 1.8 --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <manifestEntries> <Main-Class>${mainclass}</Main-Class> <Main-Verticle>${mainverticle}</Main-Verticle> </manifestEntries> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>META-INF/services/io.vertx.core.spi.VerticleFactory</resource> </transformer> <!-- transformer implementation="org.apache.maven.plugins.shade.resource.IncludeResourceTransformer"> <resource>resources/entries.json</resource> <file>src/main/resources/entries.json</file> </transformer --> </transformers> <artifactSet></artifactSet> <outputFile>${project.build.directory}/${project.name}-${project.version}-fat.jar</outputFile> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/microserviceExample/src/main/java/com/esentri/microservice/example/EntryDatabasePopulator.java package com.esentri.microservice.example; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import io.vertx.core.AsyncResult; import io.vertx.core.Vertx; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.jdbc.JDBCClient; import io.vertx.ext.sql.SQLConnection; /** * The class EntryDatabasePopulator provides simple * mechanisms and implementations, to populate an entry database * and insert some default tuples, defined in an json file. * * @author dominikgaller * */ public class EntryDatabasePopulator { /** Vert.x Instance to create the shared database. */ private Vertx vertxInstance; /** The name for the data base. */ private String dbName; /** * Path to entries.json file, where initial values for the phone book are * stored. */ private static final String ENTRIESPATH = "src/main/resources/entries.json"; /** * Constructor for a new EntryDatabasePopulator instance. * @param vertx the vertx context * @param dbname the data base name */ public EntryDatabasePopulator(Vertx vertx, String dbname) { this.setVertxInstance(vertx); this.setDBName(dbname); } /** * Populates the database. */ public void populateDatabase() { initDBClient(); } /** * Initializes the JDBCClient, and establishes a connection to the data * base. * * @param vertx * this verticles vertx instance. */ private void initDBClient() { final JDBCClient client = JDBCClient.createShared(this.vertxInstance, createConfig(), this.dbName); client.getConnection(conn -> { if (conn.failed()) { throw new IllegalStateException(conn.cause().getMessage()); } setUpDB(conn); }); } /** * Fills the database with entry table and content. * * @param conn */ private void setUpDB(AsyncResult<SQLConnection> conn) { createEntryDB(conn); insertEntries(conn); } /** * Creates the entry table. * * @param conn * AsyncReslut<SQLConnection> SqlConnection handler */ private void createEntryDB(AsyncResult<SQLConnection> conn) { SQLConnection connection = conn.result(); connection.execute( "create table entry(id integer identity primary key, name varchar(255), number varchar(255))", res -> { if (res.failed()) { throw new IllegalStateException(conn.cause().getMessage()); } connection.close(); }); } /** * Inserts phone book entries into the data base. The entries are defined in * the entries.json file. * * @param conn * AsyncReslut<SQLConnection> SqlConnection handler */ private void insertEntries(AsyncResult<SQLConnection> conn) { JsonArray arr = readJsonArrayFile(ENTRIESPATH); arr.forEach(elem -> { JsonObject val = new JsonObject(elem.toString()); insertEntry(conn, val.getString("name"), val.getString("number")); }); } /** * Inserts a single entry into the entry table. * * @param conn * the SQLConnection for the transaction * @param name * the entries name * @param number * the entries number */ private void insertEntry(AsyncResult<SQLConnection> conn, String name, String number) { SQLConnection connection = conn.result(); connection.execute("insert into entry (name, number) values ('" + name + "','" + number + "')", res -> { if (res.failed()) { throw new IllegalStateException(res.cause().getMessage()); } connection.close(); }); } // TODO Insert error handling :D /** * Reads a file into a json array by using non blocking io. FYI: Does no * error handling. Put in clean json array and get one out. Do something * else and no guarantees what will happen :-) * * @param path * the path to the file to read. * @return the json array representing the file content. */ private JsonArray readJsonArrayFile(String path) { try { String content = new String(Files.readAllBytes(Paths.get(path))); return new JsonArray(content); } catch (IOException e) { throw new IllegalStateException(e.getMessage()); } } /** * Creates the configuration for the data base. * * @return a json object defining the configuration. */ private JsonObject createConfig() { JsonObject config = new JsonObject().put("url", "jdbc:hsqldb:mem:" + this.dbName + "?shutdown=false") .put("driver_class", "org.hsqldb.jdbcDriver").put("max_pool_size", 30); return config; } /** * @return the vertxInstance */ public Vertx getVertxInstance() { return vertxInstance; } /** * @param vertxInstance * the vertxInstance to set */ public void setVertxInstance(Vertx vertxInstance) { this.vertxInstance = vertxInstance; } /** * @return the dBNAME */ public String getDBName() { return this.dbName; } /** * @param dBNAME * the dBNAME to set */ public void setDBName(String dbName) { this.dbName = dbName; } } <file_sep>/clientUI/app/partials/auth/authController.js var authController = angular.module('authController', []); authController.controller('LoginCtrl', [ '$scope', '$rootScope', 'vertxEventBusService', function($scope, $rootScope, vertxEventBusService) { $scope.$on("session-id-assigned", function(event) { console.log("sessionIDassigned"); vertxEventBusService.on("esentri.login.reply:" + $rootScope.sessionId, function(message) { console.log("Received login reply. Payload is: " + message); var msg = angular.fromJson(message); $rootScope.loggedIn = msg.loggedIn; if(msg.loggedIn) { console.log("Login was successful. User logged in."); $rootScope.notification = "Hi, " + msg.user.name + " (ID: " + msg.user.id + ")"; $('#login').css("display", "none"); $('#logout').css("display", "block"); } else { console.log("Login failed."); $rootScope.loginerr = "credentials wrong. try again."; } }); }); $scope.login = function(cred) { console.log(cred); if(cred === 'undefined') { $rootScope.loginerr = "please enter credentials."; } else { cred.sessionId = $rootScope.sessionId; console.log("Sending login request with payload: " + cred); vertxEventBusService.send("esentri.login.request", angular.toJson(cred)); } }; } ]); authController.controller('LogoutCtrl', [ '$scope', '$rootScope', 'vertxEventBusService', '$location', function($scope, $rootScope, vertxEventBusService, $location) { $scope.logout = function() { vertxEventBusService.send("esentri.logout", "logmeout").then(function(message) { console.log("Logout request sent, and answer received."); console.log("Payload for sending was irrelevant."); console.log("Answer is: " + message.body); msg = angular.fromJson(message.body); if(msg.logout) { $rootScope.loggedIn = false; $('#logout').css("display", "none"); $('#login').css("display", "block"); $location.path('phonebook'); } }); }; } ]);<file_sep>/clientUI/app/partials/phonebook/phonebookController.js var phonebookController = angular.module('phonebookController', []); phonebookController.controller('PhonebookCtrl', [ '$scope', '$rootScope', 'vertxEventBusService', function($scope, $rootScope, vertxEventBusService) { $scope.entries = $rootScope.entries; $scope.request = false; $scope.$on('vertx-eventbus.system.connected', function (event) { console.log("Eventbus connected."); if($rootScope.sessionId == 0) { console.log("Sending intial request for session id."); vertxEventBusService.send("esentri.session.request", "requesting session").then(function(message){ //Body is needed here because msg is sync (format changes here) console.log("session id received. With payload: " + message.body); var json = angular.fromJson(message.body); $rootScope.sessionId = json.sessionId; var sObj = { sessionId: $rootScope.sessionId }; $rootScope.sessionObj = angular.toJson(sObj); $rootScope.$broadcast("session-id-assigned"); vertxEventBusService.addListener("esentri.entries.display:" + $rootScope.sessionId, function(message) { console.log("Received answer for entries."); console.log("Payload is: " + message); $scope.entries = JSON.parse(message); $rootScope.entries = $scope.entries; }); console.log("Sending intial request for entries."); vertxEventBusService.send("esentri.entries.request", $rootScope.sessionObj); $scope.request = true; }); } else { console.log("Sending request for entries."); vertxEventBusService.send("esentri.entries.request", $rootScope.sessionObj); $scope.request = true; } }); if(!$scope.request && $rootScope.sessionId != 0) { console.log("Sending request for entries."); vertxEventBusService.send("esentri.entries.request", $rootScope.sessionObj); } } ]);<file_sep>/clientUI/app/partials/edit/editController.js var editController = angular.module('editController', []); editController.controller('EditCtrl', [ '$scope', '$rootScope', 'vertxEventBusService', function($scope, $rootScope, vertxEventBusService) { $scope.editrequest = false; $scope.entries = $rootScope.entries; $scope.$on('vertx-eventbus.system.connected', function (event) { console.log("Eventbus connected."); console.log("Sending initial request for entries. Payload is: " + $rootScope.sessionObj); vertxEventBusService.send("esentri.entries.request", $rootScope.sessionObj); $scope.editrequest = true; }); if(!$scope.editrequest) { console.log("Sending request for entries. Payload is: " + $rootScope.sessionObj); vertxEventBusService.send("esentri.entries.request", $rootScope.sessionObj); } vertxEventBusService.addListener("esentri.entries.display:" + $rootScope.sessionId, function(message) { console.log("Received answer for entries."); console.log("Payload is: " + message); $scope.entries = angular.fromJson(message); $rootScope.entries = $scope.entries; }); $scope.deleteEntry = function(entry) { var request = { entry: entry, sessionId: $rootScope.sessionId }; console.log("Sending request for deleting an entry. Payload is: " + request); vertxEventBusService.send("esentri.entries.delete", angular.toJson(request)); }; $scope.addEntry = function(toBeAdded) { var request = { entry: toBeAdded, sessionId: $rootScope.sessionId }; console.log("Sending request for adding an entry. Payload is: " + request); vertxEventBusService.send("esentri.entries.add", angular.toJson(request)); }; } ]);
440f16e0b656eb3cda2d85365bb57cb795b9b1cb
[ "JavaScript", "Java", "Maven POM" ]
7
Java
dominikgaller/esentrimicroserviceexample
232345403cfe30f23b772ec14573413c3cabb4af
591ff2ee9b473d390b662cdc2d574d9c52a84205
refs/heads/master
<file_sep>console.log("successful require workspace a")
2dd6eae80b16b411c88ef816672376fffc709c27
[ "JavaScript" ]
1
JavaScript
yace132/Aries
efbe201c1bbad2f85efc660ed01bc09d518487f2
6e75920f06657a0061c0d191299ee3f7ef9622e5
refs/heads/master
<file_sep>import numpy as np import pandas as pd from pandas.tseries.holiday import USFederalHolidayCalendar import xgboost as xgb from sklearn.cross_validation import train_test_split from sklearn.cross_validation import ShuffleSplit from sklearn.cross_validation import StratifiedKFold from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import Normalizer from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from scipy.sparse import csr_matrix from sklearn.decomposition import NMF from sklearn.metrics import log_loss import operator import matplotlib.pyplot as plt ############################################################################################# # Feature Extraction # ############################################################################################# def map_age(x): if (x >= 100) | (x < 15): return -1 return (x - 15) / 5 def holiday_transform(x): if x >= 0: if x < 6: return x else: return 7 else: if x > -6: return x else: return -7 def build_features(data, features): #Timestamp First Active data['timestamp_first_active'] = data['timestamp_first_active'].astype(str) data['timestamp_first_active_date'] = data['timestamp_first_active'].str[:8] data['timestamp_first_active_date'] = pd.to_datetime(data['timestamp_first_active_date'], format='%Y%m%d') data['tfa_month'] = data['timestamp_first_active_date'].map(lambda x : x.month) data['tfa_year'] = data['timestamp_first_active_date'].map(lambda x : x.year) data['tfa_day'] = data['timestamp_first_active_date'].map(lambda x : x.day) data['tfa_dayofyear'] = data.timestamp_first_active_date.dt.dayofyear data['tfa_dayofweek'] = data.timestamp_first_active_date.dt.dayofweek data['tfa_week'] = data.timestamp_first_active_date.dt.week data['tfa_quarter'] = data.timestamp_first_active_date.dt.quarter features.extend(['tfa_day','tfa_month','tfa_year','tfa_dayofyear','tfa_dayofweek','tfa_week','tfa_quarter']) #TFA Holidays #calendar = USFederalHolidayCalendar() #tfa_holidays = calendar.holidays(start=data['timestamp_first_active_date'].min(),end=data['timestamp_first_active_date'].max()) #for i in range(len(tfa_holidays)): #data['tfa_holiday_diff_'+str(i)] = data['timestamp_first_active_date'].map(lambda x : (x-tfa_holidays[i]).days) #data['tfa_holiday_diff_'+str(i)] = data['tfa_holiday_diff_'+str(i)].map(holiday_transform) #data_dummy = pd.get_dummies(data['tfa_holiday_diff_'+str(i)],prefix='tfa_holiday_diff_'+str(i)) #features.extend(data_dummy.columns.values) #data.drop(['tfa_holiday_diff_'+str(i)],axis=1,inplace=True) #data = pd.concat((data,data_dummy),axis=1) #features.extend('tfa_holiday_diff_'+str(i)) #Date Account Created data['date_account_created'] = pd.to_datetime(data['date_account_created']) data['dac_month'] = data['date_account_created'].map(lambda x : x.month) data['dac_year'] = data['date_account_created'].map(lambda x : x.year) data['dac_day'] = data['date_account_created'].map(lambda x : x.day) data['dac_dayofyear'] = data.date_account_created.dt.dayofyear data['dac_dayofweek'] = data.date_account_created.dt.dayofweek data['dac_week'] = data.date_account_created.dt.week data['dac_quarter'] = data.date_account_created.dt.quarter features.extend(['dac_year','dac_month','dac_day','dac_dayofyear','dac_dayofweek','dac_week','dac_quarter']) #DAC Holidays calendar = USFederalHolidayCalendar() dac_holidays = calendar.holidays(start=data['date_account_created'].min(),end=data['date_account_created'].max()) for i in range(len(dac_holidays)): data['dac_holiday_diff_'+str(i)] = data['date_account_created'].map(lambda x : (x-dac_holidays[i]).days) data['dac_holiday_diff_'+str(i)] = data['dac_holiday_diff_'+str(i)].map(holiday_transform) features.extend(['dac_holiday_diff_'+str(i)]) #Days Difference Between TFA and DAC data['days_diff'] = (data['date_account_created'] - data['timestamp_first_active_date']).dt.days #data['days_diff'] = data['days_diff'].map(holiday_transform) features.extend(['days_diff']) data.drop(['date_account_created','timestamp_first_active','timestamp_first_active_date'],axis=1,inplace=True) other_features = ['gender', 'signup_method','signup_flow','language','affiliate_channel', 'affiliate_provider', 'first_affiliate_tracked', 'signup_app', 'first_device_type', 'first_browser'] for f in other_features: data_dummy = pd.get_dummies(data[f],prefix=f) features.extend(data_dummy.columns.values) data.drop([f],axis=1,inplace=True) data = pd.concat((data,data_dummy),axis=1) return data train = pd.read_csv('train_users_2.csv') test = pd.read_csv('test_users.csv') data = pd.concat((train, test),axis=0,ignore_index=True) data = data.drop('date_first_booking',axis=1) data.fillna(-1,inplace=True) train_dim = train.shape[0] #Build Features features = [] data = build_features(data,features) #Age dummy data['age'] = data['age'].astype(int) data['age'] = data['age'].map(map_age) age_dummy = pd.get_dummies(data['age'],prefix='age') data.drop(['age'],axis=1,inplace=True) data = pd.concat((data,age_dummy),axis=1) features.extend(age_dummy.columns.values) #print features #print data.head() #Restore Train and Test train = data[:train_dim] test = data[train_dim:] print ('tf-idf...') #Sessions Data sessions = pd.read_csv('sessions2.csv') sessions_secs = sessions[['user_id','secs_elapsed']] sessions_actions = sessions[['user_id','action']] #total_time = sessions_secs.groupby('user_id')['secs_elapsed'].sum().reset_index() sessions_reduce = sessions_actions.groupby('user_id')['action'].apply(lambda r : r.tolist()).reset_index() def toList(line): return ' '.join(str(x) for x in line) sessions_reduce['action_string'] = sessions_reduce['action'].map(toList) actions = list(sessions_reduce['action_string']) #Tfidf Features for Action max_features = 12 vectorizer = TfidfVectorizer(min_df=1, max_features=max_features) action_tfidf = vectorizer.fit_transform(actions) a_cols = ['action_'+str(i) for i in range(max_features)] a_vec = pd.DataFrame(action_tfidf.toarray(),columns=a_cols) a_vectorizer_features = pd.concat((sessions_reduce['user_id'], a_vec), axis=1) #Tfidf Features for Action Type sessions_action_types = sessions[['user_id','action_type']] sessions_action_types_reduce = sessions_action_types.groupby('user_id')['action_type'].apply(lambda r : r.tolist()).reset_index() sessions_action_types_reduce['action_types'] = sessions_action_types_reduce['action_type'].map(toList) action_types = list(sessions_action_types_reduce['action_types']) max_features = 6 action_type_vec = TfidfVectorizer(min_df=1, max_features=max_features) action_type_tfidf = action_type_vec.fit_transform(action_types) at_cols = ['action_type_'+str(i) for i in range(max_features)] at_vec = pd.DataFrame(action_type_tfidf.toarray(),columns=at_cols) at_vectorizer_features = pd.concat((sessions_action_types_reduce['user_id'], at_vec), axis=1) #Combine Tfidf Features of Action and Action Type sessions_features = a_vectorizer_features.merge(at_vectorizer_features, on='user_id') #Combine Sessions Data with Train and Test train = pd.merge(train, sessions_features, how='left', left_on='id', right_on='user_id') test = pd.merge(test, sessions_features, how='left', left_on='id', right_on='user_id') train.fillna(-1,inplace=True) test.fillna(-1,inplace=True) features.extend(a_cols) features.extend(at_cols) print ('Latent semantic analysis...') #Latent Semantic Analysis #Actions n_components = 12 vectorizer = CountVectorizer(min_df=1) action_vec = vectorizer.fit_transform(actions) action_lsa = TruncatedSVD(n_components,algorithm='arpack') action_lsa_features = action_lsa.fit_transform(action_vec) action_lsa_features = Normalizer(copy=False).fit_transform(action_lsa_features) a_lsa_cols = ['action_lsa_'+str(i) for i in range(n_components)] action_lsa_df = pd.DataFrame(action_lsa_features,columns=a_lsa_cols) a_lsa = pd.concat((sessions_reduce['user_id'], action_lsa_df), axis=1) #Action Types n_components = 6 vectorizer = CountVectorizer(min_df=1) action_type_vec = vectorizer.fit_transform(action_types) action_type_lsa = TruncatedSVD(n_components,algorithm='arpack') action_type_lsa_features = action_type_lsa.fit_transform(action_type_vec) action_type_lsa_features = Normalizer(copy=False).fit_transform(action_type_lsa_features) at_lsa_cols = ['action_type_lsa_'+str(i) for i in range(n_components)] action_type_lsa_df = pd.DataFrame(action_type_lsa_features,columns=at_lsa_cols) at_lsa = pd.concat((sessions_action_types_reduce['user_id'], action_type_lsa_df), axis=1) lsa_df = a_lsa.merge(at_lsa,on='user_id') #Combine LSA Data with Train and Test train = pd.merge(train, lsa_df, how='left', left_on='id', right_on='user_id') test = pd.merge(test, lsa_df, how='left', left_on='id', right_on='user_id') train.fillna(-1,inplace=True) test.fillna(-1,inplace=True) features.extend(a_lsa_cols) features.extend(at_lsa_cols) grpby = sessions.groupby(['user_id'])['secs_elapsed'].sum().reset_index() grpby.columns = ['user_id','secs_elapsed'] action_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['action_type'],values = 'action',aggfunc=len,fill_value=0).reset_index() action_type = action_type.drop(['booking_response'],axis=1) device_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['device_type'],values = 'action',aggfunc=len,fill_value=0).reset_index() device_type = device_type.drop(['Blackberry','Opera Phone','iPodtouch','Windows Phone'],axis=1) sessions_data = pd.merge(action_type,device_type,on='user_id',how='inner') sessions_transform = pd.merge(sessions_data,grpby,on='user_id',how='inner') train = pd.merge(train,sessions_transform, how='left', left_on='id',right_on='user_id') test = pd.merge(test, sessions_transform, how='left', left_on='id', right_on='user_id') sessions_transform = sessions_transform.drop(['user_id','secs_elapsed'],axis=1) train.fillna(-1,inplace=True) test.fillna(-1,inplace=True) features.extend(['id']) #Sessions Data PCA print ('sessioins data ....') sessions = sessions[sessions.user_id.notnull()] sessions = sessions.fillna(0) sessions_data = sessions.groupby(['user_id'])['secs_elapsed'].sum().reset_index() sessions_data.columns = ['user_id','secs_elapsed_per_user'] # total_secs_elapsed per ... print "total_secs_elapsed per ..." action = pd.pivot_table(sessions, index = ['user_id'],columns = ['action'], values = 'secs_elapsed',aggfunc=sum,fill_value=0).reset_index() action.rename(columns=lambda x: "total_secs_elapsed_per_user_per_action_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, action, on='user_id', how='inner') action_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['action_type'], values = 'secs_elapsed',aggfunc=sum,fill_value=0).reset_index() action_type.rename(columns=lambda x: "total_secs_elapsed_per_user_per_action_type_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, action_type, on='user_id', how='inner') device_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['device_type'], values = 'secs_elapsed',aggfunc=sum,fill_value=0).reset_index() device_type.rename(columns=lambda x: "total_secs_elapsed_per_user_per_device_type_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, device_type, on='user_id', how='inner') # total ... number per user print "total ... number per user" action = pd.pivot_table(sessions, index = ['user_id'],columns = ['action'], values = 'secs_elapsed',aggfunc=len,fill_value=0).reset_index() action.rename(columns=lambda x: "total_action_number_per_user_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, action, on='user_id', how='inner') action_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['action_type'], values = 'action',aggfunc=len,fill_value=0).reset_index() action_type.rename(columns=lambda x: "total_action_type_number_per_user_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, action_type, on='user_id', how='inner') device_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['device_type'], values = 'action',aggfunc=len,fill_value=0).reset_index() device_type.rename(columns=lambda x: "total_device_type_number_per_user_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, device_type, on='user_id', how='inner') # mean_secs_elapsed per ... print "mean_secs_elapsed per ..." action = pd.pivot_table(sessions, index = ['user_id'],columns = ['action'], values = 'secs_elapsed',aggfunc=np.mean,fill_value=0).reset_index() action.rename(columns=lambda x: "mean_secs_elapsed_per_user_per_action_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, action, on='user_id', how='inner') action_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['action_type'], values = 'secs_elapsed',aggfunc=np.mean,fill_value=0).reset_index() action_type.rename(columns=lambda x: "mean_secs_elapsed_per_user_per_action_type_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, action_type, on='user_id', how='inner') device_type = pd.pivot_table(sessions, index = ['user_id'],columns = ['device_type'], values = 'secs_elapsed',aggfunc=np.mean,fill_value=0).reset_index() device_type.rename(columns=lambda x: "mean_secs_elapsed_per_user_per_device_type_" + str(x) if x != "user_id" else str(x), inplace=True) sessions_data = pd.merge(sessions_data, device_type, on='user_id', how='inner') train = pd.merge(train,sessions_data, how='left', left_on='id',right_on='user_id') test = pd.merge(test, sessions_data, how='left', left_on='id', right_on='user_id') sessions_data.drop('user_id',axis=1,inplace=True) features.extend(sessions_data.columns.values) train.fillna(-1,inplace=True) test.fillna(-1,inplace=True) print ('NMF feature ...') #NMF session_df = sessions.groupby(['user_id','action'])['secs_elapsed'].sum().reset_index() lex = LabelEncoder() ley = LabelEncoder() session_df.fillna(0,inplace=True) session_df['user_id'] = lex.fit_transform(session_df['user_id']) session_df['action'] = ley.fit_transform(session_df['action']) row = session_df['user_id'] col = session_df['action'] secs = session_df['secs_elapsed'] n = max(session_df['user_id']) + 1 m = max(session_df['action']) + 1 sparse_matrix = csr_matrix((secs,(row,col)),shape=(n,m)) n_components = 15 nmf = NMF(n_components=n_components,max_iter=200,random_state=130) W = nmf.fit_transform(sparse_matrix) user_features = pd.DataFrame(W, columns=['nmf_'+str(i) for i in range(n_components)]) user_features['user_id'] = lex.inverse_transform(range(n)) train = pd.merge(train,user_features,how='left',left_on='id',right_on='user_id') test = pd.merge(test,user_features,how='left',left_on='id',right_on='user_id') user_features = user_features.drop('user_id',axis=1) train.fillna(0,inplace=True) test.fillna(0,inplace=True) features.extend(sessions_transform.columns.values) features.extend(user_features.columns.values) #Save Train and Test Data test = test[features] train = train[features+['country_destination']] train = train.drop(['id'],axis=1) #Counties Encoder le = LabelEncoder() train['country'] = le.fit_transform(train['country_destination']) print('training data processed') def customized_eval(preds, dtrain): labels = dtrain.get_label() top = [] for i in range(preds.shape[0]): top.append(np.argsort(preds[i])[::-1][:5]) mat = np.reshape(np.repeat(labels,np.shape(top)[1]) == np.array(top).ravel(),np.array(top).shape).astype(int) score = np.mean(np.sum(mat/np.log2(np.arange(2, mat.shape[1] + 2)),axis = 1)) return 'ndcg5', score ########################################################################### # XGBoost # ########################################################################### print('XGboost Training') print len(train.columns.values) params = {"objective": "multi:softprob", "eta": 0.01, "gamma":0, "min_child_wegiht":1, "max_delta_step":0, "lambda":1, "alpha":0, "max_depth": 7, "subsample": 0.9, "colsample_bytree": 0.6, "silent": 1, "seed": 0, "num_class": 12 } num_boost_round = 2000 rs = StratifiedKFold(train["country"],n_folds=5,shuffle=True,random_state=0) y_pred = np.zeros((test.shape[0],12),dtype=float) for train_index, test_index in rs: X_train = train.loc[train_index] X_valid = train.loc[test_index] y_train = X_train.country y_valid = X_valid.country X_train = X_train.drop(["country","country_destination"],axis=1) X_valid = X_valid.drop(["country","country_destination"],axis=1) dtrain = xgb.DMatrix(X_train, y_train) dvalid = xgb.DMatrix(X_valid, y_valid) dtest = xgb.DMatrix(test[X_train.columns.values]) watchlist = [(dtrain, 'train'), (dvalid, 'eval')] gbm = xgb.train(params, dtrain, num_boost_round, evals=watchlist, feval=customized_eval, maximize=True,early_stopping_rounds=100, verbose_eval=True) #gbm = xgb.train(params, dtrain, num_boost_round, evals=watchlist,early_stopping_rounds=100, verbose_eval=True) print ("Making Prediction on Test Data of XGBoost") #Make Prediction on Test Data y_pred += gbm.predict(dtest,ntree_limit=gbm.best_iteration).reshape(test.shape[0],12) #Taking the 5 classes with highest probabilities user_id = [] countries = [] test_ids = test['id'] for i in range(len(test_ids)): idx = test_ids[i] user_id += [idx] * 5 countries += le.inverse_transform(np.argsort(y_pred[i])[::-1])[:5].tolist() result = pd.DataFrame(np.column_stack((user_id, countries)),columns=['id','country']) result.to_csv("combine_submission_0.csv", index=False)
ea9a8b9ef04104cff795321e060042c1f8f0e7b4
[ "Python" ]
1
Python
happyphonon/Airbnb
795c189677342aee9926db741056085c76d6d657
5b2e25437d2996d9f87c2433e0a9d4566e1901ee
refs/heads/master
<file_sep>package com.qspl.quagnitia.listview; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class ListViewDemo extends AppCompatActivity { ListView lvList; Context context=this; String cities[]={"Nashik","Mumbai","Pune","Ahemednagar","Aurangabad","Satara","Kolhapur","Dhule","Nandurbar","Sangali","Shirdi","Jalgaon","Nandgaon","Malegaon","Bhusaval","Akola","Nanded","Katraj"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view_demo); lvList=findViewById(R.id.lvList); ArrayAdapter<String> myArray=new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,cities); lvList.setAdapter(myArray); } }
3d67251821219d2176615e30db547c2d46f659c0
[ "Java" ]
1
Java
patilrahul9923/ListView
f02043b576637b746ab47882bcc820af30a45d25
954f701197496b41cf1a14e406633238daf6447b
refs/heads/master
<repo_name>maicol07/flarum-sso-plugin<file_sep>/.github/ISSUE_TEMPLATE/important--how-to-submit-an-issue.md --- name: 'IMPORTANT: HOW TO SUBMIT AN ISSUE' about: Please read this to know how to submit an issue title: "[INVALID] " labels: invalid assignees: '' --- In order to organize better the developer work, issues should be created in the developer bug tracker. Here is the link: https://tracker.maicol07.it Please, create an issue there and not here on Github. This is the only way to get sure your request will be remembered and solved! Every issue created here on Github will be marked as invalid, as you should use the official bug tracker!! <file_sep>/src/Flarum.php <?php /** @noinspection PhpPrivateFieldCanBeLocalVariableInspection @noinspection PhpUndefinedMethodInspection */ namespace Maicol07\SSO; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Maicol07\Flarum\Api\Client; use Maicol07\Flarum\Api\Resource\Item; use Maicol07\SSO\Traits\Addons; use Maicol07\SSO\Traits\Cookies; /** * Flarum SSO * * @author maicol07 * @package Maicol07\SSO */ class Flarum { use Cookies, Addons; /* @var Client Api client */ public $api; /* @var bool Should the login be remembered (this equals to 5 years remember from last usage)? If false, token will be remembered only for 1 hour */ private $remember; /* @var string Random token to create passwords */ public $password_token; /* @var string Main site or SSO system domain */ public $root_domain; /* @var string Flarum URL */ public $url; /** @var bool Verify SSL cert. More details on https://docs.guzzlephp.org/en/stable/request-options.html#verify */ public $verify; /** @var User|null */ private $user; /** * Flarum constructor * * @param array $config { * @type string $url Flarum URL * @type string $root_domain Main site or SSO system domain * @type string $api_key Random key from the api_keys table of your Flarum forum * @type string $password_token <PASSWORD> create passwords * @type bool $remember Should the login be remembered (this equals to 5 years remember from last usage)? If false, token will be remembered only for 1 hour. Default: false * @type bool|string $verify_ssl Verify SSL cert. More details on https://docs.guzzlephp.org/en/stable/request-options.html#verify. Default: true * } */ public function __construct(array $config) { // Urls $this->url = Arr::get($config, 'url'); // Fix URL scheme if (empty(Arr::get(parse_url($this->url), 'scheme'))) { $this->url = 'https://' . $this->url; } $this->root_domain = Arr::get($config, 'root_domain'); $url = parse_url($this->root_domain); if (!empty(Arr::get($url, 'host'))) { $this->root_domain = Arr::get($url, 'host'); } $this->password_token = Arr::get($config, 'password_token'); $this->verify = Arr::get($config, 'verify_ssl', true); $this->api = new Client($this->url, ['token' => Arr::get($config, 'api_key')], [ 'verify' => $this->verify ]); $this->remember = Arr::get($config, 'remember', false); $this->initAddons(); } /** * Logs out the current user from Flarum. Generally, you should use this method when an user successfully logged out from * your SSO system (or main website) * * @return bool */ public function logout(): bool { $this->action_hook('before_logout'); $deleted = $this->deleteSessionTokenCookie() and $this->deleteRememberTokenCookie(); $created = $this->setLogoutCookie(); $this->hooks->do_action('after_logout', $deleted, $created); return ($deleted and $created); } public function user(string $username = null): User { if ($this->user === null) { $this->user = new User($username, $this); } return $this->user; } /** * Gets a collection of the users actually signed up on Flarum, with all the properties * * @param null|string|array $filters Include in the returned collection only the values from filter(s) * Can be one or more of the following: type, id, attributes, attributes.username, attributes.displayName, * attributes.avatarUrl, attributes.joinTime, attributes.discussionCount, attributes.commentCount, * attributes.canEdit, attributes.canDelete, attributes.lastSeenAt, attributes.isEmailConfirmed, attributes.email, * attributes.markedAllAsReadAt, attributes.unreadNotificationCount, attributes.newNotificationCount, * attributes.preferences, attributes.canSuspend, attributes.bio, attributes.newFlagCount, * attributes.canViewRankingPage, attributes.Points, attributes.canPermanentNicknameChange, attributes.canEditPolls, * attributes.canStartPolls, attributes.canSelfEditPolls, attributes.canVotePolls, attributes.cover, * attributes.cover_thumbnail, relationships, relationships.groups * * There could be more if you have other extensions that adds them to Flarum API * * @return Collection * * @noinspection MissingParameterTypeDeclarationInspection */ public function getUsersList($filters = null): Collection { $offset = 0; $collection = collect(); while ($offset !== null) { $response = $this->api->users()->offset($offset)->request(); if ($response instanceof Item and empty($response->type)) { $offset = null; continue; } $collection = $collection->merge($response->collect()->all()); $offset = array_key_last($collection->all()) + 1; } // Filters $filtered = collect(); if (!empty($filters)) { $grouped = true; if (is_string($filters)) { $filters = [$filters]; $grouped = false; } foreach ($filters as $filter) { $plucked = $collection->pluck($filter); if (!empty($grouped)) { $plucked = [$filter => $plucked]; } $filtered = $filtered->mergeRecursive($plucked); } $collection = $filtered; } return $collection; } /** * Returns the value of $remember (indicates if login should be remembered) * * @return bool|void * * @see $remember * * @noinspection MissingReturnTypeInspection */ public function isSessionRemembered(bool $remember = null) { if ($remember !== null) { $this->remember = $remember; return; } return $this->remember; } /** * Redirects the user to your Flarum instance */ public function redirect(): void { header('Location: ' . $this->url); die(); } } <file_sep>/src/User/Relationships.php <?php namespace Maicol07\SSO\User; use Maicol07\SSO\Flarum; /** * Class Relationships * @package Maicol07\SSO\User */ class Relationships { /** @var array */ public $groups = []; public function toArray(Flarum $flarum): array { $groups = []; $flarum_groups = $flarum->api->groups()->request(); foreach ($flarum_groups as $group) { if (in_array($group->attributes['nameSingular'], $this->groups, true)) { $groups[] = [ 'type' => 'groups', 'id' => $group->id ]; } } return [ 'groups' => [ 'data' => $groups ] ]; } } <file_sep>/example/flarum.php <?php // Create the Flarum object with the required configuration. The parameters are explained in the class file (src/Flarum.php) use Maicol07\SSO\Flarum; $flarum = new Flarum([ 'url' => env('FLARUM_HOST', 'https://discuss.flarum.org'), 'root_domain' => env('ROOT_DOMAIN', 'flarum.org'), 'api_key' => env('API_KEY', 'NotSecureToken'), 'password_token' => env('<PASSWORD>_TOKEN', '<PASSWORD>'), 'remember' => $_POST['remember'] ?? false, 'verify_ssl' => env('VERIFY_SSL', true), 'set_groups_admins' => env('SET_GROUPS_ADMINS', true) ]); <file_sep>/example/delete.php <?php /** @noinspection DuplicatedCode */ use Dotenv\Dotenv; // Note: Since this is called from the example folder, the vendor folder is located in the previous tree level require_once __DIR__ . '/../vendor/autoload.php'; // Load .env $env = Dotenv::createImmutable(__DIR__); $env->load(); require_once __DIR__ . '/flarum.php'; /** @var $flarum <-- Fix PHPStorm hints */ // Delete the user $success = $flarum->user($_GET['username'])->delete(); if (!empty($_GET['redirect'])) { $flarum->redirect(); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Delete user</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Lightweight CSS only to make this page beautiful --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" integrity="<KEY> crossorigin="anonymous"> </head> <body class="container"> <div class="box" style="margin-top: 25px;"> <h1 class="title">Delete user</h1> <?php if (isset($flarum) and !empty($success)) { ?> <div class="notification is-success"> <button class="delete"></button> <?php echo "Successfully deleted {$_GET['username']}"; ?><br> </div> <?php } elseif (isset($flarum) and empty($success)) { ?> <div class="notification is-danger"> <button class="delete"></button> <?php echo "Something went wrong while deleting {$_GET['username']} :("; ?><br><br> Check if one of this common error cases has occurred: <ul> <li>Username has not been typed correctly</li> <li>User does not exists in Flarum</li> </ul> </div> <?php } ?> <details> <summary>Users list</summary> <ul> <li><?php echo implode('</li><li>', $flarum->getUsersList('attributes.username')->all()); ?></li> </ul> </details> </div> <?php require_once 'footer.php' ?> </body> </html> <file_sep>/src/Addons/Groups.php <?php namespace Maicol07\SSO\Addons; use Illuminate\Support\Arr; /** * Class Groups * @package Maicol07\SSO\Addons */ class Groups extends Core { protected $actions = [ 'after_login' => 'setGroups', 'after_update' => 'setGroups' ]; /** * Sets groups to a user * */ public function setGroups(): void { $user = $this->flarum->user(); if (!empty($user->id)) { $groups = []; /** Search flarum groups - @noinspection NullPointerExceptionInspection */ $flarum_groups = Arr::pluck( $this->flarum->api->groups()->request()->collect()->all(), 'attributes.nameSingular', 'id' ); foreach ($user->relationships->groups as $group) { if (empty($group) or !is_string($group)) { continue; } // Find ID of the group $id = array_key_first(Arr::where($flarum_groups, function ($name) use ($group) { return $name === $group; })); // If it doesn't exists, create it if (empty($id)) { $id = $this->createGroup($group); } $groups[] = [ 'type' => 'groups', 'id' => $id ]; } $this->flarum->api->users($user->id)->patch([ 'relationships' => [ 'groups' => [ 'data' => $groups ], ], ])->request(); } } /** * Add a group to Flarum * * @param string $group * * @return mixed * * @noinspection MissingReturnTypeInspection */ public function createGroup(string $group) { $response = $this->flarum->api->groups()->post([ 'type' => 'groups', 'attributes' => [ 'namePlural' => $group, 'nameSingular' => $group ] ])->request(); return $response->id; } } <file_sep>/src/User/Attributes.php <?php namespace Maicol07\SSO\User; /** * Class Attributes * @package Maicol07\SSO\User */ class Attributes { /** @var string */ public $username; /** @var string */ public $email; /** @var string|null */ public $password; /** * WARNING! This is read only! Overwriting this when updating the user won't do anything! * To change the display name use the $nickname variable (beta16+. Nickname extension required). * * @var string * @see $nickname */ public $displayName; /** * WARNING! This is write only! To read this attribute use the $displayName property. * To change the nickname you must have the nickname extension installed on your Flarum. * * @var string */ public $nickname; /** @var string */ public $avatarUrl; /** @var string */ public $joinTime; /** @var int */ public $discussionCount; /** @var int */ public $commentCount; /** @var bool */ public $canEdit; /** @var bool */ public $canDelete; /** @var bool */ public $canSuspend; /** @var string */ public $bio; /** @var bool */ public $canViewBio; /** @var bool */ public $canEditBio; /** @var bool */ public $canSpamblock; /** @var bool */ public $blocksPd; /** @var bool */ public $cannotBeDirectMessaged; /** @var bool */ public $isBanned; /** @var bool */ public $canBandIP; /** @var array */ public $usernameHistory; /** @var bool */ public $canViewWarnings; /** @var bool */ public $canManageWarnings; /** @var bool */ public $canDeleteWarnings; /** @var int */ public $visibleWarningCount; public function toArray(): array { return get_object_vars($this); } } <file_sep>/example/.env.example FLARUM_HOST= API_KEY= ROOT_DOMAIN=<file_sep>/src/User.php <?php namespace Maicol07\SSO; use GuzzleHttp\Exception\ClientException; use Maicol07\SSO\User\Attributes; use Maicol07\SSO\User\Relationships; use Maicol07\SSO\User\Traits\Auth; /** * Class User * * @package Maicol07\SSO */ class User { use Auth; /** @var null|int */ public $id; /** @var string */ public $type = 'users'; /** @var Attributes */ public $attributes; /** @var Relationships */ public $relationships; /** @var bool */ public $isAdmin = false; /** @var Flarum */ private $flarum; public function __construct(?string $username, Flarum $flarum) { $this->flarum = $flarum; $this->id = null; $this->attributes = new Attributes(); $this->relationships = new Relationships(); $this->attributes->username = $username; $this->flarum->filter_hook('before_user_init', $this); if (!empty($username)) { $this->fetch(); } $this->flarum->filter_hook('after_user_init', $this); } /** * Updates a user. If user id is not set, user will be fetched. Warning! User needs to be found with username or email, so one of those two has to be the old one */ public function update(): bool { if (empty($this->id)) { $fetched = $this->fetch(); if (!$fetched) { return false; } } $this->flarum->action_hook('before_update'); $response = $this->flarum->api->users($this->id)->patch([ 'attributes' => $this->getAttributes() ])->request(); $this->flarum->action_hook('after_update', $response); return ($response->id === $this->id); } /** * Deletes a user from Flarum database. Generally, you should use this method when an user successfully deleted * his account from your SSO system (or main website) * * @return bool */ public function delete(): bool { $this->flarum->action_hook('before_delete'); // Logout the user $this->flarum->logout(); if (empty($this->id)) { return false; } try { $result = $this->flarum->api->users($this->id)->delete()->request(); } catch (ClientException $e) { if ($e->getCode() === 404 and $e->getResponse()->getReasonPhrase() === "Not Found") { $result = false; } else { throw $e; } } $this->flarum->action_hook('after_delete'); return $result; } /** * Fetch user data from Flarum * * @return bool Returns true if successful, false or exception (other than Not Found) otherwise */ public function fetch(): bool { try { $user = $this->flarum->api->users($this->attributes->username)->request(); } catch (ClientException $e) { if ($e->getCode() === 404 and $e->getResponse()->getReasonPhrase() === "Not Found") { // User doesn't exists in Flarum $this->id = null; return false; } throw $e; } $this->id = $user->id; // Set attributes foreach ($user->attributes as $attribute => $value) { $this->attributes->$attribute = $value; } // Admin? if (array_key_exists(1, $user->relationships['groups'])) { $this->isAdmin = true; } // Set groups foreach ($user->relationships['groups'] as $group) { $this->relationships->groups[] = $group->attributes['nameSingular']; } return true; } public function getAttributes(): array { return $this->attributes->toArray(); } public function getRelationships(): array { return $this->relationships->toArray($this->flarum); } } <file_sep>/example/logout.php <?php /** @noinspection DuplicatedCode */ use Dotenv\Dotenv; // Note: Since this is called from the example folder, the vendor folder is located in the previous tree level require_once __DIR__ . '/../vendor/autoload.php'; // Load .env $env = Dotenv::createImmutable(__DIR__); $env->load(); require_once __DIR__ . '/flarum.php'; /** @var $flarum <-- Fix PHPStorm hints */ // Logout current user $success = $flarum->logout(); if (!empty($_GET['redirect'])) { $flarum->redirect(); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Logout user</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Lightweight CSS only to make this page beautiful --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" integrity="<KEY> crossorigin="anonymous"> </head> <body class="container"> <div class="box" style="margin-top: 25px;"> <h1 class="title">Logout user</h1> <?php if (isset($flarum) and !empty($success)) { ?> <div class="notification is-success"> <button class="delete"></button> Successfully logged out </div> <?php } elseif (isset($flarum) and empty($success)) { ?> <div class="notification is-danger"> <button class="delete"></button> Something went wrong while logging you out of Flarum :( </div> <?php } ?> </div> <?php require_once 'footer.php' ?> </body> </html><file_sep>/documentation/doctum.config.php <?php use Doctum\Doctum; use Doctum\RemoteRepository\GitHubRemoteRepository; use Symfony\Component\Finder\Finder; $dir = 'src'; $iterator = Finder::create() ->files() ->name('*.php') ->in($dir); return new Doctum($iterator, [ 'title' => 'Flarum SSO PHP Plugin API Docs', 'theme' => 'flarum', 'source_dir' => dirname($dir) . '/', 'build_dir' => 'docs', 'template_dirs' => [__DIR__ . '/themes/flarum'], 'remote_repository' => new GitHubRemoteRepository('maicol07/flarum-sso-php-plugin', dirname($dir)), 'source_url' => 'https://github.com/maicol07/flarum-sso-php-plugin' ]); <file_sep>/README.md # Flarum SSO Extension - PHP plugin [![Latest Stable Version](https://poser.pugx.org/maicol07/flarum-ext-sso/v)](//packagist.org/packages/maicol07/flarum-ext-sso) [![Total Downloads](https://poser.pugx.org/maicol07/flarum-ext-sso/downloads)](//packagist.org/packages/maicol07/flarum-ext-sso) [![Latest Unstable Version](https://poser.pugx.org/maicol07/flarum-ext-sso/v/unstable)](//packagist.org/packages/maicol07/flarum-ext-sso) [![License](https://poser.pugx.org/maicol07/flarum-ext-sso/license)](//packagist.org/packages/maicol07/flarum-ext-sso) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/dwyl/esta/issues) [![HitCount](http://hits.dwyl.com/maicol07/flarum_sso_php_plugin.svg)](http://hits.dwyl.com/maicol07/flarum_sso_php_plugin) Plugin for your PHP website to get the [Flarum SSO extension](https://github.com/maicol07/flarum-ext-sso) working ## Documentation Check the [docs](https://docs.maicol07.it/en/flarum-sso/plugins/php) to know more about the plugin, how to install it and to use it. <file_sep>/src/User/Traits/Auth.php <?php namespace Maicol07\SSO\User\Traits; use GuzzleHttp\Exception\ClientException; use RuntimeException; /** * Trait Auth * @package Maicol07\SSO\Traits */ trait Auth { /** * Logs the user in Flarum. Generally, you should use this method when an user successfully log into * your SSO system (or main website). * * @return bool */ public function login(): bool { $r = $this->flarum->filter_hook('replace_login', null); if ($r !== -1) { return $r; } $this->flarum->action_hook('before_login'); if (empty($this->attributes->password)) { throw new RuntimeException("User's password not set"); } $token = $this->getToken(); $this->flarum->action_hook('after_token_obtained', $token); // If no token has been returned... if (empty($token)) { // ...try to search the user... try { $this->flarum->api->users($this->attributes->username)->request(); // Backward compatibility (create password based on username) $this->attributes->password = $<PASSWORD>(); $token = $this->getToken(); if (empty($token)) { return false; } } catch (ClientException $e) { // ...otherwise signup it if ($e->getCode() === 404 and $e->getResponse()->getReasonPhrase() === "Not Found") { $signed_up = $this->signup(); if (!$signed_up) { return false; } $this->flarum->action_hook('after_signup'); $token = $this->getToken(); } else { throw $e; } } } $this->flarum->action_hook('after_login', $token); $deleted = $this->flarum->deleteLogoutCookie(); $created = $this->flarum->isSessionRemembered() ? $this->flarum->setRememberTokenCookie($token) : $this->flarum->setSessionTokenCookie($token); return ($deleted and $created); } /** * Sign up user in Flarum. Generally, you should use this method when an user successfully log into * your SSO system (or main website) and you found out that user don't have a token (because he hasn't an account on Flarum) * * @return bool */ public function signup(): bool { $r = $this->flarum->filter_hook('replace_signup', null); if ($r !== -1) { return $r; } $this->flarum->action_hook('before_signup'); $data = [ "type" => "users", "attributes" => $this->getAttributes() ]; try { $user = $this->flarum->api->users()->post($data)->request(); $this->flarum->action_hook('after_signup'); return isset($user->id); } catch (ClientException $e) { if ($e->getResponse()->getReasonPhrase() === "Unprocessable Entity") { return false; } throw $e; } } /** * Generates a password based on username and password token * * @return string */ private function createPassword(): string { return hash('sha256', $this->attributes->username . $this->flarum->password_token); } /** * Get user token from Flarum (if user exists) * * @return string */ private function getToken(): ?string { $data = [ 'identification' => $this->attributes->username, 'password' => $this->attributes->password, 'remember' => $this->flarum->isSessionRemembered(), ]; try { $response = $this->flarum->api->token()->post($data)->request(); return $response->token ?? ''; } catch (ClientException $e) { if ($e->getResponse()->getReasonPhrase() === "Unauthorized") { return null; } throw $e; } } } <file_sep>/src/Traits/Addons.php <?php namespace Maicol07\SSO\Traits; use Hooks\Hooks; trait Addons { /** @var Hooks|null */ private $hooks; /** @var array List of loaded addons */ private $addons = []; /** * Load an addon to the plugin * * @param string $addon Class name to add as addon * @return int */ public function loadAddon(string $addon): int { $this->addons[] = new $addon($this->hooks, $this); return array_key_last($this->addons); } /** * Unloads an addon from the plugin * * @param string $addon Addon class name to remove * @return $this */ public function unloadAddon(string $addon): self { $key = array_search($addon, $this->addons, true); $hook = $this->addons[$key]; $hook->unload(); unset($hook); return $this; } /** * Set addon properties * * @param string $addon * @param array $attributes * @return $this */ public function setAddonProperties(string $addon, array $attributes): self { $hook = $this->addons[array_search($addon, $this->addons, true)]; foreach ($attributes as $key => $value) { $hook->$key = $value; } return $this; } /** * Check if addon is loaded * * @param string $addon * @return bool */ public function isAddonLoaded(string $addon): bool { return in_array($addon, $this->addons, true); } /** * A simple proxy to Hook do_action function * * @param string $tag * @return int|null */ public function action_hook(string $tag): ?int { $args = func_get_args(); array_shift($args); if (!$this->hooks->has_action($tag)) { return -1; } $this->hooks->do_action($tag, $args); return null; } /** * A simple proxy to Hook apply_filters function * * @param string $tag * @param $value * * @return mixed * * @noinspection MissingReturnTypeInspection * @noinspection MissingParameterTypeDeclarationInspection */ public function filter_hook(string $tag, $value) { if (!$this->hooks->has_filter($tag)) { return -1; } return $this->hooks->apply_filters($tag, $value); } /** * Inits addons */ private function initAddons(): void { $this->hooks = new Hooks(); foreach ($this->addons as $key => $addon) { unset($this->addons[$key]); $this->addons[$key] = new $addon($this->hooks, $this); } } } <file_sep>/src/Exceptions/MissingRequiredAddonException.php <?php namespace Maicol07\SSO\Exceptions; use RuntimeException; class MissingRequiredAddonException extends RuntimeException { } <file_sep>/example/update.php <?php /** @noinspection ForgottenDebugOutputInspection */ use Dotenv\Dotenv; use Illuminate\Support\Arr; use Maicol07\SSO\Addons\Groups; // Note: Since this is called from the example folder, the vendor folder is located in the previous tree level require_once __DIR__ . '/../vendor/autoload.php'; // Load .env $env = Dotenv::createImmutable(__DIR__); $env->load(); if (Arr::exists($_POST, 'username')) { require_once __DIR__ . '/flarum.php'; /** @var $flarum <-- Fix PHPStorm hints */ // Create the user to work with $flarum_user = $flarum->user(Arr::get($_POST, 'username')); // Check if user exists in flarum if (!empty($flarum_user->id)) { // Set his attributes (from form) $flarum_user->attributes->nickname = Arr::get($_POST, 'nickname'); $flarum_user->attributes->avatarUrl = Arr::get($_POST, 'avatar'); $flarum_user->attributes->bio = Arr::get($_POST, 'bio'); // Let's add to it some groups (optional, only for demonstration) // First, let's add the Groups addon (note that the Groups class is imported at the top with the use statement) $flarum->loadAddon(Groups::class); $flarum->setAddonProperties(Groups::class, ['set_groups_admins' => env('SET_GROUPS_ADMINS') ?? true]); // Then, add the groups (as an array) to the correct attribute in user relationships $flarum_user->relationships->groups = ['Premium', 'Novice']; // Update the user $success = $flarum_user->update(); // Redirect to Flarum if (!empty($_GET['redirect'])) { $flarum->redirect(); } } else { $success = false; } } elseif (!empty($username) || !empty($password)) { $success = false; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Update user</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Lightweight CSS only to make this page beauty --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" integrity="<KEY> crossorigin="anonymous"> </head> <body> <div class="container"> <div class="box" style="margin-top: 25px;"> <h1 class="title">Update user</h1> <form method="post"> <p class="mb-3">Note: This is only a test, so the infos you can edit here are limited!</p> <div class="columns"> <div class="column"> <label class="label" for="username">Username (doesn't change)</label> <input id="username" type="text" class="input" name="username" placeholder="Username"> <label class="label" for="nickname">Nickname</label> <input id="nickname" type="text" class="input" name="nickname" placeholder="Nickname"> </div> <div class="column"> <label class="label mt-3" for="avatar">Avatar URL</label> <input id="avatar" type="url" class="input" name="avatar" placeholder="Avatar URL"> <label class="label mt-3" for="bio">Bio</label> <textarea id="bio" name="bio" class="textarea" placeholder="Update user bio"></textarea> </div> </div> <button class="button is-centered is-center" type="submit" style="display: block; margin: 0 auto;">Update </button> </form> <?php if (isset($flarum) and !empty($success)) { ?> <div class="notification is-success"> <button class="delete"></button> Successfully updated! Click the button below to go to Flarum user! <br> <a class="button is-rounded mt-5" href="<?php echo $flarum->url . (isset($_POST['username']) ? "/u/{$_POST['username']}" : '') ?>" style="display: block; margin: 0 auto; width: max-content;"> Go to user in Flarum </a> <details> <summary>User details</summary> <pre style="margin: 16px 0;"> <?php if (isset($flarum_user) and $flarum_user->fetch()) { $is_admin = $flarum_user->isAdmin ? 'Yes' : 'No'; echo "User ID: $flarum_user->id<br>Is user admin? <b>$is_admin</b><br>User attributes: <br>"; var_export($flarum_user->getAttributes()); echo "<br>User relationships: <br>"; var_export($flarum_user->getRelationships()); } else { echo "Can't fetch user from Flarum!"; } ?> </pre> </details> </div> <?php } elseif (isset($success) and empty($success)) { ?> <div class="notification is-danger"> <button class="delete"></button> Update failed </div> <?php } ?> </div> </div> <?php require_once 'footer.php' ?> </body> </html> <file_sep>/src/Traits/Cookies.php <?php namespace Maicol07\SSO\Traits; use Delight\Cookie\Cookie; use Illuminate\Support\Carbon; trait Cookies { public function setRememberTokenCookie(string $token): bool { return $this->generateCookie('remember', $token, Carbon::now()->addYears(5))->saveAndSet(); } /** * Generate a cookie * * @param string $name * @param string|null $value * @param Carbon|null $expiry * * @return Cookie * * @noinspection CallableParameterUseCaseInTypeContextInspection */ public function generateCookie(string $name, string $value = null, Carbon $expiry = null): Cookie { if ($expiry === null) { $expiry = Carbon::now(); } return (new Cookie("flarum_$name")) ->setDomain($this->root_domain) ->setSecureOnly($this->verify) ->setValue($value) ->setExpiryTime($expiry->getTimestamp()); } public function deleteRememberTokenCookie(): bool { return $this->generateCookie('remember')->deleteAndUnset(); } public function setSessionTokenCookie(string $token): bool { return $this->generateCookie('token', $token, Carbon::now()->addHour())->saveAndSet(); } public function deleteSessionTokenCookie(): bool { return $this->generateCookie('token')->deleteAndUnset(); } public function setLogoutCookie(): bool { return $this->generateCookie('logout', 'flarum_logout', Carbon::now()->addYears(5)) ->saveAndSet(); } public function deleteLogoutCookie(): bool { return $this->generateCookie('logout')->deleteAndUnset(); } } <file_sep>/src/Addons/Core.php <?php namespace Maicol07\SSO\Addons; use Hooks\Hooks; use Maicol07\SSO\Exceptions\MissingRequiredAddonException; use Maicol07\SSO\Flarum; /** * Class Core * @package Maicol07\SSO\Addons */ class Core { /** @var Hooks */ protected $hooks; /** @var array Actions list */ protected $actions = []; /** @var array Filters list */ protected $filters = []; /** @var array Required addons that needs to be loaded before this one */ protected $required = []; /** @var Flarum */ protected $flarum; public function __construct(Hooks $hooks, Flarum $flarum) { $this->flarum = $flarum; $this->hooks = $hooks; $this->load(); } /** * Load Addons hooks. If the addons require other addons loaded before it, then it will raise an exception * * @return $this */ public function load(): Core { // Check required addons $required = []; foreach ($this->required as $addon) { if (!$this->flarum->isAddonLoaded($addon)) { $required[] = $addon; } } if (!empty($required)) { throw new MissingRequiredAddonException('Following required addons not loaded: ' . implode(', ', $required) . '. You need to load it/them to use this addon'); } $this->manageHooks('add'); return $this; } /** * Manages hooks addition/removal * * @param string $op Must be 'add' or 'remove' */ private function manageHooks(string $op): void { foreach (array_merge($this->actions, $this->filters) as $name => $method) { $type = in_array($method, $this->actions, true) ? 'action' : 'filter'; $methods = is_array($method) ? $method : [$method]; foreach ($methods as $m) { $this->hooks->{"{$op}_$type"}($name, [$this, $m]); } } } /** * Unload Addons hooks * * @return $this */ public function unload(): Core { $this->manageHooks('remove'); return $this; } } <file_sep>/CHANGELOG.md # CHANGELOG <a name="3.0"></a> ## [3.0](https://github.com/maicol07/flarum_sso_php_plugin/compare/2.0...3.0) > Released on April 06, 2021 ### 📝 Documentation changes - [`2b2dcb3`](https://github.com/maicol07/flarum_sso_php_plugin/commit/2b2dcb38b547443bfb73a72399fe4079a4ebd14b) 📝 Updated docs - [`94a2a84`](https://github.com/maicol07/flarum_sso_php_plugin/commit/94a2a84d3e270190c2ad4d3adfe26dd9c26e700b) 📝 Updated docs - [`37ce682`](https://github.com/maicol07/flarum_sso_php_plugin/commit/37ce682eadd9a4e2ee1fc24c3af49499909f8d06) 📝 Updated docs Now using doctum with a modified version of the Flarum docs theme - 🙈 Updated .gitignore - [`7b7cbb8`](https://github.com/maicol07/flarum_sso_php_plugin/commit/7b7cbb8d95eb4ec2c37b32ae98842cd8c1ad541f) 📝 PHPDoc fix ### 🐛 Bug Fixes - [`6c262d8`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6c262d898f3ccc68ee20a93dbd0c12ebe4182236) 👽 Nickname attribute instead of display name ### 🔄 Updates - [`443658d`](https://github.com/maicol07/flarum_sso_php_plugin/commit/443658d6ca64b7a22a443866a82f8361434f8096) 🔥 Removed the getForumLink URL is accessible via the url property - [`3f31ea6`](https://github.com/maicol07/flarum_sso_php_plugin/commit/3f31ea614a15c9e409f6cd31dc0792801788b377) ✨ Updated user `update` method - ✨ Added check if id is set. If not set, it will be fetched automatically. - ✨ Response is now saved and passed as argument to the after_update method hook. - ✨ The method now returns a bool. True if the user has been updated (the response correctly reports the user id); false if the user can't be fetched (if the user id doesn't exists) or the response id is different from user id - [`7b14a69`](https://github.com/maicol07/flarum_sso_php_plugin/commit/7b14a69e8b8853096a90e560957423f656d80ffa) 🚚 💥 Renamed the `fetchUser` method to simply `fetch` - [`e9c1c9e`](https://github.com/maicol07/flarum_sso_php_plugin/commit/e9c1c9ed309ead47182e465284900c042f4edca4) 🚚 Moved and Renamed the Basic trait to the Auth trait in the Maicol07\SSO\User\Traits namespace - [`80d1f7e`](https://github.com/maicol07/flarum_sso_php_plugin/commit/80d1f7eb6991b195eb2dcd2ee4438345cf9e1937) Minor improvements - [`c1e71eb`](https://github.com/maicol07/flarum_sso_php_plugin/commit/c1e71eba648d64c2607eb4b7f3e1ea64db0fcc41) **addons:** 🚚 Renamed master property to flarum (consistency) - [`e886c59`](https://github.com/maicol07/flarum_sso_php_plugin/commit/e886c596b6e6bdc9c8cf3543bffb732617c8e118) **example:** Updated example - [`204e0a2`](https://github.com/maicol07/flarum_sso_php_plugin/commit/204e0a26d33e76c541d11c93d92a8e3f27537301) **examples:** ✨ Added users list on the delete page ### ✨ Features - [`d173cb1`](https://github.com/maicol07/flarum_sso_php_plugin/commit/d173cb1c2b6c5e048567f167a65d02e141456d5d) ✨ Addons can now specify what addons are required to be loaded before it - [`c0dc540`](https://github.com/maicol07/flarum_sso_php_plugin/commit/c0dc5403ee64a9e89140def8ba81167b1b0b74c4) ✨ Allow to change the remember property via the `isSessionRemembered` method - [`f152d95`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f152d950cb79ca9af033a232b02c6126f6aae89c) ✨ 💥 New user() method - Replaces the current user object creation - User property is now private. You can only access to the user via this method - Improved examples - [`99c0594`](https://github.com/maicol07/flarum_sso_php_plugin/commit/99c059459d1f264fd4c15d6162a7fbcef697e2d8) 💥 ✨ 🚚 Moved Addons and Cookies features to traits - Removed class cookie. Now all the necessary cookies are generated on the fly. - Addons initialization in the constructor is moved to the initAddons() method in the Addons trait. - Login: now the logout cookie is deleted (if it exists), the session token or remember token is created - Logout: now the session token and remember token cookies are deleted (if they exist), a new logout cookie (flarum_logout) is created. New methods: - setRememberCookie - deleteRememberCookie - setSessionTokenCookie - deleteSessionTokenCookie - setLogoutCookie - deleteLogoutCookie - generateCookie Renamed methods: - addAddon is now loadAddon - removeAddon is now unloadAddon Removed methods: - setCookie BREAKING CHANGE - [`613b5b5`](https://github.com/maicol07/flarum_sso_php_plugin/commit/613b5b5317a174b74199c28e94a4515fb992f4fa) ✨ Added Remember me checkbox to example + some visual improvements - [`5865c51`](https://github.com/maicol07/flarum_sso_php_plugin/commit/5865c51d8ae57ace218d8c6648afd0612902d4ce) ✨ Changed `lifetime` to `remember` Lifetime is deprecated in beta16. Remember should be set to true when you want to login the user with a "Remember me" option. - [`edd34eb`](https://github.com/maicol07/flarum_sso_php_plugin/commit/edd34eb1356fe28baf77c54be1b69b8cb0e2bcbe) ✨ Initial attempt to beta16 compatibility - BREAKING CHANGE: 💥 Replaced the `lifetime` setting with `remember` - BREAKING CHANGE: 💥 Removed the `getLifeTimeSeconds` method - BREAKING CHANGE: 💥 PHP 7.3 required - WARNING! illuminate/support pinned to ^8 (removed support for Laravel 6 & 7) ### ♻ Code Refactoring - [`7f5f752`](https://github.com/maicol07/flarum_sso_php_plugin/commit/7f5f752005d6645194a8445b0bdc7cb6e20453a6) ♻️ 🚚 Moved delete and update methods out of the basic trait - [`e3c00de`](https://github.com/maicol07/flarum_sso_php_plugin/commit/e3c00dede0d2ee171e9a1a0d09a5dbcbf5601b40) ♻️ Refactor doctum.config.php - [`a72432d`](https://github.com/maicol07/flarum_sso_php_plugin/commit/a72432d75f7b0b5c930fad708fcda143b0613347) ♻️ Refactor doctum.config.php - [`6331b3c`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6331b3c2fc92746c85a6e2bb8a9c6b931eceb8f2) ♻️ General refactor ### Rename - [`768152a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/768152a6cd531f7b8d460c0177352b3ad275e172) **addons:** 🚚 `setAddonAttributes` renamed to `setAddonProperties` ### 🎨 Code styling - [`1b6448b`](https://github.com/maicol07/flarum_sso_php_plugin/commit/1b6448bd8f3a79c609e07c05ef8958735386ac4e) 💄 Minor example styling improvement ### 🔀 Pull Requests - [`befa080`](https://github.com/maicol07/flarum_sso_php_plugin/commit/befa08099f3818c9c2e57ffec26a55c05ebd40ce) Merge pull request [#9](https://github.com/maicol07/flarum_sso_php_plugin/issues/9) from richstandbrook/patch-1 feat: ✨ Be able to programmatically signup users <a name="2.0"></a> ## [2.0](https://github.com/maicol07/flarum_sso_php_plugin/compare/1.2.2...2.0) > Released on November 02, 2020 ### Other changes - [`996b9db`](https://github.com/maicol07/flarum_sso_php_plugin/commit/996b9db534cff0ed548fbb9db6d03165061e6c6c) Fixed links - [`cc0864a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/cc0864a9ccfb04185fab3677631438ee80f8c0bf) Removed unused packages - [`8f81cc7`](https://github.com/maicol07/flarum_sso_php_plugin/commit/8f81cc71c8cc1a2acd8fbc6034753121cc87c18b) Moved set_groups_admins to Groups addon - [`3ed03f1`](https://github.com/maicol07/flarum_sso_php_plugin/commit/3ed03f132397e1dd16f123b343f9e07895f7493d) Moved set_groups_admins to Groups addon - [`ad50268`](https://github.com/maicol07/flarum_sso_php_plugin/commit/ad5026869c8e7ccc3db4eb0834372247324a2f9c) improved ssl verification BREAKING CHANGE: changed option name and behaviour - [`f01e4bb`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f01e4bb0bf700adf167e52594868117f3ff22237) Improved group search - [`68df590`](https://github.com/maicol07/flarum_sso_php_plugin/commit/68df59024cab8469d33f5b95bf6b7e99f6a2cf54) Changed `addAddon` return and `setAddonAttributes` - [`f9652ea`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f9652eaaac3c552177c45cee66e932e0d210cf31) 🚚 Moved cookie saving to its own method - [`23136fa`](https://github.com/maicol07/flarum_sso_php_plugin/commit/23136fa021b3c51c937e3e918cb69e6afba6e86e) Changed method visibility - [`a676033`](https://github.com/maicol07/flarum_sso_php_plugin/commit/a6760336cfade7684054c890ebd92ad9210451b7) 📄 Wrong license - [`40b3924`](https://github.com/maicol07/flarum_sso_php_plugin/commit/40b3924383f9d17e769e8234ec37cc3da63fe402) Add username on init - [`a4481a3`](https://github.com/maicol07/flarum_sso_php_plugin/commit/a4481a3780dac12b77d154e0002f45474782a9ba) Updated composer.json - [`15a409a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/15a409ad3a16c7efa793c63ed9f861879ba0acbb) Updated composer.json - [`b6accc9`](https://github.com/maicol07/flarum_sso_php_plugin/commit/b6accc998f51f2f1e689fc3005bc28a5c9f602b0) Improvements to actions and filters - Returns -1 if hook/filter does not exist - Added login and register replacer - [`6aee96a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6aee96a4c7684f791edf4ccb6990bafb6252e80b) 🔥 Removed cookie removal - Linked to 1ea3d15456e643f893cda609df2e6195f8352143 - Tracker issue: #FSSOE-1 - [`ac9a9be`](https://github.com/maicol07/flarum_sso_php_plugin/commit/ac9a9bef3e3dfbd0e16a747c6d1a2d7d5d691a4f) Changed to bool - [`73df168`](https://github.com/maicol07/flarum_sso_php_plugin/commit/73df1680ff266d56f654a01d550435d19817579f) Support for more than one filter in users list - [`3315834`](https://github.com/maicol07/flarum_sso_php_plugin/commit/331583416243bf7245bac809c4022dd101c9bdc3) Return always a Collection BREAKING CHANGE: return type - [`6821785`](https://github.com/maicol07/flarum_sso_php_plugin/commit/682178521fe8b32ecff9e54b694db965ab0e8114) 🚚 Moved function `logout()` to Flarum - [`0a895d0`](https://github.com/maicol07/flarum_sso_php_plugin/commit/0a895d0af08e6c4f75c9e8377883ce3f4e872c86) Better error handling - [`94b173f`](https://github.com/maicol07/flarum_sso_php_plugin/commit/94b173fd37a94bbd0405a5a2bfa16be81e8ccc7f) Improved cookie saving - [`8842c70`](https://github.com/maicol07/flarum_sso_php_plugin/commit/8842c706298465f3fbe17f3b9c8ab7bbada4ce29) ♿️ Improvements to hooks - fix: Hook can't be executed - Added 1 filter - [`993e70b`](https://github.com/maicol07/flarum_sso_php_plugin/commit/993e70b93308b6f3c5387ef3378dca92268cabd6) Allow null as username For methods that don't involve user data such as `logout()` - [`f1964a1`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f1964a1aa58be72e942d46719dc1351c5ad3c625) 🏷️ Added type property - [`63f7269`](https://github.com/maicol07/flarum_sso_php_plugin/commit/63f72690c6586920458272056d7b29da31b0b1bb) 💥 Changed constructor parameters format BREAKING CHANGE - [`806582f`](https://github.com/maicol07/flarum_sso_php_plugin/commit/806582fb26df97a037dbdca7008c6ec0d902b40c) 🔥 Removed `setCookie()` function BREAKING CHANGE: function removed - [`f0d9655`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f0d9655dd9255a6a2ece97093a8eee81e4dea9df) Updated example - Added more ENV options - [`f4d4f8e`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f4d4f8ee39f9c3c4e1f4d5258d3de1af9eda2f8f) Updated example - [`83f0b4a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/83f0b4abc029055dec7aeb8a582fcf3debaa18fd) Updated example - [`6842ee6`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6842ee6bdc29430236c9d266e30302c962492c71) ✨ Added support for Laravel 8 - [`5b568a8`](https://github.com/maicol07/flarum_sso_php_plugin/commit/5b568a88dcd819ecefeda74622e6b4427ea2f24c) 🚚 Renamed package ### 📝 Documentation changes - [`5a764bc`](https://github.com/maicol07/flarum_sso_php_plugin/commit/5a764bc4a8ee669e188bd895c2863d6df734fbfe) Added missing docs - [`c5ffd73`](https://github.com/maicol07/flarum_sso_php_plugin/commit/c5ffd73ad7e91e870b490f4abeb4da83a804db24) 📝 Updated example to add groups - [`7ed7e78`](https://github.com/maicol07/flarum_sso_php_plugin/commit/7ed7e78fb79a732d9ba1fbf56d1ff107e7b7506c) 📝 Updated docs and examples - [`6b5e92c`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6b5e92c2c4841a2f845e3cfd4ebc1626a62cf184) Updated API Docs - [`cc04d97`](https://github.com/maicol07/flarum_sso_php_plugin/commit/cc04d979c74d11141b7acb99780a494cc2afa36d) Added packages to every class - [`0a4a97a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/0a4a97ae684e10509fb3cf78708d4fa051054889) Added env to example - [`ff3558f`](https://github.com/maicol07/flarum_sso_php_plugin/commit/ff3558f73444717704e18745dcbf75bf6fac1e91) 📝 Updated docs - [`197ebf0`](https://github.com/maicol07/flarum_sso_php_plugin/commit/197ebf0d82fd8555db77e8858f7a3d12ea715ae0) Updated API Docs - New design! - Updated to the new features! - [`96e99b3`](https://github.com/maicol07/flarum_sso_php_plugin/commit/96e99b34e6d0fc887d73ef84818ad40c90ccae24) Updated example - Added some HTML markup and CSS to examples - Updated to new plugin features ### ✨ Features - [`19fa6cc`](https://github.com/maicol07/flarum_sso_php_plugin/commit/19fa6cc6def4d5631c0078553f8f783c252907c1) Fetch user data from Flarum - [`31089ae`](https://github.com/maicol07/flarum_sso_php_plugin/commit/31089ae848eb9f7d2aa06349a58d3256f7df69e6) Support multiple arguments for hooks actions - [`b955432`](https://github.com/maicol07/flarum_sso_php_plugin/commit/b955432a06305f0a6875ea7c9bd22fed27afca92) ✨ Added missing default attributes - [`264af5d`](https://github.com/maicol07/flarum_sso_php_plugin/commit/264af5df64a9d0be9f8440d5086032097b55b0d4) ✨ New User class and properties classes FILES - Added a new User Class. This automatically fetch the user and initializes it with Flarum database info - Added new Attributes and Relationships classes BASIC TRAIT - [BREAKING CHANGE] Bundled to the user class, not to Flarum one - ♻️ General refactor - 🚚 Moved the `getUsersList` function to the Flarum class - 🚚 Moved the `getLifeTimeSeconds` to the Basic Trait BUNDLED ADDONS - [BREAKING CHANGE] Groups: 🔥 Removed `removeGroups()` function. Edit the User manually and then update him - Groups: Groups now will be updated when using the `update()` function - [`0027f3e`](https://github.com/maicol07/flarum_sso_php_plugin/commit/0027f3e7fa7716454ce454a7115603d50dacc785) ✨ Hooks/Addons system This way it is possible to split features across modules. The new Traits folders includes Basic features ### ⚡ Performance Improvements - [`02a22f9`](https://github.com/maicol07/flarum_sso_php_plugin/commit/02a22f931fd6e5e687ccce6056177bdbcd3ceac6) ⚡️ Avoid unnecessary request ### 🐛 Bug Fixes - [`c6e6adb`](https://github.com/maicol07/flarum_sso_php_plugin/commit/c6e6adb56b8f9f46752dc0fbf9d3c6b5af355aa4) Groups don't get added to the user - [`f913e74`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f913e74b5402482c2613dc329f189c5aab5c181f) Load namespaces in composer autoloader - [`1ce51e4`](https://github.com/maicol07/flarum_sso_php_plugin/commit/1ce51e4ec6e1260d78353a73aa8e96a99a17f955) 🐛 Warnings when username is null - [`5e99f70`](https://github.com/maicol07/flarum_sso_php_plugin/commit/5e99f70e54f8e23b86b2247b948b3b3ad3b88603) Replace methods - [`be32b36`](https://github.com/maicol07/flarum_sso_php_plugin/commit/be32b36747fca430f1cb31ddb8a36f8c1bd17472) 🐛 Attributes and relationships not initialized - [`50bc982`](https://github.com/maicol07/flarum_sso_php_plugin/commit/50bc982f3880d8ae8578a436fb00ce3f5e1b17bc) 🐛 Redirect not working when no scheme was specified Example before this fix: example.com --> NOT WORKING https://example.com --> WORKING After the fix: example.com --> BECOMES https://example.com --> WORKING https://example.com --> WORKING - [`cf2be12`](https://github.com/maicol07/flarum_sso_php_plugin/commit/cf2be127b5e5aa74fd2fad1f31cb50154b0690c4) 🥅 Exception if user does not exists in Flarum - Also added a new hook action - [`0d9c12e`](https://github.com/maicol07/flarum_sso_php_plugin/commit/0d9c12ea655a894ad35c09dc797bb4faf91b1aa6) last commit fixes - [`daeaf04`](https://github.com/maicol07/flarum_sso_php_plugin/commit/daeaf04317c9a183e98e15be078bf08ec4b14a56) ✏️ Typos - [`ff7c262`](https://github.com/maicol07/flarum_sso_php_plugin/commit/ff7c26263b77a41b112cac33b3994303dc17af7f) ✏️ Typos - [`6ec4a91`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6ec4a916da70262c5afc88caf33e1a509a5194bc) **deps:** 📌 Can't allow installations - [`6ca94d3`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6ca94d3bce7471f4f633a73b9ee620166f9f11c9) **deps:** 📌 Can't allow installations ### ♻ Code Refactoring - [`b2d029b`](https://github.com/maicol07/flarum_sso_php_plugin/commit/b2d029bc787f6e0d1239ef13786d86c0cdf11ab5) ♻️ Refactored comments - [`f31f07d`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f31f07d0d943b463da96c391480386e0dc4aa5c0) 🚚 Moved `setDomain()` method - [`7766209`](https://github.com/maicol07/flarum_sso_php_plugin/commit/7766209b532f6c80d027ec9271fa8c8c2950cf9d) :recycle: General refactor ### 🔀 Pull Requests - [`1cb4b3f`](https://github.com/maicol07/flarum_sso_php_plugin/commit/1cb4b3f7e06d021b635fcdc96c39eef8fd308488) Merge pull request [#5](https://github.com/maicol07/flarum_sso_php_plugin/issues/5) from maicol07/renovate/configure Configure Renovate ### BREAKING CHANGE changed option name and behaviour return type function removed <a name="1.2.2"></a> ## [1.2.2](https://github.com/maicol07/flarum_sso_php_plugin/compare/1.2.1...1.2.2) > Released on August 27, 2020 ### 🐛 Bug Fixes - [`16f4e75`](https://github.com/maicol07/flarum_sso_php_plugin/commit/16f4e750d126454cd12f8a5aabc7c038a7dfd787) :pencil2:: Wrong version constraint <a name="1.2.1"></a> ## [1.2.1](https://github.com/maicol07/flarum_sso_php_plugin/compare/1.2...1.2.1) > Released on August 27, 2020 ### 🐛 Bug Fixes - [`5c394c9`](https://github.com/maicol07/flarum_sso_php_plugin/commit/5c394c93d991adfa7317803ac83ae2ac3b86ed46) :bug: Missing class error ### Other changes - [`9df0685`](https://github.com/maicol07/flarum_sso_php_plugin/commit/9df0685f54bf5903ebfd1286cd67489ddddcb9c3) **deps:** Changed api client namespace - [`714011b`](https://github.com/maicol07/flarum_sso_php_plugin/commit/714011b174303cae5befc357db793d9056bb647a) **deps:** :arrow_up: Updated composer dependencies Changelogs summary:     - symfony/translation-contracts updated from v2.0.1 to v2.1.3   See changes: https://github.com/symfony/translation-contracts/compare/v2.0.1...v2.1.3   Release notes: https://github.com/symfony/translation-contracts/releases/tag/v2.1.3     - symfony/polyfill-php80 installed in version v1.18.1   Release notes: https://github.com/symfony/polyfill-php80/releases/tag/v1.18.1     - symfony/polyfill-mbstring updated from v1.15.0 to v1.18.1   See changes: https://github.com/symfony/polyfill-mbstring/compare/v1.15.0...v1.18.1   Release notes: https://github.com/symfony/polyfill-mbstring/releases/tag/v1.18.1     - symfony/translation updated from v5.0.7 to v5.1.3   See changes: https://github.com/symfony/translation/compare/v5.0.7...v5.1.3   Release notes: https://github.com/symfony/translation/releases/tag/v5.1.3     - nesbot/carbon updated from 2.32.2 to 2.39.0   See changes: https://github.com/briannesbitt/Carbon/compare/2.32.2...2.39.0   Release notes: https://github.com/briannesbitt/Carbon/releases/tag/2.39.0     - doctrine/inflector updated from 1.3.1 to 1.4.3   See changes: https://github.com/doctrine/inflector/compare/1.3.1...1.4.3   Release notes: https://github.com/doctrine/inflector/releases/tag/1.4.3     - symfony/polyfill-php72 installed in version v1.18.1   Release notes: https://github.com/symfony/polyfill-php72/releases/tag/v1.18.1     - paragonie/random_compat installed in version v9.99.99   Release notes: https://github.com/paragonie/random_compat/releases/tag/v9.99.99     - symfony/polyfill-php70 installed in version v1.18.1   Release notes: https://github.com/symfony/polyfill-php70/releases/tag/v1.18.1     - symfony/polyfill-intl-normalizer installed in version v1.18.1   Release notes: https://github.com/symfony/polyfill-intl-normalizer/releases/tag/v1.18.1     - symfony/polyfill-intl-idn installed in version v1.18.1   Release notes: https://github.com/symfony/polyfill-intl-idn/releases/tag/v1.18.1     - guzzlehttp/guzzle updated from 6.5.2 to 6.5.5   See changes: https://github.com/guzzle/guzzle/compare/6.5.2...6.5.5   Release notes: https://github.com/guzzle/guzzle/releases/tag/6.5.5     - flagrow/flarum-api-client updated from dev-master[@c6faca2](https://github.com/c6faca2) to dev-master[@08c300c](https://github.com/08c300c)   See changes: https://github.com/flagrow/flarum-api-client/compare/maicol07:c6faca2...flagrow:08c300c     - roave/security-advisories installed in version dev-master[@89bed67](https://github.com/89bed67) ### 🔀 Pull Requests - [`316760f`](https://github.com/maicol07/flarum_sso_php_plugin/commit/316760fb8e7c530ff1f6a434809c6e02812fe717) Merge pull request [#4](https://github.com/maicol07/flarum_sso_php_plugin/issues/4) from Scumi/master src/Flarum.php: fixed plugin cookie not being deleted <a name="1.2"></a> ## [1.2](https://github.com/maicol07/flarum_sso_php_plugin/compare/1.1.1...1.2) > Released on April 22, 2020 ### 🐛 Bug Fixes - [`abcf173`](https://github.com/maicol07/flarum_sso_php_plugin/commit/abcf173f29aa931cf3710702a50ec13af20fe778) Groups were not deleted from user - [`6a1a7ff`](https://github.com/maicol07/flarum_sso_php_plugin/commit/6a1a7ffb8db039e58545c4cbd9ead4a3fb98d2b4) Removing PRO key don't deactivate PRO features - [`9977f16`](https://github.com/maicol07/flarum_sso_php_plugin/commit/9977f16d9426644ad68f4745d2a511699804f743) User can't login if it's not an admin - [`e44e552`](https://github.com/maicol07/flarum_sso_php_plugin/commit/e44e55208efd267bf349400b9cf886765fb9c634) Added missing class of previous commit - [`c57421a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/c57421af59dd1dd04df5d728ae9358e8d0b602d1) User can't login if his id > 20 * Better getUserList method. Now is public * Changed full parameter to filter (see API doc) ### 🐛 Bug Fixes - [`bd4ed25`](https://github.com/maicol07/flarum_sso_php_plugin/commit/bd4ed25d7a27cffb73c41fc9cec3d7d718a75e42) set_groups_admins and update ### ✨ Features - [`abe07d7`](https://github.com/maicol07/flarum_sso_php_plugin/commit/abe07d77820e23cf76d02f8c164b86dcd58af885) Disable setting groups to admins ### 🎨 Code styling - [`ca1524a`](https://github.com/maicol07/flarum_sso_php_plugin/commit/ca1524a2b91934d720e23abcf1ac888cc04702a1) Rearranged code ### ⚡ Performance Improvements - [`213eb2c`](https://github.com/maicol07/flarum_sso_php_plugin/commit/213eb2c041c4caaa479d23a6507974509e76fd5c) Optimized login times <a name="1.1.1"></a> ## [1.1.1](https://github.com/maicol07/flarum_sso_php_plugin/compare/1.1...1.1.1) > Released on April 20, 2020 ### 🔀 Pull Requests - [`a74be40`](https://github.com/maicol07/flarum_sso_php_plugin/commit/a74be40e8c8d43cf67648976a2745209410823ef) Merge pull request [#1](https://github.com/maicol07/flarum_sso_php_plugin/issues/1) from maicol07/imgbot [ImgBot] Optimize images <a name="1.1"></a> ## [1.1](https://github.com/maicol07/flarum_sso_php_plugin/compare/1.0...1.1) > Released on April 20, 2020 ### ✨ Features - [`f33e9c8`](https://github.com/maicol07/flarum_sso_php_plugin/commit/f33e9c8c006892982b2155ed2db3a38da6ca53c7) Password reset Includes general code style reformat and some fixes for the pro login feature - [`afdb5d1`](https://github.com/maicol07/flarum_sso_php_plugin/commit/afdb5d1888895f113f72645e5e848c3bab0247fd) Groups setting on signup, update user Includes a general code style refactor and some fixes for the setGroup features ### 🐛 Bug Fixes - [`01635c3`](https://github.com/maicol07/flarum_sso_php_plugin/commit/01635c3ec321cffd1c5453651851b53fcbbfa4b3) #FSSOE-1 - [`8e55936`](https://github.com/maicol07/flarum_sso_php_plugin/commit/8e55936bce798185401d14c9f70d06955ee752a9) Fixed not_authenticated error ### Other changes - [`06353e3`](https://github.com/maicol07/flarum_sso_php_plugin/commit/06353e3165e867867abfdce447ce711275a11f28) Silenced error on login form - [`bfecf7b`](https://github.com/maicol07/flarum_sso_php_plugin/commit/bfecf7be1fb6ba16105bbfcbc926f2c48de81296) Fixed critical rename error - [`2167d47`](https://github.com/maicol07/flarum_sso_php_plugin/commit/2167d47947628d0af6560887e263c5ae569275d6) Slug rename Plugin slug has been renamed to sso-flarum. Naming conventions from now on: - Files: prefix-flarum-sso-suffix.ext - Options names, ids or function names: prefix_flarum_sso_plugin_suffix - Slugs, text domain and other slug-related strings: sso-flarum with eventually a prefix, suffix or extension <a name="1.0"></a> ## 1.0 > Released on April 08, 2020 ### Other changes - [`2955fd9`](https://github.com/maicol07/flarum_sso_php_plugin/commit/2955fd991f1b8f142bdda0d0b75098ef208f0a5e) Release 1.0 - Completely new WordPress plugin! - Settings page - PRO features (read more on docs) - In the nearby future will be published in the WordPress Plugins Directory! - [`053b49b`](https://github.com/maicol07/flarum_sso_php_plugin/commit/053b49ba2f958c1f8326611d79eef40eaff380ec) Release 1.0 - BREAKING CHANGE! PHP 7+ required - BREAKING CHANGE! New request system: now using the great Flagrow API client - New Cookie management: now using the awesome Cookie library by Delight-im - New option: insecure mode (principally for local development, read in docs for more) - Added groups settings for users: you can now set a group for a user and, if doesn't exists, it will be created! - BREAKING CHANGE! Deleted sendRequest and get methods as no more used. - Code and performance improvements - Various fixes (see also the bug tracker) - [`54a0231`](https://github.com/maicol07/flarum_sso_php_plugin/commit/54a023106dab22fcece619f2b1a1c63d8589018d) New WordPress plugin - [`47eb6d3`](https://github.com/maicol07/flarum_sso_php_plugin/commit/47eb6d3ad1677371ef0bf71c1295d1f443bc9c9e) Better installation details - [`4e67550`](https://github.com/maicol07/flarum_sso_php_plugin/commit/4e6755080dd9806cea90f63a2d5014c25dcf8fb8) Added namespace to Flarum class - [`08b2561`](https://github.com/maicol07/flarum_sso_php_plugin/commit/08b25617e411f689f1c03bb8a60887eddac14b67) General refactor - !!! PLUGIN NOW REQUIRES PHP 7+ - Plugin can now be installed with composer! - Organized files in folders - !!! Removed config.php. Configuration can now be set with class parameters - New Cookie management - Removed removeCookie method - Improved README.md BREAKING CHANGE: See description ### ✨ Features - [`30c2c61`](https://github.com/maicol07/flarum_sso_php_plugin/commit/30c2c619df9ab92628b3f4eab8cc8a72038b0c91) Addded insecure mode and groups setting ### BREAKING CHANGE See description <file_sep>/example/index.php <?php /** @noinspection ForgottenDebugOutputInspection */ use Dotenv\Dotenv; use Illuminate\Support\Arr; use Maicol07\SSO\Addons\Groups; // Note: Since this is called from the example folder, the vendor folder is located in the previous tree level require_once __DIR__ . '/../vendor/autoload.php'; // Load .env $env = Dotenv::createImmutable(__DIR__); $env->load(); // Dummy users $users = [ 'user' => [ 'password' => '<PASSWORD>', 'email' => '<EMAIL>', ], 'admin' => [ 'password' => '<PASSWORD>', 'email' => '<EMAIL>', ], ]; // Get username and password $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; if (!empty(Arr::get($users, $username)) && Arr::get($users, "$username.password") === $password) { require_once __DIR__ . '/flarum.php'; /** @var $flarum <-- Fix PHPStorm hints */ // Create the user to work with $flarum_user = $flarum->user($username); // Set his password $flarum_user->attributes->password = Arr::get($users, "$username.password"); // If user is not signed up into Flarum... if (empty($flarum_user->id)) { // ...add details to Flarum user $flarum_user->attributes->username = $username; $flarum_user->attributes->email = Arr::get($users, "$username.email"); } // Let's add to it some groups (optional, only for demonstation) // First, let's add the Groups addon (note that the Groups class is imported at the top with the use statement) $flarum->loadAddon(Groups::class); $flarum->setAddonProperties(Groups::class, ['set_groups_admins' => env('SET_GROUPS_ADMINS') ?? true]); // Then, add the groups (as an array) to the correct attribute in user relationships $flarum_user->relationships->groups = ['Premium', 'Novice']; // Login the user with username. If user doesn't exists in Flarum, it will be created $success = $flarum_user->login(); // Redirect to Flarum if (!empty($_GET['redirect'])) { $flarum->redirect(); } } elseif (!empty($username) || !empty($password)) { $success = false; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Login</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Lightweight CSS only to make this page beauty --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" integrity="<KEY> crossorigin="anonymous"> </head> <body class="container"> <div class="box" style="margin-top: 25px;"> <h1 class="title">Login</h1> <div class="columns"> <div class="column"> <table class="table"> <thead> <tr> <th>Username</th> <th>Password</th> </tr> </thead> <tbody> <?php foreach ($users as $username => $details) { echo "<tr> <td>$username</td> <td>" . Arr::get($details, 'password') . "</td> </tr>"; } ?> </tbody> </table> </div> <div class="column"> <form method="post"> <label class="label" for="username">Username</label> <input id="username" type="text" class="input" name="username" placeholder="Username"> <label class="label mt-3" for="password">Password</label> <input id="password" type="<PASSWORD>" class="input" name="password" placeholder="<PASSWORD>"> <label class="checkbox mt-2 mb-2"> <input id="remember" name="remember" type="checkbox"> Remember me </label> <button class="button" type="submit" style="display: block; margin: 0 auto;">Login</button> </form> </div> </div> <?php if (isset($flarum) and !empty($success)) { ?> <div class="notification is-success"> <button class="delete"></button> Successfully logged in! Click the button below to go to Flarum! <br> <a class="button is-rounded mt-5" href="<?php echo $flarum->url ?>" style="display: block; margin: 0 auto; width: max-content;"> Go to Flarum </a> <details> <summary>User details</summary> <pre style="margin: 16px 0;"> <?php if (isset($flarum_user) and $flarum_user->fetch()) { $is_admin = $flarum_user->isAdmin ? 'Yes' : 'No'; echo "User ID: $flarum_user->id<br>Is user admin? <b>$is_admin</b><br>User attributes: <br>"; var_export($flarum_user->getAttributes()); echo "<br>User relationships: <br>"; var_export($flarum_user->getRelationships()); } else { echo "Can't fetch user from Flarum!"; } ?> </pre> </details> </div> <?php } elseif (isset($success) and empty($success)) { ?> <div class="notification is-danger"> <button class="delete"></button> Login failed </div> <?php } ?> </div> <?php require_once 'footer.php' ?> </body> </html>
0a8504adaec1bc67d8a6ab34466a24bdb6f32077
[ "Markdown", "PHP", "Shell" ]
20
Markdown
maicol07/flarum-sso-plugin
f3c9c505336bd5ccd5081170f2dfdc9fb9b44244
3328b7e47293c5402cd55ac0e67f6fc597826ad4
refs/heads/master
<file_sep>import React from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Image, } from 'react-native'; import { Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; import TopBar from './components/TopBar' import BottomNav from './components/BottomNav' import { BottomNavigation } from 'react-native-paper'; export default class App extends React.Component { render() { return ( <View style={{ flex: 1 }}> <TopBar /> {/* <ScrollView contentInsetAdjustmentBehavior="automatic" style={styles.scrollView}> <SafeAreaView> <View style={styles.body}> <View style={styles.imageContainer}> <Image source={{ uri: 'https://i.pinimg.com/474x/e3/5f/4f/e35f4fdec41c2e1769da1fe725783c75.jpg', }} style={{ width: '100%', height: '100%' }} /> </View> <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Yoooooo</Text> <Text style={styles.sectionDescription}> Edit <Text style={styles.highlight}>App.js</Text> to change this screen and then come back to see your edits. </Text> </View> <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Yoooooo</Text> <Text style={styles.sectionDescription}> Edit <Text style={styles.highlight}>App.js</Text> to change this screen and then come back to see your edits. </Text> </View> <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Yoooooo</Text> <Text style={styles.sectionDescription}> Edit <Text style={styles.highlight}>App.js</Text> to change this screen and then come back to see your edits. </Text> </View> <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Yoooooo</Text> <Text style={styles.sectionDescription}> Edit <Text style={styles.highlight}>App.js</Text> to change this screen and then come back to see your edits. </Text> </View> <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Debug</Text> <Text style={styles.sectionDescription}> <DebugInstructions /> </Text> </View> </View> </SafeAreaView> </ScrollView> */} <BottomNav /> </View> ); }; }; const styles = StyleSheet.create({ scrollView: { backgroundColor: Colors.lighter, }, engine: { position: 'absolute', right: 0, }, body: { backgroundColor: Colors.white, }, imageContainer: { marginTop: 32, paddingHorizontal: 24, height: 300, }, sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', color: Colors.black, }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', color: Colors.dark, }, highlight: { fontWeight: '700', }, footer: { color: Colors.dark, fontSize: 12, fontWeight: '600', padding: 4, paddingRight: 12, textAlign: 'right', } });
c5aea3dcf345b2937d5766d171f7f1c24f21814d
[ "JavaScript" ]
1
JavaScript
Stef013/HealthTracker
514120a6d647dcb69bd36f3a0aa604e6fbe0ba36
15e2ad3d2670645d5236845a7eab45a6b24bacd3
refs/heads/master
<file_sep>import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; public class rect extends Rectangle { Color blue = Color.CYAN ; int x ; int y ; int width ; int height ; public rect (int a , int b ,int w , int h ) { x = a ; y = b ; width = w ; height = h ; } public void draw (Graphics g) { g.setColor(blue); g.drawRect(x, y, width, height); g.fillRect(x, y, width, height); } } <file_sep>import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; public class Ball { } <file_sep>import java.awt.Canvas; import java.awt.Graphics; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame1 = new JFrame ("Game"); frame1.setVisible(true); frame1.setSize(612, 500); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.setResizable(false); MYCanvas mycanvas = new MYCanvas () ; frame1.add(mycanvas); // BBPanel panel = new BBPanel () ; // frame1.add(panel) ; } }
f6e1c9381530fc2342d6f2303597a6dc18e1c96a
[ "Java" ]
3
Java
DinaGenena/Games
1cbeb86d6b96b5bc64177b1b02d13e58d7648823
49f83c27f1bf20d7b47824240d64496ab8043a82
refs/heads/master
<repo_name>MaelManifacier/javaFX-MVVM<file_sep>/javaFX10/src/viewmodel/VillageVM.java package viewmodel; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import launch.Launch; import modele.Aventure; import modele.Schtroumpf; import modele.Village; import modele.VillageIO; import java.beans.IndexedPropertyChangeEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; public class VillageVM implements PropertyChangeListener { private Village village; private ObservableList<SchtroumpfVM> listeSchtroumpfsData = FXCollections.observableArrayList(); private ListProperty<SchtroumpfVM> listeSchtroumpfs = new SimpleListProperty<>(listeSchtroumpfsData); public ListProperty<SchtroumpfVM> listeSchtroumpfsProperty() { return listeSchtroumpfs; } public ObservableList<SchtroumpfVM> getListeSchtroumpfs() { return listeSchtroumpfs.get(); } public void setListeSchtroumpfs(ObservableList<SchtroumpfVM> listeSchtroumpfs) { this.listeSchtroumpfs.set(listeSchtroumpfs); } public VillageVM(){ try { this.village = VillageIO.load(); if(this.village == null){ this.village = new Village(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } this.village.addListener(this); this.village.getListSchtroumpf().forEach(schtroumpf -> { this.listeSchtroumpfsData.add(new SchtroumpfVM(schtroumpf)); }); } public void ajouterSchtroumpf(String caractere){ this.village.ajouterSchtroumpf(new Schtroumpf(caractere)); } public void ajouterAventure(String theme, int schtroumpfIndex){ SchtroumpfVM schtroumpfVM = this.getListeSchtroumpfs().get(schtroumpfIndex); if(schtroumpfVM != null){ schtroumpfVM.ajouterAventure(theme); } } @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (propertyChangeEvent.getPropertyName().equals(Village.LIST)){ if(propertyChangeEvent.getNewValue() != null){ this.listeSchtroumpfsData.add( ((IndexedPropertyChangeEvent)propertyChangeEvent).getIndex(), new SchtroumpfVM((Schtroumpf) propertyChangeEvent.getNewValue())); } } } public void sauver() { VillageIO villageIO = new VillageIO(); try { villageIO.sauver(this.village); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/javaFX9/src/view/FenetrePrincipale.java package view; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.util.Callback; import viewmodel.EleveurVM; import viewmodel.MaCell; import viewmodel.SourisVM; public class FenetrePrincipale { @FXML ListView<SourisVM> listeSouris; @FXML Label nomSouris; @FXML TextField changerNomSouris; private EleveurVM eleveurVM = new EleveurVM(); public FenetrePrincipale(EleveurVM eleveurVM) { if(eleveurVM != null){ this.eleveurVM = eleveurVM; } } public void initialize(){ listeSouris.itemsProperty().bind(eleveurVM.listeSourisProperty()); listeSouris.setCellFactory(new Callback<ListView<SourisVM>, ListCell<SourisVM>>() { @Override public ListCell<SourisVM> call(ListView<SourisVM> param) { return new MaCell(); } }); listeSouris.getSelectionModel().selectedItemProperty().addListener((__, old, newValue)->{ if(old != null){ changerNomSouris.textProperty().unbindBidirectional(old.nomProperty()); } if(newValue != null){ nomSouris.textProperty().bind(newValue.nomProperty()); changerNomSouris.textProperty().bindBidirectional(newValue.nomProperty()); } }); this.eleveurVM.addSouris("HEY"); } public void ajouterSouris(ActionEvent actionEvent) { eleveurVM.addSouris("-- une souris --"); } public void sauvegarder(){ this.eleveurVM.sauvegarder(); } } <file_sep>/javaFX9/src/modele/Eleveur.java package modele; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Eleveur implements Serializable { public static String LISTE = "jrqe"; private transient PropertyChangeSupport support; private List<Souris> listeSouris; public Eleveur() { this.listeSouris = new ArrayList<>(); this.support = new PropertyChangeSupport(this); } public List<Souris> getListeSouris() { return listeSouris; } public void addSouris(Souris souris) { this.listeSouris.add(souris); this.support.fireIndexedPropertyChange(LISTE, this.listeSouris.size()-1, null, souris); } public void addObserver(PropertyChangeListener listener){ this.support.addPropertyChangeListener(listener); } public void removeObserver(PropertyChangeListener listener){ this.support.removePropertyChangeListener(listener); } } <file_sep>/javaFX11/src/viewmodel/MaCellACookie.java package viewmodel; import javafx.scene.control.ListCell; public class MaCellACookie extends ListCell<CookieVM> { @Override protected void updateItem(CookieVM item, boolean empty) { super.updateItem(item, empty); if(!empty){ textProperty().bind(item.typeProperty()); } else { textProperty().unbind(); setText(""); } } } <file_sep>/README.md javaFX3 : juste un view/model -> problème: le modèle n'est pas sérializable. Il faut donc séparer la vue du modèle. Pour cela, on va utiliser le pattern MVVM : Modele ViewModel View. Les deux tp suivants utilisent ce pattern. (créé avec Intellij Idea, dans les configurations, ajout de javafx-sdk-11.0.2 en VM options : --module-path /chemin/sdk/lib --add-modules javafx.controls,javafx.fxml dans Module Settings du projet : add library /chemin/sdk/lib ) <file_sep>/javaFX11/src/viewmodel/BoiteVM.java package viewmodel; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import modele.Boite; import modele.BoiteIO; import modele.Cookie; import modele.Ingredient; import java.beans.IndexedPropertyChangeEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; public class BoiteVM implements PropertyChangeListener { private Boite modele; private ObservableList<CookieVM> listeCookiesData = FXCollections.observableArrayList(); private ListProperty<CookieVM> listeCookies = new SimpleListProperty<>(listeCookiesData); public ListProperty<CookieVM> listeCookiesProperty() { return listeCookies; } public ObservableList<CookieVM> getListeCookies() { return listeCookies.get(); } public void setListeCookies(ObservableList<CookieVM> listeCookies) { this.listeCookies.set(listeCookies); } public BoiteVM(){ this.modele = new Boite(); this.modele.ajouterListener(this); this.modele.getListeCookies().forEach(cookie -> { this.listeCookiesData.add(new CookieVM(cookie)); }); } public void ajouterCookie(String type){ /* Cookie cookie = new Cookie(cookieVM.getType()); //ajouter à la liste cookieVM.getListeIngredients().forEach(ingredientVM -> { cookie.ajouterIngredient(new Ingredient(ingredientVM.getNom())); });*/ this.modele.ajouterCookie(new Cookie(type)); } @Override public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().equals(Boite.LISTCOOKIE)){ if(evt.getNewValue() != null){ this.listeCookiesData.add( ((IndexedPropertyChangeEvent)evt).getIndex(), new CookieVM((Cookie) evt.getNewValue())); } } } public void ajouterIngredient(int index) { this.modele.ajouterIngredient(index, "-- ingredient --"); } public void sauvegarder() { try { BoiteIO.sauvegarder(this.modele); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/javaFX11/src/viewmodel/CookieVM.java package viewmodel; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import modele.Cookie; import modele.Ingredient; import java.beans.IndexedPropertyChangeEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public class CookieVM implements PropertyChangeListener { private Cookie modele; private StringProperty type = new SimpleStringProperty(); public StringProperty typeProperty() { return type; } public String getType() { return type.get(); } public void setType(String type) { this.type.set(type); } private ObservableList<IngredientVM> listeIngredientsData = FXCollections.observableArrayList(); private ListProperty<IngredientVM> listeIngredients = new SimpleListProperty<>(listeIngredientsData); public ListProperty<IngredientVM> listeIngredientsProperty() { return listeIngredients; } public ObservableList<IngredientVM> getListeIngredients() { return listeIngredients.get(); } public void setListeIngredients(ObservableList<IngredientVM> listeIngredients) { this.listeIngredients.set(listeIngredients); } public CookieVM(Cookie cookie){ this.modele = cookie; setType(cookie.getType()); cookie.getListeIngredients().forEach(ingredient -> { this.listeIngredientsData.add(new IngredientVM(ingredient)); }); this.modele.ajouterListener(this); } public void ajouterIngredient(String nom){ this.modele.ajouterIngredient(new Ingredient(nom)); } @Override public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().equals(Cookie.TYPECOOKIE)){ if(evt.getNewValue() != null){ setType((String) evt.getNewValue()); } } if(evt.getPropertyName().equals(Cookie.LISTINGREDIENT)){ if(evt.getNewValue() != null){ listeIngredientsData.add(((IndexedPropertyChangeEvent)evt).getIndex(), new IngredientVM((Ingredient) evt.getNewValue())); } } } } <file_sep>/javaFX5/src/view/FenetrePrincipale.java package view; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TextField; import stub.LapinStub; public class FenetrePrincipale { @FXML TextField textFieldNomLapin; @FXML Label labelNomLapin; @FXML Label labelNomLapinRecupere; @FXML Label messageErreur; private LapinStub stub = new LapinStub(); public void initialize() { textFieldNomLapin.textProperty().bindBidirectional(this.stub.lapinVM.nomProperty()); labelNomLapin.textProperty().bind(stub.lapinVM.nomProperty()); } public void sauvegarder(){ String message = stub.lapinVM.sauvegarder(); if(!message.equals("")){ this.messageErreur.setText(message); } } public void recuperer(){ String nom = stub.lapinVM.recuperer(); if(nom != null){ labelNomLapinRecupere.setText(nom); } else { labelNomLapinRecupere.setText("Probleme a la recuperation"); } } } <file_sep>/javaFX3/src/view/CelluleListe.java package view; import javafx.scene.control.CheckBox; import javafx.scene.control.ListCell; import modele.Lapin; public class CelluleListe extends ListCell<Lapin> { @Override protected void updateItem(Lapin item, boolean empty) { super.updateItem(item, empty); if(!empty){ CheckBox checkBox = new CheckBox(); checkBox.selectedProperty().bindBidirectional(item.isLapinGarouProperty()); textProperty().bind(item.nomProperty()); setGraphic(checkBox); } else { textProperty().unbind(); setText(""); setGraphic(null); } } } <file_sep>/javaFX10/src/viewmodel/AventureVM.java package viewmodel; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import modele.Aventure; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public class AventureVM implements PropertyChangeListener { private Aventure model; private StringProperty theme = new SimpleStringProperty(); public StringProperty themeProperty() { return theme; } public String getTheme() { return theme.get(); } public void setTheme(String theme) { this.theme.set(theme); } public AventureVM(Aventure aventure){ this.model = aventure; this.model.addListener(this); setTheme(aventure.getTheme()); } @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if(propertyChangeEvent.getPropertyName().equals(Aventure.THEME)){ if(propertyChangeEvent.getNewValue() != null){ setTheme( (String) propertyChangeEvent.getNewValue()); } } } } <file_sep>/javaFX9/src/viewmodel/MaCell.java package viewmodel; import javafx.scene.control.ListCell; public class MaCell extends ListCell<SourisVM> { @Override protected void updateItem(SourisVM item, boolean empty) { super.updateItem(item, empty); if(!empty){ textProperty().bind(item.nomProperty()); } else { textProperty().unbind(); setText(""); } } } <file_sep>/javaFX11/src/viewmodel/IngredientVM.java package viewmodel; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import modele.Ingredient; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public class IngredientVM implements PropertyChangeListener { private Ingredient model; private StringProperty nom = new SimpleStringProperty(); public StringProperty nomProperty() { return nom; } public String getNom() { return nom.get(); } public void setNom(String nom) { this.nom.set(nom); } public IngredientVM(Ingredient ingredient){ this.model = ingredient; setNom(ingredient.getNom()); this.model.addListener(this); } @Override public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().equals(Ingredient.NOMINGREDIENT)){ if(evt.getNewValue() != null){ setNom((String) evt.getNewValue()); } } } } <file_sep>/javaFX10/src/modele/Aventure.java package modele; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; public class Aventure implements Serializable { public static String THEME = "hgqr"; private transient PropertyChangeSupport support; private String theme; public String getTheme() { return theme; } public void setTheme(String theme) { String oldTheme = this.theme; this.theme = theme; this.getSupport().firePropertyChange(THEME, oldTheme, theme); } public Aventure(String theme) { setTheme(theme); this.support = new PropertyChangeSupport(this); } public void addListener(PropertyChangeListener listener){ this.getSupport().addPropertyChangeListener(listener); } public void removeListener(PropertyChangeListener listener){ this.getSupport().removePropertyChangeListener(listener); } public PropertyChangeSupport getSupport(){ if(this.support == null){ this.support = new PropertyChangeSupport(this); } return this.support; } } <file_sep>/javaFX5/src/launch/Launch.java package launch; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Launch extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent p = FXMLLoader.load(getClass().getResource("/fxml/FenetrePrincipale.fxml")); Scene scene = new Scene(p); primaryStage.setScene(scene); primaryStage.show(); } @Override public void stop() throws Exception { super.stop(); } } <file_sep>/javaFX10/src/modele/Schtroumpf.java package modele; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Schtroumpf implements Serializable { public static final String CARACTERE = "hgfds"; public static final String LISTAVENTURE = "jhgfd"; private transient PropertyChangeSupport support; private String caractere; private List<Aventure> listeAventures; public String getCaractere() { return caractere; } public void setCaractere(String caractere) { this.getSupport().firePropertyChange(CARACTERE, this.caractere, caractere); this.caractere = caractere; } public Schtroumpf(String caractere) { setCaractere(caractere); this.listeAventures = new ArrayList<>(); this.support = new PropertyChangeSupport(this); } public List<Aventure> getListAventures() { return listeAventures; } public void ajouterAventure(Aventure aventure){ this.listeAventures.add(aventure); this.getSupport().fireIndexedPropertyChange(LISTAVENTURE, this.listeAventures.size()-1, null, aventure); } public void addListener(PropertyChangeListener listener){ this.getSupport().addPropertyChangeListener(listener); } public void removeListener(PropertyChangeListener listener){ this.getSupport().removePropertyChangeListener(listener); } public PropertyChangeSupport getSupport(){ if(this.support == null){ this.support = new PropertyChangeSupport(this); } return this.support; } } <file_sep>/javaFX10/src/modele/Village.java package modele; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Village implements Serializable { public static final String LIST = "yhrs"; private transient PropertyChangeSupport support; private List<Schtroumpf> listeSchtroumpf; public List<Schtroumpf> getListSchtroumpf() { return listeSchtroumpf; } public Village() { this.listeSchtroumpf = new ArrayList<>(); this.support = new PropertyChangeSupport(this); } public void ajouterSchtroumpf(Schtroumpf schtroumpf){ this.listeSchtroumpf.add(schtroumpf); this.getSupport().fireIndexedPropertyChange(LIST, this.listeSchtroumpf.size()-1, null, schtroumpf); } public void addListener(PropertyChangeListener listener){ this.getSupport().addPropertyChangeListener(listener); } public void removeListener(PropertyChangeListener listener){ this.getSupport().removePropertyChangeListener(listener); } public PropertyChangeSupport getSupport(){ if(this.support == null){ this.support = new PropertyChangeSupport(this); } return this.support; } } <file_sep>/javaFX3/src/modele/Lapin.java package modele; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class Lapin { private StringProperty nom = new SimpleStringProperty(); public StringProperty nomProperty() {return nom;} public String getNom() {return nom.getValue();} public void setNom (String nom) {this.nom.setValue(nom);} private StringProperty couleur = new SimpleStringProperty(); public StringProperty couleurProperty() {return couleur;} public String getCouleur() { return couleur.get(); } public void setCouleur(String couleur) { this.couleur.set(couleur); } private BooleanProperty isLapinGarou = new SimpleBooleanProperty(); public BooleanProperty isLapinGarouProperty() { return isLapinGarou; } public boolean isIsLapinGarou() { return isLapinGarou.get(); } public void setIsLapinGarou(boolean isLapinGarou) { this.isLapinGarou.set(isLapinGarou); } public Lapin(String nom, String couleur){ setNom(nom); setCouleur(couleur); } @Override public String toString(){ return this.getNom(); } } <file_sep>/javaFX9/src/viewmodel/SourisVM.java package viewmodel; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import modele.Souris; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public class SourisVM implements PropertyChangeListener{ private Souris model; private StringProperty nom = new SimpleStringProperty(); public StringProperty nomProperty() { return nom; } public String getNom() { return nom.get(); } public void setNom(String nom) { this.nom.set(nom); } public SourisVM(Souris model) { this.model = model; this.model.addListener(this); setNom(model.getNom()); nom.addListener((__, old, newValue) -> { if(newValue != null){ model.setNom(newValue); } }); } @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if(propertyChangeEvent.getPropertyName().equals(Souris.SOURIS)){ if(propertyChangeEvent.getNewValue() != null){ setNom((String)propertyChangeEvent.getNewValue()); } } } } <file_sep>/javaFX11/src/modele/BoiteIO.java package modele; import java.io.*; public class BoiteIO { public static Boite load() throws IOException, ClassNotFoundException { try(ObjectInputStream os = new ObjectInputStream(new FileInputStream("boite.bin"))){ return (Boite) os.readObject(); } } public static void sauvegarder(Boite boite) throws IOException { try(ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("boite.bin"))){ os.writeObject(boite); } } }
6c6bb8c55244102106f7b529c88beb45b3fece56
[ "Markdown", "Java" ]
19
Java
MaelManifacier/javaFX-MVVM
9f7fb0989c85cad02c3a96d2aa5bfc3ee321d5b4
1a61d1009c2a7f2035c4a3b8705e101a0e5666ba
refs/heads/master
<file_sep># See LICENSE for license details. #-------------------------------------------------------------------- # global define #-------------------------------------------------------------------- base_dir = $(abspath ..) sim_dir = . output_dir = $(sim_dir)/output SPIKE_FLAGS = -p1 -m2048 -t2 --ic=64:4:64 --dc=64:4:64 --l2=256:8:64 --tt=64:8:64:1 --tm0=4:4:16:1 #SPIKE_FLAGS = -p1 -m2048 -t4 --ic=64:4:64 --dc=64:4:64 --l2=256:8:64 --utc=64:8:64:1 .PHONY: default #-------------------------------------------------------------------- # Test cases #-------------------------------------------------------------------- rv32ui = simple add addi and andi auipc beq bge bgeu blt bltu bne fence_i \ j jal jalr lb lbu lh lhu lui lw or ori sb sh sw sll slli \ slt slti sra srai srl srli sub xor xori \ rv32um = mul mulh mulhsu mulhu div divu rem remu \ rv32ua = amoadd_w amoand_w amoor_w amoxor_w amoswap_w amomax_w amomaxu_w amomin_w amominu_w \ rv32si = csr ma_fetch scall sbreak wfi \ rv32mi = csr mcsr dirty illegal ma_addr ma_fetch sbreak scall \ rv64ui = $(rv32ui) addw addiw ld lwu sd slliw sllw sltiu sltu sraiw sraw srliw srlw subw \ rv64um = $(rv32um) divuw divw mulw remuw remw \ rv64ua = amoadd_d amoand_d amoor_d amoxor_d amoswap_d amomax_d amomaxu_d amomin_d amominu_d \ rv64uf = ldst move fsgnj fcmp fcvt fcvt_w fclass fadd fdiv fmin fmadd structural \ rv64si = $(rv32si) rv64mi = $(rv32mi) bmarks = median multiply qsort towers vvadd mm dhrystone spmv mt-vvadd mt-matmul #-------------------------------------------------------------------- asm_p_tests += $(addprefix rv64ui-p-, $(rv64ui)) asm_p_tests += $(addprefix rv64ui-p-, $(rv64um)) asm_p_tests += $(addprefix rv64ui-p-, $(rv64ua)) asm_p_tests += $(addprefix rv64uf-p-, $(rv64uf)) asm_p_tests += $(addprefix rv64si-p-, $(rv64si)) asm_p_tests += $(addprefix rv64mi-p-, $(rv64mi)) asm_v_tests += $(addprefix rv64ui-v-, $(rv64ui)) asm_v_tests += $(addprefix rv64ui-v-, $(rv64um)) asm_v_tests += $(addprefix rv64ui-v-, $(rv64ua)) asm_v_tests += $(addprefix rv64uf-v-, $(rv64uf)) bmarks_tests += $(bmarks) #-------------------------------------------------------------------- riscv_test_asm_dir = $(base_dir)/riscv-tests/isa riscv_test_bmarks_dir = $(base_dir)/riscv-tests/benchmarks $(addprefix $(output_dir)/, $(addsuffix .riscv, $(asm_p_tests) $(asm_v_tests))): mkdir -p $(output_dir) $(MAKE) -C $(riscv_test_asm_dir) $(basename $(notdir $@)) ln -fs $(riscv_test_asm_dir)/$(basename $(notdir $@)) $@ $(addprefix $(output_dir)/, $(addsuffix .riscv, $(bmarks_tests))): mkdir -p $(output_dir) $(MAKE) -C $(riscv_test_bmarks_dir) $(basename $(notdir $@)) ln -fs $(riscv_test_asm_dir)/$(basename $(notdir $@)) $@ #-------------------------------------------------------------------- # Run (verilator) #-------------------------------------------------------------------- asm_tests_out = $(foreach test, $(asm_p_tests) $(asm_pt_tests) $(asm_v_tests), $(output_dir)/$(test).out) bmarks_out = $(foreach test, $(bmarks_tests), $(output_dir)/$(test).out) $(output_dir)/%.out: $(output_dir)/%.riscv spike $(SPIKE_FLAGS) $< 2>&1 | spike-dasm > $@ && [ $$PIPESTATUS -eq 0 ] .PRECIOUS: $(output_dir)/%.out run-asm-tests: $(asm_tests_out) run-bmarks-test: $(bmarks_out) run: run-asm-tests run-bmarks-test .PHONY: run-asm-tests run-bmarks-test run junk += $(output_dir) #-------------------------------------------------------------------- # clean up #-------------------------------------------------------------------- clean: rm -rf $(junk) .PHONY: clean <file_sep>cd $TOP/riscv-tools mkdir -p linux-4.6.2 mv -f linux-4.6.2{,-old-`date -Isec`} curl https://www.kernel.org/pub/linux/kernel/v4.x/linux-4.6.2.tar.xz | tar -xJ cd linux-4.6.2 git init git remote add origin https://github.com/lowrisc/riscv-linux.git git fetch git checkout -f -t origin/update_eth patch -p1 < sdhci_minion_sd.patch <file_sep>BUSYBOX=$TOP/riscv-tools/busybox-1.21.1 BUSYBOX_CFG=$TOP/riscv-tools/busybox_config ROOT_INITTAB=$TOP/riscv-tools/inittab LINUX=$TOP/riscv-tools/linux-4.1.25 LINUX_CFG=$TOP/riscv-tools/vmlinux_config echo "build busybox..." cp $BUSYBOX_CFG "$BUSYBOX"/.config make -j$(nproc) -C "$BUSYBOX" 2>&1 1>/dev/null if [ -d ramfs ]; then rm -fr ramfs; fi mkdir ramfs && cd ramfs mkdir -p bin etc dev lib proc sbin sys tmp usr usr/bin usr/lib usr/sbin cp "$BUSYBOX"/busybox bin/ ln -s bin/busybox ./init cp $ROOT_INITTAB etc/inittab # here, copy your program to here echo "\ mknod dev/null c 1 3 && \ mknod dev/tty c 5 0 && \ mknod dev/zero c 1 5 && \ mknod dev/console c 5 1 && \ find . | cpio -H newc -o > "$LINUX"/initramfs.cpio\ " | fakeroot if [ $? -ne 0 ]; then echo "build busybox failed!"; fi echo "build linux..." cp $LINUX_CFG "$LINUX"/.config make -j$(nproc) -C "$LINUX" ARCH=riscv vmlinux 2>&1 1>/dev/null if [ $? -ne 0 ]; then echo "build linux failed!"; fi echo "build bbl..." if [ ! -d $TOP/riscv-tools/riscv-pk/build ]; then mkdir -p $TOP/riscv-tools/riscv-pk/build fi cd $TOP/riscv-tools/riscv-pk/build ../configure \ --host=riscv64-unknown-elf \ --with-payload="$LINUX"/vmlinux \ 2>&1 1>/dev/null make -j$(nproc) bbl 2>&1 1>/dev/null if [ $? -ne 0 ]; then echo "build linux failed!"; fi
9adb7250314b700f2e22c65d559d9001ea293c24
[ "Makefile", "Shell" ]
3
Makefile
GuillemCabo/riscv-tools
61b46d18f693aaaaa829666df3d8e25a1ece2386
9b6279d3e0e687cc55726895ba562fa538f0c206
refs/heads/master
<repo_name>KenadAraujo/sistemasDiarias<file_sep>/index.php <?php require_once ('classes/pagina.php'); //Extende da classe Pagina class Pagina_Principal extends Pagina{ public function exibir_body() { // parent::exibir_body();//Metodo da classe PAI ?> <!-- Conteúdo --> <div id="conteudo"> <!-- Conteúdo Interno --> <div class="container"> <div class="row"> <div class="col-md-5 col-sm-5 col-xs-3"></div> <div class="col-md-2 col-sm-2 col-xs-6"> <img class="img-responsive" src="img/logo_uespi.png"> </div> </div> <div class="row"> <div class="col-sm-4 col-xs-1"></div> <div class="col-sm-4 col-xs-10"> <div class="formulario"> <form autocomplete="off" class="form-signin" action="controller/logica_login.php" method="post"> <strong><h4>Matricula</h4></strong></br> <input type="text" class="form-control entrada" id="inputMatricula" name="matricula"> <strong><h4>Senha</h4></strong></br> <input type="password" id="inputPassword" class="form-control entrada" name="senha"> <?php if(filter_has_var(INPUT_GET, 'resultado')){ if(filter_input(INPUT_GET, 'resultado') == 'erro'){ ?> <div class="alert alert-danger" style="margin-top: 10px;"> <strong>Erro!</strong> Usuário e/ou senha inválidos! </div> <?php } } ?> <input type="submit" class="btn btn-lg btn-primary btn-block botao" value="Entrar"> <input class="btn btn-lg btn-danger btn-block botao" value="Recuperar senha"> </form> </div> </div> </div> </div> <!-- /Conteúdo Interno --> </div><!-- /Conteúdo --> <?php } } $t = new Pagina_Principal(NULL); $t->set_titulo('Pagina inicial'); $t->display(); ?><file_sep>/DAO/CargoDAO.php <?php /** * Description of ClasseDAO * * @author kenad */ require_once('DAO/DAO.php'); require_once('classes/Cargo.php'); class CargoDAO { private $conexao; function __construct($conexao) { $this->conexao = $conexao; } function inserir(Cargo $cargo) { try { $query = "insert into cargo(nome,id_perfil_diaria) values('{$cargo->getNome()}','{$cargo->getPerfilDiaria()->getId()}')"; mysqli_query($conexao, $query); return true; } catch (Exception $ex) { echo $ex->getMessage(); return false; } } function buscarPorId($id) { $query = "select * from cargo where id = '{$id}'"; $resultado = mysqli_query($conexao, $query); $cargos = array(); while($cargo = mysqli_fetch_assoc($resultado)) { array_push($cargos,$cargo); } return $cargo; } function buscarPorNome($nome) { $query = "select * from cargo where nome = '{$nome}'"; $resultado = mysqli_query($conexao, $query); $cargos = array(); while($cargo = mysqli_fetch_assoc($resultado)) { array_push($cargos,$cargo); } return $cargo; } function listarTodos() { $query = "select * from cargo"; $resultado = mysqli_query($this->conexao, $query); $cargos = array(); while($cargo = mysqli_fetch_assoc($resultado)) { array_push($cargos,$cargo); } return $cargos; } } <file_sep>/sistemaDiarias.sql CREATE TABLE `cargo` ( `id` bigint(20) NOT NULL, `nome` varchar(255) NOT NULL, `classe` int(11) NOT NULL, `id_perfil_diaria` bigint(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `endereco` ( `id` bigint(20) NOT NULL, `rua` varchar(255) NOT NULL, `numero` int(11) DEFAULT NULL, `bairro` varchar(255) NOT NULL, `cidade` varchar(255) NOT NULL, `cep` varchar(9) NOT NULL, `estado` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `modalidade_transporte` ( `id` bigint(20) NOT NULL, `nome` varchar(200) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `perfil_diaria` ( `id` bigint(20) NOT NULL, `valor_no_estado` double NOT NULL, `valor_fora_estado` double NOT NULL, `classe` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `projeto` ( `id` bigint(20) NOT NULL, `nome` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `servidor` ( `matricula` varchar(15) NOT NULL, `cpf` varchar(15) NOT NULL, `nome` varchar(255) NOT NULL, `senha` varchar(50) NOT NULL, `id_cargo` bigint(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `trajeto` ( `id` bigint(20) NOT NULL, `saida` bigint(20) NOT NULL, `chegada` bigint(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `diaria_viagem` ( `id` bigint(20) NOT NULL, `quant_dias` int(11) DEFAULT NULL, `objeto_viagem` VARCHAR(500) NOT NULL, `data_inicial` VARCHAR(10) NOT NULL, `data_final` VARCHAR(10) NOT NULL, `relato` VARCHAR(2000) NOT NULL, `id_projeto` bigint(20) NOT NULL, `id_trajeto` bigint(20) NOT NULL, `id_modalidade` bigint(20) NOT NULL, `id_servidor` varchar(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `cargo` ADD PRIMARY KEY (`id`), ADD KEY `id_perfil_diaria` (`id_perfil_diaria`); ALTER TABLE `endereco` ADD PRIMARY KEY (`id`); ALTER TABLE `modalidade_transporte` ADD PRIMARY KEY (`id`); ALTER TABLE `perfil_diaria` ADD PRIMARY KEY (`id`); ALTER TABLE `projeto` ADD PRIMARY KEY (`id`); ALTER TABLE `servidor` ADD PRIMARY KEY (`matricula`), ADD KEY `id_cargo` (`id_cargo`); ALTER TABLE `trajeto` ADD PRIMARY KEY (`id`), ADD KEY `saida` (`saida`), ADD KEY `chegada` (`chegada`); ALTER TABLE `diaria_viagem` ADD PRIMARY KEY(`id`), ADD KEY `id_projeto` (`id_projeto`), ADD KEY `id_trajeto` (`id_trajeto`), ADD KEY `id_modalidade` (`id_modalidade`), ADD KEY `id_servidor` (`id_servidor`); ALTER TABLE `cargo` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; ALTER TABLE `endereco` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; ALTER TABLE `modalidade_transporte` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; ALTER TABLE `perfil_diaria` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; ALTER TABLE `projeto` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; ALTER TABLE `trajeto` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; ALTER TABLE `diaria_viagem` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; ALTER TABLE `cargo` ADD CONSTRAINT `cargo_ibfk_1` FOREIGN KEY (`id_perfil_diaria`) REFERENCES `perfil_diaria` (`id`); ALTER TABLE `servidor` ADD CONSTRAINT `servidor_ibfk_1` FOREIGN KEY (`id_cargo`) REFERENCES `cargo` (`id`); ALTER TABLE `trajeto` ADD CONSTRAINT `trajeto_ibfk_1` FOREIGN KEY (`saida`) REFERENCES `endereco` (`id`), ADD CONSTRAINT `trajeto_ibfk_2` FOREIGN KEY (`chegada`) REFERENCES `endereco` (`id`); ALTER TABLE `diaria_viagem` ADD CONSTRAINT `viagem_ibfk_1` FOREIGN KEY (`id_projeto`) REFERENCES `projeto` (`id`), ADD CONSTRAINT `viagem_ibfk_2` FOREIGN KEY (`id_trajeto`) REFERENCES `trajeto` (`id`), ADD CONSTRAINT `viagem_ibfk_3` FOREIGN KEY (`id_modalidade`) REFERENCES `modalidade_transporte` (`id`), ADD CONSTRAINT `viagem_ibfk_4` FOREIGN KEY (`id_servidor`) REFERENCES `servidor`(`matricula`); ALTER TABLE `servidor` ADD `email` VARCHAR(255) NOT NULL AFTER `cpf`; INSERT INTO `perfil_diaria` (`id`, `valor_no_estado`, `valor_fora_estado`, `classe`) VALUES (NULL, '172.50', '345.00', 'I'), (NULL, '120.00', '240.00', 'II'), (NULL, '75', '150', 'III'); INSERT INTO `cargo` (`id`, `nome`, `classe`, `id_perfil_diaria`) VALUES (NULL, 'SECRETÁRIOS', '1', '1'), (NULL, 'PROCURADOR GERAL', '1', '1'), (NULL, 'DEFENSOR GERAL', '1', '1'), (NULL, 'CONTROLADOR GERAL', '1', '1'), (NULL, 'DIRETOR GERAL', '1', '1'), (NULL, 'CONTROLADOR GERAL', '1', '1'), (NULL, 'DIRETOR GERAL', '1', '1'), (NULL, 'PRESIDENTE', '1', '1'), (NULL, 'SUPERINTENDENTES', '1', '1'), (NULL, 'COORDENADORES GERAIS', '1', '1'), (NULL, 'DIREÇÃO E ASSESSORAMENTO SUPERIOR - DAS', '2', '2'), (NULL, 'PILOTOS', '2', '2'), (NULL, 'VICE-PRESIDENTE', '2', '2'), (NULL, 'SECRETÁRIO GERAL', '2', '2'), (NULL, 'DELEGADO GERAL', '2', '2'), (NULL, 'DIRETOR DE GESTÃO INTERNA', '2', '2'), (NULL, 'TÉCNICOS DE NIVEL SUPERIOR', '2', '2'), (NULL, 'DEMAIS DIRENTES', '2', '2'), (NULL, 'OUTRAS FUNÇÕES', '3', '3'), (NULL, 'MILITAR - COMANDANTE E SUBCOMANDANTE', '1', '1'), (NULL, 'MILITAR - OFICIAIS', '2', '2'), (NULL, 'MILITAR - PRAÇAS', '3', '3'); ALTER TABLE cargo DROP COLUMN classe;<file_sep>/DAO/DAO.php <?php /** * Description of DAO * * @author kenad */ class DAO { private $con; function getConexao(){ $this->con = new mysqli('localhost', 'root', '', 'sistemadiarias'); $this->con->set_charset("utf8"); if(mysqli_connect_errno()){ echo 'Codigo do erro '. mysqli_connect_errno(); exit(); } $this->con->set_charset("utf8"); return $this->con; } function fecharConexao(){ return $this->con->close(); } } <file_sep>/classes/pagina.php <?php class Pagina { private $titulo; private $servidorLogado; function Pagina(){ $this->titulo = "Titulo da pagina"; } function getServidorLogado() { return $this->servidorLogado; } final function display(){ echo "<!DOCTYPE html>\n"; echo "<html lang='pt-br'>\n"; echo "<head>\n"; $this->exibir_titulo(); $this->exibir_config(); echo "</head>\n<body>\n"; $this->exibir_body(); echo "</body>\n</html>"; } final function set_titulo($titulo){ $this->titulo = $titulo; } function exibir_titulo(){ echo "<title>".$this->titulo."</title>\n"; } private function exibir_config(){ ?> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="bootstrap/css/bootstrap.css"> <link rel="stylesheet" href="css/estilo.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <?php } function exibir_body(){ $this->exibir_navbar(); } function exibir_navbar(){ ?> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Sistemas Diarias</a> </div> <ul class="nav navbar-nav"> <li class="active"><a href="pagina_principal.php">Home</a></li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Servidores <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="cadastro_servidores.php">Cadastrar Servidor</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Diaria <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Solicitar</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Perfil Diaria <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="cadastro_perfil_de_diaria.php">Cadastrar</a></li> </ul> </li> </ul> </div> </nav> <!--Login Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog modal-xg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Entrar no sistema</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email"> </div> <div class="form-group"> <label for="senha">Senha:</label> <input type="<PASSWORD>" class="form-control" id="senha"> </div> <div class="checkbox"> <label><input type="checkbox" class="checkbox" disabled>Lembrar-me</label> </div> <div class="row"> <div class="col-xs-1"></div> <button type="submit" class="btn btn-success col-xs-5">Login</button> <div class="col-xs-4"> <a href="#"> <button class="btn btn-warning">Esqueci a senha</button> </a> </div> </div> </form> </div> <div class="modal-footer row"> <div class="col-xs-3"> <a href="cadastro_servidores.php"> <button class="btn btn-default">Não possuo cadastro</button> </a> </div> <div class="col-xs-5"> </div> <div class="col-xs-3"> <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button> </div> </div> </div> </div> </div> <?php } } ?><file_sep>/DAO/ServidorDAO.php <?php //require_once '../classes/Servidor.php'; require_once 'DAO.php'; class ServidorDAO{ private $conexao; public function __construct($conexao) { $this->conexao = $conexao; } public function inserir_servidor(Servidor $servidor){ try{ $con = $this->conexao; $query = "INSERT INTO servidor (matricula, cpf, email, nome, senha, id_cargo) VALUES (?,?,?,?,?,?)"; $stmt = $con->prepare($query); $nome = mysqli_real_escape_string($con,$servidor->getNome()); $cpf = mysqli_real_escape_string($con,$servidor->getCpf()); $senha = mysqli_real_escape_string($con,$servidor->getSenha()); $matricula = mysqli_real_escape_string($con,$servidor->getMatricula()); $email = mysqli_real_escape_string($con,$servidor->getEmail()); $cargo = mysqli_real_escape_string($con,intval($servidor->getCargo())); $query = "INSERT INTO servidor (matricula, cpf, email, nome, senha, id_cargo) VALUES ('{$matricula}','{$cpf}','{$email}','{$nome}','{$senha}','{$cargo}')"; /*if ($con->query($query) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $con->error; }*/ $stmt->bind_param("sssssi",$matricula,$cpf,$email,$nome,$senha,$cargo); if(!$stmt->execute()){ return false; } $stmt->close(); return true; } catch (Exception $e) { echo $e->getMessage(); return false; } } public function buscarPorMatricula($matricula) { $query = "SELECT * FROM servidor WHERE matricula = '{$matricula}'"; $resultado = mysqli_query($this->conexao, $query); $servidores = array(); while($servidor = mysqli_fetch_assoc($resultado)) { array_push($servidores,$servidor); } return $servidores; } }
45d9a639795415169d5c1c825cea07bc35c94a80
[ "SQL", "PHP" ]
6
PHP
KenadAraujo/sistemasDiarias
489a327d366dd597dd26a1c0b0b16b8e6e56a5cd
e9c79c94f7f43d47002d64a6ee69e1f7ffe5c916
refs/heads/master
<file_sep>#pragma once #include "board.h" #define DRAM_START ((void*) 0xC0000000) void dram_init(void); <file_sep>#pragma once #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include "usbdfu.h" size_t target_get_max_fw_size(void); uint16_t target_get_timeout(void); void target_flash_unlock(void); enum dfu_status target_flash_write(uint8_t* dst, uint8_t* src, size_t len); enum dfu_status target_prepare_flash(void); void target_flash_lock(void); enum dfu_status target_complete_programming(void); <file_sep>#pragma once #include <stdint.h> #include <stddef.h> extern uint8_t* firmware_buffer; extern size_t firmware_size; <file_sep>#include "dfu_target.h" #include "usbdfu.h" #include "ch.h" #include "hal.h" #include <string.h> static size_t last_program_addr = 0; size_t target_get_max_fw_size(void) { return MAX_FLASH_ADDR - APP_BASE; } uint16_t target_get_timeout(void) { if (last_program_addr == 0) { return 6000; } return 25; } void target_flash_unlock(void) { osalSysLockFromISR(); FLASH->KEYR = 0x45670123; // KEY 1 FLASH->KEYR = 0xCDEF89AB; // KEY 2 } enum dfu_status target_flash_write(uint8_t* dst, uint8_t* src, size_t len) { last_program_addr = (size_t)dst; if (FLASH->CR & FLASH_CR_LOCK) { return DFU_STATUS_ERR_CHECK_ERASED; // Still locked after unlock. Can't recover from this unless reset. } // We are 3.3V powered, we need to write to 4 byte aligned address if (((size_t)dst % sizeof(uint32_t) != 0) || ((size_t)src % sizeof(uint32_t) != 0) || (len % sizeof(uint32_t) != 0)) { return DFU_STATUS_ERR_ADDRESS; } while(FLASH->SR & FLASH_SR_BSY) {} FLASH->CR = FLASH_CR_PG | FLASH_CR_PSIZE_1; for (size_t i = 0; i < len / sizeof(uint32_t); ++i) { ((uint32_t*)dst)[i] = ((uint32_t*)src)[i]; while(FLASH->SR & FLASH_SR_BSY){} } FLASH->CR = 0; return DFU_STATUS_OK; } enum dfu_status target_prepare_flash(void) { // Erase the whole flash from sector 1 onward (Sector 1 is bootloader itself) if (FLASH->CR & FLASH_CR_LOCK) { return DFU_STATUS_ERR_CHECK_ERASED; // Still locked after unlock. Can't recover from this unless reset. } while(FLASH->SR & FLASH_SR_BSY){} // Wait for not busy for (uint32_t i = 1; i < 12; ++i) { FLASH->CR = FLASH_CR_PSIZE_1 | FLASH_CR_SER | (i << FLASH_CR_SNB_Pos) | FLASH_CR_STRT; while(FLASH->SR & FLASH_SR_BSY){} if (FLASH->SR & (0xF << FLASH_SR_WRPERR_Pos)) { *(volatile int*)i; return DFU_STATUS_ERR_ERASE; // Error while erasing } } return DFU_STATUS_OK; } void target_flash_lock(void) { FLASH->CR = FLASH_CR_LOCK; // LOCK Flash osalSysUnlockFromISR(); } enum dfu_status target_complete_programming(void) { return DFU_STATUS_OK; } <file_sep>#include "firmware_update.h" uint8_t* firmware_buffer = (uint8_t*) 0xC0000000; size_t firmware_size = 1; <file_sep>/** * @defgroup MAIN main * * @brief Program main for mTrain bootloader * * @author Codetector * @date 2020 */ #include "ch.h" #include "hal.h" #include "dram.h" #include "usbdfu.h" #include "firmware_update.h" /* * Application entry point. */ int main(void) { /* * System initializations. * - HAL initialization, this also initializes the configured device drivers * and performs the board-specific initializations. * - Kernel initialization, the main() function becomes a thread and the * RTOS is active. */ halInit(); chSysInit(); // Init DRAM as early as possible dram_init(); usbStart(&USBD2, &usbcfg); usbDisconnectBus(&USBD2); for (int i = 0; i < 15; ++i) { chThdSleepMilliseconds(100); palToggleLine(LINE_LED_USB); } usbConnectBus(&USBD2); palSetLine(LINE_LED_USB); /* * Normal main() thread activity, in this demo it does nothing except * sleeping in a loop and check the button state. */ while (true) { chThdSleepMilliseconds(500); } } <file_sep>#include "dram.h" #include "ch.h" #include "hal.h" #include <stdint.h> // DRAM begins at 0xC000_0000 // 256Mbits = 32MBytes // Ends at 0xC1FF_FFFF // // 16 bit Access Width // Row Bits: 13 // Column Bits: 9 // Bank Count: 4 // FMC_Bank5_6 void dram_init(void) { // DAMM EMABLE FMC CLOCK!!!!! RCC->AHB3ENR |= 0x1; // 1. Program memory device feature into FMC_SDCRx FMC_Bank5_6->SDCR[0] = 0 |1 << FMC_SDCR1_NC_Pos // 9 Bit Column Addr |2 << FMC_SDCR1_NR_Pos // 13 Row Bits |1 << FMC_SDCR1_MWID_Pos // 16-bit width |1 << FMC_SDCR1_NB_Pos // 4 Banks |3 << FMC_SDCR1_CAS_Pos // 3 CAS Cycle |3 << FMC_SDCR1_SDCLK_Pos // SDCLK = HCLK/3 |1 << FMC_SDCR1_RBURST_Pos ; // 2.Program Timing into FMC_SDTRx FMC_Bank5_6->SDTR[0] = 0 | 2 << FMC_SDTR2_TMRD_Pos // tMRD: 2 tCK | 7 << FMC_SDTR1_TXSR_Pos // tXSR: 7 tCK | 4 << FMC_SDTR1_TRAS_Pos // tRAS: 5 tCK | 7 << FMC_SDTR1_TRC_Pos // tRC: tCK | 2 << FMC_SDTR1_TWR_Pos // tWR: 2 tCK | 2 << FMC_SDTR1_TRP_Pos // tRP: 2 tCK | 2 << FMC_SDTR1_TRCD_Pos // tRCD: 2 tCK ; // 3. Derive Clock Start while(FMC_Bank5_6->SDSR & FMC_SDSR_BUSY); FMC_Bank5_6->SDCMR = 0 |0b001 << FMC_SDCMR_MODE_Pos // Clock Configuration Mode |FMC_SDCMR_CTB1 // Bank 1 enable ; chThdSleepMilliseconds(1); while(FMC_Bank5_6->SDSR & FMC_SDSR_BUSY); // 5. Precharge All FMC_Bank5_6->SDCMR = 0 |0b010 << FMC_SDCMR_MODE_Pos // Pre-Charge |FMC_SDCMR_CTB1 // Bank 1 enable ; while(FMC_Bank5_6->SDSR & FMC_SDSR_BUSY); // 6. Auto-Refresh FMC_Bank5_6->SDCMR = 0 |0b011 << FMC_SDCMR_MODE_Pos // Auto Refresh | 7 << FMC_SDCMR_NRFS_Pos // Issue 8 Auto Refresh |FMC_SDCMR_CTB1 // Bank 1 enable ; while(FMC_Bank5_6->SDSR & FMC_SDSR_BUSY); // 7. Configure MODE Register // Register value: // 12 .............................. 0 // 0 0 0 | 0 | 0 0 | 0 1 0 | 0 | 0 0 0 // RES | WB| OPM | CAS |BT | BL=1 FMC_Bank5_6->SDCMR = 0 |0b100 << FMC_SDCMR_MODE_Pos // Issue Mode Register Set |0b110000 << FMC_SDCMR_MRD_Pos // |FMC_SDCMR_CTB1 // Bank 1 enable ; while(FMC_Bank5_6->SDSR & FMC_SDSR_BUSY); FMC_Bank5_6->SDRTR = 400 << FMC_SDRTR_COUNT_Pos // LMAO It's well in the safe range |FMC_SDRTR_CRE; }
cb11d2d6417861eba8593719f19b4ee7621d8029
[ "C" ]
7
C
RoboJackets/mtrain-bootloader
4ecc4c89266ba78e0edb044d3b331883e457978e
fa03150f225991cfa3a9bbfeebbfc036c549117b
refs/heads/master
<repo_name>mmangino/tunnlr_connector<file_sep>/lib/tunnlr.rb require 'tunnlr/connector' require 'tunnlr/configurator' module Tunnlr puts 'Loaded' def self.load_tasks Dir[File.expand_path("tasks/*.rake", File.dirname(__FILE__))].each { |ext| load ext } end require 'tunnlr/railtie' if defined?(Rails) && Rails::VERSION::MAJOR >= 3 end <file_sep>/lib/tunnlr/ui.rb require 'wx' module Tunnlr module Ui class MainApp < Wx::App def on_init # we're defining what the application is going to do when it starts t = Wx::Timer.new(self, 55) evt_timer(55) { Thread.pass } t.start(100) helloframe = Wx::Frame.new(nil, -1, "Tunnlr") # it's going to make a frame entitled "Hello World" @tunnlr=Tunnlr::Connector.new @start = Wx::Button.new(helloframe,-1,"Start Tunnel") @stop = Wx::Button.new(helloframe,-1,"Stop Tunnel") @configure = Wx::Button.new(helloframe,-1,"Configure") @start.evt_button(@start.id) do |event| Thread.new do begin @tunnlr.connect! rescue Exception => e puts e end end @start.hide() @stop.show() end @stop.evt_button(@stop.id) do |event| @tunnlr.disconnect! @stop.hide() @start.show() end @start.show() @stop.hide() @configure.evt_button(@configure.id) do |event| ConfigureDialog.new.show_modal end helloframe.show() # and then it's going to make the window appear end end class ConfigureDialog < Wx::Dialog def initialize end end end end<file_sep>/bin/tunnlr #!/usr/bin/env ruby -ws require 'rubygems' require 'tunnlr' class Rails def self.root @root end def self.root=(val) @root=val end end Rails.root = Dir.pwd Tunnlr::Connector.new.connect! <file_sep>/lib/tunnlr_connector.rb require "tunnlr" module TunnlrConnector end <file_sep>/init.rb require 'tunnlr' <file_sep>/lib/tunnlr/railtie.rb require 'tunnlr' require 'rails' module Tunnlr class Railtie < Rails::Railtie rake_tasks do Tunnlr.load_tasks end end end<file_sep>/tunnlr_connector.gemspec # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{tunnlr_connector} s.version = "1.0.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>"] s.date = %q{2010-04-06} s.description = %q{A simple plugin to make your local developnment environment available to the internet using the tunnlr.com service} s.email = ["<EMAIL>"] s.files = Dir['lib/**/*'] + ["init.rb","README","MIT-LICENSE"] + Dir["rails/**"] + Dir["bin/**"] s.homepage = %q{http://tunnlr.com} s.require_paths = ["lib"] s.rubyforge_project = %q{tunnlr_connector} s.rubygems_version = %q{1.3.5} s.summary = %q{Provide access to the tunnlr.com service} s.bindir = 'bin' s.executables = ['tunnlr'] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<net-ssh>, [">= 2.0.15"]) s.add_runtime_dependency(%q<highline>, [">= 1.5.0"]) else s.add_dependency(%q<net-ssh>, [">= 2.0.15"]) s.add_dependency(%q<highline>, [">= 1.5.0"]) end else s.add_dependency(%q<net-ssh>, [">= 2.0.15"]) s.add_dependency(%q<highline>, [">= 1.5.0"]) end end <file_sep>/lib/tasks/tunnlr_connector_tasks.rake namespace :tunnlr do desc "Create a tunnel" task :start => :environment do Tunnlr::Connector.new.connect! end desc "Write the tunnlr.yml file to your apps config directory" task :configure => :environment do Tunnlr::Configurator.new.configure(File.join(Rails.root,"config","tunnlr.yml")) end desc "Tunnlr UI requires the rubywx library" task :ui => :environment do require 'tunnlr/ui' Tunnlr::Ui::MainApp.new.main_loop end end<file_sep>/lib/tunnlr/connector.rb require 'yaml' require 'net/ssh' module Tunnlr class Connector def initialize @config = read_configuration @should_disconnect =false end def connect! @should_disconnect=false while true do begin Net::SSH.start(host,username,:password=><PASSWORD>) do |ssh| puts "Connecting to #{username}@#{host} and sending #{remote_port}->#{local_port}" ssh.forward.remote_to(local_port,'127.0.0.1',remote_port,'0.0.0.0') puts "You can view your tunneled connection at http://web1.tunnlr.com:#{remote_port}/" while true begin ssh.loop {!@should_disconnect} rescue Errno::ECONNRESET=>e raise rescue Interrupt=>e raise rescue Exception=>e puts "Swallowing: #{e.class.to_s} => #{e.to_s}" end end end rescue Errno::ECONNRESET=>e puts "Your connection was reset, trying to restart ..." end end rescue Net::SSH::AuthenticationFailed=>e puts "Unable to log in. Please check your password and try again." end def disconnect! @should_disconnect=true end def read_configuration path = File.join(Rails.root, "config/tunnlr.yml") YAML.load(File.read(path)) end def method_missing(name,*args) if @config[name.to_s] @config[name.to_s] else super end end end end <file_sep>/lib/tunnlr/configurator.rb require 'highline' require 'net/ssh' require "net/http" module Tunnlr class Configurator attr_accessor :not_configured,:email,:password,:subdomain def initialize @ui = HighLine.new @not_configured=true end def fetch(subdomain,username,password) url=URI.parse("https://#{subdomain}.tunnlr.com/configuration.yml") req = Net::HTTP::Get.new(url.path) req.basic_auth(username,password) res = Net::HTTP.start(url.host, url.port, :verify_mode => OpenSSL::SSL::VERIFY_NONE, :use_ssl => url.scheme == 'https') {|http| http.request(req) } @configuration = res.body end def add_password @configuration.gsub!(/PASSWD/,password) end def write_config(path) puts "Going to write: #{@configuration}" open(path,"w+") do |f| f.puts(@configuration) end end def get_credentials puts "Enter the email address and password you used to sign up for Tunnlr." self.subdomain = @ui.ask("Subdomain (i.e. elevatedrails for elevatedrails.tunnlr.com): ") self.email = @ui.ask("Email: ") self.password = @ui.ask("Password: ") { |q| q.echo = false } fetch(subdomain,email,password) end def configure(path) while not_configured begin get_credentials fetch(subdomain, email,password) add_password write_config(path) puts "Created configuration in #{path}" self.not_configured=false rescue Net::HTTPNotAcceptable=>e puts "Login failed, please try again" end end end end end
01033a14743e1dc56426de7de74fe448b1039192
[ "Ruby" ]
10
Ruby
mmangino/tunnlr_connector
2ae02958d0b6804cd41917ff9fef3a28a5930fb0
a36f2b5a46e32521e076a3659a3906323e607529
refs/heads/master
<file_sep>from django.db.backends.base.features import BaseDatabaseFeatures from django.db.utils import InterfaceError class DatabaseFeatures(BaseDatabaseFeatures): supports_partial_indexes = False supports_functions_in_partial_indexes = False supports_regex_backreferencing = False can_return_columns_from_insert = True supports_transactions = True can_introspect_small_integer_field = True closed_cursor_error_class = InterfaceError has_case_insensitive_like = False implied_column_null = True ignores_table_name_case = True truncates_names = True bare_select_suffix = " FROM RDB$DATABASE" supports_sequence_reset = False supports_subqueries_in_group_by = False supports_partially_nullable_unique_constraints = False supports_mixed_date_datetime_comparisons = False can_introspect_autofield = True supports_over_clause = True has_bulk_insert = False can_introspect_duration_field = False supports_timezones = False has_zoneinfo_database = False supports_select_intersection = False supports_select_difference = False supports_ignore_conflicts = False can_create_inline_fk = False supports_atomic_references_rename = False supports_column_check_constraints = False supports_table_check_constraints = False can_introspect_check_constraints = False max_query_params = 999 connection_persists_old_columns = True supports_index_column_ordering = False supports_index_on_text_field = False supports_forward_references = False
206a37e9f2952a93bde507c817f34a16c09bccad
[ "Python" ]
1
Python
toninhonunes/djfirebirdsql
878396979896c875b0924ff1e4c69494fc5fa897
c3c2c2a2180e5ebc4eaf6b6bcef656e85f62047d
refs/heads/master
<repo_name>dennisscho/sencha-app<file_sep>/app/view/ToDoList.js Ext.define('ToDo.view.ToDoList', { extend: 'Ext.dataview.List', alias: 'widget.todolist', config: { itemTpl: '{title}', emptyText: "No ToDo\'s left!", loadingText: "Loading...", disableSelection: true, onItemDisclosure: true } });<file_sep>/app/view/Main.js Ext.define('ToDo.view.Main', { extend: 'Ext.Container', xtype: 'main', alias: 'widget.maincontainer', initialize: function() { this.callParent(arguments); var sortButton = { xtype: 'button', ui: 'action', text: 'Sort', handler: this.onSortButtonTap, scope: this }; var newButton = { xtype: 'button', ui: 'action', text: 'New', handler: this.onNewButtonTap, scope: this }; var topToolbar = { xtype: 'toolbar', docked: 'top', title: 'ToDo', items: [sortButton, { xtype: 'spacer' }, newButton ] }; var todoList = { xtype: 'todolist', store: Ext.getStore('ToDos'), listeners: { disclose: { fn: this.onToDoDisclose, scope: this } } }; this.add([topToolbar, todoList]); }, config: { layout: { type: 'fit' } }, onNewButtonTap: function() { this.fireEvent('newToDo', this); }, onToDoDisclose: function(list, record, target, index, event, options) { this.fireEvent('toDoDisclose', this, record); }, onSortButtonTap: function(){ this.fireEvent('sort', this); } });<file_sep>/app/view/ToDoEditor.js Ext.define('ToDo.view.ToDoEditor', { extend: 'Ext.form.Panel', alias: 'widget.todoeditor', requires: ['Ext.form.FieldSet', 'Ext.field.DatePicker', 'Ext.field.Slider'], initialize: function() { this.callParent(arguments); //Hinzufuegen von Komponenten zur GUI var backButton = { xtype: 'button', text: 'Back', ui: 'back', handler: 'onBackButtonTap', scope: this }; var saveButton = { xtype: 'button', text: 'Save', ui: 'action', handler: 'onSaveButtonTap', scope: this }; var topToolbar = { xtype: 'toolbar', docked: 'top', title: 'New ToDo', items: [backButton, { xtype: 'spacer' }, saveButton] }; var titleTextField = { xtype: 'textfield', label: 'Title', required: true, name: 'title' }; var descriptionTextArea = { xtype: 'textareafield', label: 'Description', name: 'description' }; //FieldSets fassen mehrere Formularelemente zusammen var toDoFieldSet = { xtype: 'fieldset', title: 'ToDo Information', items: [titleTextField, descriptionTextArea] }; var deleteButton = { xtype: 'button', text: 'Delete', ui: 'decline', handler: 'onDeleteButtonTap', scope: this }; var datePickerField = { xtype: 'datepickerfield', label: 'Date', name: 'date', picker: { xtype: 'datepicker', yearFrom: 2015, yearTo: 2030 } }; var datePickerFieldSet = { xtype: 'fieldset', items: [datePickerField] }; var prioritySlider = { xtype: 'sliderfield', value: 1, minValue: 1, maxValue: 10, name: 'priority', label: 'Priority' }; var prioritySliderFieldSet = { xtype: 'fieldset', items: [prioritySlider] }; this.add([topToolbar, toDoFieldSet, datePickerFieldSet, prioritySliderFieldSet, deleteButton]); }, onBackButtonTap: function() { this.fireEvent('backToMain', this); }, onSaveButtonTap: function() { this.fireEvent('saveToDo', this); }, onDeleteButtonTap: function() { this.fireEvent('deleteToDo', this); } });<file_sep>/app/controller/MainController.js Ext.define('ToDo.controller.MainController', { extend: 'Ext.app.Controller', requires: 'Ext.ActionSheet', config: { refs: { mainContainer: 'maincontainer', toDoEditor: 'todoeditor', calendar: 'todocalendar' }, control: { mainContainer: { newToDo: 'onNewToDo', toDoDisclose: 'onToDoDisclose', sort: 'onSort' } } }, launch: function() { this.callParent(arguments); Ext.getStore('ToDos').load(); }, onNewToDo: function() { this.transferToDoToEditor(); this.transitionToToDoEditor(); }, transferToDoToEditor: function() { var newToDo = Ext.create('ToDo.model.ToDo', { title: '' }); this.getToDoEditor().setRecord(newToDo); }, leftSlide: { type: 'slide', direction: 'left' }, transitionToToDoEditor: function() { var toDoEditor = this.getToDoEditor(); Ext.Viewport.animateActiveItem(toDoEditor, this.leftSlide); }, onToDoDisclose: function(list, record){ this.getToDoEditor().setRecord(record); this.transitionToToDoEditor(); }, onSort: function(){ var sortActionSheet = Ext.create('Ext.ActionSheet', { items: [{ text: 'Sort by priority', handler: this.sortByPriority, scope: this }, { text: 'Sort by date', handler: this.sortByDate, scope: this },{ text: 'cancel', ui: 'decline' }], defaults: { listeners: { tap: function(){ sortActionSheet.hide(); } } }, hidden: true }); Ext.Viewport.add(sortActionSheet); sortActionSheet.show(); }, sortByPriority: function(){ Ext.getStore('ToDos').sort('priority', 'DESC'); }, sortByDate: function(){ Ext.getStore('ToDos').sort('date', 'ASC'); } });<file_sep>/app/controller/ToDoEditorController.js Ext.define('ToDo.controller.ToDoEditorController', { extend: 'Ext.app.Controller', config: { refs: { toDoEditor: 'todoeditor', mainContainer: 'maincontainer' }, control: { toDoEditor: { backToMain: 'onBackToMain', saveToDo: 'onSaveToDo', deleteToDo: 'onDeleteToDo' } } }, slideRight: { type: 'slide', direction: 'right' }, onBackToMain: function() { this.transitionToMain(); }, transitionToMain: function() { var mainContainer = this.getMainContainer(); Ext.Viewport.animateActiveItem(mainContainer, this.slideRight); }, onSaveToDo: function() { this.setNewValuesForToDo(); if (this.toDoHasErrors()) { return; } this.addToDoToStore(); this.transitionToMain(); }, setNewValuesForToDo: function() { var toDoEditor = this.getToDoEditor(); var currentToDo = toDoEditor.getRecord(); var newValues = toDoEditor.getValues(); currentToDo.set('title', newValues.title); currentToDo.set('description', newValues.description); currentToDo.set('date', newValues.date); currentToDo.set('priority', newValues.priority); }, toDoHasErrors: function() { var toDoEditor = this.getToDoEditor(); var currentToDo = toDoEditor.getRecord(); var errors = currentToDo.validate(); if (!errors.isValid()) { Ext.Msg.alert('Error!', errors.getByField('title')[0].getMessage(), Ext.emptyFn); currentToDo.reject(); return true; } else { return false; } }, addToDoToStore: function() { var toDoEditor = this.getToDoEditor(); var currentToDo = toDoEditor.getRecord(); var toDoStore = Ext.getStore('ToDos'); toDoStore.add(currentToDo); toDoStore.sync(); }, removeToDoFromStore: function(){ var toDoEditor = this.getToDoEditor(); var currentToDo = toDoEditor.getRecord(); var toDoStore = Ext.getStore('ToDos'); toDoStore.remove(currentToDo); toDoStore.sync(); }, onDeleteToDo: function(){ this.removeToDoFromStore(); this.transitionToMain(); } });
ffa7a1ab4cd12111dcedbcc411f009671400a532
[ "JavaScript" ]
5
JavaScript
dennisscho/sencha-app
50556053d283199b251d4e819138defb0168c68e
e973758106b8b53b1e9639a3c27368cff9571f30
refs/heads/master
<file_sep>// dependencies const express = require('express'); const url = require('url'); var cors = require('cors'); //create the server const app = express(); const port = 3002; app.use(cors()) let tableOfContent = [{id: 1, name: 'The supermarket'}, {id: 2, name: 'Outdoor'}, {id: 3, name: 'houses'}]; let toc = "HI?" let images = [{id:23, name:'the-supermarket.png', themeId: 1}, {id:24, name:'outdoor-clothes.png', themeId: 2}, {id:25, name:'houses.png', themeId: 3}]; let words = [{id: 1, name: 'scale', X: 120, Y: 250, number: 7, themeId: 1, imageId: 23}, {id: 2, name: 'aisle', X: 450, Y: 230, number: 10, themeId: 1, imageId: 23}]; function stepOne() { var themes = document.getElementById("browsers"); var option = document.createElement("option"); option.text = toc; themes.appendChild(option); } // the methods app.get('/', (request, response) => { response.send('This is picture dictionary service.'); var themes = document.getElementById("browsers"); for (var i in images) { var option = document.createElement("option"); option.text = i.name; themes.add(option); }; }); app.use(express.static("../ista330.sp20.pictureDictionary")) app.get('/words/:contentId/:imageId/:objectX/:objectY', (request, response) => { let themeId = Number(request.params.contentId); let imageId = Number(request.params.imageId); let objectX = Number(request.params.objectX); let objectY = Number(request.params.objectY); // TODO: let word = words.find(x => x.themeId === themeId && x.imageId === imageId && x.X === objectX && x.Y === objectY); if(word) { response.json({name: word.name, number: word.number}); } else { response.status(404).send('No word was found.'); } }); app.get('/pages/:contentId/image/:imageId', (request, response) => { let themeId = Number(request.params.contentId); let imageId = Number(request.params.imageId); let image = images.find(x => x.themeId === themeId && x.id === imageId); if(image) { response.sendFile(__dirname + '/data/' + image.name); } else { response.status(404).send('No images were found.'); } }); app.get('/contents', (request, response) => { response.json(tableOfContent); }); app.get('/pages/:contentId', (request, response) => { let themeId = Number(request.params.contentId); let ids = images.filter(x => x.themeId === themeId) .map(x => x.id); response.json(ids); }); // start the server app.listen(port, () => console.log('Listening on port ' + port)); <file_sep>'use strict'; require('dotenv').config(); const {Pool}=require('pg'); const isProduction = process.env.IS_PRODUCTION.toLowerCase()==='true'; console.log(process.env.IS_PRODUCTION); console.log("Is this the production environment? ${isProduction?'yes':'no'}");
ea8028491301a0e4f5dba1c8acb3380087c09b4c
[ "JavaScript" ]
2
JavaScript
olivertr98/picture_dictionary_service
4c19dbbdcb83b37daf70126cd9fbeb9c0e3c83d6
3fd7941d1e31d6d2cfb25322d0ed3078b27b91c3
refs/heads/master
<file_sep># levitator Magnetic levitation experiment using Arduino to control electromagnetic coil based on light reflection feedback <file_sep>/* Name: Levitator.ino Created: 10/11/2016 8:25:24 PM Author: Andrei */ int initialDistance; // the setup function runs once when you press reset or power the board void setup() { // this pin is used to control coil power through PWM pinMode(PIN3, OUTPUT); analogWrite(PIN3, 0); // these two pins are used to control current direction through the coil digitalWrite(PIN1, LOW); pinMode(PIN1, OUTPUT); digitalWrite(PIN2, HIGH); pinMode(PIN2, OUTPUT); pinMode(PIN_A0, INPUT); // wait for power to stabilize delay(100); // read initial distance from our sensor to the magnet initialDistance = analogRead(PIN_A0); } // the loop function runs over and over again until power down or reset void loop() { // wait 1ms (1/1000 of a second) every iteration delayMicroseconds(1000); // read current distance from sensor to magnet int currentDistance = analogRead(PIN_A0); // calculate difference between initial and current distance int difference = currentDistance - initialDistance; if (difference > 0) { // if the difference is more than initial, set one direction digitalWrite(PIN1, HIGH); digitalWrite(PIN2, LOW); } else // (difference <= 0) { // otherwise, set another direction digitalWrite(PIN1, LOW); digitalWrite(PIN2, HIGH); // then make sure the "difference" value is not negative difference = -difference; } // multiply difference by 2 to get higher amplitude of output signal int pwmValue = difference * 4; // make sure it does not exceed maximum of 255 if (pwmValue > 255) pwmValue = 255; analogWrite(PIN3, pwmValue); }
f2d2dc3bd848b60cbba55019db572bcc698d8feb
[ "Markdown", "C++" ]
2
Markdown
andreitanas/levitator
bd3ea191054046fc6145d85db0c8d36452c78e6e
a72430fdea38b768569537eb9f0c7aca993a18ea
refs/heads/main
<file_sep>package com.decagon.jones.notificationactivities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import org.w3c.dom.Text class NotifiedActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_notified) init() } fun init(){ val statusTextView: TextView = findViewById<TextView>(R.id.status_text_view).apply { setText(getIntent().getStringExtra("status")) if(getIntent().getStringExtra("status")=="Inactive") setTextColor(resources.getColor(R.color.red)) else if(getIntent().getStringExtra("status")=="Active"){ setTextColor(resources.getColor(R.color.teal_700)) } } val backButton : Button = findViewById<Button>(R.id.back_button) backButton.setOnClickListener( { val intent: Intent = Intent(this,MainActivity::class.java) startActivity(intent) finish() } ) } }<file_sep>package com.decagon.jones.notificationactivities import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat class MainActivity : AppCompatActivity() { val CHANNEL_ID = "KEY" lateinit var notificationBuilder: NotificationCompat.Builder override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) notificationChannel() init() } fun init(){ val notifyButton: Button = findViewById<Button>(R.id.notify_button) notifyButton.setOnClickListener({ val intent:Intent = Intent(this,NotifiedActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK putExtra("status","Active") } val pendingIntent : PendingIntent = PendingIntent.getActivity(this, 0,intent,0) val notificationBuilder = NotificationCompat.Builder(this,CHANNEL_ID).apply { setSmallIcon(R.drawable.ic_baseline_notifications_24) setContentTitle("Activation Alert") setContentText("Click me To Go To Activity: \"NotifiedActivity\"") setPriority(NotificationCompat.PRIORITY_DEFAULT) setContentIntent(pendingIntent) setAutoCancel(true) } with(NotificationManagerCompat.from(this)){ notify(0,notificationBuilder.build()) } }) val moveButton: Button = findViewById<Button>(R.id.move_button) moveButton.setOnClickListener({ val intent: Intent = Intent(this, NotifiedActivity::class.java) intent.putExtra("status", "Inactive") startActivity(intent) }) } fun notificationChannel(){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ val name ="channel name" val descriptionText ="channel description" val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID,name,importance).apply { description = descriptionText } val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } }
90b07b4443aa41cffd620ab1436fdd063c3de8dc
[ "Kotlin" ]
2
Kotlin
jonesomoyibo/NotificationActivityAssignment
afe5201cf398c50e33eab1147b1ec0c71c26aa67
4cddbe616a1fd5b2d93867d6f7551189beef0e89
refs/heads/master
<repo_name>aqtrans/argosnap<file_sep>/test/lib/argosnap/options_test.rb require_relative '../../test_helper' describe Argosnap do it "return 'help' message" do end end <file_sep>/Gemfile source 'https://rubygems.org' gem 'mechanize', '2.7.3' gem 'terminal-notifier', '1.6.0' gem 'plist', '3.1.0' # Specify your gem's dependencies in argosnap.gemspec gemspec <file_sep>/lib/argosnap/osxnotify.rb require 'terminal-notifier' require_relative File.expand_path('../balance', __FILE__) require 'yaml' module Argosnap class OSXNotifications def initialize begin user = ENV['USER'] raise ArgumentError.new("This command is made for Darwin! Please check the website for details #{url} !") unless Gem::Platform.local.os == 'darwin' r = YAML::load_file("#{Dir.home}/.argosnap/config.yml") logfile = "#{Dir.home}/.argosnap/argosnap.log" @threshold, @logger, @picodollars, @time_interval = r[:threshold], Logger.new(logfile), Argosnap::Fetch.new.balance, r[:seconds] rescue ArgumentError => e puts e.message # puts e.backtrace exit end end # Creates launchd script with user's variables def install_launchd_script raise ArgumentError.new("Please make sure you run 'argosnap install' in order to install configuration files, before running asnap!") unless File.exists?("#{Dir.home}/.argosnap/config.yml") user = ENV['USER'] c = "#{Dir.home}/.argosnap/config.yml" begin launch_agents = "/Users/#{user}/Library/LaunchAgents/" # start_script loads the RVM environment. start_script = File.expand_path('../../../files/local.sh', __FILE__) if Dir.exists?(launch_agents) filename = "org.#{user}.argosnap.plist" if File.exist?("#{launch_agents}#{filename}") puts "Please delete file: #{launch_agents}#{filename} before proceeding!" else hash = {"Label"=>"#{filename.scan(/(.+)(?:\.[^.]+)/).flatten[0]}", "ProgramArguments"=>["#{start_script}"], "StartInterval"=> @time_interval, "RunAtLoad"=>true} File.open("#{launch_agents}#{filename}", 'w') {|f| f.write(hash.to_plist)} puts "Launchd script is installed. Type 'launchctl load -w #{launch_agents}#{filename}' to load the plist." end else puts "No '#{launch_agents}' directory found! Aborting installation." end rescue Exception => e puts e.message # puts e.backtrace end end # Display notifications def display TerminalNotifier.notify("Current balance: #{@picodollars}", :title => 'TarSnap', :subtitle => 'balance running out') if @picodollars < @threshold.to_i end end end <file_sep>/bin/argosnap #!/usr/bin/env ruby require_relative File.expand_path('../../lib/argosnap', __FILE__) require 'optparse' options = {} opt_parser = OptionParser.new do |opt| opt.banner = "argosnap #{Argosnap::VERSION} ( https://github.com/atmosx/argosnap/ )\nUsage: argosnap [OPTIONS]" opt.separator "" opt.separator " -v: dislay version" opt.separator " -i config: install configuration files" opt.separator " -i cron: installs Launchd script under OSX" opt.separator " -p: prints the current amount in picodollars" opt.separator " -p osx: prints desktop osx notification" opt.separator " -p clean: prints only the picollars (float rounded in 4 decimals), to use in cli" opt.separator "" opt.on("-v","--version","display version") do |version| options[:version] = version end opt.on("-i","--install [OPTION]", "install configuration files") do |install| options[:install] = install || 'config' end opt.on("-p","--print [OPTION]","fetch current amount in picodollars") do |print| options[:print] = print || 'default' end opt.on("-h","--help","help") do |h| options[:help] = h puts opt_parser end end # Execution flow begin opt_parser.parse! if options[:version] puts Argosnap::VERSION elsif options[:install] if options[:install] == 'config' Argosnap::Install.new.config elsif options[:install] == 'cron' Argosnap::OSXNotifications.new.install_launchd_script end elsif options[:help] # do nothing - avoids double printing of 'opt_parser' elsif options[:print] if options[:print] == 'osx' Argosnap::OSXNotifications.new.display elsif options[:print] == 'default' b = Argosnap::Fetch.new.balance puts "Current balance (picodollars): #{b}" elsif options[:print] == 'clean' b = Argosnap::Fetch.new.balance puts b else puts "Option not recognized" end else puts opt_parser end rescue OptionParser::InvalidOption => e puts "No such option! Type 'argosnap -h' for help!" exit end <file_sep>/README.md # Argosnap This gem allows you to displays your current amount of picodollars along with [OSX notifications](http://support.apple.com/kb/ht5362) when your [tarsnap account](http://www.tarsnap.com/) falls bellow a predefined threshold of [picodollars](http://www.tarsnap.com/picoUSD-why.html). ## Installation Install the gem via rubygems: $ gem install argosnap plist mechanize terminal-notifier ## Configure Run the following command for the script to create a configuration file like: $ argosnap -i config You'll see the location of the newly created configuration file on your terminal. Then you need to configure the `config.yml` file which looks like this: --- :email: <EMAIL> :password: <PASSWORD> :threshold: 10 :seconds: 7200 Just put your tarsnap login credentials. You can omit the other two variables if you are not using an OSX system. To view your account use the command: $ argosnap -p ## Configure Launchd under MacOSX In the `config.yml` adjust the `threshold` and `seconds` options as you see fit. Threshold is the amount of *picodollars* bellow which you'd like to start seeing notifications and the `seconds` consists of the time window. Then type: $ argosnap -i cron Now just start the installed `.plist` file following instruction you'll see on the screen and you're done. ## Options To run an osx notification use the command: $ argosnap -p osx Current balance (picodollars): 4.8812 To get the amount of picodollars as an integer type: $ argosnap -p clean 4.8812 That's all :-) ## Contributing 1. Fork it ( http://github.com/atmosx/argosnap/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request <file_sep>/lib/argosnap/install.rb require 'logger' require 'yaml' require 'plist' module Argosnap class Install # Install 'config.yml' def config url = 'http://atmosx.github.com/argosnap' raise ArgumentError.new("This gem is made for UNIX! Please check the website for details #{url} !") unless %w{ darwin linux freebsd openbsd netbsd }.include? Gem::Platform.local.os begin Dir.mkdir(File.join(Dir.home, ".argosnap"), 0700) unless Dir.exists?("/Users/#{ENV['USER']}/.argosnap")# permissions are a-rwx,u+rwx config = {email: 'tarsnap_email', password: '<PASSWORD>', threshold: 10, seconds: 7200} File.open("#{Dir.home}/.argosnap/config.yml", "w") {|f| f.write(config.to_yaml)} puts "1. Edit the configuration file: #{Dir.home}/.argosnap/config.yml" puts "2. Launch argosnap by typing in the terminal: argosnap -p" rescue Exception => e puts e.message end end end end <file_sep>/lib/argosnap.rb # argosnap module require_relative File.expand_path("../argosnap/version", __FILE__) require_relative File.expand_path("../argosnap/install", __FILE__) require_relative File.expand_path("../argosnap/balance", __FILE__) require_relative File.expand_path("../argosnap/osxnotify", __FILE__) if Gem::Platform.local.os == 'darwin' <file_sep>/lib/argosnap/balance.rb require 'yaml' require 'mechanize' require 'logger' module Argosnap # Given a username and a password, fetch balance from http://www.tarsnap.com class Fetch def initialize begin user = ENV['USER'] raise ArgumentError.new("Please make sure you run 'argosnap install' in order to install configuration files, before running asnap!") unless File.exists?("#{Dir.home}/.argosnap/config.yml") r = YAML::load_file("#{Dir.home}/.argosnap/config.yml") logfile = "#{Dir.home}/.argosnap/argosnap.log" @email, @password, @threshold, @logger, @agent = r[:email], r[:password], r[:threshold], Logger.new(logfile), Mechanize.new rescue ArgumentError => e puts e.message # puts e.backtrace exit end end # Fetch balance from tarsnap using mechanize def balance begin page = @agent.get('https://www.tarsnap.com/account.html') form = page.form_with(:action => 'https://www.tarsnap.com/manage.cgi') form.address = @email form.password = <PASSWORD> panel = @agent.submit(form) picodollars = panel.parser.to_s.scan(/\$\d+\.\d+/)[0].scan(/\d+\.\d+/)[0].to_f.round(4) # I'm the feeling that this can be done in a prettier way @logger.info "Execution ended successfully! Picodollars: #{picodollars}" picodollars rescue Exception => e @logger.error "A problem with tarsnap notification occured:" @logger.error "#{e}" end end end end
de863e2a0e0589f3fd44f2c474d798d7089965a3
[ "Markdown", "Ruby" ]
8
Ruby
aqtrans/argosnap
6cb80947849b281fe598637f5ecec343af0fdb1a
16218e0b8f15fed2fa4edfb49df61c64cbb92c1e
refs/heads/master
<file_sep># Coursera # Getting and Cleaning Data # Peer Assessment Project # ### # # This assignment uses data collected from the accelerometers # from the Samsung Galaxy S smartphone. # (Data science area of wearable computing) # A full description of the data used is available at the: # # http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones # ### # # The script merges the training and the test sets and returns one data set. # It extracts only the measurements on the mean and standard deviation for # each measurement. Then it labels the data set with descriptive activity # names. Finaly, it creates a tidy data set with the average of each variable # for each activity and each subject. # ### # Read and merge the training and test sets x.train <- read.table("train/X_train.txt") x.test <- read.table("test/X_test.txt") merged.x <- rbind(x.train, x.test) y.train <- read.table("train/Y_train.txt") y.test <- read.table("test/Y_test.txt") merged.y <- rbind(y.train, y.test) subject.train <- read.table("train/subject_train.txt") subject.test <- read.table("test/subject_test.txt") merged.subject <- rbind(subject.train, subject.test) # Extract only the measurements on the mean and standard deviation for each # measurement features <- read.table("features.txt", header=FALSE, col.names=c("FeaturesID", "FeatureName")) # Add names to data sets names(merged.x) <- features$FeatureName names(merged.y) <- "Activity" names(merged.subject) <- "Subject" # Subset only the mean and stdev measurements sub.col <- grep(".*mean\\(\\)|.*std\\(\\)", features$FeatureName) merged.xsub <- merged.x[, sub.col] # Crete one data set merged.data <- cbind(merged.xsub, merged.y, merged.subject) # Label the activity names activity.lab <- read.table("activity_labels.txt", header=F, col.names=c("Activity", "ActivityName")) activity.lab$ActivityName <- as.factor(activity.lab$ActivityName) # Create data set with labeled activity names merged.data.lab <- merge(merged.data, activity.lab) merged.data.lab <- merged.data.lab[, -1] # Delete activity class labels # (first column) # Create a tidy data set # Data set reshaping: # Average of each variable for each activity and each subject. id.colnames <- c("Subject", "ActivityName") measure.vars = setdiff(colnames(merged.data.lab), id.colnames) melt.data <- melt(merged.data.lab, id=id.colnames, measure.vars=measure.vars) data <- dcast(melt.data, ActivityName + Subject ~ variable, mean) # Save tidy data set write.table(data, "tidy_data.txt") <file_sep>Tidy Data =================== The script `run_analysis.R` uses data collected from the accelerometers from the Samsung Galaxy S smartphone. Full description of the data can be found at [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones). ## run_analysis.R * Download [data set](https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip) * Downloaded zip.file contains folder `UCI HAR Dataset`. * Extract and set your working directory to `UCI HAR Dataset` in order to run the script. * The script reads the raw training and the test sets (`X, y and subject`) from `test`and `train` folders and returns one data set. * It extracts only the measurements on the mean and standard deviation for each measurement. Raw data sets contain more variables (See [`CodeBook.md`](https://github.com/anedeljkovic/GettingCleaningData/blob/master/CodeBook.md)) * Then it labels the data set with descriptive activity names (`WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING`). (See [`CodeBook.md`](https://github.com/anedeljkovic/GettingCleaningData/blob/master/CodeBook.md)) * Finaly, it creates a tidy data set with the average of each variable for each activity and each subject. * Resulting data set is named `tidy_data.txt` and it is saved in `UCI HAR Dataset` folder.
b5369629b951864118227fe21b5daabb6dcae646
[ "Markdown", "R" ]
2
R
naleksandarn/GettingCleaningData
274e4f4a74ea0e157a1c5a3a8ba0ba5897252f6f
7f8b4a85bd7a694975dfe90799d9be48a6a1ee00
refs/heads/main
<repo_name>SheCodes-IEEE-CIS-GHRCE/Entertainment-Recommendation-System<file_sep>/README.md # Entertainment-Recommendation-System based on Emotion Recognition <i> 🙋 Team Members: <NAME>, <NAME>, <NAME>, <NAME> </i> <br></br> <br></br> ## PROJECT EXPLANATION ❄️ Nowadays we have so many websites that categorize movies based on their successful ratings, actors who have worked on it, their box office collections and so on and also categorise songs based on the users previou choices. ❄️ People watch movies or listen to songs so that they can relate to the feel of it , to relieve themselves etc.. ❄️ But there are hardly any websites which recommend movies/songs based on user's current emotions. ❄️ The proposed entertainment system eliminates the time-consuming and tedious task of manually Segregating or grouping movies/songs into different lists and helps in generating an appropriate movie/song list based on an individual's emotional features. ❄️ The system will play the role of a real time application which captures the users live emotions and suggests movies/songs based on that. So the following operations take place: ✨ Instructions through voice assistant ✨ Face Detection ✨ Analyzing facial expression ✨ Emotion detection ✨ Genre allocation based on emotion detected ✨ Suggestion of movies/songs <br> ## Getting Started ✅ Detailed instructions regarding how to retrain the model and make predictions on the video is given in the pdf named: <b>Project_Instructions.pdf<b> <br></br> ## TECHNOLOGY STACK: 💻 Python<br> 💻 Matplotlib<br> 💻 Tensorflow<br> 💻 Keras<br> 💻 Tkinter<br> 💻 PyQt5<br> 💻 OpenCV<br> 💻 Pyaudio<br> ## PROJECT IMPLEMENTATION: <b>User has to choose between movies/music:<b> <img src="https://github.com/SheCodes-IEEE-CIS-GHRCE/Entertainment-Recommendation-System/blob/main/screenshots/image%20(1).png"></img> <br></br> <b>Process of face+emotion detection:<b> <img src="https://github.com/SheCodes-IEEE-CIS-GHRCE/Entertainment-Recommendation-System/blob/main/screenshots/image%20(2).png"></img> <br></br> <b>List of movies suggested from IMDB displayed on the tkinter window:<b> <img src="https://github.com/SheCodes-IEEE-CIS-GHRCE/Entertainment-Recommendation-System/blob/main/screenshots/image%20(3).png"></img> <br></br> <b>For music recommendation, the list of songs of the allocated genre will be played for the user. The user can pause,resume,go to next/prev song.<b> <img src="https://github.com/SheCodes-IEEE-CIS-GHRCE/Entertainment-Recommendation-System/blob/main/screenshots/image%20(5).png"></img> <br></br> ## DEMO OF THE PROJECT: <a href="https://drive.google.com/file/d/1aBjg37GIlmCA_Ddukeahh3Rgd8grp6DS/view?usp=sharing"> 📷 VIDEO LINK </a> <br></br> ## Contributors * **❄️<NAME>** - [GitHub Profile](https://github.com/silpasreeni99) * **❄️<NAME>** - [GitHub Profile](https://github.com/khushbooagnihotri) * **❄️<NAME>** - [GitHub Profile](https://github.com/kamal-kaur04) * **❄️<NAME>** - [GitHub Profile](https://github.com/RuchaYagnik) <file_sep>/neutral.py from os import listdir from os.path import isfile,join from os import walk import vlc from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QWidget ,QVBoxLayout import os mypath="E:\\songs\\neutral\\" onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] f = [] f2=[] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break for i in f: if i.endswith(".mp3") or i.endswith(".flac") or i.endswith(".m4a") or i.endswith(".wav") or i.endswith(".wma"): f2.append(i) count=0 player=vlc.MediaPlayer("E:\\songs\\neutral\\"+str(f2[count])) def button_pressed(): # player=vlc.MediaPlayer("B:\\BAPU\\01) I Ain't No Joke.mp3") global count global player player.play() def button2_pressed(): global player player.pause() def nextS(): global count # count+=1 global player player.stop() count+=1 player=vlc.MediaPlayer("E:\\songs\\neutral\\"+str(f2[count])) player.play() # player=vlc.MediaPlayer("B:\\BAPU\\"+str(f.pop())) def prevS(): global count global player player.stop() count-=1 player=vlc.MediaPlayer("E:\\songs\\neutral\\"+str(f2[count])) player.play() # def cam(): # player.stop() # import os # os.popen("python real_time_video.py") # while True: # pass app = QApplication([]) win = QMainWindow() central_widget = QWidget() button = QPushButton('PLAY') button.clicked.connect(button_pressed) button2=QPushButton('PAUSE') button2.clicked.connect(button2_pressed) button3=QPushButton("NEXT") button3.clicked.connect(nextS) button4=QPushButton('PREV') button4.clicked.connect(prevS) # button5=QPushButton('camera') # button5.clicked.connect(cam) layout = QVBoxLayout(central_widget) layout.addWidget(button) layout.addWidget(button2) layout.addWidget(button3) layout.addWidget(button4) # layout.addWidget(button5) win.setCentralWidget(central_widget) # print(vlc.__version__) player.play() # win.setCentralWidget(button) win.show() app.exit(app.exec_()) # print(f2) <file_sep>/main+movie_recommendation.py from keras.preprocessing.image import img_to_array import imutils import cv2 from keras.models import load_model import numpy as np import tkinter as tk from tkinter import* import playsound # to play saved mp3 file from gtts import gTTS # google text to speech import os from matplotlib import pyplot as plt num=1 def speaks(output): global num num +=1 #print("Safety Assistant : ", output) tospeak = gTTS(text=output, lang='en-US', slow=False) file = str(num)+".mp3" tospeak.save(file) playsound.playsound(file, True) os.remove(file) def music(): import music_recommendation def movie(): speaks("MOVIES WILL BE SUGGESTED BASED ON THE EMOTION DETECTED") # parameters for loading data and images detection_model_path = 'haarcascade_files/haarcascade_frontalface_default.xml' emotion_model_path = 'models/_mini_XCEPTION.102-0.66.hdf5' # hyper-parameters for bounding boxes shape # loading models face_detection = cv2.CascadeClassifier(detection_model_path) emotion_classifier = load_model(emotion_model_path, compile=False) EMOTIONS = ["angry" ,"disgust","scared", "happy", "sad", "surprised", "neutral"] #feelings_faces = [] #for index, emotion in enumerate(EMOTIONS): # feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1)) # starting video streaming cv2.namedWindow('your_face') camera = cv2.VideoCapture(0) while True: frame = camera.read()[1] #reading the frame frame = imutils.resize(frame,width=300) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_detection.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,minSize=(30,30),flags=cv2.CASCADE_SCALE_IMAGE) canvas = np.zeros((250, 300, 3), dtype="uint8") frameClone = frame.copy() if len(faces) > 0: faces = sorted(faces, reverse=True, key=lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0] (fX, fY, fW, fH) = faces # Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare # the ROI for classification via the CNN roi = gray[fY:fY + fH, fX:fX + fW] roi = cv2.resize(roi, (64, 64)) roi = roi.astype("float") / 255.0 roi = img_to_array(roi) roi = np.expand_dims(roi, axis=0) preds = emotion_classifier.predict(roi)[0] emotion_probability = np.max(preds) label = EMOTIONS[preds.argmax()] else: import tkinter as tk from tkinter import messagebox root123= tk.Tk() root123.withdraw() msgbox=tk.messagebox.showinfo('ERROR MESSAGE', "FACE NOT DETECTED,PLEASE TRY AGAIN!!") break for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)): # construct the label text text = "{}: {:.2f}%".format(emotion, prob * 100) # draw the label + probability bar on the canvas # emoji_face = feelings_faces[np.argmax(preds)] w = int(prob * 300) cv2.rectangle(canvas, (7, (i * 35) + 5), (w, (i * 35) + 35), (0, 0, 255), -1) cv2.putText(canvas, text, (10, (i * 35) + 23), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 2) cv2.putText(frameClone, label, (fX, fY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2) cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH), (0, 0, 255), 2) # for c in range(0, 3): # frame[200:320, 10:130, c] = emoji_face[:, :, c] * \ # (emoji_face[:, :, 3] / 255.0) + frame[200:320, # 10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0) cv2.imshow('your_face', frameClone) cv2.imshow("Probabilities", canvas) if cv2.waitKey(1) & 0xFF == ord('s'): from bs4 import BeautifulSoup as SOUP import re import requests as HTTP # Main Function for scraping def main(emotion): em=emotion.lower() import tkinter as tk from tkinter import messagebox root= tk.Tk() root.withdraw() msgbox=tk.messagebox.showinfo('EMOTION', em.upper()) # IMDb Url for Drama genre of # movie against emotion Sad if(em == "sad"): speaks('GENRE ALLOCATED IS DRAMA') urlhere = 'http://www.imdb.com/search/title?genres=drama&title_type=feature&sort=moviemeter, asc' # IMDb Url for Musical genre of # movie against emotion Disgust elif(em == "disgust"): speaks('GENRE ALLOCATED IS MUSICAL') urlhere = 'http://www.imdb.com/search/title?genres=musical&title_type=feature&sort=moviemeter, asc' # IMDb Url for Family genre of # movie against emotion Anger elif(em == "angry"): speaks('GENRE ALLOCATED IS FAMILY') urlhere = 'http://www.imdb.com/search/title?genres=family&title_type=feature&sort=moviemeter, asc' # IMDb Url for Thriller genre of # movie against emotion Anticipation elif(em == "neutral"): speaks('GENRE ALLOCATED IS THRILLER') urlhere = 'http://www.imdb.com/search/title?genres=thriller&title_type=feature&sort=moviemeter, asc' # IMDb Url for Sport genre of # movie against emotion Fear elif(em == "scared"): speaks('GENRE ALLOCATED IS SPORTS') urlhere = 'http://www.imdb.com/search/title?genres=sport&title_type=feature&sort=moviemeter, asc' # IMDb Url for Thriller genre of # movie against emotion Enjoyment elif(em == "happy"): speaks('GENRE ALLOCATED IS THRILLER') urlhere = 'http://www.imdb.com/search/title?genres=thriller&title_type=feature&sort=moviemeter, asc' # IMDb Url for Film_noir genre of # movie against emotion Surprise elif(em == "surprised"): speaks('GENRE ALLOCATED IS FILM NOIR') urlhere = 'http://www.imdb.com/search/title?genres=film_noir&title_type=feature&sort=moviemeter, asc' # HTTP request to get the data of # the whole page response = HTTP.get(urlhere) data = response.text # Parsing the data using # BeautifulSoup soup = SOUP(data, "lxml") # Extract movie titles from the # data using regex title = soup.find_all("a", attrs = {"href" : re.compile(r'\/title\/tt+\d*\/')}) title1 = soup.find_all("h3",{"class":"lister-item-header"}) rating = soup.find_all("div", {"class": "inline-block ratings-imdb-rating"}) import tkinter from tkinter import ttk root12 = tkinter.Tk() root12.geometry("600x600") root12.title("MOVIES RECOMMENDED FOR DETECTED EMOTION") tree = ttk.Treeview(root12) tree["columns"]=("one","two") tree.column("one", width=200) tree.column("two", width=200) style = ttk.Style(root12) style.configure('Treeview', rowheight=45) tree.heading("one", text="MOVIES") tree.heading("two", text="RATINGS") for i in range(9,-1,-1): tree.insert("" , 0, text="", values=(title1[i].text,rating[i].text)) tree.pack() return title1 # Driver Function if __name__ == '__main__': #emotion = input("Enter the emotion: ") a = main(label) cv2.destroyAllWindows() break camera.release() cv2.destroyAllWindows() speaks("WELCOME TO ENTERTAINMENT RECOMMENDATION SYSTEM BASED ON EMOTION RECOGNITION") speaks("In the next window,choose what you want us to suggest between MOVIES or MUSIC ") root = Tk() root.geometry("200x200") var = IntVar() R1 = Radiobutton(root, text="MOVIES", variable=var, value=1, command=movie) R1.pack( anchor = W ) R2 = Radiobutton(root, text="MUSIC", variable=var, value=2,command=music) R2.pack( anchor = W ) label = Label(root) label.pack()
f43a1d0b6e8b91d490599b5822639dc63327d521
[ "Markdown", "Python" ]
3
Markdown
SheCodes-IEEE-CIS-GHRCE/Entertainment-Recommendation-System
31920ff7ef12bca2b6db392cbcf59c1e9b642e6f
d3ed79c51e8e7eb6e5c999cc4974ecc5122cc2e3
refs/heads/main
<file_sep># 2019-08-02 Interface to Host When looking at the current interface between bot and host, some questions came up: + What does it mean when the `botRequests` contain multiple `FinishSession` entries? What is the difference to having just one `FinishSession` entry? + When `botRequests` contains tasks after a `FinishSession` entry, are these tasks started? + When a response contains a `StartTask` entry, is this task started even if the same response also contains a `FinishSession` entry? + What is the `Process` in `ProcessEventResponse`? + Why does the `Delay` task have a `taskId`? How would we use this id? + How does the bot specify that it is not interested anymore in `Delay` tasks it has started before? We can ignore the resulting events, but would it not be better to avoid having these events generated at all? <file_sep># Input Focus Scheduling for Multiple Bot Instances Input focus scheduling is a technique to resolve the contention for device input focus between multiple bots. This problem occurs when we run multiple bots requiring input focus on the operating system level in parallel. Not all bots require input focus on this level. For example, bots interacting with websites can use web browsers' programmatic interfaces to send input without depending on the OS input focus. However, many bots simulate input from the mouse or keyboard to control apps. This way of sending inputs works similar to a human using the mouse and keyboard manually. Bots don't send their inputs instantaneously but in sequences that can span several hundred milliseconds. Take, for example, a drag&drop gesture: A bot can use four steps to perform this gesture: 1. Move the mouse cursor to the start location. 2. Press down the mouse button. 3. Move the mouse cursor to the destination. 4. Release the mouse button. Bots also often insert small pauses between these steps. On operating systems like Windows, we can simultaneously run multiple apps. Each app has its user interface contained in a window. When you press a key, the input focus determines which of these windows receives the input. Before sending inputs, a bot switches the input focus to the right window if necessary. Most bots have no problem if a user takes over for a second and interrupts the input flow. The bot will automatically switch back to the right window. In case one of the inputs planned by the bot got lost, the bot will see the effect was not achieved yet and plan the input again. (This is in contrast to a macro, which blindly sends inputs without checking the current state of the target app) ![BotLab coordinates input scheduling between bots](./image/2023-05-11-botlab-input-scheduling-illustration.png) Such interference will slow down the bot as it has to repeat the inputs more often. When we run multiple bots that send inputs often, this can become a problem. ## Avoiding Interference Through Input Focus Scheduling When we run multiple bots simultaneously on the same machine, the input focus becomes a shared resource. Scheduling enables us to make the best use of this resource and prevent the interference problems described above. The BotLab client software comes with built-in support for input focus scheduling. The bot program code sends a sequence of inputs, like the one in the drag&drop example above, to the host in one package. The client instance hosting this bot then coordinates with the other instances to find a time slot for the input package. When giving such a package to the host, the bot also specifies a maximum wait time to acquire input focus. In case there is no time-slot available soon enough, the host informs the bot that the acquisition of input focus failed. From the user's perspective, there is no big difference to running just one bot instance. Each bot is still started the same way, in a separate process. Each instance of the BotLab client automatically connects to the other currently running instances. They then elect one instance to act as a central scheduler. This scheduling instance takes requests from the other ones and assigns time slots. When the scheduling instance disappears, the remaining ones will elect a new scheduler. This design means there is no need to start or stop the bots together. And we can use any mixture of bots since all the scheduling program is on the host side. When running a bot, the BotLab client displays information on the input scheduling in the 'Play Session' view. The screenshot below is an example with two bots running, each on their own instance of the BotLab client: ![two botlab client instances coordinating for input scheduling](./image/2023-05-11-botlab-input-scheduling-two-client-instances-gui.png) This view shows the count of other instances currently running bots that require input focus. Bots that run entirely in the background, like inside a web browser, do not increase the count here. At the label `scheduling via`, the BotLab client window also shows the process ID of the instance that currently has the scheduler role. In the screenshot above, we see that every instance connects to the same BotLab client instance to coordinate the scheduling of inputs to the game clients. ## RDP as Alternative to Input Focus Scheduling Input focus scheduling is not the only way to run multiple bots on the same machine. Another option is to use a remote desktop connection to the machine. When we connect to a machine via RDP, we get a separate desktop session. This session has its input focus. We can run bots in this session without interference from other bots running on the same machine. The more bots you run on the desktop, the greater the average delay for a bot to wait for its turn. The RDP approach avoids these delays by enabling multiple desktop sessions on the same machine. ### How to Allow Multiple RDP Sessions in Windows 10 and 11? Compared to input focus scheduling, the RDP solution has the disadvantage of requiring a setup on the machine. There is a guide on setting up RDP at <https://woshub.com/how-to-allow-multiple-rdp-sessions-in-windows-10/> <file_sep># Farm Manager - Tribal Wars 2 Farmbot This bot farms barbarian villages in Tribal Wars 2. It automatically detects barbarian villages, available troops and configured army presets to attack. ## Features ### Easy to Use + Automatically reads the required information from the game: Locations of farms, available units, army presets, current attacks per village, etc. + Use the in-game army presets to configure which villages should attack and which units to use. + Requires no input focus: You can continue using your PC as usual while the bot runs in the background. ### Efficient + Fast enough to send 800 attacks per hour. + Supports multiple army presets per village to make the best use of your troops. + Takes into account the limit of 50 attacks per village. + Option to skip barbarian villages under a certain amount of points. + Avoid having your troops die at remaining walls: Option to skip barbarian villages with specific coordinates. + Supports running on multiple accounts simultaneously on a single PC. ### Safe + Supports random breaks between farming cycles. + Uses a normal web browser to interact with the game server for maximum security. + Stops the farming when the configured time limit is met to avoid perpetual activity on your account. ## Starting the Farmbot This video shows the process of starting the farmbot and setting up your Tribal Wars 2 account: https://youtu.be/yzkernqechE Following are the first steps shown in the video: + Download the file from <https://botlabs.blob.core.windows.net/blob-library/by-name/2023-06-01-tribal-wars-2-farmbot.zip> + Extract the downloaded zip archive. The extraction will give you a file named `tribal-wars-2-farmbot.exe`. + Run the `tribal-wars-2-farmbot.exe` program. + Click on 'Continue without Installing' + Click on 'Run Bot' Then we land on this screen where we can select the Tribal Wars 2 farmbot: ![Screen to select the Tribal Wars 2 Farmbot](./image/2022-11-15-tribal-wars-2-farmbot-pick-bot-bundled-bot-with-marker.png) + Here click on the 'Tribal Wars 2 farmbot' under 'Bundled Bot' + On the next screen, scroll down and click the button 'Start Play Session' ![Start the play session](./image/2022-12-01-tw2-farmbot-configure-session-start-marked.png) Then the bot starts and we see a screen like this: ![Tribal Wars 2 farmbot session started](./image/2022-12-02-tribal-wars-2-farmbot-started.png) In the left pane, we see information about the play session and controls to pause and continue the bot. The left pane also shows a status report from the bot under 'Status text from bot'. Here the bot also informs us about any setup we need to complete manually. When we have just started the session, the bot also shows this text: > I did not yet read game root information. Please log in to the game so that you see your villages. In the right pane, the bot opens a web browser tab. The web browser tab is initially empty, but there is an address bar at the top where we can enter a new web page to load, just as in other web browsers. Here we enter the address of the Tribal Wars 2 game world we want to enter with the bot. Since the browser by the bot is entirely separate from other web browsers and has a different user profile, we need to log in to the game to be able to enter the game world. After logging in and selecting the game world, this new browser tab shows the game as any other web browser: ![Tribal Wars 2 farmbot session started](./image/2022-12-02-tribal-wars-2-farmbot-game-entered.jpg) Then the bot displays a message like this: > Found no army presets matching the filter 'farm'. Or, in case our Tribal Wars 2 account has no army presets configured at all, it shows this message: > Did not find any army presets. Maybe loading is not completed yet. In any case, we need to configure at least one army preset before the bot can start farming. ### Configuring Army Presets The bot only uses army presets matching the following three criteria: + The preset name contains the string 'farm'. ('farm' is only the default pattern, we can change it in the bot settings) + The preset is enabled for the currently selected village. + The village has enough units available for the preset. If multiple army presets match these criteria, it uses the first one by alphabetical order. If no army preset matches this filter, it switches to the next village. You can use the in-game user interface to configure an army preset and enable it for villages: ![Configuring Army Presets in-game](./image/2020-01-25.tribal-wars-2-farmbot-configure-army-preset.png) Besides the army presets, no configuration is required. The bot searches for barbarian villages and then attacks them using the matching presets. You can also see it jumping to the barbarian villages on the map. Under 'Status text from bot', you can read about the number of sent attacks and what the bot is currently doing: ```text Session performance: attacks sent: 129, coordinates read: 1478, completed farm cycles: 1 --- Sent 129 attacks in the current cycle. Checked 1413 unique coordinates and found 364 villages, 129 of wich are barbarian villages. Found 3 own villages. Current activity: + Currently selected village is 871 (482|523 'Segundo pueblo de skal'. Last update 6 s ago. 537 available units. 11 outgoing commands.) ++ Best matching army preset for this village is 'farm beta'. +++ Farm at 567|524. ++++ Send attack using preset 'Farm 1'. [...] ``` When all your villages are out of units or at the attack limit, the bot stops with this message: > Finish session because I finished all 1 configured farm cycles. ## Configuration Settings All settings are optional; you only need them in case the defaults don't fit your use-case. Following is a list of available settings: + `number-of-farm-cycles` : Number of farm cycles before the bot stops. The default is only one (`1`) cycle. + `break-duration` : Duration of breaks between farm cycles, in minutes. You can also specify a range like `60 - 120`. The bot then picks a random value in this range. + `farm-barb-min-points`: Minimum points of barbarian villages to attack. + `farm-barb-max-distance`: Maximum distance of barbarian villages to attack. + `farm-avoid-coordinates`: List of village coordinates to avoid when farming. Here is an example with two coordinates: '567|456 413|593'. This filter applies to both target and sending villages. + `farm-player`: Name of a player/character to farm. By default, the bot only farms barbarians, but this setting allows you to also farm players. + `farm-army-preset-pattern`: Text for filtering the army presets to use for farm attacks. Army presets only pass the filter when their name contains this text. + `limit-outgoing-commands-per-village`: The maximum number of outgoing commands per village before the bot considers the village completed. By default, the bot will use up all available 50 outgoing commands per village. You can also specify a range like `45 - 48`. The bot then picks a random value in this range for each village. + `restart-game-client-after-break`: Set this to 'yes' to make the bot restart the game client/web browser after each break. + `open-website-on-start`: Website to open when starting the web browser. You can enter any combination of settings before starting the bot. When in the 'Configure Session' view, scroll to the 'Bot Settings' section and click on 'Edit'. ![Button to enter configuration](./image/2022-12-01-tw2-farmbot-configure-session-section-bot-settings-marked-edit.png) This opens a popup where you can enter a settings text: ![Text input to enter bot settings](./image/2022-12-01-tw2-farmbot-configure-session-section-bot-settings-edited-crop.png) When using more than one setting, start a new line for each setting in the text input field. Here is an example for three farm cycles with breaks of 20 to 40 minutes in between: ```text number-of-farm-cycles = 3 break-duration = 20 - 40 ``` After entering the settings, use the 'Save' button to apply these to the new session. When you have applied settings for multiple farm cycles, the bot displays this message during the breaks between farm cycles: > Next farm cycle starts in 17 minutes. Last cycle completed 16 minutes ago. ## Pricing and Online Sessions You can test the bot for free. When you want the bot to run more than 15 minutes per session, use an online session as explained at <https://to.botlab.org/guide/online-session> Online sessions cost 2000 credits per hour. To add credits to your account, follow the instructions at <https://reactor.botlab.org/billing/add-credits> For more about purchasing and using credits, see the guide at <https://forum.botlab.org/t/purchasing-and-using-botlab-credits-frequently-asked-questions-faq/837> ## Frequently Asked Questions ### How can I make the bot remember the locations of the barbarian villages? To make it remember the farm locations, configure the number of farm cycles to be at least two. The bot automatically remembers all locations of barbarian villages within the same session, so it can reuse this knowledge, starting with the second farm cycle. It sends only one attack per target per farm cycle, so the remembering does not affect the first farm cycle. If you don't use any configuration, the bot only performs one farm cycle and then stops. ### How much time does this bot need to send all attacks on my account? Sending one attack takes less than four seconds. The bot can cover 800 farms per hour. The first farm cycle per session is a special case: For the first cycle, it needs additional time to find the farm villages. The game limits us to 50 concurrent attacks per village, and the bot switches to the next village when the currently selected village hits that limit. One farm cycle is complete when all your villages are at the limit, either because of the attack limit or because no matching units are remaining. ### How can I farm (multiple) inactive players? To select multiple players for farming, use the `farm-player` setting name multiple times. Here is an example of a complete bot-settings string with multiple `farm-player`: ```text number-of-farm-cycles = 3 farm-player = player one farm-player = player two farm-player = player three ``` There is no limit to the number of players here, you can add as many `farm-player` as you want. ### How to use it with multiple accounts at the same time? Start a new instance of the bot for each account. This separation also means the instance configurations are separate. For example, you could assign each instance another break duration. The challenge with using multiple Tribal Wars 2 accounts simultaneously is that the game website does not support logging into two accounts simultaneously. This constraint of the game client applies to a whole browser user profile. With most common browsers, like Chrome, Firefox, and Safari, all browser windows/tabs we open on the same machine share the same user profile. When logging into the Tribal Wars account in one browser window, the other browser windows share the same session by default. To prevent this sharing of game session state between multiple bot instances, we set up our bot to use a separate browser user profile for each instance. Currently, the only way to do this is to copy the 'BotLab.exe' file into a separate directory. This works because the bot's user profile is located under the executable file's directory. TODO: Engineering: Expand API to support the bot specifying a separate browser user profile. Future versions should support this way: > To use multiple instances simultaneously, you need to expand the bot-settings in the configuration of each instance. When the bot starts, it opens a new browser window and will also close other browser windows. To avoid it closing the browser window of another instance, we need to assign it a scope of browser instances in bot-settings explicitly. > > To configure this scope, use the new `web-browser-user-profile-id` bot-setting like this: > > ``` > web-browser-user-profile-id = profile-beta > ``` > > While running, the bot displays the profile ID, so you can check that each running instance has a unique value: > ![bot displays the web-browser-user-profile-id setting](./image/2021-12-02-tribal-wars-2-farmbot-browser-profile-id.png) > Note that browser state like bookmarks and cookies belong to that web browser profile. That means you need to log in to the game for each new profile that you create. ## Getting Help If you have any questions, the [BotLab forum](https://forum.botlab.org) is a good place to learn more. You can also contact me at [<EMAIL>](mailto:<EMAIL>?subject=Tribal%20Wars%202%20Farmbot%20-%20your%20issue%20here) When asking for help with the bot, include one of these two artifacts to help us see what happened on your setup: + The summary from the `Report Problem or Share Session` dialog in the play session interface. Either upload the saved JSON file or copy the text in that file. To reach this dialog, use the buttons labeled `Get Help With This Bot Session` and then `Report Problem or Share Session`. + The play session recording archive from the session view in DevTools. <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace BotEngine { public class ProcessMeasurement { public KeyValuePair<Int64, byte[]>[] MemoryBaseAddressAndListOctet; static string ProcessMemoryEntryName => @"Process\Memory"; static public Int64? BaseAddressFromMemoryEntryName(string MemoryEntryName) { if (null == MemoryEntryName) { return null; } var match = Regex.Match(MemoryEntryName, @"0x([\d\w]+)"); if (!match.Success) { return null; } if (Int64.TryParse( match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture.NumberFormat, out var asInt)) return asInt; return null; } static public ProcessMeasurement MeasurementFromZipArchive(byte[] ZipArchiveSerial) { using (var ZipArchive = new System.IO.Compression.ZipArchive(new MemoryStream(ZipArchiveSerial), System.IO.Compression.ZipArchiveMode.Read)) { var memoryEntries = ZipArchive.Entries .Where(entry => entry.FullName.StartsWith(ProcessMemoryEntryName, StringComparison.InvariantCultureIgnoreCase)) .ToList(); var memoryList = memoryEntries ?.Select(Entry => { var content = new byte[Entry.Length]; using (var stream = Entry.Open()) { if (stream.Read(content, 0, content.Length) != content.Length) throw new NotImplementedException(); } return new { baseAddress = BaseAddressFromMemoryEntryName(Entry.Name), content = content, }; }) ?.ToArray(); return new ProcessMeasurement { MemoryBaseAddressAndListOctet = memoryList ?.Where(AddressAndListOctet => AddressAndListOctet.baseAddress.HasValue && null != AddressAndListOctet.content) ?.Select(AddressAndListOctet => new KeyValuePair<Int64, byte[]>(AddressAndListOctet.baseAddress.Value, AddressAndListOctet.content)) ?.ToArray(), }; } } } }<file_sep># How to Install the BotLab Client and Register the `botlab` Command When you land here, you might have tried to use the `botlab` program in some form. Maybe you downloaded a script from the [bot catalog](https://to.botlab.org/catalog), and got this error message when running the script: > I failed to run the bot because I did not find the 'botlab.exe' program. Or maybe you followed instructions to run a command in Windows and got an error message like this: > 'botlab' is not recognized as an internal or external command, operable program or batch file. The BotLab client program is a tool for developing and running bots, and many guides assume it is registered on your Windows system. To make these guides and scripts work, follow these steps: + Download the file from <https://botlabs.blob.core.windows.net/blob-library/by-name/2023-08-11-botlab-client.zip> + Extract the downloaded zip archive. The extraction will give you a file named `BotLab.exe`. + Run the `BotLab.exe` program, for example by double clicking the file in the Windows Explorer. It will open a window like in this screenshot: ![BotLab client offers to install](./image/2022-10-07-botlab-client-offer-install.png) + To start the installation, use the button labeled `Install and Continue`. + The program then confirms the successful installation with a new output like this: ![BotLab client completed installation](./image/2022-10-07-botlab-client-completed-installation.png) That's it; the installation is complete. Now you can run bots by using the 'Run Bot' button in the BotLab client GUI: ![The first view visible in the BotLab client after installing](./image/2022-12-10-botlab-client-main-menu.png) If you have any questions, the [BotLab forum](https://forum.botlab.org) is a good place to learn more. ## Using Different Versions Simultaneously As the evolution of functionality in BotLab continues, multiple new versions of the BotLab client are offered each year. Sometimes, you might want to simultaneously use different client software versions on the same Windows system. To do this, place each of the versions you want to use in a separate directory in the file system. You don't have to use the installation to run bots. If you don't want to register the current instance as 'botlab.exe' on the whole Windows user account, use the 'Continue without installing' option. You can also rename the executable file and then use the installation to register multiple different versions on the whole Windows user account. Scripts from the configuration export or catalog assume the name `botlab.exe` by default. If you renamed the executable file on your system, change the script accordingly. <file_sep># Testing a Bot Using Simulations Simulated environments are a great time saver for testing and debugging a bot. Simulated environments let us test a complete bot without starting a game client. When we run a bot for productive use, we want it to interface with a real game client. For the bot to be useful, it needs to affect the game world or read and forward information from the game. This mode is what we call a 'live environment'. During bot development, our goals are different. We are confronted with many possible bot programs and want to test and compare those. There are various ways to find a bot program. We could write it ourselves or copy it from some website. But no matter how we find a bot program, we want to test it before letting it run unattended for hours. We want to check if it works for our scenarios. We often want to run different bot programs in the same scenario to compare their fitness. Setting up a game client for each test would be a distraction and would slow us down. But even after the setup, testing a new bot on a real game client can still require further work. If we let a new, previously untested bot run unattended, it might put in-game resources at risk. We use simulated environments to test and compare bots faster and without risk. Simulated environments allow us to test different bots in the same situation without using a live game client. How does this work? Remember that all information that a bot receives comes through events. This also implies that the sequence of events in a session determines all outputs of a bot. In the case of productive use, the events encode information from the user (bot-settings) and the game client (e.g. screenshots). When we use a simulated environment, another program generates the events that the bot receives. ## Simulation from Session Replay The simplest type of simulation is replaying a session. This is a kind of off-policy simulation, which means the bot's output is not fed back into the simulation. To create a simulation by session replay, we only need the recording of a session as input. Here we can use a session archive as we get it from the [export function in DevTools](https://to.botlab.org/guide/how-to-report-an-issue-with-a-bot-or-request-a-new-feature). We can start a session replay by using the `botlab play` command with the `--environment` option. We use the `--environment` to point to the file containing the session recording archive. After the `--environment` option, we add the path to the bot program code, the same way as with the `botlab play` command. Here is an example of the final command as we can run it in the Windows Command Prompt: ``` botlab play --environment="C:\Users\John\Downloads\session-2020-08-04T06-44-41-3bfe2b.zip" https://github.com/Viir/bots/tree/e733ebde1f86b878dd29ae9cb90e6a12d007c1f9/implement/applications/eve-online/eve-online-combat-anomaly-bot ``` ![command to simulate-run in Command Prompt](./image/2020-08-08-simulate-run-cmd.png) When running this command, the output looks similar to when running a bot live. The same way as when running live, we see a session ID that we can use later to find the details of this simulated session again. One difference you can see is that the BotLab client displays the number of remaining events to be processed: ![BotLab displays progress during simulate-run](./image/2020-08-08-simulate-run-progress.png) The simulation runs faster than the original session because it never has to wait for another process, and the passing of time is encoded in the bot event data. When the simulation is complete, we find the recording in the list of sessions shown in DevTools. (You might have to restart DevTools to make a new session visible). By selecting the session recording in DevTools, you can inspect it the same way as any other session recording. The guide on observing and inspecting a bot explains how this works: https://to.botlab.org/guide/observing-and-inspecting-a-bot ### Replacing Bot-Settings in a Session Replay When developing a new feature for a bot, we sometimes want to add a new setting to let users configure that feature. But how do we test this with a session replay? The session replay contains an event with the bot-settings string, so the replay determines the settings. What we want in this case is not an exact replay but one with modified events. Use the `--bot-settings` option to override these bot settings. BotLab then replaces the bot-settings string with the new value for each bot-settings event in the loaded session before giving it to the bot. ## Related Resources You can see an example of simulations in action in this video: https://vimeo.com/user132945801/making-an-eve-online-bot-see-anomalies-and-other-pilots#t=583s <file_sep># EVE Online Warp-To-0 Autopilot Bot When playing EVE Online, you might spend significant time traveling between solar systems. This activity is so common that there is even an in-game autopilot to automate this process. But that autopilot has a critical flaw: It is quite inefficient and will cause long travel times. You can travel faster by manually commanding your ship. Fortunately, this process can be automated using a bot. The bot we are using here follows the route set in the in-game autopilot and uses the context menu to initiate warp and dock commands. ## Starting the Autopilot Bot If the BotLab client is not already installed on your machine, follow the guide at <https://to.botlab.org/guide/how-to-install-the-botlab-client> The BotLab client is a tool for developing bots and also makes running bots easier with graphical user interfaces for configuration. In the BotLab client, load the bot by entering the following link in the 'Select Bot' view: <https://catalog.botlab.org/64c85637044f124a> There is a detailed walkthrough video on how to load and run a bot at <https://to.botlab.org/guide/video/how-to-run-a-bot-live> Before starting the bot, set up the game client as follows: + Set the UI language to English. + Set the in-game autopilot route. + Make sure the autopilot info panel is expanded, so that the route is visible. The bot needs a few seconds to start and find the EVE Online client process. It also shows status messages to inform what it is doing at the moment and when the startup is complete. ![EVE Online Bot Starting](./image/2023-03-08-botlab-gui-eve-online-bot-startup.png) When the startup sequence has completed, the bot might display this message: > I see no route in the info panel. I will start when a route is set. We need to set the destination in the in-game autopilot so that the route is visible in the `Route` info panel. But we do not start the in-game autopilot because it would interfere with our bot. Also, this bot does not undock, so we need to undock our ship manually for the bot to start piloting. As long as the ship is docked, the bot displays the following message: > I cannot see if the ship is warping or jumping. I wait for the ship UI to appear on the screen. As soon as we undock, the bot will start to send mouse clicks to the game client to initiate warp and jump maneuvers. ## Configuration Settings Settings are optional; you only need them in case the defaults don't fit your use-case. + `activate-module-always` : Text found in tooltips of ship modules that should always be active. For example: "cloaking device". Alright, I think that is all there is to know about the basic autopilot bot. If you have questions about this bot or are searching for other bots, don't hesitate to ask on the [BotLab forum](https://forum.botlab.org/). <file_sep># Parsed User Interface of the EVE Online Game Client The parsed user interface is a library of building blocks to build apps that read from the EVE Online game client. This library helps us identify and locate the various UI elements in the EVE Online game client. It takes the low-level data available in the game client and extracts high-level information such as text, numbers, or types of icons. Developers use the parsing library to make ratting, mining, and mission running bots and intel tools. Following are some links to bots and tools using the parsing library: + <https://forum.botlab.org/t/list-of-eve-online-bots-for-beginners/629> + <https://catalog.botlab.org/?q=eve%2Bonline> ### Functions The EVE Online client's UI tree can contain thousands of nodes and tens of thousands of individual properties. Because of this large amount of data, navigating in there can be time-consuming. When programming an app, we use functions to reach into the UI tree and extract the parts needed for our app. Sometimes the information we need is buried somewhere deep in the tree, contained in other nodes with redundant data. The structure we find in the UI tree is what CCP uses to build a visual representation of the game. It is not designed to be easily accessible to us, so it is not surprising to find many things there that we don't need for our applications and want to filter out. ### Types To find things faster and automatically detect program code errors, we also use types adapted to the user interface's shape. We use the type system of the Elm programming language to assign names to parts of the UI tree describe the values that we expect in certain parts of the UI. The types provide us with names more closely related to players' experience, such as the overview window or ship modules. To help find these functions and types, we collect the most popular ones in the [`EveOnline.ParseUserInterface`](https://github.com/Viir/bots/blob/c7f7c4d015e08746c4103c713441103a786caa52/implement/applications/eve-online/eve-online-mining-bot/EveOnline/ParseUserInterface.elm) Elm module. If you are not sure how to read the type definitions in that module, see the ["Reading Types"](https://guide.elm-lang.org/types/reading_types.html) and ["Type Aliases"](https://guide.elm-lang.org/types/type_aliases.html) sections in the Elm programming language guide. When you use the alternate UI or one of the example apps in the bots repository, you will find these already integrate the parsing framework. These apps apply the `parseUserInterfaceFromUITree` function to parse the complete user interface. The return type of that function represents the whole user interface: ```Elm type alias ParsedUserInterface = { uiTree : UITreeNodeWithDisplayRegion , contextMenus : List ContextMenu , shipUI : Maybe ShipUI , targets : List Target , infoPanelContainer : Maybe InfoPanelContainer , overviewWindows : List OverviewWindow , selectedItemWindow : Maybe SelectedItemWindow , dronesWindow : Maybe DronesWindow , fittingWindow : Maybe FittingWindow , probeScannerWindow : Maybe ProbeScannerWindow , directionalScannerWindow : Maybe DirectionalScannerWindow , stationWindow : Maybe StationWindow , inventoryWindows : List InventoryWindow , chatWindowStacks : List ChatWindowStack , agentConversationWindows : List AgentConversationWindow , marketOrdersWindow : Maybe MarketOrdersWindow , surveyScanWindow : Maybe SurveyScanWindow , bookmarkLocationWindow : Maybe BookmarkLocationWindow , repairShopWindow : Maybe RepairShopWindow , characterSheetWindow : Maybe CharacterSheetWindow , fleetWindow : Maybe FleetWindow , watchListPanel : Maybe WatchListPanel , standaloneBookmarkWindow : Maybe StandaloneBookmarkWindow , moduleButtonTooltip : Maybe ModuleButtonTooltip , heatStatusTooltip : Maybe HeatStatusTooltip , neocom : Maybe Neocom , messageBoxes : List MessageBox , layerAbovemain : Maybe LayerAbovemain , keyActivationWindow : Maybe KeyActivationWindow , compressionWindow : Maybe CompressionWindow } ``` As we can see in the definition of this record type above, its fields integrate many other types found in this module. Below you find some of those types copied combined with a screenshot of the corresponding portion in the user interface. Of all the fields, the `uiTree` field is a bit special. This field links to the raw UI tree that went into the `parseUserInterfaceFromUITree` function. All the other fields contain derivations of the UI tree for easier access. In case the field names aren't clear, this annotated screenshot of the game client illustrates what is what, for some of the more popular elements: ![Some elements of the parsed user interface](./image/2020-03-11-eve-online-parsed-user-interface-names.png) ## Ship UI ```Elm type alias ShipUI = { uiNode : UITreeNodeWithDisplayRegion , capacitor : ShipUICapacitor , hitpointsPercent : Hitpoints , indication : Maybe ShipUIIndication , moduleButtons : List ShipUIModuleButton , moduleButtonsRows : { top : List ShipUIModuleButton , middle : List ShipUIModuleButton , bottom : List ShipUIModuleButton } , offensiveBuffButtonNames : List String , squadronsUI : Maybe SquadronsUI , stopButton : Maybe UITreeNodeWithDisplayRegion , maxSpeedButton : Maybe UITreeNodeWithDisplayRegion , heatGauges : Maybe ShipUIHeatGauges } ``` ### Capacitor ```Elm type alias ShipUICapacitor = { uiNode : UITreeNodeWithDisplayRegion , pmarks : List ShipUICapacitorPmark , levelFromPmarksPercent : Maybe Int } ``` Use the field `levelFromPmarksPercent` to get the capacitor level in percent. ### Module Buttons ```Elm type alias ShipUIModuleButton = { uiNode : UITreeNodeWithDisplayRegion , slotUINode : UITreeNodeWithDisplayRegion , isActive : Maybe Bool , isHiliteVisible : Bool , rampRotationMilli : Maybe Int } ``` The ship UI displays ship modules in the form of module buttons. The game client UI lets us group modules, so one module button can represent a single module or multiple grouped modules. We can look at these module buttons to learn about the state of the modules, and we can also click on them to toggle the module activity. Some bots identify ship modules by their display location because this is faster than reading the tooltips. You can find some bots descriptions calling for arranging modules into the three available rows based on the role of the module. Other bots read the module tooltips to identify the module behind the button. These bots don't require a particular arrangement of the module buttons because they remember the tooltip of each button. To access the modules grouped into `top`, `middle`, and `bottom`, use the field `moduleButtonsRows`. ![Ship UI modules grouped into rows](./image/2020-03-11-eve-online-ship-ui-module-rows-names.png) ## Module Button Tooltip ![Module Button Tooltip](./image/2020-05-13-eve-online-module-button-tooltip-scaled.png) ```Elm type alias ModuleButtonTooltip = { uiNode : UITreeNodeWithDisplayRegion , shortcut : Maybe { text : String, parseResult : Result String (List Common.EffectOnWindow.VirtualKeyCode) } , optimalRange : Maybe { asString : String, inMeters : Result String Int } } ``` The module button tooltip helps us to learn more about the module buttons displayed in the ship UI. This UI element appears when we move the mouse over a module button and shows details of the ship module(s) it represents. Use the function `getAllContainedDisplayTexts` to get the texts contained in the tooltip. Besides information about the modules, the tooltip also shows the keyboard shortcut to toggle the activity of the module(s). The framework parses these into representations of the keyboard keys. You can use this list of keys to toggle modules without using the mouse. ### Linking a Tooltip With Its Module Button For the module button tooltip to be useful, we usually want to know which module button it belongs to. The easiest way to establish this link is by using the `isHiliteVisible` field on the module button: When you move the mouse over a module button to trigger the tooltip, you can see `isHiliteVisible` switches to `True` for the module button. Apps use this approach and then remember the tooltip for each module button. There are common functions to update a memory structure holding this information, most importantly `integrateCurrentReadingsIntoShipModulesMemory` in the mining bot example. ## Inventory Window ```Elm type alias InventoryWindow = { uiNode : UITreeNodeWithDisplayRegion , leftTreeEntries : List InventoryWindowLeftTreeEntry , subCaptionLabelText : Maybe String , selectedContainerCapacityGauge : Maybe (Result String InventoryWindowCapacityGauge) , selectedContainerInventory : Maybe Inventory , buttonToSwitchToListView : Maybe UITreeNodeWithDisplayRegion , buttonToStackAll : Maybe UITreeNodeWithDisplayRegion } ``` To work with items in the inventory, use the field `selectedContainerInventory` in the inventory window. In the field `itemsView`, you get this list of items visible in the selected container: ![Inventory items](./image/2020-03-11-eve-online-parsed-user-interface-inventory-inspect.png) Are looking for an item with a specific name? You could use the filtering function in the game client, but there is an easier way: Using the function `getAllContainedDisplayTexts` on the inventory item, you can filter the list of items immediately. As you can also see in the screenshot of the live inspector, we get the used, selected, and maximum capacity of the selected container with the field `selectedContainerCapacityGauge`. You can compare the `used` and `maximum` values to see if the container is (almost) full. [Mining bots do this](https://github.com/Viir/bots/blob/eca3adf93f2b6fd31ff0c38e4118a4e31759d9c6/implement/applications/eve-online/eve-online-mining-bot/Bot.elm#L1353-L1358) on the mining hold to know when to travel to the unload location. ## Drones Window The 'Drones' window offers controls for the drones in your ship's drone bay. ![Drones window](./image/2021-02-23-briancorner-eve-online-drones-window.png) This window shows the drones aggregated into collapsible groups. These groups can be nested, as shown in the screenshot. Because of the possibility of nesting, the types represent these UI elements as tree structures. Each of the top-level groups has its tree structure that can contain other groups or individual drones. To command your drones, open a context menu on a drone or a drone group (header) and use one of the menu entries to let your drone(s) launch, engage, return, etc. To get a list of all drones in one group, for example, to check their hitpoints, use the `enumerateAllDronesFromDronesGroup` function. ```Elm type alias DronesWindow = { uiNode : UITreeNodeWithDisplayRegion , droneGroups : List DronesWindowEntryGroupStructure , droneGroupInBay : Maybe DronesWindowEntryGroupStructure , droneGroupInSpace : Maybe DronesWindowEntryGroupStructure } type alias DronesWindowEntryGroupStructure = { header : DronesWindowDroneGroupHeader , children : List DronesWindowEntry } type DronesWindowEntry = DronesWindowEntryGroup DronesWindowEntryGroupStructure | DronesWindowEntryDrone DronesWindowEntryDroneStructure type alias DronesWindowDroneGroupHeader = { uiNode : UITreeNodeWithDisplayRegion , mainText : Maybe String , quantityFromTitle : Maybe DronesWindowDroneGroupHeaderQuantity } type alias DronesWindowDroneGroupHeaderQuantity = { current : Int , maximum : Maybe Int } type alias DronesWindowEntryDroneStructure = { uiNode : UITreeNodeWithDisplayRegion , mainText : Maybe String , hitpointsPercent : Maybe Hitpoints } ``` ## Repairshop Window In the 'Repairshop'/'Repair Facilities' window, you can repair your ship. ```Elm type alias RepairShopWindow = { uiNode : UITreeNodeWithDisplayRegion , items : List UITreeNodeWithDisplayRegion , buttonGroup : Maybe UITreeNodeWithDisplayRegion , buttons : List { uiNode : UITreeNodeWithDisplayRegion, mainText : Maybe String } } ``` ![Repairshop window](./image/2020-07-19-BrianCorner-eve-online-repair-all.png) <file_sep>#r "mscorlib" #r "netstandard" #r "System" #r "System.Collections.Immutable" #r "System.IO.Compression" #r "System.Net" #r "System.Linq" #r "System.Text.Json" using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; class Request { public ConsoleBeepStructure[] EffectConsoleBeepSequence { set; get; } public struct ConsoleBeepStructure { public int frequency { set; get; } public int durationInMs { set; get; } } } class Response { public object CompletedOtherEffect; } string serialRequest(string serializedRequest) { var requestStructure = System.Text.Json.JsonSerializer.Deserialize<Request>(serializedRequest); var response = request(requestStructure); return SerializeToJsonForBot(response); } Response request(Request request) { if (request?.EffectConsoleBeepSequence != null) { foreach (var beep in request?.EffectConsoleBeepSequence) { if (beep.frequency == 0) // Avoid exception "The frequency must be between 37 and 32767." System.Threading.Thread.Sleep(beep.durationInMs); else System.Console.Beep(beep.frequency, beep.durationInMs); } return new Response { CompletedOtherEffect = new object(), }; } return null; } string SerializeToJsonForBot<T>(T value) => System.Text.Json.JsonSerializer.Serialize(value); string InterfaceToHost_Request(string request) { return serialRequest(request); } <file_sep># BotLab Online Session When starting a play session with a bot, you can choose to start an online session. Online sessions provide several advantages over offline sessions: + Monitoring from other devices: No need to go to your PC to check the status of your bot. You can use your smartphone or any other device with a web browser to see the status of your bot. + Organize and keep track of your operations and experiments: Easily see which bots you already tested and when you used them the last time. + Longer running time: Run a bot continuously in one session for up to 72 hours. To see a list of your most recent online sessions, log in at <https://reactor.botlab.org> Below is a screenshot of the website to view your online sessions and monitor your bots: ![viewing details of an online play session with a bot](./image/2021-11-30-botlab-reactor-online-session-detail.png) Online sessions cost 2000 credits per hour. When you log in to your account for the first time, you automatically get 1000 credits. Using these initial credits balance, you can test the online session feature without paying anything (Creating an account is free). When you have used up the credits on your account, you can add more following the instructions at <https://reactor.botlab.org/billing/add-credits> For more about purchasing and using credits, see the guide at <https://forum.botlab.org/t/purchasing-and-using-botlab-credits-frequently-asked-questions-faq/837> ### Starting an Online Session Follow these steps to start a bot in an online session: + Load a bot in the BotLab client to get to the 'Configure Session' view. + Scroll down to the 'Online Session' section. + Click on the checkbox at 'Connect to the BotLab Reactor and start an online session'. + Continue with other configurations (bot settings, pause keys) as usual, and start the play session. ![configure session to start online session](./image/2022-12-02-botlab-client-configure-session-online-session-marked.png) The first time you start an online session, the client will ask you to enter your online session key from your Reactor account: ![botlab client prompt for online session key](./image/2022-12-02-botlab-client-confirm-online-session.png) Here you need to enter your online session key to continue. To get the key to enter here, go to <https://reactor.botlab.org> and log in to your account. After logging in, you see a section titled `Online play session keys`. In this section, there is an entry for a key, containing a button labeled `Show key`. Clicking this button reveals your key. Please don't share this key with anyone, and don't post it on the forum. ![Web UI displaying online session key](./image/2021-11-30-botlab-reactor-show-online-session-key.png) Copy the key from the web page and paste it into the botlab console window. Press the enter key to complete the input. BotLab then checks the key and continues to start the bot in an online session. The BotLab client also stores the entered key in the Windows user account, so you don't have to enter it the next time you start an online session. After starting an online session, you can also see it at <https://reactor.botlab.org> under `Most recent play sessions`: ![List of most recent online sessions](./image/2021-11-30-botlab-reactor-dashboard-recent-sessions.png) Clicking on the session ID brings you to the details view of the session, where you can also see the status reported by the bot. The sessions under `Most recent play sessions` are still available after stopping the BotLab client, so you can continue to view details of past sessions. ## Getting Help If you have any questions, the [BotLab forum](https://forum.botlab.org) is a good place to learn more. <file_sep># 2020-05-20 Read Battle Reports in Tribal Wars 2 ## Motivation From the conversation at https://forum.botengine.org/t/farm-manager-tribal-wars-2-farmbot/3038/87?u=viir > I was wondering if there is a way to make sure the bot doesn’t send a farm to a specific village? Some barbarian villages of players who stopped playing still have walls, so everytime a farm is sent there some troops die. > [...] > At the moment, there is no quick way to avoid a specific village. > I could expand the bot to support these scenarios: It could read the battle reports and avoid villages where troops died in the last 24 hours. > [...] ## Exploring Implementation Found this way to read a list of battle reports: ```javacript reportService = angular.element(document.body).injector().get('reportService'); reportService.requestReportList('battle', 0, 100, null, { "BATTLE_RESULTS": { "1": false, "2": false, "3": false }, "BATTLE_TYPES": { "attack": true, "defense": true, "support": true, "scouting": true }, "OTHERS_TYPES": { "trade": true, "system": true, "misc": true }, "MISC": { "favourite": false, "full_haul": false, "forwarded": false, "character": false } }, function (data) { console.log(JSON.stringify(data)); }); ``` What values does `requestReportList` support for the `filters` parameter? I used `JSON.stringify` on a value for `filters` coming from the `ReportListController` (`$scope.activeFilters` in the calling site) and got this: ``` "{"BATTLE_RESULTS":{"1":false,"2":false,"3":false},"BATTLE_TYPES":{"attack":true,"defense":true,"support":true,"scouting":true},"OTHERS_TYPES":{"trade":true,"system":true,"misc":true},"MISC":{"favourite":false,"full_haul":false,"forwarded":false,"character":false}}" ``` The above `filters` variant was with all visible; at least that was the intention. Let's see what `filters` we find when using the filters in the UI: Victory with casualties: ``` "{"BATTLE_RESULTS":{"1":false,"2":true,"3":false},"BATTLE_TYPES":{"attack":true,"defense":true,"support":true,"scouting":true},"OTHERS_TYPES":{"trade":true,"system":true,"misc":true},"MISC":{"favourite":false,"full_haul":false,"forwarded":false,"character":false}}" ``` Defeat: ``` "{"BATTLE_RESULTS":{"1":false,"2":false,"3":true},"BATTLE_TYPES":{"attack":true,"defense":true,"support":true,"scouting":true},"OTHERS_TYPES":{"trade":true,"system":true,"misc":true},"MISC":{"favourite":false,"full_haul":false,"forwarded":false,"character":false}}" ``` Here is a result returned 2020-05-20: ```json { "offset": 0, "total": 2, "reports": [ { "id": 1137257, "time_created": 1589744135, "type": "attack", "title": "Segundo pueblo de John ataca (ESTRELLA DEL NORTE )", "favourite": 0, "haul": "partial", "result": 2, "token": "<KEY>", "read": 0 }, { "id": 1093285, "time_created": 1589698147, "type": "attack", "title": "Segundo pueblo de John ataca (ESTRELLA DEL NORTE )", "favourite": 0, "haul": "full", "result": 2, "token": "1<PASSWORD>.123456.8<PASSWORD>", "read": 0 } ] } ``` Now lets get details for a report: ```javascript reportService.getReport(1137257, function (data) { console.log(JSON.stringify(data)); }); ``` This gets us: ```json { "id": 1137257, "time_created": 1589744135, "title": "Segundo pueblo de John ataca (ESTRELLA DEL NORTE )", "favourite": 0, "haul": "partial", "result": 2, "token": "<KEY>", "type": "ReportAttack", "ReportAttack": { "outcome": 17, "attUnits": { "spear": 12, "sword": 0, "axe": 0, "archer": 0, "light_cavalry": 0, "heavy_cavalry": 0, "mounted_archer": 0, "ram": 0, "catapult": 0, "knight": 0, "snob": 0, "trebuchet": 0, "doppelsoldner": 0 }, "attLosses": { "spear": 4, "sword": 0, "axe": 0, "archer": 0, "light_cavalry": 0, "heavy_cavalry": 0, "mounted_archer": 0, "ram": 0, "catapult": 0, "knight": 0, "snob": 0, "trebuchet": 0, "doppelsoldner": 0 }, "attRevived": [], "attFaith": 0.5, "attModifier": 0.5650000000000001, "attEffects": [], "attWon": true, "defUnits": { "spear": 0, "sword": 0, "axe": 0, "archer": 0, "light_cavalry": 0, "heavy_cavalry": 0, "mounted_archer": 0, "ram": 0, "catapult": 0, "knight": 0, "snob": 0, "trebuchet": 0, "doppelsoldner": 0 }, "defLosses": { "spear": 0, "sword": 0, "axe": 0, "archer": 0, "light_cavalry": 0, "heavy_cavalry": 0, "mounted_archer": 0, "ram": 0, "catapult": 0, "knight": 0, "snob": 0, "trebuchet": 0, "doppelsoldner": 0 }, "defRevived": null, "defFaith": 0.5, "defModifier": 0.5, "defEffects": [], "officers": { "leader": false, "loot_master": false, "medic": false, "scout": false, "supporter": false, "bastard": false }, "loyaltyBefore": null, "loyaltyAfter": null, "luck": 1.1300000000000001, "morale": 1, "leader": 1, "wallBonus": 0.1499999999999999, "night": false, "farmRule": 1, "wallBefore": null, "wallAfter": null, "building": null, "buildingBefore": null, "buildingAfter": null, "haul": { "wood": 25, "clay": 28, "iron": 28, "food": 0 }, "capacity": 200, "storage": null, "buildings": { "timber_camp": 9, "clay_pit": 10, "iron_mine": 10 }, "attCharacterIcon": 0, "defCharacterIcon": null, "attVillageId": 1617, "attVillageName": "Segundo pueblo de John", "attVillageX": 511, "attVillageY": 488, "attCharacterId": 123456, "attCharacterName": "John", "defVillageId": 2170, "defVillageName": "ESTRELLA DEL NORTE", "defVillageX": 499, "defVillageY": 459, "defCharacterId": 0, "defCharacterName": null } } ``` tags:tribal-wars-2,explore,botengine<file_sep># Observing and Inspecting a Bot Observations are the basis for improving a bot. One way of observing a bot is to watch the BotLab client window and the game client on a screen. That is what you see anyway when running a bot. The BotLab client window displays the status text from the bot and thus helps with the inspection. But this mode of observing is limiting in two ways. It is limiting because it requires us to process everything in real-time. But in most cases, information flows too fast for us to keep up. Things happen so quickly that we cannot even read all the status messages. We could pause the bot to have more time to read, but that leads to other problems since every break distorts the bot's perception of the environment. The second limitation is the merely superficial representation we find in this mode. To understand how a bot works, we need to make visible more than just the status texts. When investigating a bot's behavior, we want to follow the data-flow backward. Seeing the status text and the effects emitted by the bot in response to an event is only the first step in this process. While this simple way of observing is severely limiting, it can work. We can offset the incomplete observations with more experiments. Ten hours of tests could save us one hour of careful inspection. But we don't have to make it so difficult for ourselves. These problems with observability are not new, and there are tools to help us overcome these limitations. ## DevTools and Time Travel The first step to enable observability is to decouple the observation time from the bot running time. Our development tools allow us to go back to any point in time and see everything as it was back then. Let's see how this works in practice. To travel back in time, we need a play session recording. The BotLab client automatically saves a recording to disk by default when we run a bot. To inspect completed play sessions, we use the `Devtools` in the BotLab client: ![Opening DevTools from the main menu](./image/2021-12-09-botlab-client-main-menu-enter-devtools.png) A button in the main menu brings us into the `Devtools` view: ![DevTools view in the botlab client](./image/2021-12-09-botlab-client-devtools-default.png) Here we see a link to a web page on the `localhost` domain. Clicking that link brings opens a web browser. The actual graphical user interface for the Devtools is on this web page. On that web page, we find a list of recent sessions, the last one at the top: ![DevTools - choose a session to inspect](./image/2021-12-09-botlab-devtools-select-session.png) Clicking on one of the sessions' names brings us into the view of this particular session: ![DevTools - initial view of a session](./image/2021-12-09-botlab-devtools-session-summary.png) In the session view, we have a timeline of events in that session. Clicking on an event in the timeline opens the details for this event. The event details also contain the bot's response to this event. ![DevTools - view of play session event details](./image/2021-12-09-botlab-devtools-session-event-details.png) Besides the complete response, we also see the status text, which is part of the response but repeated in a dedicated section for better readability. Some events inform the bot about the completion of reading from the game client. For these events, the event details also show a visualization of the reading. For EVE Online, a common way to read from the game client is using memory reading. That is why we don't see a screenshot here, but a (limited) visualization. ![DevTools - view of play session event details - EVE Online specific part](./image/2021-12-09-botlab-devtools-session-event-details-eve-online-reading.png) This visualization shows the display regions of UI elements and some of the display texts. Using the button "Download reading as JSON file", we can export this memory reading for further examination. The inspection tools found in the alternate UI for EVE Online help us with that. You can find those tools at <https://botlabs.blob.core.windows.net/blob-library/by-name/2023-06-21-eve-online-alternate-ui.html> (If you want to enable the Elm inspector ('debugger') tool too, you can use the variant at <https://botlabs.blob.core.windows.net/blob-library/by-name/2023-06-21-eve-online-alternate-ui-with-inspector.html>) ## Sharing Observations To collaborate on the development of a bot, we often need to communicate scenarios, situations in which we want the bot to work. One way to describe such a scenario is to use the recording of an actual session as it happened. To export any session displayed in the DevTools, use the `Download session recording archive` button. This gets you a zip archive that you can then share with other people. Now you can get help from other developers for your exact situation, no matter if the solution requires a change in program code or just different bot-settings. To import such a session archive in DevTools, use the `import artifact` button in the Devtools view in the botlab client: ![Import artifact in DevTools](./image/2021-12-09-botlab-client-devtools-import-artifact.png) When you start DevTools this way, the session from the specified path will show up at the top of the list of sessions in the DevTools UI: ![DevTools - choose a session to inspect](./image/2021-12-09-botlab-devtools-select-session-with-imported.png) <file_sep># Common Player Agent Interface ## Motivation for a Common Player Agent Interface The common interface for player agents results from the cost reduction it implies in bot development projects. Bot developers typically spend the most effort on tests depending on the environment. This environment can be a live game client, as would be the case during productive use of the bot. Because setting up a live game client is often relatively expensive, most tests happen with environment programs that simulate a game client. The standard interface to the player agent enables the reuse of existing simulation programs for more bot development projects. <file_sep># 2020-02-07 EVE Online - Anomaly Ratting This time, my goal is to find an implementation for an EVE Online anomaly ratting bot. So, where do I get the information from that allows me to write code? The source of information is feedback from playing the game. Usually, most or all of this feedback comes from other people who share their observations in various ways, such as publishing training data sets. There is also another way to get the training data: I will soon have access to a game account with a setup sufficient for anomaly ratting. This way, I can do the live testing myself and get the training data faster. As a result, I can find a working bot within a few hours. For me, there is yet another source of information: The experience with A-Bot, which was an earlier anomaly ratting bot. Since this project started in 2016, we already got a lot of feedback on the approach there. So I learned that an architecture based on a decision tree is sufficient for this activity and works well. Also, the source code from A-Bot encodes the knowledge of how to do the ratting in-game. It is easy for me to understand because it is organized to follow the same coding principles as explained in the guide on developing for EVE Online (In the [navigation basics](https://github.com/Viir/bots/blob/master/guide/eve-online/developing-bots-for-eve-online.md#navigation-basics) chapter) Before writing the first piece of code, my idea is to start with the combat part of the bot. When I see that the combat works, I can add other components, like finding anomalies and warping there. The mining bot example project already implements a decision tree (https://forum.botengine.org/t/how-to-automate-mining-asteroids-in-eve-online/628/109?u=viir), so I start implementation by copying the mining bot code. I want to speed up the development process, so I will use a trick to get a head start: Before even attempting the first live test with a game client, I try to convert the combat part of A-Bot, coded in the file [`Combat.cs`](https://github.com/botengine-de/A-Bot/blob/2fc03f1345955ad068da17b862f05cee8daab195/src/Sanderling.ABot/Bot/Task/Combat.cs) This combat function is distributed over 53 lines of code and contains a lot of information we can reuse for ratting. One way to summarize it is to list the subtrees it emits that can lead to effects: + Unlock target. + Lock target. + Activate weapon module. + Launch drones. + Engage drones. + Return drones to the bay. The unlocking of targets might have been added because there is a risk that a bot will accidentally target the wrong object. Even if this happens only one out of ten thousand times, accounting for this helps avoid interruptions. Let's take a closer look at locking new targets: The way it uses `TargetCountMax`, we can see that it will lock multiple targets, to allow us to continue attacking as fast as possible when one target is defeated. This feature makes the bot more efficient as it will avoid waiting for new target locks during operation. The downside is it makes the code more complex than the simplest possible combat function, but since it is easy to translate this code, it is OK to use this extra feature right from the start. We can also see that there is some filtering going on to find the next overview entry to lock a target: It is not sufficient to look for entries which represent rats to attack, because we might already have locked that object. To avoid this, the combat function filters out the overview entries which have any of these icons: + Indicating we have locked the object as target. + Indicating we are in the process of locking the object as target. You find this filtering expression on [line 87](https://github.com/botengine-de/A-Bot/blob/2fc03f1345955ad068da17b862f05cee8daab195/src/Sanderling.ABot/Bot/Task/Combat.cs#L87) Attempting a rough translation of the A-Bot combat function, I arrive at this decision tree: + Branch: Is there a target to unlock? + Yes: Unlock that target. + No: Branch: Is there at least one locked target? + No: Branch: Is there at least one overview entry to attack? + No: Return to integrating function: We are done here. + Yes: Use 'Lock target' on that overview entry. + Yes: Branch: Is there any inactive weapon module? + Yes: Activate that module. + No: Branch: Is the number of drones in the bay greater than 0 and the number of drones in space less than 5? + Yes: Launch drones from bay. + No: Branch: Are there drones in local space idling? + Yes: Engage drones. + No: Branch: Is there an overview entry that we should lock as target? (See the filtering of overview entries explained above) + Yes: Use 'Lock target' on that overview entry. + No: Wait To identify the weapon modules, we can reuse the approach from the mining bot: Let the user place the modules so that only weapon modules are in the upmost row: https://github.com/Viir/bots/blob/d2c881f35b59bdbdd6616b8f1c1e40332c403558/implement/applications/eve-online/eve-online-mining-bot/src/Bot.elm#L13 We can use the second row for modules that should always be active. Since the mining bot already implements the grouping of modules into rows, we can copy the code from there. <file_sep># EVE Online Players Strategies ### Travel - Bounce of Celestial to Avoid Gate Campers [MutantWizard](https://forum.botlab.org/u/MutantWizard) described it at https://forum.botlab.org/t/how-to-automate-mining-asteroids-in-eve-online/628/61?u=viir: > Do you think it might be interesting to implement a bounce of a random celestial where the route takes one through a system other than high sec? > Its a standard strategy for trying to avoid gate campers deploying bubbles and smart bombs. Normally a traveler is expected to warp from gate to gate so his trajectory is reasonable foreseeable. Gate campers would often deploy bubbles on this trajectory or wait for a traveler to come out of warp on this trajectory. To avoid the trajectory traps we often warp from the system entry gate to some celestial and then from there to the exit gate. this changes the foreseeable trajectory and adds a bit of a safety margin. If its not a major development task it may be worth while considering. <file_sep>using System; using System.Linq; using System.Text.RegularExpressions; namespace eve_online_memory_reading { class Program { /* This program reads from the memory of an EVE Online client process. The memory reading approach here is based on the example from https://forum.botengine.org/t/advanced-do-it-yourself-memory-reading-in-eve-online/68 In contrast to the original code, this version also supports reading from a file containing a sample of the client process. This allows us to repeat the reading as often we want, without having to start an instance of the game client. For a guide on how to save a Windows process to a file, see https://forum.botengine.org/t/how-to-collect-samples-for-memory-reading-development/50 Example command line: dotnet run -- --source="C:\path-to-a-process-sample-file.zip" --output="C:\path\to\directory\with\write\access" */ static void Main(string[] args) { var outputPathParamName = "--output"; (bool isPresent, string argumentValue) argumentFromParameterName(string parameterName) { var match = args .Select(arg => Regex.Match(arg, parameterName + "(=(.*)|)", RegexOptions.IgnoreCase)) .FirstOrDefault(match => match.Success); if (match == null) return (false, null); if (match.Groups[1].Length < 1) return (true, null); return (true, match?.Groups[2].Value); } var sourceArgument = argumentFromParameterName("--source").argumentValue; var outputPathArgument = argumentFromParameterName(outputPathParamName).argumentValue; IMemoryReader memoryReader = null; try { string sampleId = null; if (0 < sourceArgument?.Length) { Console.WriteLine("I got the following source and will load from this file: '" + sourceArgument + "'"); var sampleFile = System.IO.File.ReadAllBytes(sourceArgument); sampleId = CommonConversion.StringIdentifierFromValue(sampleFile); Console.WriteLine("Loaded sample " + sampleId + " from '" + sourceArgument + "'"); var sampleStructure = BotEngine.ProcessMeasurement.MeasurementFromZipArchive(sampleFile); memoryReader = new SampleMemoryReader(sampleStructure); } else { Console.WriteLine("I did not receive a path to a sample file, so I will try to find a live EVE Online client process to read from."); var MengeCandidateProcess = System.Diagnostics.Process.GetProcessesByName("exefile"); var gameClientProcess = MengeCandidateProcess.FirstOrDefault(); if (null == gameClientProcess) { Console.WriteLine("I did not find an EVE Online client process."); return; } memoryReader = new ProcessMemoryReader(gameClientProcess); } var pythonMemoryReader = new PythonMemoryReader(memoryReader); var uiTreeRoot = EveOnline.UITreeRoot(pythonMemoryReader); if (null == uiTreeRoot) { Console.WriteLine("Did not find the root of the UI tree."); return; } Console.WriteLine("Found the root of the UI tree at {0} (0x{0:X})", uiTreeRoot.BaseAddress); var allNodes = new UITreeNode[] { uiTreeRoot } .Concat(uiTreeRoot.EnumerateChildrenTransitive(pythonMemoryReader)).ToArray(); Console.WriteLine("Found {0} nodes in this UI tree.", allNodes.Length); var representationForReading = System.Text.Encoding.UTF8.GetBytes( Newtonsoft.Json.JsonConvert.SerializeObject(InspectUITreeNode(uiTreeRoot), Newtonsoft.Json.Formatting.Indented)); Console.WriteLine("The representation for reading has the id '{0}'.", CommonConversion.StringIdentifierFromValue(representationForReading)); if (outputPathArgument == null) { Console.WriteLine("Did not receive a path to write the results for reading. Add the '" + outputPathParamName + "' argument to specify the directory to write the results to."); return; } Console.WriteLine("I write the result to '{0}'.", outputPathArgument); System.IO.Directory.CreateDirectory(outputPathArgument); var outputFilePath = System.IO.Path.Combine(outputPathArgument, "memory-reading-from-sample-" + sampleId?.Substring(0, 8) + ".json"); System.IO.File.WriteAllBytes(outputFilePath, representationForReading); } finally { (memoryReader as IDisposable)?.Dispose(); } } static object InspectUITreeNode(UITreeNode node) { var children = node.children ?.Select(InspectUITreeNode) ?.ToList(); var dictEntriesWithStringKey = node.Dict?.Slots ?.Where(slot => slot.KeyStr != null) ?.Select(slot => { return new { keyString = slot.KeyStr, value_address = slot.me_value.ToString(), }; }).ToList(); return new { address = node.BaseAddress, dictEntriesWithStringKey = dictEntriesWithStringKey, children = children, }; } } } <file_sep># Elvenar Bot This bot collects coins in the Elvenar game client window. It locates the coins over residential buildings in the Elvenar window and then clicks on them to collect them 🪙 ## Setup and starting the bot If the BotLab client is not already installed on your machine, follow the guide at <https://to.botlab.org/guide/how-to-install-the-botlab-client> The BotLab client is a tool for developing bots and also makes running bots easier with graphical user interfaces for configuration. In the BotLab client, load the bot by entering the following link in the 'Select Bot' view: <https://catalog.botlab.org/3e28ced601b84b5c> There is a detailed walkthrough video on how to load and run a bot at <https://to.botlab.org/guide/video/how-to-run-a-bot-live> Follow these steps to start a new bot session: + Load Elvenar in a web browser. + Ensure the product of the display 'scale' setting in Windows and the 'zoom' setting in the web browser is 125%. If the 'scale' in Windows settings is 100%, zoom the web browser tab to 125%. If the 'scale' in Windows settings is 125%, zoom the web browser tab to 100%. + Elvenar offers you five different zoom levels. Zoom to the middle level to ensure the bot will correctly recognize the icons in the game. (You can change zoom levels using the mouse wheel or via the looking glass icons in the settings menu) + Start the bot and immediately click on the web browser containing Elvenar. From here on, the bot works automatically, periodically checking for and collecting coins. > The bot picks the topmost window in the display order, the one in the front. This selection happens once when starting the bot. The bot then remembers the window address and continues working on the same window. > To use this bot, bring the Elvenar game client window to the foreground after pressing the button to run the bot. When the bot displays the window title in the status text, it has completed the selection of the game window. You can test this bot by placing a screenshot in a paint app like MS Paint or Paint.NET, where you can quickly change its location within the window. You can see the training data samples used to develop this bot at <https://github.com/Viir/bots/tree/71d857d01597a3dfa36c5724be79e85c44dfd3ae/implement/applications/elvenar/training-data> ## Getting Help If you have any questions, the [BotLab forum](https://forum.botlab.org) is a good place to learn more. You can also contact me at [<EMAIL>](mailto:<EMAIL>?subject=Tribal%20Wars%202%20Farmbot%20-%20your%20issue%20here) When asking for help with the bot, include one of these two artifacts to help us see what happened on your setup: + The summary from the `Report Problem or Share Session` dialog in the play session interface. Either upload the saved JSON file or copy the text in that file. To reach this dialog, use the buttons labeled `Get Help With This Bot Session` and then `Report Problem or Share Session`. + The play session recording archive from the session view in DevTools. <file_sep>using System; namespace eve_online_memory_reading { public class PyStr : PyObject { readonly public string String; public PyStr( Int64 BaseAddress, IMemoryReader MemoryReader) : base(BaseAddress, MemoryReader) { String = MemoryReader.ReadStringAsciiNullTerminated(BaseAddress + 20); } } } <file_sep># EVE Online Combat Anomaly Bot This bot uses the probe scanner to find combat anomalies and kills rats using drones and weapon modules. ## Features + Automatically detects if another pilot is in an anomaly on arrival and switches to another anomaly if necessary. + Filtering for specific anomalies using bot settings. + Avoiding dangerous or too-powerful rats using bot settings. + Remembers observed properties of anomalies, like other pilots or dangerous rats, to inform the selection of anomalies in the future. ## Setting up the Game Client Despite being quite robust, this bot is less intelligent than a human. For example, its perception is more limited than ours, so we need to set up the game to ensure that the bot can see everything it needs. Following is the list of setup instructions for the EVE Online client: + Set the UI language to English. + Undock, open probe scanner, overview window and drones window. + Set the Overview window to sort objects in space by distance with the nearest entry at the top. + In the ship UI, arrange the modules: + Place the modules to use in combat (to activate on targets) in the top row. + Hide passive modules by disabling the check-box `Display Passive Modules`. + Configure the keyboard key 'W' to make the ship orbit. ## Starting the Bot If the BotLab client is not already installed on your machine, follow the guide at <https://to.botlab.org/guide/how-to-install-the-botlab-client> The BotLab client is a tool for developing bots and also makes running bots easier with graphical user interfaces for configuration. In the BotLab client, load the bot by entering the following link in the 'Select Bot' view: <https://catalog.botlab.org/aa232fa52a38e9c9> There is a detailed walkthrough video on how to load and run a bot at <https://to.botlab.org/guide/video/how-to-run-a-bot-live> The bot needs a few seconds to start and find the EVE Online client process. It also shows status messages to inform what it is doing at the moment and when the startup is complete. ![EVE Online Bot Starting](./image/2023-03-08-botlab-gui-eve-online-bot-startup.png) From here on, the bot works automatically. It detects the topmost game client window and starts working in that game client. ## Configuration Settings All settings are optional; you only need them in case the defaults don't fit your use-case. + `anomaly-name` : Choose the name of anomalies to take. You can use this setting multiple times to select multiple names. + `hide-when-neutral-in-local` : Set this to 'yes' to make the bot dock in a station or structure when a neutral or hostile appears in the 'local' chat. + `avoid-rat` : Name of a rat to avoid, as it appears in the overview. You can use this setting multiple times to select multiple names. + `activate-module-always` : Text found in tooltips of ship modules that should always be active. For example: "shield hardener". + `anomaly-wait-time`: Minimum time to wait after arriving in an anomaly before considering it finished. Use this if you see anomalies in which rats arrive later than you arrive on grid. When using more than one setting, start a new line for each setting in the text input field. Here is an example of a complete settings string: ``` anomaly-name = Drone Patrol anomaly-name = Drone Horde hide-when-neutral-in-local = yes avoid-rat = Infested Carrier activate-module-always = shield hardener ``` ---- In case I forgot to add something here or you have any questions, don't hesitate to ask on the [BotLab forum](https://forum.botlab.org/). ## Pricing and Online Sessions You can test the bot for free. When you want the bot to run more than 15 minutes per session, use an online session as explained at <https://to.botlab.org/guide/online-session> Online sessions cost 2000 credits per hour. To add credits to your account, follow the instructions at <https://reactor.botlab.org/billing/add-credits> For more about purchasing and using credits, see the guide at <https://forum.botlab.org/t/purchasing-and-using-botlab-credits-frequently-asked-questions-faq/837> ## Running Multiple Instances This bot supports running multiple instances on the same desktop. In such a scenario, the individual bot instances take turns sending input and coordinate to avoid interfering with each other's input. To learn more about multi-instance setup, see <https://to.botlab.org/guide/running-bots-on-multiple-game-clients> <file_sep># 2019-12-30 Explore Tribal Wars 2 The goal is to find a better process to farm barbarian villages in Tribal Wars 2. Older approaches are limited by the bug in the games user interface: https://forum.botengine.org/t/farm-manager-tribal-wars-2-farmbot/1406/209?u=viir Last ideas to implement the automation: > Seeing this screenshot, I remembered more details about the game: > As far as I remember, there was some way to open the village context menu for given coordinates. If this (still) exists we could even scan all coordinates around your villages to search for barbarians. We could enumerate all possible coordinates in a given radius from your villages, ordered by distance, and try to open the village menu for these. > > Then we would not need the reports anymore to learn the coordinates of villages. Then the bugs in the report list UI would not anymore limit the bot. > > If we can find a way to open the list seen in the screenshot, we could speed up this scanning process by filtering out some of the coordinates earlier. > > About distinguishing between barbarians and other: > The formular to send an army might look different if there is a player owning the destination village. ## Explore Live Open chrome devtools. In the 'Elements' panel, find an element like this: ```HTML <div id="map" role="main" tabindex="1" ng-controller="MapController" ng-class="{running: isInitialized}" class="running"> <div ng-embedded-include="true"> [...] ``` Get the `MapController` in the chrome devtools console: ```javascript angular.element(document.getElementById('map')).controller() ``` Now we can jump to coordinates on the map: ```javascript angular.element(document.getElementById('map')).controller().jumpTo(494,502) ``` But, using the approach above, the context menu does not open, even if there is a village at that location. Maybe it is easier to stay close to the UI, open the map by clicking on this element: ```HTML <a id="world-map" href="#" ng-click="toggleWorldMapSearch($event)" class="btn-orange icon-44x44-view-worldmap" tooltip="" tooltip-content="Busca en el Mapa Mundial" internal-id="52"></a> ``` ```javascript document.getElementById('world-map').click() ``` A new element appears: ```HTML <div id="world-map-search-wrapper" world-map-search=""><div id="world-map-search-0xc" class="directive-world-map-search box-border-dark box-wrapper visible"> <div> <table [...] ``` Looking closer into the javascript related to that part of the UI, find this interesting part: ```javascript define('directives/WorldMapSearchDirective',['app', 'battlecat', 'conf/conf', 'helper/dom', 'helper/parse', 'generators/generate'], function(app, $, conf, domHelper, parseHelper, generate) { app.directive('worldMapSearch', ['$rootScope', 'eventTypeProvider', 'linkService', '$filter', 'mapService', 'storageService', 'modelDataService', 'autoCompleteService', function($rootScope, eventTypeProvider, linkService, $filter, mapService, storageService, modelDataService, autoCompleteService) { var textObject = 'directive_world_map'; [...] /** * Uses some events to jump on the specified coordinates. * * @param {Object} item item to jump to */ jumpTo = function jumpTo(item) { validateCoordinates(item); if (item.type === 'village') { mapService.jumpToVillage(item.x, item.y, item.id); } else { autoCompleteService.villageByCoordinates(item, function(data) { mapService.jumpToVillage(item.x, item.y, data.id); }); } }, ``` Seems that is the `jumpTo` that is used in the world map search. If we could get references to `autoCompleteService` and `mapService`, then maybe we can use these without depending on clicks. Get the services: ```javascript autoCompleteService = angular.element(document.body).injector().get('autoCompleteService') mapService = angular.element(document.body).injector().get('mapService') ``` Now we can build a function to jump to coordinates and also open the menu if a village is there: ```javascript jumpTo = function jumpTo(item) { autoCompleteService.villageByCoordinates(item, function(data) { mapService.jumpToVillage(item.x, item.y, data.id); }); } ``` And use it like this: ```javascript jumpTo({x:501,y:501}) ``` <file_sep># Bot Development Language and Terms This document explains terms and language specific to the use and development of bots. ## Play Session Whether we run a bot or record a human playing, we get a play session in both cases. Why do we not distinguish (everywhere) between sessions with a human and sessions with a bot as the player agent? Because in some cases, we prefer to have a human take over temporarily when a bot gets stuck. This implies that a single session can have both human and bot as the player agent at different times. ## Player Agent A player agent can be either a bot or a human. We use bots as agents for productive use. For development, we sometimes let a human take the role of the agent. After a human has demonstrated how to perform a task, we can use the recording of that play session for training bots. (Process mining) ## Program We categorize programs based on their interfaces, that is, their inputs and outputs. We distinguish the following three types of interfaces: + Player Agent ('Bot') + Environment + Assistant The standard interface between player agent and environment allows us to combine any agent with any environment for testing and comparing fitness. ### Bot Program A bot defines the behavior of a player agent. We also call it a programmatic player. It receives impressions from the environment, typically via screenshots of the game client. It outputs effects to perform on the game client. These are effects that could result from human interaction, such as mouse clicks or keyboard inputs. We use the bot program interface also to derive metrics and notifications in a play session. ### Environment Program An environment program allows us to simulate a player's environment. In contrast to a live environment, a simulated environment enables reproducible and automated testing. Reproducible environments, in turn, allow us to quickly compare the fitness of different bots in the same situation. ### Assistant Program An assistant program helps with developing programs. Input for this program includes our complete workspace, including the program we are working on and past play sessions. With this context, the assistant makes recommendations specific to our project and the situations our bots encountered in the past. These recommendations can include changes to bot-settings or program codes. <file_sep>using System; using System.Collections.Generic; using System.Linq; using Kernel32 = BotEngine.Windows.Kernel32; namespace eve_online_memory_reading { /// <summary> /// reads memory from the process identified by <paramref name="ProcessId"/>. /// </summary> public class ProcessMemoryReader : IMemoryReader, IDisposable { readonly public int ProcessId; IntPtr ProcessHandle; MemoryReaderModuleInfo[] ModulesCache; public MemoryReaderModuleInfo[] Modules() { // assuming that Modules havent changed since call to constructor. return ModulesCache; } static public MemoryReaderModuleInfo[] ModulesOfProcess(int ProcessId) { var Process = System.Diagnostics.Process.GetProcessById(ProcessId); var Modules = new List<MemoryReaderModuleInfo>(); foreach (var Module in Process.Modules.OfType<System.Diagnostics.ProcessModule>()) { Modules.Add(new MemoryReaderModuleInfo(Module.ModuleName, Module.BaseAddress.ToInt64())); } return Modules.ToArray(); } public ProcessMemoryReader( int ProcessId) { this.ProcessId = ProcessId; ProcessHandle = Kernel32.OpenProcess(Kernel32.PROCESS_ACCESS_RIGHT.PROCESS_VM_READ, 0, (uint)ProcessId); ModulesCache = ModulesOfProcess(ProcessId); } public ProcessMemoryReader( System.Diagnostics.Process Process) : this(Process.Id) { } public void Dispose() { Kernel32.CloseHandle(ProcessHandle); } static public IntPtr? CastToIntPtrAvoidOverflow(Int64 Address) { if (4 == IntPtr.Size) { if (Address < UInt32.MinValue) { return null; } if (UInt32.MaxValue < Address) { return null; } } return (IntPtr)((Int32)Address); } public byte[] ReadBytes(Int64 Address, int BytesCount) { var Buffer = new byte[BytesCount]; var lpNumberOfBytesRead = IntPtr.Zero; var AddressAsIntPtr = CastToIntPtrAvoidOverflow(Address); if (!AddressAsIntPtr.HasValue) { return null; } var Error = Kernel32.ReadProcessMemory(ProcessHandle, AddressAsIntPtr.Value, Buffer, (IntPtr)Buffer.Length, out lpNumberOfBytesRead); var NumberOfBytesRead = (int)lpNumberOfBytesRead; if (NumberOfBytesRead < 1) { return null; } if (Buffer.Length == NumberOfBytesRead) { return Buffer; } return Buffer.Take(NumberOfBytesRead).ToArray(); } } } <file_sep># Refining Bot Development Examples and Guides - Improving EVE Online Jet Can Collection Example Today I discovered a way to improve on yesterdays implementation for Foivos Saropoulos jet can collection in EVE Online (See the commit at https://github.com/Viir/bots/commit/b5f2fb0e09b9aa7846f2bdc31506dd84b8eeb4d0) The benefit of this improvement is making it easier to implement similar functionality in the future; it would not necessarily bring any improvement for this particular app. That is why I do not add it there immediately; it is not on the shortest path to a working app for Foivos. A problem with changes in the linked commit is the introduction of remembering the action we performed. In this specific case, a sequence to initiate warping to a fleet member (App-specific language). Yesterday's implementation bases this memory on a leaf of the decision tree selecting this action. This kind of dependency makes development more complex, also affecting the ability to employ machine learning to automate programming by training data. To get rid of this dependency again, we can instead draw on what we can observe passively. The analogy here is watching someone play: Given a video recording of the gameplay, can we decide if the warp-to-fleet member is complete? Drawing on what I know about the game, it seems possible: Is the context menu close enough to the right character in the chat window? Is it expanded up to the stage where we can initiate the warp with the next click? If these conditions are met, we can check if the ship started a warp within two seconds of the context menu disappearing. We do not have to stop here. If, for some reason, the set of conditions to meet is not strict enough yet, we could also draw on remembering the location of the last mouse click to boost confidence. We can check if that location is within the right context menu entry. This dependency on past inputs is less problematic than the dependency taken in yesterday's change, as it is not specific to the origin of the action in the policy. Not depending on the learning/collecting policy is the goal, since it allows for reuse of already available data sets. A concrete example is a case where we attempt to implement that jet can collection feature and test it: We don't want to depend on starting a game client to perform a live test, as this would slow down the development process. With the policy-independent variant, we can test the new implementation using a recording from another session. That other session does not even have to be related to the use of any bot; it could be as well a record of a human playing. <file_sep># BotLab Contributor Program We created the BotLab Contributor Program to recognize and reward the hard work of our awesome contributors, encourage knowledge sharing within the developer community, and build friendly competition around contributions. Through the contributor program, contributors are rewarded with BotLab credits and can use the [BotLab 'Pro' features](https://botlab.org/pricing) for free. ## How it works Earn credits by recording videos, writing content, collecting training data, contributing code, answering technical questions, or validating others' contributions. ## Automatic rewards for bot programs Besides the manual distribution of rewards, there are automatic rewards for sharing bot programs. Through automated rewards, authors earn credits proportional to the popularity of their publications. After publishing a new bot program under their name, the contributor receives 20 % of all credits spent with that bot. For each 500 thousand credits users pay for running that bot, the contributor gets 100 thousand credits. To enable the automatic rewards, the contributor must publish their bot on the BotLab catalog under their name. ### Attribution and verification of authorship To register as the author of a bot program, set the `authors-forum-usernames` tag in the bot program's `Bot.elm` file. If the bot has multiple names in `authors-forum-usernames`, the rewards will be split between these authors. When publishing a bot on the catalog, ensure the list of authors does not contain a name without their consent since users tend to message the listed authors with support requests. The listed authors receive the credits via a voucher code via a private message on the [BotLab forum](https://forum.botlab.org). <file_sep># How to Run a Bot We can find countless bot program codes on the internet, on code hosting sites like GitHub and other websites. But how to run such a bot program? Following is a detailed walkthrough on how to run a bot program using the BotLab client. ## Prerequisites - Installing the BotLab client on Windows Before running any bot for the first time, we install the BotLab client on Windows. If you are not sure you have done this on your system already, check the installation guide at <https://to.botlab.org/guide/how-to-install-the-botlab-client> ## Running a Bot Here is a video showing how to start a live run of a bot, also covering the initial download and installation: https://to.botlab.org/guide/video/how-to-run-a-bot After following the installation guide, our Windows system is ready to run bots. When we open the BotLab client that we installed in the previous step, we see this screen: ![The first view visible in the BotLab client after installing](./image/2022-12-10-botlab-client-main-menu.png) The most common way to run a bot is to use this graphical interface. For expert users and developers, a command-line interface offers another route to run a bot, but this guide only covers the graphical interface. After clicking on the 'Run Bot' button, we land on this screen where we can select which bot we want to run: ![The view to select a bot in the BotLab client](./image/2022-12-10-botlab-client-select-bot.png) The BotLab client supports running bot programs from many different sources. The 'Select Bot' screen contains a single text input field to name the bot we want to use. Here we enter a bot's name or a path to a file or directory containing a bot program. A path can point, for example, to a directory on our computer, such as `C:\my-bot-programs\awesome-bot` It can also point to a public git repository on git hosting services like [GitHub](https://github.com) and [GitLab](https://gitlab.com). If a developer has sent us a zip archive containing a bot program, we can also enter the path to the zip archive directly, like `C:\Users\John\Downloads\bot-program.zip`. The BotLab client will do the extraction automatically in the background, so we don't need to unpack the archive manually. We can also enter any bot ID or short name, as seen on the BotLab catalog at <https://catalog.botlab.org> ![The view to select a bot in the BotLab client - after entering a path to a bot](./image/2022-12-10-botlab-client-select-bot-entered-catalog-url.png) By pressing the 'Load Bot' button, we advance into the 'Configure Session' view. ![The view to configure a session](./image/2022-12-10-botlab-client-configure-session-bot-description.png) Here we can configure various aspects of the new bot session. At the top of the 'Configure Session' view, we see the description of the bot we selected in the previous step. In some cases, we will refer to this description to better understand which activities the selected bot can carry out for us. In some cases, the description will help us understand that the selected bot is not a good match for the in-game activity we want to automate. In this case, we can go back to the bot selection stage using the 'back' button in the upper left corner. The various configurations offered further down are optional. The fastest way to run the bot is to skip changing them and scroll past them down to the bottom. Here we find the 'Start Play Session' button to start running the bot. ![Start the play session](./tribal-wars-2/image/2022-12-01-tw2-farmbot-configure-session-start-marked.png) ### Operating the Bot When running a bot live, the engine displays status information in the console window. This display is updated as the bot continues operating. Most of the time, you don't need to watch this. After all, that is the point of automation right? To go back in time and see past status information from the bot, you can use the time-travel functionality in the devtools: https://to.botlab.org/guide/observing-and-inspecting-a-bot But in case a bot gets stuck, you want to take a look at this status display. Among general information from the engine, this display can also contain information as coded by the author. This way, the bot can tell you about the goal of its current actions or inform you about problems. For example, this [auto-pilot bot](https://github.com/Viir/bots/tree/e1eac00ab6a818e722fd64d552a2615d78f9628b/implement/applications/eve-online/eve-online-warp-to-0-autopilot) shows diverse messages to inform you what it is doing at the moment. When you run this bot, the botlab client might show a text like the following in the section 'Status text from bot': ``` jumps completed: 0 current solar system: Kemerk + I see ship UI and overview, undocking complete. ++ I see no route in the info panel. I will start when a route is set. +++ Wait ``` You can pause the bot by pressing the `SHIFT` + `CTRL` + `ALT` keys. To let the bot continue, focus the console window and press the enter key. The key combination `CTRL` + `C` stops the bot and the BotLab client process. ## Running a Bot in a Simulated Environment Running a bot can serve various goals. We categorize those goals broadly into two groups as follows: 1. **To achieve an effect in some other system or software, like a game client.** In this case, we want the bot to interact with the world around it. The bot reads information from and sends inputs to another software. We call this a 'live' or 'productive' run. 2. **To understand how the bot works or to test if it works as expected.** In this case, we isolate the bot in a simulation, which means it cannot send any inputs and not affect any other software. We call this a 'simulated' or 'test' run. Every time we start running a bot, we choose one of these two modes, depending on whether we want it to work in a live environment or test it. There is no difference between a live run and a simulated run from the bot's perspective. The bot does not know if it is running in a simulation. To learn about testing a bot using simulated environments, see the dedicated guide at https://to.botlab.org/guide/testing-a-bot-using-simulated-environments <file_sep># Running Bots on Multiple Game Clients Do you want to use a bot with multiple game clients? There is no general limit to the number of game clients; supporting multiple clients depends on your bot's programming. Many bots support multiple clients, but it is not always obvious how to set this up if you use a bot made by somebody else. However, many bots follow the same approach to multi-client support, so you can check if it also applies to the bot you are using. Most bots use a variant of multi-client support with these traits: + One bot instance per game client instance. + Select the game client window on startup. + Default to select the topmost game client window. These bullet points need some further explanation. Let's see what they mean in detail. ### One Bot Instance per Game Client Instance You start a new instance of the bot for each game client you want to use. This approach has several implications. For example, it means that you can use different bots for each game client, and you can start, pause, and stop them at different times. It also means you can see the performance metrics for each instance individually. ### Select the Game Client Window on Startup When the bot starts, it expects an instance of the game client already present. The bot selects a window to work on only at startup. It remembers the window's ID and keeps working on the same window for the rest of the session. Note that the bots need some time to startup and complete the window selection. When the bot reports what it sees in the game client or sends input, you know it has completed the window selection. ### Default to Select the Topmost Game Client Window There are many windows open on the desktop, and there can be multiple instances of the game client. The default way to select the right one allows for using multiple game clients without any configuration. The bot uses a property of the window called 'Z-index' to sort them. The Z-index is tracked by the operating system and establishes an ordering of the windows, based on how far they are from the window with input focus, also called the 'topmost' window. When you select a window for [input focus](https://en.wikipedia.org/wiki/Focus_(computing)), it becomes the topmost window and has the highest priority for the bot's selection. Focusing a window can be as simple as clicking on it. There are also keyboard commands to switch between windows, such as `Alt` + `Tab` in Microsoft Windows. Some bots offer optional settings to limit the selection of the game client window. For example, some bots for the game EVE Online offer a setting to pick a pilot name. Such options reduce the dependency on maintaining the window order on startup. ## Process to Start Bots on Multiple Game Clients When using a bot that follows the three choices above, this is the process to start your bots: + Focus the game client window to be used with bot instance A. + Start bot instance A and wait until the bot has selected the window. + Pause bot instance A. + Focus the game client window to be used with bot instance B. + Start bot instance B and wait until the bot has selected the window. + Unpause bot instance A. The order in which you started the game clients is not relevant. It also does not matter if you had a different bot running on a game client window. ## Avoiding Interference Through Input Focus Scheduling When you run multiple bot instances in parallel, you might want to use input focus scheduling to prevent them from interfering with each other's inputs. The BotLab client comes with built-in support for input focus scheduling. To make sure this feature is enabled for your bot instances, see the guide at https://to.botlab.org/guide/input-focus-scheduling-for-multiple-bot-instances <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace eve_online_memory_reading { public class MemoryReaderModuleInfo { readonly public string ModuleName; readonly public Int64 BaseAddress; public MemoryReaderModuleInfo( string ModuleName, Int64 BaseAddress) { this.ModuleName = ModuleName; this.BaseAddress = BaseAddress; } } public interface IMemoryReader { byte[] ReadBytes(Int64 Address, int BytesCount); MemoryReaderModuleInfo[] Modules(); } /// <summary> /// extension methods for IMemoryReader. /// </summary> static public class MemoryReaderExtension { static public UInt32? ReadPointerPath32( this IMemoryReader MemoryReader, KeyValuePair<string, UInt32[]> RootModuleNameAndListOffset) { return ReadPointerPath32(MemoryReader, RootModuleNameAndListOffset.Key, RootModuleNameAndListOffset.Value); } static public UInt32? ReadPointerPath32( this IMemoryReader MemoryReader, string RootModuleName, UInt32[] ListOffset) { if (null == MemoryReader) { return null; } if (null == ListOffset) { return null; } if (ListOffset.Length < 1) { return null; } UInt32 RootModuleOffset = 0; if (null != RootModuleName) { var Modules = MemoryReader.Modules(); if (null == Modules) { return null; } var RootModule = Modules.FirstOrDefault((Module) => string.Equals(Module.ModuleName, RootModuleName, StringComparison.InvariantCultureIgnoreCase)); if (null == RootModule) { return null; } RootModuleOffset = (UInt32)RootModule.BaseAddress; } var CurrentAddress = RootModuleOffset; for (int NodeIndex = 0; NodeIndex < ListOffset.Length - 1; NodeIndex++) { var NodeOffset = ListOffset[NodeIndex]; CurrentAddress += NodeOffset; var NodePointer = MemoryReader.ReadUInt32(CurrentAddress); if (!NodePointer.HasValue) { return null; } CurrentAddress = NodePointer.Value; } CurrentAddress += ListOffset.LastOrDefault(); return CurrentAddress; } static public UInt32? ReadUInt32( this IMemoryReader MemoryReader, Int64 Address) { if (null == MemoryReader) { return null; } var Bytes = MemoryReader.ReadBytes(Address, 4); if (null == Bytes) { return null; } if (Bytes.Length < 4) { return null; } return BitConverter.ToUInt32(Bytes, 0); } static public string ReadStringAsciiNullTerminated( this IMemoryReader MemoryReader, Int64 Address, int LengthMax = 0x1000) { if (null == MemoryReader) { return null; } var Bytes = MemoryReader.ReadBytes(Address, LengthMax); if (null == Bytes) { return null; } var BytesNullTerminated = Bytes.TakeWhile((Byte) => 0 != Byte).ToArray(); return Encoding.ASCII.GetString(BytesNullTerminated); } static public T[] ReadArray<T>( this IMemoryReader MemoryReader, Int64 Address, int NumberOfBytes) where T : struct { if (null == MemoryReader) { return null; } var BytesRead = MemoryReader.ReadBytes(Address, NumberOfBytes); if (null == BytesRead) { return null; } var ElementSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); var NumberOfElements = (BytesRead.Length - 1) / ElementSize + 1; var Array = new T[NumberOfElements]; Buffer.BlockCopy(BytesRead, 0, Array, 0, BytesRead.Length); return Array; } /// <summary> /// enumerates all Addresses which are aligned to 32Bits and hold the value <paramref name="SearchedValue"/>. /// </summary> /// <param name="MemoryReader"></param> /// <param name="SearchedValue"></param> /// <param name="SearchedRegionBegin"></param> /// <param name="SearchedRegionEnd"></param> /// <returns></returns> static public IEnumerable<Int64> AddressesHoldingValue32Aligned32( this IMemoryReader MemoryReader, UInt32 SearchedValue, Int64 SearchedRegionBegin, Int64 SearchedRegionEnd) { if (null == MemoryReader) { yield break; } var FirstBlockAddress = (SearchedRegionBegin / PyObject.Specialisation_RuntimeCost_BlockSize) * PyObject.Specialisation_RuntimeCost_BlockSize; var LastBlockAddress = (SearchedRegionEnd / PyObject.Specialisation_RuntimeCost_BlockSize) * PyObject.Specialisation_RuntimeCost_BlockSize; for (Int64 BlockAddress = FirstBlockAddress; BlockAddress <= LastBlockAddress; BlockAddress += PyObject.Specialisation_RuntimeCost_BlockSize) { var BlockValues = MemoryReader.ReadArray<UInt32>(BlockAddress, PyObject.Specialisation_RuntimeCost_BlockSize); if (null == BlockValues) { continue; } for (int InBlockIndex = 0; InBlockIndex < BlockValues.Length; InBlockIndex++) { var Address = BlockAddress + (InBlockIndex * 4); if (Address < SearchedRegionBegin || SearchedRegionEnd < Address) { continue; } if (SearchedValue == BlockValues[InBlockIndex]) { yield return Address; } } } } } } <file_sep>using System; using System.Runtime.InteropServices; namespace BotEngine.Windows { static public class Kernel32 { public enum PROCESS_ACCESS_RIGHT { PROCESS_CREATE_PROCESS = 0x0080, PROCESS_CREATE_THREAD = 0x0002, PROCESS_DUP_HANDLE = 0x0040, PROCESS_QUERY_INFORMATION = 0x0400, PROCESS_SET_INFORMATION = 0x0200, PROCESS_SET_QUOTA = 0x0100, PROCESS_SUSPEND_RESUME = 0x0800, PROCESS_TERMINATE = 0x0001, PROCESS_VM_OPERATION = 0x0008, PROCESS_VM_READ = 0x0010, PROCESS_VM_WRITE = 0x0020, SYNCHRONIZE = 0x00100000, } [DllImport("kernel32.dll")] static extern public Int32 CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] static extern public IntPtr OpenProcess( PROCESS_ACCESS_RIGHT dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] static extern public UInt32 ReadProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, IntPtr size, [Out] out IntPtr lpNumberOfBytesRead); } } <file_sep># 2019-07-10 Locate Objects in Screenshot In this exploration, I want to learn more about how we can quickly test functions to read from screenshots. Reading from screenshots is the default method for a bot to learn about the current state of the (game)world. After the bot takes a screenshot of the game client, it applies functions to extract information out of the screenshot. A typical example is locating objects to interact with using mouse clicks. Just as the bot development process in general, composing such an image processing function is an iterative process: Looking at an example image, I get an idea of how to model the pattern to search for and sketch the first approximation of the function. Then I run this function on the example image and review its output. Depending on the results I see there, I make changes to the image processing function. This cycle of testing and adjusting repeats until I have arrived at a version that produces the expected output for the example images. Since bot developers run such tests hundreds of times per hour, I check that this process works smoothly. Last weeks exploration ([2019-07-04.read-screenshot-from-file-and-configure-image-search](./../2019-07-04.read-screenshot-from-file-and-configure-image-search/app/src/Main.elm)) resulted in improvements in the same area: One of the results was a graphical user interface which allows a user to interactively load example screenshot and compose a function to search for objects in these screenshots. What I miss in the result from last week: Support for testing any image processing function. The image pattern model developed there allows only to model a subset of these functions. After completing the last weeks' exploration, I became aware of some cases where that specific model was not flexible enough. > ## Reminder About Image Representation > > What we can already see in last weeks exploration: The screenshot is represented as a set of pixels, each with a two-dimensional location and a value. This pixel value is composed of a numeric intensity for each of the three color channels red, green and blue. > In the type [`DecodeBMPImageResult`](./../2019-07-04.read-screenshot-from-file-and-configure-image-search/app/src/DecodeBMPImage.elm), the two-dimensional location of the pixel is modeled implicitly, as the index of the pixel in the list `pixelsLeftToRightTopToBottom` combined with the image property `bitmapWidthInPixels`. ## Initial Idea The simplest way I found so far for this testing process: + Start from a test implementation. This is simply a bot code which we can run like any other bot, by specifying the `bot-source` location. + This template bot code contains all the functionality to load example images and render results from image processing to make review easy. It also contains a function which is responsible for the image processing part. + To test our own image processing function, we just replace that image processing function in the example bot code by our own, then run this code as usual. This approach has the advantage that we reuse significant parts of the general bot development process, including the development environment which analysis the code and draws our attention to potential problems. This reuse ensures familiarity and minimizes required learning effort on the bot developers side. ## Demo Image For testing during exploration, I save an example image to a file in this directory here. The example, in this case, is the screenshot from https://github.com/Viir/bots/blob/21e030d9b6d496a0d0b2e02e2eca1bea3dfb91d0/explore/2019-06-26.how-to-take-screenshots/2019-06-26.eve-online-screenshot.jpeg To ensure the right image file format, I use the same ['save as BMP' process as last week](./../2019-07-04.read-screenshot-from-file-and-configure-image-search/app/tests/DecodeBMPImageTest.elm). To reduce the cost of the image file in the repository, I crop it before adding it here. The resulting file is in [`2019-07-11.example-from-eve-online-crop-0.bmp`](./2019-07-11.example-from-eve-online-crop-0.bmp): ![2019-07-11.example-from-eve-online-crop-0.bmp](./2019-07-11.example-from-eve-online-crop-0.bmp) ## Implementation A good outcome of this exploration would be completing a usable version of that bot code template as described above so that bot developers can start using it. To reduce the wait time for bot developers, the initial scope is reduced to contain only essential functionality. For the image file decoding functionality, we can reuse the implementation `decodeBMPImageFile` from last weeks exploration, as this already maps from a file (`Bytes` type) to an image (`DecodeBMPImageResult` type). Since we use the bot interfaces for the implementation, I start by copying the code of an existing bot. I use the bot from [implement/bot/eve-online/eve-online-warp-to-0-autopilot](./../../implement/bot/eve-online/eve-online-warp-to-0-autopilot) to start the implementation of the template. ### Loading a File Trough the Volatile Host What does the bot need on the volatile host side? As far as I see now, returning the content of a file at a specified path is enough. Everything else can be implemented on the transparent side. The `SanderlingVolatileHostSetup.elm` file already contains the overall structure for running requests from the bot in the volatile host. The simplest way to implement the new file loading command seems to add it here analogous. ## Result During the process of developing this template, I reduced the scope of applications: I concentrated on locating instances of an object in an image. Starting from this template also helps with other kinds of extracting information (e.g., a general classification) from a screenshot, but the guide added here focuses on the use-case of locating objects. The template implemented in this exploration supports testing a function which should locate instances of an object in an image. It contains the framework to load and parse the image file and display the object search results for easy review. By looking at the test results and comparing them with the expectations, a bot developer can check if the object locating function works correctly. The simplest way to locate instances of an object in an image is to provide a function with a type as follows: ```elm image_shows_object_at_origin : ({ x : Int, y : Int } -> Maybe PixelValue) -> Bool ``` Where `PixelValue` is defined as follows: ```elm type alias PixelValue = { red : Int, green : Int, blue : Int } ``` The function takes one parameter, which is itself a function: For a given pixel location, it returns the pixels value. Since the location could also be outside the image, the returned pixel value is wrapped in a `Maybe`. As can be seen from the return type, this function only returns `True` or `False`. It just tells the framework if the searched object is present in the image. Since this function does not know the size of the image, it cannot attempt to search the whole image. It just searches at a single area, by looking at pixels at surrounding (relative) locations. To get a list of object locations for an image, the framework calls this function several times, for shifted versions of the image. The function `getMatchesLocationsFromImage` knows all pixels in the image, and calls `image_shows_object_at_origin` for each pixel. It supplies `image_shows_object_at_origin` with a pixel query function that shifts the location according to the current search origin location. Because of this shift, `image_shows_object_at_origin` can also find pixel values at locations in negative coordinate space (e.g. `{ x = -11, y = -3 }`). Where the `image_shows_object_at_origin` returns true, the location which was `{ x = 0, y = 0 }` in the scope of `image_shows_object_at_origin` is the relative object location. The integrating function adds the search origin offset to compute the absolute object location in the image. During this exploration, I also added an example implementation of `image_shows_object_at_origin`. This included example finds the four waypoint markers in the demo image created above. To test the image search, start the code using the `start-bot` command, and supply the path to the image file using the `--bot-configuration` parameter. Starting the code is explained in detail in the guide at https://github.com/Viir/bots/blob/21e030d9b6d496a0d0b2e02e2eca1bea3dfb91d0/guide/how-to-use-eve-online-bots.md When running the unmodified template on said demo image, the bot outputs the following result: ```text I received 'path-on-local-machine\bots\explore\2019-07-10.read-from-screenshot\2019-07-11.example-from-eve-online-crop-0.bmp' as the path to the image to load. Stopped with result: Decoded image: bitmapWidthInPixels: 153, bitmapHeightInPixels: 81 Found matches in 4 locations: [ { x = 23, y = 57 }, { x = 33, y = 57 }, { x = 43, y = 57 }, { x = 53, y = 57 } ] ``` Further aspects we could expand on in a guide: + Detail connection between output quoted above and demo image. (Upper left corner). + Why is it the upper left corner? How would it be another relative location? Show example code change to make it lower right corner or center. + Visualize instantiation and image shift, the mapping between relative and absolute locations. + Demonstrate how we get false positives by relaxing the constraints (brightness, saturation) in the example. + Optional addition of a broad phase? <file_sep>using System; using System.Collections.Generic; namespace eve_online_memory_reading { public interface IPythonMemoryReader : IMemoryReader { PyTypeObject TypeFromAddress(UInt32 TypeObjectAddress); } /// <summary> /// caches Type Objects. /// </summary> public class PythonMemoryReader : IPythonMemoryReader { readonly IMemoryReader MemoryReader; readonly Dictionary<UInt32, PyTypeObject> CacheTypeObject = new Dictionary<UInt32, PyTypeObject>(); public PythonMemoryReader( IMemoryReader MemoryReader) { this.MemoryReader = MemoryReader; } PyTypeObject IPythonMemoryReader.TypeFromAddress(uint TypeObjectAddress) { PyTypeObject TypeObject; if (CacheTypeObject.TryGetValue(TypeObjectAddress, out TypeObject)) { return TypeObject; } TypeObject = new PyTypeObject(TypeObjectAddress, MemoryReader); CacheTypeObject[TypeObjectAddress] = TypeObject; return TypeObject; } byte[] IMemoryReader.ReadBytes(long Address, int BytesCount) { return MemoryReader.ReadBytes(Address, BytesCount); } MemoryReaderModuleInfo[] IMemoryReader.Modules() { return MemoryReader.Modules(); } } } <file_sep>#r "mscorlib" #r "netstandard" #r "System" #r "System.Collections.Immutable" #r "System.ComponentModel.Primitives" #r "System.IO.Compression" #r "System.Net" #r "System.Net.WebClient" #r "System.Private.Uri" #r "System.Linq" #r "System.Security.Cryptography.Algorithms" #r "System.Security.Cryptography.Primitives" // "Newtonsoft.Json" #r "sha256:B9B4E633EA6C728BAD5F7CBBEF7F8B842F7E10181731DBE5EC3CD995A6F60287" // "WindowsInput" #r "sha256:81110D44256397F0F3C572A20CA94BB4C669E5DE89F9348ABAD263FBD81C54B9" // "System.Drawing.Common" #r "sha256:C5333AA60281006DFCFBBC0BC04C217C581EFF886890565E994900FB60448B02" // "System.Drawing.Primitives" #r "sha256:CA24032E6D39C44A01D316498E18FE9A568D59C6009842029BC129AA6B989BCD" using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Security.Cryptography; using System.Runtime.InteropServices; int readingFromGameCount = 0; var generalStopwatch = System.Diagnostics.Stopwatch.StartNew(); var readingFromGameHistory = new Queue<ReadingFromGameClient>(); public class Request { public object ListWindowsRequest; public TaskOnIdentifiedWindowRequestStruct TaskOnWindowRequest; public GetImageDataFromReadingRequestStruct? GetImageDataFromReadingRequest; public object GetForegroundWindow; public string GetWindowText; public GetImageDataFromReadingRequestStruct? GetImageDataFromReading; public class TaskOnIdentifiedWindowRequestStruct { public string windowId; public TaskOnWindowRequestStruct task; } public class TaskOnWindowRequestStruct { public object BringWindowToForeground; public ReadFromWindowStructure ReadFromWindowRequest; public EffectSequenceOnWindowElement[] EffectSequenceOnWindowRequest; } public class EffectSequenceOnWindowElement { public EffectOnWindowStructure EffectElement; public int? DelayInMillisecondsElement; } public class VirtualKeyCode { public int virtualKeyCode; } public class ReadFromWindowStructure { public GetImageDataFromReadingStructure getImageData; } public struct GetImageDataFromReadingRequestStruct { public string readingId; public GetImageDataFromReadingStructure getImageData; } public struct GetImageDataFromReadingStructure { public Rect2d[] crops_1x1_r8g8b8; public Rect2d[] crops_2x2_r8g8b8; } public class EffectOnWindowStructure { public Location2d? SetMouseCursorPositionEffect; public VirtualKeyCode KeyDownEffect; public VirtualKeyCode KeyUpEffect; } } public class Response { public WindowSummaryStruct[] ListWindowsResponse; public TaskOnIdentifiedWindowResponseStruct TaskOnWindowResponse; public object ReadingNotFound; public GetImageDataFromReadingCompleteStruct? GetImageDataFromReadingComplete; public object NoReturnValue; public string GetWindowTextResult; public string GetForegroundWindowResult; public struct WindowSummaryStruct { public string windowId; public string windowTitle; public int windowZIndex; } public class TaskOnIdentifiedWindowResponseStruct { public string windowId; public TaskOnWindowResponseStruct result; } public class TaskOnWindowResponseStruct { public object WindowNotFound; public ReadFromWindowCompleteStruct ReadFromWindowComplete; } public class ReadFromWindowCompleteStruct { public string readingId; public Location2d windowSize; public Location2d windowClientRectOffset; public Location2d windowClientAreaSize; public GetImageDataFromReadingResultStructure imageData; } public struct GetImageDataFromReadingCompleteStruct { public string windowId; public string readingId; public GetImageDataFromReadingResultStructure imageData; } public struct GetImageDataFromReadingResultStructure { public ImageCropRGB[] crops_1x1_r8g8b8; public IReadOnlyList<ImageCropRGB> crops_2x2_r8g8b8; } } struct ReadingFromGameClient { public string windowId = null; public string readingId = null; public ReadOnlyMemory<int>[] pixels_1x1_R8G8B8 = null; private readonly IDictionary<Location2d, ReadOnlyMemory<int>[]> pixels_2x2_R8G8B8_by_offset = new Dictionary<Location2d, ReadOnlyMemory<int>[]>(); public ReadingFromGameClient() { } public ReadOnlyMemory<int>[] Pixels_2x2_R8G8B8_by_offset(Location2d offset) { if (pixels_2x2_R8G8B8_by_offset.TryGetValue(offset, out var pixels)) { return pixels; } pixels = Build_pixels_2x2_R8G8B8_by_offset(offset); pixels_2x2_R8G8B8_by_offset[offset] = pixels; return pixels; } public ReadOnlyMemory<int>[] Build_pixels_2x2_R8G8B8_by_offset(Location2d offset) { var offsetRows = pixels_1x1_R8G8B8.Skip(offset.y).ToList(); var pixels_2x2_R8G8B8 = Enumerable.Range(0, offsetRows.Count / 2) .Select(rowIndex => { var row0Pixels = offsetRows[rowIndex * 2]; var row1Pixels = offsetRows[rowIndex * 2 + 1]; var offsetRow0Pixels = row0Pixels.Slice(offset.x); var offsetRow1Pixels = row1Pixels.Slice(offset.x); var binnedRowLength = Math.Min(offsetRow0Pixels.Length, offsetRow1Pixels.Length) / 2; var binnedRow = new int[binnedRowLength]; for (int x = 0; x < binnedRowLength; ++x) { var p0 = offsetRow0Pixels.Span[x * 2]; var p1 = offsetRow0Pixels.Span[x * 2 + 1]; var p2 = offsetRow1Pixels.Span[x * 2]; var p3 = offsetRow1Pixels.Span[x * 2 + 1]; var r0 = (p0 >> 16) & 0xff; var g0 = (p0 >> 8) & 0xff; var b0 = p0 & 0xff; var r1 = (p1 >> 16) & 0xff; var g1 = (p1 >> 8) & 0xff; var b1 = p1 & 0xff; var r2 = (p2 >> 16) & 0xff; var g2 = (p2 >> 8) & 0xff; var b2 = p2 & 0xff; var r3 = (p3 >> 16) & 0xff; var g3 = (p3 >> 8) & 0xff; var b3 = p3 & 0xff; binnedRow[x] = (((r0 + r1 + r2 + r3) / 4) << 16) | (((g0 + g1 + g2 + g3) / 4) << 8) | (((b0 + b1 + b2 + b3) / 4)); } return (ReadOnlyMemory<int>)binnedRow; }) .ToArray(); return pixels_2x2_R8G8B8; } } public struct ImageCropRGB { public Location2d offset; public int[][] pixels; } public struct Rect2d { public int x, y, width, height; } public record struct Location2d(int x, int y); string ToStringBase16(byte[] array) => BitConverter.ToString(array).Replace("-", ""); string serialRequest(string serializedRequest) { var requestStructure = Newtonsoft.Json.JsonConvert.DeserializeObject<Request>(serializedRequest); var response = request(requestStructure); return SerializeToJsonForBot(response); } public Response request(Request request) { SetProcessDPIAware(); string GetWindowText(string windowId) { var windowHandle = new IntPtr(Int64.Parse(windowId)); return GetWindowTextFromHandle(windowHandle); } if (request.ListWindowsRequest != null) { return new Response { ListWindowsResponse = ListWindowsSummaries(windowCountLimit: 4).ToArray(), }; } if (request.GetForegroundWindow != null) { return new Response { GetForegroundWindowResult = GetForegroundWindow() }; } if (request.GetWindowText != null) { return new Response { GetWindowTextResult = GetWindowText(request.GetWindowText), }; } if (request.TaskOnWindowRequest != null) { return performTaskOnWindow(request.TaskOnWindowRequest); } if (request.GetImageDataFromReadingRequest?.readingId != null) { var historyEntry = readingFromGameHistory .Cast<ReadingFromGameClient?>() .FirstOrDefault(c => c?.readingId == request.GetImageDataFromReadingRequest?.readingId); if (historyEntry == null) { return new Response { ReadingNotFound = new object() }; } return new Response { GetImageDataFromReadingComplete = new Response.GetImageDataFromReadingCompleteStruct { windowId = historyEntry.Value.windowId, readingId = request.GetImageDataFromReadingRequest?.readingId, imageData = CompileImageDataFromReadingResult( request.GetImageDataFromReadingRequest.Value.getImageData, historyEntry.Value), } }; } throw new Exception("Unexpected request value."); } public string GetForegroundWindow() => WinApi.GetForegroundWindow().ToInt64().ToString(); Response performTaskOnWindow( Request.TaskOnIdentifiedWindowRequestStruct taskOnIdentifiedWindow) { var windowHandle = new IntPtr(Int64.Parse(taskOnIdentifiedWindow.windowId)); Response ResponseFromResultOnWindow(Response.TaskOnWindowResponseStruct resultOnWindow) { return new Response { TaskOnWindowResponse = new Response.TaskOnIdentifiedWindowResponseStruct { windowId = taskOnIdentifiedWindow.windowId, result = resultOnWindow } }; } var windowRect = new WinApi.Rect(); if (!WinApi.GetWindowRect(windowHandle, ref windowRect)) { return ResponseFromResultOnWindow( new Response.TaskOnWindowResponseStruct { WindowNotFound = new object() }); } var inputSimulator = new WindowsInput.InputSimulator(); var task = taskOnIdentifiedWindow.task; if (task.BringWindowToForeground != null) { WinApi.SetForegroundWindow(windowHandle); WinApi.ShowWindow(windowHandle, WinApi.SW_RESTORE); return new Response { NoReturnValue = new object() }; } if (task.ReadFromWindowRequest != null) { var readingFromGameIndex = System.Threading.Interlocked.Increment(ref readingFromGameCount); var readingId = readingFromGameIndex.ToString("D6") + "-" + generalStopwatch.ElapsedMilliseconds; var pixels_1x1_R8G8B8 = GetScreenshotOfWindowAsPixelsValues_R8G8B8(windowHandle); var windowClientRect = new WinApi.Rect(); WinApi.GetClientRect(windowHandle, ref windowClientRect); var clientRectOffsetFromScreen = new WinApi.Point(0, 0); WinApi.ClientToScreen(windowHandle, ref clientRectOffsetFromScreen); var windowSize = new Location2d { x = windowRect.right - windowRect.left, y = windowRect.bottom - windowRect.top }; var windowClientRectOffset = new Location2d { x = clientRectOffsetFromScreen.x - windowRect.left, y = clientRectOffsetFromScreen.y - windowRect.top }; var windowClientAreaSize = new Location2d { x = windowClientRect.right - windowClientRect.left, y = windowClientRect.bottom - windowClientRect.top }; var historyEntry = new ReadingFromGameClient { windowId = taskOnIdentifiedWindow.windowId, readingId = readingId, pixels_1x1_R8G8B8 = pixels_1x1_R8G8B8, }; readingFromGameHistory.Enqueue(historyEntry); while (4 < readingFromGameHistory.Count) { readingFromGameHistory.Dequeue(); } var imageData = CompileImageDataFromReadingResult(task.ReadFromWindowRequest.getImageData, historyEntry); return ResponseFromResultOnWindow( new Response.TaskOnWindowResponseStruct { ReadFromWindowComplete = new Response.ReadFromWindowCompleteStruct { readingId = readingId, windowSize = windowSize, windowClientRectOffset = windowClientRectOffset, windowClientAreaSize = windowClientAreaSize, imageData = imageData } }); } if (task.EffectSequenceOnWindowRequest != null) { foreach (var sequenceElement in task.EffectSequenceOnWindowRequest) { if (sequenceElement?.EffectElement != null) ExecuteEffectOnWindow( sequenceElement.EffectElement, windowHandle: windowHandle, windowRect: windowRect, bringWindowToForeground: false); if (sequenceElement?.DelayInMillisecondsElement != null) System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(sequenceElement.DelayInMillisecondsElement.Value)).Wait(); } return new Response { NoReturnValue = new object() }; } throw new Exception("Unexpected task in request:\n" + Newtonsoft.Json.JsonConvert.SerializeObject(task)); } System.Collections.Generic.IReadOnlyList<Response.WindowSummaryStruct> ListWindowsSummaries(int windowCountLimit) { var windowHandlesInZOrder = WinApi.EnumerateWindowHandlesInZOrderStartingFromForegroundWindow() .Take(windowCountLimit) .ToList(); int? zIndexFromWindowHandle(IntPtr windowHandleToSearch) => windowHandlesInZOrder .Select((windowHandle, index) => (windowHandle, index: (int?)index)) .FirstOrDefault(handleAndIndex => handleAndIndex.windowHandle == windowHandleToSearch) .index; var windows = windowHandlesInZOrder .Select(windowHandle => { return new Response.WindowSummaryStruct { windowId = windowHandle.ToInt64().ToString(), windowTitle = GetWindowTextFromHandle(windowHandle), windowZIndex = zIndexFromWindowHandle(windowHandle) ?? 9999, }; }) .ToList(); return windows; } void ExecuteEffectOnWindow( Request.EffectOnWindowStructure effectOnWindow, IntPtr windowHandle, WinApi.Rect windowRect, bool bringWindowToForeground) { if (bringWindowToForeground) { WinApi.SetForegroundWindow(windowHandle); WinApi.ShowWindow(windowHandle, WinApi.SW_RESTORE); } if (effectOnWindow.SetMouseCursorPositionEffect != null) { WinApi.SetCursorPos( effectOnWindow.SetMouseCursorPositionEffect.Value.x + windowRect.left, effectOnWindow.SetMouseCursorPositionEffect.Value.y + windowRect.top); } if (effectOnWindow?.KeyDownEffect != null) { var virtualKeyCode = (WindowsInput.Native.VirtualKeyCode)effectOnWindow.KeyDownEffect.virtualKeyCode; (MouseActionForKeyUpOrDown(keyCode: virtualKeyCode, buttonUp: false) ?? (() => new WindowsInput.InputSimulator().Keyboard.KeyDown(virtualKeyCode)))(); } if (effectOnWindow?.KeyUpEffect != null) { var virtualKeyCode = (WindowsInput.Native.VirtualKeyCode)effectOnWindow.KeyUpEffect.virtualKeyCode; (MouseActionForKeyUpOrDown(keyCode: virtualKeyCode, buttonUp: true) ?? (() => new WindowsInput.InputSimulator().Keyboard.KeyUp(virtualKeyCode)))(); } } static System.Action MouseActionForKeyUpOrDown(WindowsInput.Native.VirtualKeyCode keyCode, bool buttonUp) { WindowsInput.IMouseSimulator mouseSimulator() => new WindowsInput.InputSimulator().Mouse; var method = keyCode switch { WindowsInput.Native.VirtualKeyCode.LBUTTON => buttonUp ? (System.Func<WindowsInput.IMouseSimulator>)mouseSimulator().LeftButtonUp : mouseSimulator().LeftButtonDown, WindowsInput.Native.VirtualKeyCode.RBUTTON => buttonUp ? (System.Func<WindowsInput.IMouseSimulator>)mouseSimulator().RightButtonUp : mouseSimulator().RightButtonDown, _ => null }; if (method != null) return () => method(); return null; } string GetWindowTextFromHandle(IntPtr windowHandle) { var windowTitle = new System.Text.StringBuilder(capacity: 256); WinApi.GetWindowText(windowHandle, windowTitle, windowTitle.Capacity); return windowTitle.ToString(); } Response.GetImageDataFromReadingResultStructure CompileImageDataFromReadingResult( Request.GetImageDataFromReadingStructure request, ReadingFromGameClient historyEntry) { ImageCropRGB[] crops_1x1_r8g8b8 = null; IReadOnlyList<ImageCropRGB> crops_2x2_r8g8b8 = null; if (historyEntry.pixels_1x1_R8G8B8 != null) { crops_1x1_r8g8b8 = request.crops_1x1_r8g8b8 .Select(rect => { var cropPixels = CopyRectangularCrop(historyEntry.pixels_1x1_R8G8B8, rect); return new ImageCropRGB { pixels = cropPixels.Select(memory => memory.ToArray()).ToArray(), offset = new Location2d { x = rect.x, y = rect.y }, }; }).ToArray(); crops_2x2_r8g8b8 = request.crops_2x2_r8g8b8 .Select(rect => { var wrappedOffsetX = rect.x % 2; var wrappedOffsetY = rect.y % 2; var binnedPixels = historyEntry.Pixels_2x2_R8G8B8_by_offset( new Location2d { x = wrappedOffsetX, y = wrappedOffsetY }); var cropPixels = CopyRectangularCrop( binnedPixels, new Rect2d { x = rect.x / 2, y = rect.y / 2, width = rect.width, height = rect.height }); return new ImageCropRGB { pixels = cropPixels.Select(memory => memory.ToArray()).ToArray(), offset = new Location2d { x = rect.x, y = rect.y }, }; }).ToArray(); } return new Response.GetImageDataFromReadingResultStructure { crops_1x1_r8g8b8 = crops_1x1_r8g8b8, crops_2x2_r8g8b8 = crops_2x2_r8g8b8 ?? ImmutableList<ImageCropRGB>.Empty }; } ReadOnlyMemory<int>[] CopyRectangularCrop(ReadOnlyMemory<int>[] original, Rect2d rect) { return original .Skip(rect.y) .Take(rect.height) .Select(rowPixels => { if (rect.x == 0 && rect.width == rowPixels.Length) return rowPixels; var sliceLength = Math.Min(rect.width, rowPixels.Length - rect.x); return rowPixels.Slice(rect.x, sliceLength); }) .ToArray(); } void SetProcessDPIAware() { // https://www.google.com/search?q=GetWindowRect+dpi // https://github.com/dotnet/wpf/issues/859 // https://github.com/dotnet/winforms/issues/135 WinApi.SetProcessDPIAware(); } public byte[] GetScreenshotOfWindowAsImageFileBMP(IntPtr windowHandle) { var screenshotAsBitmap = GetScreenshotOfWindowAsBitmap(windowHandle); if (screenshotAsBitmap == null) return null; using (var stream = new System.IO.MemoryStream()) { screenshotAsBitmap.Save(stream, format: System.Drawing.Imaging.ImageFormat.Bmp); return stream.ToArray(); } } public ReadOnlyMemory<int>[] GetScreenshotOfWindowAsPixelsValues_R8G8B8(IntPtr windowHandle) { var screenshotAsBitmap = GetScreenshotOfWindowAsBitmap(windowHandle); if (screenshotAsBitmap == null) return null; var bitmapData = screenshotAsBitmap.LockBits( new System.Drawing.Rectangle(0, 0, screenshotAsBitmap.Width, screenshotAsBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); int byteCount = bitmapData.Stride * screenshotAsBitmap.Height; byte[] pixelsArray = new byte[byteCount]; IntPtr ptrFirstPixel = bitmapData.Scan0; Marshal.Copy(ptrFirstPixel, pixelsArray, 0, pixelsArray.Length); screenshotAsBitmap.UnlockBits(bitmapData); var pixels = new ReadOnlyMemory<int>[screenshotAsBitmap.Height]; for (var rowIndex = 0; rowIndex < screenshotAsBitmap.Height; ++rowIndex) { var rowPixelValues = new int[screenshotAsBitmap.Width]; for (var columnIndex = 0; columnIndex < screenshotAsBitmap.Width; ++columnIndex) { var pixelBeginInArray = bitmapData.Stride * rowIndex + columnIndex * 3; var red = pixelsArray[pixelBeginInArray + 2]; var green = pixelsArray[pixelBeginInArray + 1]; var blue = pixelsArray[pixelBeginInArray + 0]; rowPixelValues[columnIndex] = (red << 16) | (green << 8) | blue; } pixels[rowIndex] = rowPixelValues; } return pixels; } public System.Drawing.Bitmap GetScreenshotOfWindowAsBitmap(IntPtr windowHandle) { SetProcessDPIAware(); var windowRect = new WinApi.Rect(); if (!WinApi.GetWindowRect(windowHandle, ref windowRect)) return null; int width = windowRect.right - windowRect.left; int height = windowRect.bottom - windowRect.top; var asBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); System.Drawing.Graphics.FromImage(asBitmap).CopyFromScreen( windowRect.left, windowRect.top, 0, 0, new System.Drawing.Size(width, height), System.Drawing.CopyPixelOperation.SourceCopy); return asBitmap; } static public class WinApi { [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left; public int top; public int right; public int bottom; } [StructLayout(LayoutKind.Sequential)] public struct Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } public enum MouseButton { Left = 0, Middle = 1, Right = 2, } [DllImport("user32.dll", SetLastError = true)] static public extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] static public extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count); [DllImport("user32.dll", SetLastError = true)] static public extern bool SetProcessDPIAware(); [DllImport("user32.dll")] static public extern int SetForegroundWindow(IntPtr hWnd); public const int SW_RESTORE = 9; [DllImport("user32.dll")] static public extern IntPtr ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] static public extern bool GetWindowRect(IntPtr hWnd, ref Rect rect); [DllImport("user32.dll")] static public extern IntPtr GetClientRect(IntPtr hWnd, ref Rect rect); [DllImport("user32.dll", SetLastError = false)] static public extern IntPtr GetDesktopWindow(); [DllImport("user32.dll", SetLastError = false)] static public extern IntPtr GetTopWindow(IntPtr hWnd); [DllImport("user32.dll", SetLastError = false)] static public extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static public extern bool SetCursorPos(int x, int y); [DllImport("user32.dll")] static public extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint); [DllImport("user32.dll")] static public extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam); public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); /* https://stackoverflow.com/questions/19867402/how-can-i-use-enumwindows-to-find-windows-with-a-specific-caption-title/20276701#20276701 https://stackoverflow.com/questions/295996/is-the-order-in-which-handles-are-returned-by-enumwindows-meaningful/296014#296014 */ public static IEnumerable<IntPtr> EnumerateWindowHandlesInZOrderStartingFromForegroundWindow() { var windowHandle = GetForegroundWindow(); while (windowHandle != IntPtr.Zero) { yield return windowHandle; // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getnextwindow // https://stackoverflow.com/questions/798295/how-can-i-use-getnextwindow-in-c/798303#798303 windowHandle = GetWindow(windowHandle, 2); } } } string SerializeToJsonForBot<T>(T value) => Newtonsoft.Json.JsonConvert.SerializeObject( value, // Use settings to get same derivation as at https://github.com/Arcitectus/Sanderling/blob/ada11c9f8df2367976a6bcc53efbe9917107bfa7/src/Sanderling/Sanderling.MemoryReading.Test/MemoryReadingDemo.cs#L91-L97 new Newtonsoft.Json.JsonSerializerSettings { // Bot code does not expect properties with null values, see https://github.com/Viir/bots/blob/880d745b0aa8408a4417575d54ecf1f513e7aef4/explore/2019-05-14.eve-online-bot-framework/src/Sanderling_Interface_20190514.elm NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, //\thttps://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type/18223985#18223985 ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, }); string InterfaceToHost_Request(string request) { return serialRequest(request); } <file_sep> using System; namespace eve_online_memory_reading { static public class CommonConversion { static public string StringIdentifierFromValue(byte[] value) { using (var sha = new System.Security.Cryptography.SHA256Managed()) { return BitConverter.ToString(sha.ComputeHash(value)).Replace("-", ""); } } } } <file_sep>string InterfaceToHost_Request(string request) { return "Hello from volatile process! I got this from the agent host: " + ____request_to_botlab_agent_host____("from script code"); } <file_sep>using System; using System.Collections.Generic; using System.Linq; namespace eve_online_memory_reading { /// <summary> /// Offsets from https://docs.python.org/2/c-api/structures.html /// </summary> public class PyObject { public const int Specialisation_RuntimeCost_BlockSize = 0x1000; public const int Offset_ob_refcnt = 0; public const int Offset_ob_type = 4; readonly public Int64 BaseAddress; readonly public UInt32? ob_refcnt; readonly public UInt32? ob_type; public PyTypeObject TypeObject; public PyObject( Int64 BaseAddress, IMemoryReader MemoryReader) { this.BaseAddress = BaseAddress; ob_refcnt = MemoryReader.ReadUInt32(BaseAddress + Offset_ob_refcnt); ob_type = MemoryReader.ReadUInt32(BaseAddress + Offset_ob_type); } public PyTypeObject LoadType(IPythonMemoryReader MemoryReader) { if (ob_type.HasValue) { TypeObject = MemoryReader.TypeFromAddress(ob_type.Value); } return TypeObject; } static public string TypeNameForObjectWithAddress( UInt32 ObjectAddress, IPythonMemoryReader MemoryReader) { var Object = new PyObject(ObjectAddress, MemoryReader); Object.LoadType(MemoryReader); var ObjectTypeObject = Object.TypeObject; if (null == ObjectTypeObject) { return null; } return ObjectTypeObject.tp_name_Val; } } public class PyObjectVar : PyObject { readonly public UInt32? ob_size; public const int Offset_ob_size = 8; public PyObjectVar( Int64 BaseAddress, IMemoryReader MemoryReader) : base(BaseAddress, MemoryReader) { ob_size = MemoryReader.ReadUInt32(BaseAddress + Offset_ob_size); } } /// <summary> /// Offsets from https://docs.python.org/2/c-api/typeobj.html /// </summary> public class PyTypeObject : PyObject { const int Offset_tp_name = 12; readonly public UInt32? tp_name; readonly public string tp_name_Val; public PyTypeObject( Int64 BaseAddress, IMemoryReader MemoryReader) : base( BaseAddress, MemoryReader) { tp_name = MemoryReader.ReadUInt32(BaseAddress + Offset_tp_name); if (tp_name < int.MaxValue) { tp_name_Val = MemoryReader.ReadStringAsciiNullTerminated(tp_name.Value, 0x100); } } /// <summary> /// the enumerated set contains all addresses of Python Objects of the type with the given <paramref name="tp_name"/>. /// /// the addresses are only filtered for appropriate ob_type. /// </summary> /// <param name="MemoryReader"></param> /// <param name="tp_name"></param> /// <returns></returns> static public IEnumerable<UInt32> EnumeratePossibleAddressesOfInstancesOfPythonTypeFilteredByObType( IMemoryReader MemoryReader, string tp_name) { var CandidatesTypeObjectType = PyTypeObject.FindCandidatesTypeObjectTypeAddress(MemoryReader); var TypeObjectType = PyTypeObject.TypeObjectAddressesFilterByTpName(CandidatesTypeObjectType, MemoryReader, "type").FirstOrDefault(); if (null == TypeObjectType) yield break; // finds candidate Addresses for Objects of type "type" with only requiring them to have a appropriate value for ob_type. var TypeCandidateAddressesPlus4 = MemoryReader.AddressesHoldingValue32Aligned32((UInt32)TypeObjectType.BaseAddress, 0, Int32.MaxValue) .ToArray(); var TypeCandidateAddresses = TypeCandidateAddressesPlus4 .Select((Address) => (UInt32)(Address - 4)) .ToArray(); var TypeObjectsWithProperName = PyTypeObject.TypeObjectAddressesFilterByTpName(TypeCandidateAddresses, MemoryReader, tp_name) .ToArray(); foreach (var TypeObject in TypeObjectsWithProperName) { // finds candidate Addresses for Objects of type tp_name with only requiring them to have a appropriate value for ob_type. foreach (var CandidateForObjectOfTypeAddressPlus4 in MemoryReader.AddressesHoldingValue32Aligned32((UInt32)TypeObject.BaseAddress, 0, Int32.MaxValue)) { yield return (UInt32)(CandidateForObjectOfTypeAddressPlus4 - 4); } } } /// <summary> /// enumerates the subset of Addresses that satisfy this condition: /// + Interpreted as the Address of a Python Type Object, the tp_name of this Object Equals <paramref name="tp_name"/> /// </summary> /// <param name="TypeObjectAddresses"></param> /// <param name="MemoryReader"></param> /// <param name="tp_name"></param> /// <returns></returns> static public IEnumerable<PyTypeObject> TypeObjectAddressesFilterByTpName( IEnumerable<UInt32> TypeObjectAddresses, IMemoryReader MemoryReader, string tp_name) { if (null == TypeObjectAddresses || null == MemoryReader) { yield break; } foreach (var CandidateTypeAddress in TypeObjectAddresses) { var PyType = new PyTypeObject(CandidateTypeAddress, MemoryReader); if (!string.Equals(PyType.tp_name_Val, tp_name)) { continue; } yield return PyType; } } /// <summary> /// enumerates all Addresses that satisfy this condition: /// +interpreted as the Address of a Python Type Object, the Member tp_type points to the Object itself. /// /// instead of reusing the PyObject class, this method uses a more specialized implementation to achieve lower runtime cost. /// /// the method assumes the objects to be 32Bit aligned. /// </summary> /// <param name="MemoryReader"></param> /// <returns></returns> static public IEnumerable<UInt32> FindCandidatesTypeObjectTypeAddress( IMemoryReader MemoryReader) { var CandidatesAddress = new List<UInt32>(); for (Int64 BlockAddress = 0; BlockAddress < int.MaxValue; BlockAddress += Specialisation_RuntimeCost_BlockSize) { var BlockValues32 = MemoryReader.ReadArray<UInt32>(BlockAddress, Specialisation_RuntimeCost_BlockSize); if (null == BlockValues32) continue; for (int InBlockIndex = 0; InBlockIndex < BlockValues32.Length; InBlockIndex++) { var CandidatePointerInBlockAddress = InBlockIndex * 4; var CandidatePointerAddress = BlockAddress + CandidatePointerInBlockAddress; var CandidatePointer = BlockValues32[InBlockIndex]; if (CandidatePointerAddress == Offset_ob_type + CandidatePointer) { yield return CandidatePointer; } } } } } } <file_sep># 2019-08-14 Locate Object in Window The overall goal of this stage is to expand the simple bot framework to support sensing the bots environment. The change last week already added the parts for acting on a window. This weeks expansion adds the functionality to read information from such a window so that the bot has all the information it needs to act. The information to extract includes locating objects as well as overall classification. ## Runtime Expenses for Screenshot Transfer To allow the bot to read from the screenshot, we transfer the screenshot from the volatile host to the bot. In an early version of this transport, I reused the BMP image file decoding developed earlier on the bot side. So the bot would receive the screenshot as BMP encoded image file. I implemented a variant in which the data is sent encoded in base64. But I did not find a solution to decode from the base64 string to `Bytes` fast enough. The first base64 decoding function I experimented with was from `ivadzy/bbase64 1.1.1`. Then I tried the base64 decoding function from `danfishgold/base64-bytes 1.0.2`. With both of them, I saw more than five seconds of bot event processing time. When I just let it store the base64 string on the bot side, the duration dropped dramatically: In most cases, less than 300ms for an image with 1000x800 pixels. I achieved a significant reduction of the time to process the bot event when completely removing base64 decoding and instead pack the pixel values into arrays of integers in the JSON. Remember that processing times also depend on the used javascript engine. After switching to V8/puppeteer, we might find new/other variants to be faster. <file_sep>What is more interesting than playing video games? - Programming bots to play video games! ## Guides + Video on how to run a bot live: <https://to.botlab.org/guide/video/how-to-run-a-bot-live> + How to install the BotLab client and register the `botlab` command: <https://to.botlab.org/guide/how-to-install-the-botlab-client> + How to run a bot: <https://to.botlab.org/guide/how-to-run-a-bot> + How to report an issue with a bot or request a new feature: <https://to.botlab.org/guide/how-to-report-an-issue-with-a-bot-or-request-a-new-feature> + Observing and inspecting (aka 'debugging') a bot: <https://to.botlab.org/guide/observing-and-inspecting-a-bot> + Testing a bot using simulated environments: <https://to.botlab.org/guide/testing-a-bot-using-simulated-environments> + Input focus scheduling for multiple bot instances: <https://to.botlab.org/guide/input-focus-scheduling-for-multiple-bot-instances> + Running bots on multiple game clients: <https://to.botlab.org/guide/running-bots-on-multiple-game-clients> + [Walkthrough, Programming, Video] Combining behaviors of multiple bot programs: <https://youtu.be/ALXsLznDOfM> + Learn how to develop EVE Online bots and intel tools. Discover the engineering methods and tools behind the most advanced bots: <https://to.botlab.org/guide/developing-for-eve-online> + Syntax of the Elm programming language: <https://elm-lang.org/docs/syntax> + Elm programming language - forward pipe (`|>`) and function composition (`>>`) operators: <https://to.botlab.org/guide/elm-programming-language-forward-pipe-and-function-composition-operators> + Learning Elm? Download the Elm Cheat Sheet to support you during the learning process: <https://github.com/lucamug/elm-cheat-sheet/> + Get a guide for writing Elm code that reads from the EVE Online game client's user interface: Using types from the parsed user interface: <https://to.botlab.org/guide/parsed-user-interface-of-the-eve-online-game-client> + Inspect the UI tree of an EVE Online game client process (live or from archived samples): <https://to.botlab.org/guide/alternate-ui-for-eve-online> + [Programming]: Adding a counter to a bot: <https://forum.botlab.org/t/i-would-like-to-use-survey-scanner-for-every-even-numbers-of-targets-targetted/3807> + [Walkthrough, Programming]: Making an EVE Online bot see anomalies and other pilots: <https://vimeo.com/526817258> + How to collect samples for 64-bit memory reading development: <https://to.botlab.org/guide/collect-samples-for-memory-reading-development> + Syntax highlighting of code blocks - How to format code on the forum: <https://forum.botlab.org/t/syntax-highlighting-of-code-blocks-how-to-format-code-on-the-forum/738> + BotLab Contributor Program: <https://to.botlab.org/guide/botlab-contributor-program> ## Example Bots Wondering what outcome you can expect from following the guides? Below is a list of example bots. You can test them for free: + EVE Online warp-to-0 autopilot + User guide: <https://to.botlab.org/guide/app/eve-online-autopilot-bot> + Program code: <https://github.com/Viir/bots/tree/main/implement/applications/eve-online/eve-online-warp-to-0-autopilot> + EVE Online mining bot + User guide: <https://to.botlab.org/guide/app/eve-online-mining-bot> + Program code: <https://github.com/Viir/bots/tree/main/implement/applications/eve-online/eve-online-mining-bot> + EVE Online combat anomaly bot + User guide: <https://to.botlab.org/guide/app/eve-online-combat-anomaly-bot> + Program code: <https://github.com/Viir/bots/tree/main/implement/applications/eve-online/eve-online-combat-anomaly-bot> + Tribal Wars 2 farmbot + User guide: <https://to.botlab.org/guide/app/tribal-wars-2-farmbot> + Program code: <https://github.com/Viir/bots/tree/main/implement/applications/tribal-wars-2/tribal-wars-2-farmbot> + Elvenar bot + User guide: <https://to.botlab.org/guide/app/elvenar-bot> + Program code: <https://github.com/Viir/bots/tree/main/implement/applications/elvenar> ## Related Guides + Learn to make online games using the Elm programming language: <https://github.com/onlinegamemaker/making-online-games> ## Experimental Tools and Guides + Use an integrated development environment to test your Elm code: <https://elm-editor.com> + Explore Elm syntax and core library with the Elm Explorer: <https://botlabs.blob.core.windows.net/blob-library/by-name/ElmExplorer.html> + Inspection tool to explore the structure of EVE Online memory readings: <https://botlabs.blob.core.windows.net/blob-library/by-name/2023-06-21-eve-online-alternate-ui.html> + How to Allow Multiple RDP Sessions in Windows 10: <https://woshub.com/how-to-allow-multiple-rdp-sessions-in-windows-10/> <file_sep>using System; using System.Collections.Generic; using System.Linq; namespace eve_online_memory_reading { public class PyObjectWithRefToDictAt8 : PyObject { public const int Offset_dict = 8; readonly public UInt32? ref_dict; public PyDict Dict { private set; get; } public PyObjectWithRefToDictAt8( Int64 BaseAddress, IMemoryReader MemoryReader) : base(BaseAddress, MemoryReader) { ref_dict = MemoryReader.ReadUInt32(BaseAddress + Offset_dict); } public PyDict LoadDict( IPythonMemoryReader MemoryReader) { if (ref_dict.HasValue) { Dict = new PyDict(ref_dict.Value, MemoryReader, 0x1000); } return Dict; } } public class PyChildrenList : PyObjectWithRefToDictAt8 { PyDictEntry DictEntryChildren; PyList ChildrenList; public UITreeNode[] children { private set; get; } public PyChildrenList( Int64 BaseAddress, IMemoryReader MemoryReader) : base(BaseAddress, MemoryReader) { } public UITreeNode[] LoadChildren( IPythonMemoryReader MemoryReader) { var Dict = this.Dict; if (null != Dict) { DictEntryChildren = Dict.EntryForKeyStr("_childrenObjects"); } if (null != DictEntryChildren) { if (DictEntryChildren.me_value.HasValue) { ChildrenList = new PyList(DictEntryChildren.me_value.Value, MemoryReader); } } if (null != ChildrenList) { var Items = ChildrenList.Items; if (null != Items) { children = Items.Select((ChildAddress) => new UITreeNode(ChildAddress, MemoryReader)).ToArray(); } } return children; } } public class UITreeNode : PyObjectWithRefToDictAt8 { PyDictEntry DictEntryChildren; PyChildrenList ChildrenList; public UITreeNode[] children { private set; get; } public UITreeNode( Int64 BaseAddress, IMemoryReader MemoryReader) : base(BaseAddress, MemoryReader) { } public UITreeNode[] LoadChildren( IPythonMemoryReader MemoryReader) { var Dict = this.Dict; if (null != Dict) { DictEntryChildren = Dict.EntryForKeyStr("children"); } if (null != DictEntryChildren) { if (DictEntryChildren.me_value.HasValue) { ChildrenList = new PyChildrenList(DictEntryChildren.me_value.Value, MemoryReader); ChildrenList.LoadDict(MemoryReader); ChildrenList.LoadChildren(MemoryReader); } } if (null != ChildrenList) { children = ChildrenList.children; } return children; } public IEnumerable<UITreeNode> EnumerateChildrenTransitive( IPythonMemoryReader MemoryReader, int? DepthMax = null) { if (DepthMax <= 0) { yield break; } this.LoadDict(MemoryReader); this.LoadChildren(MemoryReader); var children = this.children; if (null == children) { yield break; } foreach (var child in children) { yield return child; foreach (var childChild in child.EnumerateChildrenTransitive(MemoryReader, DepthMax - 1)) { yield return childChild; } } } } } <file_sep>using System; namespace eve_online_memory_reading { /// <summary> /// Offsets from https://github.com/python/cpython/blob/2.7/Include/listobject.h and https://github.com/python/cpython/blob/2.7/Objects/listobject.c /// </summary> public class PyList : PyObjectVar { public const int Offset_ob_item = 12; readonly public UInt32? ob_item; readonly public UInt32[] Items; public PyList( Int64 BaseAddress, IMemoryReader MemoryReader) : base(BaseAddress, MemoryReader) { ob_item = MemoryReader.ReadUInt32(BaseAddress + Offset_ob_item); if (ob_item.HasValue && ob_size.HasValue) { Items = MemoryReader.ReadArray<UInt32>(ob_item.Value, (int)ob_size.Value * 4); } } } } <file_sep>using System; using System.Linq; namespace eve_online_memory_reading { public class PyDictEntry { readonly public Int64 BaseAddress; readonly public UInt32? me_hash; readonly public UInt32? me_key; readonly public UInt32? me_value; readonly public PyStr KeyAsStr; public string KeyStr { get { var KeyAsStr = this.KeyAsStr; if (null == KeyAsStr) { return null; } return KeyAsStr.String; } } public PyDictEntry( Int64 BaseAddress, IMemoryReader MemoryReader) { this.BaseAddress = BaseAddress; var Array = MemoryReader.ReadArray<UInt32>(BaseAddress, 12); if (null == Array) { return; } if (0 < Array.Length) { me_hash = Array[0]; } if (1 < Array.Length) { me_key = Array[1]; KeyAsStr = new PyStr(me_key.Value, MemoryReader); } if (2 < Array.Length) { me_value = Array[2]; } } } /// <summary> /// Offsets from https://github.com/python/cpython/blob/2.7/Include/dictobject.h and https://github.com/python/cpython/blob/2.7/Objects/dictobject.c /// </summary> public class PyDict : PyObject { public const int Offset_ma_fill = 8; public const int Offset_ma_used = 12; public const int Offset_ma_mask = 16; public const int Offset_ma_table = 20; readonly public UInt32? ma_fill; readonly public UInt32? ma_used; readonly public UInt32? ma_mask; readonly public UInt32? ma_table; readonly public UInt32? SlotsCount; readonly public PyDictEntry[] Slots; public PyDict( Int64 BaseAddress, IMemoryReader MemoryReader, int? SlotsCountMax = null) : base(BaseAddress, MemoryReader) { ma_fill = MemoryReader.ReadUInt32(BaseAddress + Offset_ma_fill); ma_used = MemoryReader.ReadUInt32(BaseAddress + Offset_ma_used); ma_mask = MemoryReader.ReadUInt32(BaseAddress + Offset_ma_mask); ma_table = MemoryReader.ReadUInt32(BaseAddress + Offset_ma_table); SlotsCount = ma_mask + 1; if (ma_table.HasValue && SlotsCount.HasValue) { var SlotsToReadCount = (int)Math.Min(SlotsCountMax ?? int.MaxValue, SlotsCount.Value); Slots = Enumerable.Range(0, SlotsToReadCount) .Select((SlotIndex) => new PyDictEntry(ma_table.Value + SlotIndex * 12, MemoryReader)) .ToArray(); } } public PyDictEntry EntryForKeyStr(string KeyStr) { var Slots = this.Slots; if (null == Slots) { return null; } foreach (var Slot in Slots) { if (null == Slot) { continue; } if (string.Equals(Slot.KeyStr, KeyStr)) { return Slot; } } return null; } } } <file_sep># Developing for EVE Online Have you ever wondered about the process of creating bots or intel tools for EVE Online? This guide walks you through the process and enables you to customize bots. After learning about the simple customization of an existing bot, we'll explore the techniques and tools used to develop the most advanced bots that can autonomously perform a range of in-game activities such as mining, ratting, trading, and mission running for hours on end. In part, this is a summary of my learnings from development projects. But more importantly, this guide is a product of your feedback. Thank you for the countless questions and suggestions, which made the guide what it is today. ## The Simplest Custom Bot In this exercise, we take the fastest way to a custom bot, starting with an open-source bot we find published on the internet. Let's run this autopilot bot: <https://github.com/Viir/bots/tree/eca3adf93f2b6fd31ff0c38e4118a4e31759d9c6/implement/applications/eve-online/eve-online-warp-to-0-autopilot> The easiest way to run this bot is by entering the address above into the BotLab client in the 'Select Bot' view. In case the BotLab client program is not yet installed on your system, follow the installation guide at <https://to.botlab.org/guide/how-to-install-the-botlab-client> Before running this bot, you need to start an EVE Online client, no need to go beyond character selection. When the bot has started, it will display this message: > I see no route in the info panel. I will start when a route is set. That is unless you have set a route in the autopilot. To customize this bot, we change its program code. The program code consists of the files behind the address we gave to the BotLab program. The easiest way to work on program codes is using the Elm Editor at <https://elm-editor.com> In this editor, we can load program code files, edit the code and get assistance in case of problems. You can use the 'Project' -> 'Load from Git Repository' dialog in Elm Editor to load any bot program code that is located on GitHub, such as the one we used above. After loading the program files into Elm Editor, select the `Bot.elm` file to open in the code editor. Here is a link that brings you directly into the `Bot.elm` file in Elm Editor, automating the import steps described above: <https://elm-editor.com/?project-state=https%3A%2F%2Fgithub.com%2FViir%2Fbots%2Ftree%2Feca3adf93f2b6fd31ff0c38e4118a4e31759d9c6%2Fimplement%2Fapplications%2Feve-online%2Feve-online-warp-to-0-autopilot&file-path-to-open=Bot.elm> After making changes to the program code, we can use the 'Project' -> 'Export to Zip Archive' dialog in Elm Editor to download all the files in the project with their new content. In the BotLab client, we can load the bot directly from that zip archive by entering the path to the archive as the source. We don't need to extract the archive, as that happens automatically. Now that we know how to run a program code from the editor, let's change it to make it our own. In the `Bot.elm` file on line 154, we find the text that we saw in the bots status message earlier, enclosed in double-quotes: ![EVE Online autopilot bot code in Elm Editor](./image/2021-08-29-eve-online-autopilot-bot-code-in-elm-editor-in-space.png) Replace that text between the double-quotes with another text: ```Elm case context.readingFromGameClient |> infoPanelRouteFirstMarkerFromReadingFromGameClient of Nothing -> describeBranch "Hello World! - I see no route in the info panel. I will start when a route is set." (decideStepWhenInSpaceWaiting context) ``` After changing the program code, use the 'Export Project to Zip Archive' dialog again to get the complete program code in a runnable format. Running our new version, we see the change reflected in the bot's status text. ### Getting Faster Now you could generate random sequences of program text and test which ones are more useful. If you do this long enough, you will discover one that is more useful than anything anyone has ever found before. But the number of possible combinations is too large to proceed in such a simple way. We need a way to discard the useless combinations faster. In the remainder of this guide, I show how to speed up this process of discovering and identifying useful combinations. ## Observing and Inspecting a Bot An improvement to a bots program code begins with observation of the behavior of the bot in an environment. Environments can be synthetic, simulated, or an actual live game client. To learn how to observe and inspect the behavior of a bot, see the guide at <https://to.botlab.org/guide/observing-and-inspecting-a-bot> ## Overall Program Code Structure and Data Flow In the 'The Simplest Custom Bot' section, we changed the code in the `Bot.elm` file to customize a bot. Because we only made a simple change, we could do it without understanding the program code's overall structure. The more we want to change, the more we benefit from understanding how everything works together. This chapter explains the program code's overall structure and how data flows when the bot runs. To explore how a program works, we start from the part that you have already experience with: The observable behavior. From there, we work towards the parts which are invisible to the user, the implementation details. On this journey, we will also pick up some basic vocabulary used in bot development. Knowing the language will help you communicate with other developers and get help in case you need it. ### Effects For the bot to be useful, it needs to affect its environment in some way eventually. If it is a bot, it might send input to the game client. An intel tool, on the other hand, might play a sound. We have a common name for these observable consequences of running the bot: We call them 'effects'. Following is a list of effects available in our framework: + Move the mouse cursor to a given location. (Relative to the game window (The client area of that window to be more specific)) + Press a given mouse button. + Release a given mouse button. + Press a given keyboard key. + Release a given keyboard key. These effects are not specific to EVE Online, which is why we use functions from the code module `Common.EffectOnWindow` to describe these effects. ### Events To be able to decide which effects would be most useful, the bot needs to learn about its environment. In our case, this environment is the game client. The bot receives this information about the game client with events. When programming a bot, every effect originates from an event. An event can result in zero or multiple effects, but the bot cannot issue an effect without an event. This constraint is not evident from a user's perspective because the user does not know when events happen. But knowing this rule helps to understand the structure of the program code. In our framework for EVE Online, the events are simplified as follows: The only event that we customize is the arrival of a new reading from the game client. If we were using a more general framework, we had other kinds of events too. One example is when the user changes the bot-settings, which can happen at any time. Our framework will not notify us every time the bot-settings change. Instead, it forwards us the bot-settings and other contextual information together with the next new reading from the game client. Another critical piece of context is the current time. The time too is forwarded only with the following new reading from the game client. ### Bot Program Code Structure - Framework For EVE Online To make development easier, we can use one of the frameworks available for EVE Online. Using a framework is a tradeoff between flexibility and ease of use. You can compare it to using Microsoft Windows instead of building your custom operating system: Using this platform, we can avoid learning about lower levels of the software stack, like a machine programming language. In this guide, I use the most mainstream framework evolved from the works of some hundred EVE Online users and developers. When you look at the example projects, you will find that many kinds of bots use the same framework. It is flexible enough to cover activities like mining, ratting, trading, and mission running. This framework's program code is included with the overall program code in the subdirectory named `EveOnline`. This makes it easier to look up a definition of a framework function. You can code all your customizations in the `Bot.elm` file. When you compare the files making up the example bots, you will find that the different bots only differ in the `Bot.elm` file. At the beginning of that code module, these bots import building blocks from other code modules of the framework, namely `EveOnline.BotFramework`, `EveOnline.BotFrameworkSeparatingMemory` and `EveOnline.ParseUserInterface`. These three modules contain hundreds of building blocks to compose your bot. ### Entry Point - `botMain` In the `Bot.elm` file of each bot program code, you can find a declaration named [`botMain`](https://github.com/Viir/bots/blob/eca3adf93f2b6fd31ff0c38e4118a4e31759d9c6/implement/applications/eve-online/eve-online-warp-to-0-autopilot/Bot.elm#L258-L269). In contrast to other declarations in that file, `botMain` has a unique role. Any other declaration can contribute to the bots behavior only if it is somehow referenced by `botMain`, directly or indirectly. Because of its unique role, we also call it the 'entry point'. The type of `botMain` is not specific to EVE Online. Bots for other games use the same structure. Program codes for the EVE Online client use functions from `EveOnline.BotFrameworkSeparatingMemory` module to build the more general `botMain` value. We can see this in the example projects, no matter if it is a mining bot, ratting bot, or just a monitor that watches local chat and alerts the user when a hostile pilot enters. Here is how the [autopilot example bot code](https://github.com/Viir/bots/blob/eca3adf93f2b6fd31ff0c38e4118a4e31759d9c6/implement/applications/eve-online/eve-online-warp-to-0-autopilot/Bot.elm#L258-L269) uses framework functions to configure the bot: ```Elm botMain : InterfaceToHost.BotConfig State botMain = { init = EveOnline.BotFrameworkSeparatingMemory.initState initBotMemory , processEvent = EveOnline.BotFrameworkSeparatingMemory.processEvent { parseBotSettings = parseBotSettings , selectGameClientInstance = always EveOnline.BotFramework.selectGameClientInstanceWithTopmostWindow , updateMemoryForNewReadingFromGame = updateMemoryForNewReadingFromGame , decideNextStep = autopilotBotDecisionRoot , statusTextFromDecisionContext = statusTextFromDecisionContext } } ``` In the snippet above, our program code composes the bot by combining multiple values from `Bot.elm` using the framework. Using the `parseBotSettings` field, we configure how to parse the user's bot settings string into a structured representation. The bot-settings offer a way to customize bot behavior without changing the bot code. We can use any type we want for our bot settings. ### Data Flow for a Bot Step The framework structures the execution of our bot as a series of 'bot steps'. Every time a new reading from the game client is complete, the framework performs one such bot step. The information going into a bot step contains: + The reading from the game client. + The current time. + bot-settings, structure as parsed earlier. + The planned session duration. The result from a bot step contains: + Do we finish the session now, or do we continue? If we continue the session, what is the sequence of inputs we send to the game client? + The new status text to display to the user. Of the five elements that we gave to the framework in the code snippet above, it uses the following three in each bot step: + `updateMemoryForNewReadingFromGame`: Here, we define anything we might need to remember in future bot steps. We use this memory to remember observations about the game world that we need to make decisions in the future: Which asteroid belts are already depleted? Which anomalies contains dangerous rats that we want to avoid? Another application of this memory is tracking performance statistics: How many rats have we killed in this session? + `decideNextStep`: Here, we decide how to proceed in the session: Do we continue or finish the session? If we continue, which inputs do we send to the game client? + `statusTextFromDecisionContext`: Here, we add to the status text displayed by the whole bot. We expand this status text, for example, to show the performance metrics of our bot. The `decideNextStep` and `statusTextFromDecisionContext` run in parallel. They do not depend on each others output, but both depend on the return value from `updateMemoryForNewReadingFromGame`. The diagram below visualizes the data flow for a single bot step: ![Data flow in a bot step in the framework for EVE Online](./../image/2021-10-13-data-flow-in-bot-architecture-separating-memory.png) The arrows in this diagram illustrate how the framework forwards data between the functions we supplied to compose the bot. ### `parseBotSettings` The framework invokes the `parseBotSettings` function every time the user changes the bot-settings. The return type is a kind of `Result` which means we can decide that a given bot-settings string is invalid and reject it. The `Err` case uses the `String` type, and we use this to explain to the user what is wrong with the given bot-settings string. In most cases, you don't want to code the parsing and generation of error messages for the user from scratch. There is a framework that parses settings strings based on a list of settings that you specified. Using this framework makes it trivial to add new settings. In our bot, we only need to define a list of valid settings, and the framework will generate a precise error message if the user misspells the name of a setting or tries to use a setting with an unsupported value. ## Programming Language The bots here are mainly written using the Elm programming language. Many bots also contain a small portion of glue code in other languages like C#, but thanks to the framework, you don't even need to read these low-level parts. ### An Introduction to Elm A great resource to learn about the Elm programming language is the official guide at <https://guide.elm-lang.org> Parts of this guide are specific to web applications and less interesting when building bots. However, it also teaches fundamentals, which are very useful for us, specifically ["Core Language"](https://guide.elm-lang.org/core_language.html) and ["Types"](https://guide.elm-lang.org/types/). And if you want to get into even more detail: The [Appendix](https://guide.elm-lang.org/appendix/function_types.html) covers more advanced topics, helping to understand not only how to write apps, but also how the framework is built. ### Types Types are an important tool we get with the programming language. The type system allows the engine to draw our attention to problems in the program code before we even run an app. In the program code of examples, you can find many descriptions of types on lines starting with the "type" keyword. Here are two examples: ```Elm type alias DronesWindow = { uiNode : UITreeNodeWithDisplayRegion , droneGroups : List DronesWindowEntryGroupStructure , droneGroupInBay : Maybe DronesWindowEntryGroupStructure , droneGroupInSpace : Maybe DronesWindowEntryGroupStructure } ``` ```Elm type ShipManeuverType = ManeuverWarp | ManeuverJump | ManeuverOrbit | ManeuverApproach ``` The guide on the Elm programming language has a chapter ["Types"](https://guide.elm-lang.org/types/), and I recommend reading this to learn what these syntaxes mean. This chapter is also worth a look if you encounter a confusing "TYPE MISMATCH" error in a program code. In the ["Reading Types"](https://guide.elm-lang.org/types/reading_types.html) part, you will also find an interactive playground where you can test Elm syntax to reveal types that are sometimes not visible in program syntax. Here is the link to the "Types" chapter in the Elm guide: <https://guide.elm-lang.org/types/> ---- Any questions? The [BotLab forum](https://forum.botlab.org) is the place to meet other developers and get help. <file_sep># 2019-10-14 Improve Automated Testing Based on experience working on these changes: + https://github.com/Viir/bots/commit/9929d49f4c38611181c08325d23bad5ef8a36cab + https://github.com/Viir/bots/commit/1b93524d8c43bd7a66d3c0cbd09a37eeaccc4534 Problems experienced there: + Process to extract the relevant portions from the sample files which were already present in the same repository: + So far, using `elm-test` to run tests. + The sample data (from https://github.com/Viir/bots/tree/1b93524d8c43bd7a66d3c0cbd09a37eeaccc4534/implement/applications/eve-online/training-data/2019-10-12.eve-online-mining) has to be made available to the Elm test function somehow. To solve this, test data was copied into the Elm module source code. + To avoid problems with parsing the Elm modules and with readability for humans, the sample data was not copied completely but reduced to portions which are relevant for the test. + Just removing contents before and after the part of the JSON tree containing the tested object was not sufficient; in some cases also removed superfluous elements within the subtree tree, which is parsed in the test. Not everything in there is parsed. + Ideally, we could reference the file we already have, instead of messing with the Elm source code. How about using a test runner that supports referencing and loading files and propagating them into the tests? We could describe a test in the Elm module like this: ```Elm type alias FileTest = { name : String , source : String , passes : Bytes.Bytes -> Bool } allTestsToRun : List FileTest allTestsToRun = [ sample_7C3AE6AF_ship_UI_first_module ] sample_7C3AE6AF_ship_UI_first_module : List FileTest sample_7C3AE6AF_ship_UI_first_module = { name = "7C3AE6AF - First Ship UI Module" , source = "https://github.com/Viir/bots/blob/1b93524d8c43bd7a66d3c0cbd09a37eeaccc4534/implement/applications/eve-online/training-data/2019-10-12.eve-online-mining/2019-10-12.from-7C3AE6AF.reduced-with-named-nodes.only-shipui.json" , passes = (Bytes.Decode.decode Bytes.Decode.string |> Maybe.andThen (parseMemoryMeasurementFromJson >> Result.toMaybe) |> Maybe.andThen (.shipUi >> maybeNothingFromCanNotSeeIt) |> Maybe.map .modules |> Maybe.andThen List.head ) == Just { uiElement = { id = 543723600, region = { left = 632, top = 539, right = 696, bottom = 603 } } , isActive = Just True } } ``` Note about the source in the example above: Since it specifies a commit hash, we do not need to load from the given address. Maybe we have the same commit in a local repository; then, we can get it from there. At the same time, having the URL in the code helps humans navigate. This design should allow to only give the name of the compilation root module and the name of the `allTestsToRun` function to the test runner. <file_sep>using System; using System.Runtime.InteropServices; namespace dotnet_windows_bot_interface { class Program { static void Main(string[] args) { var waitTimeInSeconds = 1; // Before continuing, give the user some time to activate the window we want to work with. Console.WriteLine("Please activate the window I should work in. I will read the active window in " + waitTimeInSeconds + " seconds."); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(waitTimeInSeconds)); // Test the request/response code as if used from the bot. var windowToWorkOn = request(new Request { GetForegroundWindow = true }) .GetForegroundWindowResult; var windowTitle = request(new Request { GetWindowText = windowToWorkOn }).GetWindowTextResult; Console.WriteLine("I identified a window with the title '" + windowTitle + "' as the window to work in."); // if (false) { // Test sequence to use with MS Paint. (When testing this with Paint.NET, no lines were drawn) foreach (var taskSequence in demoSequenceToTestMousePathOnPaint()) { foreach (var task in taskSequence) { request( new Request { TaskOnWindow = new Request.TaskOnIdentifiedWindowStructure { windowId = windowToWorkOn, task = task, } }); } waitMilliseconds(44); } } var windowToWorkOnHandle = new IntPtr(windowToWorkOn.WindowHandleFromInt); var screenshotImageFile = GetScreenshotOfWindowAsImageFileBMP(windowToWorkOnHandle); if (screenshotImageFile == null) { Console.WriteLine("I failed to get a screenshot of the window."); return; } var filePath = System.IO.Path.Combine(Environment.CurrentDirectory, "test", DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH-mm-ss") + ".screenshot.bmp"); System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath)); System.IO.File.WriteAllBytes(filePath, screenshotImageFile); Console.WriteLine("I got a screenshot of the window, and saved it to file '" + filePath + "'."); } static public Response request(Request request) { SetProcessDPIAware(); string GetWindowText(WindowId windowId) { var windowHandle = new IntPtr(windowId.WindowHandleFromInt); var windowTitle = new System.Text.StringBuilder(capacity: 256); WinApi.GetWindowText(windowHandle, windowTitle, windowTitle.Capacity); return windowTitle.ToString(); } if (request.GetForegroundWindow != null) { return new Response { GetForegroundWindowResult = GetForegroundWindow() }; } if (request.GetWindowText != null) { return new Response { GetWindowTextResult = GetWindowText(request.GetWindowText), }; } if (request.TaskOnWindow != null) { performTaskOnWindow(request.TaskOnWindow); return new Response { NoReturnValue = new object() }; } throw new Exception("Unexpected request value."); } static public WindowId GetForegroundWindow() => new WindowId { WindowHandleFromInt = WinApi.GetForegroundWindow().ToInt64() }; static public byte[] GetScreenshotOfWindowAsImageFileBMP(IntPtr windowHandle) { var screenshotAsBitmap = GetScreenshotOfWindowAsBitmap(windowHandle); if (screenshotAsBitmap == null) return null; using (var stream = new System.IO.MemoryStream()) { screenshotAsBitmap.Save(stream, format: System.Drawing.Imaging.ImageFormat.Bmp); return stream.ToArray(); } } static public System.Drawing.Bitmap GetScreenshotOfWindowAsBitmap(IntPtr windowHandle) { SetProcessDPIAware(); var windowRect = new WinApi.Rect(); if (WinApi.GetWindowRect(windowHandle, ref windowRect) == IntPtr.Zero) return null; int width = windowRect.right - windowRect.left; int height = windowRect.bottom - windowRect.top; var asBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); // Where from could we get the scale to apply to compute the rect in screen coordinates? Console.WriteLine("System.Drawing.Graphics.FromImage(asBitmap).DpiX: " + System.Drawing.Graphics.FromImage(asBitmap).DpiX); Console.WriteLine("System.Drawing.Graphics.FromHwnd(GetDesktopWindow()).DpiX: " + System.Drawing.Graphics.FromHwnd(WinApi.GetDesktopWindow()).DpiX); Console.WriteLine("System.Drawing.Graphics.FromHwnd(windowHandle).DpiX: " + System.Drawing.Graphics.FromHwnd(windowHandle).DpiX); System.Drawing.Graphics.FromImage(asBitmap).CopyFromScreen( windowRect.left, windowRect.top, 0, 0, new System.Drawing.Size(width, height), System.Drawing.CopyPixelOperation.SourceCopy); return asBitmap; } static void SetProcessDPIAware() { // https://www.google.com/search?q=GetWindowRect+dpi // https://github.com/dotnet/wpf/issues/859 // https://github.com/dotnet/winforms/issues/135 WinApi.SetProcessDPIAware(); } static void waitMilliseconds(int milliseconds) => System.Threading.Thread.Sleep(milliseconds); static void performTaskOnWindow(Request.TaskOnIdentifiedWindowStructure taskOnIdentifiedWindow) { var windowHandle = new IntPtr(taskOnIdentifiedWindow.windowId.WindowHandleFromInt); var windowRect = new WinApi.Rect(); if (WinApi.GetWindowRect(windowHandle, ref windowRect) == IntPtr.Zero) return; var inputSimulator = new WindowsInput.InputSimulator(); var task = taskOnIdentifiedWindow.task; if (task.BringWindowToForeground != null) { WinApi.SetForegroundWindow(windowHandle); WinApi.ShowWindow(windowHandle, WinApi.SW_RESTORE); } if (task.MoveMouseToLocation != null) { WinApi.SetCursorPos( task.MoveMouseToLocation.x + windowRect.left, task.MoveMouseToLocation.y + windowRect.top); } if (task.MouseButtonDown != null) { if (task.MouseButtonDown.MouseButtonLeft != null) inputSimulator.Mouse.LeftButtonDown(); if (task.MouseButtonDown.MouseButtonRight != null) inputSimulator.Mouse.RightButtonDown(); } if (task.MouseButtonUp != null) { if (task.MouseButtonUp.MouseButtonLeft != null) inputSimulator.Mouse.LeftButtonUp(); if (task.MouseButtonUp.MouseButtonRight != null) inputSimulator.Mouse.RightButtonUp(); } if (task.KeyboardKeyDown != null) inputSimulator.Keyboard.KeyDown((WindowsInput.Native.VirtualKeyCode)task.KeyboardKeyDown.KeyboardKeyFromVirtualKeyCode); if (task.KeyboardKeyUp != null) inputSimulator.Keyboard.KeyUp((WindowsInput.Native.VirtualKeyCode)task.KeyboardKeyUp.KeyboardKeyFromVirtualKeyCode); } static Request.TaskOnWindowStructure[][] demoSequenceToTestMousePathOnPaint() => new[] { new [] { new Request.TaskOnWindowStructure { BringWindowToForeground = true, }, }, new [] { new Request.TaskOnWindowStructure { MoveMouseToLocation = new Request.Location2d { x = 100, y = 250 }, }, new Request.TaskOnWindowStructure { MouseButtonDown = new Request.MouseButton{ MouseButtonLeft = true }, }, }, new [] { new Request.TaskOnWindowStructure { MoveMouseToLocation = new Request.Location2d { x = 200, y = 300 }, }, new Request.TaskOnWindowStructure { MouseButtonUp = new Request.MouseButton{ MouseButtonLeft = true }, }, new Request.TaskOnWindowStructure { MouseButtonDown = new Request.MouseButton{ MouseButtonRight = true }, }, }, new [] { new Request.TaskOnWindowStructure { MoveMouseToLocation = new Request.Location2d { x = 300, y = 230 }, }, new Request.TaskOnWindowStructure { MouseButtonUp = new Request.MouseButton{ MouseButtonRight = true }, }, }, new [] { new Request.TaskOnWindowStructure { MoveMouseToLocation = new Request.Location2d { x = 160, y = 235 }, }, new Request.TaskOnWindowStructure { MouseButtonDown = new Request.MouseButton{ MouseButtonLeft = true }, }, new Request.TaskOnWindowStructure { MouseButtonUp = new Request.MouseButton{ MouseButtonLeft = true }, }, }, // 2019-06-09 MS Paint did also draw when space key was pressed. Next, we draw a line without a mouse button, by holding the space key down. new [] { new Request.TaskOnWindowStructure { MoveMouseToLocation = new Request.Location2d { x = 180, y = 230 }, }, new Request.TaskOnWindowStructure { KeyboardKeyDown = new Request.KeyboardKey{ KeyboardKeyFromVirtualKeyCode = (int)WindowsInput.Native.VirtualKeyCode.SPACE } }, }, new [] { new Request.TaskOnWindowStructure { MoveMouseToLocation = new Request.Location2d { x = 210, y = 240 }, }, new Request.TaskOnWindowStructure { KeyboardKeyUp = new Request.KeyboardKey{ KeyboardKeyFromVirtualKeyCode = (int)WindowsInput.Native.VirtualKeyCode.SPACE } }, }, }; } static public class WinApi { [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left; public int top; public int right; public int bottom; } public enum MouseButton { Left = 0, Middle = 1, Right = 2, } [DllImport("user32.dll")] static public extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static public extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count); [DllImport("user32.dll", SetLastError = true)] static public extern bool SetProcessDPIAware(); [DllImport("user32.dll")] static public extern int SetForegroundWindow(IntPtr hWnd); public const int SW_RESTORE = 9; [DllImport("user32.dll")] static public extern IntPtr ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] static public extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); [DllImport("user32.dll", SetLastError = false)] static public extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static public extern bool SetCursorPos(int x, int y); } public class Request { public TaskOnIdentifiedWindowStructure TaskOnWindow; public object GetForegroundWindow; public WindowId GetWindowText; public class TaskOnIdentifiedWindowStructure { public WindowId windowId; public TaskOnWindowStructure task; } public class TaskOnWindowStructure { public object BringWindowToForeground; public Location2d MoveMouseToLocation; public MouseButton MouseButtonDown; public MouseButton MouseButtonUp; public KeyboardKey KeyboardKeyDown; public KeyboardKey KeyboardKeyUp; } public class Location2d { public int x, y; } public class MouseButton { public object MouseButtonLeft; public object MouseButtonRight; } public class KeyboardKey { public int KeyboardKeyFromVirtualKeyCode; } } public class Response { public WindowId GetForegroundWindowResult; public object NoReturnValue; public string GetWindowTextResult; } public class WindowId { public long WindowHandleFromInt; } } <file_sep># Setting up Programming Tools Locally The easiest way to work on program codes is using the Elm Editor at https://elm-editor.com In this editor, we can load program code files, edit the code and get assistance in case of problems. However, in some cases, you might prefer using a local development environment. In contrast to using the online editor, a local setup reduces dependency on network bandwidth and response times. This guide shows the process of setting up a local development environment on a Windows machine. To achieve this, we combine the following tools: + Elm command line program + Visual Studio Code + elmtooling.elm-ls-vscode + elm-format The following subsections explain in detail how to set up these tools. To test and verify that the setup works, you need the program code files of an Elm app on your system. You can use the files from https://github.com/Viir/bots/tree/3a19d243ce02b9fdc8ac199c74164d86b4777a5b/implement/applications/eve-online/eve-online-warp-to-0-autopilot for this purpose. ### Elm command line program The Elm command line program understands the [programming language](https://elm-lang.org/blog/the-perfect-bug-report) we use and [helps us](https://elm-lang.org/blog/compilers-as-assistants) find problems in the code we write. You can download the Elm executable file from https://botengine.blob.core.windows.net/blob-library/by-name/elm.exe Next, we perform a small test to verify the elm.exe program works on the program code as intended. Since `elm.exe` is a command line program, we start it from the Windows Command Prompt (cmd.exe). Before starting the elm.exe, you need to navigate to the program code directory containing the `elm.json` file. You can use the `cd` command in the Command Prompt to switch to this directory, with a command like this: ```cmd cd "C:\Users\John\Downloads\bots-39afeba4ca24884666a8e473a9d7ae6842ee6227\implement\applications\eve-online\eve-online-warp-to-0-autopilot" ``` Now you can use elm.exe on the program code files with a command like the following: ``` "C:\Users\John\Downloads\binary-for-windows-64-bit\elm.exe" make Bot.elm ``` If everything works so far, the elm.exe will write an output which ends like the following: ``` Success! Compiled 10 modules. ``` or just ``` Success! ``` That number of modules it mentions can vary; For development, we don't need to use the Elm program directly, but other tools depend on it. The tools we set up next automate the process of starting the Elm program and presenting the results inside a code editor. ### Visual Studio Code Visual Studio Code is a software development tool from Microsoft, which also contains a code editor. This is not the same as 'Visual Studio', a commercial product from Microsoft. Visual Studio Code is free and open-source, and often abbreviated as 'VSCode' to better distinguish it from Visual Studio. To set it up, use the installer from https://code.visualstudio.com/download ### elmtooling.elm-ls-vscode [elmtooling.elm-ls-vscode](https://marketplace.visualstudio.com/items?itemName=Elmtooling.elm-ls-vscode) is an extension for VSCode. It has multiple features to help with development in Elm programs such as our bots. An important one is the display of error messages inside the code editor. A more obvious feature is the syntax coloring in Elm files, as you will soon see. To install this extension, open VSCode and open the 'Extensions' section (`Ctrl + Shift + X`). Type 'elm' in the search box, and you will see the `Elm` extension as shown in the screenshot below: ![Elm extension installation in Visual Studio Code](.//image/2020-01-20.vscode-elm-extension-install.png) Use the `Install` button to install this extension in VSCode. Before this extension can work correctly, we need to tell it where to find the Elm program. Open the Visual Studio Code settings, using the menu entries `File` > `Preferences` > `Settings`. In the settings interface, select the `Elm configuration` entry under `Extensions` in the tree on the left. Then you will see diverse settings for the elm extension on the right, as shown in the screenshot below. Scroll down to the `Elm Path` section and enter the file path to the elm.exe we downloaded earlier into the textbox. The screenshot below shows how this looks like: ![Elm extension settings in Visual Studio Code](./image/2020-01-20.vscode-elm-extension-settings.png) VSCode automatically saves this setting and remembers it the next time you open the program. To use VSCode with Elm, open it with the directory containing the `elm.json` file as the working directory. Otherwise, the Elm functionality will not work. A convenient way to do this is using the Windows Explorer context menu entry `Open with Code` on the directory containing the code, as shown in the screenshot below: ![Open a directory in Visual Studio Code from the Windows Explorer](./image/vscode-open-directory-from-explorer.png) Now we can test if our setup works correctly. In VSCode, open the `Bot.elm` file and make a code change to provoke a compilation error. When you save the file (`Ctrl + S`), the VSCode extension starts Elm in the background to check the code. On the first time, it can take longer as required packages are downloaded. But usually, Elm should complete the check in a second. If the code is ok, you will not see any change. If there is a problem, this is displayed in multiple places, as you can see in the screenshot below: + In the file tree view, coloring files containing errors in red. + On the scroll bar in an open file. You can see this as a red dot in the screenshot. This indicator helps to scroll to interesting locations in large files quickly. + When the offending portion of the code is visible in an editor viewport, the error is pointed out with a red squiggly underline. ![Visual Studio Code displays diagnostics from Elm](./image/2020-06-10-vscode-elm-display-error.png) When you hover the mouse cursor over the highlighted text, a popup window shows more details. Here you find the message we get from Elm: ![Visual Studio Code displays diagnostics from Elm - details on hover](./image/2020-06-10-vscode-elm-display-error-hover.png) ### elm-format elm-format is a tool we use to format the text in the program code files. This tool arranges program codes in a standard way - without changing the function. This consistent formatting makes the code easier to read. Using this standardized layout is especially useful when collaborating with other people or asking for help with coding. The easiest way to use elm-format is by integrating it with VSCode, the same way as we did with the Elm command line program above. You can download a zip archive containing the executable program from https://github.com/avh4/elm-format/releases/download/0.8.3/elm-format-0.8.3-win-i386.zip Extracting that zip archive gets you the file `elm-format.exe`. To integrate it with VSCode, navigate again to the `Elm LS` extension settings as we did for the other settings earlier. Here, enter the path to the `elm-format.exe` file in the text box under `Elm Format Path`, as shown in this image: ![Elm extension setting elm-format](./image/2020-05-08-vscode-settings-extension-elm-format.png) Now you can invoke the formatting using the `Format Document` command in the VSCode editor. An easy way to test if the formatting works is to open an `.elm` file from the example projects and add a blank line between two functions. As we can see in the example projects, the standard format is to have two empty lines between function definitions. When you add a third one in between, you can see it revert to two blank lines as soon as you invoke the formatting. <file_sep># Custom Programs This file lists some of the customizations of bot programs found on the internet. Often these emerged from answering developers' questions. The list serves as an additional way to find customizations again, besides the general [catalog](https://catalog.botlab.org). If you think a change should be merged into the main branch, you can post on the [forum](https://forum.botlab.org) or create an issue on the [bots GitHub page](https://github.com/Viir/bots/issues). The main branch of the example programs develops by evolution: The more popular a change with users, the more likely it will be merged into the main branch. You can see the popularity displayed at `Total running time in hours` on the program's catalog entry. To find a program on the catalog, you can also enter the commit as a search term, or use the `botlab describe` command. ## 2020-03-19 - goondola - EVE Online - print the list of pilots in local + Original discussion: https://forum.botlab.org/t/learning-be-and-elm/3160 + Program code: https://github.com/Viir/bots/commit/0dcadd5b6d1de84d12be96af32148d618e4fee78 and parent commits. ## 2020-04-21 - Caleb Tribal Wars 2 - Support Multiple Instances https://github.com/Viir/bots/tree/9b623a9cc678de660e3aa57b3e1b131da3ad54f9/implement/applications/tribal-wars-2/tribal-wars-2-farmbot > Support scenario shared by Caleb at https://forum.botlab.org/t/farm-manager-tribal-wars-2-farmbot/3038/62?u=viir 2020-07-06 From the catalog entry at https://catalog.botlab.org/fd575d579bc77305a45495b862f060206e93bc26f3ed39cec87c5f05c74e4928 > Total running time in hours: 162 ## 2020-06-30 - <NAME> - EVE Online - local watch Origin and discussion: https://forum.botlab.org/t/local-intel-bot/3413/6?u=viir https://github.com/Viir/bots/commit/d01478b69a9e71ac7bffc34c25585723d3abf28e ## 2020-07-01 - <NAME> - EVE Online - local watch Origin and discussion: https://github.com/Viir/bots/pull/15 > Uses whitelist instead of blacklist for determining the trigger list. Allows selection of character during launch, still supports auto-picking top window. Beep a bit more. https://github.com/Viir/bots/commit/acf8c8c34dfe910f19bd838236e845d51bafb7e2 ## 2020-07-30 - TheRealManiac - EVE Online - hiding when neutral or hostile appears in local chat On 2020-07-30, the catalog entry at https://catalog.botlab.org/782844bb5667da19d2dec276b3afd9d0a2e381c7e5011f837752c4a0d523e110 shows: > Total running time in hours: 4 Program code change at https://github.com/Viir/bots/commit/42819720f12f34658d88e29ff0e55d158869568d > Support hiding when neutral or hostile appears in local chat > > Add a setting to enable this behavior. > If conditions are met for hiding, do not undock anymore. If conditions are met for hiding, return drones to bay and dock to station or structure. > > Original discussion at https://forum.botlab.org/t/mining-bot-master-branch/3463?u=viir On 2020-08-07, the catalog entry at https://catalog.botlab.org/782844bb5667da19d2dec276b3afd9d0a2e381c7e5011f837752c4a0d523e110 shows: > Total running time in hours: 119 Therefore integrate these into the recommendation on the main branch. ## 2020-08-20 - Dante - EVE Online - priority-rat https://github.com/Viir/bots/tree/95178b9233710d335eedcaf7bd2ac31fffce280f/implement/applications/eve-online/eve-online-combat-anomaly-bot Original discussion: https://forum.botlab.org/t/let-me-know-how-to-make-my-app/3514 2020-08-20 the catalog entry for [App 8e7e916263...](https://catalog.botlab.org/8e7e916263f4cf75eb2fa7e68fc995fe9932324c2c90c37dcaf2206202117351) shows: > Total running time in hours: 76 ## 2020-10-12 - Mactastic08 & annar_731 - EVE Online - Orca Mining https://github.com/Viir/bots/tree/02027201fd8c506c6d88d160b1a80763f8bdabbd/implement/applications/eve-online/eve-online-mactastic08-orca-mining Original discussion: https://forum.botlab.org/t/orca-targeting-mining/3591 2020-10-12 the catalog entry for [App 81395744f5...](https://catalog.botlab.org/81395744f5857f15f5cf22cf091a71b440b42a81dddd0e992a0d9db1fce92da2) shows: > Total running time in hours: 33 2022-04-15 the catalog entry for [Bot 81395744f5...](https://catalog.botlab.org/81395744f5857f15f5cf22cf091a71b440b42a81dddd0e992a0d9db1fce92da2) shows: > Total running time in hours: 175 ## 2020-10-31 - <NAME> - EVE Online - Merged Mining Scripts https://github.com/Viir/bots/commit/f6246764ac106894e74669815c0e675c48ab9262 Original discussion: https://forum.botlab.org/t/eve-online-request-suggestion/3663 ``` Would it be possible to merge both mining scripts? So that the normal mining script would use mining drones as well? Currently the drones willl be activated, but they don’t mine (I guess because most people are using them as fighting drones) Thanks for your help and your great tools ``` 2020-11-06 the catalog entry for [App dbbec0a31d...](https://catalog.botlab.org/dbbec0a31dfe05b39cf37bb4f329c1fe5e4eb5ed85ceadac37f04ccff4a14c0b) shows: > Total running time in hours: 116 2022-04-15 the catalog entry for [Bot dbbec0a31d...](https://catalog.botlab.org/dbbec0a31dfe05b39cf37bb4f329c1fe5e4eb5ed85ceadac37f04ccff4a14c0b) shows: > Total running time in hours: 292 ## 2021-09-22 - Drklord and opticcanadian - Tribal Wars 2 - avoid targets based on outgoing commands https://github.com/Viir/bots/commit/828e5b23a892b050f34680e006543af4df823221 Original discussion: + <https://forum.botlab.org/t/farm-manager-tribal-wars-2-farmbot/3038/222> + <https://forum.botlab.org/t/farm-manager-tribal-wars-2-farmbot/3038/314> 2021-09-22 the catalog entry for [d5a06db64f](https://botcatalog.org/d5a06db64fd579fbcf695ef99162cd1cd069b7c9eddc19e6e5abee5d7be21c43) shows: > Total running time in hours: 71 2022-04-15 the catalog entry for [d5a06db64fd579fb](https://botcatalog.org/d5a06db64fd579fbcf695ef99162cd1cd069b7c9eddc19e6e5abee5d7be21c43) shows: > Total running time in hours: 1343 ## 2021-10-05 - qmail - EVE Online Intel Bot - Local Watch Script Original discussion: + <https://forum.botlab.org/t/bot-not-working-with-new-engine/4142> > EVE Online Intel Bot - Local Watch Script - 2021-09-21 > This bot watches local and plays an alarm sound when a pilot with bad standing appears. + <https://github.com/Viir/bots/tree/0bce0d7f3cd6e560d5a625e9f8a8068610950901/implement/applications/eve-online/eve-online-local-watch> + <https://reactor.botlab.org/catalog/b590279a1fbac9b39a76512df2d5dae3ef92ece4863f307ad4faea03a193ce4d> 2021-10-05 the catalog entry shows: > Total running time in hours: 91 2022-04-15 the catalog entry shows: > Total running time in hours: 1442 ## 2022-09-01 - Maunzinator - EVE Online Intel Bot - Local Watch Bot Discussion: + <https://forum.botlab.org/t/local-watch-bot/4112/3> + <https://catalog.botlab.org/413d1319fc4d45a8> + <https://github.com/Viir/bots/tree/1067c27ab4e56a91f6d7b00c2f45926dd76b8a3a/implement/applications/eve-online/eve-online-local-watch> ## 2022-09-19 - opticcanadian and Drklord - Tribal Wars 2 - avoid targets based on outgoing commands + <https://github.com/Viir/bots/commit/96b22107183d708ec1c44f6e0d2bd6d322d33ba4> + <https://catalog.botlab.org/ab0771677670681c> Original discussion: + <https://forum.botlab.org/t/update-upgrade-to-recent-tribal-wars-2-bot/4443> 2022-10-17 the catalog entry <https://catalog.botlab.org/ab0771677670681c> shows: > Total running time in hours: 1293 <file_sep># How to Report an Issue with a Bot or Request a New Feature Have you used a bot that should be improved? This guide helps you report bugs and communicate ideas for new features. Improving a bot starts with documenting the scenario(s) in which we want the bot to behave differently than it did so far. This applies to both fixing bugs and adding features. These scenarios are the fuel for bot development. Developing bots is very much an incremental process. A bot evolves as we collect more scenarios describing the desired behavior. Explaining your use-case in human language is a good start, but a developer will usually ask for more data. ## Session Recording and Archive The most common way to describe your scenario or use-case is to share a recording of a play session using the bot. The artifact of the session recording allows us to: + See which bot program was used in the session and how it was configured (including bot-settings). + Travel back in time and see what the bot saw in the past. + Understand why our bot did what it did. + Create simulation environments to test new bot programs: https://to.botlab.org/guide/testing-a-bot-using-simulated-environments + Extract training data used to adapt bot program codes to new users and their setups. In summary, sharing a session recording is a fast and efficient way to answer many questions from people who want to help you. ### Getting the Session Recording Archive How do you get a session recording that you can share with others? By default, the BotLab client automatically creates that recording every time you run a bot. That means saving the session recording is already taken care of unless you chose to disable it for that session. (If you have set the `--detailed-session-recording` switch to `off` on a session, the recording will not be available for that session) To export a recording after running a bot, we use the `Devtools` in the BotLab client: ![Opening DevTools from the main menu](./image/2021-12-09-botlab-client-main-menu-enter-devtools.png) A button in the main menu brings us into the `Devtools` view: ![DevTools view in the botlab client](./image/2021-12-09-botlab-client-devtools-default.png) Here we see a link to a web page on the `localhost` domain. Clicking that link brings opens a web browser. The actual graphical user interface for the Devtools is on this web page. ![DevTools - choose a session to inspect](./image/2021-12-09-botlab-devtools-select-session.png) You find a list of recent play sessions on that web page, the last one at the top. When you run a bot, the BotLab client window also displays the session's name, so you can find it again in this list later, even if you started other sessions in the meantime. Clicking on one of the sessions' names brings us into the view of this particular session: ![DevTools - initial view of a session](./image/2021-12-09-botlab-devtools-session-summary.png) To export the session recording, use the `Download session recording archive` button. This gets you a zip archive that you can then share with other people. Now you can get help from other developers for your exact situation, no matter if the solution requires a change in program code or just different bot-settings. ### Inspecting a Session and Identifying the Time of Interest Besides the session archive, a developer might ask you at which time the bot should have behaved differently. The longer the session, the more likely you will be asked to clarify this. A precise way to communicate the time range of interest is to note the events indices for this range. Each action that a bot sends to a game client belongs to one event in the session timeline. In the session view, there is a timeline of events in that session. The events are numbered so that we can identify them; each has its index. A play session can easily contain thousands of events, and we want to find out what subsequence of events is related to the current problem or feature request. Clicking on an event in the timeline opens the details for this event. Here you can see what the game looked like at that time and what the bot did. The event details contain the complete bot's response to this event, including the inputs to send to a game client. ![DevTools - view of play session event details](./image/2021-12-09-botlab-devtools-session-event-details.png) Bot authors often use the status text to inform about what action the bot takes and how it decided to prefer this action. The bot generates a new status text for each event. The status texts for consecutive events can be very similar or even the same, especially if the bot was waiting for a process in the game to complete and did not take any action in the event. <file_sep># Elm Programming Language - Forward Pipe (`|>`) and Function Composition (`>>`) Operators When getting started with programming in Elm, reading the program code of typical real-world projects can be challenging. Two related language elements often confuse newcomers: + Forward pipe operator, written as `|>` + Forward function composition operator, written as `>>` To understand how they work, a good start is looking at their description in the official docs at https://package.elm-lang.org/packages/elm/core/latest/Basics# and https://elm-lang.org/docs/syntax#operators These operators don't do anything that we couldn't achieve with other language elements. They only allow us to write a function differently. We can rewrite any program without them. But, if these are not even strictly necessary, why do we even use them? The reason is that they can help improve the readability of the program code. Just like abbreviations in natural language, they act as shortcuts to consolidate common patterns in our code. An excellent way to learn how a language element works is to look at an alternative implementation that does the same without that unknown element. We will look at different program codes that all do the same—one version with the operator and one version without the operator. Suppose our program does some parsing, and we want to extract a substring from a string after the first comma character. This table of inputs and outputs illustrates the behavior we are looking for: | input | output | | ----------- | --------- | | `"a, b, c"` | `" b, c"` | | `"test"` | `""` | We can implement this function with the following syntax: ```Elm get_substring_after_first_comma : String -> String get_substring_after_first_comma originalString = String.join "," (List.drop 1 (String.split "," originalString)) ``` I am not going into the details of the functions we combine here. These are all part of the core library, and you can read more about them at https://package.elm-lang.org/packages/elm/core/latest/String and https://package.elm-lang.org/packages/elm/core/latest/List If we had a more complex function, the expression's code line would become longer. To counteract long lines, we could format the expression over multiple lines: ```Elm get_substring_after_first_comma : String -> String get_substring_after_first_comma originalString = String.join "," (List.drop 1 (String.split "," originalString) ) ``` ## `|>` Operator So far, so simple. But when you read actual projects code, you might see this function expressed using the forward pipe operator like this: ```Elm get_substring_after_first_comma : String -> String get_substring_after_first_comma originalString = originalString |> String.split "," |> List.drop 1 |> String.join "," ``` This way, we get rid of the parentheses and the indentation that grows with the number of processing steps. But another difference is more important in my opinion: The piped variant better visualizes the direction of data flow: The functions appear in the same order as we apply them to our data: First `String.split`, then `List.drop`, then `String.join`. ## `>>` Operator The `>>` operator lets us combine two functions into one, in this enables a more concise representation of our string processing function: ```Elm get_substring_after_first_comma : String -> String get_substring_after_first_comma = String.split "," >> List.drop 1 >> String.join "," ``` The function composition operator helps us to clarify that we use the argument only once. In cases where we use small functions inline, it saves us from writing a lambda expression. Here is an example from a current project: ```Elm getSubstringBetweenXmlTagsAfterMarker : String -> String -> Maybe String getSubstringBetweenXmlTagsAfterMarker marker xmlString = String.split marker xmlString |> List.drop 1 |> List.head |> Maybe.andThen (String.split ">" >> List.drop 1 >> List.head) |> Maybe.andThen (String.split "<" >> List.head) ``` And here is how we could write it without the `>>` operator: ```Elm getSubstringBetweenXmlTagsAfterMarker : String -> String -> Maybe String getSubstringBetweenXmlTagsAfterMarker marker xmlString = String.split marker xmlString |> List.drop 1 |> List.head |> Maybe.andThen (\s -> s |> String.split ">" |> List.drop 1 |> List.head) |> Maybe.andThen (\s -> s |> String.split "<" |> List.head) ``` For more guides on programming, see the overview at https://to.botlab.org/guide/overview <file_sep># 2020-07-31 - Learning How An App Works Its program code defines the behavior of a bot. No matter if you want to fix a bug or expand an app with a new feature, you need to make a change in the program code. But how do you know what to change and where? People who already have experience with the programming language can read the program code and then use that experience to simulate the program execution in their head. But that does not work if you are new to the programming language. Besides not know the rules of the language, there is another reason why reading the program code is an inefficient way to learn how a program works: The source code covers many different situations and, as a result, is relatively abstract. For example, the ordering in the program code is independent of the actual processing order at runtime. How do we find out in which order things happen and what are the roles of specific parts? To do this, we look at how the program execution happened in a specific scenario. We already have a way to see each event and the resulting response of the app. The next step is to look into the computations happening for a single event and see which parts of the program code contributed to what parts of the app's response. To use terms of the programming language: To illustrate the data flow, we could use a tree view that follows the data flow backward via the applications. Let's take this function as an example: https://github.com/Viir/bots/blob/5f711e9043bd20810578b1185a81ef5764d45e7c/implement/applications/eve-online/eve-online-combat-anomaly-bot/BotEngineApp.elm#L175-L197 This function expresses an application of `branchDependingOnDockedOrInSpace`. This application has a return value. I notice I am going too far when looking for a useful visualization of this case. At first, I was thinking of a complete variant that supports the inspection of everything everywhere. But I notice that I find it easier to think about a variant where we would only see inspection branches for applications of named functions. Even this limited version seems a vast improvement over today's state. I will continue with this simplified version for now. I think we can more fine-grained inspection support later. So `branchDependingOnDockedOrInSpace` is applied, or instantiated, which means we have arguments and a return value. Besides that, we want a way to see the program code that is responsible for this part. How do we make the connection between the value and the next instantiations? We can add an option to expand at the `branchDependingOnDockedOrInSpace` text in `anomalyBotDecisionRoot`. One of the branches to view here is the arguments given to `branchDependingOnDockedOrInSpace`. The arguments look different from the expression we see in `anomalyBotDecisionRoot`, because this expression contains applications that lead to more concrete values. We could use an approach more focusing on the return value: For every component, like a record field or an element in a tuple, we can add a branch to show the originating expression. More generally, for every value, offer to show the originating expression. To help with reading the parts that are program code, we could highlight the expressions used/forced at least once from those not evaluated/forced in the current scenario. Or we could collapse the ones which are not used by default. How could the visual tree look like starting at an application of `anomalyBotDecisionRoot` and expanding a few branches? + `anomalyBotDecisionRoot` + Arguments values + Return value + [Function code](https://github.com/Viir/bots/blob/5f711e9043bd20810578b1185a81ef5764d45e7c/implement/applications/eve-online/eve-online-combat-anomaly-bot/BotEngineApp.elm#L175-L197) + Evaluation + `branchDependingOnDockedOrInSpace` + Arguments values + Return value + [Function code](https://github.com/Viir/bots/blob/5f711e9043bd20810578b1185a81ef5764d45e7c/implement/applications/eve-online/eve-online-combat-anomaly-bot/EveOnline/AppFramework.elm#L1287-L1313) + Evaluation + `case readingFromGameClient.shipUI of` + Matching case `CanSee shipUI` + Arguments values + Return value + [Expression code](https://github.com/Viir/bots/blob/5f711e9043bd20810578b1185a81ef5764d45e7c/implement/applications/eve-online/eve-online-combat-anomaly-bot/EveOnline/AppFramework.elm#L1300-L1313) + Evaluation + `Maybe.withDefault` + Unused cases Can we simplify this further for a MVP? What else can we remove? <file_sep># 2019-09-26 Simplify Using Bots Currently, the [guide on how to use a bot](/guide/how-to-use-eve-online-bots.md) offers a version of the BotEngine console app which comes as many files bundled in a zip-archive. This archive also contains the `BotEngine.exe` file which is executed to start bots. The executable file then depends on and loads the other files. It would be nicer to have a single file instead, without the noise in the file system. This recent article from Microsoft about new developments in .NET core indicated this might be simple to implement now : https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#single-file-executables Today I explored using this new variant of `dotnet publish`, but it did not work yet. I filed this issue in the dotnet repository to get feedback from Microsoft: https://github.com/dotnet/cli/issues/12723 Below is whats posted in that issue: ---- > How can I use publishing of [single-file executables](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#single-file-executables)? > > I tried to follow the instructions from https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#single-file-executables, but this did not work: > > ## Steps to reproduce > > + Clone the repository from https://github.com/Viir/bots > + `publish` the .NET core app in this directory: https://github.com/Viir/bots/tree/82ef37f3089a3e40bd496f507b691a5c25011b33/implement/engine/BotEngine.Windows.Console , using the following command: > ```powershell > dotnet publish -r win10-x64 /p:PublishSingleFile=true > ``` > + Run the published app on the same machine, by entering the following command in powershell: `./botengine` > > The publish command produced following output in the console: > ```text > Microsoft (R) Build Engine version 16.3.0+0f4c62fea for .NET Core > Copyright (C) Microsoft Corporation. All rights reserved. > > Restore completed in 85,07 ms for K:\Source\Repos\bots\implement\engine\BotEngine.Windows.Console\BotEngine.Windows.Console.csproj. > BotEngine.Windows.Console -> K:\Source\Repos\bots\implement\engine\BotEngine.Windows.Console\bin\Debug\netcoreapp3.0\win10-x64\BotEngine.dll > BotEngine.Windows.Console -> K:\Source\Repos\bots\implement\engine\BotEngine.Windows.Console\bin\Debug\netcoreapp3.0\win10-x64\publish\ > ``` > > ## Expected behavior > > I expected the single-file executable app to behave the same way as when published without the `/p:PublishSingleFile=true` option. > When published without the `/p:PublishSingleFile=true` option, the apps output starts as follows: > ``` > Please specify a subcommand. > BotEngine console version 2019-09-01 > [...] > ``` > > ## Actual behavior > > When trying to start the app, it outputs the following message: > ```consoleoutput > Error: > An assembly specified in the application dependencies manifest (BotEngine.deps.json) was not found: > package: 'LibGit2Sharp.NativeBinaries', version: '2.0.267' > path: 'runtimes/win-x64/native/git2-572e4d8.pdb' > ``` > and then exits. > > ## Environment data > `dotnet --info` output: > ```console-output > .NET Core SDK (reflecting any global.json): > Version: 3.0.100 > Commit: 04339<PASSWORD> > > Runtime Environment: > OS Name: Windows > OS Version: 10.0.18362 > OS Platform: Windows > RID: win10-x64 > Base Path: C:\Program Files\dotnet\sdk\3.0.100\ > > Host (useful for support): > Version: 3.0.0 > Commit: <PASSWORD> > > .NET Core SDKs installed: > 1.0.0-preview4-004233 [C:\Program Files\dotnet\sdk] > 1.0.0-rc4-004771 [C:\Program Files\dotnet\sdk] > 1.0.4 [C:\Program Files\dotnet\sdk] > 1.1.0 [C:\Program Files\dotnet\sdk] > 2.0.0-preview2-006497 [C:\Program Files\dotnet\sdk] > 2.0.1-servicing-006957 [C:\Program Files\dotnet\sdk] > 2.1.4 [C:\Program Files\dotnet\sdk] > 2.1.103 [C:\Program Files\dotnet\sdk] > 2.1.201 [C:\Program Files\dotnet\sdk] > 2.1.202 [C:\Program Files\dotnet\sdk] > 2.1.300 [C:\Program Files\dotnet\sdk] > 2.1.403 [C:\Program Files\dotnet\sdk] > 2.1.500 [C:\Program Files\dotnet\sdk] > 2.1.502 [C:\Program Files\dotnet\sdk] > 2.1.503 [C:\Program Files\dotnet\sdk] > 2.1.504 [C:\Program Files\dotnet\sdk] > 2.1.505 [C:\Program Files\dotnet\sdk] > 2.1.602 [C:\Program Files\dotnet\sdk] > 2.1.604 [C:\Program Files\dotnet\sdk] > 2.1.700 [C:\Program Files\dotnet\sdk] > 2.1.701 [C:\Program Files\dotnet\sdk] > 2.2.101 [C:\Program Files\dotnet\sdk] > 2.2.104 [C:\Program Files\dotnet\sdk] > 2.2.202 [C:\Program Files\dotnet\sdk] > 2.2.204 [C:\Program Files\dotnet\sdk] > 2.2.300 [C:\Program Files\dotnet\sdk] > 2.2.301 [C:\Program Files\dotnet\sdk] > 3.0.100 [C:\Program Files\dotnet\sdk] > > .NET Core runtimes installed: > Microsoft.AspNetCore.All 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.1.7 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.1.8 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.1.9 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.2.2 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.2.3 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.2.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.All 2.2.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] > Microsoft.AspNetCore.App 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.1.7 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.1.8 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.1.9 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.2.2 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.2.3 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.2.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 2.2.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.AspNetCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] > Microsoft.NETCore.App 1.0.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 1.0.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 1.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 1.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 1.1.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.0.0-preview2-25407-01 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.0.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.0.2-servicing-25708-01 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.0.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.0.7 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.0.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.7 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.8 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.2.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.2.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.2.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 2.2.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.NETCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] > Microsoft.WindowsDesktop.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] > > To install additional .NET Core runtimes or SDKs: > https://aka.ms/dotnet-download > ``` ---- After reading more in the documentation, [we found a workaround](https://github.com/dotnet/cli/issues/12723#issuecomment-535624758): ---- > I added this to the `.csproj` file: https://github.com/Viir/bots/commit/30e7533d92bd2aa0cb03baffbfaa009d579b9b3a (https://github.com/Viir/bots/tree/adapt-for-single-file-exe-publish) > > I confirm this helps, at least the app seems to start normally. I did not find a problem with the apps behaviour when published from that version. > > Adding the `IncludeSymbolsInSingleFile` resulted in the executable file coming out around 7 MB larger (107.599 kB instead of 100.327 kB). Would be nice if would not need this workaround. ---- Another source of complexity in the the [guide on how to use a bot](/guide/how-to-use-eve-online-bots.md) is that it calls for the installation of .NET frameworks. To simplify this part, we can `publish` using the `--self-contained` option: ```powershell dotnet publish -r win10-x64 --self-contained true /p:PublishSingleFile=true ``` <file_sep># 2019-09-15 EVE Online Memory Reading Today I explored memory reading EVE Online. This is for advanced users who want to learn how the memory reading for EVE Online works and maybe customize it. To make this easier, I took the reference implementation and improved it. The original tutorial was published in 2016, and the memory reading was discussed in this thread: https://forum.botengine.org/t/advanced-do-it-yourself-memory-reading-in-eve-online/68 I used the implementation from there as a basis so the Python side of things might already look familiar to you. In contrast to the older code, today's version also supports reading from a file containing a sample of the client process. This new feature allows us to repeat the reading as often we want, without having to start an instance of the game client. In addition to that, another new feature lets you save the result of the memory reading to a JSON file for easy inspection and further processing. This JSON file contains the UI tree read from the EVE Online client. To use this feature, add the `--output` parameter when running the program. Below is an example of a full command-line; in this case, it reads the memory contents from a [file saved earlier](https://forum.botengine.org/t/how-to-collect-samples-for-memory-reading-development/50): ``` dotnet run -- --source="C:\path-to-a-process-sample-file.zip" --output="C:\path\to\directory\with\write\access" ``` So the result of today's exploration is a .NET console app which supports both from a live client process and a saved process. All the memory reading functions are inlined in the source code so that you don't have to look up DLL files or other assemblies to see the implementation. I added this program to the repository here: https://github.com/Viir/bots/commit/92410ac78c46957462431719f0c34781e2620da5 <file_sep>using System; namespace eve_online_memory_reading { public class SampleMemoryReader : IMemoryReader { readonly BotEngine.ProcessMeasurement sample; public MemoryReaderModuleInfo[] Modules() { throw new NotImplementedException(); } public SampleMemoryReader(BotEngine.ProcessMeasurement sample) { this.sample = sample; } public byte[] ReadBytes(Int64 address, int bytesCount) { foreach (var memoryBaseAddressAndListOctet in sample.MemoryBaseAddressAndListOctet) { var offsetInSampleRange = address - memoryBaseAddressAndListOctet.Key; if (offsetInSampleRange < 0 || memoryBaseAddressAndListOctet.Value.Length <= offsetInSampleRange) continue; var bytes = new byte[Math.Min(bytesCount, memoryBaseAddressAndListOctet.Value.Length - offsetInSampleRange)]; Array.Copy(memoryBaseAddressAndListOctet.Value, offsetInSampleRange, bytes, 0, bytes.Length); return bytes; } return null; } } } <file_sep># EVE Online Mining Bot For this guide, I picked a mining bot optimal for beginners, which means easy to set up and use. After several iterations in development, this bot has matured to be robust regarding interruptions and changes in the game environment. Maybe you have seen some bots or 'macros' which follow a fixed sequence of actions to perform an in-game task. The bot we will use here does not just follow a rigid series of steps but frequently looks at the current state of the game to decide the next action. This also means it can detect if it failed to perform a particular subtask, (for example, warping to the mining site) and try again. So it also does not matter if your ship is docked or in space when you start the bot. Before going into the setup, a quick overview of this bot and what it does: + When the mining hold is not full, warps to an asteroid belt. + Uses drones to defend against rats if available. + Mines from asteroids. + When the mining hold is full, warps and docks to a station or structure to unload the ore into the item hangar. (It remembers the station in which it was last docked, and docks again at the same station.) + Runs away if shield hitpoints drop too low (The default threshold is 70%). + Displays statistics such as the total volume of unloaded ore, so that you can easily track performance. + Closes message boxes that could pop up sometimes during gameplay. ## Setting up the Game Client Despite being quite robust, this mining bot is far from being as smart as a human. For example, its perception is more limited than ours, so we need to set up the game to make sure that the bot can see everything it needs to. Following is the list of setup instructions for the EVE Online client: + Set the UI language to English. + In the ship UI in the 'Options' menu, tick the checkbox for 'Display Module Tooltips'. + In Overview window, make asteroids visible. + Set the Overview window to sort objects in space by distance with the nearest entry at the top. + Open one inventory window. + If you want to use drones for defense against rats, place them in the drone bay, and open the 'Drones' window. ## Starting the Mining Bot If the BotLab client is not already installed on your machine, follow the guide at <https://to.botlab.org/guide/how-to-install-the-botlab-client> The BotLab client is a tool for developing bots and also makes running bots easier with graphical user interfaces for configuration. In the BotLab client, load the bot by entering the following link in the 'Select Bot' view: <https://catalog.botlab.org/ad09c9ace1e216cf> There is a detailed walkthrough video on how to load and run a bot at <https://to.botlab.org/guide/video/how-to-run-a-bot-live> The bot needs a few seconds to start and find the EVE Online client process. It also shows status messages to inform what it is doing at the moment and when the startup is complete. ![EVE Online Bot Starting](./image/2023-03-08-botlab-gui-eve-online-bot-startup.png) From here on, the bot works automatically. It detects the topmost game client window and starts working in that game client. In case the bot does not work as expected, the first place to look is in the status message of the bot. Depending on what the bot is seeing and doing at the moment, it can display many different status messages. For example, if you disable the location ('System info') info panel in the EVE Online client, the bot displays the following message: > I cannot see the location info panel. As soon as you enable this info panel again, the bot will also continue working. The bot repeats the cycle of mining and unloading until you tell it to pause (`SHIFT` + `CTRL` + `ALT` keys) or stop it. To give an overview of the performance of the bot, it displays statistics like this: > Session performance: times unloaded: 13, volume unloaded / m³: 351706 ## Configuration Settings All settings are optional; you only need them in case the defaults don't fit your use-case. + `unload-station-name` : Name of a station to dock to when the mining hold is full. + `unload-structure-name` : Name of a structure to dock to when the mining hold is full. + `activate-module-always` : Text found in tooltips of ship modules that should always be active. For example: "shield hardener". + `hide-when-neutral-in-local` : Should we hide when a neutral or hostile pilot appears in the local chat? The only supported values are `no` and `yes`. + `unload-fleet-hangar-percent` : This will make the bot to unload the mining hold at least XX percent full to the fleet hangar, you must be in a fleet with an orca or a rorqual and the fleet hangar must be visible within the inventory window. + `dock-when-without-drones` : This will make the bot dock when it's out of drones. The only supported values are `no` and `yes`. + `repair-before-undocking` : Repair the ship at the station before undocking. The only supported values are `no` and `yes`. When using more than one setting, start a new line for each setting in the text input field. Here is an example of a complete settings string: ``` unload-station-name = Noghere VII - Moon 15 activate-module-always = shield hardener activate-module-always = afterburner ``` ## Running Multiple Instances This bot supports running multiple instances on the same desktop. In such a scenario, the individual bot instances take turns sending input and coordinate to avoid interfering with each other's input. To learn more about multi-instance setup, see <https://to.botlab.org/guide/running-bots-on-multiple-game-clients> ---- If you want to learn how this bot or other apps for EVE Online are developed, have a look at the directory of development guides at <https://to.botlab.org/guide/overview> In case I forgot to add something here or you have any questions, don't hesitate to ask on the [BotLab forum](https://forum.botlab.org/). <file_sep>using System; using System.Linq; namespace web_browser_csharp; class Program { static PuppeteerSharp.Browser browser; static PuppeteerSharp.Page browserPage; static Action<string> callbackFromBrowserDelegate; static string UserDataDirPath(string userProfileId) => System.IO.Path.Combine( Environment.GetEnvironmentVariable("LOCALAPPDATA"), "bot", "web-browser", "user-profile", userProfileId, "user-data"); static string BrowserDownloadDirPath() => System.IO.Path.Combine( Environment.GetEnvironmentVariable("LOCALAPPDATA"), "bot", "web-browser", "download"); static void Main(string[] args) { /* 2020-02-17 Observation before introducing the killing of previous web browser processes: LaunchAsync failed if a process from the last run was still present. (See report of this issue at https://forum.botlab.org/t/farm-manager-tribal-wars-2-farmbot/3038/32?u=viir) Unhandled exception. System.AggregateException: One or more errors occurred. (Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5) [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_000 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -2 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process. ) ---> PuppeteerSharp.ChromiumProcessException: Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5) [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_000 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -2 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process. at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p) at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p) at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) */ KillPreviousWebBrowserProcesses(); StartWebBrowser().Wait(); } static void KillPreviousWebBrowserProcesses() { var matchingProcesses = System.Diagnostics.Process.GetProcesses() /* 2020-02-17 .Where(process => process.StartInfo.Arguments.Contains(UserDataDirPath(), StringComparison.InvariantCultureIgnoreCase)) */ .Where(ProcessIsWebBrowser) .ToList(); foreach (var process in matchingProcesses) { if (process.HasExited) continue; process.Kill(); } } static bool ProcessIsWebBrowser(System.Diagnostics.Process process) { try { return process.MainModule.FileName.Contains(".local-chromium"); } catch { return false; } } static async System.Threading.Tasks.Task StartWebBrowser() { var browserRevision = PuppeteerSharp.BrowserFetcher.DefaultChromiumRevision; var browserFetcher = new PuppeteerSharp.BrowserFetcher(new PuppeteerSharp.BrowserFetcherOptions { Path = BrowserDownloadDirPath() }); await browserFetcher.DownloadAsync(browserRevision); browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions { Headless = false, UserDataDir = UserDataDirPath("default"), DefaultViewport = null, ExecutablePath = browserFetcher.RevisionInfo(browserRevision).ExecutablePath, }); browserPage = (await browser.PagesAsync()).FirstOrDefault() ?? await browser.NewPageAsync(); await browserPage.ExposeFunctionAsync("____callback____", (string returnValue) => { callbackFromBrowserDelegate?.Invoke(returnValue); return 0; }); } } <file_sep>using System.Linq; namespace eve_online_memory_reading { static public class EveOnline { /// <summary> /// returns the root of the UI tree. /// </summary> /// <param name="MemoryReader"></param> /// <returns></returns> static public UITreeNode UITreeRoot( IPythonMemoryReader MemoryReader) { var candidateAddresses = PyTypeObject.EnumeratePossibleAddressesOfInstancesOfPythonTypeFilteredByObType(MemoryReader, "UIRoot"); // return the candidate tree with the largest number of nodes. return candidateAddresses .Select(candidateAddress => new UITreeNode(candidateAddress, MemoryReader)) .OrderByDescending(candidate => candidate.EnumerateChildrenTransitive(MemoryReader)?.Count()) .FirstOrDefault(); } } }
8419780f0a6731dd6d4254f24b3867a74fe058bf
[ "Markdown", "C#" ]
53
Markdown
Viir/bots
fb6378ce666eb86a73bdbd270da306721fec7042
8b844e9694f2ac348a0e514a0900558617f9d939
refs/heads/master
<repo_name>Air6n6/Recommendation<file_sep>/client/src/Favorites.jsx import React from 'react'; import styled from 'styled-components'; const Wrapper = styled.div` position: relative; background-color: white; width: 400px; height: 500px; z-index: 3; border: 1px solid grey; ` const Exit = styled.button` ` const Container = styled.div` text-align: center; ` const Instructions = styled.p` ` const Facebook = styled.button` background-color: blue; color: white; ` const Google = styled.button` background-color: red; color: white; ` function Favorites (props){ return ( <Wrapper> <Exit onClick={()=> props.handlePopup(false)}>X</Exit> <Container> <Instructions>Save to list</Instructions> <Facebook onClick={() =>window.location.href = 'https://facebook.com'}><img></img>Continue with Facebook</Facebook> <br></br> <Google onClick={() =>window.location.href = 'https://accounts.google.com/servicelogin/signinchooser?flowName=GlifWebSignIn&flowEntry=ServiceLogin'}><img></img>Continue with Google</Google> <span><Line1></Line1><span><Or>Or</Or></span><Line2></Line2></span> <SignUp><img></img>Sign up with Email</SignUp> <SignInText> Already have an Airbnb account? </SignInText> <SignIn onClick={() =>window.location.href = 'https://www.airbnb.com/login'}>Sign In</SignIn> </Container> </Wrapper> ); } export default Favorites;<file_sep>/database/seed.js const db = require('./index.js'); const faker = require('faker'); const homeGenerator = () => { var homeByCity = (city, state, country) => { for (var i = 0; i < 10; i++) { let listing = [faker.lorem.word(), faker.lorem.words(5), faker.commerce.price(), faker.random.number(), faker.finance.amount(0,5,2), city, state, country, faker.image.imageUrl()]; db.query(`insert into listings (homeType, title, price, reviewCount, rating, cityName, stateName, country, picture) values(?,?,?,?,?,?,?,?,?);`, listing, (err, results) => { if (err) { console.log(err, "could not add to homes table") } else { console.log('home added') } }); } } homeByCity("Boston", "MA", "US"); homeByCity("Cupertino", "CA", "US"); homeByCity("Miami", "FL", "US"); homeByCity("Denver", "CO", "US"); homeByCity("San Francisco", "CA", "US"); homeByCity("Honolulu", "HI", "US"); homeByCity("Seattle", "WA", "US"); homeByCity("San Jose", "CA", "US"); homeByCity("New York", "NY", "US"); homeByCity("Los Angeles", "CA", "US") }; homeGenerator()<file_sep>/schema.sql DROP DATABASE IF EXISTS recommendations; CREATE DATABASE recommendations; USE recommendations; CREATE TABLE pictures (id int NOT NULL auto_increment, url varchar(500), primary key (id)); -- CREATE TABLE cities ( -- id int NOT NULL auto_increment, -- cityName varchar(100), -- stateName varchar(50), -- country varchar(100), -- primary key (id) -- ); -- CREATE TABLE pictures_homes -- CREATE TABLE users ( -- id int NOT NULL auto_increment, -- userName varchar(100), -- primary key (id)); CREATE TABLE listings ( id int NOT NULL auto_increment, homeType varchar(100), title varchar(100), price decimal(5,2), reviewCount varchar(20), rating decimal(3,2), cityName varchar(100), stateName varchar(50), country varchar(100), picture varchar(300), primary key (id)); <file_sep>/server/index.js const express = require('express'); const path = require('path'); const controller = require('../database/dbMethods.js'); const cors = require('cors'); const app = express(); const port = 5500; const bodyParser = require("body-parser"); const compression = require('compression'); app.use(bodyParser.json()) app.use(cors()); app.use('/', express.static(path.join(__dirname, '../client/dist'))) // app.use('/air6n6/*/listing', express.static(path.join(__dirname, '/../client/dist'))) app.use(compression()); app.listen(port, () => console.log(`Example app listening on port ${port}!`)) app.get("/allHomes", (req,res) => { controller.getAllFromHomes((err,dbObj)=> { if (err) { console.log('error from index.js SERVER******') res.status(500).send(err); } else { console.log('SENT All') res.status(200).send(dbObj); } }) }) 
29fe9283bab814d2258cc0ed1e1b1b7ebe89e599
[ "JavaScript", "SQL" ]
4
JavaScript
Air6n6/Recommendation
9f377be9dc3806b938fbb261993ce75eb66cfc66
7311129a978f91beeb788118c9ebd6a7be887fe8
refs/heads/master
<repo_name>tillkuhn/kotlin-angular<file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/DishController.kt package net.timafe.angkor.rest import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.Dish import net.timafe.angkor.repo.DishRepository import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import java.security.Principal @RestController @RequestMapping(Constants.API_DEFAULT_VERSION + "/dishes") class DishController { @Autowired private lateinit var dishRepository: DishRepository private val log: Logger = LoggerFactory.getLogger(this.javaClass) @GetMapping @ResponseStatus(HttpStatus.OK) fun allDishes(principal: Principal?): List<Dish> { // val dishes = if (principal != null) placeRepository.findByOrderByName() else placeRepository.findPublicPlaces() val dishes = dishRepository.findAll() // coo ${places.get(0).coordinates}" log.info("allDishes() return ${dishes.size} dishes principal=${principal}") return dishes } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/MetricsController.kt package net.timafe.angkor.rest import com.fasterxml.jackson.databind.ObjectMapper import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.dto.MetricDTO import org.slf4j.LoggerFactory import org.springframework.boot.actuate.metrics.MetricsEndpoint import org.springframework.http.HttpStatus import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping(Constants.API_DEFAULT_VERSION + "/admin") /** * https://stackoverflow.com/questions/32382349/how-to-get-metrics-from-spring-boot-actuator-programmatically */ class MetricsController(private val metrics: MetricsEndpoint, private val objectMapper: ObjectMapper) { private val log = LoggerFactory.getLogger(javaClass) // @PreAuthorize(Constants.ADMIN_AUTHORITY) @GetMapping("/metrics") @ResponseStatus(HttpStatus.OK) fun metrics(): List<MetricDTO> { val meli = mutableListOf<MetricDTO>() metrics.listNames().names.forEach{ // example it: tomcat.sessions.active.current val resp: MetricsEndpoint.MetricResponse = metrics.metric(it,null) log.trace(objectMapper.writeValueAsString(resp)) val metricDTO = MetricDTO(resp.name,resp.description,resp.measurements.get(0).value,resp.baseUnit) meli.add(metricDTO) } return meli } } <file_sep>/.github/ISSUE_TEMPLATE/feature_angular.md --- name: New Angular Feature about: Add an UI feature to help us improve title: '' labels: '' assignees: '' --- **Feature** A clear and concise description of what the bug is. **URL References** <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/dto/PlaceSummary.kt package net.timafe.angkor.domain.dto import net.timafe.angkor.domain.Mappable import net.timafe.angkor.domain.Taggable import net.timafe.angkor.domain.enums.LocationType import java.util.* data class PlaceSummary( var id: UUID, var name: String, var summary: String?, var areaCode: String, var primaryUrl: String?, var locationType: LocationType = LocationType.PLACE, // coordinates should be List<Double>? but this didn't work with JPA SELECT NEW query // (see PlaceRepository) which raises // Expected arguments are: java.util.UUID, java.lang.String, java.lang.Object // var coordinates: java.lang.Object? = null override var coordinates: List<Double> = listOf(), override var tags: List<String> = listOf() ) : Mappable, Taggable { // Satisfy entity query in PlaceRepository which cannot cast coorindates arg constructor(id: UUID, name: String, summary: String, areaCode: String, primaryUrl: String?, locationType: LocationType, coordinates: Any) : this(id, name, summary, areaCode, primaryUrl, locationType, coordinates as List<Double>, listOf()) } <file_sep>/ui/src/app/places/places.component.ts import {Component, OnInit} from '@angular/core'; import {ApiService} from '../shared/api.service'; import {EnvironmentService} from '../environment.service'; import {NGXLogger} from 'ngx-logger'; import {MasterDataService} from '../shared/master-data.service'; import {ListItem} from '../domain/shared'; import {Place} from '../domain/place'; @Component({ selector: 'app-places', templateUrl: './places.component.html', styleUrls: ['./places.component.scss'] }) export class PlacesComponent implements OnInit { // icon should match https://material.io/resources/icons/ displayedColumns: string[] = ['areaCode', 'locationType', 'name', 'coordinates']; data: Place[] = []; constructor(private api: ApiService, private env: EnvironmentService, private logger: NGXLogger, private masterData: MasterDataService) { } getSelectedLotype(row: Place): ListItem { return this.masterData.lookupLocationType(row.locationType); } ngOnInit() { this.api.getPlaces() .subscribe((res: any) => { this.data = res; this.logger.debug('getPlaces()', this.data.length); }, err => { this.logger.error(err); }); } // https://www.google.com/maps/@51.4424832,6.9861376,13z // Google format is **LAT**itude followed by **LON**ngitude and Z (altitude? data grid? we don't know and don't need) getGoogleLink(place: Place) { if (place.coordinates && place.coordinates.length > 1) { return 'https://www.google.com/maps/search/?api=1&query=' + place.coordinates[1] + ',' + place.coordinates[0]; } else { return 'no loca, chica'; } } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/config/Constants.kt package net.timafe.angkor.config object Constants { const val API_ROOT = "/api" const val API_SECURE = API_ROOT + "/secure" const val API_DEFAULT_VERSION = API_ROOT + "/v1" const val PROFILE_CLEAN = "clean" const val PROFILE_PROD = "prod" const val PROFILE_TEST = "test" const val PROFILE_OFFLINE = "offline" const val JACKSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss" /* should be "2019-11-08T07:08:45.134Z" */ const val USER_ANONYMOUS = "anonymous" const val LOGIN_REGEX: String = "^[_.@A-Za-z0-9-]*\$" const val ADMIN_AUTHORITY = "hasAuthority('ROLE_ADMIN')" const val USER_AUTHORITY = "hasAuthority('ROLE_USER')" } <file_sep>/api/src/main/resources/db/migration/README.md ### drop all ``` drop table place; drop table region; drop table flyway_schema_history; ``` ### add colums ``` ALTER TABLE place ADD COLUMN IF NOT EXISTS coordinates double precision[]; ``` <file_sep>/ui/src/app/place-detail/place-detail.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {PlaceDetailComponent} from './place-detail.component'; import {LoggerTestingModule} from 'ngx-logger/testing'; import {RouterTestingModule} from '@angular/router/testing'; import {HttpClientTestingModule} from '@angular/common/http/testing'; import {MomentModule} from 'ngx-moment'; import {MatDialogModule} from '@angular/material/dialog'; import {MatSnackBarModule} from '@angular/material/snack-bar'; describe('PlaceDetailComponent', () => { let component: PlaceDetailComponent; let fixture: ComponentFixture<PlaceDetailComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [PlaceDetailComponent], imports: [RouterTestingModule, LoggerTestingModule, HttpClientTestingModule, MomentModule, MatDialogModule, MatSnackBarModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PlaceDetailComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/api/src/main/kotlin/net/timafe/angkor/service/AuthService.kt package net.timafe.angkor.service import com.fasterxml.jackson.databind.ObjectMapper import com.sun.el.parser.AstMapEntry import net.minidev.json.JSONArray import net.timafe.angkor.domain.Authority import net.timafe.angkor.domain.User import net.timafe.angkor.domain.dto.UserDTO import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.context.annotation.Bean import org.springframework.security.authentication.AbstractAuthenticationToken import org.springframework.security.authentication.AnonymousAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority import org.springframework.stereotype.Service @Service class AuthService(private val mapper: ObjectMapper) { private val log: Logger = LoggerFactory.getLogger(this.javaClass) fun isAnonymous(): Boolean { val auth: Authentication = SecurityContextHolder.getContext().authentication; // anonymous: org.springframework.security.authentication.AnonymousAuthenticationToken@b7d78d14: // Principal: anonymousUser; // logged in: org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken@9b65b523: // Principal: Name: [Facebook_145501.....], Granted Authorities: [[ROLE_USER, SCOPE_openid]], return auth is AnonymousAuthenticationToken } /** * Returns the user from an OAuth 2.0 login or resource server with JWT. * Synchronizes the user in the local repository. * * @param authToken the authentication token. * @return the user from the authentication. */ fun getUserFromAuthentication(authToken: AbstractAuthenticationToken): UserDTO { val attributes: Map<String, Any> = when (authToken) { is OAuth2AuthenticationToken -> authToken.principal.attributes // is JwtAuthenticationToken -> authToken.tokenAttributes else -> throw IllegalArgumentException("AuthenticationToken is not OAuth2") } val user = getUser(attributes) // log.info(mapper.writeValueAsString(attributes)) user.authorities = authToken.authorities.asSequence() .map(GrantedAuthority::getAuthority) .map { Authority(name = it).name } .toMutableSet() return user; } /** * Map authorities from "groups" or "roles" claim in ID Token. * * @return a [GrantedAuthoritiesMapper] that maps groups from * the IdP to Spring Security Authorities. */ @Bean fun userAuthoritiesMapper() = GrantedAuthoritiesMapper { authorities -> val mappedAuthorities = mutableSetOf<GrantedAuthority>() authorities.forEach { authority -> if (authority is OidcUserAuthority) { val grantedList = extractAuthorityFromClaims(authority.idToken.claims) mappedAuthorities.addAll(grantedList) } } mappedAuthorities } fun extractAuthorityFromClaims(claims: Map<String, Any>): List<GrantedAuthority> { return mapRolesToGrantedAuthorities(getRolesFromClaims(claims)) } // take a list of simple names role strings, and map it into a list of GrantedAuthority objects if pattern machtes fun mapRolesToGrantedAuthorities(roles: Collection<String>): List<GrantedAuthority> { return roles .filter { it.startsWith("ROLE_") } .map { SimpleGrantedAuthority(it) } } @Suppress("UNCHECKED_CAST") fun getRolesFromClaims(claims: Map<String, Any>): Collection<String> { // Cognito groups gibts auch noch ... return if (claims.containsKey("cognito:roles")) { when (val coros = claims.get("cognito:roles")) { is JSONArray -> extractRolesFromJSONArray(coros) else -> listOf<String>() } } else { listOf<String>() } } // roles look like arn:aws:iam::06*******:role/angkor-cognito-role-guest // so we just take the last part after cognito-role- fun extractRolesFromJSONArray(jsonArray: JSONArray): List<String> { val iamRolePattern = "cognito-role-" return jsonArray .filter { it.toString().contains(iamRolePattern) } .map { "ROLE_" + it.toString().substring(it.toString().indexOf(iamRolePattern) + iamRolePattern.length).toUpperCase() } } companion object { @JvmStatic private fun getUser(details: Map<String, Any>): UserDTO { val user = UserDTO() // handle resource server JWT, where sub claim is email and uid is ID if (details["uid"] != null) { user.id = details["uid"] as String user.login = details["sub"] as String } else { user.id = details["sub"] as String } if (details["preferred_username"] != null) { user.login = (details["preferred_username"] as String).toLowerCase() } else if (user.login == null) { user.login = user.id } if (details["given_name"] != null) { user.firstName = details["given_name"] as String } if (details["family_name"] != null) { user.lastName = details["family_name"] as String } if (details["name"] != null) { user.name = details["name"] as String } if (details["email_verified"] != null) { user.activated = details["email_verified"] as Boolean } if (details["email"] != null) { user.email = (details["email"] as String).toLowerCase() } else { user.email = details["sub"] as String } if (details["picture"] != null) { user.imageUrl = details["picture"] as String } user.activated = true return user } } } <file_sep>/infra/templates/deploy.sh #!/usr/bin/env bash # variables in this file are substitued by terraform templates # so you need to use double dollar signs ($$) to escape variables SCRIPT=$(basename $${BASH_SOURCE[0]}) logit() { printf "%(%Y-%m-%d %T)T %s\n" -1 "$1" } if [ $# -lt 1 ]; then set -- help # display help if called w/o args fi # common start export WORKDIR=$(dirname $${BASH_SOURCE[0]}) mkdir -p $${WORKDIR}/docs $${WORKDIR}/logs $${WORKDIR}/backup # pull file artifacts needed for all targets from s3 if [[ "$*" == *update* ]] || [[ "$*" == *all* ]]; then logit "Updating docker-compose and script artifacts including myself" aws s3 cp s3://${bucket_name}/deploy/$${SCRIPT} $${WORKDIR}/$${SCRIPT} # update myself aws s3 cp s3://${bucket_name}/deploy/docker-compose.yml $${WORKDIR}/docker-compose.yml chmod ugo+x $${WORKDIR}/$${SCRIPT} fi # init cron daily jobs if [[ "$*" == *init-cron* ]] || [[ "$*" == *all* ]]; then logit "Setting up scheduled tasks in /etc/cron.daily" sudo bash -c "cat >/etc/cron.daily/renew-cert" <<-'EOF' /home/ec2-user/deploy.sh renew-cert >>/home/ec2-user/logs/renew-cert.log 2>&1 EOF sudo chmod 755 /etc/cron.daily/renew-cert sudo bash -c "cat >/etc/cron.daily/backup-db" <<-'EOF' /home/ec2-user/deploy.sh backup-db >>/home/ec2-user/logs/backup-db.log 2>&1 EOF sudo bash -c "cat >/etc/cron.daily/docker-prune" <<-'EOF' docker system prune -f >>/home/ec2-user/logs/docker-prune.log 2>&1 EOF for SCRIPT in backup-db renew-cert docker-prune; do sudo chmod 755 /etc/cron.daily/$${SCRIPT}; done fi # regular database backups if [[ "$*" == *backup-db* ]]; then logit "Backup PostgresDB, to be implemented" fi # cerbot renew if [[ "$*" == *renew-cert* ]] || [[ "$*" == *all* ]]; then logit "Deploy and renew SSL Certificates" CERTBOT_ADD_ARGS="" # use --dry-run to simulate cerbot interaction if docker ps --no-trunc -f name=^/${appid}-ui$ |grep -q ${appid}; then echo ${appid}-ui is up, adding tempory shut down hook for cerbot renew set -x sudo --preserve-env=WORKDIR certbot --standalone -m ${certbot_mail} --agree-tos --expand --redirect -n ${certbot_domain_str} \ --pre-hook "docker-compose --no-ansi --file $${WORKDIR}/docker-compose.yml stop ${appid}-ui" \ --post-hook "docker-compose --no-ansi --file $${WORKDIR}/docker-compose.yml start ${appid}-ui" \ $${CERTBOT_ADD_ARGS} certonly set +x else echo ${appid}-ui is down or not yet installed, cerbot can take safely over port 80 sudo --preserve-env=WORKDIR certbot --standalone -m ${certbot_mail} --agree-tos --expand --redirect -n ${certbot_domain_str} $${CERTBOT_ADD_ARGS} certonly fi # if files relevant to letsencrypt changed, trigger backup update if sudo find /etc/letsencrypt/ -type f -mtime -1 |grep -q "."; then logit "Files in /etc/letsencrypt changes, trigger backup" sudo tar -C /etc -zcf /tmp/letsencrypt.tar.gz letsencrypt sudo aws s3 cp --sse=AES256 /tmp/letsencrypt.tar.gz s3://${bucket_name}/backup/letsencrypt.tar.gz sudo rm -f /tmp/letsencrypt.tar.gz else logit "Files in /etc/letsencrypt are unchanged, skip backup" fi fi # python or golang webhook if [[ "$*" == *webhook* ]] || [[ "$*" == *all* ]]; then logit "Deploying webhook" aws s3 cp s3://${bucket_name}/deploy/captain-hook.py $${WORKDIR}/captain-hook.py chmod ugo+x $${WORKDIR}/captain-hook.py fi # antora docs if [[ "$*" == *docs* ]] || [[ "$*" == *all* ]]; then logit "Deploying Antora docs" set -x aws s3 sync --delete s3://${bucket_name}/deploy/docs $${WORKDIR}/docs/ set +x fi # api deployment if [[ "$*" == *api* ]] || [[ "$*" == *all* ]]; then logit "Deploying API Backend" # pull recent docker images from dockerhub docker pull ${docker_user}/${appid}-api:${api_version} docker-compose --file $${WORKDIR}/docker-compose.yml up --detach ${appid}-api fi if [[ "$*" == *ui* ]] || [[ "$*" == *all* ]]; then logit "Deploying UI Frontend" docker pull ${docker_user}/${appid}-ui:${ui_version} docker-compose --file $${WORKDIR}/docker-compose.yml up --detach ${appid}-ui fi ## if target required docker-compose interaction, show processes if [[ "$*" == *ui* ]] || [[ "$*" == *api* ]] || [[ "$*" == *all* ]]; then docker ps fi ## display usage if [[ "$*" == *help* ]]; then echo "Usage: $SCRIPT [target]" echo echo "Targets:" echo " all Runs all targets" echo " ui Deploys Angular UI" echo " api Deploys Spring Boot API" echo " docs Deploys Antora Docs" echo " webhook Deploys Python Webhook" echo " update Update myself and docker-compose config" echo " renew-cert Deploys and renews SSL certificate" echo " init-cron Init Cronjobs" echo " backup-db Backup Database" echo " help This help" echo fi <file_sep>/Makefile # Inspired by https://github.com/pgporada/terraform-makefile # quickref: https://www.gnu.org/software/make/manual/html_node/Quick-Reference.html .DEFAULT_GOAL := help # default target when launched without arguments .ONESHELL: .SHELL := /usr/bin/bash .PHONY: ec2-start ec2-stop ec2-status ssh infra-init infra-plan infra-apply api-deploy ui-deploy help .SILENT: ec2-status help ## no preceding @s needed .EXPORT_ALL_VARIABLES: AWS_PROFILE = timafe ENV_FILE ?= .env AWS_CMD ?= aws SSH_OPTIONS ?= -o StrictHostKeyChecking=no # https://unix.stackexchange.com/questions/269077/tput-setaf-color-table-how-to-determine-color-codes BOLD=$(shell tput bold) RED=$(shell tput setaf 1) GREEN=$(shell tput setaf 2) YELLOW=$(shell tput setaf 3) CYAN=$(shell tput setaf 6) RESET=$(shell tput sgr0) STARTED=$(shell date +%s) ############################ # self documenting makefile recipe: https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html ############################ help: for PFX in api ui infra ec2 docs all ang; do \ grep -E "^$$PFX[0-9a-zA-Z_-]+:.*?## .*$$" $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-20s\033[0m %s\n", $$1, $$2}'; echo "";\ done ############################ # infra tasks for terraform ############################ infra-init: ## Runs terraform init on working directory ./infra, switch to cd infra; test -f .terraform-version && hash tfswitch 2>/dev/null && tfswitch; terraform init @echo "🏗️ $(GREEN)Terraform successfully initialized $(RESET)[$$(($$(date +%s)-$(STARTED)))s] " infra-plan: infra-init ## Runs terraform plan with implicit init and fmt (alias: plan) cd infra; terraform fmt; terraform validate; terraform plan @echo "🏗️ $(GREEN)Infrastructure succcessfully planned $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" infra-deploy: infra-init ## Runs terraform apply with auto-approval (alias: apply) cd infra; terraform apply --auto-approve @echo "🏗️ $(GREEN)Terraform Infrastructure succcessfully deployed $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" # terraform aliases apply: infra-deploy plan: infra-plan ############################## # api backend tasks for gradle ############################## api-clean: ## Cleans up ./api/build folder rm -rf api/build api-build: ## Assembles backend jar in ./api/build with gradle (alias: assemble) cd api; gradle assemble @echo "🌇 $(GREEN) Successfully build API jar $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" api-test: ## Runs spring boot unit and integration tests in ./api cd api; gradle test --fail-fast --stacktrace @echo "🌇 $(GREEN) API Tests finished $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" api-run: ## Runs springBoot API in ./api using gradle bootRun (alias: bootrun) cd api; gradle bootRun @# gradle bootRun --args='--spring.profiles.active=dev' # Check resulting image with docker run -it --entrypoint bash angkor-api:latest # Deprecated, now handled by Github CI Actions _api-dockerize: .docker_checkrunning api-build ## Builds API docker images on top of recent opdenjdk cd api; docker build --build-arg FROM_TAG=jre-14.0.1_7-alpine \ --build-arg LATEST_REPO_TAG=$(shell git describe --abbrev=0) --tag angkor-api:latest . @# docker tag angkor-api:latest angkor-api:$(shell git describe --abbrev=0) # optional # # Deprecated, now handled by Github CI Actions _api-push: api-dockerize .docker_login ## Build and tags API docker image, and pushes to dockerhub docker tag angkor-api:latest $(shell grep "^docker_user" $(ENV_FILE) |cut -d= -f2-)/angkor-api:latest docker push $(shell grep "^docker_user" $(ENV_FILE) |cut -d= -f2-)/angkor-api:latest @echo "🐳 $(GREEN)Pushed API image to dockerhub, seconds elapsed $(RESET)[$$(($$(date +%s)-$(STARTED)))s] " api-deploy: ec2-deploy ## Deploys API with subsequent pull and restart of server on EC2 # backend aliases bootrun: api-run assemble: api-build ########################### # frontend tasks yarn / ng ########################### ui-clean: ## Remove UI dist folder ./ui/dist rm -rf ui/dist ui-build: ## Run ng build in ./ui cd ui; ng build @echo "🌇 $(GREEN) Successfully build UI $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" ui-build-prod: ## Run ng build --prod in ./ui cd ui; ng build --prod @echo "🌇 $(GREEN) Successfully build prod optimized UI $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" ui-test: ## Runs chromeHeadless tests in ./ui cd ui; ng test --browsers ChromeHeadless --watch=false @echo "🌇 $(GREEN) UI Tests finished $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" ui-run: ## Run UI with ng serve and opens UI in browser (alias: serve,open,ui) cd ui; ng serve --open # Deprecated, now handled by Github CI Actions _ui-dockerize: .docker_checkrunning ui-build-prod ## Creates UI docker image based on nginx cd ui; docker build --build-arg FROM_TAG=1-alpine \ --build-arg LATEST_REPO_TAG=$(shell git describe --abbrev=0) --tag angkor-ui:latest . # docker tag angkor-api:latest angkor-ui:$(shell git describe --abbrev=0) #optional # Check resulting image with docker run -it --entrypoint ash angkor-ui:latest # Deprecated, now handled by Github CI Actions _ui-push: ui-dockerize .docker_login ## Creates UI docker frontend image and deploys to dockerhub docker tag angkor-ui:latest $(shell grep "^docker_user" $(ENV_FILE) |cut -d= -f2-)/angkor-ui:latest docker push $(shell grep "^docker_user" $(ENV_FILE) |cut -d= -f2-)/angkor-ui:latest @echo "🐳 $(GREEN)Pushed UI image to dockerhub, seconds elapsed $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" ui-deploy: ec2-deploy ## Deploys UI with subsequent pull and restart of server on EC2 ui-mocks: ## Run json-server on foreground to mock API services for UI (alias: mock) @#cd ui; ./mock.sh json-server --port 8080 --watch --routes ui/server/routes.json ui/server/db.json ## run locally: docker run -e SERVER_NAMES=localhost -e SERVER_NAME_PATTERN=localhost -e API_HOST=localhost -e API_PORT=8080 --rm tillkuhn/angkor-ui:latest # frontend aliases serve: ui-run open: ui-run ui: ui-run mock: ui-mocks ################################# # docs tasks using antora ################################# docs-clean: ## Cleanup docs build directory rm -rf ./docs/build docs-build: ## Generate documentation site using antora-playbook.yml DOCSEARCH_ENABLED=true DOCSEARCH_ENGINE=lunr antora --stacktrace --fetch --generator antora-site-generator-lunr antora-playbook.yml @echo "📃 $(GREEN)Antora documentation successfully generated in ./docs/build $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" docs-push: docs-build ## Generate documentation site and push to s3 aws s3 sync --delete ./docs/build s3://$(shell grep "^bucket_name" $(ENV_FILE) |cut -d= -f2-)/docs @echo "📃 $(GREEN)Antora documentation successfully published to s3 $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" docs-deploy: docs-push ## Deploys docs with subsequent pull and restart of server on EC2 (alias: docs) ssh -i $(shell grep "^ssh_privkey_file" $(ENV_FILE) |cut -d= -f2-) $(SSH_OPTIONS) ec2-user@$(shell grep "^public_ip" $(ENV_FILE) |cut -d= -f2-) "./deploy.sh docs" @echo "📃 $(GREEN)Antora documentation successfully deployed on server $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" # docs aliases docs: docs-deploy ################################# # ec2 instance management tasks ################################# ec2-stop: ## Stops the ec2 instance (alias: stop) aws ec2 stop-instances --instance-ids $(shell grep "^instance_id" $(ENV_FILE) |cut -d= -f2-) ec2-start: ## Launches the ec-2instamce (alias: start) aws ec2 start-instances --instance-ids $(shell grep "^instance_id" $(ENV_FILE) |cut -d= -f2-) ec2-status: ## Get ec2 instance status (alias: status) @echo "🖥️ $(GREEN) Current Status of EC2-Instance $(shell grep "^instance_id" $(ENV_FILE) |cut -d= -f2-):$(RESET)"; @# better: aws ec2 describe-instances --filters "Name=tag:appid,Values=angkor" aws ec2 describe-instances --instance-ids $(shell grep "^instance_id" $(ENV_FILE) |cut -d= -f2-) --query 'Reservations[].Instances[].State[].Name' --output text ec2-ps: ## Run docker compose status on instance (alias: ps) @ssh -i $(shell grep "^ssh_privkey_file" $(ENV_FILE) |cut -d= -f2-) $(SSH_OPTIONS) ec2-user@$(shell grep "^public_ip" $(ENV_FILE) |cut -d= -f2-) \ "docker ps;echo;top -b -n 1 | head -5" ec2-login: ## Exec ssh login into current instance (alias: ssh,login) ssh -i $(shell grep "^ssh_privkey_file" $(ENV_FILE) |cut -d= -f2-) $(SSH_OPTIONS) ec2-user@$(shell grep "^public_ip" $(ENV_FILE) |cut -d= -f2-) ec2-deploy: ## Pull recent config on server, triggers docker-compose up (alias: pull) ssh -i $(shell grep "^ssh_privkey_file" $(ENV_FILE) |cut -d= -f2-) $(SSH_OPTIONS) ec2-user@$(shell grep "^public_ip" $(ENV_FILE) |cut -d= -f2-) "./deploy.sh update api ui docs" # ec2- aliases stop: ec2-stop start: ec2-start status: ec2-status ssh: ec2-login login: ec2-login deploy: ec2-deploy ps: ec2-ps ################################ # combine targets for whole app ################################ all-clean: api-clean ui-clean ## Clean up build artifact directories in backend and frontend (alias: clean) all-build: api-build ui-build ## Builds frontend and backend (alias: build) all-deploy: api-deploy ui-deploy ## builds and deploys frontend and backend images (alias deploy) # all aliases clean: all-clean build: all-build deploy: all-deploy #todo enable dependenceisapideploy uideploy infradeloy angkor: api-push ui-push docs-push infra-deploy ec2-pull ## The ultimate target - builds and deploys everything 🦄 @echo "🌇 $(GREEN)Successfully built Angkor $(RESET)[$$(($$(date +%s)-$(STARTED)))s]" ########################################## # internal shared tasks (prefix with .) ########################################### .docker_login: echo $(shell grep "^docker_token" $(ENV_FILE) |cut -d= -f2-) | docker login --username $(shell grep "^docker_user" $(ENV_FILE) |cut -d= -f2-) --password-stdin # will exit with make: *** [.docker_checkrunning] Error 1 if daemon is not running .docker_checkrunning: @if docker ps -q 2>/dev/null; then \ echo "🐳 Docker daemon is running happily"; \ else echo "🐳 Docker daemon seems to be offline, please launch!"; exit 1; fi ########################################## # experimental tasks (undocumented, no ##) ########################################### .localstack: # start localstack with dynamodb SERVICES=s3:4572,dynamodb:8000 DEFAULT_REGION=eu-central-1 localstack --debug start --host scratch: # run typescript scratchfile cd ui; ts-node scratch.ts scra: scratch <file_sep>/api/src/main/kotlin/net/timafe/angkor/repo/DishRepository.kt package net.timafe.angkor.repo import net.timafe.angkor.domain.Dish import org.springframework.data.repository.CrudRepository import java.util.* interface DishRepository : CrudRepository<Dish, UUID> { fun findByName(name: String): List<Dish> override fun findAll(): List<Dish> } <file_sep>/api/src/main/kotlin/net/timafe/angkor/repo/NoteRepository.kt package net.timafe.angkor.repo import net.timafe.angkor.domain.Note import org.springframework.data.repository.CrudRepository import java.util.* interface NoteRepository : CrudRepository<Note, UUID> { override fun findAll(): List<Note> } <file_sep>/tools/webhooks.go package main import ( "bytes" "fmt" log "github.com/sirupsen/logrus" "net/http" "os/exec" "strings" ) const ( // port sould match with infra/modules/ec2/variables.tf DefaultListenaddress = ":5000" certRoot = "" // todo ) func hello(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "hello\n") } func hook(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "hook has been called\n") cmd := exec.Command("docker-compose", "-v") cmd.Stdin = strings.NewReader("some input") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) } // fmt.Printf("in all caps: %q\n", out.String()) log.Infof("hook is called agent %v compose version %v", req.UserAgent(), out.String()) fmt.Fprintf(w, "%v\n", out.String()) } func headers(w http.ResponseWriter, req *http.Request) { for name, headers := range req.Header { for _, h := range headers { fmt.Fprintf(w, "%v: %v\n", name, h) } } } func main() { http.HandleFunc("/hello", hello) http.HandleFunc("/hook", hook) log.Infof("Serving on %v", DefaultListenaddress) // http.ListenAndServe(DefaultListenaddress, nil) // https://gist.github.com/denji/12b3a568f092ab951456n // Display cert curl -vvI https://localhost:8443/hello err := http.ListenAndServeTLS(DefaultListenaddress, certRoot+"/fullchain.pem", certRoot+"/privkey.pem", nil) if err != nil { log.Fatal(err) } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/config/SecurityConfig.kt package net.timafe.angkor.config import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.http.HttpMethod import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter @Configuration @EnableWebSecurity // @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) class SecurityConfig : WebSecurityConfigurerAdapter() { @Throws(Exception::class) public override fun configure(http: HttpSecurity) { http.cors() http.csrf().disable() http.authorizeRequests() .antMatchers("/authorize").authenticated() .antMatchers("/api/auth-info").permitAll() .antMatchers("/api/public/**").permitAll() // tku for unauthenticated users .antMatchers("/actuator/health").permitAll() // temporary only for /api/secure //.antMatchers("/api/**").authenticated() .antMatchers("/api/secure/**").authenticated() .antMatchers( "/api/v1/admin/**").hasRole("ADMIN") .antMatchers(HttpMethod.DELETE, "/api/v1/places/**").hasRole("ADMIN") //.antMatchers("/management/**").hasAuthority(ADMIN) .and() .oauth2Login() .and() //.oauth2ResourceServer() //.jwt() //.jwtAuthenticationConverter(jwtAuthorityExtractor) //.and() .oauth2Client() } } <file_sep>/ui/src/app/shared/api.service.ts import {Injectable} from '@angular/core'; import {Observable, of, throwError} from 'rxjs'; import {HttpClient, HttpHeaders, HttpErrorResponse} from '@angular/common/http'; import {catchError, tap, map} from 'rxjs/operators'; import {Place} from '../domain/place'; import {environment} from '../../environments/environment'; import {NGXLogger} from 'ngx-logger'; import {Area} from '../domain/area'; import {POI} from '../domain/poi'; import {Dish} from '../domain/dish'; import {Note} from '../domain/note'; import {Metric} from '../admin/metrics/metric'; import {MasterDataService} from './master-data.service'; import {ListItem} from '../domain/shared'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrlPlaces = environment.apiUrlRoot + '/places'; const apiUrlNotes = environment.apiUrlRoot + '/notes'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient, private logger: NGXLogger, private masterDate: MasterDataService) { } getCountries(): Observable<Area[]> { return this.http.get<Area[]>(environment.apiUrlRoot + '/countries') .pipe( // tap: Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source. tap(place => this.logger.debug('fetched countries')), catchError(this.handleError('getCountries', [])) ); } getPOIs(): Observable<POI[]> { return this.http.get<POI[]>(environment.apiUrlRoot + '/pois') .pipe( tap(poi => this.logger.debug('fetched pois')), catchError(this.handleError('getPOIs', [])) ); } getDishes(): Observable<Dish[]> { return this.http.get<Dish[]>(environment.apiUrlRoot + '/dishes') .pipe( tap(dish => this.logger.debug('fetched dishes')), catchError(this.handleError('getDishes', [])) ); } getNotes(): Observable<Note[]> { return this.http.get<Note[]>(apiUrlNotes) .pipe( tap(note => this.logger.debug('fetched notes')), catchError(this.handleError('getNotes', [])) ); } addNote(item: Note): Observable<Note> { return this.http.post<Note>(apiUrlNotes, item, httpOptions).pipe( tap((note: any) => this.logger.debug(`added note w/ id=${note.id}`)), catchError(this.handleError<Place>('addItem')) ); } deleteNote(id: any): Observable<Note> { const url = `${apiUrlNotes}/${id}`; return this.http.delete<Note>(url, httpOptions).pipe( tap(_ => this.logger.debug(`deleted note id=${id}`)), catchError(this.handleError<Note>('deleteNote')) ); } getPlaces(): Observable<Place[]> { return this.http.get<Place[]>(apiUrlPlaces) .pipe( tap(place => this.logger.debug('fetched places')), catchError(this.handleError('getPlaces', [])) ); } // Details of a single place getPlace(id: number): Observable<Place> { const url = `${apiUrlPlaces}/${id}`; return this.http.get<Place>(url).pipe( map(placeRaw => this.fromRaw(placeRaw)), tap(_ => this.logger.debug(`fetched place id=${id}`)), catchError(this.handleError<Place>(`getPlace id=${id}`)) ); } // Todo: move to factory fromRaw(rawPlace: Place): Place { const authScopeConst = rawPlace.authScope; // replace authScope String with ListItem Object return { ...rawPlace, authScope: this.masterDate.lookupAuthscope(authScopeConst as string) }; } updatePlace(id: any, place: Place): Observable<any> { const url = `${apiUrlPlaces}/${id}`; const apiPlace = { ...place, authScope: (place.authScope as ListItem).value} return this.http.put(url, apiPlace, httpOptions).pipe( tap(_ => this.logger.debug(`updated place id=${id}`)), catchError(this.handleError<any>('updatePlace')) ); } addPlace(place: Place): Observable<Place> { return this.http.post<Place>(apiUrlPlaces, place, httpOptions).pipe( tap((prod: any) => this.logger.debug(`added place w/ id=${prod.id}`)), catchError(this.handleError<Place>('addPlace')) ); } deletePlace(id: any): Observable<Place> { const url = `${apiUrlPlaces}/${id}`; return this.http.delete<Place>(url, httpOptions).pipe( tap(_ => this.logger.debug(`deleted place id=${id}`)), catchError(this.handleError<Place>('deletePlace')) ); } getMetrics(): Observable<Metric[]> { return this.http.get<Metric[]>(environment.apiUrlRoot + '/metrics') .pipe( tap(metrics => this.logger.debug(`svc fetched ${metrics.length} metrics`)), catchError(this.handleError('getDishes', [])) ); } private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure this.logger.error(error); // log to console instead // Let the app keep running by returning an empty result. return of(result as T); }; } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/GreetingController.kt package net.timafe.angkor.rest import net.timafe.angkor.domain.Greeting import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.util.concurrent.atomic.AtomicLong @RestController class GreetingController { val counter = AtomicLong() private val log: Logger = LoggerFactory.getLogger(this.javaClass) @GetMapping("/greeting") fun greeting(@RequestParam(value = "name", defaultValue = "World") name: String) = Greeting(counter.incrementAndGet(), "Hello, $name") @GetMapping("/") fun index() = "Hello!" } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Area.kt package net.timafe.angkor.domain import com.vladmihalcea.hibernate.type.basic.PostgreSQLEnumType import net.timafe.angkor.domain.enums.AreaLevel import org.hibernate.annotations.Type import org.hibernate.annotations.TypeDef import javax.persistence.* @Entity @TypeDef( name = "pgsql_enum", typeClass = PostgreSQLEnumType::class ) data class Area( // https://vladmihalcea.com/uuid-identifier-jpa-hibernate/ @Id var code: String?, var name: String, var parentCode: String, // https://vladmihalcea.com/the-best-way-to-map-an-enum-type-with-jpa-and-hibernate/ @Enumerated(EnumType.STRING) @Column(columnDefinition = "level") @Type(type = "pgsql_enum") var level: AreaLevel = AreaLevel.COUNTRY ) <file_sep>/api/src/test/kotlin/net/timafe/angkor/ListToTree.kt package net.timafe.angkor import java.util.* import kotlin.collections.HashMap import kotlin.collections.List import kotlin.collections.MutableList import kotlin.collections.MutableMap import kotlin.collections.set import net.timafe.angkor.domain.TreeNode import kotlin.test.Test import kotlin.test.assertEquals /** * * https://www.java-success.com/00-%E2%99%A6-creating-tree-list-flattening-back-list-java/ */ class ListToTree { @Test fun testTree() { //Create a List of nodes val treeNodes: MutableList<TreeNode> = ArrayList<TreeNode>() treeNodes.add( TreeNode("Five", "5", "4")) treeNodes.add(TreeNode("Four", "4", "2")) treeNodes.add( TreeNode("Two", "2", "1")) treeNodes.add( TreeNode("Three", "3", "2")) treeNodes.add(TreeNode("One", "1", null) ) treeNodes.add(TreeNode("TwoHalf", "9", "1")) //convert to a tree var tree = createTree(treeNodes) // expected, actual, message assertEquals(2, tree?.getChildren()?.size, "expected 5 children" ) //System.out.println(tree) } private fun createTree(treeNodes: List<TreeNode>): TreeNode? { val mapTmp: MutableMap<String?, TreeNode> = HashMap<String?, TreeNode>() //Save all nodes to a map for (current in treeNodes) { mapTmp[current.id] = current } //loop and assign parent/child relationships for (current in treeNodes) { val parentId: String? = current.parentId if (parentId != null) { val parent: TreeNode? = mapTmp[parentId] if (parent != null) { current.parent = parent parent.addChild(current) mapTmp[parentId] = parent mapTmp[current.id] = current } } } //get the root var root: TreeNode? = null for (node in mapTmp.values) { if (node.parent == null) { root = node break } } return root } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/Application.kt package net.timafe.angkor import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.data.jpa.repository.config.EnableJpaRepositories // @SpringBootApplication(exclude = arrayOf(DataSourceAutoConfiguration::class)) @SpringBootApplication @EnableJpaRepositories class Application fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) } <file_sep>/docs/modules/ROOT/pages/api_spring.adoc = Spring Boot == Slimmer? * https://www.baeldung.com/spring-boot-thin-jar[spring-boot-thin-jar] * https://openliberty.io/blog/2018/06/29/optimizing-spring-boot-apps-for-docker.html[Optimizing Spring Boot apps for Docker] and https://openliberty.io/blog/2018/07/02/creating-dual-layer-docker-images-for-spring-boot-apps.html[Creating Dual Layer Docker images for Spring Boot apps ] == Relaxed Binding rules (environment vs properties) [quote, spring boot manual] ____ To convert a property name in the canonical-form to an environment variable name you can follow these rules: * Replace dots (.) with underscores (_). * Remove any dashes (-). * Convert to uppercase. https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html[source] For example, the configuration property spring.main.log-startup-info would be an environment variable named SPRING_MAIN_LOGSTARTUPINFO. ____ == Interesting Spring resources on the Web * https://dzone.com/articles/spring-boot-secured-by-lets-encrypt[Let's encrypt with Spring Boot] (but we use it only with nginx) * Lot's of inspiration for https://kotlinlang.org/docs/tutorials/spring-boot-restful.html[Creating a RESTful Web Service with Spring Boot] Source https://github.com/Kotlin/kotlin-examples/tree/master/tutorials/spring-boot-restful[Github] * https://www.baeldung.com/spring-boot-angular-web[Spring Boot bootstrapping class and populate the database with a few User entities] could be interesting * https://tuhrig.de/dynamodb-with-kotlin-and-spring-boot/[DynamoDB with Kotlin and Spring Boot (Part 1)] (but we dumped dynamodb java integration) * https://docs.spring.io/spring-boot/docs/current/reference/html/deployment.html[Deploying Spring Boot Applications] * https://spring.io/guides/tutorials/spring-security-and-angular-js/[Spring Security and Angular] * https://blog.codecentric.de/en/2019/08/spring-boot-heroku-docker-jdk11/[Spring Boot on Heroku with Docker Multistage builds, JDK 11 & Maven 3.5.x] <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/AreaController.kt package net.timafe.angkor.rest import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.Area import net.timafe.angkor.domain.enums.AreaLevel import net.timafe.angkor.repo.AreaRepository import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController /** * CHeck out * https://www.callicoder.com/kotlin-spring-boot-mysql-jpa-hibernate-rest-api-tutorial/ */ @RestController @RequestMapping(Constants.API_DEFAULT_VERSION) class AreaController { @Autowired private lateinit var areaRepository: AreaRepository private val log: Logger = LoggerFactory.getLogger(this.javaClass) @GetMapping @ResponseStatus(HttpStatus.OK) @RequestMapping("/geocodes") // https://www.baeldung.com/spring-data-sorting#1-sorting-with-the-orderby-method-keyword fun geocodes(): List<Area> { return areaRepository.findByOrderByName() } @GetMapping @ResponseStatus(HttpStatus.OK) @RequestMapping("/countries") fun countries(): List<Area> { // return areaRepository.findByLevelOrderByName(AreaLevel.COUNTRY) return areaRepository.findAllAcountiesAndregions() } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/User.kt package net.timafe.angkor.domain data class User(var name: String) <file_sep>/ui/src/app/place-edit/place-edit.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import {LoggerTestingModule} from 'ngx-logger/testing'; import {RouterTestingModule} from '@angular/router/testing'; import {HttpClientTestingModule} from '@angular/common/http/testing'; import { PlaceEditComponent } from './place-edit.component'; // https://stackoverflow.com/questions/38983766/angular-2-and-observables-cant-bind-to-ngmodel-since-it-isnt-a-known-prope import {FormsModule,ReactiveFormsModule} from '@angular/forms'; // important for test describe('PlaceEditComponent', () => { let component: PlaceEditComponent; let fixture: ComponentFixture<PlaceEditComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ PlaceEditComponent ], imports: [LoggerTestingModule,RouterTestingModule,HttpClientTestingModule,FormsModule,ReactiveFormsModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PlaceEditComponent); component = fixture.componentInstance; fixture.detectChanges(); }); // Error: No value accessor for form control with name: 'areaCode' :-( but why? xit('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Taggable.kt package net.timafe.angkor.domain interface Taggable { var tags: List<String> } <file_sep>/ui/Dockerfile ARG FROM_TAG=1-alpine FROM nginx:$FROM_TAG LABEL maintainer="angkor project team" ENV API_HOST "" ENV API_PORT "8080" ENV DOMAIN_NAME "localhost" # overwrite if not called from Dockerfile diretory (e.g. from project root) ARG BASEDIR=. # should be passed in from git describe --abbrev=0 ARG LATEST_REPO_TAG=latest # https://vsupalov.com/docker-build-time-env-values/ so we can use at runtime ENV VERSION=$LATEST_REPO_TAG # only needed if we want basic auth #RUN apk add --no-cache --update apache2-utils=~2.4 && rm -rf /var/cache/apk/* ## only copy into the image what you really need ## use .dockerignore file to keep your build context slim and improve build performance COPY ${BASEDIR}/nginx/nginx.conf /etc/nginx/nginx.tmpl.conf COPY ${BASEDIR}/dist/webapp/ /www COPY ${BASEDIR}/nginx/options-ssl-nginx.conf /etc/nginx/options-ssl-nginx.conf ## before firing up the actual application process you can perform dynamic substitions ## for example replace values in static configuration files by environment variable entries #envsubst '${monitoring_API_KEY}' < /www/monitoring.js.tpl > /www/monitoring.js && \ #htpasswd -bBc /etc/nginx/.htpasswd $BASIC_AUTH_USERNAME $BASIC_AUTH_PASSWORD && \ CMD ["sh","-c", "cp /www/index.html /www/index.tmpl.html && \ envsubst '$VERSION $MAPBOX_ACCESS_TOKEN' </www/assets/window-env.tmpl.js >/www/assets/window-env.js && \ DYNAMIC_ENV_CHECKSUM=$(md5sum /www/assets/window-env.js|cut -f1 -d' ') envsubst '$DYNAMIC_ENV_CHECKSUM' </www/index.tmpl.html >/www/index.html && \ envsubst '$SERVER_NAME_PATTERN $SERVER_NAMES $API_HOST $API_PORT' </etc/nginx/nginx.tmpl.conf >/etc/nginx/nginx.conf && \ nginx -c /etc/nginx/nginx.conf -t || cat /etc/nginx/nginx.conf && \ exec nginx -g 'daemon off;' " ] <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/enums/AuthScope.kt package net.timafe.angkor.domain.enums enum class AuthScope { PUBLIC, ALL_AUTH, PRIVATE; } <file_sep>/api/src/main/kotlin/net/timafe/angkor/config/JacksonConfiguration.kt package net.timafe.angkor.config import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.afterburner.AfterburnerModule import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder @Configuration class JacksonConfiguration { /** * Support for Java date and time API. * @return the corresponding Jackson module. */ @Bean fun javaTimeModule() = JavaTimeModule() @Bean fun jdk8TimeModule() = Jdk8Module() /* * Jackson Afterburner module to speed up serialization/deserialization. */ @Bean fun afterburnerModule() = AfterburnerModule() // Seems to kick in only for testing ?? @Bean @Primary fun customJson(): Jackson2ObjectMapperBuilderCustomizer? { return Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder -> // Also doesn't work :-( builder.indentOutput(true) // builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) } } /* @Bean @Primary fun objectMapper(builder: Jackson2ObjectMapperBuilder): ObjectMapper? { val objectMapper = builder.build<ObjectMapper>() objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) // objectMapper.configure(SerializationFeature.INDENT_OUTPUT,true) objectMapper.enable(SerializationFeature.INDENT_OUTPUT) objectMapper.findAndRegisterModules() return objectMapper }*/ } <file_sep>/docs/modules/ROOT/nav.adoc * xref:index.adoc[Welcome] * Infrastructure ** xref:infra.adoc[Build and CI/CD] ** xref:infra_aws.adoc[AWS Infra] * API (Backend) ** xref:api_spring.adoc[Spring/Kotlin] ** xref:api_docker.adoc[Docker] ** xref:db.adoc[Database / JPA] * UI (Frontend) ** xref:ui_typescript.adoc[Typescript] ** xref:ui_angular.adoc[Angular UI] * Domain Model ** xref:geodata.adoc[Geodata/Mapbox] ** xref:model.adoc[Entity Model] * CI / CD ** xref:build.adoc[] ** xref:cicd.adoc[] * Security ** xref:sec_cognito.adoc[] ** xref:sec_certbot.adoc[] <file_sep>/ui/src/app/place-add/place-add.component.ts import {Component, OnInit} from '@angular/core'; import {Router} from '@angular/router'; import {ApiService} from '../shared/api.service'; import {FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators} from '@angular/forms'; import {ErrorStateMatcher} from '@angular/material/core'; import {NGXLogger} from 'ngx-logger'; import {MyErrorStateMatcher} from '../shared/form-helper'; import {Observable} from 'rxjs'; import {Area} from '../domain/area'; import {MasterDataService} from '../shared/master-data.service'; @Component({ selector: 'app-place-add', templateUrl: './place-add.component.html', styleUrls: ['./place-add.component.scss'] }) export class PlaceAddComponent implements OnInit { countries$: Observable<Array<Area>>; placeForm: FormGroup; matcher = new MyErrorStateMatcher(); areaCode= ''; constructor(private router: Router, private api: ApiService, private masterDataService: MasterDataService,private logger: NGXLogger, private formBuilder: FormBuilder) { } ngOnInit() { this.countries$ = this.masterDataService.countries; this.placeForm = this.formBuilder.group({ name: [null, Validators.required], summary: [null, Validators.required], areaCode: [null, Validators.required], imageUrl: [null] }); } onFormSubmit() { this.masterDataService.forceReload(); this.api.addPlace(this.placeForm.value) .subscribe((res: any) => { const id = res.id; this.router.navigate(['/place-details', id]); }, (err: any) => { this.logger.error(err); }); } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/AccountController.kt package net.timafe.angkor.rest import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.dto.UserDTO import net.timafe.angkor.service.AuthService import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken import org.springframework.web.bind.annotation.* import java.security.Principal /** * REST controller for managing the current user's account. */ @RestController @RequestMapping(Constants.API_DEFAULT_VERSION) class AccountController(private val authService: AuthService) { internal class AccountResourceException(message: String) : RuntimeException(message) private val log = LoggerFactory.getLogger(javaClass) @GetMapping("/account") fun getAccount(principal: Principal?) : UserDTO { log.debug("Account for principal $principal") if (principal != null && principal is OAuth2AuthenticationToken) { return authService.getUserFromAuthentication(principal) } else { // return ResponseEntity.status(HttpStatus.FORBIDDEN).build() throw AccountResourceException("User could not be found or principal is $principal") } } @GetMapping("/authenticated") fun isAuthenticated(principal: Principal?) : ResponseEntity<Boolean> { log.debug("isAuthenticated for principal $principal") return ResponseEntity(principal != null,HttpStatus.OK); } /** * `GET /authenticate` : check if the user is authenticated, and return its login. * * @param request the HTTP request. * @return the login if the user is authenticated. */ /* @GetMapping("/authenticate") fun isAuthenticated(request: HttpServletRequest): String? { log.debug("REST request to check if remoteUser=${request.remoteUser} is authenticated") return request.remoteUser } */ /** * `GET /account` : get the current user. * * @param principal the current user; resolves to `null` if not authenticated. * @return the current user. * @throws AccountResourceException `500 (Internal Server Error)` if the user couldn't be returned. */ /* @GetMapping("/account") fun getAccount(principal: Principal?): User = if (principal is AbstractAuthenticationToken) { userService.getUserFromAuthentication(principal) } else { throw AccountResourceException("User could not be found") } */ } <file_sep>/ui/src/app/shared/master-data.service.ts import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {NGXLogger} from 'ngx-logger'; import {Observable, Subject} from 'rxjs'; import {Area} from '../domain/area'; import {environment} from '../../environments/environment'; import {shareReplay, tap} from 'rxjs/operators'; import {ListItem} from '../domain/shared'; const CACHE_SIZE = 1; @Injectable({ providedIn: 'root' }) // inspired by https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html export class MasterDataService { private countriesCache$: Observable<Array<Area>>; private reload$ = new Subject<void>(); private authScopes: Array<ListItem>; private authScopesLookup: Map<string, number> = new Map(); private locationTypes: Array<ListItem>; private locationTypesLookup: Map<string, number> = new Map(); constructor(private http: HttpClient, private logger: NGXLogger) { // todo export declare type AuthScope = 'PUBLIC' | 'ALL_AUTH' | 'PRIVATE'; this.authScopes = [ {label: 'Public', icon: 'lock_open', value: 'PUBLIC'}, {label: 'Authenticated', icon: 'lock', value: 'ALL_AUTH'}, {label: 'Private', icon: 'security', value: 'PRIVATE'} ]; this.authScopes.forEach( (item, i) => this.authScopesLookup.set(item.value, i )); this.locationTypes = [ {label: 'Place', icon: 'place', value: 'PLACE'}, {label: 'Accomodation', icon: 'hotel', value: 'ACCOM'}, {label: 'Beach & Island', icon: 'beach_access', value: 'BEACH'}, {label: 'Citytrip', icon: 'location_city', value: 'CITY'}, {label: 'Excursion & Activities', icon: 'directions_walk', value: 'EXCURS'}, {label: 'Monument', icon: 'account_balance', value: 'MONUM'}, {label: 'Mountain & Skiing', icon: 'ac_unit', value: 'MOUNT'}, {label: 'Roadtrip Destination', icon: 'directions:car', value: 'ROAD'} ]; this.locationTypes.forEach( (item, i) => this.locationTypesLookup.set(item.value, i )); } getAuthScopes() { return this.authScopes; } /** * Can use like this: <mat-icon>{{masterDataService.lookupAuthscope('ALL_AUTH').icon}}</mat-icon> */ lookupAuthscope(itemValue: string) { // todo handle undefined if called too early or key does not exist // this.logger.debug('checl auth ' +itemValue); return this.authScopes[this.authScopesLookup.get(itemValue)]; } getLocationTypes() { return this.locationTypes; } lookupLocationType(itemValue: string) { // this.logger.debug('checl loc ' +itemValue); return this.locationTypes[this.locationTypesLookup.get(itemValue)]; } get countries() { // This shareReplay operator returns an Observable that shares a single subscription // to the underlying source, which is the Observable returned from this.requestCountriesWithRegions() if (!this.countriesCache$) { this.countriesCache$ = this.requestCountries().pipe( shareReplay(CACHE_SIZE) ); } return this.countriesCache$; } private requestCountries(): Observable<Area[]> { return this.http.get<Area[]>(environment.apiUrlRoot + '/countries') .pipe( tap(items => this.logger.debug(`fetched ${items.length} countries from server`)) /*, catchError(this.handleError('getCountries', []))*/ ); } forceReload() { // Calling next will complete the current cache instance this.reload$.next(); // Setting the cache to null will create a new cache the next time 'countries' is called this.countriesCache$ = null; this.logger.debug('all caches invalidated'); } } <file_sep>/ui/src/app/place-detail/place-detail.component.ts import {Component, OnInit} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {ApiService} from '../shared/api.service'; import {NGXLogger} from 'ngx-logger'; import {Place} from '../domain/place'; import {MasterDataService} from '../shared/master-data.service'; import {SmartCoordinates} from '../domain/smart-coordinates'; import {MatDialog} from '@angular/material/dialog'; import {ConfirmDialogComponent, ConfirmDialogModel} from '../shared/confirm-dialog/confirm-dialog.component'; import {MatSnackBar} from '@angular/material/snack-bar'; @Component({ selector: 'app-place-detail', templateUrl: './place-detail.component.html', styleUrls: ['./place-detail.component.scss'] }) export class PlaceDetailComponent implements OnInit { place: Place = {id: '', name: '', areaCode: ''}; coordinates: SmartCoordinates; deleteDialogResult = ''; constructor(private route: ActivatedRoute, private api: ApiService, public masterData: MasterDataService, private router: Router, private logger: NGXLogger, private dialog: MatDialog, private snackBar: MatSnackBar) { } ngOnInit() { this.getPlaceDetails(this.route.snapshot.params.id); } getPlaceDetails(id: any) { this.api.getPlace(id) .subscribe((data: any) => { this.place = data; if (this.place.coordinates && this.place.coordinates.length > 1) { this.coordinates = new SmartCoordinates(this.place.coordinates); } this.logger.debug('getPlaceDetails()', this.place); }); } deletePlace(id: string) { this.logger.debug(`Deleting ${id}`); this.api.deletePlace(id) .subscribe(res => { this.snackBar.open('Place was successfully trashed', 'Close'); this.router.navigate(['/places']); }, (err) => { this.logger.error('deletePlace', err); } ); } confirmDeleteDialog(place: Place): void { const message = `Are you sure you want to do trash ${place.name}?`; const dialogData = new ConfirmDialogModel('Confirm Action', message); const dialogRef = this.dialog.open(ConfirmDialogComponent, { maxWidth: '400px', data: dialogData }); dialogRef.afterClosed().subscribe(dialogResult => { if (dialogResult) { this.deletePlace(place.id); } }); } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Dish.kt package net.timafe.angkor.domain import net.timafe.angkor.domain.enums.AuthScope import org.hibernate.annotations.Type import org.hibernate.annotations.TypeDef import java.util.* import javax.persistence.* /* { "origin": "gr", "lastServed": "2015-07-07T21:33:37.718Z", "authenticName": "<NAME>", "timesServed": 5, "rating": 9, "createdAt": "2015-08-09-09T22:22:22.222Z", "primaryUrl": "http://de.allrecipes.com/rezept/1268/authentischer-griechischer-salat.aspx", "updatedBy": "<EMAIL>", "name": "<NAME>", "imageUrl": "http://www.casualcatering.com/shop/images/greek.jpg", "updatedAt": "2018-09-19T21:58:30.910Z", "notes": "1. Paprikaschoten halbieren, entkernen und in 2 cm große Würfel schneiden. Tomaten sechsteln. Salatgurke längs vierteln und quer in 2 cm große Stücke schneiden. Zwiebeln in 1 cm dicke Scheiben schneiden. Minze in feine Streifen schneiden. Oliven halbieren, Schafskäse in 2 cm große Würfel schneiden.\n\n2. Essig mit 10 El kaltem Wasser, Öl, Salz und Pfeffer in einer Schüssel verrühren. Paprikaschoten, Tomaten, Gurke, Zwiebeln, Minze, Schafskäse und Oliven mit dem Dressing mischen und kurz durchziehen lassen. Dazu passt Fladenbrot.", "id": "5585e234e4b062eca3674e08", "tags": [ "feta", "oliven", "salat", "tomaten", "veggy" ] }*/ @Entity @TypeDef( name = "list-array", typeClass = com.vladmihalcea.hibernate.type.array.ListArrayType::class ) data class Dish( // https://vladmihalcea.com/uuid-identifier-jpa-hibernate/ @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: UUID?, var name: String, var areaCode: String, var summary: String?, var imageUrl: String?, var primaryUrl: String?, @Enumerated(EnumType.STRING) @Column(columnDefinition = "scope") @Type(type = "pgsql_enum") var authScope: AuthScope = AuthScope.PUBLIC, @Type(type = "list-array") @Column( name = "tags", columnDefinition = "text[]" ) override var tags: List<String> = listOf() //var updated: LocalDateTime = LocalDateTime // //.now() ): Taggable <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/LogoutResource.kt package net.timafe.angkor.rest import net.timafe.angkor.config.Constants import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.context.annotation.Profile import org.springframework.http.ResponseEntity import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.security.oauth2.client.registration.ClientRegistration import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.oauth2.core.oidc.OidcIdToken import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import javax.servlet.http.HttpServletRequest /** * REST controller for managing global OIDC logout. */ @RestController @RequestMapping(Constants.API_DEFAULT_VERSION) class LogoutResource(registrations: ClientRegistrationRepository) { private val registration: ClientRegistration = registrations.findByRegistrationId("cognito") private val log: Logger = LoggerFactory.getLogger(this.javaClass) /** * `POST /api/logout` : logout the current user. * * @param request the [HttpServletRequest]. * @param idToken the ID token. * @return the [ResponseEntity] with status `200 (OK)` and a body with a global logout URL and ID token. */ @PostMapping("/logout") fun logout( request: HttpServletRequest, @AuthenticationPrincipal(expression = "idToken") idToken: OidcIdToken? ): ResponseEntity<*> { log.info("Logging out current user") val logoutUrl = registration.providerDetails.configurationMetadata["end_session_endpoint"].toString() val logoutDetails = mutableMapOf( "logoutUrl" to logoutUrl, "idToken" to idToken?.tokenValue ) request.session.invalidate() return ResponseEntity.ok().body(logoutDetails) } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/NoteController.kt package net.timafe.angkor.rest import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.Note import net.timafe.angkor.repo.NoteRepository import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import java.security.Principal import java.util.* @RestController @RequestMapping(Constants.API_DEFAULT_VERSION + "/notes") class NoteController { @Autowired private lateinit var noteRepository: NoteRepository private val log: Logger = LoggerFactory.getLogger(this.javaClass) @GetMapping @ResponseStatus(HttpStatus.OK) fun allNotes(principal: Principal?): List<Note> { // val dishes = if (principal != null) placeRepository.findByOrderByName() else placeRepository.findPublicPlaces() val entities = noteRepository.findAll() // coo ${places.get(0).coordinates}" log.info("allNotes() return ${entities.size} notes principal=${principal}") return entities } @PostMapping @ResponseStatus(HttpStatus.CREATED) fun createNewNote(@RequestBody note: Note): Note = noteRepository.save(note) @DeleteMapping("{id}") fun deleteNote(@PathVariable(value = "id") id: UUID): ResponseEntity<Void> { log.debug("Deleting note item $id") return noteRepository.findById(id).map { item -> noteRepository.delete(item) ResponseEntity<Void>(HttpStatus.OK) }.orElse(ResponseEntity.notFound().build()) } } <file_sep>/ui/src/app/map/map.component.ts import {Component, OnInit} from '@angular/core'; import {EnvironmentService} from '../environment.service'; import {NGXLogger} from 'ngx-logger'; import {MapboxGeoJSONFeature, MapLayerMouseEvent} from 'mapbox-gl'; import {ApiService} from '../shared/api.service'; import {Feature} from 'geojson'; import {POI} from '../domain/poi'; @Component({ selector: 'app-map', templateUrl: './map.component.html', styleUrls: ['./map.component.scss'] }) export class MapComponent implements OnInit { // zoom into ... The latitude of Bangkok, Thailand is 13.736717, and the longitude is 100.523186. // check https://docs.mapbox.com/mapbox-gl-js/example/setstyle/ for alternative styles, streets-v11, // https://docs.mapbox.com/api/maps/#styles mapstyles = [ { description: 'Outdoor', id: 'outdoors-v11' }, { description: 'Satellite', id: 'satellite-streets-v11' // 'satellite-v9' is w/o streets }, { description: 'Street', id: 'streets-v11' } ]; mapstyle = 'mapbox://styles/mapbox/' + this.mapstyles[0].id; // default outdoor // [51.2097352,35.6970118] teheran ~middle between europe + SE asia // [100.523186, 13.736717] = bangkok coordinates = [51.2097352, 35.6970118] ; zoom = [3]; // 10 ~ detailed like bangkok + area, 5 ~ southease asia accessToken = this.envservice.mapboxAccessToken points: GeoJSON.FeatureCollection<GeoJSON.Point>; selectedPoint: MapboxGeoJSONFeature | null; cursorStyle: string; constructor(private envservice: EnvironmentService, private apiService: ApiService, private logger: NGXLogger) { } ngOnInit(): void { this.logger.info('Mapper is ready token len=', this.envservice.mapboxAccessToken.length) // console.log('token', this.envservice.mapboxAccessToken, 'version',this.envservice.version) this.apiService.getPOIs() // .query() // .pipe( // filter((res: HttpResponse<IPoi[]>) => res.ok), // map((res: HttpResponse<IPoi[]>) => res.body) // ) .subscribe((res: POI[]) => { const features: Array<Feature<GeoJSON.Point>> = []; res.forEach(poi => { if (!poi.coordinates) { this.logger.warn(poi.id + ' empty coordinates'); return; } features.push({ type: 'Feature', properties: { // tslint:disable-next-line:max-line-length id: poi.id, name: poi.name, // https://labs.mapbox.com/maki-icons/ icon: 'attraction' }, geometry: { type: 'Point', coordinates: poi.coordinates } }); }); this.points = { type: 'FeatureCollection', features }; }); } // pois: IPoi[]; onClick(evt: MapLayerMouseEvent) { // this.selectedPoint = evt.features![0]; // 50:26 error This assertion is unnecessary ... typescript-eslint/no-unnecessary-type-assertion ß? this.selectedPoint = evt.features[0]; } onMapboxStyleChange(entry: { [key: string]: any }) { // clone the object for immutability // clone the object for immutability // eslint-disable-next-line no-console this.logger.info('Switch to mapbox://styles/mapbox/' + entry.id); this.mapstyle = 'mapbox://styles/mapbox/' + entry.id; } } <file_sep>/infra/templates/captain-hook.py #!/usr/bin/env python3 # based on import os, argparse from datetime import datetime, timedelta from flask import Flask, request, abort, jsonify from subprocess import check_output def temp_token(): import binascii temp_token = binascii.hexlify(os.urandom(24)) return temp_token.decode('utf-8') WEBHOOK_VERIFY_TOKEN = os.getenv('WEBHOOK_VERIFY_TOKEN') CLIENT_AUTH_TIMEOUT = 24 # in Hours app = Flask(__name__) authorised_clients = {} @app.route('/webhook', methods=['GET', 'POST']) def webhook(): if request.method == 'GET': verify_token = request.args.get('verify_token') if verify_token == WEBHOOK_VERIFY_TOKEN: authorised_clients[request.remote_addr] = datetime.now() #p = subprocess.run("echo 'hello world!'", capture_output=True, shell=True, encoding="utf8") ## assert p.stdout == 'hello world!\n' out = check_output(["docker-compose", "version"]) print(out.decode('ascii')) return jsonify({'status':'success','result':out.decode('ascii')}), 200 else: return jsonify({'status':'bad token'}), 401 # elif request.method == 'POST': # client = request.remote_addr # if client in authorised_clients: # if datetime.now() - authorised_clients.get(client) > timedelta(hours=CLIENT_AUTH_TIMEOUT): # authorised_clients.pop(client) # return jsonify({'status':'authorisation timeout'}), 401 # else: # print(request.json) # return jsonify({'status':'success'}), 200 # else: # return jsonify({'status':'not authorised'}), 401 else: abort(400) if __name__ == '__main__': if WEBHOOK_VERIFY_TOKEN is None: print('WEBHOOK_VERIFY_TOKEN has not been set in the environment.\nGenerating random token...') token = temp_token() print('Token: %s' % token) WEBHOOK_VERIFY_TOKEN = token else: print(f'Using WEBHOOK_VERIFY_TOKEN from environment len={len(WEBHOOK_VERIFY_TOKEN)}') parser = argparse.ArgumentParser() parser.add_argument('-s', '--ssl', dest='ssl_enabled', default=False, action='store_true',help="run in ssl mode") parser.add_argument('-p', '--port', dest='port', default=5000,help="listener port (default 5000)") args = parser.parse_args() if args.ssl_enabled: print(f'Running with ssl_enabled={args.ssl_enabled} port={args.port}') certdir= os.path.join('/etc/letsencrypt/live/','${certbot_domain_name}') app.run(host='0.0.0.0',port=args.port, ssl_context=(os.path.join(certdir,'fullchain.pem'),os.path.join(certdir,'privkey.pem'))) else: print(f'Running in http only mode port={args.port}') app.run(host='0.0.0.0',port=args.port) <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Mappable.kt package net.timafe.angkor.domain interface Mappable { var coordinates: List<Double> // abstract property } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Greeting.kt package net.timafe.angkor.domain data class Greeting(val id: Long, val content: String) <file_sep>/ui/src/app/place-add/place-add.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { PlaceAddComponent } from './place-add.component'; import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; import {LoggerTestingModule} from 'ngx-logger/testing'; import {RouterTestingModule} from '@angular/router/testing'; // imports: [RouterTestingModule, LoggerTestingModule, HttpClientTestingModule] import {FormsModule,ReactiveFormsModule} from '@angular/forms'; describe('PlaceAddComponent', () => { let component: PlaceAddComponent; let fixture: ComponentFixture<PlaceAddComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ PlaceAddComponent ], imports: [RouterTestingModule, LoggerTestingModule, HttpClientTestingModule,FormsModule,ReactiveFormsModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PlaceAddComponent); component = fixture.componentInstance; fixture.detectChanges(); }); // todo fix Error: No value accessor for form control with name: 'areaCode' xit('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/ui/src/app/notes/notes.component.ts import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {Note, NOTE_TAGS} from '../domain/note'; import {ApiService} from '../shared/api.service'; import {NGXLogger} from 'ngx-logger'; import {FormArray, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {MatSnackBar} from '@angular/material/snack-bar'; import {MyErrorStateMatcher} from '../shared/form-helper'; import {COMMA, ENTER} from '@angular/cdk/keycodes'; import {MatAutocomplete, MatAutocompleteSelectedEvent} from '@angular/material/autocomplete'; import {MatChipInputEvent} from '@angular/material/chips'; import {Observable} from 'rxjs'; import {map, startWith} from 'rxjs/operators'; import {MatTable} from '@angular/material/table'; @Component({ selector: 'app-notes', templateUrl: './notes.component.html', styleUrls: ['./notes.component.scss'] }) export class NotesComponent implements OnInit { displayedColumns: string[] = ['summary', 'status', /*'createdAt' */'dueDate','actions']; matcher = new MyErrorStateMatcher(); data: Note[] = []; @ViewChild(MatTable,{static:true}) table: MatTable<any>; // tag chip support // https://stackoverflow.com/questions/52061184/input-material-chips-init-form-array formData: FormGroup; selectable = true; removable = true; addOnBlur = true; readonly separatorKeysCodes: number[] = [ENTER, COMMA]; constructor(private api: ApiService, private logger: NGXLogger, private formBuilder: FormBuilder, private snackBar: MatSnackBar) { } ngOnInit() { this.initForm(); this.api.getNotes() .subscribe((res: any) => { this.data = res; this.logger.debug('getNotes()', this.data); }, err => { this.logger.error(err); }); } initForm() { this.formData = this.formBuilder.group({ summary: [null, Validators.required], tags: this.formBuilder.array([]), dueDate: new FormControl() }); } add(e: MatChipInputEvent) { const input = e.input; const value = e.value; if ((value || '').trim()) { const control = this.formData.controls.tags as FormArray; control.push(this.formBuilder.control(value.trim().toLowerCase())); } if (input) { input.value = ''; } } remove(i: number) { const control = this.formData.controls.tags as FormArray; control.removeAt(i); } onFormSubmit() { // this.newItemForm.patchValue({tags: ['new']}); this.api.addNote(this.formData.value) .subscribe((res: any) => { const id = res.id; this.snackBar.open('Quicknote saved with id ' + id, 'Close', { duration: 2000, }); this.initForm(); // reset new note form this.data.push(res); // add new item to datasource this.table.renderRows(); // refresh table // this.ngOnInit(); // reset / reload list // this.router.navigate(['/place-details', id]); }, (err: any) => { this.logger.error(err); }); } // Read https://stackoverflow.com/questions/49172970/angular-material-table-add-remove-rows-at-runtime // and https://www.freakyjolly.com/angular-material-table-operations-using-dialog/#.Xxm0XvgzbmE deleteRow(row: Note, rowid: number){ this.api.deleteNote(row.id) .subscribe((res: any) => { // const id = res.id; if (rowid > -1) { this.data.splice(rowid, 1); this.table.renderRows(); // refresh table } this.snackBar.open('Quicknote deleted', 'Close', { duration: 2000, }); // this.ngOnInit(); // reset / reload list // this.router.navigate(['/place-details', id]); }, (err: any) => { this.logger.error(err); }); } } <file_sep>/ui/src/app/domain/user.ts export interface User { id?: any; login?: string; firstName?: string; lastName?: string; name?: string; email?: string; activated?: boolean; langKey?: string; authorities?: any[]; createdBy?: string; createdDate?: Date; lastModifiedBy?: string; lastModifiedDate?: Date; password?: string; } // export declare type AuthScope = 'PUBLIC' | 'ALL_AUTH' | 'PRIVATE'; <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/dto/POI.kt package net.timafe.angkor.domain.dto import net.timafe.angkor.domain.Mappable import java.util.* data class POI( var id: UUID, var name: String, // coordinates should be List<Double>? but this didn't work with JPA SELECT NEW query // (see PlaceRepository) which raises // Expected arguments are: java.util.UUID, java.lang.String, java.lang.Object // var coordinates: java.lang.Object? = null override var coordinates: List<Double> = listOf() ) : Mappable { // Satisfy entity query in PlaceRepository which cannot cast coorindates arg // Unable to locate appropriate constructor on class [net.timafe.angkor.domain.dto.POI]. // Expected arguments are: java.util.UUID, java.lang.String, java.lang.Object constructor(id: UUID, name: String, coordinates: Any) : this(id, name, coordinates as List<Double>) } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Response.kt package net.timafe.angkor.domain data class Response(var result: String) <file_sep>/ui/src/app/domain/shared.ts // https://basarat.gitbook.io/typescript/type-system/index-signatures#typescript-index-signature export interface ListItem { label: string; value: string; icon?: string; // check https://material.io/resources/icons/?style=baseline emoji?: string; // https://emojipedia.org/search/ } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/TreeNode.kt package net.timafe.angkor.domain import java.util.* /* * Based on https://www.java-success.com/00-%E2%99%A6-creating-tree-list-flattening-back-list-java/ */ class TreeNode { var id //Current node id : String? = null var parentId //Parent node id : String? = null var value: String? = null var parent: TreeNode? = null private var children: MutableList<TreeNode> constructor() : super() { children = ArrayList() } constructor(value: String?, childId: String?, parentId: String?) { this.value = value id = childId this.parentId = parentId children = ArrayList() } fun getChildren(): List<TreeNode> { return children } fun setChildren(children: MutableList<TreeNode>) { this.children = children } fun addChild(child: TreeNode?) { if (!children.contains(child) && child != null) children.add(child) } override fun toString(): String { return ("Node [id=" + id + ", parentId=" + parentId + ", value=" + value + ", children=" + children + "]") } } <file_sep>/ui/src/app/notes/notes.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {NotesComponent} from './notes.component'; import {HttpClientTestingModule} from '@angular/common/http/testing'; import {LoggerTestingModule} from 'ngx-logger/testing'; import {RouterTestingModule} from '@angular/router/testing'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatSnackBarModule} from '@angular/material/snack-bar'; import {LayoutModule} from '@angular/cdk/layout'; import {MatInputModule} from '@angular/material/input'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MomentModule} from 'ngx-moment'; describe('NotesComponent', () => { let component: NotesComponent; let fixture: ComponentFixture<NotesComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [NotesComponent], imports: [LayoutModule, LoggerTestingModule, RouterTestingModule, HttpClientTestingModule, MomentModule, FormsModule, ReactiveFormsModule, MatSnackBarModule, MatInputModule, BrowserAnimationsModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(NotesComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/docs/modules/ROOT/pages/ui_typescript.adoc = Typescript :toc: <file_sep>/api/src/main/kotlin/net/timafe/angkor/repo/PlaceRepository.kt package net.timafe.angkor.repo import net.timafe.angkor.domain.dto.POI import net.timafe.angkor.domain.Place import net.timafe.angkor.domain.dto.PlaceSummary import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository import java.util.* interface PlaceRepository : CrudRepository<Place, UUID> { fun findByName(name: String): List<Place> override fun findAll(): List<Place> /** * Returns all places, irrespective of AuthScope */ @Query(""" SELECT NEW net.timafe.angkor.domain.dto.PlaceSummary(p.id, p.name, p.summary, p.areaCode, p.primaryUrl, p.locationType, p.coordinates) FROM Place p ORDER BY p.name """) fun findAllPlacesOrderByName(): List<PlaceSummary> /** * Returs all places that are public (i.e. save to display to anonymous users) */ @Query(""" SELECT NEW net.timafe.angkor.domain.dto.PlaceSummary(p.id, p.name, p.summary, p.areaCode, p.primaryUrl, p.locationType, p.coordinates) FROM Place p where p.authScope = net.timafe.angkor.domain.enums.AuthScope.PUBLIC ORDER BY p.name """) fun findPublicPlaces(): List<PlaceSummary> // https://stackoverflow.com/questions/8217144/problems-with-making-a-query-when-using-enum-in-entity //@Query(value = "SELECT p FROM Place p where p.lotype = net.timafe.angkor.domain.enums.LocationType.CITY order by p.name") // try SELECT NEW example.CountryAndCapital(c.name, c.capital.name) //FROM Country AS c // https://stackoverflow.com/questions/52166439/jpa-using-param-values-in-return-for-select @Query(value = "SELECT NEW net.timafe.angkor.domain.dto.POI(p.id,p.name,p.coordinates) FROM Place p") fun findPointOfInterests(): List<POI> // Adhoc queries // var query: TypedQuery<Place?>? = em.createQuery("SELECT c FROM Place c where c.lotype=net.timafe.angkor.domain.enums.LocationType.CITY", Place::class.java) // val results: List<Place?> = query!!.getResultList() } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Place.kt package net.timafe.angkor.domain import com.fasterxml.jackson.annotation.JsonFormat import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.enums.AuthScope import net.timafe.angkor.domain.enums.LocationType import org.hibernate.annotations.Type import org.hibernate.annotations.TypeDef import java.time.LocalDateTime import java.util.* import javax.persistence.* /** * { "id": "70c4916f-e621-477b-8654-44952491bee1", "name": "Sperlonga", "country": "it", "imageUrl": "https://www.portanapoli.de/sites/default/files/styles/half_column_250/public/pictures/taxonomy/sperlonga_by_night.jpg?itok=uCh02nl8", "lotype": "BEACH", "coordinates": [ 13.42714, 41.26367 ], "primaryUrl": "https://www.portanapoli.de/sperlonga", "summary": "Tip Sperlonga mit herrlichen Sandstränden und einer malerischen Altstadt ist einer der schönsten Orte Süditaliens.", "notes": "Sperlonga ist einer der malerischsten Orte Süditaliens.\n Bezaubernd ist der Blick von der Altstadt.", "createdAt": "2019-10-02T18:57:27.534Z", "createdBy": "<EMAIL>", "updatedAt": "2019-11-09T12:15:45.689Z", "updatedBy": "<EMAIL>" } */ @Entity @TypeDef( name = "list-array", typeClass = com.vladmihalcea.hibernate.type.array.ListArrayType::class ) data class Place( // https://vladmihalcea.com/uuid-identifier-jpa-hibernate/ @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: UUID?, var name: String, var areaCode: String, var summary: String?, var notes: String?, var imageUrl: String?, var primaryUrl: String?, @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = Constants.JACKSON_DATE_FORMAT) var createdAt: LocalDateTime? = LocalDateTime.now(), @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = Constants.JACKSON_DATE_FORMAT) var updatedAt: LocalDateTime? = LocalDateTime.now(), @Enumerated(EnumType.STRING) @Column(columnDefinition = "location_type") @Type(type = "pgsql_enum") var locationType: LocationType = LocationType.PLACE, @Enumerated(EnumType.STRING) @Column(columnDefinition = "scope") @Type(type = "pgsql_enum") var authScope: AuthScope = AuthScope.PUBLIC, @Type(type = "list-array") @Column( name = "coordinates", columnDefinition = "double precision[]" ) override var coordinates: List<Double> = listOf() /* 0.0, 0.0 */, @Type(type = "list-array") @Column( name = "tags", columnDefinition = "text[]" ) override var tags: List<String> = listOf() ) : Mappable, Taggable { @PrePersist @PreUpdate fun prePersist() { updatedAt = LocalDateTime.now(); } } <file_sep>/ui/src/app/domain/poi.ts export interface POI { id?: string; name?: string; // lotype?: string; // country?: string; coordinates?: Array<number>; } <file_sep>/ui/src/app/place-edit/place-edit.component.ts import {Component, OnInit} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {ApiService} from '../shared/api.service'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {NGXLogger} from 'ngx-logger'; import {Area} from '../domain/area'; import {MyErrorStateMatcher} from '../shared/form-helper'; import {MasterDataService} from '../shared/master-data.service'; import {ListItem} from '../domain/shared'; import {SmartCoordinates} from '../domain/smart-coordinates'; import {MatSnackBar} from '@angular/material/snack-bar'; @Component({ selector: 'app-place-edit', templateUrl: './place-edit.component.html', styleUrls: ['./place-edit.component.scss'] }) export class PlaceEditComponent implements OnInit { countries: Area[] = []; locationTypes: ListItem[]; placeForm: FormGroup; id = ''; matcher = new MyErrorStateMatcher(); constructor(private router: Router, private route: ActivatedRoute, private api: ApiService, private formBuilder: FormBuilder, private snackBar: MatSnackBar, private logger: NGXLogger, public masterData: MasterDataService) { } // get initial value of selecbox base on enum value provided by backend getSelectedLotype(): ListItem { return this.masterData.lookupLocationType(this.placeForm.get('locationType').value); } ngOnInit() { this.getPlace(this.route.snapshot.params.id); this.api.getCountries() .subscribe((res: any) => { this.countries = res; this.logger.debug(`PlaceEditComponent getCountries() ${this.countries.length} items`); }, err => { this.logger.error(err); }); this.placeForm = this.formBuilder.group({ name: [null, Validators.required], summary: [null, Validators.required], notes: [null], coordinatesStr: [null], areaCode: [null, Validators.required], primaryUrl: [null], imageUrl: [null, Validators.required], locationType: [null, Validators.required], authScope: [null] }); this.locationTypes = this.masterData.getLocationTypes(); } getPlace(id: any) { this.api.getPlace(id).subscribe((data: any) => { this.id = data.id; // use patch not set, avoid // https://stackoverflow.com/questions/51047540/angular-reactive-form-error-must-supply-a-value-for-form-control-with-name this.placeForm.patchValue({ name: data.name, summary: data.summary, notes: data.notes, areaCode: data.areaCode, imageUrl: data.imageUrl, primaryUrl: data.primaryUrl, locationType: data.locationType, authScope: data.authScope, coordinatesStr: (Array.isArray((data.coordinates)) && (data.coordinates.length > 1)) ? `${data.coordinates[1]} ${data.coordinates[0]}` : null }); }); } onFormSubmit() { const place = this.placeForm.value; // Todo: validate update coordindates array after they've been entered, not shortly before submit if (place.coordinatesStr) { const sco = new SmartCoordinates((place.coordinatesStr)); place.coordinates = sco.lonLatArray; this.logger.debug('coordinates',sco); delete place.coordinatesStr; } this.logger.debug('submit()', place); this.api.updatePlace(this.id, this.placeForm.value) .subscribe((res: any) => { this.snackBar.open('Place has been successfully updated', 'Close'); const id = res.id; this.router.navigate(['/place-details', id]); }, (err: any) => { this.logger.error(err); } ); } placeDetails() { this.router.navigate(['/place-details', this.id]); } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/MapController.kt package net.timafe.angkor.rest import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.dto.POI import net.timafe.angkor.repo.PlaceRepository import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping(Constants.API_DEFAULT_VERSION) class MapController { private val log = LoggerFactory.getLogger(javaClass) @Autowired private lateinit var placeRepository: PlaceRepository @GetMapping("/pois") fun getCoordinates(): List<POI> { log.debug("REST request to get all coordinates") val pois = placeRepository.findPointOfInterests() //val list = mutableListOf<POI>() /* val mapper = DynamoDBMapper(amazonDynamoDB) val nameMap = HashMap<String, String>() nameMap["#name"] = "name" // reserved keyword val scanExpression = DynamoDBScanExpression().withExpressionAttributeNames(nameMap).withProjectionExpression("id,coordinates,country,#name") val iList = mapper.scan(Place::class.java,scanExpression) val iter = iList.iterator() while (iter.hasNext()) { val item = iter.next(); list.add(Coordinates(item.id,item.name,item.coordinates)) //log.debug("hase"+item) } */ return pois.filter { it.coordinates != null && it.coordinates.size > 1 } } } <file_sep>/ui/src/app/domain/area.ts export interface Area { code: string; name: string; parentCode: string; level: string; // coordinates?: number[]; } <file_sep>/api/src/main/kotlin/net/timafe/angkor/repo/AreaRepository.kt package net.timafe.angkor.repo import net.timafe.angkor.domain.Area import net.timafe.angkor.domain.enums.AreaLevel import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository interface AreaRepository : CrudRepository<Area, String> { fun findByName(name: String): List<Area> override fun findAll(): List<Area> fun findByOrderByName(): List<Area> fun findByLevelOrderByName(level: AreaLevel): List<Area> @Query("SELECT a FROM Area a where a.level IN(net.timafe.angkor.domain.enums.AreaLevel.COUNTRY,net.timafe.angkor.domain.enums.AreaLevel.REGION) ORDER BY a.name") fun findAllAcountiesAndregions(): List<Area> } <file_sep>/api/src/main/kotlin/net/timafe/angkor/config/FlywayConfig.kt package net.timafe.angkor.config import org.slf4j.LoggerFactory import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile @Configuration class FlywayConfig { @Bean @Profile(Constants.PROFILE_CLEAN) fun cleanMigrateStrategy(): FlywayMigrationStrategy? { return FlywayMigrationStrategy { flyway -> LoggerFactory.getLogger(FlywayMigrationStrategy::class.java).info("Profile {}, cleaning Flyway Schema", Constants.PROFILE_CLEAN) flyway.clean() flyway.migrate() } } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/rest/PlaceController.kt package net.timafe.angkor.rest import com.fasterxml.jackson.databind.ObjectMapper import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.Place import net.timafe.angkor.domain.dto.PlaceSummary import net.timafe.angkor.repo.PlaceRepository import net.timafe.angkor.service.AuthService import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.* import java.security.Principal import java.util.* import javax.persistence.EntityManager import javax.validation.Valid /** * CHeck out * https://www.callicoder.com/kotlin-spring-boot-mysql-jpa-hibernate-rest-api-tutorial/ */ @RestController @RequestMapping(Constants.API_DEFAULT_VERSION + "/places") class PlaceController { @Autowired private lateinit var placeRepository: PlaceRepository @Autowired private lateinit var em: EntityManager @Autowired private lateinit var authService: AuthService @Autowired private lateinit var objectMapper: ObjectMapper private val log: Logger = LoggerFactory.getLogger(this.javaClass) /** * Get public places if logged in and all places if not ... */ @GetMapping @ResponseStatus(HttpStatus.OK) fun allPlaces(principal: Principal?): List<PlaceSummary> { val isAnonymous = authService.isAnonymous() val places = if (isAnonymous) placeRepository.findPublicPlaces() else placeRepository.findAllPlacesOrderByName() // coo ${places.get(0).coordinates}" log.info("allPlaces() returns ${places.size} happy places anoymous=$isAnonymous") return places } /** * Get all details of a single place */ @GetMapping("{id}") @ResponseStatus(HttpStatus.OK) fun singleplace(@PathVariable id: UUID): ResponseEntity<Place> { return placeRepository.findById(id).map { place -> ResponseEntity.ok(place) }.orElse(ResponseEntity.notFound().build()) } /** * Post a new place */ //@RequestMapping(method = [RequestMethod.POST,RequestMethod.PUT]) @PostMapping @ResponseStatus(HttpStatus.CREATED) fun createNewPlace(@RequestBody place: Place): Place = placeRepository.save(place) /** * Updates a place, this operation neefs to be adapted if we add new attributes */ @PutMapping(value = ["{id}"]) @ResponseStatus(HttpStatus.OK) fun updatePlace(@Valid @RequestBody newPlace: Place, @PathVariable id: UUID): ResponseEntity<Place> { log.info("update () called for place $id") return placeRepository.findById(id).map { existingPlace -> val updatedPlace: Place = existingPlace .copy(name = newPlace.name, summary = newPlace.summary, notes = newPlace.notes, locationType = newPlace.locationType, areaCode = newPlace.areaCode, primaryUrl = newPlace.primaryUrl, imageUrl = newPlace.imageUrl, coordinates = newPlace.coordinates, authScope = newPlace.authScope ) ResponseEntity.ok().body(placeRepository.save(updatedPlace)) }.orElse(ResponseEntity.notFound().build()) } // https://www.callicoder.com/kotlin-spring-boot-mysql-jpa-hibernate-rest-api-tutorial/ @DeleteMapping("{id}") fun deletePlaceById(@PathVariable(value = "id") placeId: UUID): ResponseEntity<Void> { log.debug("Deleting place $placeId") return placeRepository.findById(placeId).map { place -> placeRepository.delete(place) ResponseEntity<Void>(HttpStatus.OK) }.orElse(ResponseEntity.notFound().build()) } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/config/WebConfig.kt package net.timafe.angkor.config import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.web.servlet.config.annotation.CorsRegistry import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.WebMvcConfigurer /** * Enable CORS for local development (profile dev) */ @Configuration @EnableWebMvc @Profile("!" + Constants.PROFILE_PROD) class WebConfig : WebMvcConfigurer { private val log: Logger = LoggerFactory.getLogger(this.javaClass) override fun addCorsMappings(registry: CorsRegistry) { log.trace("We've come for a good CORS") registry.addMapping(Constants.API_ROOT + "/**") .allowedOrigins("http://localhost:3000", "http://localhost:8080", "http://localhost:4200") .allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS") } } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/enums/LocationType.kt package net.timafe.angkor.domain.enums enum class LocationType { PLACE, ACCOM, BEACH, CITY, EXCURS, MONUM, MOUNT, ROAD } <file_sep>/ui/src/app/app.component.ts import {Component, OnInit} from '@angular/core'; import {MatIconRegistry} from '@angular/material/icon'; import {DomSanitizer} from '@angular/platform-browser'; import {Observable} from 'rxjs'; import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout'; import {catchError, map, shareReplay, tap} from 'rxjs/operators'; import {MatSnackBar} from '@angular/material/snack-bar'; import {LoadingService} from './shared/loading.service'; import {MatSidenav} from '@angular/material/sidenav'; import {MatDrawerToggleResult} from '@angular/material/sidenav/drawer'; import {EnvironmentService} from './environment.service'; import {NGXLogger} from 'ngx-logger'; import {AuthService} from './shared/auth.service'; import {User} from './domain/user'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit { title = 'TiMaFe on Air'; isLoading: boolean; constructor(private breakpointObserver: BreakpointObserver, private snackBar: MatSnackBar, public loadingService: LoadingService, public authService: AuthService, private logger: NGXLogger ) { } isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches), shareReplay() ); ngOnInit() { this.loadingService.isLoading.subscribe(async data => { this.isLoading = await data; }); } /** Result of the toggle promise that indicates the state of the drawer. */ // export declare type MatDrawerToggleResult = 'open' | 'close'; // https://angular.io/guide/observables-in-angular closeIfHandset(drawer: MatSidenav): Promise<MatDrawerToggleResult> { return new Promise<MatDrawerToggleResult>((resolve, reject) => { this.isHandset$.subscribe(isHandset => { if (isHandset) { drawer.close().then(result => { if (result !== 'close') this.logger.warn('unexpected return state ' + result + ' during close drawer'); }); resolve('close'); } else { this.logger.debug('deskop mode, keep open'); resolve('open'); } }); }); } } <file_sep>/ui/src/app/shared/auth.service.ts import { Injectable } from '@angular/core'; import { Location } from '@angular/common'; // import {EnvironmentService} from "../environment.service"; import {environment} from '../../environments/environment'; import {NGXLogger} from 'ngx-logger'; import {BehaviorSubject, Observable} from 'rxjs'; import {tap} from 'rxjs/operators'; import { share} from 'rxjs/operators'; import {HttpClient} from '@angular/common/http'; import {User} from '../domain/user'; // import { AuthServerProvider } from 'app/core/auth/auth-session.service'; /** * https://netbasal.com/angular-2-persist-your-login-status-with-behaviorsubject-45da9ec43243 * Persisting user authentication with BehaviorSubject in Angular */ @Injectable({ providedIn: 'root' }) export class AuthService { constructor(private http: HttpClient, private logger: NGXLogger, private location: Location ) { this.checkAuthenticated(); } public currentUser: User; // use .share() when creating the isLoginSubject Observable, so async pipes don’t create multiple subscriptions. isAuthenticatedSubject = new BehaviorSubject<boolean>(false); // A subject in Rx is both Observable and Observer. In this case, we only care about the Observable part, // letting other parts of our app the ability to subscribe to our Observable. isAuthenticated(): Observable<boolean> { return this.isAuthenticatedSubject.asObservable().pipe(share());; } login() { // If you have configured multiple OIDC providers, then, you can update this URL to /login. // It will show a Spring Security generated login page with links to configured OIDC providers. // location.href = `${location.origin}${this.location.prepareExternalUrl('oauth2/authorization/oidc')}`; this.logger.debug(location.origin,this.location.prepareExternalUrl('oauth2/authorization/cognito')); // location.href = `${location.origin}${this.location.prepareExternalUrl('oauth2/authorization/cognito')}`; location.href = `${environment.apiUrlRoot}/../..${this.location.prepareExternalUrl('oauth2/authorization/cognito')}`; } checkAuthenticated() { this.http.get<any>(environment.apiUrlRoot + '/authenticated') .subscribe(res => { this.logger.info('check auth='+res); this.setAuthenticated(res); if (res) { this.http.get<User>(environment.apiUrlRoot + '/account').subscribe( user => this.currentUser = user); } }); } setAuthenticated(state:boolean) { this.isAuthenticatedSubject.next(state); } logout() { this.logger.warn('logout user '); this.setAuthenticated(false); this.http.post(environment.apiUrlRoot + '/logout', {}, { observe: 'response' }).subscribe( response => { const data = response.body; this.logger.info(`todo call logoutUrl`); } // map((response: HttpResponse<any>) => { // to get a new csrf token call the api // this.http.get(SERVER_API_URL + 'api/account').subscribe(() => {}, () => {}); // return response; // }) ); /* logout(): Observable<any> { // logout from the server return this.http.post(SERVER_API_URL + 'api/logout', {}, { observe: 'response' }).pipe( map((response: HttpResponse<any>) => { // to get a new csrf token call the api this.http.get(SERVER_API_URL + 'api/account').subscribe(() => {}, () => {}); return response; }) ); } */ // this.authServerProvider.logout().subscribe(response => { // const data = response.body; // let logoutUrl = data.logoutUrl; // const redirectUri = `${location.origin}${this.location.prepareExternalUrl('/')}`; // // // if Keycloak, uri has protocol/openid-connect/token // if (logoutUrl.indexOf('/protocol') > -1) { // logoutUrl = logoutUrl + '?redirect_uri=' + redirectUri; // } else { // // Okta // logoutUrl = logoutUrl + '?id_token_hint=' + data.idToken + '&post_logout_redirect_uri=' + redirectUri; // } // window.location.href = logoutUrl; // }); // } } <file_sep>/api/README.md # Angkor API Backend 1. Copy [config.application.properties.tmpl](./config.application.properties.tmpl) to config.application.properties 1. Enter secrets etc. e.g. Database password 1. Make sure to set working directory to `api` folder in your IntelliJ Run Configuration <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/enums/NoteStatus.kt package net.timafe.angkor.domain.enums enum class NoteStatus { OPEN, IN_PROGRESS, IMPEDED, CLOSED } <file_sep>/tools/go.mod module github.com/tillkuhn/angkor/tools go 1.14 require ( github.com/sirupsen/logrus v1.6.0 ) <file_sep>/ui/src/app/shared/loading.service.ts import { Injectable } from '@angular/core'; import {BehaviorSubject} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class LoadingService { // A BehaviorSubject is an Observable with a default value public isLoading = new BehaviorSubject(false); constructor() { } setLoading(state:boolean) { this.isLoading.next(state); } } <file_sep>/docs/modules/ROOT/pages/db.adoc = Database and JPA :toc: == JPA https://vladmihalcea.com/prepersist-preupdate-embeddable-jpa-hibernate/[How to use @PrePersist and @PreUpdate on Embeddable with JPA and Hibernate with embedded Audit Entity] Create Audit Embeddable [source,java] ---- @Embeddable public class Audit { @Column(name = "created_on") private LocalDateTime createdOn; @PrePersist public void prePersist() { createdOn = LocalDateTime.now(); } // (...) } ---- The use as .... [source,java] ---- @Entity(name = "Something") public class Something { @Embedded private Audit audit = new Audit(); // (...) } ---- == ElefantSQL PostgreSQL as a Service In search of a free DB I found https://www.elephantsql.com/[www.elephantsql.com] which provide free plans for DBs up to *20MB* and *5 concurrent connections* which was perfectly sufficient for my project. Of course you can also host your own DB or use AWS managed https://aws.amazon.com/rds/?nc1=h_ls[RDS] service == Create local database [source,shell script] ---- $ psql select version(); PostgreSQL 11.5 (Ubuntu 11.5-3.pgdg18.04+1) create database angkor; create user angkor; grant all privileges on database angkor to angkor; $ psql -U rootuser angkor CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; $ psql -U angkor -d angkor -f import.sql ---- == Get all backups via API [source,shell script] ---- curl -u :xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx https://api.elephantsql.com/api/backup?db=my-db ---- == Drop all tables w/o dropping schema As you don't own the public schema in ElefantSQL, you can't drop the entire schema but https://stackoverflow.com/questions/3327312/how-can-i-drop-all-the-tables-in-a-postgresql-database[this] discussion helps [source,sql] ---- SELECT 'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;' from pg_tables WHERE schemaname = 'public'; ---- == Useful SQL To test, whether the index can be used, disable sequential scans in a test session (for debugging only!): `SET enable_seqscan = OFF;` == Resources to check * Don't load all attributes for summary: https://vladmihalcea.com/the-best-way-to-lazy-load-entity-attributes-using-jpa-and-hibernate/[The best way to lazy load entity attributes using JPA and Hibernate] * https://stackoverflow.com/questions/18896329/export-data-from-dynamodb[export-data-from-dynamodb] * https://tapoueh.org/blog/2018/04/postgresql-data-types-arrays/[Hashtags as Arrays,Indexing PostgreSQL Arrays for Statistics and Profit] * https://dba.stackexchange.com/questions/20974/should-i-add-an-arbitrary-length-limit-to-varchar-columns[Should I add an arbitrary length limit to VARCHAR columns?] <file_sep>/api/build.gradle.kts import org.jetbrains.kotlin.gradle.tasks.KotlinCompile buildscript { val kotlinVersion: String by System.getProperties() val postgresVersion: String by System.getProperties() dependencies { classpath("org.postgresql:postgresql:$postgresVersion") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") } } group = "com.github.tillkuhn" version = "0.0.1-SNAPSHOT" java.sourceCompatibility = JavaVersion.VERSION_11 plugins { val kotlinVersion: String by System.getProperties() val flywayVersion: String by System.getProperties() id("org.springframework.boot") version "2.3.2.RELEASE" id("io.spring.dependency-management") version "1.0.9.RELEASE" id("org.flywaydb.flyway") version flywayVersion kotlin("jvm") version kotlinVersion kotlin("plugin.spring") version kotlinVersion kotlin("plugin.jpa") version kotlinVersion kotlin("plugin.noarg") version kotlinVersion kotlin("plugin.allopen") version kotlinVersion // maven jacoco java } repositories { mavenCentral() maven { name = "jitpack.io" url = uri("https://jitpack.io") } } dependencies { // Spring implementation("org.springframework.boot:spring-boot-starter-data-jpa") implementation("org.springframework.boot:spring-boot-starter-actuator") implementation("org.springframework.boot:spring-boot-starter-oauth2-client") implementation("org.springframework.boot:spring-boot-starter-json") implementation("org.springframework.boot:spring-boot-starter-web") // since 2.3.1 we need to add validation starter ourselves // https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#validation-starter-no-longer-included-in-web-starters implementation("org.springframework.boot:spring-boot-starter-validation") // Kotlin - Use the Kotlin JDK 8 standard library. implementation("org.jetbrains.kotlin:kotlin-reflect") implementation(kotlin("stdlib-jdk8")) implementation(kotlin("reflect")) testImplementation(kotlin("test")) testImplementation(kotlin("test-junit5")) // Commons // implementation("commons-io:commons-io:2.6") implementation("org.apache.commons:commons-lang3:3.11") // Persistence val postgresVersion: String by System.getProperties() val flywayVersion: String by System.getProperties() implementation("org.postgresql:postgresql:$postgresVersion") implementation("org.flywaydb:flyway-core:$flywayVersion") // looks for classpath:db/migration implementation("com.vladmihalcea:hibernate-types-52:2.9.12") // https://vladmihalcea.com/how-to-map-java-and-sql-arrays-with-jpa-and-hibernate/ // Jackson JSON Parsing //val jacksonVersion: String = "2.11.1" // https://stackoverflow.com/questions/25184556/how-to-make-sure-spring-boot-extra-jackson-modules-are-of-same-version // For Gradle users, if you use the Spring Boot Gradle plugin you can omit the version number to adopt // the dependencies managed by Spring Boot, such as those Jackson modules implementation("com.fasterxml.jackson.module:jackson-module-kotlin") implementation("com.fasterxml.jackson.module:jackson-module-afterburner") implementation("com.fasterxml.jackson.core:jackson-databind") //implementation("com.fasterxml.jackson.dataformat:jackson-dataformats-text:2.11.0") implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") // AWS Integration(s) - currently disabled // implementation("com.github.derjust:spring-data-dynamodb:5.1.0") // Test Dependencies testImplementation("org.springframework.boot:spring-boot-starter-test") { exclude(group = "org.junit.vintage", module = "junit-vintage-engine") } } tasks.test { useJUnitPlatform() finalizedBy("jacocoTestReport") doLast { println("Code coverage report can be found at: file://$buildDir/reports/jacoco/test/html/index.html") } } tasks.withType<KotlinCompile> { kotlinOptions { freeCompilerArgs = listOf("-Xjsr305=strict") jvmTarget = "11" } } tasks.bootJar { archiveVersion.set("") // https://stackoverflow.com/questions/53123012/spring-boot-2-change-jar-name archiveFileName.set("app.jar") } jacoco { toolVersion = "0.8.5" } // https://kevcodez.de/posts/2018-08-19-test-coverage-in-kotlin-with-jacoco/ tasks.jacocoTestReport { reports { xml.setEnabled(true) } } tasks.bootRun.configure { systemProperty("spring.profiles.active", "default") } // Custom tasks for different spring profiles... tasks.register("bootRunClean") { group = "application" description = "Runs this project as a Spring Boot application with the clean db profile" doFirst { tasks.bootRun.configure { systemProperty("spring.profiles.active", "clean") } } finalizedBy("bootRun") } tasks.register("bootRunProd") { group = "application" description = "Runs this project as a Spring Boot application with the prod profile" doFirst { tasks.bootRun.configure { systemProperty("spring.profiles.active", "prod") } } finalizedBy("bootRun") } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/Note.kt package net.timafe.angkor.domain import com.fasterxml.jackson.annotation.JsonFormat import com.fasterxml.jackson.annotation.JsonInclude import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.enums.AuthScope import net.timafe.angkor.domain.enums.NoteStatus import org.hibernate.annotations.Type import java.time.LocalDate import java.time.LocalDateTime import java.util.* import javax.persistence.* @Entity @JsonInclude(JsonInclude.Include.NON_NULL) data class Note( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: UUID?, var summary: String, @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = Constants.JACKSON_DATE_FORMAT) var createdAt: LocalDateTime = LocalDateTime.now(), var createdBy: String = Constants.USER_ANONYMOUS, var dueDate: LocalDate?, @Enumerated(EnumType.STRING) @Column(columnDefinition = "status") @Type(type = "pgsql_enum") var status: NoteStatus = NoteStatus.OPEN, @Type(type = "list-array") @Column( name = "tags", columnDefinition = "text[]" ) override var tags: List<String> = listOf() ) : Taggable <file_sep>/ui/src/app/environment.service.ts import { Injectable, VERSION } from '@angular/core'; /* hack from https://github.com/angular/angular-cli/issues/3855#issuecomment-579719646 * use index.html to envsubst post build / runtime values */ @Injectable({ providedIn: 'root' }) export class EnvironmentService { version: string; mapboxAccessToken: string; // https://github.com/angular/angular/issues/1357#issuecomment-346084639 angularVersion = VERSION.full; // e.g. 10.0.7 constructor() { const windowEnv = (window as any).env; // console.log(this.angularVersion); this.version = windowEnv && windowEnv.VERSION !== '' && windowEnv.VERSION !== '${VERSION}' ? windowEnv.VERSION : 'latest'; this.mapboxAccessToken = windowEnv && windowEnv.MAT !== '' && windowEnv.MAT !== '${MAT}' ? windowEnv.MAT : 'no-token'; } } <file_sep>/api/Dockerfile # https://docs.docker.com/engine/reference/builder/#understand-how-arg-and-from-interact # default can be overwritten by --build-arg ARG FROM_TAG=jre-14.0.2_12-alpine FROM adoptopenjdk/openjdk14:$FROM_TAG # should be passed in from git describe --abbrev=0 ARG LATEST_REPO_TAG=latest # https://vsupalov.com/docker-build-time-env-values/ so we can use at runtime ENV VERSION=$LATEST_REPO_TAG # Possibility to set JVM options https://dzone.com/articles/spring-boot-run-and-build-in-docker ENV JAVA_OPTS "" VOLUME /tmp EXPOSE 8080 COPY ./build/libs/app.jar /app.jar # what about heap ? https://medium.com/faun/docker-sizing-java-application-326d39992592 # and https://stackoverflow.com/questions/44491257/how-to-reduce-spring-boot-memory-usage # use shell form to support JAVA_OPTS ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar app.jar" ] <file_sep>/ui/src/app/dishes/dishes.component.ts import { Component, OnInit } from '@angular/core'; import {ApiService} from '../shared/api.service'; import {EnvironmentService} from '../environment.service'; import {NGXLogger} from 'ngx-logger'; import {Dish} from '../domain/dish'; @Component({ selector: 'app-dishes', templateUrl: './dishes.component.html', styleUrls: ['./dishes.component.scss'] }) export class DishesComponent implements OnInit { displayedColumns: string[] = ['country', 'name']; data: Dish[] = []; constructor(private api: ApiService, private env: EnvironmentService, private logger: NGXLogger) { } ngOnInit() { this.api.getDishes() .subscribe((res: any) => { this.data = res; this.logger.debug('getDishes()', this.data); }, err => { this.logger.error(err); }); } } <file_sep>/ui/src/app/domain/dish.ts export interface Dish { id: string; name: string; areaCode: string; summary?: string; imageUrl?: string; // lon/länge, lat/breite tags?: string[]; } <file_sep>/api/src/test/kotlin/net/timafe/angkor/IntegrationTests.kt package net.timafe.angkor import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import net.timafe.angkor.config.Constants import net.timafe.angkor.domain.dto.POI import net.timafe.angkor.domain.Place import org.assertj.core.api.Assertions.assertThat import org.hamcrest.CoreMatchers.containsString import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.post @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles(Constants.PROFILE_TEST, Constants.PROFILE_CLEAN) // @ActiveProfiles(Constants.PROFILE_TEST) @AutoConfigureMockMvc class IntegrationTests(@Autowired val restTemplate: TestRestTemplate) { // https://www.baeldung.com/mockmvc-kotlin-dsl // https://github.com/eugenp/tutorials/blob/master/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt @Autowired lateinit var mockMvc: MockMvc @Autowired lateinit var objectMapper: ObjectMapper @Test @Throws(Exception::class) fun testPlacePost() { val mvcResult = mockMvc.post(Constants.API_DEFAULT_VERSION + "/places") { contentType = MediaType.APPLICATION_JSON content = objectMapper.writeValueAsString(Place(name = "hase", id = null, areaCode = "de", imageUrl = "http://", primaryUrl = "http://", summary = "nice place",notes="come back again")) accept = MediaType.APPLICATION_JSON }.andExpect { status { /*isOk*/ isCreated } content { contentType(MediaType.APPLICATION_JSON) } content { string(containsString("hase")) } jsonPath("$.name") { value("hase") } jsonPath("$.summary") { value("nice place") } /*content { json("{}") }*/ }.andDo { /* print ())*/ }.andReturn() val newPlace = objectMapper.readValue(mvcResult.response.contentAsString,Place::class.java) assertThat(newPlace.id).isNotNull() // objectMapper.writeValue(System.out,newPlace) } @Test @Throws(Exception::class) fun testGetDishes() { mockMvc.get(Constants.API_DEFAULT_VERSION + "/dishes") { }.andExpect { status { isOk } jsonPath("$") {isArray} }.andDo{print()} } @Test @Throws(Exception::class) fun testGetPois() { val mvcResult = mockMvc.get(Constants.API_DEFAULT_VERSION + "/pois") { }.andExpect { status { isOk } jsonPath("$") {isArray} }.andDo{ /* print() */}.andReturn() val actual: List<POI?>? = objectMapper.readValue(mvcResult.response.contentAsString, object : TypeReference<List<POI?>?>() {}) assertThat(actual?.size).isGreaterThan(0) } @Test @Throws(Exception::class) fun `Assert we get notes`() { mockMvc.get(Constants.API_DEFAULT_VERSION + "/notes") { }.andExpect { status { isOk } jsonPath("$") {isArray} } } @Test fun `Assert greeting content and status code`() { val entity = restTemplate.getForEntity<String>("/greeting",String::class.java) assertThat(entity.statusCode).isEqualTo(HttpStatus.OK) assertThat(entity.body).contains("World") } @Test fun `Assert we have geocodes`() { val entity = restTemplate.getForEntity<String>(Constants.API_DEFAULT_VERSION+"/geocodes",String::class.java) assertThat(entity.statusCode).isEqualTo(HttpStatus.OK) assertThat(entity.body).contains("Thailand") } } <file_sep>/ui/src/app/admin/metrics/metrics.component.ts import { Component, OnInit } from '@angular/core'; import {ApiService} from '../../shared/api.service'; import {NGXLogger} from 'ngx-logger'; import {FormBuilder} from '@angular/forms'; import {MatSnackBar} from '@angular/material/snack-bar'; import {Note} from '../../domain/note'; import {Metric} from './metric'; @Component({ selector: 'app-metrics', templateUrl: './metrics.component.html', }) export class MetricsComponent implements OnInit { data: Metric[] = []; displayedColumns: string[] = ['name', 'value', 'description']; constructor(private api: ApiService, private logger: NGXLogger) { } ngOnInit(): void { this.api.getMetrics().subscribe(data => this.data = data); } } <file_sep>/ui/src/app/places/places.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { PlacesComponent } from './places.component'; import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; import {LoggerTestingModule} from 'ngx-logger/testing'; import {RouterTestingModule} from '@angular/router/testing'; describe('PlacesComponent', () => { let component: PlacesComponent; let fixture: ComponentFixture<PlacesComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ PlacesComponent ], imports: [RouterTestingModule, LoggerTestingModule, HttpClientTestingModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PlacesComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/ui/src/app/app-routing.module.ts import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {PlacesComponent} from './places/places.component'; import {PlaceDetailComponent} from './place-detail/place-detail.component'; import {PlaceAddComponent} from './place-add/place-add.component'; import {PlaceEditComponent} from './place-edit/place-edit.component'; import {CommonModule} from '@angular/common'; import {MapComponent} from './map/map.component'; import {HomeComponent} from './home/home.component'; import {DishesComponent} from './dishes/dishes.component'; import {NotesComponent} from './notes/notes.component'; import {MetricsComponent} from './admin/metrics/metrics.component'; const routes: Routes = [ { path: 'home', component: HomeComponent, data: {title: 'Home'} }, { path: 'map', component: MapComponent, data: {title: 'Map'} }, { path: 'dishes', component: DishesComponent, data: {title: 'Dishes'} }, { path: 'notes', component: NotesComponent, data: {title: 'Notes'} }, { path: 'places', component: PlacesComponent, data: {title: 'List of Places'} }, { path: 'place-details/:id', component: PlaceDetailComponent, data: {title: 'Place Details'} }, { path: 'place-add', component: PlaceAddComponent, data: {title: 'Add Place'} }, { path: 'place-edit/:id', component: PlaceEditComponent, data: {title: 'Edit Place'} }, { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'admin/metrics', component: MetricsComponent, data: {title: 'Admin Metrics'} }, ]; @NgModule({ imports: [CommonModule, RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/ui/src/app/home/home.component.ts // Fix karma tests: // https://www.hhutzler.de/blog/angular-6-using-karma-testing/#Error_Datails_NullInjectorError_No_provider_for_Router import { Component, OnInit } from '@angular/core'; import {AuthService} from '../shared/auth.service'; import {NGXLogger} from 'ngx-logger'; import {getTableUnknownDataSourceError} from '@angular/cdk/table/table-errors'; import {MasterDataService} from '../shared/master-data.service'; import {MatIconRegistry} from '@angular/material/icon'; import {DomSanitizer} from '@angular/platform-browser'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.sass'] }) export class HomeComponent implements OnInit { constructor(public authService: AuthService, private logger: NGXLogger, public masterData: MasterDataService, private matIconRegistry: MatIconRegistry, private domSanitizer: DomSanitizer) {} account: any; greeting = 'Welcome home, TiMaFe guest!'; ngOnInit(): void { // https://www.digitalocean.com/community/tutorials/angular-custom-svg-icons-angular-material this.matIconRegistry.addSvgIcon( `backpack`, this.domSanitizer.bypassSecurityTrustResourceUrl('../assets/backpack.svg') ); this.matIconRegistry.addSvgIcon( `noodlebowl`, this.domSanitizer.bypassSecurityTrustResourceUrl('../assets/noodlebowl.svg') ); } login() { this.logger.info('logint'); this.authService.login(); } logout() { // this.loginService.login(); this.logger.warn('logout to be implemented'); } } <file_sep>/ui/src/app/domain/note.ts import { Moment} from 'moment'; export interface Note { id: string; summary: string; status: string; createdAt: Moment; dueDate: Moment; createdBy: string; tags: string[]; } export const NOTE_TAGS: string[] = ['new','urgent','place','dish','music']; <file_sep>/docs/modules/ROOT/pages/infra.adoc = Angkor Infrastructure == In a Nutshell ... // https://real-world-plantuml.com/?cursor=Ci8SKWoVc35yZWFsLXdvcmxkLXBsYW50dW1schALEgNVbWwYgICAgNmfvgkMGAAgAA&type=component // https://github.com/yfuruyama/real-world-plantuml [plantuml,"PlantUML Test",png] ---- @startuml title Angkor Deploy and Runtime Components skinparam handwritten false actor User as user actor Developer as developer frame "AWS" { node "EC2 t3a.nano" { frame systemd { [Deploy Webhook] as webhook } frame "docker" { [UI / Proxy (nginx)] as ui [API (Spring Boot)] as api } } frame "AWS Services" { database "S3 Bucket" as s3 [Cognito] as cognito } } cloud "Cloud Services" { frame GitHub as github { database "Code Repo" as code [Action Workflows] as actions } frame DockerHub as dockerhub { database "api-repo" as apirepo database "ui-repo" as uirepo } frame "ElephantSQL" { database "Test DB" as testdb database "Prod DB" as proddb } } developer --> code: commit user ----> ui: https code -> actions actions --> dockerhub: push actions --> webhook: trigger actions --> testdb: upload actions --> s3 api -- proddb: jdbc ui ---> s3 ui --> api: proxy api --> cognito apirepo --> api: pull uirepo --> ui: pull webhook --> docker: reload @enduml ---- <file_sep>/ui/src/app/app.module.ts import {AppComponent} from './app.component'; import {AppRoutingModule} from './app-routing.module'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {BrowserModule} from '@angular/platform-browser'; import {DishesComponent} from './dishes/dishes.component'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {HomeComponent} from './home/home.component'; import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http'; import {LayoutModule} from '@angular/cdk/layout'; import {LoggerModule, NgxLoggerLevel} from 'ngx-logger'; import {MatAutocompleteModule} from '@angular/material/autocomplete'; import {MapComponent} from './map/map.component'; import {MatButtonModule} from '@angular/material/button'; import {MatCardModule} from '@angular/material/card'; import {MatChipsModule} from '@angular/material/chips'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatIconModule} from '@angular/material/icon'; import {MatInputModule} from '@angular/material/input'; import {MatListModule} from '@angular/material/list'; import {MatMenuModule} from '@angular/material/menu'; import {MatPaginatorModule} from '@angular/material/paginator'; import {MatProgressBarModule} from '@angular/material/progress-bar'; import {MatProgressSpinnerModule} from '@angular/material/progress-spinner'; import {MatSelectModule} from '@angular/material/select'; import {MatSidenavModule} from '@angular/material/sidenav'; import {MAT_SNACK_BAR_DEFAULT_OPTIONS, MatSnackBarModule} from '@angular/material/snack-bar'; import {MatSortModule} from '@angular/material/sort'; import {MatTableModule} from '@angular/material/table'; import {MatToolbarModule} from '@angular/material/toolbar'; import {MomentModule} from 'ngx-moment'; import {NgModule} from '@angular/core'; import {NgxMapboxGLModule} from 'ngx-mapbox-gl'; import {NotesComponent} from './notes/notes.component'; import {PlaceAddComponent} from './place-add/place-add.component'; import {PlaceDetailComponent} from './place-detail/place-detail.component'; import {PlaceEditComponent} from './place-edit/place-edit.component'; import {PlacesComponent} from './places/places.component'; import {MatDatepickerModule} from '@angular/material/datepicker'; import {MatNativeDateModule} from '@angular/material/core'; import {LoadingInterceptor} from './shared/loading.interceptor'; import {MatDialogModule} from '@angular/material/dialog'; import { ConfirmDialogComponent } from './shared/confirm-dialog/confirm-dialog.component'; import { MetricsComponent } from './admin/metrics/metrics.component'; // imports makes the exported declarations of other modules available in the current module // declarations are to make directives (including components and pipes) from the current module available to other // directives in the current module. Selectors of directives components or pipes are only matched against the HTML // if they are declared or imported. // providers are to make services and values known to DI (dependency injection). They are added to the root scope and // they are injected to other services or directives that have them as dependency. @NgModule({ declarations: [ AppComponent, PlacesComponent, PlaceDetailComponent, PlaceAddComponent, PlaceEditComponent, MapComponent, HomeComponent, DishesComponent, NotesComponent, ConfirmDialogComponent, MetricsComponent, ], imports: [ AppRoutingModule, BrowserAnimationsModule, BrowserModule, FormsModule, HttpClientModule, LayoutModule, LayoutModule, MatAutocompleteModule, MatButtonModule, MatCardModule, MatChipsModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatSidenavModule, MatSnackBarModule, MatSortModule, MatTableModule, MatToolbarModule, NgxMapboxGLModule, ReactiveFormsModule, LoggerModule.forRoot({ // serverLoggingUrl: '/api/logs', level: NgxLoggerLevel.DEBUG, // serverLogLevel: NgxLoggerLevel.ERROR, disableConsoleLogging: false }), // https://www.npmjs.com/package/ngx-moment MomentModule.forRoot({ relativeTimeThresholdOptions: { m: 59 } }), MatSelectModule, MatDatepickerModule, MatDialogModule ], exports: [], providers: [ // intercept all http requests for progess (aka loading) bar {provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true}, // default duration for snackbar messages // https://material.angular.io/components/snack-bar/overview#setting-the-global-configuration-defaults {provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: {duration: 2500}} ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/api/src/main/kotlin/net/timafe/angkor/domain/dto/MetricDTO.kt package net.timafe.angkor.domain.dto data class MetricDTO ( var name: String, var description: String?, var value: Double, var baseUnit: String? ) /* Example metric repsponse "name" : "process.uptime", "description" : "The uptime of the Java virtual machine", "baseUnit" : "seconds", "measurements" : [ { "statistic" : "VALUE", "value" : 19.572 } ], "availableTags" : [ ] */ <file_sep>/ui/src/app/domain/place.ts /* * Location types also used in * dropdown for places */ import {Moment} from 'moment'; import {ListItem} from './shared'; export interface Place { id: string; name: string; areaCode: string; summary?: string; notes?: string; primaryUrl?: string; imageUrl?: string; locationType?: string; coordinates?: number[]; // lon/länge, lat/breite createdAt?: Moment; updatedAt?: Moment; authScope?: string | ListItem; // Todo typesafe } // https://basarat.gitbook.io/typescript/type-system/index-signatures#typescript-index-signature export interface LocationType { label: string; icon: string; value: string; } <file_sep>/ui/scratch.ts /** * This is just a scratch file to execute plan typescript from the shell * yarn global add ts-node * ts-node scratch.js */ import {SmartCoordinates} from './src/app/domain/smart-coordinates'; export declare const enum SomeState { OPEN = 0, CLOSED = 2 } interface Place { name: string; country: string; summary?: string; } // The lat(itude) of Bangkok, Thailand is 13.736717, and the lon(gitude) is 100.523186. const point = new SmartCoordinates([100.523186, 13.736717]); console.log(point.latLonDeg, SomeState.CLOSED ); console.log(point.gmapsUrl); console.log(new SmartCoordinates([1, 2])); console.log(new SmartCoordinates('13.75633 100.50177').gmapsUrl); console.log('lumpi,',new SmartCoordinates('https://www.google.com/maps/place/Lumphini+Park/@13.7314029,100.5392509,17z/data=!4m12!1m6!')); // console.log(new GeoPoint('horst')); const place: Place = {name: '<NAME>', summary: 'High Towers', country: 'my'}; const place2: Place = {...place, name: 'Georgetown'}; console.log(place, place2); hase('eins','zwei'); function hase(...args: string[]) { console.log(args); }
b1f1d5897a0fd7bd5f70a9304d31b7aac94cf55e
[ "Markdown", "Makefile", "AsciiDoc", "Dockerfile", "Python", "Go Module", "TypeScript", "Go", "Kotlin", "Shell" ]
84
Kotlin
tillkuhn/kotlin-angular
4fb2b66b563a4a1141b6c34c61dd280171badcc0
14032454f8d914899be21566a43fadb97c293cd7
refs/heads/master
<repo_name>Alex111one/FindRestaurants<file_sep>/Location/FoursquareClient.swift // // FoursquareClient.swift // Location // // Created by One on 25/04/2017. // Copyright © 2017 AlexOne. All rights reserved. // import Foundation // according to Foursquare API, every case is a member of endpoint (developer.foursquare.com). This makes adding functionality easyer enum Foursquare: Endpoint { case venues(VenueEndpoint) enum VenueEndpoint: Endpoint { case search(clientID: String, clientSecret: String, coordinate: Coordinate, category: Category, query: String?, searchRadius: Int?, limit: Int?) // id for what we are searching for enum Category: CustomStringConvertible { case food([FoodCategory]?) // also from Foursquare API. Category for concrete food enum FoodCategory: String { case Japanese = "4bf58dd8d48988d111941735" } var description: String { switch self { case .food(let categories): if let categories = categories { let commaSeparatedString = categories.reduce("") { categoryString, category in "\(categoryString),(\(category.rawValue)" } // removing "," if categoryString is empty return commaSeparatedString.substring(from: commaSeparatedString.index(after: commaSeparatedString.startIndex)) } else { // returning top level Food (for all food instead of category) return "4d4b7105d754a06374d81259" } } } } // MARK: - Venue Endpoint conforming to Endpoint var baseURL: String { return "https://api.foursquare.com" } var path: String { switch self { case .search: return "/v2/venues/search" } } // from Foursquare API to help private struct ParameterKeys { static let clientID = "client_id" static let clientSecret = "client_secret" static let version = "v" static let category = "categoryId" static let location = "ll" static let query = "query" static let limit = "limit" static let searchRadius = "radius" } private struct DefaultValues { static let version = "20160301" static let limit = "50" static let searchRadius = "2000" } // where most of the work happens var parameters: [String : AnyObject] { switch self { case .search(let clientID, let clientSecret, let coordinate, let category, let query, let searchRadius, let limit): var parameters: [String: AnyObject] = [ ParameterKeys.clientID: clientID as AnyObject, ParameterKeys.clientSecret: clientSecret as AnyObject, ParameterKeys.version: DefaultValues.version as AnyObject, ParameterKeys.location: coordinate.description as AnyObject, ParameterKeys.category: category.description as AnyObject ] if let searchRadius = searchRadius { parameters[ParameterKeys.searchRadius] = searchRadius as AnyObject } else { parameters[ParameterKeys.searchRadius] = DefaultValues.searchRadius as AnyObject } if let limit = limit { parameters[ParameterKeys.limit] = limit as AnyObject? } else { parameters[ParameterKeys.limit] = DefaultValues.limit as AnyObject? } if let query = query { parameters[ParameterKeys.query] = query as AnyObject? } return parameters } } } // MARK: - Foursqueare conforming to Endpoint var baseURL: String { switch self { case .venues(let endpoint): return endpoint.baseURL } } var path: String { switch self { case .venues(let endpoint): return endpoint.path } } var parameters: [String : AnyObject] { switch self { case .venues(let endpoint): return endpoint.parameters } } } final class FoursquareClient: APIClient { let configuration: URLSessionConfiguration lazy var session: URLSession = { return URLSession(configuration: self.configuration) }() let clientID: String let clientSecret: String init(configuration: URLSessionConfiguration, clientID: String, clientSecret: String) { self.configuration = configuration self.clientID = clientID self.clientSecret = clientSecret } convenience init(clientID: String, clientSecret: String) { self.init(configuration: .default, clientID: clientID, clientSecret: clientSecret) } func fetchRestaurantsFor(_ location: Coordinate, category: Foursquare.VenueEndpoint.Category, query: String? = nil, searchRadius: Int? = nil, limit: Int? = nil, completion: @escaping (APIResult<[Venue]>) -> Void) { let searchEndpoint = Foursquare.VenueEndpoint.search(clientID: self.clientID, clientSecret: self.clientSecret, coordinate: location, category: category, query: query, searchRadius: searchRadius, limit: limit) let endpoint = Foursquare.venues(searchEndpoint) fetch(endpoint, parse: { json -> [Venue]? in guard let venues = json["response"]?["venues"] as? [[String: AnyObject]] else { return nil } // "flatMap" because Venue() is a failable initializer. When it can't be created, it will return nil to the array // "flatMap" removes all nil values and return only non-optional values. return venues.flatMap { venueDict in return Venue(JSON: venueDict) } }, completion: completion) } } <file_sep>/README.md [![Platform](http://img.shields.io/badge/platform-ios-blue.svg?style=flat )](https://www.apple.com/ios/ios-10/) [![Swift Version](https://img.shields.io/badge/swift-3.0-yellow.svg?style=flat)](https://swift.org) [![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](http://mit-license.org) # FindRestaurants ### Networking, Core Location and MapKit practice. Основной функционал приложения - наглядно отображать ближайшие к пользователю рестораны с кратким описанием на карте. Необходимая информация предоставляется сервером developer.foursquare.com. Данные о ближайших заведениях основываются на геолокации пользователя. Для наглядности используется `MapView`. При необходимости, код можно легко менять с целью получения других сведений: достопримечательностей, клубов, музеев и т.д. <p align="center"> <img src="https://cloud.githubusercontent.com/assets/23423988/25395999/a273d3ea-29eb-11e7-823c-06720c8baf88.png" alt="Image") /> <img src="https://cloud.githubusercontent.com/assets/23423988/25395998/a26c8b30-29eb-11e7-9964-a24a8c0a1eb9.png" alt="Image") /> </p> Первый запуск приложения сопровождается пояснительными инструкциями (`UIScrollView` and `UIPageControl` practice). Информация о тексте и картинке передаётся в отдельный `.xib` файл. Навигация к следующей странице осуществляется по `SwipeGesture`. <p align="center"> <img src="https://cloud.githubusercontent.com/assets/23423988/25405365/c29ebe26-2a0b-11e7-8520-eb5f31dd34e5.gif" alt="Image") /> </p> ## Used - FourSquare API without user authentication - Search by location - Construct more complex `url` with query parameters - `MapKIt`, `CoreLocation` frameworks - `UITableView` search - Delegation (location, map, search) - `UIScrollView`, `UIPageControl` ## To do - [x] Additional information by tapping on a pin - [ ] Add more groups: museums, clubs, monuments. ## License FindRestaurants is available under the MIT license. See the LICENSE file for more info. <file_sep>/Location/APIClient.swift // // APIClient.swift // Location // // Created by One on 23/04/2017. // Copyright © 2017 AlexOne. All rights reserved. // import Foundation public let MissingHTTPResponseError: Int = 10 public let UnexpectedResponseError: Int = 20 // conforming types have to implement init that constructs an instance using dictionary protocol JSONDecodable { init?(JSON: [String : AnyObject]) } // to avoid strings in URL endpoints protocol Endpoint { var baseURL: String { get } var path: String { get } var parameters: [String: AnyObject] { get } } extension Endpoint { // creating an object that represents a single name-value pair for an item in query portion of url var queryComponents: [URLQueryItem] { var components = [URLQueryItem]() // iterating through Endpoint protocol's "parameters" and getting key and value out of it for (key, value) in parameters { let queryItem = URLQueryItem(name: key, value: "\(value)") components.append(queryItem) } return components } var request: URLRequest { // constructing result URL from various parts - baseURL, path, and queryComponents var components = URLComponents(string: baseURL)! components.path = path components.queryItems = queryComponents let url = components.url! // passing result url return URLRequest(url: url) } } typealias JSON = [String: AnyObject] typealias JSONCompletion = (JSON?, HTTPURLResponse?, NSError?) -> Void typealias JSONTask = URLSessionDataTask // this enum used for the completion handler of "fetch" method enum APIResult<T> { case success(T) case failure(Error) } // main protocol APIClient { var configuration: URLSessionConfiguration { get } var session: URLSession { get } // simply take a request object, create a data task with session func jsonTask(withRequest request: URLRequest, completion: @escaping JSONCompletion) -> JSONTask func fetch<T: JSONDecodable>(_ request: URLRequest, parse: @escaping (JSON) -> T?, completion: @escaping (APIResult<T>) -> Void) } extension APIClient { // implementation func jsonTask(withRequest request: URLRequest, completion: @escaping JSONCompletion) -> JSONTask { let task = session.dataTask(with: request, completionHandler: { data, response, error in // checking response guard let HTTPResponse = response as? HTTPURLResponse else { return } // should contain data != nil if data == nil { if let error = error { completion(nil, HTTPResponse, error as NSError?) } } else { switch HTTPResponse.statusCode { case 200: // happy path do { // receive JSON representation of response let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : AnyObject] completion(json, HTTPResponse, nil) } catch let error as NSError { completion(nil, HTTPResponse, error) } default: print("Received HTTP response: \(HTTPResponse.statusCode), which was not handled") } } }) return task } // parsing implementation func fetch<T>(_ request: URLRequest, parse: @escaping (JSON) -> T?, completion: @escaping (APIResult<T>) -> Void) { let task = jsonTask(withRequest: request) { json, response, error in DispatchQueue.main.async { guard let json = json else { if let error = error { completion(.failure(error)) } else { // TODO: Implement error handling } return } if let resource = parse(json) { completion(.success(resource)) } else { return } } } task.resume() } func fetch<T: JSONDecodable>(_ endpoint: Endpoint, parse: @escaping (JSON) -> [T]?, completion: @escaping (APIResult<[T]>) -> Void) { let request = endpoint.request let task = jsonTask(withRequest: request) { json, response, error in DispatchQueue.main.async { guard let json = json else { if let error = error { completion(.failure(error)) } else { // TODO: Implement error handling } return } if let resource = parse(json) { completion(.success(resource)) } else { return } } } task.resume() } } <file_sep>/Location/RestaurantCell.swift // // RestaurantCell.swift // Location // // Created by One on 25/04/2017. // Copyright © 2017 AlexOne. All rights reserved. // import UIKit class RestaurantCell: UITableViewCell { @IBOutlet weak var restaurantTitleLabel: UILabel! @IBOutlet weak var restaurantCheckinLabel: UILabel! @IBOutlet weak var restaurantCategoryLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } <file_sep>/Location/TutorialController.swift // // RestaurantCell.swift // Location // // Created by One on 25/04/2017. // Copyright © 2017 AlexOne. All rights reserved. // import UIKit class TutorialController: UIViewController { @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var button: UIButton! // массив dictionary с данными. Картинка и текст. let tourData = [ [ "image" : "introtour01", "title" : "Поиск кафе и ресторанов основан на вашем местоположении", ], [ "image" : "introtour02", "title" : "Ближайшие к вам заведения обозначены маркерами на карте", ], [ "image" : "introtour03", "title" : "Вы можете получить дополнительную информацию нажав на маркер", ], [ "image" : "introtour04", "title" : "Используйте поиск для фильтрации ближайших мест", ] ] // именно viewDidAppear, т.к. view.bounds здесь сформированы. (в отличае от viewDidLoad) override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // графическая настройка scrollView.layer.cornerRadius = 15 scrollView.backgroundColor = UIColor(colorLiteralRed: 161/255.0, green: 194/255.0, blue: 255/255.0, alpha: 1.0) view.backgroundColor = UIColor(colorLiteralRed: 101/255.0, green: 154/255.0, blue: 235/255.0, alpha: 1.0) button.layer.cornerRadius = 20 // возможность перелистывать ScrollView постранично scrollView.isPagingEnabled = true // для имплементации scrollViewDelegate и scrollViewDidScroll scrollView.delegate = self // заполнение ScrollView setupPageViews() } // создание и заполнение Page данными func createPageView(data: [String: String]) -> PageView { let pageView = PageView.loadFromNib() // передача данных из массива pageView.configure(data: data) return pageView } // заполнение ScrollView func setupPageViews() { // счетчик для ширины var totalWidth: CGFloat = 0 // устанавливает Images рядом друг с другом подряд, справа. for data in tourData { let pageView = createPageView(data: data) pageView.frame = CGRect(origin: CGPoint(x: totalWidth - 10, y: 0), size: view.bounds.size) // -10 т.к. отступ scrollView.addSubview(pageView) // увеличение общей ширины на добавленный image (-20 т.к. отступ от края) totalWidth += pageView.bounds.size.width - 20 } // один из ключевых параметров ScrollView scrollView.contentSize = CGSize(width: totalWidth, height: scrollView.bounds.size.height-50) } // перемещение ScrollView по нажатию Button (основываясь на Page Control) @IBAction func buttonAction(_ sender: Any) { var frame = scrollView.frame frame.origin.x = frame.size.width * CGFloat(pageControl.currentPage + 1) frame.origin.y = 0 scrollView.scrollRectToVisible(frame, animated: true) } } // реализация связи с Page Contorl extension TutorialController: UIScrollViewDelegate { // необходимо знать ширину страницы. Из этого делается вывод, на какой по счету странице находимся func scrollViewDidScroll(_ scrollView: UIScrollView) { // общая ширина делится на количество images let pageWidth = Int(scrollView.contentSize.width) / tourData.count // передача номера конкретной страницы в Page Control pageControl.currentPage = Int(scrollView.contentOffset.x) / pageWidth } } <file_sep>/Location/PageView.swift // // PageView.swift // Tutorial // // Created by One on 23/02/2017. // Copyright © 2017 One. All rights reserved. // import UIKit class PageView: UIView { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! @IBOutlet weak var step: UILabel! // данная функция класса PageView будет загружать содержимое xib файла в ScrollView - картинку и текст. class func loadFromNib() -> PageView { let bundle = Bundle(for: self) // доступ в соответсвтии с Identity Inspector let nib = UINib(nibName: "PageView", bundle: bundle) // pageView let view = nib.instantiate(withOwner: self, options: nil)[0] as! PageView return view } // заполнение label and image соотвествующими данными из массива func configure(data: [String: String]) { label.text = data["title"] let image = UIImage(named: data["image"]!) imageView.image = image } }
1b6047b3c4ddc45dd00c8aab60cdb31619148c5a
[ "Swift", "Markdown" ]
6
Swift
Alex111one/FindRestaurants
022fc195fba614d0502f792bcee7be90fd0cf04e
32efb0b74d978c454903b1af8fd93b543dc95adb
refs/heads/master
<repo_name>mishraaditya595/Khabar-News-App<file_sep>/app/src/main/java/com/vob/repository/NewsRepository.kt package com.vob.repository import com.vob.api.RetrofitInstance import com.vob.db.ArticleDatabase import com.vob.models.Article class NewsRepository(val db: ArticleDatabase) { suspend fun getBreakingNews(countryCode: String, pageNumber: Int) = RetrofitInstance.api.getBreakingNews(countryCode, pageNumber) suspend fun getGeneralNews(countryCode: String, pageNumber: Int, category: String) = RetrofitInstance.api.getGeneralNews(countryCode, category, pageNumber ) suspend fun searchNews(searchQuery: String, pageNumber: Int) = RetrofitInstance.api.searchForNews(searchQuery, pageNumber) suspend fun upsert(article: Article) = db.getArticleDao().upsert(article) fun getSavedNews() = db.getArticleDao().getAllArticles() suspend fun deleteArticle(article: Article) = db.getArticleDao().deleteArticle(article) }<file_sep>/app/src/main/java/com/vob/ui/fragments/ArticleFragment.kt package com.vob.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebViewClient import androidx.navigation.fragment.navArgs import com.google.android.material.snackbar.Snackbar import com.vob.MainActivity import com.vob.R import com.vob.ui.NewsViewModel import kotlinx.android.synthetic.main.fragment_article.* class ArticleFragment : Fragment() { lateinit var viewModel: NewsViewModel val articleFragmentArgs: ArticleFragmentArgs by navArgs() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_article, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = (activity as MainActivity).viewModel webview_PB.visibility = View.VISIBLE Snackbar.make(view, "Loading news article", Snackbar.LENGTH_LONG).show() val article = articleFragmentArgs.article webView.apply { webViewClient = WebViewClient() loadUrl(article.url) } saved_button_fab.setOnClickListener { viewModel.saveArticle(article) Snackbar.make(view, "Article saved successfully", Snackbar.LENGTH_SHORT).show() } } } <file_sep>/app/src/main/java/com/vob/ui/LoginActivity.kt package com.vob.ui import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.GoogleAuthProvider import com.vob.MainActivity import com.vob.R import com.vob.util.Constants.Companion.REQUEST_CODE_GOOGLE_SIGN_IN import kotlinx.android.synthetic.main.activity_login.* import java.lang.Exception class LoginActivity : AppCompatActivity() { lateinit var auth: FirebaseAuth lateinit var googleSignInClient: GoogleSignInClient override fun onStart() { super.onStart() val currentUser = auth.currentUser if(currentUser != null) { startActivity(Intent(this, MainActivity::class.java)) finish() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) auth = FirebaseAuth.getInstance() signin_button.setOnClickListener { val options = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.webclient_id)) .requestEmail() .build() googleSignInClient = GoogleSignIn.getClient(this, options) val signInIntent = googleSignInClient.signInIntent startActivityForResult(signInIntent, REQUEST_CODE_GOOGLE_SIGN_IN) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if(requestCode == REQUEST_CODE_GOOGLE_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { val account = task.getResult(ApiException::class.java) firebaseAuthWithGoogle(account?.idToken!!) } catch (e: Exception) { Toast.makeText(this, "Google Sign In Failed ${e.message}", Toast.LENGTH_LONG).show() } } } private fun firebaseAuthWithGoogle(idToken: String) { val credential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if(task.isSuccessful) { Toast.makeText(this, "Login successful", Toast.LENGTH_LONG).show() startActivity(Intent(this,MainActivity::class.java)) } else { Toast.makeText(this, "LogIn failed", Toast.LENGTH_LONG).show() } } } }<file_sep>/app/src/main/java/com/vob/ui/MainActivity.kt package com.vob import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdView import com.google.android.gms.ads.MobileAds import com.vob.db.ArticleDatabase import com.vob.ui.fragments.HomeFragment import com.vob.ui.fragments.SavedNewsFragment import com.vob.ui.fragments.SearchFragment import com.vob.repository.NewsRepository import com.vob.ui.NewsViewModel import com.vob.ui.NewsViewModelProviderFactory import com.vob.ui.SettingsActivity import com.vob.ui.fragments.LocationBasedNewsFraagment import com.vob.util.Constants.Companion.ADMOB_APP_ID import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { lateinit var viewModel: NewsViewModel private lateinit var mAdView: AdView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mAdView = findViewById(R.id.adView) MobileAds.initialize(this, ADMOB_APP_ID) val adRequest = AdRequest.Builder().build() mAdView.loadAd(adRequest) val newsRepository = NewsRepository(ArticleDatabase(this)) val viewModelProviderFactory = NewsViewModelProviderFactory(application, newsRepository) viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java) setSupportActionBar(app_toolbar) //to setup the app's action bar loadFragment(HomeFragment()) //to make home fragment as the default fragment bottom_navigation_view.setOnNavigationItemSelectedListener { when (it.itemId) { R.id.home_item -> { loadFragment(HomeFragment()) return@setOnNavigationItemSelectedListener true } R.id.location_based_news_item -> { loadFragment(LocationBasedNewsFraagment()) return@setOnNavigationItemSelectedListener true } R.id.search_item -> { loadFragment(SearchFragment()) return@setOnNavigationItemSelectedListener true } R.id.saved_news_item -> { loadFragment(SavedNewsFragment()) return@setOnNavigationItemSelectedListener true } else -> { return@setOnNavigationItemSelectedListener false } } } } private fun loadFragment(fragment: Fragment) { // load fragment val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.toolbar_menu,menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.item_settings -> { startActivity(Intent(this, SettingsActivity::class.java)) } } return true } }<file_sep>/app/src/main/java/com/vob/api/NewsAPI.kt package com.vob.api import com.vob.models.NewsResponse import com.vob.util.Constants.Companion.API_KEY import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface NewsAPI { @GET("v2/top-headlines") suspend fun getBreakingNews( @Query("country")countryCode: String = "in", @Query("page")pageNumber: Int = 1, @Query("apiKey")apiKey: String = API_KEY ): Response<NewsResponse> @GET("v2/everything") suspend fun searchForNews( @Query("q")searchQuery: String, @Query("page")pageNumber: Int = 1, @Query("apiKey")apiKey: String = API_KEY ): Response<NewsResponse> @GET("v2/top-headlines") suspend fun getGeneralNews( @Query("country") countryCode: String = "in", @Query("category") category: String = "general", @Query("page") pageNumber: Int = 1, @Query("apiKey") apiKey: String = API_KEY ): Response<NewsResponse> }<file_sep>/app/src/main/java/com/vob/NewsApplication.kt package com.vob import android.app.Application class NewsApplication: Application() { }<file_sep>/app/src/main/java/com/vob/util/Constants.kt package com.vob.util class Constants { companion object{ const val API_KEY = "396f74a6d2ef45ad9f4aa86d7063c289" const val BASE_URL = "https://newsapi.org" const val SEARCH_NEWS_TIME_DELAY = 500L const val QUERY_PAGE_SIZE = 1 const val REQUEST_CODE_GOOGLE_SIGN_IN = 0 const val webClient_ID = "903066228484-uskbngkkh21ghqittu1i1f3qfokdai3n.apps.googleusercontent.com" const val ADMOB_APP_ID = "ca-app-pub-9893869558337815~1890181144" const val ADMOB_AD_UNIT_ID = "ca-app-pub-9893869558337815/4686545507" } }<file_sep>/app/src/main/java/com/vob/adapters/TabAdapter.kt package com.vob.adapters import android.content.Context import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import com.vob.ui.fragments.GeneralNewsFragment import com.vob.ui.fragments.HomeFragment import com.vob.ui.fragments.TrendingNewsFragment class TabAdapter( private val context: Context, fm: FragmentManager, internal var totalTabs: Int ): FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment { when(position){ 0 -> { return TrendingNewsFragment() } 1 -> { return GeneralNewsFragment() } 2 -> {} 3 -> {} 4 -> {} 5 -> {} 6 -> {} 7 -> {} } return TrendingNewsFragment() } override fun getCount(): Int { return totalTabs } }<file_sep>/app/src/main/java/com/vob/ui/ArticleWebViewActivity.kt package com.vob.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.webkit.WebViewClient import androidx.navigation.navArgs import com.google.android.material.snackbar.Snackbar import com.vob.R import com.vob.ui.fragments.ArticleFragmentArgs import kotlinx.android.synthetic.main.fragment_article.* class ArticleWebViewActivity : AppCompatActivity() { lateinit var viewModel: NewsViewModel val articleFragmentArgs: ArticleFragmentArgs by navArgs() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_article_web_view) viewModel = this.viewModel val article = articleFragmentArgs.article webView.apply { webViewClient = WebViewClient() loadUrl(article.url) } saved_button_fab.setOnClickListener { viewModel.saveArticle(article) Snackbar.make(findViewById(android.R.id.content), "Article saved successfully", Snackbar.LENGTH_SHORT).show() } } }<file_sep>/app/src/main/java/com/vob/ui/fragments/SavedNewsFragment.kt package com.vob.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import com.vob.MainActivity import com.vob.R import com.vob.adapters.NewsAdapter import com.vob.ui.NewsViewModel import kotlinx.android.synthetic.main.fragment_saved_news.* class SavedNewsFragment : Fragment() { lateinit var viewModel: NewsViewModel lateinit var newsAdapter: NewsAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_saved_news, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = (activity as MainActivity).viewModel setupRecyclerView() newsAdapter.setOnItemClickListener { val bundle = Bundle().apply { putSerializable("article", it) } replaceFragment(ArticleFragment(),bundle) } val itemTouchHelperCallback = object: ItemTouchHelper.SimpleCallback( ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT ){ override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition val article = newsAdapter.differ.currentList[position] viewModel.deleteArticle(article) Snackbar.make(view, "Successfully deleted article", Snackbar.LENGTH_LONG).apply { setAction("Undo"){ viewModel.saveArticle(article) } show() } } } ItemTouchHelper(itemTouchHelperCallback).apply { attachToRecyclerView(saved_news_fragment_rv) } viewModel.getSavedNews().observe(viewLifecycleOwner, Observer { articles -> newsAdapter.differ.submitList(articles) }) } private fun setupRecyclerView() { newsAdapter = NewsAdapter() saved_news_fragment_rv.apply { adapter = newsAdapter layoutManager = LinearLayoutManager(activity) } } private fun replaceFragment(fragment: Fragment, bundle: Bundle) { val transaction = fragmentManager?.beginTransaction() val frag= fragment frag.arguments = bundle transaction?.add(R.id.container, frag) transaction?.commit() } }<file_sep>/app/src/main/java/com/vob/ui/SplashScreenActivity.kt package com.vob.ui import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import com.vob.MainActivity import com.vob.R class SplashScreenActivity : AppCompatActivity() { lateinit var handler: Handler override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) handler = Handler() handler.postDelayed({ startActivity(Intent(this, MainActivity::class.java)) finish() },800) //delaying by 0.8 sec to open main activity } }<file_sep>/app/src/main/java/com/vob/ui/fragments/HomeFragment.kt package com.vob.ui.fragments import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AbsListView import android.widget.Toast import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.tabs.TabLayout import com.vob.MainActivity import com.vob.R import com.vob.adapters.NewsAdapter import com.vob.adapters.TabAdapter import com.vob.ui.ArticleWebViewActivity import com.vob.ui.NewsViewModel import com.vob.util.Constants.Companion.QUERY_PAGE_SIZE import com.vob.util.Resource import kotlinx.android.synthetic.main.fragment_home.* class HomeFragment : Fragment() { lateinit var viewModel: NewsViewModel lateinit var newsAdapater: NewsAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_home, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = (activity as MainActivity).viewModel val context = (activity as MainActivity) tablayout_home.addTab(tablayout_home.newTab().setText("Trending")) tablayout_home.addTab(tablayout_home.newTab().setText("General")) tablayout_home.addTab(tablayout_home.newTab().setText("Business")) tablayout_home.addTab(tablayout_home.newTab().setText("Sports")) tablayout_home.addTab(tablayout_home.newTab().setText("Entertainment")) tablayout_home.addTab(tablayout_home.newTab().setText("Technology")) tablayout_home.addTab(tablayout_home.newTab().setText("Science")) tablayout_home.addTab(tablayout_home.newTab().setText("Health")) val adapter = TabAdapter(context.applicationContext, context.supportFragmentManager, tablayout_home.tabCount) viewpager_home.adapter = adapter viewpager_home.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tablayout_home)) tablayout_home.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{ override fun onTabSelected(tab: TabLayout.Tab?) { viewpager_home.currentItem = tab?.position!! } override fun onTabUnselected(tab: TabLayout.Tab?) {} override fun onTabReselected(tab: TabLayout.Tab?) {} }) /*setupRecyclerView() newsAdapater.setOnItemClickListener { val bundle = Bundle().apply { putSerializable("article", it) } replaceFragment(ArticleFragment(),bundle) } viewModel.breakingNews.observe(viewLifecycleOwner, Observer { response -> when(response){ is Resource.Success -> { hideProgressBar() response.data?.let { newsResponse -> newsAdapater.differ.submitList(newsResponse.articles.toList()) val totalPages = newsResponse.totalResults / QUERY_PAGE_SIZE + 10 isLastPage = viewModel.breakingNewsPage == totalPages if (isLastPage) { home_fragment_rv.setPadding(0,0,0,0) } } } is Resource.Error -> { hideProgressBar() response.message?.let { message -> Toast.makeText(activity, "Error: $message ", Toast.LENGTH_LONG).show() } } is Resource.Loading -> { showProgressBar() } } })*/ } /* var isLoading: Boolean = false var isLastPage: Boolean = false var isScrolling: Boolean = false val scrollListener = object: RecyclerView.OnScrollListener(){ override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView.layoutManager as LinearLayoutManager val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() val visibleItemCount = layoutManager.childCount val totalItemCount = layoutManager.itemCount val isNotLoadingAndNotLastPage = !isLoading && !isLastPage val isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount val isNotAtBeginning = firstVisibleItemPosition >= 0 val isTotalMoreThanVisible = totalItemCount >= QUERY_PAGE_SIZE val shouldPaginate = isNotLoadingAndNotLastPage && isAtLastItem && isNotAtBeginning && isTotalMoreThanVisible && isScrolling if (shouldPaginate){ viewModel.getBreakingNews("in") isScrolling = false } } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){ isScrolling = true } } } private fun setupRecyclerView() { newsAdapater = NewsAdapter() home_fragment_rv.apply { adapter = newsAdapater layoutManager = LinearLayoutManager(activity) addOnScrollListener([email protected]) } } private fun hideProgressBar() { home_pagination_PB.visibility = View.INVISIBLE isLoading = false } private fun showProgressBar() { home_pagination_PB.visibility = View.VISIBLE isLoading = true } private fun replaceFragment(fragment: Fragment, bundle: Bundle) { val transaction = fragmentManager?.beginTransaction() val frag= fragment frag.arguments = bundle transaction?.replace(R.id.container, frag) transaction?.addToBackStack(null)?.commit() } private fun replaceActivity(activity: Activity, bundle: Bundle){ activity?.let{ val act = activity val intent = Intent (it, ArticleWebViewActivity::class.java) it.startActivity(intent) } } */ }<file_sep>/settings.gradle include ':app' rootProject.name = "Khabar"
5a5e63904a7d80ba5ef0d5143112ac4f11c747e3
[ "Kotlin", "Gradle" ]
13
Kotlin
mishraaditya595/Khabar-News-App
163448c37ee0812fdf280c7b329ffa1f354ea519
61723b8003d47a52a441d5253e68108d340cdc59
refs/heads/master
<file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "net" ) type Actor struct { Name string Age int } func main() { actor := Actor{"<NAME>", 99} service := "localhost:1200" conn, err := net.Dial("tcp", service) if err != nil { fmt.Errorf("Error dialing to service") return } err = json.NewEncoder(conn).Encode(actor) if err != nil { fmt.Errorf("Error encoding JSON") return } var result []byte result, err = ioutil.ReadAll(conn) fmt.Println(string(result)) } <file_sep>package main import ( "encoding/json" "fmt" "net" ) type Actor struct { Name string Age int } func main() { service := ":1200" addr, err := net.ResolveTCPAddr("tcp", service) if err != nil { fmt.Errorf("Error resolving tcp addr") } listener, err := net.ListenTCP("tcp", addr) if err != nil { fmt.Errorf("Error to get listener") } for { conn, err := listener.Accept() if err != nil { continue } var actor Actor err = json.NewDecoder(conn).Decode(&actor) if err != nil { fmt.Println("Server: Error decoding JSON") return } fmt.Println(actor) fmt.Println("Actor name: ", actor.Name) response := fmt.Sprintf("Received data from: %s", actor.Name) conn.Write([]byte(response)) conn.Close() } } <file_sep>Client sends JSON Server receives JSON and returns the name of the actor
02cf12149d1f64bf67539f6d643acaecae2a6276
[ "Markdown", "Go" ]
3
Go
lucaspwbx/tcpjson
19c233938018db6b0724c1633e5a40b59394357c
f7ba52320e60897fb02d09a5fde415f39c819bce
refs/heads/master
<repo_name>captain-miao/FragmentTutorial<file_sep>/README.md FragmentTutorial ================ Android Fragment Tutorial <file_sep>/app/src/main/java/com/yanlu/android/fragment/model/DemoParcel.java package com.yanlu.android.fragment.model; import android.os.Parcel; import android.os.Parcelable; /** * User: captain_miao * Date: 14-5-6 * Time: 下午1:55 */ public class DemoParcel implements Parcelable { private String name; private int id; /** * 1.必须实现Parcelable.Creator接口,否则在获取Person数据的时候,会报错,如下: * android.os.BadParcelableException: * Parcelable protocol requires a Parcelable.Creator object called CREATOR on class com.um.demo.Person * 2.这个接口实现了从Percel容器读取数据,并返回对象给逻辑层使用 * 3.实现Parcelable.Creator接口对象名必须为CREATOR,不如同样会报错上面所提到的错; * 4.在读取Parcel容器里的数据时,必须按成员变量声明的顺序读取数据,不然会出现获取数据出错 * 5.反序列化对象 */ @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(id); } public static final Parcelable.Creator<DemoParcel> CREATOR = new Creator<DemoParcel>(){ @Override public DemoParcel createFromParcel(Parcel source) { DemoParcel demoParcel = new DemoParcel(); demoParcel.setName(source.readString()); demoParcel.setId(source.readInt()); return demoParcel; } @Override public DemoParcel[] newArray(int size) { return new DemoParcel[size]; } }; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } <file_sep>/app/src/main/java/com/yanlu/android/fragment/frg/FragmentByXml.java package com.yanlu.android.fragment.frg; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.yanlu.android.fragment.R; /** * User: captain_miao * Date: 14-5-7 * Time: 上午9:23 */ public class FragmentByXml extends Fragment { private static final String TAG = "FragmentByXml"; public FragmentByXml() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment setRetainInstance(true);//Static fragment are always recreated return inflater.inflate(R.layout.fragment_setting, container, false); } @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume( )"); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach(activity)"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate(savedInstanceState)"); } @Override public void onDetach() { super.onDetach(); Log.d(TAG, "onDetach( )"); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated(savedInstanceState)"); } @Override public void onStart() { super.onStart(); Log.d(TAG, "onStart( )"); } @Override public void onPause() { super.onPause(); Log.d(TAG, "onPause( )"); } @Override public void onStop() { super.onStop(); Log.d(TAG, "onStop( )"); } @Override public void onDestroyView() { super.onDestroyView(); Log.d(TAG, "onDestroyView( )"); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy( )"); } } <file_sep>/app/src/main/java/com/yanlu/android/fragment/frg/RightFragment.java package com.yanlu.android.fragment.frg; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.yanlu.android.fragment.MainActivity; import com.yanlu.android.fragment.R; import com.yanlu.android.fragment.SettingsActivity; import com.yanlu.android.fragment.model.DemoParcel; public class RightFragment extends Fragment implements View.OnClickListener { private static final String TAG = "RightFragment"; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private DemoParcel mParam2; private TextView mTv; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment LeftFragment. */ // TODO: Rename and change types and number of parameters public static RightFragment newInstance(String param1, DemoParcel param2) { RightFragment fragment = new RightFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putParcelable(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public RightFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getParcelable(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView(LayoutInflater, ViewGroup, Bundle) "); setRetainInstance(true); // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_right, container, false); view.findViewById(R.id.btn_ok).setOnClickListener(this); mTv = (TextView) view.findViewById(R.id.content); if (TextUtils.isEmpty(mParam1) || null == mParam2) { mTv.setText("no param"); } else { mTv.setText(ARG_PARAM1 + " = " + mParam1 + "\r\n" + ARG_PARAM2 + " = " + mParam2.getName() + "\r\ngetActivity(): " + ((MainActivity)getActivity()).getStringFromActivity()); } return view; } @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume( )"); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach(activity)"); } @Override public void onDetach() { super.onDetach(); Log.d(TAG, "onDetach( )"); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated(savedInstanceState)"); } @Override public void onStart() { super.onStart(); Log.d(TAG, "onStart( )"); } @Override public void onPause() { super.onPause(); Log.d(TAG, "onPause( )"); } @Override public void onStop() { super.onStop(); Log.d(TAG, "onStop( )"); } @Override public void onDestroyView() { super.onDestroyView(); Log.d(TAG, "onDestroyView( )"); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy( )"); } @Override public void onClick(View v) { //Toast.makeText(getActivity(), "onClick() in fragment", Toast.LENGTH_SHORT).show(); startActivityForResult(new Intent(getActivity(), SettingsActivity.class), REQ_CODE); } private final static int REQ_CODE = 22223; @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (REQ_CODE == requestCode && resultCode == Activity.RESULT_OK) { Toast.makeText(getActivity(), "onActivityResult() in fragment", Toast.LENGTH_SHORT).show(); } else { super.onActivityResult(requestCode, resultCode, data); } } } <file_sep>/app/src/main/java/com/yanlu/android/fragment/App.java package com.yanlu.android.fragment; import android.app.Application; import android.content.Context; import android.util.Log; import com.yanlu.android.fragment.net.RequestManager; /** * 管理全局信息 * * @author yanlu * @date 2012-10-31 上午11:24:54 */ public class App extends Application { private static final String TAG = "Application"; private static Context context; public static Context getContext() { return context; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "app start"); context = this.getApplicationContext(); RequestManager.init(context); Log.d(TAG, "app start over"); } public void onTerminate() { super.onTerminate(); Log.d(TAG, "app onTerminate"); } }
922402ed0dcca2ef2e627d3e001a0cd974395e5e
[ "Markdown", "Java" ]
5
Markdown
captain-miao/FragmentTutorial
8ea009a8827f3c153a1a761adb7227147fefb74a
959bdfb1836f43b3f064154630278c0909a6f7dd
refs/heads/master
<file_sep># Insertion Sort Algorithm Visualisation This project is a visual representation of how the insertion sort algorithm works behind the scenes. This project each step of the algorithm in a visual representation which gives further knowledge as to how this algorithm works. <br>This project was made using: <br> * Javascript * D3 * HTML * SCSS # Demo This is the codepen link to view this project: https://codepen.io/devalpanchal2401/full/vYXQBQL <br> To properly view this project click the `Change View` button on the top-left of the page and change to `Full Page View`. # Download If you gave git installed on your local machine then you can simply `git clone` this repository into a directory on your computer. From there you can just open the index.html file which will redirect you to a brower with the project open. <br><br> If you don't have git installed then you can click the `code` button on the top left of the repository and you can download a ZIP file and extract to a desired location on your computer. From there you can open the index.html file which will redirect you to a brower with the project open.<file_sep>let width = 900; let height = 600; let NUMBER_OF_BARS = 41; let count = 1 + 50; let durationTime = 100 / NUMBER_OF_BARS; let array = d3.shuffle(d3.range(1, NUMBER_OF_BARS)); let unsortedArray = [...array]; let sortedArray = []; let barWidth = width / NUMBER_OF_BARS; let xAxis = d3.scaleLinear().domain([0, NUMBER_OF_BARS]).range([0, width]); let svg = d3.select('body').append('svg') .attr('width', width) .attr('height', height) .append('g'); let xScale = d3.scaleBand() .domain(d3.range(unsortedArray.length)) .rangeRound([0, width]) .paddingInner(0.05); let yScale = d3.scaleLinear() .domain([0, d3.max(unsortedArray)]) .range([0, height]); let rects = svg.append('g') .attr('transform', 'translate(' + barWidth + ", 2)") .selectAll('rect') .data(unsortedArray) .enter() .append('rect') let labels = svg.selectAll('text') .data(unsortedArray) .enter() .append('text') labels.attr('id', function(d) { return 'text'}) .attr('transform', function(d, i) { return 'translate(' + xAxis(i) + ',0)'}) .html(function(d) { return d; }) rects.attr('id', function(d) {return 'rect' + d}) .attr('transform', function(d, i) {return 'translate(' + (xAxis(i) - barWidth) + ', 0)'}) .attr('width', barWidth * 0.95) .attr('height', function(d) {return d * (barWidth - 6)}) .attr('x', function(d, i) { return barWidth; }) .attr('y', function(d) { return height - yScale(d); }) .attr('fill', function(d) { return "blue"; }); function resetArray() { unsortedArray = [...array]; sortedArray = []; labels.attr('class', '') .data(unsortedArray) .enter() .append('text') .text(function (d) { return d; }) .transition() .duration(300) .attr('transform', function(d, i) { return 'translate(' + (xAxis(i)) + ', 0)'}) rects.attr('class', '') .transition() .delay(function(d, i) { return (i / unsortedArray.length) * 700; }) .duration(300) .ease(d3.easeLinear) .attr('transform', function(d, i) { return 'translate(' + (xAxis(i - 1)) + ', 0)'}) .attr('fill', function(d) { return 'blue'; }) } function insertionSort() { let key = unsortedArray.shift(); sortedArray.push(key); reArrange(sortedArray.length - 1); function reArrange(n) { d3.selectAll('rect').attr('class', ''); d3.select('#rect' + key) .attr('class', 'testing') .attr('fill', function(d) { return 'green' }); if ((n >= 0) && sortedArray[n - 1] > key) { d3.timeout(function () { sortedArray.splice(n, 1); sortedArray.splice(n - 1, 0 , key); slide(sortedArray[n], n); slide(sortedArray[n - 1], n - 1); reArrange(--n); }, 50); } else if (unsortedArray.length) { d3.timeout(function () { insertionSort()}, durationTime); } else { return d3.selectAll('rect').attr('class', ''); } } } function slide(d, i) { d3.select('#text' + d) .transition() .duration(300) .attr('transform', function(d) { return 'translate(' + (xAxis(i)) + ', 0)'}) d3.select('#rect' + d) .transition() .duration(300) .ease(d3.easeLinear) .attr('transform', function(d) { return 'translate(' + (xAxis(i - 1)) + ', 0)'}) }
12a37942b71f911679b56a52f6541d291c35bafd
[ "Markdown", "JavaScript" ]
2
Markdown
DevalPanchal/Insertion-Sort-Visualisation
c52a2c3734a208e9694e6a93e1255d95bbbbfac1
7dcfcf7cbfbff9a12959b5350bf825a8c81cd5b0
refs/heads/master
<file_sep>class Shout < ActiveRecord::Base attr_accessible :content, :user_id belongs_to :user validates :content, length: {maximum: 140} end <file_sep>class Network < ActiveRecord::Base attr_accessible :network_name, :owner_first_name, :owner_last_name, :owner_password # networks can have many users has_many :users # owner password and network name are required # password length must be between 8 and 14 characters long and must include at least one number and letter # username must be unique #username_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :owner_password, :network_name, :presence => true validates :owner_password, :length => { :in => 8..14 } validates :network_name, :uniqueness => true end <file_sep>class AddITunesColumnsToSongs < ActiveRecord::Migration def change add_column :songs, :track_name, :string add_column :songs, :artist_name, :string add_column :songs, :track_price, :string add_column :songs, :artworkurl100, :string add_column :songs, :viewurl, :string add_column :songs, :previewurl, :string end end <file_sep>class AddColumnsToPromotions < ActiveRecord::Migration def up add_column :promotions, :track_url, :string add_column :promotions, :slug, :string add_column :promotions, :short_url, :string add_column :promotions, :short_url2, :string add_column :promotions, :custom_ending, :string end def down remove_column :promotions, :track_url, :string remove_column :promotions, :slug, :string remove_column :promotions, :short_url, :string remove_column :promotions, :short_url2, :string remove_column :promotions, :custom_ending, :string end end <file_sep>class AffiliatesController < ApplicationController # ---------- # Allowing for the use the short form of their email to login before_create :create_login # ---------- def new @affiliate = Affiliate.new end def create @affiliate = Affiliate.new(params[:affiliate]) if @affiliate.save redirect_to @affiliate else render action: :new end end def create_login email = self.email.split(/@/) login_taken = Affiliate.where( :login => email[0]).first unless login_taken self.login = email[0] else self.login = self.email end end def self.find_for_database_authentication(conditions) self.where(:login => conditions[:email]).first || self.where(:email => conditions[:email]).first end end def show @affiliate = Affiliate.find(params[:id]) end end <file_sep>require_relative 'lib/player.rb' require_relative 'lib/secret_number.rb' require_relative 'lib/game.rb' def ask_for(number_question) begin print "#{number_question}?" Integer(gets.chomp) rescue ArgumentError puts "Please enter an Integer" retry end end puts "This is my game" highest_number = ask_for("what is the highest_number") lowest_number = ask_for("what is the lowest_number") puts "You will have to guess a number between #{lowest_number} and #{highest_number}!" max_guesses = ask_for("How many guesses") loop do game = Game.new(max_guesses, highest_number, lowest_number) game.start_game puts "Would you like to play again? Y/N" if gets.chomp == "Y" next else break end end puts "¿Quieres jugar de nuevo?...'si' o 'no'" @jugar = gets.chomp.downcase jugar_de_nuevo?(@jugar) def jugar_de_nuevo?(jugar) while @jugar != "si" && @jugar != "no" puts "¿Que?" end if @jugar == "si" game = Game.new(3, (0..20)) game.start_game elsif exit end end puts "Gracias por venir"<file_sep>class Link < ActiveRecord::Base attr_accessible :promotion_id, :slug, :url end <file_sep>class ShoutController < ApplicationController def new @shout = Shout.new end def create @shout = Shout.new(params[:shout]) if @shout.save redirect_to @shout else render action: :new end end end <file_sep>itr_homework ============ this is where i will be storing all of the homework done during GA's intro to rail course sadly i deleted my first 4 homework programs :( <file_sep>class CreateShortUrls < ActiveRecord::Migration def change create_table :short_urls do |t| t.string :affiliate_id t.string :promotion_id t.string :song_id t.string :track_url t.string :slug t.string :short_url t.timestamps end end end <file_sep>class Promotion < ActiveRecord::Base attr_accessible :affiliate_id, :song_id, :track_url, :slug, :short_url, :short_url2, :custom_ending # validates :short_url2, :uniqueness => true # ----- we only want to save the slug once to the database # if we did not do this the slug would either never save or # it would regenerate every time the promotion was updated before_create :generate_slug # before_update :customize_redirect_link # ----- belongs_to :affiliate belongs_to :song def set_track_url end private @url_head = "localhost:3000/" def generate_slug self.slug = SecureRandom.hex(3) # redirect_link = @url_head + slug self.short_url = "www.msclvr.com/" + slug.to_s end # ----- http://rails-bestpractices.com/posts/47-fetch-current-user-in-models # def self.current # Thread.current[:promotion] # end # def self.current=(promotion) # Thread.current[:promotion] = promotion # end end <file_sep>class Game include Comparable attr_accessor :guesses_allowed attr_reader :secret_number :current_guess_count win = "\nCongrats! It turns out you've won!!" lose = "\nOuch! It turns out you've lost!!" too_low = "\nSorry - that guess was too low" too_high = "\nNot quite - too high" keys = [:win , :lose , :too_low , :too_high] @@messages = { :win => win, :lose => lose, :too_low => too_low, :too_high => too_high } def initialize(guesses_allowed , highest_number , lowest_number) @guesses_allowed = guesses_allowed @highest_number = highest_number @lowest_number = lowest_number @secret_number = (lowest_number..highest_number).to_a.sample @secret_number = SecretNumber.new(set_of_numbers) @current_guess_count = 0 @current_guess = nil @player = Player.new() @jugar = nil end def print_created_by puts "\n\nHello, friend. This superb game was created by yours truly, <NAME>" end def start_game puts "Bienvenidos!" print_created_by puts "\n ¿Como te llamas?" @player.name = $stdin.gets.chomp.capitalize puts "¡Hola, #{@player.name}! Tú tienes #{@guesses_allowed} suposiciónes del Numero Secreto entre #{@secret_number}" while @current_guess_count < @guesses_allowed && !guess_correct?(@current_guess) do puts "Faltan #{@guesses_allowed} suposiciónes..." @current_guess = $stdin.gets.chomp.to_i game_records.write("\nGuess number #{@guesses_allowed} was #{@current_guess}") @current_guess_count += 1 end end def guess_correct?(guess) if guess.nil? puts "Whatsamattayou?!" return false while guesses_allowed > current_guess_count print "what is your guess" guess = gets.chomp if guess.to_i == secret_number puts @@messages[keys[0]] puts "You guessed within #{@current_guess_count} tries" return true elsif guess > @secret_number.secret_number puts @@messages[keys[3]] puts "You have #{@current_guess_count} guess(es) left" return false elsif guess < @secret_number.secret_number puts @@messages[keys[2]] puts "You have #{@current_guess_count} guess(es) left" return false end end def guess! @current_guess_count+=1 end def remaining_guesses guesses_allowed - current_guess_count end end <file_sep>class Affiliate < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # ----- # Devise modifications to allow users to sign in using either email or username attr_accessor :login # ----- # Setup accessible (or protected) attributes for your model attr_accessible :username, :login, :email, :password, :password_confirmation, :remember_me, :first_name, :last_name # an affiliate can only belong to one network (or no network at all) # an affiliate can have many songs that they are tracking belongs_to :network has_many :promotions has_many :songs, :through => :promotions # password and username are required # password length must be between 8 and 14 characters long and must include at least one number and letter # username must be unique #username_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i # ---------- # Overriding the find_for_database_authentication method as prescribed by Devise to allow # for email and username login capability def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase } ]).first else where(conditions).first end end end <file_sep>class RemoveOldColumnsFromSongs < ActiveRecord::Migration def up remove_column :songs, :song_title remove_column :songs, :song_performer end def down add_column :songs, :song_title add_column :songs, :song_performer end end <file_sep>class DashboardsController < ApplicationController def index @dashboard = current_affiliate.promotions respond_to do |format| format.html # index.html.erb format.json { render json: @promotions } end end <file_sep>class RenameTableUsersToAffiliates < ActiveRecord::Migration def change rename_table :users, :affiliates end end <file_sep>class SecretNumber attr_reader :set_of_numbers :secret_number def initialize(set_of_numbers) @set_of_numbers = set_of_numbers || (0..10) @secret_number = generate end private def generate @secret_number = @set_of_numbers.to_a.sample.to_i end end <file_sep>class DropAdminTable < ActiveRecord::Migration def up drop_table :admins end def down #I am not sure what this is doing. I copied it from a stackoverflow response raise ActiveRecord::IrreversibleMigration end end <file_sep>class Song < ActiveRecord::Base attr_accessible :track_name, :artist_name, :track_url has_many :promotions has_many :affiliates, :through => :promotions has_many :short_urls, :through => :promotions end <file_sep>############################################################################### # # Introduction to Ruby on Rails # # Lesson 5 homework # # Purpose: # # Read the links below and complete the exercises in this file. This Lab # will help you to review more advanced topics on Object-Oriented # Programming within the Ruby context based on what we've learned in # Lesson 5. # ############################################################################### # # 1. Review your solution to lesson 4 homework. Copy and Paste your solution to # this file. # # 2. Create a new folder called `lib` by running: # # mkdir lib # # 3. Create a new file called `player.rb` with the class # `Player` defined within it in the `lib` directory. # # 1. In its initialize method, it should keep track of the Player's # name stored in the instance variable `@name`. When we create # a new Player, the initialize method should accept a parameter # that will be set for this instance variable. # # 2. Also, it should have an instance variable called # `@current_guess_count` which by default starts at 0. # # 3. Create a new method called `increment_guess_count` which increments # `@current_guess_count` by 1. # # 4. Make sure that the instance variable `@current_guess_count` can be # READ but not WRITTEN to. # # Hint: Which `attr_` should you use at the top of your Class? # # 5. Make sure that the instance variable `@name` can be READ and # WRITTEN to. # # Hint: Which `attr_` should you use at the top of your Class? # # 4. Create a new file called `secret_number.rb` with the class # `SecretNumber` defined within it in the `lib` directory. # # 1. The initialize method should accept a paramter of a range of # numbers that the Player must guess from and should be saved into # the instance variable `@set_of_numbers`. If not parameter is set, # it should default to (0..10). # # 2. In its initialize method, you should have an instance variable # called `@secret_number` which will hold the randomly generated # secret number that the Player must guess. # # 3. Make sure that the instance variables `@secret_number`, # `@guesses_allowed`, and @set_of_numbers may only be READ and # not WRITTEN to. # # 4. Create a new private class method called `generate_secret_number`, # set your instance variable `@secret_number` to call this method upon # initialization. # # 6. Create a new file called `game.rb` with the class `Game` defined # within it in the `lib` directory. # # 1. In its initialize method, it should keep track of how many # guesses are allowed to be made by the Player in the Integer instance # variable `@guesses_allowed`. When we create a new Game, the # initialize method should accept a parameter that will be set for # this instance variable. If no parameter is set, it should default # to `3`. # # 2. Additionally, it should accept as a parameter a range of # numbers that will be passed along to the `SecretNumber` class. # # 3. Also in its initialize method, it should keep track of how many # guesses have been currently made by the Player. Create the # Integer instance variable `@current_guess_count`. By default, set # this to `0`. # # 4. Your initialize method should also create the instance variables # `@player` and `@secret_number`. Set these variables # to create new instances of each of these classes. For the new # SecretNumber instance, pass along the set_of_numbers parameter. # # 5. Make sure that the instance variables `@guesses_allowed` and # `@current_guess_count` may only be READ and not WRITTEN to. # # 6. In your initialize method, create a new Integer instance # variable called `@current_guess` and set it to `nil` by default. # This will keep track of the Player's current guess. # # 6. Move the `increment_guess_count` method from your Player class # to the Game class. Instead of hard-coding the number of guesses # allowed as `3` use the new `@guesses_allowed` instance variable. # # 7. In your Game class, create the class variable `@@messages`. Move # your logic for creating your `messages` Hash from this file to the # Game class. # # 8. Create a new public instance method called `guess_correct?` # that accept the parameter `guess`. This will evalute whether or # not the Player's guess is correct. Use cases or conditionals to # see if the Player guessed correctly or guessed too high or too # low. Use the `@@messages` Hash to display which message to show to # the user. Also let the Player know how many guesses they have # left. If the guess is correct, make sure to return true, # otherwise return false. # # 7. Create a new public instance method in your Game class called # `print_created_by`. Move your logic from this file into this new # method so that when this method is called, your name will be # shown. # # 8. Create a new public instance method in your Game class called # `start_game`. In this method: # # 1. First call the method `print_created_by` so that your credit # is shown to the Player. # # 2. Next, ask the Player their name. Save this to @player.name. # # 3. Tell the Player how many guesses they get and the range of # numbers they can choose from. # # 4. Loop through however many `@guesses_allowed` are, running # increment_guess_count along the way. On each call, you should # ask the Player for their guess and use the `guess_correct?` # method. If at the end of the loop they still did not guess # correctly, tell the player that they have lost using the # `@@messages` class variable and what the secret number was. # # 7. In this file, load `player.rb`, `secret_number.rb`, and `game.rb` # along with their respective classes using `require_relative`. # # 8. For the most part, everything has been removed from this file and # placed in other classes. Now, when this Ruby script is run it # should: # # 1. Create a new instance of the class Game. Here when you # initialize the new Game, you can set how many guesses a Player # gets to guess the secret number and the range of numbers they # can select from. # # 2. Make sure to call the method `start_game` to get this # party started! # # 3. At the end, feel free to let your Player know, "Thanks for # Playing!" # # 9. Remember to keep your code clean and keep in mind how your file is # laid out. You want to make sure that the TAs reading your work will # understand your though process and give you good marks. # ############################################################################### # # Student's Solution # ############################################################################### require_relative 'lib/player.rb' guesses = 5 ##### -- Incrementing the guess count by one? def increment_guess_count(guess) incremented = guess.to_i + 1 end ##### -- How many guesses does the user have left? def guesses_left(incremented) if incremented < 3 puts 3 - incremented else puts "You have guessed at least 3 times" end end set_of_numbers = Array(1..50) secret_num = set_of_numbers[rand(set_of_numbers.length)] # puts "\n#{secret_num}" win = "\nCongrats! It turns out you've won!!" lose = "\nOuch! It turns out you've lost!!" too_low = "\nSorry - that guess was too low" too_high = "\nNot quite - too high" keys = [:win , :lose , :too_low , :too_high] messages = { :win => win, :lose => lose, :too_low => too_low, :too_high => too_high } puts "\n\n\nHello, friend. Welcome to the NUMBER GUESSING GAME" ##### -- Let's ask for the players name. puts "\nPlease tell me your name" player_name = gets.chomp.capitalize ##### -- Let's ask the player if they'd like to begin the game puts "\nThanks, #{player_name} - shall we begin? [Y/N]" prompt = nil game_records = File.new("mygame_records", "a+") ##### -- Let's make sure they are giving an appropriate response while prompt != "y" && prompt != "n" prompt = gets.chomp.downcase break if prompt == "y" break if prompt == "n" puts "Please use Y or N" end if prompt == "n" exit else puts "\nLet's have some fun!" game_records.write("\nGame Start Time = ") game_records.write(Time.now) end ##### -- The game begins while guesses > 0 puts "You have #{guesses} guess left" player_guess = gets.chomp.to_i game_records.write("\nGuess number #{guesses} was #{player_guess}") increment_guess_count(player_guess) if player_guess == secret_num puts messages[keys[0]] game_records.write("The player won by guessing #{player_guess}") exit elsif player_guess < secret_num puts messages[keys[2]] guesses -=1 else puts messages[keys[3]] guesses -=1 end end puts messages[keys[1]] game_records.write("\nThe secret number was #{secret_num}") puts "The correct number was #{secret_num}" <file_sep># Intro to Rails: Lesson 4 Object Oriented Programming ## Before we start ### Agenda * Quiz * Homework Review * Methods * Object Oriented Programming ### Quiz 1. How do you access values within an Array? 2. How are Arrays and Hashes different? 3. What are some ways to execute the same code multiple times? ### Homework Review Walkthrough `previous_homework_solution.md` Any questions about Lesson 3 homework? ## Methods ### We've already used some! * [`IO#puts`][io_puts] - Print an object to the screen. * [`IO#gets`][io_gets] - Reads the next "line" from the I/O stream. * [`Array#length`][array_length] - Returns the number of elements in an array. * [`Fixnum#+`][fixnum_plus] - Performs addition. [io_puts]: http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-puts [io_gets]: http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-gets [array_length]: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-length [fixnum_plus]: http://www.ruby-doc.org/core-1.9.3/Fixnum.html#method-i-2B ### Other methods What other methods have we used? ### Methods defined A method is a named code block wrapped by `def` and `end` which you may execute by name. In other languages, methods may be known as "functions", "operations", "procedures", "subroutines", etc. Methods may or may not return a value in Ruby, the last expression value is returned whether or not you use the `return` statement. ### Method example ```ruby def whats_up ["Not much", "A lot", "The sky"].sample end puts say_whats_up ``` ### Method parameters Methods may define parameters which allow arguments to be passed. Parameters are a value that the method expects. Arguments are what actually get passed. ### Method parameters example ```ruby def say_my_name(name) "Hey, #{name}" end say_my_name("Rick") #=> "Hey, Rick" say_my_name "Stan" #=> "Hey, Stan" ``` ### Default values for parameters We can optionally define default values for any or all of our parameters. ```ruby def say_my_name(name = "friend") "Hey, #{name}" end say_my_name("Joe") #=> "Hey, Joe" say_my_name #=> "Hey, friend" ``` ### Indefinite number of parameters If we want to allow our method to be called with an indefinite number of parameters, we precede the parameter name with an asterisk (`*`). ```ruby def format_names(*names) names.join(", ") end format_names("Alex", "Will", "John") #=> "Alex, Will, John" ``` ### Variable scope within methods Methods cannot access variables defined outside of the method. ```ruby name = "Biff" def print_name print(name) end print_name #=> NameError: undefined local variable or method `name'... ``` Use parameters instead! ### Code Along: Methods Open `coa_methods.rb` in your editor and follow along. ### Exercise: Methods Open `ex_methods.rb` in your editor and complete on your own. Ask questions if you're confused! ## Object Oriented Programming ### Objects defined An object is an *instance* of a *class*. What is a class? ### Classes defined Classes are like blueprints for the attributes and behaviors of an object. * Attributes: Instance variables * Behavior: Instance methods ### Objects defined, again An object is an *instance* of a *class*. IRL: If you had blueprints for a house, the blueprints would be the *class* and the house built is the *instance* or *object*. ### Interacting with objects *Methods* are called on an object to interact with it. This is also called "sending a message" to an object. The dot operator (`.`) sends the message on the right to the object on the left. ### Interacting with objects example ```ruby names = ["Sam", "Alan", "Gregor"] names.push("Anze") names.length ``` ### Classes are objects In Ruby, even classes are objects. ```ruby Array.new Hash.new ``` ### Why is Object Oriented Programming useful? Object Oriented Programming (OOP) provides: * A modular way to structure code * A logical way to reuse code * A way to model real world concepts in code * OOP is a *very popular* programming paradigm Supported by: Ruby, Python, C++, Java, Javascript, PHP, and many more... ### What is an object in Ruby? Almost **everything** is an object in Ruby ```ruby puts "Steve".upcase 3.times do |counter| puts counter * 10 end ``` Above, `"Steve"`, `3`, `10`, and the value of `counter` are objects. ### Object exceptions Some concepts, such as methods, are not "first-class objects". We'll learn more about this later. ### Built in classes Ruby comes with dozens of built in classes: * [String][string] * [Hash][hash] * [Array][array] * [File][file] * [Many more](http://www.ruby-doc.org/core-1.9.3/)... [string]: http://www.ruby-doc.org/core-1.9.3/String.html [hash]: http://www.ruby-doc.org/core-1.9.3/Hash.html [array]: http://www.ruby-doc.org/core-1.9.3/Array.html [file]: http://www.ruby-doc.org/core-1.9.3/File.html ### The Time class The built in Time class is used to display and format time information. ```ruby time = Time.new #=> 2013-03-06 11:36:34 -0800 time.friday? #=> false time.year #=> 2013 ``` ### The File class The built in File class can read and write files on the computer. * [`File.new`][file_new] - opens or creates the specified file. * [`File#write`][file_write] - writes data to a file. * [`File#close`][file_close] - closes the file object [file_new]: http://www.ruby-doc.org/core-1.9.3/File.html#method-c-new [file_write]: http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-write [file_close]: http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-close ### Code Along: Built in classes Open `coa_builtin_classes.rb` in your editor and follow along. ### Exercise: Methods Open `ex_buildin_classes.rb` in your editor and complete on your own. Ask questions if you're confused! <file_sep> # ----- this file needs to be edited as it was coped from promotions_controller.rb class SongsController < ApplicationController def index @songs = current_affiliate.songs respond_to do |format| format.html #show.html.erb format.json { render json: @songs } end end def show @song = Song.find(params[:id]) respond_to do |format| format.html #show.html.erb format.json { render json: @song } end end def new @song = current_affiliate.songs.build @allsongs = Song.all respond_to do |format| format.html # new.html.erb format.json { render json: @song } end end # ----- GET /songs/1/edit def edit @promotion = Promotion.find(params[:id]) end def create @promotion = current_affiliate.promotions.build(params[:promotion]) if @promotion.save redirect_to @promotion, notice: 'Promotion was successfully created.' #format.json { render json: @link, status: :created, location: @link } else render action: "new" #format.json { render json: @link.errors, status: :unprocessable_entity } end end def update @promotion = Promotion.find(params[:id]) if @promotion.update_attributes(params[:promotion]) redirect_to @promotion, notice: 'Promotion was successfully updated.' else render action: "edit" end end def destroy @promotion = Promotion.find(params[:id]) @promotion.destroy respond_to do |format| format.html { redirect_to promotions_url } format.json { head :no_content } end end end <file_sep>module RedirectHelpers def customize_redirect_link temp = "www.msclvr.com/" + short_url2 @promotion.short_url2 = temp end end<file_sep># This is where we create a Class called Person class Player attr_accessor :name def initialize(name = nil) @name = name end <file_sep>class PromotionsController < ApplicationController def go promotion = Promotion.find_by_slug!(params[:slug]) redirect_to promotion.track_url # if Promotion.find_by_custom_ending(params[:custom_ending]).nil? # promotion = Promotion.find_by_slug(params[:slug]) # redirect_to promotion.track_url # else # promotion = Promotion.find_by_custom_ending(params[:custom_ending]) # redirect_to promotion.track_url # end end def index @promotions = current_affiliate.promotions respond_to do |format| format.html #show.html.erb format.json { render json: @promotions } end end def show @promotion = Promotion.find(params[:id]) respond_to do |format| format.html #show.html.erb format.json { render json: @promotion } end end def new @promotion = current_affiliate.promotions.build @allsongs = Song.all respond_to do |format| format.html # new.html.erb format.json { render json: @promotion } end end # ----- GET /promotions/1/edit def edit @promotion = Promotion.find(params[:id]) @allsongs = Song.all end def create @promotion = current_affiliate.promotions.build(params[:promotion]) @promotion.track_url = Song.find(@promotion.song_id).track_url @allsongs = Song.all # customize_redirect_link if @promotion.save redirect_to @promotion, notice: 'Promotion was successfully created.' #format.json { render json: @link, status: :created, location: @link } else render action: "new" #format.json { render json: @link.errors, status: :unprocessable_entity } end end def update @promotion = Promotion.find(params[:id]) if @promotion.update_attributes(params[:promotion]) redirect_to @promotion, notice: 'Promotion was successfully updated.' else render action: "edit" end end def destroy @promotion = Promotion.find(params[:id]) @promotion.destroy respond_to do |format| format.html { redirect_to promotions_url } format.json { head :no_content } end end end <file_sep>class ReviewsController < ApplicationController def index @reviews = Review.all end end
e5c699f5894e590ddc2ec220170326d6d7335089
[ "Markdown", "Ruby" ]
26
Ruby
playtaplabs/itr_homework
fef90f3a0e73e38a940a669990da3473e78a705e
6f5103a373267cf498031155ff6604b9b222cbbb
refs/heads/master
<repo_name>nguyenhongson1902/solving-coloring-puzzle<file_sep>/README.md # Solving Coloring Puzzle This is a solution for coloring puzzles ## Descriptions: You are asked to build a coloring puzzle solver by using the first order logic to CNF as described below: - Given a matrix of size m x n, where each cell will be a non-negative integer or zero (empty cell). Each cell is considered to be adjacent to itself and 8 surrounding cells. - Your puzzle needs to color all the cells of the matrix with either green or red, so that the number inside each cell corresponds to the number of green squares adjacent to that cell (see Figure 1) ![alt text](figure1.JPG) ## Introduction to Satisfiability Problems (SAT) Please flick through `cnfsat.pdf` file ## Idea: The idea comes from Minesweeper problems. Read more about the problem in `./references/lecture08` and `./references/lecture09` **KN(k,n) = U(k,n) ^ L(k,n)** KN(k,n): k out of n adjacent unknown squares are mines U(k,n): At most k out of n squares contain a mine L(k,n): At least k out of n squares contain a mine **Conversion to at least** The proposition holds True if and only if k > 0 and k + 1 <= n U(k,n): For any k+1 squares out of n, at least one is not a mine L(k,n): For any n-(k-1) squares out of n, at least one is mine **With the problem:** The number of unknown squares = The number of adjacent squares ## To run this program: 1. Open a terminal 2. Run `python main.py` ## Environment: - Python 3.9.6 - Anaconda, Windows 10 ## Libraries: - pysat - numpy - matplotlib ## References: 1. https://www.geeksforgeeks.org/minesweeper-solver/ 2. https://github.com/pysathq/pysat <file_sep>/main.py from pysat.solvers import Glucose3 from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap from itertools import combinations import numpy as np import random import time """ KN(k,n) = U(k,n) ^ L(k,n) KN(k,n): k out of n adjacent unknown squares are mines U(k,n): At most k out of n squares contain a mine L(k,n): At least k out of n squares contain a mine Conversion to at least The proposition holds True if and only if k > 0 and k + 1 <= n U(k,n): For any k+1 squares out of n, at least one is not a mine L(k,n): For any n-(k-1) squares out of n, at least one is mine With the problem: The number of unknown squares = The number of adjacent squares """ class Puzzle_Solver: def __init__(self, shape): """ Input: shape: A tuple of 2 integers. E.g: (4, 5) """ self.shape = shape self.matrix = np.zeros(shape) self.model = list() def isValid(self, x, y): """ Input: x, y: integers shape: The shape of the matrix Output: Returns True if x, y are valid matrix indices. Otherwise, returns False """ return x >= 0 and y >= 0 and x < self.shape[0] and y < self.shape[1] def createPuzzle(self, threshold=20): """ Input: shape: A tuple of 2 integers. E.g: (4, 5) threshold: A threshold to use probability when generating a random number Output: puzzle: A numpy array """ print('Creating a puzzle...') dx = [-1, 0, 1, -1, 0, 1, -1, 0, 1] dy = [0, 0, 0, -1, -1, -1, 1, 1, 1] num_rows = self.shape[0] num_cols = self.shape[1] for x in range(num_rows): for y in range(num_cols): rand = random.randint(0, 99) if rand < threshold: self.matrix[x][y] = True else: self.matrix[x][y] = False # Count the number of adjacent squares and stores it in arr arr = np.zeros(shape=self.shape) for x in range(num_rows): for y in range(num_cols): for k in range(9): if self.isValid(x+dx[k], y+dy[k]) and self.matrix[x+dx[k]][y+dy[k]]: arr[x][y] += 1 print(round(arr[x][y]), end=' ') print() self.matrix = arr.astype(int) print('A puzzle created!') def solve(self): """ Input: matrix: A numpy array """ start = time.time() g = Glucose3() # A SAT-solver num_rows = self.shape[0] num_cols = self.shape[1] dx = [-1, 0, 1, -1, 0, 1, -1, 0, 1] dy = [0, 0, 0, -1, -1, -1, 1, 1, 1] U = list() L = list() for x in range(num_rows): for y in range(num_cols): adjacents = list() for z in range(9): if self.isValid(x+dx[z], y+dy[z]): adjacents.append(1 + (x+dx[z])*num_cols + y+dy[z]) # convert 2d array indexes to 1d array indexes (one-based indexes) k = int(self.matrix[x][y]) n = len(adjacents) for combination in combinations(adjacents, k+1): U.append({i*-1 for i in combination}) # element-wise multiplication with -1 for combination in combinations(adjacents, n - k + 1): L.append(set(combination)) for clause in np.unique(U): g.add_clause(clause) for clause in np.unique(L): g.add_clause(clause) if not g.solve(): print('No solutions!') else: self.model = g.get_model() # self.display(model) print('Solving time: {} s'.format(time.time() - start)) def display(self): print('Showing the solution') mod = np.array(self.model).reshape(self.shape) mod = mod > 0 fig, ax = plt.subplots() cmap = ListedColormap(['w', 'g']) ax.matshow(mod, cmap=cmap) num_rows = self.shape[0] num_cols = self.shape[1] for i in range(num_rows): for j in range(num_cols): value = self.matrix[i][j] ax.text(j, i, value , va='center', ha='center') plt.show() def main(): solver = Puzzle_Solver(shape=(10, 10)) solver.createPuzzle(threshold=20) solver.solve() solver.display() if __name__ == '__main__': main()
c5f54fe7057f6b9104692b43c8c18ec13698caa7
[ "Markdown", "Python" ]
2
Markdown
nguyenhongson1902/solving-coloring-puzzle
500bc68f667fe940aba224b5cc9c961e3c57d629
80885d9020cd6f2058ae6c833b44a7dbbce973f4