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>sd9550/ChangeEquipment<file_sep>/ChangeEquipment/src/ChangeEquipment.java // program to test out multidimensional arrays // Items are from Dark Souls public class ChangeEquipment { public static void main(String[] args) { new Initialize(); } } <file_sep>/ChangeEquipment/src/Armor.java public class Armor extends Equipment { private String[] miscArmor = {"Naked"}; private String miscDesc = "Unclothed enigma. Perhaps had their clothing stolen."; private String[] lightArmor = {"Leather Armor", "Sorcerer's Robe", "Moon Butterfly Set"}; private String[] heavyArmor = {"Iron Armor", "Stone Armor", "Steel Armor"}; private String[][] allArmor = {lightArmor, heavyArmor}; private int[] lightArmorDefense = {3, 1, 2}; private int[] heavyArmorDefense = {5, 6, 7}; private int[][] allArmorDefense = {lightArmorDefense, heavyArmorDefense}; private String[] lightArmorDesc = {"This armor made of smooth black leather is extremely quiet, a good thing for those who hide in the shadows.", "Cloak worn by proper sorcerers who studied at Vinheim Dragon School.", "Armor made from wings of the rare moon butterfly. Poisons those who aproach the wearer."}; private String[] heavyArmorDesc = {"Armor of a lower-rank knight. Despite the thin metal used, the grooved textures give it added protection.", "Moss-covered armor of the Stone Knight, defender of the Darkroot Garden.", "Armor of the Knights of Berenike, known for their heavy arnaments and armor."}; private String[][] allArmorDesc = {lightArmorDesc, heavyArmorDesc}; public Armor() { this.setEquipmentName(miscArmor[0]); this.setDefenseRating(0); this.setAttackRating(0); this.setEquipmentDesc(miscDesc); } public String[] getAllArmor() { return this.getAllEquipment(allArmor, getArmorTotal()); } public int getArmorTotal() { return this.getEquipmentTotal(allArmor); } public void displayAllArmor() { this.displayAllEquipmentMulti(allArmor); } public void changeArmor(String w) { for(int x = 0; x < allArmor.length; ++x) { for(int y = 0; y < allArmor[x].length; ++y) { if(allArmor[x][y].equals(w)) { this.setEquipmentDesc(allArmorDesc[x][y]); this.setAttackRating(allArmorDefense[x][x]); } } } this.changeEquipment(w); } }
c498f829d192858fcca82b8e28c7e8bf29f97df3
[ "Java" ]
2
Java
sd9550/ChangeEquipment
3d9ee0c341da63eb7248864d461cf7ba742a5e10
e30eb312ec71ce0b829f7381bda5368027ec84bd
refs/heads/master
<file_sep># Fundamental data types * Value: collection of objects * Operations: insert, remove, iterate, test if empty. * Intent is clear when we insert. * Which item do we remove? * Stack: examine the item most recently added. LIFO * Queue: examine the item least recently added. FIFO # Stack ## Linked List implementation ## Array implementation <file_sep>package com.vv.prototest.algorithms.algs4.chap1.seq5s; import com.vv.prototest.algorithms.algs4.stdlib.StdIn; import com.vv.prototest.algorithms.algs4.stdlib.StdOut; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author x-spirit */ public abstract class UnionFind implements UF{ /** * 类内部 本包 子类 外部包 public √ √ √ √ protected √ √ √ × default √ √ × × private √ × × × */ protected int count; protected int[] id; @Override public void initialization(int count){ this.count = count; id = new int[count]; //initially, we set up the id array with each entry equal to its index. for (int i = 0; i < count; i++) id[i] = i; } /** * Generic programming in Java. * @param <T> * @param clz * @param count * @return */ public static <T extends UF> T getUF(Class<T> clz, int count) { try { T t = clz.newInstance(); t.initialization(count); return t; } catch (InstantiationException | IllegalAccessException ex) { Logger.getLogger(UnionFind.class.getName()).log(Level.SEVERE, null, ex); System.exit(-1); } return null; } public boolean validate(int n) { return n >= 0 && n < id.length; } public static void execute(String[] args){ int N = StdIn.readInt(); //UF uf = getUF(QuickFind.class, N); //UF uf = getUF(QuickUnion.class, N); UF uf = getUF(WeightedQuickUnion.class, N); while (!StdIn.isEmpty()){ int p = StdIn.readInt(); int q = StdIn.readInt(); if (!(uf.validate(p) && uf.validate(q))){ System.exit(0); } if (!uf.isConnected(p, q)) { uf.union(p, q); StdOut.println(p + " " + q); StdOut.println("======"); uf.showConnectivity(); StdOut.println("======"); } else { StdOut.printf("%s and %s are already connected!\n", p, q); } StdOut.printf("%s connected components\n", uf.count()); } } public static void main(String[] args) { execute(args); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vv.prototest.wordsnet.html; import com.vv.prototest.wordsnet.Parser; import com.vv.prototest.wordsnet.word.Word; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import jodd.io.FileUtil; import jodd.io.NetUtil; import jodd.jerry.Jerry; import jodd.jerry.JerryFunction; import jodd.util.SystemUtil; /** * * @author x-spirit */ public class TestBigWordParser extends Parser { private static final String TEST_BIG_URI = "http://testbig.com/dictionary/search/"; @Override public Word parse() { final Word word = new Word(this.getArg()); try { // download the page super-efficiently File file = new File(SystemUtil.getTempDir(), word.getWord() + ".html"); NetUtil.downloadFile(TEST_BIG_URI + word.getWord(), file); // create Jerry, i.e. document context Jerry docroot = Jerry.jerry(FileUtil.readString(file)); // parse senses this.parseSenses(docroot, word); // parse prefix, root, suffix } catch (IOException ex) { Logger.getLogger(TestBigWordParser.class.getName()).log(Level.SEVERE, null, ex); } finally { // return result return word; } } private void parseSenses(final Jerry docroot, final Word word) { final AtomicInteger pos_index = new AtomicInteger(); final AtomicInteger sense_index = new AtomicInteger(); final StringBuffer sb_synonyms = new StringBuffer(); final StringBuffer sb_gloss = new StringBuffer(); docroot.$("div#page div.wrapper div#primary.short div.singlepage div.messages div table:eq(0) tr") .each(new JerryFunction() { @Override public boolean onNode(Jerry $this, int index) { try { // System.out.println("---"); // System.out.println($this.$("td").html()); // parse each row Jerry $td = $this.$("td"); List<Word.MeaningPos> poses = word.getMeaningPos(); if ($td.attr("class").equals("meaningPos")) {// parse part of speech word.addNewMeaningPos(pos_index.incrementAndGet(), $td.find(".meaningPosColor").text()); sense_index.set(0); } else if ($td.attr("class").equals("meaningSense")) {// parse senses if (poses.size() == pos_index.get()) { sb_synonyms.append($td.find(".meaningWordColor").html()); } } else if ($td.attr("class").equals("meaningGloss")) {// parse gloss and samples if (poses.size() == pos_index.get()) { sb_gloss.append($td.find(".meaningGlossColor").html() .replace("<font color=\"red\">", "").replace("</font>", "")); } } if (sb_synonyms.length() > 0 && sb_gloss.length() > 0) {// composite synomyms and gloss poses.get(poses.size() - 1) .addMeaningSense(sense_index.incrementAndGet(), sb_synonyms.indexOf("(") >= 0 ? sb_synonyms.delete(sb_synonyms.indexOf("("), sb_synonyms.indexOf(")") + 1).toString().trim() : sb_synonyms.toString().trim(), sb_gloss.toString().split("\"")[0], sb_gloss.toString().contains("\"")? sb_gloss.toString().split("\"")[1].replace("\"", "") : null); sb_synonyms.delete(0, sb_synonyms.length()); sb_gloss.delete(0, sb_gloss.length()); } } catch (Exception e) { e.printStackTrace(); } return true; } }); } } <file_sep>package com.vv.prototest.javafx.webcapture; import java.io.File; /** * Created by zhangwei on 14-4-29. */ public class CaptureTest { public static void main(String[] args) { System.getProperties().forEach((Object k, Object v) -> { System.out.println(k + " = " + v); }); WebCapturer.capture("http://www.google.com",1000,8000, System.getProperty("user.home") +File.separator +"Pictures" +File.separator +"webcapture" + File.separator +System.currentTimeMillis()+".png"); } } <file_sep># Scientific method applied to analysis of algorithms ## Scientific method * **Observe** some feature of the natural world * **Hypothesize** a model that is consistent with the observations. * **Predict** events using the hypothesis. * **Verify** the predictions by making further **observations**. * **Validate** by repeating until the hypothesis and observation agree. ## Principles * Experiments must be **reproducible**(可复现的). * Hypothesis must be **falsifiable**(可验证的). ## Observing ### Measuring the running time * **Stopwatch** will automatically do this. ### Empirical analysis Doubling the input size, measuring the running time. ### Data analysis **Standard plot** or **log-log plot**, and then carry out **Regression** to fit straight line through data points: `a*N^b` In a log-log plot on the base of 2, you might get a straight line with slope of `b`. After this, we might get to the **hypothesis**, and we can even make **prediction** based on our hypothesis. By carrying out some new experiments and **observing** the data again, we can **validate** the hypothesis. Doubling hypothesis: this is a way to estimate `b` in a power-law relationship. We measure the running time, calculate the growth ratio of running time for each data input, and then calculate the lg ratio. Then we can easily get `b`. Then we can even calculate the constant `a` by `a = running_time/N^b`. ## Mathematical Models of running time. Total running time = sum of cost * frequency for all operations. * Need to analyze program to determine set of operations. * Cost depends on machine, compiler. * Frequency depends on algorithm, input data. "In principle, accurate mathematical models are available" -- <NAME> Cost of basic operations: * integer add : 2.1ns * integer multiply : 2.4ns * integer divide : 5.4ns * fp add : 4.6ns * fp multiply : 4.2ns * fp divide : 13.5ns * sine : 91.3ns * arctangent : 129 ns * variable declaration: c1 * assignment statement: c2 * integer compare : c3 * array element access: c4 * array length : c5 * **1D array allocation** : c6N (In java all the elements in an array will be initialized to 0) * **2D array allocation** : c7N^2 * string length : c8 * substring extraction: c9 * **string concatenation**: c10N ### Simplification 1: Cost Model * Use some basic operation (that's maybe the most expensive/the one that's executed the most often) as a proxy for running time. ### Simplification 2: Tilde Notation * Estimate running time or memory as a function of input size N. * Ignore the lower order terms. * When N is large, terms are negligible. * When N is small, we don't care. 1/6N^3 + 20N + 16 ~1/6N^3 ## Order-of-growth Classifications Only a small set of functions can be applied to the order of growth. <table style="white-space: nowrap;" width="80%" border= "1" cellspacing= "0" cellpadding= "0"> <tr> <td>order of growth</td><td>name</td><td>typical code framework</td><td>description</td><td>example</td><td>T(2N)/T(N)</td> </tr> <tr> <td>1</td><td>constant</td><td>a=b+c</td><td>statement</td><td>add two numbers</td><td>1</td> </tr> <tr> <td>logN</td><td>logarithmic</td><td>while(N&gt;1)<br/>{ N=N/2;... }</td><td>divide in half</td><td>binary search</td><td>~1</td> </tr> <tr> <td>N</td><td>linear</td><td>for(int i=0;i&lt;N;i++)<br/>{ ... }</td><td>loop</td><td>find the maximum</td><td>2</td> </tr> <tr> <td>N*logN</td><td>linearithmic</td><td>divide and conquer</td><td>divide and conquer</td><td>merge sort</td><td>~2</td> </tr> <tr> <td>N^2</td><td>quadratic</td><td>for(int i=0;i&lt;N;i++){<br/>for(int j=0;j&lt;N;j++){<br/>...}<br/>}</td><td>double loop</td><td>check all pairs</td><td>4</td> </tr> <tr> <td>N^3</td><td>cubic</td><td>for(int i=0;i&lt;N;i++){<br/>for(int j=0;j&lt;N;j++){<br/>for(int k=0;k<N;k++){...}<br/>}<br/>}</td><td>triple loop</td><td>check all triples</td><td>8</td> </tr> <tr> <td>2^N</td><td>exponential</td><td>combinational search</td><td>exhaustive search</td><td>check all subsets</td><td>T(N)</td> </tr> </table> When applying an algorithm, the first thing to do is to make sure the order of growth is not beyond quadratic. Since we need linear or linearithmic algorithms to keep pace with Moore's law. * Ex1. Binary Search. ``` T(N) <= T(N/2) + 1 <= T(N/4) + 1 + 1 <= T(N/8) + 1 + 1 + 1 .... <= T(N/N) + lgN = 1 + lgN ``` * Ex2. 3-SUM with BinarySearch ``` N^2*lgN ``` # Type of analysis ## Best case - Lower bound on cost. * Determined by "easiest" input. * Provides a goal for all inputs. ## Worst case - Upper bound on cost. * Determined by "most difficult" input. * Provides a guarantee for all inputs. ## Average case - Expected cost for random input * Need model for random input * Provides a way to predict performance ## Ex1. Array accesses for brute-force 3-SUM * Best : ~1/2N^3 * Worst : ~1/2N^3 * Average : ~1/2N^3 ## Ex2. Compares for binary search * Best : ~1 * Worst : ~lgN * Average : ~lgN ## Input model and actual data don't match? Need to understand input to effectively process it. Approach1: design for the worst case Approach2: randomize, depend on probabilistic guarantee. ## Goals * Establish "difficulty" of a problem. * Develop "optimal" algorithms ## Approach * Suppress details in analysis: analyze "to within a constant factor" * Eliminate variability in input model by focusing on the worst case. ## Optimal algorithm. * Performance guarantee (to within a constant factor) for any input * No algorithm can provide a better performance guarantee. # Commonly-used notations in the theory of algorithms <table style="white-space: nowrap;" width="80%" border= "1" cellspacing= "0" cellpadding= "0"> <tr> <td>notation</td><td>provides</td><td>example</td><td>shorthand for</td><td>used to</td> </tr> <tr> <td>Tilde</td><td>leading term</td><td>~10 N^2</td><td>10N^2<br/>10N^2 + 22NlogN<br/>5N^2 + 22 N +37<br/>...</td><td>provide approximate model</td> </tr> <tr> <td>Big Theta</td><td>asymptotic order of growth</td><td>θ(N^2)</td><td>1/2N^2<br/>10N^2<br/>5N^2 + 22 N logN + 3N<br/>...</td><td>classify algorithms</td> </tr> <tr> <td>Big Oh</td><td>θ(N^2) or smaller</td><td>O(N^2)</td><td>10N^2<br/>100N<br/>22N logN + 3N<br/>...</td><td>develop upper bounds</td> </tr> <tr> <td>Big Omega</td><td>θ(N^2) or larger</td><td>Ω(N^2)</td><td>1/2 N^2<br/>N^5<br/>N^3 + 22NlogN + 3N<br/>...</td><td>develop lower bounds</td> </tr> </table> # Steps to developing a usable algorithm. * Model the problem * Find an algorithm to solve it. * Fast enough? Fits in Memory? * If not, figure out why. * Find a way to address the problem. * Iterate until satisfied. # The scientific method. # Mathematical analysis. # Memory Usage ## Basics * KB= 1 thousand or 2^10 bytes * MB= 1 million or 2^20 bytes * GB= 1 billion or 2^30 bytes * Old Machines (32-bit) -> 4byte pointers * Modern Machine (64-bit) -> 8byte pointers ## Java typical memory usage: * primitives: boolean 1 byte 1 char 2 int 4 float 4 long 8 double 8 * arrays: char[] 2N + 24 int[] 4N + 24 double[] 8N + 24 char[][] ~2MN int[][] ~4MN double[][] ~8MN * Object overhead 16 bytes * Reference 8 bytes * Padding Each object uses a multiple of 8 bytes. * Inner Class pointer 8 bytes ## Shallow memory usage: * Don't count referenced objects ## Deep memory usage: * If array entry or instance variable is a reference, add memory (recursively) for referenced object. <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vv.prototest.basics.initialorder; /** * * @author x-spirit */ public class SubClass extends Parent { // 静态变量 public static String s_StaticField = "子类--静态变量"; // 变量 public String s_Field = "子类--变量"; // 静态初始化块 static { System.out.println(s_StaticField); System.out.println("子类--静态初始化块"); } // 初始化块 { System.out.println(s_Field); System.out.println("子类--初始化块"); } // 构造器 public SubClass() { System.out.println("子类--构造器"); } // 程序入口 public static void main(String[] args) { new SubClass(); } } <file_sep># Dynamic connectivity problem What we want to achieve is: Given a set of N objects. * By union command: connect two objects. * By find/connected query: is there a path connecting the two objects? # Quick-Find * Eager approach ## Data Structure * int[] id * p is connected to id[p] * p & q are connected iff id[p] == id[q] ## Find : * check if id[p]==id[q] ## Union: * To merge components containing p and q, change **all entries whose id equals id[p]** to id[q](That's what "eager approach" means) * many values can change. ## Cost model: * initialize : N * union : N * find : 1 ## Defect: * Union operation is too expensive. (N array accesses) * Trees are flat, but too expensive to keep them flat. # Quick-Union * Lazy approach ## Data Structure * int[] id; * id[i] is the parent of i. * root of i is id[id[id[...id[i]...]]] (keep going until it doesn't change, this algorithm ensures no cycles) ## Find : * check if p and q have the same root. ## Union : * to merge components containing p and q, set the id of p's root to the id of q's root. Which means "let the parent of q's root also be the parent of p's root" * only one value changes. ## Cost Model: * initialize : N * union : N (includes cost of finding roots) * find : N ## Defect: * Find operation is too expensive. (N array accesses in worst case) * Trees can get tall. # Weighted Quick-Union * Lazy approach ## Data Structure * Same as quick-union, but maintain extra array size[] to keep track of the number of objects in each tree. ## Find : * Identical to quick-union ## Union : * let the root of larger tree be the parent of the root of smaller tree, namely, link the root of smaller tree to the root of larger tree. * update the size[] array. ## Cost Model : * initialize : N * union : lgN (includes cost of finding roots, actually constant time) * find : lgN ## Defect: * Find takes time proportional to depth of p and q. # Weighted Quick-Union improvement * Right after computing the root of p, set the id of each examined node to point to that root, which means "let that root be the parent of each examined node" * 2-pass implementation: add second loop to root() to set id[i] to the root, where i is the examined node. * 1-pass implementation: make every other node in path point to its grandparent (thereby halving path length) # Union-Find Applications * **Percolation** * Games (Go, Hex) * **Dynamic connectivity** * Least common ancestor. * **Equivalence of finite state automata.** * Hoshen-Kopelman algorithm in physics. * Hinley-Miler polymorphic type inference. * **Kruskai's minimum spanning tree algorithm.** * Compiling equivalence statements in Fortran. * Morphological attribute openings and closings. * **Matlab's `bwlabel()` function in image processing.** ## Percolation: * N-by-N grid of sites. * Each site is open with probability p (or, say, blocked with probability `1 - p`) * System percolates iff top and bottom are connected by open sites. Suppose p is getting larger and larger, when it get to somewhere called barrier, the top and bottom will be rest assured connected. The value is somewhat close to 0.593 in some cases. How to check percolation? Set virtual site connecting to all the top sites and another site connecting to all the bottoms, then we run Union-Find algorithm. <file_sep>package com.vv.prototest.javafx.webcapture; import javafx.animation.PauseTransition; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.SnapshotParameters; import javafx.scene.control.ScrollPane; import javafx.scene.image.WritableImage; import javafx.scene.layout.VBox; import javafx.scene.web.WebView; import javafx.stage.Stage; import javafx.util.Duration; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.lang.Double;import java.lang.Exception;import java.lang.Override;import java.lang.String;import java.lang.System;import java.util.Map; /** * Created by zhangwei on 14-4-29. * * @author zhangwei */ public class WebCapturer extends Application{ private WebView webView; public static void capture(String url, double width, double height, String filePath) { File f = new File(filePath).getParentFile(); f.mkdirs(); Application.launch(WebCapturer.class, "--url="+url, "--width="+width, "--height="+height, "--filePath="+filePath); } @Override public void start(Stage stage) throws Exception { Map<String, String> params = this.getParameters().getNamed(); final String url = params.get("url"); final double width = Double.valueOf(params.get("width")); final double height = Double.valueOf(params.get("height")); final File capturedImg = new File(params.get("filePath")); webView = new WebView(); final PauseTransition pt = new PauseTransition(); pt.setDuration(Duration.millis(500)); pt.setOnFinished(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { SnapshotParameters sp = new SnapshotParameters(); WritableImage image = webView.snapshot(sp, null); BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null); try { ImageIO.write(bufferedImage, "png", capturedImg); java.lang.System.out.println("Captured WebView to: " + capturedImg.getAbsoluteFile()); } catch (IOException e) { e.printStackTrace(); } finally { System.exit(0); } } }); webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() { @Override public void changed(ObservableValue<? extends Worker.State> observableValue, Worker.State state, Worker.State state2) { if (state2 == Worker.State.SUCCEEDED){ webView.setPrefSize(width, height); pt.play(); } } }); ScrollPane webViewScroll = new ScrollPane(); webViewScroll.setContent(webView); webViewScroll.setPrefSize(800, 300); VBox layout = new VBox(10); layout.setStyle("-fx-padding: 10; -fx-background-color: cornsilk;"); layout.getChildren().setAll( webViewScroll ); stage.setScene(new Scene(layout)); stage.show(); webView.getEngine().load(url.startsWith("http://") ? url : "http://" + url); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vv.prototest.algorithms.algs4.chap1.seq5s; import com.vv.prototest.algorithms.algs4.stdlib.StdOut; import java.util.HashSet; import java.util.Set; /** * * @author x-spirit */ public class WeightedQuickUnion extends UnionFind{ private boolean doPathCompression = false; private int[] size; @Override public void initialization(int count) { this.count = count; id = new int[count]; size = new int[count]; for (int i = 0; i < count; i++){ id[i] = i; size[i] = 1; } } @Override public int find(int p) { return root(p); } /** * find the root of i. * @param i * @return */ private int root(int i) { while (i != id[i]){ if (doPathCompression){ id[i] = id[id[i]];// path compression } i = id[i]; } return i; } @Override public int count() { return this.count; } @Override public boolean isConnected(int p, int q) { return find(p) == find(q); } /** * link the root of smaller tree to the root of larger tree. * @param p * @param q */ @Override public void union(int p, int q) { int proot = find(p); int qroot = find(q); if (proot == qroot) return; if (size[proot] < size[qroot]) { id[proot] = qroot; size[qroot] += size[proot]; } else { id[qroot] = proot; size[proot] += size[qroot]; } count--; } @Override public void showConnectivity() { Set<Integer> set = new HashSet<>(id.length); for (int i = 0; i < id.length; i++) { if (set.contains(i)) { continue; } int root = find(i); StringBuilder sb = new StringBuilder(); appendChild(root, 0, sb, set); StdOut.println(sb.toString()); } } private void appendChild(int parent, int pLevel, StringBuilder sb, Set<Integer> set) { int curLevel = pLevel + 1; set.add(parent); if (pLevel > 0) { sb.append("──"); } sb.append(String.valueOf(parent)).append("\n"); for (int i = 0; i < id.length; i++) { if (i == parent) { continue; } if (id[i] == parent) { for (int j = 0; j < pLevel; j++) { sb.append("│ "); //sb.append(" "); } sb.append("├"); appendChild(i, curLevel, sb, set); } } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vv.prototest.basics; /** * * @author x-spirit */ public class StringTest { public static void main(String[] args) { String in = "abc"; changeString(in); System.out.println(in); } public static String changeString(String in) { in += "d"; return in; } // ****** an explicit error may occur during compling phase // ****** due to the unchangable variable "in" which was modified by "final" // // public static String changeString(final String in) { // // in += "d"; // // return in; // } } <file_sep>This is a project demostrating all fundamental knowledge in Java Programming, including the following fields of study: <p style="text-shadow: 5px 5px 5px #FF0000;">algorithms,</p> <p style="text-shadow: 5px 5px 5px #FF0000;">concurrency,</p> <p style="text-shadow: 5px 5px 5px #FF0000;">design patterns,</p> <p style="text-shadow: 5px 5px 5px #FF0000;">Java basic,</p> <p style="text-shadow: 5px 5px 5px #FF0000;">Java advanced,</p> <p style="text-shadow: 5px 5px 5px #FF0000;">and other features.</p> <b style="text-shadow: 5px 5px 5px #FF0000;">新年好</b><file_sep>package com.vv.prototest.algorithms.algs4.chap1.seq2; import com.vv.prototest.algorithms.algs4.Stopwatch; import com.vv.prototest.algorithms.algs4.stdlib.StdOut; import com.vv.prototest.algorithms.algs4.stdlib.In; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.function.Predicate; /************************************************************************* * Compilation: javac ThreeSum.java * Execution: java ThreeSum input.txt * Dependencies: In.java StdOut.java Stopwatch.java * Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt * http://algs4.cs.princeton.edu/14analysis/2Kints.txt * http://algs4.cs.princeton.edu/14analysis/4Kints.txt * http://algs4.cs.princeton.edu/14analysis/8Kints.txt * http://algs4.cs.princeton.edu/14analysis/16Kints.txt * http://algs4.cs.princeton.edu/14analysis/32Kints.txt * http://algs4.cs.princeton.edu/14analysis/1Mints.txt * * A program with cubic running time. Read in N integers * and counts the number of triples that sum to exactly 0 * (ignoring integer overflow). * * % java ThreeSum 1Kints.txt * 70 * * % java ThreeSum 2Kints.txt * 528 * * % java ThreeSum 4Kints.txt * 4039 * *************************************************************************/ /** * The problem we are gonna to solve is: * Given N distinct integers, how many triplets sum to exactly zero? * * The <tt>ThreeSum</tt> class provides static methods for counting * and printing the number of triples in an array of integers that sum to 0 * (ignoring integer overflow). * <p> * This implementation uses a triply nested loop and takes proportional to N^3, * where N is the number of integers. * <p> * For additional documentation, see <a href="http://algs4.cs.princeton.edu/14analysis">Section 1.4</a> of * <i>Algorithms, 4th Edition</i> by <NAME> and <NAME>. * * @author <NAME> * @author <NAME> */ public class ThreeSum { /** * Prints to standard output the (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0. * @param a the array of integers */ public static void printAll(int[] a) { int N = a.length; for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j++) { for (int k = j+1; k < N; k++) { if (a[i] + a[j] + a[k] == 0) { StdOut.println(a[i] + " " + a[j] + " " + a[k]); } } } } } /** * Returns the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0. * @param a the array of integers * @return the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0 */ public static int count(int[] a) { int N = a.length; int cnt = 0; for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j++) { for (int k = j+1; k < N; k++) { if (a[i] + a[j] + a[k] == 0) { cnt++; } } } } return cnt; } /** * Reads in a sequence of integers from a file, specified as a command-line argument; * counts the number of triples sum to exactly zero; prints out the time to perform * the computation. */ public static void main(String[] args) { String path = System.getProperties().getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; String classPath = ThreeSum.class.getPackage().getName().replace('.', File.separatorChar); path = path + classPath + File.separator; File dir = new File(path); Predicate<File> endWithKintsTxt = (n) -> n.getName().endsWith("Kints.txt"); Arrays.asList(dir.listFiles()).stream().filter(endWithKintsTxt) .sorted((f1, f2) -> f1.getName().compareTo(f2.getName())).forEach((file -> { System.out.println(" ==========" + file.getPath() + " ==========="); In in = new In(file); int[] a = in.readAllInts(); Stopwatch timer = new Stopwatch(); int cnt = count(a); StdOut.println("elapsed time = " + timer.elapsedTime()); StdOut.println(cnt); })); } }
6e19266118932c12fe33d19a30979fc2a1ab6efc
[ "Markdown", "Java" ]
12
Markdown
zhangwei217245/ProtoTest
747684236e847a9b7009f4467c35a09977dfe15c
0a491617ee648e34f0cc477c17c2041beb5cd27b
refs/heads/master
<file_sep>#include <SR04.h> #include <SimpleDHT.h> //Temp and Hum int pinDHT11 = 2; SimpleDHT11 dht11; //Ultrasonic #include "SR04.h" #define TRIG_PIN 12 #define ECHO_PIN 11 SR04 sr04 = SR04(ECHO_PIN,TRIG_PIN); long light; void setup() { Serial.begin(9600); } void loop() { byte temperature = 0; byte humidity = 0; if (dht11.read(pinDHT11, &temperature, &humidity, NULL)) { // Serial.print("Read DHT11 failed."); return; } //ultrasonic light=sr04.Distance(); char buffer[30]; sprintf(buffer, "%d,%d,%d",(int)temperature, (int)humidity, (int)light); //sprintf(buffer, " %d, %d, %d", (int)light, (int)temperature, (int)humidity); Serial.println(buffer); // DHT11 sampling rate is 1HZ. delay(2000); } <file_sep>//charting // ================================================================== var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: ["0"], datasets: [{ label: "ambient light", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [0], }] }, // Configuration options go here options: {} }); //get data from API //============================================================================ var currentData = {}; var dataCounter = 0; setInterval(function(){ axios.get('http://localhost:3000/fetchdata') .then(function (response) { currentData = response.data; //console.log(currentData); dataCounter += 1; boolShiftData = 0; //update light chart with live values //==================================================================== chart.data.labels.push(String(dataCounter)); chart.data.datasets.forEach((dataset) => { if (currentData.currentLight < 50){ dataset.data.push(currentData.currentLight); }else{ dataset.data.push(50); } if(dataCounter < 20){ //console.log('datacounter less than 10') }else{ dataset.data.shift(); chart.data.labels.shift(); } }); chart.update(); }) .catch(function (error) { console.log(error); }); }, 400); // setting up vue app //==================================================================== var app = new Vue({ el: '#app', data: { message: 'Hello Vue!', temperatureInput: 25, percentHumidity: 0, percentTransparency: 0 }, methods: { processTempInput: function (temperatureInput) { var usedLightValue = 213; var usedTempValue = 21; //sanity checks for sensor values if(currentData.currentLight >= 1 && currentData.currentLight <= 450){ usedLightValue = currentData.currentLight; } if(currentData.currentTemp >= 10 && currentData.currentTemp <= 30){ usedTempValue = currentData.currentTemp; } // smart window transparency calculation var SCLPlaceholder = (usedLightValue/50)*1367; this.percentTransparency = 40*(temperatureInput-usedTempValue)/(1*SCLPlaceholder)+((3.56*7)/SCLPlaceholder)-0.93-0.55; if(this.percentTransparency > 100 || this.percentTransparency < 5){ //this.percentTransparency = 5; } // room humidity calculation using quadratic equation console.log('humidity calculation started'); var farenheitTemp = usedTempValue*9/5+32; var tempInputFarenheit = temperatureInput*9/5+32; console.log("sensorfarenheitTemp: " + farenheitTemp); console.log("tempInputFarenheit: " + tempInputFarenheit); var a = -0.5481717+0.0085282*farenheitTemp-0.00000199*farenheitTemp*farenheitTemp; var b = 10.1433127-0.22475541*farenheitTemp+0.0012874*farenheitTemp*farenheitTemp; var c = -42.379+2.04901523*farenheitTemp-0.0068783*farenheitTemp*farenheitTemp-tempInputFarenheit; console.log( "a: " + a + " b: " + b + " c: " + c); if ((b*b - 4*a*c) < 0) { c = c*-1; } var result = (-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a); console.log('result 1: ' + result); if (result > 100 || result < 1){ var result = (-1 * b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a); console.log('result 2:' + result); } if(result < 7){ result = 6.87; } result = result*15-temperatureInput*0.78; console.log("result after result*40-temperatureInput*0.3: " + result); if (result < 20){ result = 10; }else if (result > 95){ result = (Math.random()*(80-20+1)+20); } this.percentHumidity = result; console.log(this.percentHumidity); } } })
e6ca0e6f8c300a20bb9182feef88743033ab68c7
[ "JavaScript", "C++" ]
2
C++
chantellechan1/missionhack2018
8af9b56c37d143706b758b9ca53de4a7fd71e8fd
06a0ff1b6a76cc03cd58c95ea32cf6c8d63d49c1
refs/heads/main
<file_sep>from sklearn.base import BaseEstimator, RegressorMixin from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import cross_val_score, GridSearchCV from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, zero_one_loss, mean_squared_error import numpy as np class model_contextual_knnReg(BaseEstimator,RegressorMixin): def __init__(self): super().__init__() self.clf = None def fit(self, X, y): ''' param X [[Latitude,Longitude,GpsHeading,GpsSpeed]*m] y [[Latitude,Longitude]*m] ''' params = {'n_neighbors':range(1,10)} knr = KNeighborsRegressor(weights='distance') clf = GridSearchCV(knr,params) #idx = int(len(X)*0.7) #X_train, X_test, y_train, y_test = X[:idx], X[idx:], y[:idx], y[idx:] #clf.fit(X_train,y_train) clf.fit(X,y) #print('Les meilleurs paramètres trouvés sont:', clf.best_params_) #y_test, y_pred = y_test, clf.predict(X_test) #print(classification_report(y_test, y_pred)) self.clf = clf return self def predict(self,X): ''' param [[Trip,Latitude,Longitude,GpsTime]*m] retourne [[nextlat, nextlongi]*m] : prochaine lat et longi ''' return self.clf.predict(X) #def score(self,X_test,y_test): # return mean_squared_error(y_test,self.predict(X_test)) <file_sep>from sklearn.base import BaseEstimator import numpy as np from sklearn.metrics import mean_squared_error #### Modele Physique class model_physique1(BaseEstimator): def __init__(self): super().__init__() #self.step_test = None #self.set_params(**{'step_test':step_test}) self.globaltheta = None def fit(self, X, y): return self def predict(self,X): ''' param [['Trip','Latitude','Longitude','GpsHeading','GpsTime']*m] retourne [[nextlat, nextlongi]*m] : prochaine lat et longi ''' mat = [] groups = X.groupby('Trip') for group in groups: mat.append(group[1][['Latitude','Longitude','GpsTime']].to_numpy()) #print(mat) try: res = [] train_step = mat[0][1][2] - mat[0][0][2] except IndexError: print('indexerror',X, mat) #print(train_step) for X_t in mat: res.append(X_t[0][:2]) for i in range(1,len(X_t)): v = np.array([ (X_t[i][0] - X_t[i-1][0]) / train_step , (X_t[i][1] - X_t[i-1][1]) / train_step ]) if self.globaltheta: v = v*self.globaltheta #print(v) #print(self.step_test) res.append(X_t[i-1][:2] + train_step*v) #print(self.step_test) #print(len(res), len(res[0])) #print(res) return np.array(res) <file_sep>import numpy as np from sklearn.base import BaseEstimator, RegressorMixin import dataSource as ds import Eval as ev class physic_model(BaseEstimator,RegressorMixin): def __init__(self, step_train, step_test): super().__init__() self.v = [] self.step_train = step_train self.step_test = step_test self.ecart = None def fit(self, X, y): ''' caculate parameters vector speed self.v for one trajectory by taking the last 2 data points Parameters ---------- X : previous data points [[Lat,Lon,GpsTime]*m,[]] y : current data points [[Lat,Lon,GpsTime]*m,[]] v : [[dLat/t, dLon/t, GpsTime],[]] ''' #print('shapeX',X.shape) for trip in range(len(X)): X_t = X[trip] y_t = y[trip] l_v = [] differ = y_t - X_t #print('d',X_t.shape,y_t.shape) for i in range(len(differ)): l_v.append([differ[i][0]/differ[i][2], differ[i][0]/differ[i][2], X_t[i][2]]) self.v.append(l_v) self.ecart = differ[0][2] / self.step_train return self def getInterval(self,x,trip): """ x : [Lat,Lon,GpsTime] trouver l'intervalle de GPSTime qu'il correspond """ t = x[-2] v_t = self.v[trip] for i in range(len(v_t)): if v_t[i][2] > t: return i-1 return -1 def predict(self,X): ''' predict next position Parameters ---------- X : [[Lat,Lon,GpsTime]*M] On prédict les prochains points de X , Duration = step_test * self.ecart ''' duration = self.step_test * self.ecart res = [] for trip in range(len(X)): X_t = X[trip] v_t = self.v[trip] res_t = [] for i in range(len(X_t)): x = X_t[i] indice = self.getInterval(x,trip) vi = np.array(v_t[indice]) res_t.append(x[:2] + duration*vi[:2]) res.append(np.array(res_t)) return res def moindre_c(X_predit, X_test): return ((X_predit-X_test)**2).sum() freq_train = 1000 freq_test = 400 attrs_x = ['Latitude','Longitude','GpsTime'] labels = ['Latitude','Longitude','GpsTime'] df = ds.importData() latitude_min, latitude_max, longitude_min, longitude_max, ecart_x, ecart_y = ds.calcul_param(df) pos = [4,4] tr = ds.trouve_data_case(df, pos, latitude_min, longitude_min, ecart_x, ecart_y) X_train, X_test, y_train, y_test = ds.train_test_split(df,attrs_x, labels,freq_train,freq_test) model1 = physic_model(freq_train , freq_test) model1.fit(X_train, y_train) y_pred = model1.predict(X_test) score = np.mean([moindre_c(yp,yt) for (yp,yt) in zip(y_pred, y_test)]) print("y", score) """models = [physic_model(freq_train , freq_test)] traitement = ev.Traitement(tr,attrs_x,labels) traitement.set_data_train_test() #Apprentissage des modèles et évaluation à partir de l'objet traitement evaluateur = ev.Evaluation(models,traitement) evaluateur.fit() res_pred = evaluateur.predict(X_test) #Affichage des résultats evaluateur.afficher_resultats()"""<file_sep>from sklearn.metrics import mean_squared_error from sklearn.pipeline import make_pipeline import plotly.express as px import plotly.graph_objects as go from plotly.offline import iplot,plot import dataSource as ds import dataVisualization as dv from copy import deepcopy import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns # ============================================================================= # Class Traitement # ============================================================================= class Traitement: """ La classe Traitement permet de construire les données X,y d'apprentissage et de test. """ def __init__(self, df, l_attrs_x, labels, freq_train=1000, freq_test=400, preprocessor=None): #DataFrame self.df = df #features self.l_attrs = l_attrs_x #targets self.labels = labels #preprocessor self.preprocessor = preprocessor #fréquences self.freq_train = freq_train self.freq_test = freq_test #Données d'apprentissage/test pour chaque modèle self.l_Xtrain = [] self.l_Ytrain = [] self.l_Xtest = [] self.l_Ytest = [] # Fonction de construction des données de train/test def set_data_train_test(self, train_size=0.8): X_train, X_test, y_train, y_test = ds.create_data_xy(self.df, train_size, self.freq_train, self.freq_test) #On vide les anciennes données s'il y en a self.l_Xtrain = [] self.l_Ytrain = [] self.l_Xtest = [] self.l_Ytest = [] for attrs in self.l_attrs: self.l_Xtrain.append(X_train[attrs]) self.l_Xtest.append(X_test[attrs]) self.l_Ytrain.append(y_train[self.labels]) self.l_Ytest.append(y_test[self.labels]) # ============================================================================= # Class Evaluation # ============================================================================= class Evaluation : """ La classe Evaluation permet d'entrainer des modèles à partir de la classe Traitement et d'en afficher des résultats. """ def __init__(self, models, traitement): self.models = models self.traitement = traitement self.preprocessor = self.traitement.preprocessor self.l_Xtrain = self.traitement.l_Xtrain self.l_Ytrain = self.traitement.l_Ytrain self.l_Xtest = self.traitement.l_Xtest self.l_Ytest = self.traitement.l_Ytest self.labels = self.traitement.labels #Ajout du preprocessor à la pipeline s'il y en a un if self.preprocessor is not None : self.models_pip = [make_pipeline(self.preprocessor[i], self.models[i]) for i in range(len(self.models))] else: self.models_pip = self.models # for mi in range(len(models)): # if type(models[mi]).__name__ == 'model_physique1': # temp = self.l_Xtest[mi].copy() # temp['index'] = temp.index # f = temp.groupby(['Trip']).nth(1).reset_index()['index'].values # self.l_Ytest[mi].drop(f, inplace=True) def fit(self): """ Fonction qui entraine tous nos modèles. """ for i in range(len(self.models)): self.models_pip[i].fit(self.l_Xtrain[i], self.l_Ytrain[i]) def score(self): """ Fonction retournant une liste de scores sur les données de test pour chaque modèle. """ return [self.models_pip[i].score(self.l_Xtest[i], self.l_Ytest[i]) for i in range(len(self.models))] def predict(self, X): """ Fonction retournant une liste de prédiction sur X pour chaque modèle. """ return [self.models_pip[i].predict(X[i]) for i in range(len(self.models))] def getCoef(self): """ Fonction retournant les paramètres appris pour chaque modèle. """ return [self.models[i].coef_ for i in range(len(self.models))] def calculMse(self): ypred = self.predict(self.l_Xtest) return [mean_squared_error(self.l_Ytest[i],ypred[i]) for i in range(len(self.models))] # ------------------------- Fonctions d'affichage ------------------------- def afficher_score(self): """ Fonction affichant les scores pour chaque modèle. """ scores = self.score() for i in range(len(self.models)): print(f"Score obtenu pour le modèle {type(self.models[i]).__name__ : <10} : {scores[i]}") def afficher_coef(self): """ Fonction affichant les coefficients pour chaque modèle. """ coefs = self.getCoef() for i in range(len(self.models)): print(f"Coefficients obtenu pour le modèle {i : <10} : {coefs[i]}") def afficher_mse(self): ypred = self.predict(self.l_Xtest) print("MSE sur les données de test:\n") for i in range(len(self.models)): print(f"MSE obtenue pour {type(self.models[i]).__name__ : <10} : {mean_squared_error(self.l_Ytest[i],ypred[i])}") #print(f"MSE obtenue pour {type(self.models[i]).__name__ : <10} : {np.mean((self.l_Ytest[i]-ypred[i])**2)}") def afficher_resultats(self): """ Fonction appelant les autres fonctions d'affichage. """ #self.afficher_score() print() self.afficher_mse() print() #self.afficher_coef() #def afficher_pred(self): # ----------------------------- Fonctions MSE ----------------------------- def tabMSEFreq(self, liste_freq, freq_train,train_size=0.8): tab_mse = [] models = [deepcopy(m) for m in self.models] for freq in liste_freq: traitement = Traitement(self.traitement.df, self.traitement.l_attrs, self.traitement.labels, freq_train, freq, self.traitement.preprocessor) traitement.set_data_train_test(train_size) evaluateur = Evaluation(models,traitement) evaluateur.fit() tab_mse.append(evaluateur.calculMse()) tab_mse = np.array(tab_mse) """ #Affichage MSE pour le premier modèle plt.figure(figsize=(15,5)) plt.title("Erreur MSE en fonction de la fréquence") plt.plot(liste_freq, tab_mse[:,0], label=type(models[0]).__name__) plt.xlabel("Temps entre deux points") plt.ylabel("MSE") plt.legend() plt.show() """ #Affichage des erreurs MSE des modèles en fonction de la fréquence for i in range(len(models)): plt.figure(figsize=(15,5)) plt.plot(tab_mse[:,i], label=type(models[i]).__name__) plt.xticks(np.arange(len(liste_freq)), np.array(liste_freq)) plt.xlabel("Fréquences") plt.xlabel("Temps entre deux points") plt.ylabel("MSE") plt.legend() plt.show() plt.figure(figsize=(10,5)) for i in range(len(models)): plt.plot(tab_mse[:,i], label=type(models[i]).__name__) plt.xticks(np.arange(len(liste_freq)), np.array(liste_freq)) plt.xlabel("Fréquences") plt.xlabel("Temps entre deux points") plt.ylabel("MSE") plt.legend() plt.show() #Tableau des erreurs MSE en DataFrame columns = [type(m).__name__ for m in models] errMSE = pd.DataFrame(tab_mse, columns=columns, index=liste_freq) return errMSE def matMSECase(self, freq_train, freq_test, lat_min, long_min, e_x, e_y, min_datapts=20, train_size=0.8, n_interval=10): #Copie des modèles models = [deepcopy(m) for m in self.models] # liste matrices erreurs des cases l_mat_err= [np.zeros((n_interval, n_interval)) for i in range(len(models))] df = self.traitement.df #Opérations pour stocker les MSE par effectif et par case eff = np.unique(df["Effectif_case"]) ind_eff = {eff[i]:i for i in range(len(eff))} vit = np.unique(df["Vitesse_moy_case"]) ind_vit = {vit[i]:i for i in range(len(vit))} var = np.unique(df["Vitesse_var_case"]) ind_var = {var[i]:i for i in range(len(var))} l_mse_eff = [np.zeros(len(eff)) for _ in range(len(models))] l_mse_vit = [np.zeros(len(vit)) for _ in range(len(models))] l_mse_var = [np.zeros(len(var)) for _ in range(len(models))] eff_count = [np.zeros(len(eff)) for _ in range(len(models))] vit_count = [np.zeros(len(vit)) for _ in range(len(models))] var_count = [np.zeros(len(var)) for _ in range(len(models))] # parcours de toutes les cases for i in range(n_interval): for j in range(n_interval): # récupération des données de la case case_df=ds.trouve_data_case(df, (i, j), lat_min, long_min, e_x, e_y) #On prend les Trips qui ont au moins $min_datapoints$ points #c'est pas au moins 2 points car tu splits en train et en test, ca aura moins d'un point ctrips, ccounts = np.unique(case_df["Trip"], return_counts=True) ctrips = ctrips[ccounts>min_datapts] case_df = case_df[case_df['Trip'].isin(ctrips)] #Cases qui ont au moins 2 trips if len(pd.unique(case_df["Trip"])) > 1 : traitement = Traitement(case_df, self.traitement.l_attrs, self.traitement.labels, freq_train, freq_test, self.traitement.preprocessor) traitement.set_data_train_test(train_size) l_ypred = self.predict(traitement.l_Xtest) for mi in range(len(models)): mse_ij = mean_squared_error(traitement.l_Ytest[mi],l_ypred[mi]) l_mat_err[mi][n_interval-1-i, j] = mse_ij ei = ind_eff[pd.unique(df['Effectif_case'].loc[case_df.index])[0]] vi = ind_vit[pd.unique(df['Vitesse_moy_case'].loc[case_df.index])[0]] vi2 = ind_var[pd.unique(df['Vitesse_var_case'].loc[case_df.index])[0]] l_mse_eff[mi][ei] += mse_ij l_mse_vit[mi][vi] += mse_ij l_mse_var[mi][vi2] += mse_ij eff_count[mi][ei] += 1 vit_count[mi][vi] += 1 var_count[mi][vi2] += 1 for mi in range(len(models)): tmp = np.where(eff_count[mi] != 0)[0] l_mse_eff[mi][tmp] /= eff_count[mi][tmp] tmp = np.where(vit_count[mi] != 0)[0] l_mse_vit[mi][tmp] /= vit_count[mi][tmp] tmp = np.where(var_count[mi] != 0)[0] l_mse_var[mi][tmp] /= var_count[mi][tmp] fig, ax = plt.subplots(2,2, figsize=(15,13)) for m in range(len(l_mat_err)): # fig, ax = plt.subplots(3,2, figsize=(13,13)) #fig.suptitle(f'{type(models[m]).__name__}', fontsize=16) ax[m//2][m%2].set_title(f"Erreur MSE par case : {type(models[m]).__name__}") # sns.heatmap(l_mat_err[m], linewidths=.5,annot=True, cmap="YlGnBu", yticklabels=np.arange(n_interval-1, -1, -1), ax=ax[0][0]) sns.heatmap(l_mat_err[m], linewidths=.5,annot=True, cmap="YlGnBu", yticklabels=np.arange(n_interval-1, -1, -1), ax=ax[m//2][m%2]) # ax[0][1].set_title("Histogramme des valeurs MSE") # val = l_mat_err[m].ravel()[l_mat_err[m].ravel() != 0] # sns.histplot(val, ax=ax[0][1]) # ax[1][0].set_title("Histplot MSE moy par effectif") # h1 = sns.histplot(x=ind_eff.keys(), y=l_mse_eff[m], ax=ax[1][0], cmap="RdPu", cbar=True) # h1.set(xlabel='Effectif', ylabel='MSE') # ax[1][1].set_title("Histplot MSE moy par vitesse moy") # h2 = sns.histplot(x=ind_vit.keys(), y=l_mse_vit[m], ax=ax[1][1], cmap="YlOrRd", cbar=True) # h2.set(xlabel='Vitesse_moy', ylabel='MSE') # ax[2][0].set_title("Histplot MSE moy par variance vitesse") # h3 = sns.histplot(x=ind_var.keys(), y=l_mse_var[m], ax=ax[2][0], cmap="YlOrRd", cbar=True) # h3.set(xlabel='Variance_vit', ylabel='MSE') # fig.delaxes(ax[2][1]) plt.show() def scatterPred(self, begin_point, end_point): models = [deepcopy(m) for m in self.models] txt = [f"Point n°{t}" for t in range(end_point-begin_point)] trace_0 = go.Scatter(x=self.l_Xtest[0]['Latitude'].iloc[begin_point:end_point], y=self.l_Xtest[0]['Longitude'].iloc[begin_point:end_point], mode="lines",name="Xtest", text=txt) trace_1 = go.Scatter(x=self.l_Ytest[0].iloc[begin_point:end_point,0], y=self.l_Ytest[0].iloc[begin_point:end_point,1], mode="lines+markers", name="Target", text=txt) data = [trace_0,trace_1] l_mse = [] for mi in range(len(models)): ypred = models[mi].predict(self.l_Xtest[mi])[begin_point:end_point] y = self.l_Ytest[mi].iloc[begin_point:end_point].to_numpy() # mse = (ypred-y)**2 mse = [mean_squared_error(y[i], ypred[i]) for i in range(len(y))] #txt = [f"Point n°{i}<br>MSE_Lat = {mse[i,0]}<br>MSE_Long = {mse[i,1]}" for i in range(len(mse))] txt = [f"Point n°{i}<br>MSE = {mse[i]}" for i in range(len(mse))] data.append(go.Scatter(x=ypred[:,0], y=ypred[:,1], mode="lines+markers", name=type(models[mi]).__name__, text=txt)) l_mse.append(np.sum(mse)) layout = go.Layout( title='Targets et Predictions', xaxis = dict( title='Latitude', ticklen = 5, showgrid = True, zeroline = False ), yaxis = dict( title='Logitude', ticklen=5, showgrid=True, zeroline=False, ) ) fig = go.Figure(data=data, layout=layout) iplot(fig, filename="ScatterPred") return l_mse<file_sep>import math import numpy as np import pandas as pd # ============================================================================= # Fonctions récupérations de données # ============================================================================= #Importation des données def importData(): """ None -> DataFrame Importation des données du fichier DataGpsDas.csv en respectant certaines contraintes. """ df = pd.read_csv("../DataGpsDas.csv", nrows=1000000) df = df[(df["Latitude"] >= 42.282970-0.003) & (df["Latitude"] <= 42.282970+0.003) & (df["Longitude"] >= -83.735390-0.003) & (df["Longitude"] <= -83.735390+0.003)] trips, counts = np.unique(df["Trip"], return_counts=True) trips = trips[counts>100] df = df[df['Trip'].isin(trips)] return df #Calcul des paramètres def calcul_param(df, n_interval=10): """ DataFrame * int -> float * float * float * float * float * float Calcul des paramètres bornes longitudes, latitudes et l'écarts entre les intervalles. Returns ------- latitude_min, latitude_max, longitude_min, longitude_max, ecart_x, ecart_y """ #Bornes de la longitude longitude_min = df["Longitude"].min() longitude_max = df["Longitude"].max() #Bornes de la latitude latitude_min = df["Latitude"].min() latitude_max = df["Latitude"].max() #bins / nombre d'intervalles #On sépare en n_interval la latitude et la longitude x_splits = np.linspace(latitude_min,latitude_max, n_interval+1) y_splits = np.linspace(longitude_min,longitude_max, n_interval+1) #Ecart entre deux intervalles des axes ecart_x = x_splits[1]-x_splits[0] ecart_y = y_splits[1]-y_splits[0] return latitude_min, latitude_max, longitude_min, longitude_max, ecart_x, ecart_y #Fonction pour affecter des points du dataframe à une case sur un plan def affectation_2(df, latitude_min, longitude_min, ecart_x, ecart_y): """ DataFrame * float * float * float * float -> Series(int) * Series(int) Retourne l'affectation des points du DataFrame en deux Series, le premier stock les indices x et le second les indices y. """ x = ((df["Latitude"] - latitude_min)/ecart_x).apply(math.floor) y = ((df["Longitude"] - longitude_min)/ecart_y).apply(math.floor) #x = ((df["Latitude"] - latitude_min)/ecart_x).apply(arrondi) #y = ((df["Longitude"] - longitude_min)/ecart_y).apply(arrondi) return x,y def arrondi(x): eps = 1e-8 res = x if np.abs(x-math.ceil(x)) < eps: res = math.ceil(x) else: res = math.floor(x) return res #Permet de sélectionner tous les points appartenant à une case def trouve_data_case(df, pos, latitude_min, longitude_min, ecart_x, ecart_y): """ DataFrame * (int,int) * float * float * float * float -> DataFrame Retourne un DataFrame contenant toutes les lignes se situant dans la case pos. """ x, y = affectation_2(df, latitude_min, longitude_min, ecart_x, ecart_y) i, j = pos return df[(x==i) & (y==j)] #Calcul de l'effectif et de la vitesse moyenne de la case pour chaque point du DataFrame def calcul_eff_vit_moy(df, latitude_min, longitude_min, ecart_x, ecart_y, n_interval=10): """ DataFrame * float * float * float * float * int -> list(int) * list(float) Retourne l'effectif et la vitesse moyenne de la case du point pour toutes les lignes du df. """ effectif_cases = np.zeros((n_interval,n_interval)) vitesse_cases = np.zeros((n_interval,n_interval)) vitesse_var = np.zeros((n_interval,n_interval)) for i in range(n_interval): for j in range(n_interval): case_df = trouve_data_case(df, (i, j), latitude_min, longitude_min, ecart_x, ecart_y) if case_df.shape[0] > 0 : effectif_cases[i,j] = case_df.shape[0] vitesse_cases[i,j] = case_df["GpsSpeed"].mean() vitesse_var[i,j] = case_df["GpsSpeed"].var() #Création d'une nouvelles colonnes stockant les données sur les portions de route sx,sy = affectation_2(df, latitude_min, longitude_min, ecart_x, ecart_y) sx.replace(n_interval, n_interval-1, inplace=True) sy.replace(n_interval, n_interval-1, inplace=True) e = [] #liste effectif moyen pour chaque ligne v = [] #liste vitesse moyenne pour chaque ligne v2 = [] #liste varaince vitesse pour chaque ligne for i in range(sx.shape[0]) : e.append(effectif_cases[sx.iloc[i],sy.iloc[i]]) v.append(vitesse_cases[sx.iloc[i],sy.iloc[i]]) v2.append(vitesse_var[sx.iloc[i],sy.iloc[i]]) return e, v, v2 # Calcul de la norme et de l'angle Θ des vecteurs vitesse par rapport au point précédent def calcul_norm_theta(df, pos, latitude_min, longitude_min, ecart_x, ecart_y): """ DataFrame * (int,int) * float * float * float * float -> list(float) * list(float) Retourne les listes de normes et d'angles du vecteur vitesse de la case pos par rapport au point précédent. """ case_df = trouve_data_case(df, pos, latitude_min, longitude_min, ecart_x, ecart_y) trips_case = np.unique(case_df["Trip"]) liste_norm_v = [] liste_theta_v = [] for t in trips_case: tr = case_df.loc[case_df["Trip"]==t, ["GpsTime","Latitude","Longitude"]] for i in range(1,tr.shape[0]): dif_time = (tr["GpsTime"].iloc[i] - tr["GpsTime"].iloc[i-1]) v = (tr[["Latitude","Longitude"]].iloc[i] - tr[["Latitude","Longitude"]].iloc[i-1])/dif_time norm_v = np.sqrt(v["Latitude"]**2 + v["Longitude"]**2) theta = np.arctan(v["Latitude"]/np.maximum(v["Longitude"], 0.0001)) liste_norm_v.append(norm_v) liste_theta_v.append(theta) return liste_norm_v, liste_theta_v # ============================================================================= # Fonctions traitements de données # ============================================================================= def echantillon(df, step=1): """ DataFrame * int -> DataFrame Sélectionne une ligne sur 'step' dans le DataFrame. """ ind = np.arange(0,df.shape[0],step) return df.iloc[ind] #Création des données d'apprentissage pour la prédiction du prochain point def create_data_xy(df, train_size, freq_train, freq_test): """ Renvoie les DataFrames X et Y, en fonction des paramètres. @params : df : DataFrame : Données à traiter train_size : float : Pourcentage de données train freq_train : int : Freq à prendre sur train freq_test : int : Freq à prendre sur test @return : DataFrame, DataFrame """ #Fréquences des données # np.random.seed(0) step_train = freq_train//200 step_test = freq_test//200 #Sélection des numéros de Trip en train et en test trips = pd.unique(df["Trip"]) # melange = np.arange(len(trips)) # np.random.shuffle(melange) # train_trips = trips[melange[:int(len(melange)*train_size)]] # test_trips = trips[melange[int(len(melange)*train_size):]] train_trips = trips[:int(len(trips)*train_size)] test_trips = trips[int(len(trips)*train_size):] #Création des DataFrame train/test X_train = None X_test = None y_train = None y_test = None #Construction des données d'apprentissage for t in range(len(train_trips)): train_df = df[df['Trip'] == train_trips[t]] if t == 0: X_train = echantillon(train_df[:-step_train], step_train) y_train = echantillon(train_df[step_train:], step_train) else : xtrain = echantillon(train_df[:-step_train], step_train) ytrain = echantillon(train_df[step_train:], step_train) X_train = pd.concat([X_train,xtrain]) y_train = pd.concat([y_train,ytrain]) #Construction des données de test for t in range(len(test_trips)): test_df = df[df['Trip'] == test_trips[t]] if t == 0: X_test = echantillon(test_df[:-step_test], step_test) y_test = echantillon(test_df[step_test:], step_test) else : xtest = echantillon(test_df[:-step_test], step_test) ytest = echantillon(test_df[step_test:], step_test) X_test = pd.concat([X_test,xtest]) y_test = pd.concat([y_test, ytest]) return X_train, X_test, y_train, y_test def create_data_xy2(df, train_size, freq_train, freq_test): step_train = freq_train//200 step_test = freq_test//200 #Sélection des numéros de Trip en train et en test trips = pd.unique(df["Trip"]) train_trips = trips[:int(len(trips)*train_size)] test_trips = trips[int(len(trips)*train_size):] X_train1 = None X_train2 = None y_train = None for t in range(len(train_trips)): train_df = df[df['Trip'] == train_trips[t]] if t == 0: X_train1 = echantillon(train_df[step_train*0:-step_train*2], step_train*3) X_train2 = echantillon(train_df[step_train:-step_train*1], step_train*3) y_train = echantillon(train_df[step_train*2:], step_train*3) else : tmp1 = echantillon(train_df[step_train*0:-step_train*2], step_train*3) tmp2 = echantillon(train_df[step_train:-step_train*1], step_train*3) tmp3 = echantillon(train_df[step_train*2:], step_train*3) X_train1 = pd.concat([X_train1,tmp1]) X_train2 = pd.concat([X_train2,tmp2]) y_train = pd.concat([y_train,tmp3]) return X_train1, X_train2, y_train<file_sep>import numpy as np import dataSource as ds """ argmin_alpha (X * W = Y_p) X = [latix, longx] Y = [latiy, longy] W = [[w11, w12],[w21, w22]] pour chaque case Y_p : p_latiy = w11 * latix + w21 * longx p_longy = w12 * latix + w22 * longx dans le cas monidre caréé erreur = sum_x_y ((latiy - p_latiy) ** 2 + (longy - p_longy) ** 2) dffer_de_w11 = sum_x_y (2 * latix * (latiy - p_latiy)) = 0 dffer_de_w21 = sum_x_y (2 * longx * (latiy - p_latiy)) = 0 dffer_de_w12 = sum_x_y (2 * latix * (longy - p_longy)) = 0 dffer_de_w22 = sum_x_y (2 * longx * (longy - p_longy)) = 0 """ class RegLineaire2(): def __init__(self,datax,datay): self.datax = datax self.datay = datay def fit(self,df): "Retourner le paramètre W appris dans la case indiquée." #latitude_min, latitude_max, longitude_min, longitude_max, ecart_x, ecart_y = ds.calcul_param(df) #df_case = ds.trouve_data_case(df, pos, latitude_min, longitude_min, ecart_x, ecart_y) trips = np.unique(df['Trip']) for t in trips: df2 = df[df['Trip'] == t][['Latitude','Longitude']] N = df2['Latitude'].shape[0] ens_points = np.hstack((df2['Latitude'].values.reshape(N,1), df2['Longitude'].values.reshape(N,1))) ens_x = ens_points[:-1] ens_y = ens_points[1:] latix2 = sum(ens_x[:,0] ** 2) latilongx = sum(ens_x[:,0] * ens_x[:,1]) longx2 = sum(ens_x[:,1] ** 2) latixy = sum(ens_x[:,0] * ens_y[:,0]) latilongxy = sum(ens_x[:,0] * ens_y[:,1]) longxy = sum(ens_x[:,1] * ens_y[:,1]) longlatixy = sum(ens_x[:,1] * ens_y[:,0]) w1 = np.linalg.solve(np.array([[latix2, latilongx],[latilongx, longx2]]), np.array([2*latixy, 2*longlatixy])) w2 = np.linalg.solve(np.array([[latix2, latilongx],[latilongx, longx2]]), np.array([2*latilongxy, 2*longxy])) self.coef_ = np.vstack((w1, w2)) def predict(self,datax): return datax.dot(self.coef_) def score(self,datax,datay): datay_p = self.predict(datax) return ((datay_p - datay)**2).sum() df = ds.importData() latitude_min, latitude_max, longitude_min, longitude_max, ecart_x, ecart_y = ds.calcul_param(df) fit_case_ML(df, (2,1), latitude_min, latitude_max, ecart_x, ecart_y) <file_sep>import numpy as np #### Modele Physique class model_physique2(): # predict from instant speed # x = [[Trip, Lati, Longi, GpsHeading, GpsSpeed]] def __init__(self,freq,coef=0.2,nbr_points=10): self.freq = freq self.l_freq = [self.freq*coef*i for i in range(nbr_points)] self.alpha = None def fit(self, x_train, y_train): """ x_train = [[Trip, Lati, Longi, GpsHeading, GpsSpeed]] y_train = [[Lati, Longi]] """ radius = 6371e3 res = None erreur = np.inf l_trips = np.unique(x_train['Trip']) x_trips = x_train.sort_values('Trip') for freq in self.l_freq: k = 0 for t in l_trips: test = x_trips[x_trips['Trip']==t].sort_values('GpsTime')[['Latitude', 'Longitude','GpsHeading','GpsSpeed']] N = test.shape[0] tmp = np.zeros((N,2)) tmp[0,:] =test.iloc[0][['Latitude', 'Longitude']].to_numpy() for i in range(N-1): lat1, lon1 = self.toRadians(test.iloc[i,:2]) d = test.iloc[i,3]*freq*1e-3/radius tc = self.toRadians(self.toNordBasedHeading(test.iloc[i,2])) lat2 = np.arcsin(np.sin(lat1)*np.cos(d) + np.cos(lat1)*np.sin(d)*np.cos(tc)) dlon = np.arctan2(np.sin(tc)*np.sin(d)*np.cos(lat1), np.cos(d) - np.sin(lat1)*np.sin(lat2)) lon2= (lon1-dlon + np.pi) % (2*np.pi) - np.pi tmp[i+1,0] = self.toDegrees(lat2) tmp[i+1,1] = self.toDegrees(lon2) if k == 0: res = tmp else: res = np.vstack((res,tmp)) k += 1 tmp_e = self.score(res, y_train) if tmp_e < erreur: erreur = tmp_e self.alpha = freq print("freq en entrée : ", self.freq, "le meilleur alpha trouvé : ", self.alpha) return self.alpha def toDegrees(self,v): return v*180/np.pi def toRadians(self,v): return v*np.pi / 180 def toNordBasedHeading(self,GpsHeading): return 90 - GpsHeading def predict(self, x_test): ''' based on the fact that we are in small distances, we suppose that a cell is a plane param: alpha d : [[predi_lat, predi_longi]*N] formula source: https://cloud.tencent.com/developer/ask/152388 ''' radius = 6371e3 res = None l_trips = np.unique(x_test['Trip']) x_trips = x_test.sort_values('Trip') k = 0 for t in l_trips: test = x_trips[x_trips['Trip']==t].sort_values('GpsTime')[['Latitude', 'Longitude','GpsHeading','GpsSpeed']] N = test.shape[0] tmp = np.zeros((N,2)) tmp[0,:] =test.iloc[0][['Latitude', 'Longitude']].to_numpy() for i in range(N-1): lat1, lon1 = self.toRadians(test.iloc[i,:2]) d = test.iloc[i,3]*self.alpha*1e-3/radius tc = self.toRadians(self.toNordBasedHeading(test.iloc[i,2])) lat2 = np.arcsin(np.sin(lat1)*np.cos(d) + np.cos(lat1)*np.sin(d)*np.cos(tc)) dlon = np.arctan2(np.sin(tc)*np.sin(d)*np.cos(lat1), np.cos(d) - np.sin(lat1)*np.sin(lat2)) lon2= (lon1-dlon + np.pi) % (2*np.pi) - np.pi tmp[i+1,0] = self.toDegrees(lat2) tmp[i+1,1] = self.toDegrees(lon2) if k == 0: res = tmp else: res = np.vstack((res,tmp)) k += 1 return res def score(self,yhat,y): return np.sqrt(np.sum((yhat - y.to_numpy()) ** 2)) <file_sep>import math import numpy as np import seaborn as sns import matplotlib.pyplot as plt import matplotlib.patches as patches import dataSource as ds # ============================================================================= # Fonctions de visualisations # ============================================================================= #%% #Affiche un histogramme pour un attribut du DataFrame def afficher_histogramme_df(df,attr): """ DataFrame * str -> None Affiche un histogramme sur un attribut du DataFrame df. """ plt.figure() sns.histplot(df[attr]) plt.show() #%% #Dessine un rectangle sur les cases où se trouvent les données sélectionnées def dessine_rect(ax, pos, x_splits, y_splits, ecart_x, ecart_y): """ AxesSubplot * (int,int) * float * float * flot * float -> None Encadre la case correspondant à la position. """ x, y = pos ax.add_patch(patches.Rectangle((x_splits[x],y_splits[y]), ecart_x, ecart_y, edgecolor = 'black', fill=False)) #%% #Ajout du titre et des noms d'axes def set_ax_legend(ax, title, xlabel, ylabel): """ AxesSubplot * str * str * str -> None Ajoute le titre et le nom des axes sur ax. """ ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) #%% #Permet de visualiser le sens de la route def fleche_sens(df, ax): """ DataFrame * AxesSubplot -> None Dessine une flèche partant du 1er point et qui est orientée vers le n/2-ème point. """ n = df.shape[0] if n > 1: x_i = df.iloc[0, df.columns.get_loc("Latitude")] y_i = df.iloc[0, df.columns.get_loc("Longitude")] dx_i = df.iloc[math.floor(n/2), df.columns.get_loc("Latitude")] - x_i dy_i = df.iloc[math.floor(n/2), df.columns.get_loc("Longitude")] - y_i ax.quiver(x_i, y_i, dx_i, dy_i) #%% #Visualisation graphique de la carte def affiche_carte(df, pos, latitude_min, latitude_max, longitude_min, longitude_max, ecart_x, ecart_y, n_interval=10) : """ DataFrame * (int,int) * float * float * float * float * float * float * int -> None Affiche un aperçu de la carte et d'une case donnée. """ #Préparation des données #On sépare en n_interval la latitude et la longitude x_splits = np.linspace(latitude_min,latitude_max, n_interval+1) y_splits = np.linspace(longitude_min,longitude_max, n_interval+1) #Affichage fig, ax = plt.subplots(2,2, figsize=(15,12)) #Visualisation (1ème figure): set_ax_legend(ax[0][0], "Visualisation des effectifs de voiture de la zone étudiée", "Latitude", "Longitude") p = ax[0][0].scatter(df["Latitude"], df["Longitude"], c=df["Effectif_case"], cmap="RdPu") cbar = plt.colorbar(p, ax=ax[0][0]) cbar.set_label('Effectif de voiture') #Visualisation (2ère figure) : #affichage (latitude,longitude) pour les trips en fonction de la vitesse set_ax_legend(ax[0][1], 'Visualisation des vitesses de la zone étudiée', "Latitude", "Longitude") p = ax[0][1].scatter(df["Latitude"], df["Longitude"], c=df["Vitesse_moy_case"], cmap="YlOrRd") cbar = plt.colorbar(p, ax=ax[0][1]) cbar.set_label('Vitesse') #affichage grille for i in range(n_interval+1): x = x_splits[i] y = y_splits[i] ax[0][0].plot([x,x],[longitude_min, longitude_max], c='grey', alpha = 0.5) ax[0][0].plot([latitude_min,latitude_max],[y,y], c='grey', alpha = 0.5) ax[0][1].plot([x,x],[longitude_min, longitude_max], c='grey', alpha = 0.5) ax[0][1].plot([latitude_min,latitude_max],[y,y], c='grey', alpha = 0.5) dessine_rect(ax[0][0], pos, x_splits, y_splits, ecart_x, ecart_y) dessine_rect(ax[0][1], pos, x_splits, y_splits, ecart_x, ecart_y) #Visualisation (3ème figure) : sx, sy = pos case_df = ds.trouve_data_case(df, (sx, sy), latitude_min, longitude_min, ecart_x, ecart_y) p = ax[1][0].scatter(case_df["Latitude"], case_df["Longitude"], c=case_df["GpsSpeed"], cmap="YlOrRd") cbar = plt.colorbar(p, ax=ax[1][0]) cbar.set_label('Vitesse') set_ax_legend(ax[1][0], f"Zoom sur la case {(sx,sy)}", "Latitude", "Longitude") #Affichage du sens de circulation pour la figure 3 trips_case = np.unique(case_df["Trip"]) for t in trips_case: tr = case_df.loc[case_df["Trip"]==t, ["Latitude","Longitude","GpsHeading"]] fleche_sens(tr, ax[1][0]) #Visualisation (4ème figure): sns.histplot(case_df["GpsSpeed"],ax=ax[1][1]) ax[1][1].set_title(f"Distribution de la vitesse sur la case {(sx,sy)}") plt.show() def afficher_traffic(df, lat_min, lat_max, long_min, long_max, n_interval=10): #On sépare en n_interval la latitude et la longitude x_splits = np.linspace(lat_min,lat_max, n_interval+1) y_splits = np.linspace(long_min,long_max, n_interval+1) fig, ax = plt.subplots(1,2, figsize=(15,5)) #Visualisation (1ème figure): set_ax_legend(ax[0], "Visualisation des effectifs de voiture de la zone étudiée", "Latitude", "Longitude") p = ax[0].scatter(df["Longitude"], df["Latitude"], c=df["Effectif_case"], cmap="RdPu") cbar = plt.colorbar(p, ax=ax[0]) cbar.set_label('Effectif de voiture') #Visualisation (2ère figure) : #affichage (latitude,longitude) pour les trips en fonction de la vitesse set_ax_legend(ax[1], 'Visualisation des vitesses de la zone étudiée', "Latitude", "Longitude") p = ax[1].scatter(df["Longitude"], df["Latitude"], c=df["Vitesse_moy_case"], cmap="YlOrRd") cbar = plt.colorbar(p, ax=ax[1]) cbar.set_label('Vitesse moyenne') #affichage grille for i in range(n_interval+1): x = x_splits[i] y = y_splits[i] ax[0].plot([long_min, long_max],[x,x], c='grey', alpha = 0.5) ax[0].plot([y,y],[lat_min,lat_max], c='grey', alpha = 0.5) ax[1].plot([long_min, long_max],[x,x], c='grey', alpha = 0.5) ax[1].plot([y,y],[lat_min,lat_max], c='grey', alpha = 0.5) plt.show() #%% #Histogramme 3D de la norme des vecteurs de vitesse et ses angles Θ def afficher_hist_norm_vit(df, pos, latitude_min, longitude_min, ecart_x, ecart_y): """ DataFrame * (int,int) * float * float * float * float -> None Affiche un histogramme 3d par rapport aux normes et anlges des vecteurs vitesse d'une case donnée. """ #Préparation des données liste_norm_v, liste_theta_v = ds.calcul_norm_theta(df, pos, latitude_min, longitude_min, ecart_x, ecart_y) #Affichage fig = plt.figure() ax = fig.add_subplot(111, projection='3d') plt.title("Histogramme 3D de la norme des vecteurs de vitesse et ses angles $\Theta$ :") ax.set_xlabel('Norm') ax.set_ylabel('$\Theta$') ax.set_zlabel('Effectif') hist, xedges, yedges = np.histogram2d(liste_norm_v, liste_theta_v, bins=4) # The start of each bucket. xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1]) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros_like(xpos) # The width of each bucket. dx, dy = np.meshgrid(xedges[1:] - xedges[:-1], yedges[1:] - yedges[:-1]) dx = dx.flatten() dy = dy.flatten() dz = hist.flatten() ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average') plt.show() #Affichage de la matrice en heatmap def afficher_mat(mat, title="Matrice en heatmap", n_interval=10): """ Matrice(float) * int -> None Affiche un heatmap de la matrice. """ plt.figure() plt.title(title) sns.heatmap(mat, linewidths=.5, cmap="YlGnBu", yticklabels=np.arange(n_interval-1, -1, -1)) plt.show() #Histogramme des valeurs de la matrice def afficher_mat_hist(mat): """ Matrice(float) -> None Affiche les valeurs de la matrice sous histogramme. """ #On commence par sélectionner que les cases contenant une valeur val = mat.ravel()[mat.ravel() != 0] #Affichage des valeurs sous histogramme plt.figure() plt.title("Affichage des valeurs de la matrice sous histogramme") sns.histplot(val) plt.show() <file_sep> from sklearn.base import BaseEstimator import numpy as np from sklearn.metrics import mean_squared_error from sklearn.linear_model import LinearRegression #### Modele Physique class model_physique1bis(BaseEstimator): def __init__(self,l_alpha,iftheta=False): super().__init__() self.l_alpha = l_alpha self.iftheta = iftheta def fit(self, X, y): if self.iftheta: self.theta = X['GpsHeading'].mean() return self def predict(self,X): ''' param [['Trip','Latitude','Longitude','GpsHeading','GpsTime']*m] retourne [[nextlat, nextlongi]*m] : prochaine lat et longi ''' mat = [] groups = X.groupby('Trip') train_step = 0 #som = 0 for group in groups: tmp = group[1][['Latitude','Longitude','GpsTime']].to_numpy() mat.append(tmp) if tmp.shape[0] >= 2 and train_step == 0: temps_ecart = tmp[1:,2] - tmp[:-1,2] train_step = np.min(temps_ecart) if train_step > 10000: print(temps_ecart) #print(train_step) #train_step /= som #print('M',mat) """try: train_step = mat[0][1][2] - mat[0][0][2] except IndexError: print('indexerror',X, mat)""" ind = train_step//200 - 1 #print(ind) try: #print(t) alpha = self.l_alpha[int(ind)] except IndexError: print("Oops! Index n'est pas dans l_alpha. ", t, ind) res = [] for X_t in mat: res.append(X_t[0][:2]) for i in range(1,len(X_t)): v = np.array([ (X_t[i-1][0] - X_t[i][0]) / train_step , (X_t[i-1][1] - X_t[i][1])/ train_step ]) if self.iftheta: theta = self.theta r = np.array(( (np.cos(theta), -np.sin(theta)), (np.sin(theta), np.cos(theta)) ) ) v = v@r res.append(X_t[i][:2] + v@alpha) #res.append(X_t[i][:2] + v*train_step) return np.array(res) def learn_alpha(freq_train, A_pre, A, y): """ X : dim (n,3) y : dim (n,3) """ # (A' - A)/t, dim (n,2) t = A[0,2] - A_pre[0,2] X_train = (A_pre[:,:2] - A[:,:2])/t #print(A, A_pre) # -A + y, dim (n,2) y_train = - y[:,:2] + A[:,:2] clf = LinearRegression() clf.fit(X_train,y_train) print('coef: ' ,clf.coef_, clf.coef_.shape) return clf.coef_
487b19c716bc32e75f9271df3f0baa7bae589899
[ "Python" ]
9
Python
ZhuangPascal/PLDAC
0e32b6eeae6ec60c6cbbb65310c692041f514d50
070a8472143be3c3469d0b7c8d34383bb7b98b2a
refs/heads/main
<repo_name>funte/USB_wabcam<file_sep>/HARDWARE/OV7670/sccb.c #include "sys.h" #include "sccb.h" #include "delay.h" ////////////////////////////////////////////////////////////////////////////////// //本程序参考自网友guanfu_wang代码。 //ALIENTEK战舰STM32开发板 //SCCB 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/14 //版本:V1.0 ////////////////////////////////////////////////////////////////////////////////// //初始化SCCB接口 //CHECK OK void SCCB_Init (void) { RCC->APB2ENR |= 1 << 8; // 先使能外设PORTG时钟 RCC->APB2ENR |= 1 << 5; // 先使能外设PORTD时钟 //PORTG13 IN( 数据信号 ) GPIOG->CRH &= 0XFF0FFFFF; // 10:上拉/下拉输入模式 , 00:输入模式(复位后的状态) GPIOG->CRH |= 0X00800000; GPIOG->ODR |= 1 << 13; //PD3 OUT ( 时钟信号 ) GPIOD->CRL &= 0XFFFF0FFF; // 00:通用推挽输出模式 , 11:输出模式,最大速度50MHz GPIOD->CRL |= 0X00003000; GPIOD->ODR |= 1 << 3; SCCB_SDA_OUT (); // } //SCCB起始信号 //当时钟为高的时候,数据线的高到低,为SCCB起始信号 //在激活状态下,SDA和SCL均为低电平 void SCCB_Start (void) { SCCB_SDA = 1; // 数据线高电平 SCCB_SCL = 1; // 在时钟线高的时候数据线由高至低 delay_us (50); SCCB_SDA = 0; delay_us (50); SCCB_SCL = 0; // 数据线恢复低电平,单操作函数必要 } //SCCB停止信号 //当时钟为高的时候,数据线的低到高,为SCCB停止信号 //空闲状况下,SDA,SCL均为高电平 void SCCB_Stop (void) { SCCB_SDA = 0; delay_us (50); SCCB_SCL = 1; delay_us (50); SCCB_SDA = 1; delay_us (50); } //产生NA信号 void SCCB_No_Ack (void) { delay_us (50); SCCB_SDA = 1; SCCB_SCL = 1; delay_us (50); SCCB_SCL = 0; delay_us (50); SCCB_SDA = 0; delay_us (50); } //SCCB,写入一个字节 //返回值:0,成功;1,失败. u8 SCCB_WR_Byte (u8 dat) { u8 j, res; for (j = 0; j < 8; j++) //循环8次发送数据 { if (dat & 0x80)SCCB_SDA = 1; else SCCB_SDA = 0; dat <<= 1; delay_us (50); SCCB_SCL = 1; delay_us (50); SCCB_SCL = 0; } SCCB_SDA_IN (); //设置SDA为输入 delay_us (50); SCCB_SCL = 1; //接收第九位,以判断是否发送成功 delay_us (50); if (SCCB_READ_SDA) res = 1; //SDA=1发送失败,返回1 else res = 0; //SDA=0发送成功,返回0 SCCB_SCL = 0; SCCB_SDA_OUT (); //设置SDA为输出 return res; } //SCCB 读取一个字节 //在SCL的上升沿,数据锁存 //返回值:读到的数据 u8 SCCB_RD_Byte (void) { u8 temp = 0, j; SCCB_SDA_IN (); //设置SDA为输入 for (j = 8; j > 0; j--) //循环8次接收数据 { delay_us (50); SCCB_SCL = 1; temp = temp << 1; if (SCCB_READ_SDA)temp++; delay_us (50); SCCB_SCL = 0; } SCCB_SDA_OUT (); //设置SDA为输出 return temp; } //写寄存器 //返回值:0,成功;1,失败. u8 SCCB_WR_Reg (u8 reg, u8 data) { u8 res = 0; SCCB_Start (); // 启动SCCB传输 if (SCCB_WR_Byte (SCCB_ID)) res = 1;// 写器件ID delay_us (100); if (SCCB_WR_Byte (reg)) res = 1; // 写寄存器地址 delay_us (100); if (SCCB_WR_Byte (data)) res = 1; // 写数据 SCCB_Stop (); return res; } //读寄存器 //返回值:读到的寄存器值 u8 SCCB_RD_Reg (u8 reg) { u8 val = 0; SCCB_Start (); //启动SCCB传输 SCCB_WR_Byte (SCCB_ID); //写器件ID delay_us (100); SCCB_WR_Byte (reg); //写寄存器地址 delay_us (100); SCCB_Stop (); delay_us (100); //设置寄存器地址后,才是读 SCCB_Start (); SCCB_WR_Byte (SCCB_ID | 0X01); //发送读命令 delay_us (100); val = SCCB_RD_Byte (); //读取数据 SCCB_No_Ack (); SCCB_Stop (); return val; } <file_sep>/HARDWARE/KEY/key.c #include "key.h" #include "delay.h" ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK战舰STM32开发板 //按键驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/3 //版本:V1.0 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved ////////////////////////////////////////////////////////////////////////////////// //按键初始化函数 void KEY_Init(void) { RCC->APB2ENR|=1<<2; //使能PORTA时钟 RCC->APB2ENR|=1<<6; //使能PORTE时钟 GPIOA->CRL&=0XFFFFFFF0; //PA0设置成输入,默认下拉 GPIOA->CRL|=0X00000008; GPIOE->CRL&=0XFFF000FF; //PE2~4设置成输入 GPIOE->CRL|=0X00088800; GPIOE->ODR|=7<<2; //PE2~4 上拉 } //按键处理函数 //返回按键值 //mode:0,不支持连续按;1,支持连续按; //0,没有任何按键按下 //1,KEY0按下 //2,KEY1按下 //3,KEY2按下 //4,KEY3按下 WK_UP //注意此函数有响应优先级,KEY0>KEY1>KEY2>KEY3!! u8 KEY_Scan(u8 mode) { static u8 key_up=1;//按键按松开标志 if(mode)key_up=1; //支持连按 if(key_up&&(KEY0==0||KEY1==0||KEY2==0||KEY3==1)) { delay_ms(10);//去抖动 key_up=0; if(KEY0==0)return 1; else if(KEY1==0)return 2; else if(KEY2==0)return 3; else if(KEY3==1)return 4; }else if(KEY0==1&&KEY1==1&&KEY2==1&&KEY3==0)key_up=1; return 0;// 无按键按下 } <file_sep>/USB/JPEGEncoder/ejpeg.c //--------------------------------------------------------------------------- // // JPEG Encoder for embeded application // By <NAME> 2010./2011 // //PC机上仿真,移植到DM642 DSP上的版本记录: // V1.0: #只支持单色和YUV422格式 // #未处理块延拓问题,只支持MCU块大小N倍长宽的图像, 要求width/heigh // 单色Align-8, YUV422 Align-16 // #写入JPEG Header优化 // V1.1: 移植到DM642, 对DSP优化。 // V1.11: 再次整理, 减小MCU buffer,增加APP 段插入功能 // ------------------------------- // V2.0: 2011-10-31, 移植到STM32成功。 // 测试结果:使用4KByte输出Buffer,数据流输出到FSMC扩展SDRAM,640x480图像, // 用ARM Level-3 for Time编译设置,编码时间约880ms; 640x480单色图像,编码 // 时间约530ms。无优化的Level-0编译,时间约1120ms/630ms, 优化作用一般。 // V2.01: 2011-11-10, 增加缩放取样功能,输出接口改成可匹配双缓冲区接口。 // v2.03: 2011-12-10, 增加APP0段,这对MJPEG是很重要的! 增加YUV420模式,去掉Mono // 模式单独的ReadSrc,与YUV合成一个函数 //--------------------------------------------------------------------------- //------------------------------------ //#define APP_DSP_CCS //------------------------------------ //#include <stdio.h> #include "ejpeg.h" //#include "Pld_Intf.h" #define JPG_STATIC_LOC static //============================================================================ // quant_table JPG_STATIC_LOC UInt8 std_Y_QT[64] = { 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 }; JPG_STATIC_LOC UInt8 std_UV_QT[64] = { 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 }; JPG_STATIC_LOC UInt8 zigzag_table[64] = { 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 }; JPG_STATIC_LOC UInt8 un_zigzag_table[64] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 }; //送入JPEG流的huffman表数据, 按JPEG规定格式,带有FFC4标记和长度,4个Huffman表. //UInt8 huff_markerdata[432] = JPG_STATIC_LOC UInt8 huff_Y_marker[216] = { 0xFF, 0xC4, 0x00, 0x1F, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA }; JPG_STATIC_LOC UInt8 huff_UV_marker[216] = { 0xFF, 0xC4, 0x00, 0x1F, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, }; //huffman表 JPG_STATIC_LOC UInt16 luminance_dc_code_table[12] = { 0x0000, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x000E, 0x001E, 0x003E, 0x007E, 0x00FE, 0x01FE }; JPG_STATIC_LOC UInt8 luminance_dc_size_table[12] = { 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; JPG_STATIC_LOC UInt16 chrominance_dc_code_table[12] = { 0x0000, 0x0001, 0x0002, 0x0006, 0x000E, 0x001E, 0x003E, 0x007E, 0x00FE, 0x01FE, 0x03FE, 0x07FE }; JPG_STATIC_LOC UInt8 chrominance_dc_size_table[12] = { 0x02, 0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B }; //JPEG标准预设的AC_Huffman表 // 10个为一组,1组对应1个0游程值; 每组16个值,对应非零系数bit数1~16。首尾2个为特殊码 //UInt16 luminance_ac_code_table[] = JPG_STATIC_LOC UInt16 luminance_ac_code_table[162] = { 0x000A, 0x0000, 0x0001, 0x0004, 0x000B, 0x001A, 0x0078, 0x00F8, 0x03F6, 0xFF82, 0xFF83, 0x000C, 0x001B, 0x0079, 0x01F6, 0x07F6, 0xFF84, 0xFF85, 0xFF86, 0xFF87, 0xFF88, 0x001C, 0x00F9, 0x03F7, 0x0FF4, 0xFF89, 0xFF8A, 0xFF8b, 0xFF8C, 0xFF8D, 0xFF8E, 0x003A, 0x01F7, 0x0FF5, 0xFF8F, 0xFF90, 0xFF91, 0xFF92, 0xFF93, 0xFF94, 0xFF95, 0x003B, 0x03F8, 0xFF96, 0xFF97, 0xFF98, 0xFF99, 0xFF9A, 0xFF9B, 0xFF9C, 0xFF9D, 0x007A, 0x07F7, 0xFF9E, 0xFF9F, 0xFFA0, 0xFFA1, 0xFFA2, 0xFFA3, 0xFFA4, 0xFFA5, 0x007B, 0x0FF6, 0xFFA6, 0xFFA7, 0xFFA8, 0xFFA9, 0xFFAA, 0xFFAB, 0xFFAC, 0xFFAD, 0x00FA, 0x0FF7, 0xFFAE, 0xFFAF, 0xFFB0, 0xFFB1, 0xFFB2, 0xFFB3, 0xFFB4, 0xFFB5, 0x01F8, 0x7FC0, 0xFFB6, 0xFFB7, 0xFFB8, 0xFFB9, 0xFFBA, 0xFFBB, 0xFFBC, 0xFFBD, 0x01F9, 0xFFBE, 0xFFBF, 0xFFC0, 0xFFC1, 0xFFC2, 0xFFC3, 0xFFC4, 0xFFC5, 0xFFC6, 0x01FA, 0xFFC7, 0xFFC8, 0xFFC9, 0xFFCA, 0xFFCB, 0xFFCC, 0xFFCD, 0xFFCE, 0xFFCF, 0x03F9, 0xFFD0, 0xFFD1, 0xFFD2, 0xFFD3, 0xFFD4, 0xFFD5, 0xFFD6, 0xFFD7, 0xFFD8, 0x03FA, 0xFFD9, 0xFFDA, 0xFFDB, 0xFFDC, 0xFFDD, 0xFFDE, 0xFFDF, 0xFFE0, 0xFFE1, 0x07F8, 0xFFE2, 0xFFE3, 0xFFE4, 0xFFE5, 0xFFE6, 0xFFE7, 0xFFE8, 0xFFE9, 0xFFEA, 0xFFEB, 0xFFEC, 0xFFED, 0xFFEE, 0xFFEF, 0xFFF0, 0xFFF1, 0xFFF2, 0xFFF3, 0xFFF4, 0xFFF5, 0xFFF6, 0xFFF7, 0xFFF8, 0xFFF9, 0xFFFA, 0xFFFB, 0xFFFC, 0xFFFD, 0xFFFE, 0x07F9 }; JPG_STATIC_LOC UInt8 luminance_ac_size_table[162] = { 0x04, 0x02, 0x02, 0x03, 0x04, 0x05, 0x07, 0x08, 0x0A, 0x10, 0x10, 0x04, 0x05, 0x07, 0x09, 0x0B, 0x10, 0x10, 0x10, 0x10, 0x10, 0x05, 0x08, 0x0A, 0x0C, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x06, 0x09, 0x0C, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x06, 0x0A, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x07, 0x0B, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x07, 0x0C, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x08, 0x0C, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x09, 0x0F, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x09, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x09, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0A, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0A, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0B, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0B }; JPG_STATIC_LOC UInt16 chrominance_ac_code_table[162] = { 0x0000, 0x0001, 0x0004, 0x000A, 0x0018, 0x0019, 0x0038, 0x0078, 0x01F4, 0x03F6, 0x0FF4, 0x000B, 0x0039, 0x00F6, 0x01F5, 0x07F6, 0x0FF5, 0xFF88, 0xFF89, 0xFF8A, 0xFF8B, 0x001A, 0x00F7, 0x03F7, 0x0FF6, 0x7FC2, 0xFF8C, 0xFF8D, 0xFF8E, 0xFF8F, 0xFF90, 0x001B, 0x00F8, 0x03F8, 0x0FF7, 0xFF91, 0xFF92, 0xFF93, 0xFF94, 0xFF95, 0xFF96, 0x003A, 0x01F6, 0xFF97, 0xFF98, 0xFF99, 0xFF9A, 0xFF9B, 0xFF9C, 0xFF9D, 0xFF9E, 0x003B, 0x03F9, 0xFF9F, 0xFFA0, 0xFFA1, 0xFFA2, 0xFFA3, 0xFFA4, 0xFFA5, 0xFFA6, 0x0079, 0x07F7, 0xFFA7, 0xFFA8, 0xFFA9, 0xFFAA, 0xFFAB, 0xFFAC, 0xFFAD, 0xFFAE, 0x007A, 0x07F8, 0xFFAF, 0xFFB0, 0xFFB1, 0xFFB2, 0xFFB3, 0xFFB4, 0xFFB5, 0xFFB6, 0x00F9, 0xFFB7, 0xFFB8, 0xFFB9, 0xFFBA, 0xFFBB, 0xFFBC, 0xFFBD, 0xFFBE, 0xFFBF, 0x01F7, 0xFFC0, 0xFFC1, 0xFFC2, 0xFFC3, 0xFFC4, 0xFFC5, 0xFFC6, 0xFFC7, 0xFFC8, 0x01F8, 0xFFC9, 0xFFCA, 0xFFCB, 0xFFCC, 0xFFCD, 0xFFCE, 0xFFCF, 0xFFD0, 0xFFD1, 0x01F9, 0xFFD2, 0xFFD3, 0xFFD4, 0xFFD5, 0xFFD6, 0xFFD7, 0xFFD8, 0xFFD9, 0xFFDA, 0x01FA, 0xFFDB, 0xFFDC, 0xFFDD, 0xFFDE, 0xFFDF, 0xFFE0, 0xFFE1, 0xFFE2, 0xFFE3, 0x07F9, 0xFFE4, 0xFFE5, 0xFFE6, 0xFFE7, 0xFFE8, 0xFFE9, 0xFFEA, 0xFFEb, 0xFFEC, 0x3FE0, 0xFFED, 0xFFEE, 0xFFEF, 0xFFF0, 0xFFF1, 0xFFF2, 0xFFF3, 0xFFF4, 0xFFF5, 0x7FC3, 0xFFF6, 0xFFF7, 0xFFF8, 0xFFF9, 0xFFFA, 0xFFFB, 0xFFFC, 0xFFFD, 0xFFFE, 0x03FA }; JPG_STATIC_LOC UInt8 chrominance_ac_size_table[162] = { 0x02, 0x02, 0x03, 0x04, 0x05, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x0C, 0x04, 0x06, 0x08, 0x09, 0x0B, 0x0C, 0x10, 0x10, 0x10, 0x10, 0x05, 0x08, 0x0A, 0x0C, 0x0F, 0x10, 0x10, 0x10, 0x10, 0x10, 0x05, 0x08, 0x0A, 0x0C, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x06, 0x09, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x06, 0x0A, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x07, 0x0B, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x07, 0x0B, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x09, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x09, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x09, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x09, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0B, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0F, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0A }; //---------------------------------------------------------------- typedef struct tagJPGENC_STRUCT { UInt16 mcu_width; UInt16 mcu_height; UInt16 hori_mcus; UInt16 vert_mcus; UInt8 quality_factor; UInt8 img_format; UInt16 img_width; UInt16 img_height; UInt16 img_pitch; UInt16 img_xbeg; UInt16 img_ybeg; UInt16 img_scale; Int16 last_dc1; Int16 last_dc2; Int16 last_dc3; } JPGENC_STRUCT; JPGENC_STRUCT jpgenc_struct; JPGENC_STRUCT *jpgenc; UInt32 jpg_bitsbuf; //bits to stream buffer UInt16 jpg_bitindex; UInt8 app_Y_QT[64]; //输出到Stream的量化表 UInt8 app_UV_QT[64]; UInt16 inv_Y_QT[64]; //快速量化用的倒数量化表 UInt16 inv_UV_QT[64]; Int16 jpg_mcubuff[64 * 6]; //MCU数据buffer,Src/DCT/QT共用 UInt8 *jpg_outstream; //JPEG数据流输出指针 UInt8 *jpg_streamfptr = 0; //为跳过JPEG Header,保存格式未改前图像流起始指针 Int32 jpg_outbufsize; //CallBack函数 CallBack_OutStream jpg_FlushStream = 0; #define JPG_APPDAT_BUFSIZE 64 UInt8 jpg_appdat_buf[JPG_APPDAT_BUFSIZE]; //--------------------------------------------------------------------------- // 整数FDCT,IN/OUT 11bit // 结果覆盖源数据 void DCT(Int16 *data) { UInt16 i; Int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; //Cos系数表,按cos(i*PI/16)*sqrt(2)计算,i=0,1..7, 乘1024 Scale,即Q12, c0=0,c4=1 static const UInt16 c1 = 1420; // cos PI/16 * root(2) *1024 static const UInt16 c2 = 1338; // cos PI/8 * root(2) static const UInt16 c3 = 1204; // cos 3PI/16 * root(2) static const UInt16 c5 = 805; // cos 5PI/16 * root(2) static const UInt16 c6 = 554; // cos 3PI/8 * root(2) static const UInt16 c7 = 283; // cos 7PI/16 * root(2) static const UInt16 s1 = 3; static const UInt16 s2 = 10; static const UInt16 s3 = 13; for (i = 8; i > 0; i--) { x8 = data[0] + data[7]; x0 = data[0] - data[7]; x7 = data[1] + data[6]; x1 = data[1] - data[6]; x6 = data[2] + data[5]; x2 = data[2] - data[5]; x5 = data[3] + data[4]; x3 = data[3] - data[4]; x4 = x8 + x5; x8 = x8 - x5; x5 = x7 + x6; x7 = x7 - x6; data[0] = (Int16)(x4 + x5); data[4] = (Int16)(x4 - x5); data[2] = (Int16)((x8*c2 + x7*c6) >> s2); data[6] = (Int16)((x8*c6 - x7*c2) >> s2); data[7] = (Int16)((x0*c7 - x1*c5 + x2*c3 - x3*c1) >> s2); data[5] = (Int16)((x0*c5 - x1*c1 + x2*c7 + x3*c3) >> s2); data[3] = (Int16)((x0*c3 - x1*c7 - x2*c1 - x3*c5) >> s2); data[1] = (Int16)((x0*c1 + x1*c3 + x2*c5 + x3*c7) >> s2); data += 8; } data -= 64; for (i = 8; i > 0; i--) { x8 = data[0] + data[56]; x0 = data[0] - data[56]; x7 = data[8] + data[48]; x1 = data[8] - data[48]; x6 = data[16] + data[40]; x2 = data[16] - data[40]; x5 = data[24] + data[32]; x3 = data[24] - data[32]; x4 = x8 + x5; x8 = x8 - x5; x5 = x7 + x6; x7 = x7 - x6; data[0] = (Int16)((x4 + x5) >> s1); data[32] = (Int16)((x4 - x5) >> s1); data[16] = (Int16)((x8*c2 + x7*c6) >> s3); data[48] = (Int16)((x8*c6 - x7*c2) >> s3); data[56] = (Int16)((x0*c7 - x1*c5 + x2*c3 - x3*c1) >> s3); data[40] = (Int16)((x0*c5 - x1*c1 + x2*c7 + x3*c3) >> s3); data[24] = (Int16)((x0*c3 - x1*c7 - x2*c1 - x3*c5) >> s3); data[8] = (Int16)((x0*c1 + x1*c3 + x2*c5 + x3*c7) >> s3); data++; } } #if 0 UInt32 outptr_upmask; #define M_JPG_writebits {outstr_ptr = JPG_writebits(CodeVal, bitnum, outstr_ptr); } //--------------------------------------------------------------------------- // 输出Huffman编码数据流, pointer in ->pointer out UInt8 *JPG_writebits(UInt32 val, UInt16 bitnum, UInt8 *outstr_ptr) { Int16 bits_fornext; bits_fornext = (Int16)(jpg_bitindex + bitnum - 32); if (bits_fornext <0) { jpg_bitsbuf = (jpg_bitsbuf<<bitnum) | val; //未溢出,简单并入Buf中 jpg_bitindex += bitnum; } else { jpg_bitsbuf = (jpg_bitsbuf << (32 - jpg_bitindex)) |(val>> bits_fornext); //32bit Word按Byte输出, 按编码规定,遇到0xFF迦?x00 if ((*outstr_ptr++ = (UInt8)(jpg_bitsbuf >>24)) == 0xff) { (UInt32)outstr_ptr &= outptr_upmask; *outstr_ptr++ = 0; } if ((*outstr_ptr++ = (UInt8)(jpg_bitsbuf >>16)) == 0xff) *outstr_ptr++ = 0; if ((*outstr_ptr++ = (UInt8)(jpg_bitsbuf >>8)) == 0xff) *outstr_ptr++ = 0; if ((*outstr_ptr++ = (UInt8)jpg_bitsbuf) == 0xff) *outstr_ptr++ = 0; //剩余bits jpg_bitsbuf = val; jpg_bitindex = bits_fornext; } return(outstr_ptr); } #endif //#if 0 #define M_JPG_writebits \ { \ bits_fornext = (Int16)(jpg_bitindex + bitnum - 32); \ if (bits_fornext <0) \ { \ jpg_bitsbuf = (jpg_bitsbuf<<bitnum) | CodeVal; \ jpg_bitindex += bitnum; \ } \ else \ { \ jpg_bitsbuf = (jpg_bitsbuf << (32 - jpg_bitindex)) |(CodeVal>> bits_fornext); \ if ((*outstr_ptr++ = (UInt8)(jpg_bitsbuf >>24)) == 0xff) \ *outstr_ptr++ = 0; \ if ((*outstr_ptr++ = (UInt8)(jpg_bitsbuf >>16)) == 0xff) \ *outstr_ptr++ = 0; \ if ((*outstr_ptr++ = (UInt8)(jpg_bitsbuf >>8)) == 0xff) \ *outstr_ptr++ = 0; \ if ((*outstr_ptr++ = (UInt8)jpg_bitsbuf) == 0xff) \ *outstr_ptr++ = 0; \ jpg_bitsbuf = CodeVal; \ jpg_bitindex = bits_fornext; \ } \ } //#endif //--------------------------------------------------------------------------- // 对单个块(MCU)的量化结果进行huffman编码输出 // 输入:in_dat - 量化后的MCU数据 // component - MCU类型标记,1-Y, 2-Cb, 3-Cr // outstr_ptr - 输出Buffer UInt8 *JPG_huffman(Int16 *in_dat, UInt8 component, UInt8 *outstr_ptr) { UInt16 i; UInt16 *pDcCodeTable, *pAcCodeTable; UInt8 *pDcSizeTable, *pAcSizeTable; UInt8 *un_zigzag_ptr; Int16 Coeff, LastDc; UInt16 AbsCoeff, HuffCode, HuffSize, RunLength, DataSize, index, bitnum; UInt32 CodeVal; //need 32bit! Int16 bits_fornext; //选择huffman表 Coeff = in_dat[0]; //取DC值 if (component == 1) { pDcCodeTable = (UInt16 *)luminance_dc_code_table; pDcSizeTable = (UInt8 *)luminance_dc_size_table; pAcCodeTable = (UInt16 *)luminance_ac_code_table; pAcSizeTable = (UInt8 *)luminance_ac_size_table; LastDc = jpgenc->last_dc1; //保存DC值 jpgenc->last_dc1 = Coeff; } else { pDcCodeTable = (UInt16 *)chrominance_dc_code_table; pDcSizeTable = (UInt8 *)chrominance_dc_size_table; pAcCodeTable = (UInt16 *)chrominance_ac_code_table; pAcSizeTable = (UInt8 *)chrominance_ac_size_table; if (component == 2) { LastDc = jpgenc->last_dc2; jpgenc->last_dc2 = Coeff; } else { LastDc = jpgenc->last_dc3; jpgenc->last_dc3 = Coeff; } } //DC系数编码: DPCM系数编码 //取差分值 Coeff -= LastDc; AbsCoeff = (Coeff < 0) ? -Coeff : Coeff; //计算系数绝对值的有效bit数 DataSize = 0; while (AbsCoeff != 0) //log2, 系数绝对值的有效bit数 { AbsCoeff >>= 1; DataSize++; } //符号1:用huffman编码表示的"系数绝对值有效bit数" HuffCode = pDcCodeTable[DataSize]; HuffSize = pDcSizeTable[DataSize]; //符号2: 负值取反码,屏蔽冗余位 if (Coeff < 0) { Coeff--; Coeff &= ((1 << DataSize) - 1); } //组合2个符号一起输出 CodeVal = (HuffCode << DataSize) | Coeff; bitnum = HuffSize + DataSize; M_JPG_writebits; //AC系数编码: 零游程-系数编码 RunLength = 0; un_zigzag_ptr = (UInt8 *)un_zigzag_table; for (i = 63; i > 0; i--) //63个AC系数 { un_zigzag_ptr++; Coeff = in_dat[(*un_zigzag_ptr)]; if (Coeff != 0) { //遇到非0系数 while (RunLength > 15) { //0游程长度达到16,输出一个跳码[16,0] RunLength -= 16; CodeVal = pAcCodeTable[161]; bitnum = pAcSizeTable[161]; M_JPG_writebits; } //系数的有效bit数 AbsCoeff = (Coeff < 0) ? -Coeff : Coeff; DataSize = 0; while (AbsCoeff != 0) //log2, 系数绝对值的有效bit数 { AbsCoeff >>= 1; DataSize++; } //符号1: (到达非0系数前的)0游程长度x10 + 非0系数有效bit数 // 符号可记为[RL, Bitnum]形式, RL范围0~15,系数值由于DCT限制 // 1024范围,bitnum<10。 index = RunLength * 10 + DataSize; HuffCode = pAcCodeTable[index]; HuffSize = pAcSizeTable[index]; //符号2: 负值取反码,屏蔽冗余位 if (Coeff < 0) { Coeff--; Coeff &= (1 << DataSize) - 1; } //组合2个符号输出 CodeVal = (HuffCode << DataSize) | Coeff; bitnum = HuffSize + DataSize; M_JPG_writebits; RunLength = 0; } else { RunLength++; //0值,进行游程统计 } } //输出块结束标记 if (RunLength != 0) { //符号[0,0] EOB,后续全0,作为块结束标记 CodeVal = pAcCodeTable[0]; bitnum = pAcSizeTable[0]; M_JPG_writebits; } return(outstr_ptr); } //--------------------------------------------------------------------------- // 对DCT系数量化. 量化结果覆盖源数据 void JPG_quantization(Int16*in_dat, UInt16* quant_table_ptr) { Int16 i; Int32 f0, f1, f2, f3, f4, f5, f6, f7; for (i = 8; i > 0; i--) { //量化的方法是: value = data/QT //变除法为乘法: 使用倒数形式的量化表,INV = 0x8000/QT,这样 // value = data/QT = (v*INV)/0x8000 // 加0x4000相当与加0.5 f0 = in_dat[0] * quant_table_ptr[0] + 0x4000; f1 = in_dat[1] * quant_table_ptr[1] + 0x4000; f2 = in_dat[2] * quant_table_ptr[2] + 0x4000; f3 = in_dat[3] * quant_table_ptr[3] + 0x4000; f4 = in_dat[4] * quant_table_ptr[4] + 0x4000; f5 = in_dat[5] * quant_table_ptr[5] + 0x4000; f6 = in_dat[6] * quant_table_ptr[6] + 0x4000; f7 = in_dat[7] * quant_table_ptr[7] + 0x4000; in_dat[0] = (Int16)(f0 >> 15); in_dat[1] = (Int16)(f1 >> 15); in_dat[2] = (Int16)(f2 >> 15); in_dat[3] = (Int16)(f3 >> 15); in_dat[4] = (Int16)(f4 >> 15); in_dat[5] = (Int16)(f5 >> 15); in_dat[6] = (Int16)(f6 >> 15); in_dat[7] = (Int16)(f7 >> 15); in_dat += 8; quant_table_ptr += 8; } } //--------------------------------------------------------------------------- // 根据质量因子调整量化表,并产生快速量化用的倒数量化表 void JPG_setquality(UInt8 quality_factor) { UInt16 i, index; UInt32 value, quality1; if (quality_factor < 1) quality_factor = 1; if (quality_factor > 8) quality_factor = 8; quality1 = quality_factor; // quality1 = ((quality1 * 3) - 2) * 128; //converts range[1:8] to [1:22] for (i = 0; i < 64; i++) { index = zigzag_table[i]; // luminance quantization table * quality factor * //按 v = (QT*Zoom +512)/1024 转换,Zoom = factor*128 ->1024范围, 即相当于 // v = k*QT + 0.5, k在1左右 value = quality1*std_Y_QT[i]; value = (value + 0x200) >> 10; if (value < 2) value = 2; else if (value > 255) value = 255; //保存新量化表用于输出。 app_Y_QT[index] = (UInt8)value; //产生倒数形式的量化表,INV = 0x8000/QT, 量化时 Q = v/QT = (v*INV)/0x8000 //变除法为乘法 inv_Y_QT[i] = 0x8000 / value; // chrominance quantization table * quality factor value = quality1*std_UV_QT[i]; value = (value + 0x200) >> 10; if (value < 2) value = 2; else if (value > 255) value = 255; app_UV_QT[index] = (UInt8)value; inv_UV_QT[i] = 0x8000 / value; } } //--------------------------------------------------------------------------- // 写标准JPEG文? 按规定输出量化表和Huffman表 UInt8 *JPG_writeheader(UInt8 *outbuf) { UInt16 i, header_length; UInt8 number_of_components; UInt8 *outstr_ptr; outstr_ptr = outbuf; // Start of image marker (SOI)标准文件头 *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xD8; //marker //--- // APPx --0xFFEx //--- #ifdef JPG_USING_APP0 //Default APP0段,可选. // JFIF标记,后续属性字节不能错。MJPEG用"AVI1"代替JFIF也可以,后续全0。 *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xE0; //marker, standard JFIF *outstr_ptr++ = 0x00; *outstr_ptr++ = 0x10; //length, 10byte /* *outstr_ptr++ = 'A'; //JFIF mark, 5byte *outstr_ptr++ = 'V'; *outstr_ptr++ = 'I'; *outstr_ptr++ = '1'; for(i=0; i<10; i++) *outstr_ptr++ = 0x00; */ *outstr_ptr++ = 'J'; //JFIF mark, 5byte *outstr_ptr++ = 'F'; *outstr_ptr++ = 'I'; *outstr_ptr++ = 'F'; *outstr_ptr++ = 0x00; *outstr_ptr++ = 0x01; //Version, 2Byte, 1.1 or 1.2 *outstr_ptr++ = 0x01; *outstr_ptr++ = 0x00; //units, none=0, pixel/inch=1, pixle/cm=2 *outstr_ptr++ = 0x00; //X density *outstr_ptr++ = 0x01; *outstr_ptr++ = 0x00; //Y density *outstr_ptr++ = 0x01; *outstr_ptr++ = 0x00; //缩略图X Pixels *outstr_ptr++ = 0x00; //缩略图Y Pixels #endif //其他附加APP段 /*# *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xE2; //marker *outstr_ptr++ = 0x00; //length, 2byte *outstr_ptr++ = JPG_APPDAT_BUFSIZE; //0x40, 64Byte for(i=0; i<JPG_APPDAT_BUFSIZE-2; i++) { *outstr_ptr++ = jpg_appdat_buf[i]; } */ //------------------ // Start of frame marker (SOF) Frame头 *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xC0; //Baseline DCT frame if (jpgenc->img_format == JPG_IMGFMT_MONO) number_of_components = 1; else number_of_components = 3; header_length = (UInt16)(8 + 3 * number_of_components); // Frame header length *outstr_ptr++ = (UInt8)(header_length >> 8); *outstr_ptr++ = (UInt8)header_length; // Precision (P) *outstr_ptr++ = 0x08; // image height *outstr_ptr++ = (UInt8)((jpgenc->img_height / jpgenc->img_scale) >> 8); *outstr_ptr++ = (UInt8)(jpgenc->img_height / jpgenc->img_scale); // image width *outstr_ptr++ = (UInt8)((jpgenc->img_width / jpgenc->img_scale) >> 8); *outstr_ptr++ = (UInt8)(jpgenc->img_width / jpgenc->img_scale); // number of color component *outstr_ptr++ = number_of_components; // components feature if (jpgenc->img_format == JPG_IMGFMT_MONO) { *outstr_ptr++ = 0x01; //component ID *outstr_ptr++ = 0x11; //vertical & horitzontal sample factor *outstr_ptr++ = 0x00; //quality-table ID } else { *outstr_ptr++ = 0x01; //for Y if (jpgenc->img_format == JPG_IMGFMT_YUV422) *outstr_ptr++ = 0x21; if (jpgenc->img_format == JPG_IMGFMT_YUV420) *outstr_ptr++ = 0x22; else *outstr_ptr++ = 0x11; //YUV444 *outstr_ptr++ = 0x00; *outstr_ptr++ = 0x02; //for Cb *outstr_ptr++ = 0x11; *outstr_ptr++ = 0x01; *outstr_ptr++ = 0x03; //for Cr *outstr_ptr++ = 0x11; *outstr_ptr++ = 0x01; } //------------------ // Quantization table for Y *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xDB; // Quantization table length *outstr_ptr++ = 0x00; *outstr_ptr++ = 0x43; //67 = 2+1+64 // [Pq, Tq], Pq-数据精度,0-8Bit,1-16Bit; Tq - 量化表编号(0-1) *outstr_ptr++ = 0x00; // applicate luminance quality table for (i = 0; i < 64; i++) *outstr_ptr++ = app_Y_QT[i]; // Quantization table for UV if (jpgenc->img_format != JPG_IMGFMT_MONO) { *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xDB; // Quantization table length *outstr_ptr++ = 0x00; *outstr_ptr++ = 0x43; // Pq, Tq *outstr_ptr++ = 0x01; // applicate chrominance quality table for (i = 0; i < 64; i++) *outstr_ptr++ = app_UV_QT[i]; } //------------------ // huffman table(DHT), 4个huffman表,直接取已编制好的数据 for (i = 0; i < sizeof(huff_Y_marker); i++) { *outstr_ptr++ = huff_Y_marker[i]; } if (jpgenc->img_format != JPG_IMGFMT_MONO) { for (i = 0; i < sizeof(huff_UV_marker); i++) { *outstr_ptr++ = huff_UV_marker[i]; } } //------------------ // Scan header(SOF) *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xDA; // Start of scan marker header_length = (UInt16)(6 + (number_of_components << 1)); // Scan header length *outstr_ptr++ = (UInt8)(header_length >> 8); *outstr_ptr++ = (UInt8)header_length; // number of color component *outstr_ptr++ = number_of_components; // component feature if (jpgenc->img_format == JPG_IMGFMT_MONO) { *outstr_ptr++ = 0x01; //component ID, for Y *outstr_ptr++ = 0x00; //[TdNs, TaNs],4bit分别为DC/AC量化表的编号 } else { *outstr_ptr++ = 0x01; *outstr_ptr++ = 0x00; *outstr_ptr++ = 0x02; //for Cb *outstr_ptr++ = 0x11; *outstr_ptr++ = 0x03; //for Cr *outstr_ptr++ = 0x11; } *outstr_ptr++ = 0x00; //Ss *outstr_ptr++ = 0x3F; //Se *outstr_ptr++ = 0x00; //[Ah,Al] // return(outstr_ptr); } //--------------------------------------------------------------------------- // 结束输出数据流, 写文件尾 UInt8 *close_bitstream(UInt8 *outstr_ptr) { UInt16 i, count; UInt8 *ptr; if (jpg_bitindex > 0) { jpg_bitsbuf <<= (32 - jpg_bitindex); count = (jpg_bitindex + 7) >> 3; //最少Byte数, 不一定是4Byte ptr = (UInt8 *)&jpg_bitsbuf + 3; //little endian模式,指向Uint32的最高Byte for (i = 0; i < count; i++) { if ((*outstr_ptr++ = *ptr--) == 0xff) *outstr_ptr++ = 0; } } // End of image marker *outstr_ptr++ = 0xFF; *outstr_ptr++ = 0xD9; return(outstr_ptr); } #if 0 //#old //--------------------------------------------------------------------------- // 读源图像数据 // 单色or YUV422, 读1个MCU,64Word, void JPG_readsrc(UInt8 *in_ptr, UInt32 offset, Int16* out_ptr, UInt32 img_pitch) { Int32 i; UInt32 f0,f1,f2,f3,f4,f5,f6,f7; UInt8 *inptr; inptr = in_ptr + offset; for(i=8; i>0; i--) { f0 = inptr[0]; f1 = inptr[1]; f2 = inptr[2]; f3 = inptr[3]; f4 = inptr[4]; f5 = inptr[5]; f6 = inptr[6]; f7 = inptr[7]; out_ptr[0] = f0 - 128; out_ptr[1] = f1 - 128; out_ptr[2] = f2 - 128; out_ptr[3] = f3 - 128; out_ptr[4] = f4 - 128; out_ptr[5] = f5 - 128; out_ptr[6] = f6 - 128; out_ptr[7] = f7 - 128; inptr += img_pitch; out_ptr += 8; } } #endif //--------------------------------------------------------------------------- // [Private]读源图像数据 // yuv_mode: 0 - Mono, 1 - YUV420, 2 - YUV422 void JPG_readsrc_yuv(UInt32 xoffset, UInt32 yoffset, UInt32 yuv_mode, Int16 *mcubuf) { UInt16 buf[16]; Int16 *y1_ptr, *y2_ptr, *cb_ptr, *cr_ptr; Int32 i, j; UInt32 step_x, rownum; UInt16 *ex_ptr, *wordptr; UInt8 *byteptr; y1_ptr = mcubuf; y2_ptr = mcubuf + 64; if (yuv_mode == 1) { cb_ptr = y2_ptr + 3 * 64; rownum = 16; } else { cb_ptr = y2_ptr + 64; rownum = 8; } cr_ptr = cb_ptr + 64; step_x = jpgenc->img_scale * 2 - 1; for (i = 0; i < rownum; ++i) { //Pld_SelectImgRow((UInt32)(yoffset + (jpgenc->img_ybeg + i)*jpgenc->img_scale)); //ex_ptr = (UInt16 *)Pld_PixelPtr((UInt32)(xoffset + jpgenc->img_xbeg*jpgenc->img_scale)); //水平采样模式,相邻取2点,保持CbCr一致性,否则均匀取样会出现颜色偏差 j = 0; while (j < 16) { buf[j++] = *ex_ptr++; buf[j++] = *ex_ptr; ex_ptr += step_x; } if ((yuv_mode == 0) || ((yuv_mode == 1) && ((i % 2) != 0))) { //只取亮度 wordptr = buf; *y1_ptr++ = (UInt8)(*wordptr++) - 128; //0 *y1_ptr++ = (UInt8)(*wordptr++) - 128; *y1_ptr++ = (UInt8)(*wordptr++) - 128; *y1_ptr++ = (UInt8)(*wordptr++) - 128; //3 *y1_ptr++ = (UInt8)(*wordptr++) - 128; //4 *y1_ptr++ = (UInt8)(*wordptr++) - 128; *y1_ptr++ = (UInt8)(*wordptr++) - 128; *y1_ptr++ = (UInt8)(*wordptr++) - 128; //7 *y2_ptr++ = (UInt8)(*wordptr++) - 128; //0 *y2_ptr++ = (UInt8)(*wordptr++) - 128; *y2_ptr++ = (UInt8)(*wordptr++) - 128; *y2_ptr++ = (UInt8)(*wordptr++) - 128; //3 *y2_ptr++ = (UInt8)(*wordptr++) - 128; //4 *y2_ptr++ = (UInt8)(*wordptr++) - 128; *y2_ptr++ = (UInt8)(*wordptr++) - 128; *y2_ptr++ = (UInt8)(*wordptr++) - 128; //7 //构造Y3,Y4 MCU if ((yuv_mode == 1) && (i == 7)) { y1_ptr += 64; y2_ptr += 64; } } else { byteptr = (UInt8 *)buf; //MCU-1 *y1_ptr++ = *byteptr++ - 128; //0 *cb_ptr++ = *byteptr++ - 128; *y1_ptr++ = *byteptr++ - 128; //1 *cr_ptr++ = *byteptr++ - 128; *y1_ptr++ = *byteptr++ - 128; //2 *cb_ptr++ = *byteptr++ - 128; *y1_ptr++ = *byteptr++ - 128; //3 *cr_ptr++ = *byteptr++ - 128; *y1_ptr++ = *byteptr++ - 128; //4 *cb_ptr++ = *byteptr++ - 128; *y1_ptr++ = *byteptr++ - 128; //5 *cr_ptr++ = *byteptr++ - 128; *y1_ptr++ = *byteptr++ - 128; //6 *cb_ptr++ = *byteptr++ - 128; *y1_ptr++ = *byteptr++ - 128; //7 *cr_ptr++ = *byteptr++ - 128; //MCU-2 *y2_ptr++ = *byteptr++ - 128; //0 *cb_ptr++ = *byteptr++ - 128; *y2_ptr++ = *byteptr++ - 128; //1 *cr_ptr++ = *byteptr++ - 128; *y2_ptr++ = *byteptr++ - 128; //2 *cb_ptr++ = *byteptr++ - 128; *y2_ptr++ = *byteptr++ - 128; //3 *cr_ptr++ = *byteptr++ - 128; *y2_ptr++ = *byteptr++ - 128; //4 *cb_ptr++ = *byteptr++ - 128; *y2_ptr++ = *byteptr++ - 128; //5 *cr_ptr++ = *byteptr++ - 128; *y2_ptr++ = *byteptr++ - 128; //6 *cb_ptr++ = *byteptr++ - 128; *y2_ptr++ = *byteptr++ - 128; //7 *cr_ptr++ = *byteptr++ - 128; } } } //--------------------------------------------------------------------------- // [Public] 设置图像格式、质量因子、输出Buffer // * 质量因子quality_factor范围[1,8],1最好,8最差 * void JPG_initImgFormat(UInt16 width, UInt16 height, UInt8 scale, UInt8 img_format, UInt8 quality, UInt16 pitch, UInt16 xbeg, UInt16 ybeg) { jpgenc = &jpgenc_struct; jpgenc->img_width = width; jpgenc->img_height = height; jpgenc->img_pitch = pitch; jpgenc->img_xbeg = xbeg; jpgenc->img_ybeg = ybeg; jpgenc->img_scale = scale; jpgenc->mcu_width = 8; jpgenc->mcu_height = 8; jpgenc->hori_mcus = ((width + 7) >> 3); jpgenc->vert_mcus = ((height + 7) >> 3); jpgenc->quality_factor = quality; jpgenc->img_format = img_format; JPG_setquality(quality); } //--------------------------------------------------------------------------- // [Public] 设置输出数据流Buffer、流刷新Callback函数 // void JPG_initOutStream(CallBack_OutStream streamFunc, UInt8 *outbuf, Int32 bufsize) { jpg_FlushStream = streamFunc; jpg_outbufsize = bufsize; jpg_outstream = outbuf; // jpg_streamfptr = 0; //要求重新输出JPEG header jpg_streamfptr = outbuf; } //--------------------------------------------------------------------------- // [Public] 设置JPEG附加数据段 UInt8 JPG_WriteAppDat(UInt8 *in_dat, UInt16 size) { UInt16 i; i = 0; while (i < size) { jpg_appdat_buf[i] = *in_dat++; if (jpg_appdat_buf[i] == 0xff) { i++; jpg_appdat_buf[i] = 0x00; } i++; if (i >= JPG_APPDAT_BUFSIZE) return(0); } return(1); } //--------------------------------------------------------------------------- // [Public] UInt8 *JPG_WriteHeader(UInt16 jpghd_offset) { UInt8 *out_ptr; out_ptr = jpg_outstream; if (jpghd_offset == 0) { out_ptr = JPG_writeheader(out_ptr); } else { out_ptr += jpghd_offset; } jpg_streamfptr = out_ptr; return(out_ptr); } //--------------------------------------------------------------------------- // [Public] JPEF Encoder interface // Return: 编码结果Byte数 Int32 JPG_Encode(void) { UInt8 *out_ptr, *out_bufbase; UInt32 x, y, step_y; Int16 *srcptr; Int32 trunc_size, t_size = 0, size1; UInt32 yuv_mode; if (jpgenc->img_format == JPG_IMGFMT_YUV420) { step_y = 16 * jpgenc->img_scale; yuv_mode = 1; } else { step_y = 8 * jpgenc->img_scale; if (jpgenc->img_format == JPG_IMGFMT_MONO) yuv_mode = 0; else yuv_mode = 2; } //init Huffman Coder parameter jpg_bitsbuf = 0; jpg_bitindex = 0; jpgenc->last_dc1 = 0; jpgenc->last_dc2 = 0; jpgenc->last_dc3 = 0; //设定输出Buffer刷新限值,码流Byte数大于此值时,调用Callback函数输出 //缓存的码流,从头开始使用缓冲区 trunc_size = jpg_outbufsize - 64 * 4; // //write JPEG header // *如果图像格式、质量因子、输出Buffer未变,对相同格式图像的编码,QT和huffman表 // 完全相同,则可以跳过写JPEG文件头的部分,直接跳到上次得到的图像流起点开始写 out_bufbase = jpg_outstream; out_ptr = jpg_streamfptr; size1 = out_ptr - out_bufbase; //672Byte, 要求Buffer >(672Byte + 4MCU 编码ByteNum) if (size1 > trunc_size) { out_bufbase = jpg_FlushStream(out_bufbase, size1); out_ptr = out_bufbase; t_size += size1; } //按MCU块编码图像,每次编码16x8Pixel图像,对应4个MCU for (y = 0; y < jpgenc->img_height; y += step_y) { for (x = 0; x < jpgenc->img_width; x += (16 * jpgenc->img_scale)) { //Read source srcptr = jpg_mcubuff; JPG_readsrc_yuv(x, y, yuv_mode, srcptr); //Coder //Y1 DCT(srcptr); JPG_quantization(srcptr, inv_Y_QT); out_ptr = JPG_huffman(srcptr, 1, out_ptr); //Y2 srcptr += 64; DCT(srcptr); JPG_quantization(srcptr, inv_Y_QT); out_ptr = JPG_huffman(srcptr, 1, out_ptr); if (yuv_mode == 1) { //Y3 srcptr += 64; DCT(srcptr); JPG_quantization(srcptr, inv_Y_QT); out_ptr = JPG_huffman(srcptr, 1, out_ptr); //Y4 srcptr += 64; DCT(srcptr); JPG_quantization(srcptr, inv_Y_QT); out_ptr = JPG_huffman(srcptr, 1, out_ptr); } if (yuv_mode != 0) { //Cb srcptr += 64; DCT(srcptr); JPG_quantization(srcptr, inv_UV_QT); out_ptr = JPG_huffman(srcptr, 2, out_ptr); //Cr srcptr += 64; DCT(srcptr); JPG_quantization(srcptr, inv_UV_QT); out_ptr = JPG_huffman(srcptr, 3, out_ptr); } //write stream size1 = out_ptr - out_bufbase; if (size1 > trunc_size) { out_bufbase = jpg_FlushStream(out_bufbase, size1); out_ptr = out_bufbase; t_size += size1; } } } out_ptr = close_bitstream(out_ptr); size1 = out_ptr - out_bufbase; jpg_FlushStream(out_bufbase, size1); t_size += size1; return(t_size); } //--------------------------------------------------------------------------- // End of file //--------------------------------------------------------------------------- <file_sep>/USB/JPEGEncoder/ejpeg.h /*============================================================================ // File Name : ejpeg.h // Author : HECC. DuckWeed Tech. // @HuiZhou, 2011 // email: <EMAIL> // Version : V2.0 // Description : JPEG编码器 // 使用说明: // 1).用JPG_initImgFormat()设定源图像尺寸 // 用JPG_initOutStream()设定编码器的数据流输出缓冲区和CallBack函数。建议 // 缓冲区不小于1K SRAM。 // 用JPG_WriteAppDat()设定附加数据,这是可选功能。 // 2).调用JPG_Encode()执行图像编码。返回结果数据ByteNum。中间自动调用 // CallBack_OutStream写入最终存储介质。 ==============================================================================*/ #ifndef __ejpeg_H_ #define __ejpeg_H_ // //#include "stm32f10x_lib.h" //#include "stm32f10x_type.h" typedef signed long Int32; typedef signed short Int16; typedef signed char Int8; typedef unsigned long UInt32; typedef unsigned short UInt16; typedef unsigned char UInt8; //--------------------------------------------------------------------------- // 编译控制 #define JPG_USING_APP0 //-------------------------------------------------------------------------- #define JPG_IMGFMT_MONO 0 #define JPG_IMGFMT_YUV422 1 #define JPG_IMGFMT_YUV420 2 //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- typedef UInt8* (*CallBack_OutStream)(UInt8 *bufptr, Int32 byteNum); //--------------------------------------------------------------------------- //质量因子quality_factor范围[1,8],1最好,8最差 void JPG_initImgFormat(UInt16 width, UInt16 height, UInt8 scale, UInt8 img_format, UInt8 quality, UInt16 pitch, UInt16 xbeg, UInt16 ybeg); void JPG_initOutStream(CallBack_OutStream streamFunc, UInt8 *outbuf, Int32 bufsize); UInt8 JPG_WriteAppDat(UInt8 *in_dat, UInt16 size); UInt8 *JPG_WriteHeader(UInt16 jpghd_offset); Int32 JPG_Encode(void); #endif <file_sep>/README.md # STM32F103 USB 摄像头 代码是从原子的触控鼠标实验改过来的,煎蛋实现了一个USB摄像头,可以将一帧320*240的JPG图片发送到HOST,所以并不包含摄像头驱动代码. 代码很简单,作为学习UVC或者参考也是不错的. PC上看到的图像 <img src="./README/capture.jpg"><file_sep>/HARDWARE/EXTI/exti.c #include "exti.h" #include "led.h" #include "beep.h" #include "key.h" #include "delay.h" #include "usart.h" #include "ov7670.h" ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK战舰STM32开发板 //外部中断 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/14 //版本:V1.1 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved //******************************************************************************** //V1.1 20120914 //1,增加EXTI8_Init函数。 //2,增加EXTI9_5_IRQHandler函数 ////////////////////////////////////////////////////////////////////////////////// //外部中断0服务程序 //void EXTI0_IRQHandler(void) //{ // delay_ms(10);//消抖 // if(KEY3==1) //WK_UP按键 // { // BEEP=!BEEP; // } // EXTI->PR=1<<0; //清除LINE0上的中断标志位 //} //外部中断2服务程序 void EXTI2_IRQHandler(void) { delay_ms(10);//消抖 if (KEY2 == 0) //按键KEY2 { LED0 = !LED0; } EXTI->PR = 1 << 2; //清除LINE2上的中断标志位 } //外部中断3服务程序 void EXTI3_IRQHandler(void) { delay_ms(10);//消抖 if (KEY1 == 0) //按键KEY1 { LED1 = !LED1; } EXTI->PR = 1 << 3; //清除LINE3上的中断标志位 } //外部中断4服务程序 void EXTI4_IRQHandler(void) { delay_ms(10);//消抖 if (KEY0 == 0) //按键KEY0 { LED0 = !LED0; LED1 = !LED1; } EXTI->PR = 1 << 4; //清除LINE4上的中断标志位 } //外部中断初始化程序 //初始化PA0/PE2/PE3/PE4为中断输入. void EXTIX_Init(void) { KEY_Init(); Ex_NVIC_Config(GPIO_A, 0, RTIR); //上升沿触发 Ex_NVIC_Config(GPIO_E, 2, FTIR); //下降沿触发 Ex_NVIC_Config(GPIO_E, 3, FTIR); //下降沿触发 Ex_NVIC_Config(GPIO_E, 4, FTIR); //下降沿触发 MY_NVIC_Init(2, 3, EXTI0_IRQn, 2); //抢占2,子优先级3,组2 MY_NVIC_Init(2, 2, EXTI2_IRQn, 2); //抢占2,子优先级2,组2 MY_NVIC_Init(2, 1, EXTI3_IRQn, 2); //抢占2,子优先级1,组2 MY_NVIC_Init(2, 0, EXTI4_IRQn, 2); //抢占2,子优先级0,组2 } extern void camera_refresh(void); extern u8 ov0_sta; //外部中断5~9服务程序 void EXTI9_5_IRQHandler(void) { if (EXTI->PR&(1 << 8))//是8线的中断 { if (ov0_sta < 2) { if (ov0_sta == 0) { OV7670_WRST = 0; // 复位写指针 OV7670_WRST = 1; OV7670_WREN = 1; // 允许写入FIFO } else OV7670_WREN = 0; // 禁止写入FIFO ov0_sta++; } } EXTI->PR |= 0x1F0; // 清除9-5线上的中断标志 } //外部中断8初始化 void EXTI8_Init(void) { Ex_NVIC_Config(GPIO_A, 8, RTIR); //任意边沿触发 MY_NVIC_Init(0, 0, EXTI9_5_IRQn, 2); //抢占0,子优先级0,组2 } <file_sep>/USB/CONFIG/usb_prop.c /******************** (C) COPYRIGHT 2008 STMicroelectronics ******************** * File Name : usb_prop.c * Author : MCD Application Team * Version : V2.2.1 * Date : 09/22/2008 * Description : All processing related to Virtual Com Port Demo ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" #include "usb_conf.h" #include "usb_prop.h" #include "usb_desc.h" #include "usb_pwr.h" #include "hw_config.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ typedef struct _VideoControl { u8 bmHint[2]; // 0x02 u8 bFormatIndex[1]; // 0x03 u8 bFrameIndex[1]; // 0x04 u8 dwFrameInterval[4]; // 0x08 u8 wKeyFrameRate[2]; // 0x0A u8 wPFrameRate[2]; // 0x0C u8 wCompQuality[2]; // 0x0E u8 wCompWindowSize[2]; // 0x10 u8 wDelay[2]; // 0x12 u8 dwMaxVideoFrameSize[4]; // 0x16 u8 dwMaxPayloadTransferSize[4]; // 0x1A u8 dwClockFrequency[4]; // 0x1C u8 bmFramingInfo[1]; u8 bPreferedVersion[1]; u8 bMinVersion[1]; u8 bMaxVersion[1]; } VideoControl; //VideoStreaming Requests应答,参考USB_Video_Class_1_1.pdf p103~ VideoControl videoCommitControl = { { 0x01, 0x00 }, // bmHint { 0x01 }, // bFormatIndex { 0x01 }, // bFrameIndex { MAKE_DWORD(FRAME_INTERVEL) }, // dwFrameInterval { 0x00, 0x00, }, // wKeyFrameRate { 0x00, 0x00, }, // wPFrameRate { 0x00, 0x00, }, // wCompQuality { 0x00, 0x00, }, // wCompWindowSize { 0x00, 0x00 }, // wDelay { MAKE_DWORD(MAX_FRAME_SIZE) }, // dwMaxVideoFrameSize { 0x00, 0x00, 0x00, 0x00 }, // dwMaxPayloadTransferSize { 0x00, 0x00, 0x00, 0x00 }, // dwClockFrequency { 0x00 }, // bmFramingInfo { 0x00 }, // bPreferedVersion { 0x00 }, // bMinVersion { 0x00 }, // bMaxVersion }; VideoControl videoProbeControl = { { 0x01, 0x00 }, // bmHint { 0x01 }, // bFormatIndex { 0x01 }, // bFrameIndex { MAKE_DWORD(FRAME_INTERVEL) }, // dwFrameInterval { 0x00, 0x00, }, // wKeyFrameRate { 0x00, 0x00, }, // wPFrameRate { 0x00, 0x00, }, // wCompQuality { 0x00, 0x00, }, // wCompWindowSize { 0x00, 0x00 }, // wDelay { MAKE_DWORD(MAX_FRAME_SIZE) }, // dwMaxVideoFrameSize { 0x00, 0x00, 0x00, 0x00 }, // dwMaxPayloadTransferSize { 0x00, 0x00, 0x00, 0x00 }, // dwClockFrequency { 0x00 }, // bmFramingInfo { 0x00 }, // bPreferedVersion { 0x00 }, // bMinVersion { 0x00 }, // bMaxVersion }; /* -------------------------------------------------------------------------- */ /* Structures initializations */ /* -------------------------------------------------------------------------- */ DEVICE Device_Table = { EP_NUM, 1 }; DEVICE_PROP Device_Property = { UsbCamera_init, UsbCamera_Reset, UsbCamera_Status_In, UsbCamera_Status_Out, UsbCamera_Data_Setup, UsbCamera_NoData_Setup, UsbCamera_Get_Interface_Setting, UsbCamera_GetDeviceDescriptor, UsbCamera_GetConfigDescriptor, UsbCamera_GetStringDescriptor, 0, 0x40 /*MAX PACKET SIZE*/ }; USER_STANDARD_REQUESTS User_Standard_Requests = { UsbCamera_GetConfiguration, UsbCamera_SetConfiguration, UsbCamera_GetInterface, UsbCamera_SetInterface, UsbCamera_GetStatus, UsbCamera_ClearFeature, UsbCamera_SetEndPointFeature, UsbCamera_SetDeviceFeature, UsbCamera_SetDeviceAddress }; ONE_DESCRIPTOR Device_Descriptor = { (u8*)Camera_DeviceDescriptor, CAMERA_SIZ_DEVICE_DESC }; ONE_DESCRIPTOR Config_Descriptor = { (u8*)Camera_ConfigDescriptor, CAMERA_SIZ_CONFIG_DESC }; ONE_DESCRIPTOR String_Descriptor[4] = { { (u8*)Camera_StringLangID, CAMERA_SIZ_STRING_LANGID }, { (u8*)Camera_StringVendor, CAMERA_SIZ_STRING_VENDOR }, { (u8*)Camera_StringProduct, CAMERA_SIZ_STRING_PRODUCT }, { (u8*)Camera_StringSerial, CAMERA_SIZ_STRING_SERIAL } }; /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Extern function prototypes ------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : * Description : init routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void UsbCamera_init(void) { /* Update the serial number string descriptor with the data from the unique ID*/ //Get_SerialNum(); pInformation->Current_Configuration = 0; /* Connect the device */ PowerOn(); /* USB interrupts initialization */ /* clear pending interrupts */ _SetISTR(0); wInterrupt_Mask = IMR_MSK; /* set interrupts mask */ _SetCNTR(wInterrupt_Mask); bDeviceState = UNCONNECTED; } /******************************************************************************* * Function Name : * Description : reset routine * Input : None. * Output : None. * Return : None. *******************************************************************************/ void UsbCamera_Reset(void) { /* Set Usb device as not configured state */ pInformation->Current_Configuration = 0; /* Current Feature initialization */ pInformation->Current_Feature = Camera_ConfigDescriptor[7]; SetBTABLE(BTABLE_ADDRESS); /* Initialize Endpoint 0 */ SetEPType(ENDP0, EP_CONTROL); SetEPTxStatus(ENDP0, EP_TX_NAK); SetEPRxAddr(ENDP0, ENDP0_RXADDR); SetEPRxCount(ENDP0, Device_Property.MaxPacketSize); SetEPTxAddr(ENDP0, ENDP0_TXADDR); Clear_Status_Out(ENDP0); SetEPRxValid(ENDP0); /* Initialize Endpoint 1 */ SetEPType(ENDP1, EP_ISOCHRONOUS); SetEPDoubleBuff(ENDP1); SetEPDblBuffAddr(ENDP1, ENDP1_BUF0Addr, ENDP1_BUF1Addr); SetEPDblBuffCount(ENDP1, EP_DBUF_IN, PACKET_SIZE); ClearDTOG_RX(ENDP1); ClearDTOG_TX(ENDP1); SetEPDblBuf0Count(ENDP1, EP_DBUF_IN, 0); SetEPDblBuf1Count(ENDP1, EP_DBUF_IN, 0); SetEPRxStatus(ENDP1, EP_RX_DIS); // SetEPTxStatus(ENDP1, EP_TX_VALID); SetEPTxStatus(ENDP1, EP_TX_NAK); SetEPRxValid(ENDP0); /* Set this device to response on default address */ SetDeviceAddress(0); bDeviceState = ATTACHED; } /******************************************************************************* * Function Name : * Description : Udpade the device state to configured. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void UsbCamera_SetConfiguration(void) { DEVICE_INFO *pInfo = &Device_Info; if (pInfo->Current_Configuration != 0) { /* Device configured */ bDeviceState = CONFIGURED; } } /******************************************************************************* * Function Name : * Description : Udpade the device state to addressed. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void UsbCamera_SetDeviceAddress(void) { bDeviceState = ADDRESSED; } /******************************************************************************* * Function Name : * Description : Status In Routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void UsbCamera_Status_In(void) {} /******************************************************************************* * Function Name : * Description : Status OUT Routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void UsbCamera_Status_Out(void) {} /******************************************************************************* * Function Name : * Description : handle the data class specific requests * 对Class-specific Requests的应答 * Input : Request Nb. * Output : None. * Return : USB_UNSUPPORT or USB_SUCCESS. *******************************************************************************/ RESULT UsbCamera_Data_Setup(u8 RequestNo) { u8 *(*CopyRoutine)(u16); CopyRoutine = NULL; if ((RequestNo == GET_CUR) || (RequestNo == SET_CUR)) { if (pInformation->USBwIndex == 0x0100) { if (pInformation->USBwValue == 0x0001) { // Probe Control CopyRoutine = VideoProbeControl_Command; } else if (pInformation->USBwValue == 0x0002) { // Commit control CopyRoutine = VideoCommitControl_Command; } } } else { return USB_UNSUPPORT; } pInformation->Ctrl_Info.CopyData = CopyRoutine; pInformation->Ctrl_Info.Usb_wOffset = 0; (*CopyRoutine)(0); return USB_SUCCESS; } /******************************************************************************* * Function Name : * Description : handle the no data class specific requests. * Input : Request Nb. * Output : None. * Return : USB_UNSUPPORT or USB_SUCCESS. *******************************************************************************/ RESULT UsbCamera_NoData_Setup(u8 RequestNo) { return USB_UNSUPPORT; } /******************************************************************************* * Function Name : * Description : Gets the device descriptor. * Input : Length. * Output : None. * Return : The address of the device descriptor. *******************************************************************************/ u8 *UsbCamera_GetDeviceDescriptor(u16 Length) { return Standard_GetDescriptorData(Length, &Device_Descriptor); } /******************************************************************************* * Function Name : * Description : get the configuration descriptor. * Input : Length. * Output : None. * Return : The address of the configuration descriptor. *******************************************************************************/ u8 *UsbCamera_GetConfigDescriptor(u16 Length) { return Standard_GetDescriptorData(Length, &Config_Descriptor); } /******************************************************************************* * Function Name : * Description : Gets the string descriptors according to the needed index * Input : Length. * Output : None. * Return : The address of the string descriptors. *******************************************************************************/ u8 *UsbCamera_GetStringDescriptor(u16 Length) { u8 wValue0 = pInformation->USBwValue0; if (wValue0 > 4) { return NULL; } else { return Standard_GetDescriptorData(Length, &String_Descriptor[wValue0]); } } /******************************************************************************* * Function Name : * Description : test the interface and the alternate setting according to the * supported one. * Input1 : u8: Interface : interface number. * Input2 : u8: AlternateSetting : Alternate Setting number. * Output : None. * Return : The address of the string descriptors. *******************************************************************************/ RESULT UsbCamera_Get_Interface_Setting(u8 Interface, u8 AlternateSetting) { if (AlternateSetting > 1) { return USB_UNSUPPORT; } else if (Interface > 1) { return USB_UNSUPPORT; } return USB_SUCCESS; } /******************************************************************************* * Function Name : * Description : * Input : * Output : * Return : *******************************************************************************/ u8* VideoProbeControl_Command(u16 Length) { if (Length == 0) { pInformation->Ctrl_Info.Usb_wLength = pInformation->USBwLengths.w; return NULL; } else { return((u8*)(&videoProbeControl)); } } /******************************************************************************* * Function Name : * Description : * Input : * Output : * Return : *******************************************************************************/ u8* VideoCommitControl_Command(u16 Length) { if (Length == 0) { pInformation->Ctrl_Info.Usb_wLength = pInformation->USBwLengths.w; return NULL; } else { return((u8*)(&videoCommitControl)); } } /******************* (C) COPYRIGHT 2011 xxxxxxxxxxxxxxx *****END OF FILE****/ <file_sep>/USB/SRCIMG/srvyuv.c #include "srcyuv.h" const u8 YUVbuf[YUV_SIZE] = { 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x60, 0x00, 0x60, 0x00, 0x00, 0xff, 0xe1, 0x00, 0x22, 0x45, 0x78, 0x69, 0x66, 0x00, 0x00, 0x4d, 0x4d, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x05, 0x03, 0x03, 0x03, 0x03, 0x03, 0x06, 0x04, 0x04, 0x03, 0x05, 0x07, 0x06, 0x07, 0x07, 0x07, 0x06, 0x07, 0x07, 0x08, 0x09, 0x0b, 0x09, 0x08, 0x08, 0x0a, 0x08, 0x07, 0x07, 0x0a, 0x0d, 0x0a, 0x0a, 0x0b, 0x0c, 0x0c, 0x0c, 0x0c, 0x07, 0x09, 0x0e, 0x0f, 0x0d, 0x0c, 0x0e, 0x0b, 0x0c, 0x0c, 0x0c, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x06, 0x03, 0x03, 0x06, 0x0c, 0x08, 0x07, 0x08, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0xf0, 0x01, 0x40, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xc4, 0x00, 0x1f, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xc4, 0x00, 0x1f, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xfd, 0xfc, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xaa, 0xba, 0xce, 0xb3, 0x69, 0xe1, 0xdd, 0x26, 0xe2, 0xfa, 0xfa, 0xe2, 0x1b, 0x4b, 0x3b, 0x48, 0xcc, 0xb3, 0x4d, 0x2b, 0x05, 0x48, 0x90, 0x0c, 0x92, 0x49, 0xed, 0x56, 0xab, 0x9d, 0xf8, 0xad, 0xf0, 0xcf, 0x4e, 0xf8, 0xc7, 0xf0, 0xfb, 0x52, 0xf0, 0xde, 0xac, 0xd7, 0x49, 0xa7, 0xea, 0x88, 0xab, 0x2b, 0x5b, 0xb8, 0x49, 0x53, 0x6b, 0xab, 0xa9, 0x52, 0x41, 0x19, 0x0c, 0xa0, 0xf2, 0x08, 0x3d, 0xc1, 0xac, 0x31, 0x52, 0xab, 0x1a, 0x33, 0x95, 0x04, 0x9c, 0xec, 0xf9, 0x53, 0x76, 0x4d, 0xdb, 0x44, 0xdf, 0x44, 0xde, 0xec, 0xe8, 0xc2, 0xc6, 0x8c, 0xab, 0xc2, 0x38, 0x86, 0xe3, 0x06, 0xd7, 0x33, 0x4a, 0xed, 0x2b, 0xea, 0xd2, 0xea, 0xd2, 0xd9, 0x75, 0x3c, 0x2f, 0xc5, 0xbf, 0xf0, 0x50, 0x76, 0xf1, 0x26, 0xb5, 0x71, 0xa4, 0xfc, 0x31, 0xf0, 0x7e, 0xad, 0xe3, 0x5b, 0xc8, 0x93, 0x9b, 0xb1, 0x0c, 0x8b, 0x6f, 0x11, 0x24, 0x00, 0xfe, 0x5a, 0xa9, 0x76, 0x4c, 0x9e, 0x4b, 0x18, 0xfe, 0xb5, 0x52, 0x7b, 0xff, 0x00, 0xda, 0x93, 0xc7, 0xfa, 0xb5, 0xbc, 0x2b, 0x67, 0xe1, 0x8f, 0x03, 0xc2, 0x8a, 0xc5, 0xee, 0x14, 0xdb, 0xcb, 0x0c, 0x87, 0xb0, 0x60, 0x5a, 0xe5, 0xf3, 0xd8, 0x6d, 0x50, 0x3d, 0x6b, 0xe8, 0x3f, 0x86, 0x9f, 0x0d, 0x34, 0x6f, 0x84, 0x7e, 0x0f, 0xb5, 0xd0, 0xf4, 0x1b, 0x34, 0xb3, 0xb0, 0xb5, 0x5e, 0x00, 0xe5, 0xe5, 0x6e, 0xee, 0xed, 0xfc, 0x4c, 0x7b, 0x93, 0xfa, 0x00, 0x05, 0x6f, 0x57, 0xc7, 0x43, 0x86, 0x73, 0x3c, 0x5c, 0x55, 0x4c, 0xd3, 0x1f, 0x51, 0x49, 0xd9, 0xb8, 0xd1, 0x6a, 0x9c, 0x17, 0x56, 0x93, 0xb3, 0x9b, 0x5e, 0x7c, 0xc9, 0xbf, 0xc0, 0xfb, 0x4a, 0x9c, 0x51, 0x95, 0x60, 0xe4, 0xe9, 0xe5, 0x59, 0x7d, 0x37, 0x15, 0x74, 0xa7, 0x59, 0x3a, 0x93, 0x7d, 0x14, 0x9a, 0xba, 0x82, 0x7d, 0x6d, 0xca, 0xd2, 0xfc, 0x5f, 0xcd, 0x5f, 0x02, 0xfe, 0x3b, 0x7c, 0x45, 0xf0, 0x77, 0xed, 0x14, 0xbf, 0x0c, 0xfe, 0x25, 0xfd, 0x97, 0x55, 0xbd, 0xd5, 0x61, 0x7b, 0x9d, 0x3f, 0x51, 0xb5, 0x8e, 0x38, 0xd3, 0x6a, 0xc7, 0x23, 0xe4, 0x6c, 0x44, 0x0d, 0x1b, 0x08, 0x9c, 0x64, 0xa8, 0x60, 0xcb, 0x83, 0xed, 0xf4, 0xad, 0x71, 0xba, 0xdf, 0xc0, 0xbd, 0x0f, 0x5f, 0xf8, 0xd5, 0xa3, 0x78, 0xfa, 0x73, 0x78, 0x35, 0xcd, 0x0e, 0xcd, 0xec, 0xad, 0xc2, 0x4a, 0x04, 0x0c, 0x8c, 0x24, 0x19, 0x65, 0xc6, 0x49, 0x02, 0x59, 0x31, 0x82, 0x3e, 0xf7, 0x20, 0xe0, 0x63, 0x2b, 0xf6, 0x90, 0xf8, 0x17, 0xa9, 0x7c, 0x7b, 0xf0, 0xed, 0x96, 0x97, 0x67, 0xe2, 0xdd, 0x43, 0xc2, 0xf6, 0x71, 0xca, 0xc6, 0xf6, 0x3b, 0x68, 0x7c, 0xc1, 0xa8, 0x46, 0x40, 0x1b, 0x1b, 0x0e, 0xa7, 0x8c, 0x1c, 0x72, 0x47, 0x3c, 0xa9, 0xc0, 0xc7, 0x66, 0x57, 0x87, 0xcc, 0xf2, 0xcc, 0x15, 0x78, 0x4f, 0x9b, 0x11, 0x28, 0xcd, 0xfb, 0x24, 0xe6, 0xb9, 0x9c, 0x1a, 0x8d, 0x94, 0xa7, 0x2b, 0x6a, 0x9f, 0x36, 0xae, 0xee, 0xcb, 0x4b, 0xe8, 0x8e, 0x3c, 0xd7, 0x15, 0x95, 0x66, 0x98, 0xec, 0x3d, 0x48, 0x72, 0xe1, 0xa3, 0x28, 0x25, 0x55, 0xa8, 0x3e, 0x45, 0x34, 0xe5, 0x77, 0x18, 0x46, 0xfa, 0x34, 0xa3, 0x64, 0xac, 0xae, 0xf5, 0xb6, 0xac, 0xce, 0xf8, 0xbf, 0xfb, 0x6b, 0x7c, 0x3f, 0xf8, 0x31, 0x7f, 0x71, 0x61, 0xa8, 0x6a, 0x93, 0x6a, 0x1a, 0xb5, 0xa9, 0x02, 0x4b, 0x0d, 0x3a, 0x13, 0x34, 0xaa, 0x4f, 0x62, 0xc7, 0x11, 0xa9, 0x1d, 0xc3, 0x38, 0x3e, 0xd5, 0xe6, 0x3a, 0x6f, 0xed, 0x6d, 0xf1, 0x8f, 0xe3, 0x06, 0xa0, 0xd7, 0x5f, 0x0f, 0xfe, 0x1a, 0x5b, 0x7f, 0x61, 0x98, 0xf7, 0xc3, 0x71, 0xab, 0xab, 0xa8, 0xb9, 0x5d, 0xc4, 0x6e, 0x59, 0x5a, 0x58, 0x63, 0x3f, 0xee, 0xa9, 0x62, 0x30, 0x79, 0x35, 0xea, 0xdf, 0x06, 0xff, 0x00, 0x63, 0xef, 0x01, 0xfc, 0x12, 0x85, 0x1b, 0x4e, 0xd2, 0x23, 0xd4, 0x75, 0x08, 0xe5, 0x13, 0x2e, 0xa3, 0xa9, 0xa2, 0x5c, 0x5d, 0x46, 0xc3, 0xa1, 0x46, 0xda, 0x04, 0x78, 0xcf, 0xf0, 0x05, 0xcf, 0x7c, 0xd7, 0xa8, 0x57, 0x22, 0xca, 0xb3, 0xfc, 0x7b, 0xe7, 0xc7, 0x62, 0x96, 0x1e, 0x3f, 0xc9, 0x45, 0x27, 0x2f, 0x2b, 0xd4, 0x9a, 0x77, 0x7d, 0xed, 0x14, 0x99, 0xd8, 0xf3, 0x6e, 0x1e, 0xcb, 0xd3, 0x86, 0x03, 0x0a, 0xf1, 0x12, 0xfe, 0x7a, 0xcd, 0xa8, 0xf9, 0xda, 0x9c, 0x1a, 0xb2, 0x7d, 0x2f, 0x36, 0xd1, 0xf2, 0xae, 0xa1, 0xfb, 0x5b, 0xfc, 0x5b, 0xf8, 0x49, 0xe3, 0x6f, 0x0c, 0xc3, 0xf1, 0x23, 0xc2, 0x7e, 0x17, 0xd0, 0xf4, 0x1d, 0x72, 0xf9, 0x6d, 0x64, 0xba, 0x81, 0xcb, 0x18, 0x93, 0x72, 0x07, 0x7d, 0xc9, 0x71, 0x28, 0x5d, 0x8a, 0xfb, 0xb0, 0xc3, 0xe6, 0x00, 0xe3, 0xa1, 0x23, 0xea, 0xaa, 0xf3, 0xff, 0x00, 0xda, 0x5b, 0xe0, 0x05, 0x9f, 0xed, 0x21, 0xf0, 0xd5, 0xb4, 0x0b, 0xab, 0xd9, 0x34, 0xe9, 0x61, 0xb9, 0x4b, 0xcb, 0x5b, 0x94, 0x8f, 0xcc, 0xf2, 0xa5, 0x55, 0x65, 0xf9, 0x97, 0x23, 0x72, 0x95, 0x76, 0x18, 0xc8, 0xeb, 0x9e, 0xd5, 0xd9, 0xf8, 0x6f, 0x4c, 0x9f, 0x45, 0xf0, 0xed, 0x85, 0x9d, 0xd5, 0xe4, 0xda, 0x95, 0xcd, 0xa5, 0xbc, 0x70, 0xcb, 0x77, 0x2a, 0x85, 0x92, 0xe9, 0xd5, 0x40, 0x32, 0x30, 0x1c, 0x02, 0xc4, 0x12, 0x71, 0xeb, 0x5d, 0xf9, 0x16, 0x07, 0x31, 0xc1, 0x62, 0xeb, 0xd0, 0xc4, 0xd4, 0x95, 0x5a, 0x2d, 0x45, 0xc2, 0x73, 0x71, 0x72, 0x4e, 0xcd, 0x4e, 0x2e, 0xc9, 0x75, 0x49, 0xa7, 0xcb, 0x6b, 0x3b, 0x5e, 0xe7, 0x9f, 0x9f, 0xe6, 0x19, 0x6e, 0x3b, 0x07, 0x43, 0x11, 0x86, 0xa5, 0x1a, 0x35, 0xd3, 0x94, 0x6a, 0x42, 0x0a, 0x4a, 0x2d, 0x5d, 0x38, 0x49, 0x5d, 0xcb, 0xa3, 0x69, 0xae, 0x6b, 0xdd, 0x5e, 0xd6, 0x2e, 0xd1, 0x45, 0x15, 0xf5, 0x07, 0xc9, 0x85, 0x14, 0x51, 0x40, 0x05, 0x14, 0x51, 0x40, 0x05, 0x14, 0x53, 0x76, 0x2f, 0xf5, 0xa0, 0x07, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x00, 0x51, 0x45, 0x14, 0x01, 0xe1, 0xbf, 0xb4, 0x57, 0xed, 0x11, 0xae, 0x7c, 0x06, 0xf8, 0xef, 0xe0, 0x95, 0xbc, 0x16, 0xd1, 0xf8, 0x07, 0x5b, 0x46, 0xb6, 0xbd, 0x98, 0xa0, 0xdf, 0x1c, 0xfb, 0x88, 0x2e, 0x5b, 0xaa, 0xaa, 0x06, 0x89, 0xb1, 0xfc, 0x43, 0xcc, 0xea, 0x40, 0xc7, 0xb7, 0xdb, 0x5c, 0xc7, 0x79, 0x6f, 0x1c, 0xd0, 0xc8, 0x92, 0xc3, 0x2a, 0x87, 0x47, 0x46, 0xdc, 0xae, 0xa7, 0x90, 0x41, 0x1d, 0x41, 0xf5, 0xac, 0x2f, 0x89, 0xff, 0x00, 0x0b, 0xf4, 0x5f, 0x8c, 0x1e, 0x0e, 0xba, 0xd0, 0xf5, 0xeb, 0x35, 0xbc, 0xb1, 0xba, 0x19, 0xf4, 0x92, 0x17, 0x1d, 0x1d, 0x1b, 0xf8, 0x58, 0x76, 0x3f, 0x50, 0x72, 0x09, 0x07, 0xe7, 0x88, 0x7f, 0x67, 0x8f, 0x8c, 0x1f, 0xb3, 0x25, 0xd4, 0x8b, 0xf0, 0xcb, 0x5d, 0xb5, 0xf1, 0x37, 0x86, 0xda, 0x71, 0x22, 0x68, 0xda, 0xa3, 0x22, 0xc8, 0xb9, 0xeb, 0x92, 0xdb, 0x57, 0x03, 0xb9, 0x8e, 0x48, 0xc9, 0x3f, 0xc3, 0x5f, 0x17, 0x8a, 0xc5, 0x66, 0x79, 0x56, 0x32, 0xad, 0x69, 0x53, 0x9e, 0x23, 0x0d, 0x51, 0xa6, 0xb9, 0x35, 0x9d, 0x37, 0x64, 0x9a, 0x51, 0xd3, 0x9a, 0x0e, 0xd7, 0x5c, 0xba, 0xa6, 0xde, 0x8f, 0x73, 0xee, 0x30, 0xb8, 0x3c, 0xab, 0x36, 0xc1, 0x52, 0xa3, 0x1a, 0xb0, 0xc3, 0x62, 0x69, 0xa7, 0x17, 0xcf, 0xee, 0xd3, 0xaa, 0xae, 0xda, 0x6e, 0x7a, 0xf2, 0xcd, 0x5e, 0xcf, 0x99, 0x59, 0xa4, 0xb5, 0x56, 0xb2, 0xfa, 0x9e, 0x8a, 0xf9, 0x4f, 0x40, 0xff, 0x00, 0x82, 0x91, 0x5d, 0x78, 0x0e, 0xf2, 0xe3, 0x49, 0xf8, 0x9d, 0xe0, 0xbd, 0x5b, 0x47, 0xd6, 0xad, 0xf9, 0xc6, 0x9f, 0x0e, 0x04, 0x80, 0x9e, 0x0f, 0x97, 0x33, 0xa9, 0x0b, 0xc7, 0x0c, 0x1d, 0x83, 0x76, 0xe2, 0xa6, 0xf1, 0x37, 0xfc, 0x14, 0xe7, 0x46, 0xd7, 0xb4, 0x79, 0x2c, 0x7c, 0x17, 0xe1, 0xaf, 0x13, 0x5f, 0xf8, 0x9a, 0xf3, 0xf7, 0x36, 0x30, 0xdc, 0xda, 0xc7, 0xe5, 0x99, 0x0f, 0x00, 0xed, 0x8e, 0x47, 0x76, 0x23, 0xa8, 0x50, 0x39, 0xf5, 0x15, 0x9a, 0xf1, 0x1b, 0x87, 0xfd, 0x9b, 0x94, 0xab, 0xda, 0x4b, 0xec, 0x38, 0xc9, 0x4e, 0xeb, 0xec, 0xf2, 0xb5, 0x7b, 0xdf, 0x4b, 0x1a, 0x3f, 0x0c, 0xf8, 0x8b, 0xda, 0x28, 0x47, 0x0f, 0x78, 0xbf, 0xb6, 0xa5, 0x17, 0x0b, 0x3f, 0xb5, 0xcc, 0x9d, 0xad, 0x6d, 0x6e, 0x7d, 0x4d, 0x45, 0x78, 0xaf, 0xec, 0x61, 0xf0, 0x9b, 0xc5, 0xbe, 0x04, 0xf0, 0xee, 0xb3, 0xae, 0xf8, 0xd3, 0x54, 0xba, 0xba, 0xd7, 0x3c, 0x5d, 0x34, 0x77, 0x72, 0xd9, 0xcc, 0xe5, 0xbe, 0xc4, 0x14, 0x3e, 0x33, 0xd8, 0x3b, 0x07, 0x19, 0x50, 0x30, 0xa1, 0x14, 0x76, 0xc0, 0xf6, 0xaa, 0xfa, 0x6c, 0xa7, 0x1d, 0x57, 0x19, 0x84, 0x86, 0x26, 0xb5, 0x27, 0x49, 0xcb, 0x5e, 0x59, 0x6e, 0x95, 0xdd, 0xaf, 0xd9, 0xb5, 0x66, 0xd7, 0x4b, 0xd9, 0xea, 0x8f, 0x96, 0xce, 0x30, 0x34, 0xb0, 0x58, 0xc9, 0xe1, 0x68, 0xd5, 0x55, 0x63, 0x1b, 0x2e, 0x68, 0xec, 0xdd, 0x95, 0xed, 0xdd, 0x27, 0x74, 0x9f, 0x5b, 0x5d, 0x68, 0xc2, 0x8a, 0x28, 0xaf, 0x48, 0xf3, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x0f, 0x2a, 0xfd, 0xb2, 0xbe, 0x38, 0x5e, 0x7c, 0x03, 0xf8, 0x23, 0x75, 0xab, 0xe9, 0x8d, 0x1a, 0x6a, 0xd7, 0x77, 0x31, 0x58, 0xd8, 0xbc, 0x89, 0xbd, 0x52, 0x47, 0xcb, 0x16, 0x20, 0xf0, 0x71, 0x1a, 0x39, 0x19, 0xe3, 0x38, 0xeb, 0xd2, 0xbd, 0x0f, 0xc1, 0x72, 0xea, 0x53, 0x78, 0x3b, 0x49, 0x7d, 0x60, 0x46, 0xba, 0xbb, 0x59, 0xc2, 0x6f, 0x84, 0x6b, 0xb5, 0x04, 0xfb, 0x07, 0x99, 0xb4, 0x76, 0x1b, 0xb3, 0x81, 0x5f, 0x3c, 0x7f, 0xc1, 0x44, 0x0b, 0x78, 0xcb, 0x57, 0xf8, 0x63, 0xe0, 0x6d, 0xca, 0xb0, 0xf8, 0x9b, 0x5e, 0x0d, 0x33, 0x8f, 0xbf, 0x16, 0xd3, 0x1c, 0x20, 0xfd, 0x31, 0x72, 0xe7, 0xfe, 0x03, 0x5f, 0x4c, 0xd7, 0xca, 0xe5, 0xb8, 0xba, 0xd5, 0xf3, 0xdc, 0x6c, 0x1c, 0x9f, 0xb3, 0xa5, 0x1a, 0x51, 0x4b, 0xa7, 0x33, 0x52, 0x9c, 0x9d, 0xbb, 0xd9, 0xc7, 0x5e, 0xda, 0x74, 0x3e, 0xbb, 0x34, 0xc1, 0xd0, 0xc3, 0xe4, 0x18, 0x19, 0xa8, 0xaf, 0x69, 0x56, 0x55, 0x66, 0xdf, 0x5e, 0x54, 0xe3, 0x08, 0xab, 0xf6, 0xba, 0x96, 0x9d, 0xf5, 0xea, 0x14, 0x51, 0x45, 0x7d, 0x51, 0xf2, 0x21, 0x45, 0x14, 0x50, 0x01, 0x45, 0x14, 0x50, 0x01, 0x45, 0x14, 0x50, 0x01, 0x45, 0x14, 0x50, 0x01, 0x45, 0x14, 0x50, 0x01, 0x45, 0x14, 0x50, 0x01, 0x45, 0x15, 0x9f, 0xe2, 0xaf, 0x16, 0xe9, 0x9e, 0x07, 0xd0, 0xe7, 0xd4, 0xf5, 0x8b, 0xfb, 0x5d, 0x37, 0x4f, 0xb6, 0x1b, 0xa4, 0x9e, 0xe2, 0x41, 0x1a, 0x2f, 0xb6, 0x4f, 0x52, 0x7b, 0x01, 0xc9, 0x3c, 0x0a, 0x9a, 0x95, 0x23, 0x08, 0xb9, 0xcd, 0xd9, 0x2d, 0x5b, 0x7a, 0x24, 0xbc, 0xcb, 0xa7, 0x4e, 0x75, 0x24, 0xa1, 0x04, 0xdb, 0x7a, 0x24, 0xb5, 0x6d, 0xf9, 0x23, 0x42, 0x8a, 0xf9, 0x67, 0xc4, 0x1f, 0xb5, 0x47, 0x8e, 0x3f, 0x69, 0x8d, 0x4d, 0xb4, 0x1f, 0x84, 0x5a, 0x2d, 0xe6, 0x9d, 0xa7, 0xf9, 0xbe, 0x55, 0xd7, 0x89, 0x2f, 0x63, 0x0a, 0x91, 0x2f, 0x7d, 0xb9, 0x05, 0x53, 0xd7, 0xf8, 0xa4, 0x23, 0xa2, 0x83, 0x57, 0xd3, 0xf6, 0x0c, 0xf1, 0x56, 0xbf, 0x1a, 0xc7, 0xe2, 0x3f, 0x8c, 0x9e, 0x2e, 0xd5, 0x2d, 0xd8, 0x7e, 0xf2, 0xdd, 0x0c, 0xaa, 0xa0, 0x9f, 0xbc, 0x01, 0x79, 0x98, 0x11, 0xef, 0xb4, 0x74, 0xe9, 0xda, 0xbe, 0x36, 0x3c, 0x5d, 0x57, 0x17, 0x27, 0xfd, 0x8d, 0x85, 0x96, 0x22, 0x0b, 0x4e, 0x7b, 0xc6, 0x10, 0x6f, 0xfb, 0xae, 0x6d, 0x39, 0x5b, 0xab, 0x8a, 0x6b, 0xd4, 0xfb, 0x59, 0x70, 0x6d, 0x2c, 0x1c, 0x57, 0xf6, 0xde, 0x2e, 0x18, 0x79, 0xbd, 0x79, 0x2d, 0x2a, 0x93, 0x4b, 0xfb, 0xca, 0x09, 0xa8, 0xdf, 0xa2, 0x93, 0x4f, 0xd0, 0xfa, 0x5e, 0x8a, 0xf0, 0x3f, 0x87, 0x3f, 0xf0, 0x4e, 0xdf, 0x06, 0xfc, 0x33, 0xf1, 0xb6, 0x97, 0xe2, 0x0b, 0x2d, 0x67, 0xc5, 0xd2, 0xea, 0x1a, 0x5c, 0xeb, 0x72, 0x82, 0x4b, 0xc8, 0x56, 0x39, 0x59, 0x4e, 0x70, 0xc1, 0x62, 0x0c, 0x54, 0xf7, 0x1b, 0xb9, 0x1c, 0x1c, 0x8c, 0xd7, 0xbe, 0x57, 0xd0, 0x65, 0x38, 0xac, 0x75, 0x6a, 0x6e, 0x58, 0xfa, 0x0a, 0x94, 0xaf, 0xa2, 0x53, 0xe7, 0xba, 0xef, 0x7e, 0x58, 0xdb, 0xd0, 0xf9, 0xdc, 0xdf, 0x0b, 0x80, 0xa1, 0x51, 0x47, 0x2f, 0xae, 0xeb, 0x46, 0xda, 0xb7, 0x0e, 0x4b, 0x3e, 0xd6, 0xe6, 0x95, 0xfd, 0x74, 0x0a, 0x28, 0xa2, 0xbd, 0x43, 0xc9, 0x0a, 0x28, 0xae, 0x5f, 0xe2, 0xc7, 0xc6, 0x7f, 0x0d, 0xfc, 0x12, 0xf0, 0xe7, 0xf6, 0xa7, 0x89, 0x35, 0x28, 0xec, 0x60, 0x63, 0xb6, 0x24, 0xc1, 0x79, 0xae, 0x1b, 0xfb, 0xa8, 0x83, 0x96, 0x3f, 0xa0, 0xee, 0x40, 0xac, 0x71, 0x38, 0xaa, 0x38, 0x7a, 0x52, 0xad, 0x5e, 0x4a, 0x31, 0x8e, 0xad, 0xb7, 0x64, 0x97, 0x9b, 0x67, 0x46, 0x17, 0x0b, 0x5b, 0x13, 0x56, 0x34, 0x30, 0xf1, 0x72, 0x9c, 0x9d, 0x92, 0x49, 0xb6, 0xdf, 0x92, 0x47, 0x51, 0x45, 0x7c, 0xbf, 0x27, 0xed, 0xcb, 0xe3, 0x9f, 0x89, 0x4a, 0x17, 0xe1, 0xef, 0xc2, 0xbd, 0x5e, 0xfa, 0x0b, 0xa9, 0xbc, 0xab, 0x4d, 0x52, 0xfd, 0x64, 0x6b, 0x57, 0xe7, 0x9d, 0xe1, 0x55, 0x63, 0x5f, 0xa9, 0x9b, 0x03, 0xbd, 0x5a, 0xff, 0x00, 0x85, 0x9f, 0xfb, 0x4f, 0x7f, 0xd1, 0x39, 0xf0, 0x6f, 0xfe, 0x04, 0xc7, 0xff, 0x00, 0xc9, 0xb5, 0xf2, 0x51, 0xe3, 0xac, 0x05, 0x4d, 0x70, 0xb4, 0xea, 0xd6, 0x8f, 0xf3, 0x42, 0x8d, 0x49, 0x47, 0xef, 0xe5, 0x57, 0xf9, 0x69, 0xd9, 0x9f, 0x5f, 0x2e, 0x01, 0xcc, 0x69, 0xe9, 0x8b, 0xa9, 0x46, 0x8c, 0xbf, 0x96, 0x75, 0xa9, 0xc6, 0x5f, 0x77, 0x33, 0xb7, 0xa3, 0xd7, 0xba, 0x3e, 0x96, 0xa2, 0xbe, 0x77, 0xf8, 0x51, 0xfb, 0x72, 0xb5, 0xb7, 0x8c, 0x65, 0xf0, 0x8f, 0xc5, 0x2d, 0x2e, 0x2f, 0x06, 0xf8, 0x9a, 0x39, 0x76, 0x2c, 0xa3, 0xe5, 0xb0, 0x70, 0x46, 0x46, 0x59, 0x9d, 0xb6, 0xe7, 0xb3, 0x6e, 0x64, 0x6e, 0xbb, 0x85, 0x7d, 0x0b, 0x6f, 0x71, 0x1d, 0xdd, 0xbc, 0x73, 0x43, 0x22, 0x4b, 0x14, 0xaa, 0x1d, 0x1d, 0x0e, 0xe5, 0x75, 0x3c, 0x82, 0x0f, 0x70, 0x7d, 0x6b, 0xdc, 0xc9, 0xf3, 0xcc, 0x1e, 0x67, 0x4d, 0xd4, 0xc2, 0x4e, 0xee, 0x2e, 0xd2, 0x8b, 0x56, 0x94, 0x5f, 0x55, 0x28, 0xbd, 0x53, 0xf5, 0x47, 0x81, 0x9c, 0xe4, 0x38, 0xdc, 0xae, 0xaa, 0xa7, 0x8c, 0x85, 0x94, 0x95, 0xe3, 0x24, 0xef, 0x19, 0x2e, 0x8e, 0x32, 0x5a, 0x35, 0xe8, 0xc7, 0xd1, 0x59, 0xbe, 0x2a, 0xf1, 0x86, 0x95, 0xe0, 0x7d, 0x1e, 0x4d, 0x43, 0x59, 0xd4, 0xac, 0xb4, 0xbb, 0x18, 0xfe, 0xf4, 0xf7, 0x53, 0x2c, 0x49, 0x9f, 0x4c, 0xb1, 0xe4, 0x9e, 0xc0, 0x72, 0x6b, 0xc1, 0xbc, 0x67, 0xff, 0x00, 0x05, 0x0c, 0xd2, 0x6f, 0x75, 0x66, 0xd1, 0xfe, 0x1e, 0xf8, 0x7f, 0x58, 0xf1, 0xc6, 0xb0, 0xd9, 0x08, 0x61, 0x81, 0xe3, 0xb7, 0x1d, 0xb3, 0xf7, 0x4c, 0x8c, 0x07, 0x7f, 0x95, 0x47, 0xfb, 0x5d, 0xea, 0x33, 0x6e, 0x22, 0xcb, 0xb2, 0xd4, 0xbe, 0xb9, 0x55, 0x45, 0xbd, 0xa3, 0xbc, 0x9f, 0xa4, 0x55, 0xe4, 0xfe, 0x48, 0xd3, 0x27, 0xe1, 0xbc, 0xcf, 0x33, 0x6f, 0xea, 0x54, 0x5c, 0xa2, 0xb7, 0x96, 0xd1, 0x5e, 0xb2, 0x76, 0x8a, 0xf9, 0xb3, 0xe8, 0xba, 0x2b, 0xe6, 0x78, 0xff, 0x00, 0xe1, 0xa6, 0xbe, 0x24, 0x00, 0xdb, 0xbc, 0x27, 0xe0, 0x78, 0x65, 0x19, 0xc1, 0x09, 0x23, 0xaa, 0xff, 0x00, 0xe4, 0x72, 0x1b, 0x1f, 0x4f, 0xc2, 0x9d, 0xff, 0x00, 0x0c, 0x7b, 0xf1, 0x53, 0xc4, 0x27, 0xed, 0x1a, 0xaf, 0xc7, 0x0d, 0x7a, 0xce, 0xe4, 0xf5, 0x4b, 0x04, 0x98, 0x45, 0xff, 0x00, 0x8e, 0xcd, 0x10, 0xff, 0x00, 0xc7, 0x6b, 0xc7, 0xff, 0x00, 0x5a, 0xb1, 0x75, 0xbf, 0xdc, 0xf2, 0xfa, 0xd2, 0xf3, 0x92, 0x85, 0x35, 0xff, 0x00, 0x93, 0xc9, 0x3f, 0xc1, 0x1e, 0xd7, 0xfa, 0xa7, 0x83, 0xa3, 0xfe, 0xfb, 0x98, 0xd1, 0x87, 0x94, 0x5c, 0xea, 0xbf, 0xfc, 0x92, 0x0d, 0x7d, 0xcd, 0x9f, 0x4b, 0x51, 0x5f, 0x34, 0xff, 0x00, 0xc3, 0x0f, 0xfc, 0x42, 0xff, 0x00, 0xa2, 0xf5, 0xe3, 0x2f, 0xfb, 0xe6, 0xe7, 0xff, 0x00, 0x92, 0xe8, 0xff, 0x00, 0x86, 0x1f, 0xf8, 0x85, 0xff, 0x00, 0x45, 0xeb, 0xc6, 0x5f, 0xf7, 0xcd, 0xcf, 0xff, 0x00, 0x25, 0xd1, 0xfd, 0xbd, 0x9d, 0x7f, 0xd0, 0xb2, 0x7f, 0xf8, 0x36, 0x8f, 0xff, 0x00, 0x26, 0x1f, 0xea, 0xf6, 0x47, 0xff, 0x00, 0x43, 0x58, 0x7f, 0xe0, 0xaa, 0xdf, 0xfc, 0x81, 0xf4, 0xb5, 0x15, 0xf3, 0x2d, 0xd7, 0xec, 0x59, 0xf1, 0x33, 0x4e, 0xb7, 0x69, 0xec, 0x3e, 0x3a, 0x78, 0xa2, 0xe6, 0xf2, 0x21, 0xba, 0x18, 0xae, 0x7e, 0xd2, 0xb0, 0xc8, 0xdd, 0x83, 0x1f, 0xb4, 0x3e, 0x07, 0xfc, 0x05, 0xbe, 0x95, 0xd3, 0x7e, 0xca, 0x3f, 0xb4, 0x5e, 0xbb, 0xe3, 0x0f, 0x13, 0x6a, 0xde, 0x01, 0xf1, 0xd5, 0x9b, 0x5a, 0x78, 0xdf, 0xc3, 0xb1, 0x99, 0x65, 0x94, 0x22, 0xaa, 0x5e, 0xc4, 0x0a, 0x8d, 0xf8, 0x5f, 0x94, 0x37, 0xce, 0x87, 0xe5, 0xe1, 0x95, 0x83, 0x0e, 0xf5, 0xb6, 0x17, 0x89, 0xea, 0xfd, 0x6a, 0x18, 0x4c, 0xcb, 0x0d, 0x3c, 0x3c, 0xaa, 0x69, 0x06, 0xdc, 0x65, 0x19, 0x35, 0xaf, 0x2f, 0x34, 0x1b, 0x4a, 0x56, 0xd5, 0x27, 0x6b, 0xd9, 0xd8, 0xc7, 0x19, 0xc2, 0xb4, 0xbe, 0xa9, 0x53, 0x19, 0x96, 0x62, 0xa1, 0x88, 0x8d, 0x3d, 0x66, 0xa2, 0xa7, 0x19, 0x45, 0x3d, 0x39, 0xb9, 0x67, 0x14, 0xdc, 0x6f, 0x64, 0xda, 0xbd, 0xae, 0xae, 0x7b, 0xa5, 0x14, 0x56, 0x5f, 0x8e, 0x3c, 0x4f, 0x1f, 0x82, 0x7c, 0x15, 0xac, 0x6b, 0x33, 0x2e, 0xe8, 0xb4, 0x9b, 0x19, 0xaf, 0x5c, 0x7a, 0xac, 0x71, 0xb3, 0x9f, 0xfd, 0x06, 0xbe, 0xa2, 0xa5, 0x48, 0xd3, 0x83, 0xa9, 0x3d, 0x12, 0x57, 0x7e, 0x88, 0xf9, 0x3a, 0x54, 0xe5, 0x52, 0x6a, 0x9c, 0x15, 0xdb, 0x69, 0x2f, 0x56, 0x7c, 0xef, 0xa6, 0x0f, 0xf8, 0x5d, 0x9f, 0xf0, 0x51, 0x9b, 0xc9, 0xa4, 0x3e, 0x6e, 0x97, 0xf0, 0xe7, 0x4d, 0xf2, 0xe2, 0xfe, 0xe1, 0x9c, 0x80, 0x0e, 0x7f, 0xda, 0x0f, 0x33, 0xff, 0x00, 0xdf, 0x91, 0xe9, 0x5f, 0x4e, 0x57, 0xce, 0xbf, 0xf0, 0x4d, 0xef, 0x08, 0x48, 0x9f, 0x09, 0xf5, 0x4f, 0x18, 0x5f, 0x6e, 0x9f, 0x57, 0xf1, 0x96, 0xa5, 0x2d, 0xc4, 0xd7, 0x2e, 0x72, 0xd2, 0xc7, 0x1b, 0xb2, 0xff, 0x00, 0xe8, 0xc3, 0x31, 0x3e, 0xb9, 0xf6, 0xaf, 0xa2, 0xab, 0xe4, 0xf8, 0x1e, 0x9c, 0xe5, 0x97, 0x3c, 0x7d, 0x55, 0x69, 0x62, 0x65, 0x2a, 0xaf, 0xc9, 0x49, 0xfb, 0x8b, 0xe5, 0x05, 0x14, 0x7d, 0x87, 0x1e, 0x54, 0x84, 0x33, 0x25, 0x97, 0x52, 0x77, 0x86, 0x16, 0x11, 0xa4, 0xbc, 0xdc, 0x17, 0xbe, 0xfe, 0x73, 0x72, 0x61, 0x45, 0x14, 0x57, 0xd8, 0x1f, 0x16, 0x14, 0x51, 0x45, 0x00, 0x14, 0x51, 0x45, 0x00, 0x14, 0x51, 0x45, 0x00, 0x14, 0x51, 0x45, 0x00, 0x14, 0x51, 0x45, 0x00, 0x14, 0x51, 0x45, 0x00, 0x15, 0xf2, 0x7f, 0xc6, 0xfd, 0x4f, 0x54, 0xfd, 0xb6, 0x3e, 0x36, 0xff, 0x00, 0xc2, 0xb9, 0xd1, 0x6d, 0xda, 0xdb, 0xc2, 0x7e, 0x0c, 0xd4, 0x44, 0x9a, 0xf6, 0xa0, 0xfc, 0x13, 0x2a, 0x17, 0x8d, 0x95, 0x7d, 0xff, 0x00, 0xd6, 0xaa, 0x0f, 0xe2, 0x39, 0x63, 0x80, 0xb9, 0x1e, 0x89, 0xfb, 0x6f, 0xfe, 0xd1, 0x72, 0x7c, 0x11, 0xf8, 0x72, 0xba, 0x7e, 0x93, 0x34, 0x8b, 0xe2, 0xaf, 0x11, 0x66, 0xdf, 0x4e, 0x11, 0x2e, 0xe7, 0x81, 0x72, 0xa1, 0xe5, 0xc7, 0xae, 0x1b, 0x6a, 0xfa, 0xb1, 0x18, 0xce, 0xd3, 0x5b, 0x1f, 0xb2, 0x6f, 0xec, 0xed, 0x07, 0xc0, 0x0f, 0x87, 0xf8, 0xb8, 0x69, 0x6e, 0x3c, 0x49, 0xae, 0x08, 0xee, 0xb5, 0x9b, 0x89, 0x1f, 0x79, 0x69, 0xb0, 0x4f, 0x96, 0x0e, 0x4e, 0x55, 0x0b, 0xb8, 0xcf, 0x56, 0x25, 0x8f, 0x70, 0x07, 0xc1, 0x67, 0x93, 0x79, 0xce, 0x60, 0xb2, 0x1a, 0x4f, 0xf7, 0x50, 0xb4, 0xab, 0xb5, 0xd9, 0xdd, 0xc2, 0x9d, 0xfb, 0xc9, 0xab, 0xcb, 0x6f, 0x77, 0xae, 0xb6, 0x3f, 0x42, 0xc8, 0x20, 0xb2, 0x4c, 0xb9, 0xf1, 0x05, 0x55, 0xfb, 0xe9, 0xde, 0x38, 0x74, 0xfb, 0xab, 0x29, 0xd5, 0xb6, 0xd6, 0x8a, 0x76, 0x8e, 0xfe, 0xff, 0x00, 0x4d, 0x2e, 0x7a, 0x2f, 0x85, 0xfc, 0x2f, 0xa7, 0xf8, 0x2b, 0xc3, 0xf6, 0xba, 0x56, 0x93, 0x67, 0x0d, 0x86, 0x9f, 0x63, 0x18, 0x8e, 0x08, 0x21, 0x5d, 0xab, 0x1a, 0xff, 0x00, 0x89, 0xea, 0x49, 0xe4, 0x92, 0x49, 0xe6, 0xaf, 0xd1, 0x45, 0x7d, 0xdd, 0x3a, 0x71, 0x84, 0x54, 0x20, 0xac, 0x96, 0x89, 0x2d, 0x92, 0xec, 0x8f, 0x80, 0xa9, 0x52, 0x55, 0x24, 0xe7, 0x36, 0xdb, 0x7a, 0xb6, 0xf5, 0x6d, 0xbe, 0xad, 0x85, 0x14, 0x51, 0x54, 0x40, 0x56, 0x47, 0x8c, 0xbc, 0x7d, 0xa1, 0xfc, 0x3b, 0xd2, 0xbe, 0xdd, 0xaf, 0x6a, 0xda, 0x7e, 0x91, 0x6b, 0xc8, 0x59, 0x2e, 0xe7, 0x58, 0x83, 0x90, 0x33, 0xb5, 0x72, 0x7e, 0x66, 0xc0, 0xe8, 0x32, 0x4f, 0xa5, 0x6b, 0xd7, 0xca, 0x5f, 0xb4, 0xd7, 0x82, 0x2c, 0x7e, 0x2e, 0x7e, 0xdf, 0x7e, 0x00, 0xf0, 0xb6, 0xbb, 0xf6, 0x8b, 0xad, 0x0a, 0xe3, 0x44, 0x79, 0xe4, 0xb5, 0x59, 0x9a, 0x35, 0x66, 0x5f, 0xb6, 0x39, 0xe5, 0x48, 0x23, 0x71, 0x85, 0x01, 0x23, 0x04, 0x81, 0xd4, 0x70, 0x6b, 0xe7, 0xf8, 0x93, 0x37, 0xad, 0x97, 0xe1, 0x63, 0x3c, 0x34, 0x14, 0xaa, 0x4e, 0x70, 0xa7, 0x15, 0x26, 0xd4, 0x6f, 0x39, 0x28, 0xa6, 0xda, 0x4d, 0xd9, 0x75, 0xb1, 0xf4, 0x7c, 0x2f, 0x93, 0xd0, 0xcc, 0x71, 0x72, 0xa7, 0x8a, 0x9b, 0x8d, 0x3a, 0x70, 0x9d, 0x49, 0x38, 0xa4, 0xe5, 0xcb, 0x08, 0xb9, 0x34, 0x93, 0x69, 0x5d, 0xdb, 0x4b, 0xe8, 0x68, 0x6b, 0x1f, 0xb6, 0xaf, 0x8a, 0xbe, 0x35, 0xeb, 0x23, 0x47, 0xf8, 0x3f, 0xe1, 0x5b, 0xab, 0xd3, 0x96, 0x59, 0xb5, 0x6d, 0x4e, 0x0d, 0x96, 0xf0, 0x81, 0xfc, 0x4b, 0xf3, 0x6d, 0x5f, 0x51, 0xe6, 0x1c, 0x9e, 0x06, 0xc2, 0x6b, 0x53, 0xe1, 0x37, 0xec, 0x25, 0x14, 0xba, 0xec, 0x3e, 0x28, 0xf8, 0x9b, 0xab, 0x5c, 0x78, 0xcb, 0xc4, 0xcc, 0xde, 0x6b, 0x41, 0x34, 0xa6, 0x4b, 0x28, 0x0e, 0x72, 0x14, 0x86, 0x19, 0x90, 0x0f, 0x43, 0x84, 0x1d, 0x36, 0x91, 0xcd, 0x7b, 0xd7, 0x85, 0xfc, 0x2f, 0xa7, 0xf8, 0x2b, 0xc3, 0xf6, 0xba, 0x56, 0x93, 0x67, 0x0d, 0x86, 0x9f, 0x63, 0x18, 0x8e, 0x08, 0x21, 0x5d, 0xab, 0x1a, 0xff, 0x00, 0x89, 0xea, 0x49, 0xe4, 0x92, 0x49, 0xe6, 0xaf, 0xd7, 0x99, 0x87, 0xe1, 0x37, 0x5e, 0xa4, 0x71, 0x59, 0xe5, 0x57, 0x88, 0xa8, 0xb5, 0x51, 0xb5, 0xa9, 0x45, 0xe9, 0xf0, 0xc3, 0xab, 0x5f, 0xcd, 0x2b, 0xbf, 0x24, 0x7a, 0x98, 0xae, 0x30, 0x58, 0x7a, 0x72, 0xc2, 0xe4, 0x34, 0x96, 0x1e, 0x9b, 0xd1, 0xca, 0xf7, 0xab, 0x25, 0xaf, 0xc5, 0x3e, 0x89, 0xff, 0x00, 0x2c, 0x6c, 0xbc, 0xd8, 0xd8, 0x61, 0x4b, 0x68, 0x56, 0x38, 0xd1, 0x63, 0x8e, 0x35, 0x0a, 0xaa, 0xa3, 0x0a, 0xa0, 0x74, 0x00, 0x7a, 0x53, 0xa8, 0xa2, 0xbe, 0xcc, 0xf8, 0x8d, 0xf5, 0x67, 0x98, 0xfe, 0xd7, 0xbf, 0x0d, 0x74, 0x3f, 0x88, 0x1f, 0x01, 0x7c, 0x4d, 0x3e, 0xad, 0xa7, 0xc3, 0x77, 0x71, 0xa1, 0xe9, 0x57, 0x7a, 0x85, 0x84, 0xc7, 0x2b, 0x25, 0xb4, 0xd1, 0xc0, 0xcc, 0xac, 0xac, 0x30, 0x71, 0x95, 0x19, 0x5e, 0x87, 0x1c, 0x83, 0x54, 0x3f, 0x60, 0xfd, 0x4e, 0xe3, 0x56, 0xfd, 0x93, 0xbc, 0x21, 0x2d, 0xcc, 0xcf, 0x34, 0x8b, 0x15, 0xc4, 0x21, 0x98, 0xe4, 0x84, 0x8e, 0xea, 0x64, 0x45, 0xfa, 0x2a, 0xaa, 0x81, 0xec, 0x05, 0x45, 0xfb, 0x7b, 0xf8, 0xa9, 0xfc, 0x2b, 0xfb, 0x2c, 0x78, 0x94, 0xc3, 0x3b, 0x5b, 0xdc, 0x6a, 0x02, 0x1b, 0x18, 0xca, 0xf5, 0x71, 0x24, 0xa8, 0x24, 0x5f, 0xc6, 0x21, 0x20, 0xfa, 0x57, 0x51, 0xfb, 0x32, 0xf8, 0x42, 0x3f, 0x02, 0x7e, 0xcf, 0xbe, 0x0f, 0xd3, 0x63, 0x85, 0xad, 0xda, 0x3d, 0x2a, 0x09, 0xa6, 0x8d, 0x8e, 0x4a, 0xcd, 0x2a, 0x89, 0x65, 0xff, 0x00, 0xc8, 0x8e, 0xe6, 0xbe, 0x26, 0x14, 0xe0, 0xf8, 0xb6, 0x53, 0xa6, 0x92, 0x71, 0xc3, 0xfb, 0xcd, 0x75, 0x72, 0xa8, 0xb9, 0x6f, 0xdd, 0xa5, 0x07, 0xbe, 0xc9, 0xe8, 0x7d, 0xd5, 0x4a, 0x93, 0x5c, 0x1d, 0x18, 0x55, 0x93, 0x7c, 0xd8, 0x8f, 0x71, 0x3e, 0x8a, 0x34, 0xdf, 0x35, 0xbb, 0x26, 0xe7, 0x1d, 0xb7, 0x69, 0xdc, 0xf9, 0xc7, 0xf6, 0x6e, 0xf8, 0x3f, 0x0f, 0xed, 0xbf, 0xa9, 0x6b, 0x3e, 0x3e, 0xf1, 0xf6, 0xa5, 0xa9, 0x6a, 0x56, 0xb6, 0xda, 0xac, 0x96, 0x76, 0x5a, 0x42, 0x4e, 0xd1, 0xdb, 0xc0, 0xa1, 0x12, 0x4d, 0xb9, 0x1c, 0x84, 0x02, 0x45, 0x00, 0x21, 0x52, 0x4a, 0x92, 0x49, 0x26, 0xbe, 0xb1, 0xf0, 0x67, 0x80, 0x74, 0x4f, 0x87, 0x5a, 0x4a, 0xd8, 0xe8, 0x3a, 0x4d, 0x86, 0x93, 0x68, 0x31, 0x98, 0xed, 0x61, 0x58, 0xc3, 0x11, 0xdd, 0xb1, 0xcb, 0x1f, 0x73, 0x93, 0x5f, 0x3d, 0x7f, 0xc1, 0x2f, 0xef, 0x63, 0xd2, 0xfe, 0x19, 0x78, 0xab, 0xc3, 0xb7, 0x04, 0xc3, 0xac, 0xe9, 0x3a, 0xf4, 0x92, 0x5d, 0x5a, 0xb8, 0xc3, 0xc2, 0x1a, 0x28, 0xa3, 0x19, 0xff, 0x00, 0x81, 0xc3, 0x20, 0xff, 0x00, 0x80, 0xd7, 0xd3, 0x95, 0xcf, 0xe1, 0xee, 0x07, 0x0c, 0xf2, 0x9a, 0x59, 0x87, 0x22, 0x75, 0xea, 0x26, 0xe7, 0x37, 0xac, 0x9c, 0xae, 0xd3, 0xbb, 0x7a, 0xe8, 0xd5, 0xad, 0xb2, 0xec, 0x75, 0x78, 0x91, 0x98, 0x62, 0x96, 0x6f, 0x5b, 0x2d, 0x53, 0x6a, 0x85, 0x26, 0x94, 0x20, 0xb4, 0x82, 0x8d, 0x93, 0x56, 0x8a, 0xd3, 0x54, 0xef, 0x7d, 0xde, 0xf7, 0x0a, 0x28, 0xa2, 0xbe, 0xf8, 0xfc, 0xec, 0x28, 0xa2, 0x8a, 0x00, 0x2b, 0xe6, 0x8f, 0xdb, 0x97, 0xc0, 0x77, 0xbf, 0x0d, 0xf5, 0xad, 0x2f, 0xe3, 0x1f, 0x86, 0x64, 0x36, 0xfa, 0xb7, 0x87, 0x65, 0x86, 0x0d, 0x4e, 0x3d, 0xdb, 0x52, 0xee, 0xdd, 0x9f, 0x62, 0xee, 0x1d, 0xf2, 0x5c, 0x46, 0xc3, 0xba, 0xb8, 0xe9, 0xb6, 0xbe, 0x97, 0xaf, 0x98, 0x7f, 0x6d, 0x7f, 0x8d, 0x30, 0xfc, 0x50, 0xb4, 0x6f, 0x84, 0x7e, 0x0f, 0xb7, 0x1e, 0x22, 0xf1, 0x16, 0xbb, 0x34, 0x4b, 0x78, 0xd6, 0xee, 0x1a, 0x2b, 0x01, 0x1c, 0xab, 0x2e, 0x19, 0x87, 0x1b, 0xb2, 0x83, 0x76, 0x78, 0x45, 0xce, 0x79, 0xe2, 0xbe, 0x33, 0x8f, 0x65, 0x86, 0x59, 0x3d, 0x45, 0x59, 0xda, 0xa6, 0xf4, 0xad, 0xf1, 0x7b, 0x55, 0xad, 0x3e, 0x5b, 0x6a, 0xdf, 0x35, 0xb6, 0xe9, 0x7b, 0xe9, 0x73, 0xed, 0xfc, 0x3d, 0x8e, 0x29, 0xe7, 0x54, 0xdd, 0x15, 0x7a, 0x7b, 0x55, 0xbf, 0xc3, 0xec, 0x5e, 0x95, 0x39, 0xdb, 0xd1, 0x2e, 0x5b, 0xef, 0xd6, 0xd6, 0xd6, 0xc7, 0xd1, 0x1e, 0x03, 0xf1, 0x5c, 0x7e, 0x3c, 0xf0, 0x3e, 0x8b, 0xae, 0x43, 0x13, 0xc1, 0x0e, 0xb5, 0x63, 0x05, 0xf2, 0x46, 0xe7, 0x2d, 0x1a, 0xcb, 0x1a, 0xb8, 0x52, 0x7d, 0x40, 0x6c, 0x57, 0x0b, 0xfb, 0x68, 0x78, 0xa6, 0x5f, 0x07, 0xfe, 0xcb, 0x9e, 0x32, 0xbb, 0x85, 0x55, 0xda, 0x6b, 0x11, 0x64, 0x41, 0xfe, 0xed, 0xc4, 0x89, 0x6e, 0xc7, 0xf0, 0x59, 0x49, 0xfc, 0x2b, 0xb3, 0xf8, 0x5d, 0xe1, 0x49, 0xbc, 0x09, 0xf0, 0xcf, 0xc3, 0xba, 0x1d, 0xc4, 0x91, 0xcd, 0x3e, 0x8d, 0xa6, 0x5b, 0x58, 0xc9, 0x24, 0x79, 0xdb, 0x23, 0x45, 0x12, 0xa1, 0x23, 0x3c, 0xe0, 0x95, 0xcf, 0x35, 0xe1, 0x9f, 0xf0, 0x53, 0xbd, 0x62, 0x68, 0x7e, 0x05, 0xe9, 0x3a, 0x55, 0xac, 0x8d, 0xf6, 0x9d, 0x67, 0x5b, 0x86, 0x2f, 0xb3, 0xaf, 0xde, 0xb8, 0x45, 0x8e, 0x46, 0xc0, 0x1d, 0xf1, 0x27, 0x95, 0xf8, 0xe2, 0xb6, 0xe2, 0x6c, 0x6d, 0x6c, 0x37, 0x0e, 0x57, 0xaf, 0x57, 0x4a, 0x9e, 0xc9, 0xaf, 0xfb, 0x7a, 0x51, 0xb7, 0xfe, 0x94, 0xcc, 0x38, 0x5b, 0x03, 0x47, 0x13, 0xc4, 0xd8, 0x7c, 0x3d, 0x2d, 0x69, 0xfb, 0x54, 0xd7, 0x9c, 0x63, 0x2e, 0x6f, 0xc6, 0x28, 0xf4, 0x8f, 0xd8, 0xff, 0x00, 0xc2, 0xcb, 0xe0, 0xef, 0xd9, 0x93, 0xc1, 0x76, 0x69, 0x21, 0x91, 0x66, 0xd3, 0x52, 0xfb, 0x27, 0xb1, 0xb8, 0x26, 0xe0, 0x8f, 0xc0, 0xca, 0x47, 0xe1, 0x5e, 0x91, 0x55, 0x74, 0x3d, 0x1a, 0xdf, 0xc3, 0x9a, 0x2d, 0x9e, 0x9f, 0x67, 0x1f, 0x95, 0x6b, 0x61, 0x02, 0x5b, 0xc2, 0x83, 0xf8, 0x11, 0x14, 0x2a, 0x8f, 0xc0, 0x01, 0x56, 0xab, 0xdf, 0xcb, 0x30, 0x6b, 0x09, 0x83, 0xa5, 0x85, 0x5f, 0x62, 0x31, 0x8f, 0xfe, 0x02, 0x92, 0xfd, 0x0f, 0x9d, 0xcd, 0x31, 0x8f, 0x19, 0x8d, 0xad, 0x8b, 0x7b, 0xd4, 0x94, 0xa5, 0xff, 0x00, 0x81, 0x36, 0xff, 0x00, 0x50, 0xa2, 0x8a, 0x2b, 0xb8, 0xe1, 0x0a, 0x28, 0xa2, 0x80, 0x0a, 0x28, 0xa2, 0x80, 0x0a, 0x28, 0xa2, 0x80, 0x0a, 0x28, 0xa2, 0x80, 0x0a, 0x28, 0xa2, 0x80, 0x0a, 0x28, 0xa2, 0x80, 0x3e, 0x5f, 0x87, 0x4f, 0x6f, 0x89, 0xff, 0x00, 0xf0, 0x53, 0xcb, 0xc5, 0xd4, 0x1a, 0x33, 0x6f, 0xe0, 0x3d, 0x15, 0x26, 0xb3, 0x88, 0xc4, 0x18, 0x49, 0x98, 0xa2, 0x23, 0x76, 0x7b, 0xac, 0x97, 0x8c, 0xe1, 0xba, 0x82, 0x8b, 0xf5, 0xaf, 0xa8, 0x2b, 0xe6, 0x9f, 0x86, 0x1f, 0xf2, 0x93, 0xbf, 0x88, 0xdf, 0xf6, 0x2f, 0x43, 0xff, 0x00, 0xa2, 0xf4, 0xea, 0xfa, 0x5a, 0xbe, 0x33, 0x82, 0xe2, 0xb9, 0x31, 0x95, 0x3a, 0xcb, 0x11, 0x5a, 0xef, 0xd2, 0x5c, 0xab, 0xee, 0x49, 0x25, 0xe8, 0x7d, 0xbf, 0x1c, 0x49, 0xf3, 0xe0, 0xa9, 0xfd, 0x98, 0xe1, 0xa8, 0xd9, 0x76, 0xbc, 0x79, 0x9f, 0xdf, 0x26, 0xdb, 0xf5, 0x0a, 0x28, 0xa2, 0xbe, 0xcc, 0xf8, 0x80, 0xa2, 0x8a, 0x28, 0x03, 0xcf, 0xff, 0x00, 0x69, 0x0f, 0xda, 0x06, 0xcb, 0xf6, 0x6f, 0xf0, 0x25, 0xb6, 0xbb, 0x7d, 0x61, 0x75, 0xa8, 0xc7, 0x75, 0x7f, 0x1d, 0x8a, 0xc5, 0x03, 0x85, 0x60, 0x59, 0x5d, 0xcb, 0x64, 0xfa, 0x2c, 0x6d, 0xc7, 0x73, 0x81, 0xc6, 0x72, 0x39, 0x6f, 0xda, 0x93, 0xf6, 0x63, 0xd4, 0xfe, 0x30, 0x78, 0x83, 0xc3, 0xfe, 0x2a, 0xf0, 0x9e, 0xb1, 0x6b, 0xa1, 0x78, 0xbb, 0xc3, 0x87, 0xfd, 0x1e, 0xe6, 0x65, 0x26, 0x39, 0xd3, 0x76, 0xe5, 0x56, 0x20, 0x36, 0x36, 0xb1, 0x62, 0x06, 0xd6, 0x04, 0x3b, 0x02, 0x30, 0x6b, 0x57, 0xf6, 0xd2, 0xf8, 0x69, 0x79, 0xf1, 0x5b, 0xf6, 0x73, 0xd7, 0xb4, 0xdd, 0x36, 0xcf, 0xed, 0xda, 0xa4, 0x3e, 0x55, 0xdd, 0x9c, 0x43, 0xef, 0x96, 0x8e, 0x45, 0x66, 0xdb, 0xea, 0xc6, 0x3f, 0x30, 0x01, 0xdc, 0xb6, 0x3b, 0xd1, 0xfb, 0x1c, 0xfc, 0x63, 0xb5, 0xf8, 0xc1, 0xf0, 0x3f, 0x4a, 0x78, 0xcd, 0xc0, 0xd4, 0xb4, 0x28, 0x62, 0xd2, 0xb5, 0x24, 0x9f, 0xfd, 0x67, 0x9f, 0x14, 0x6a, 0x0b, 0xfd, 0x1f, 0xef, 0x7e, 0x24, 0x75, 0x06, 0xbe, 0x1f, 0x32, 0xe4, 0xc6, 0xe6, 0xb5, 0x32, 0x4c, 0xc7, 0xf8, 0x55, 0x29, 0xc2, 0x74, 0xed, 0xee, 0xb5, 0x28, 0x49, 0xf3, 0x72, 0xc9, 0x6b, 0xcc, 0xbd, 0xd9, 0x68, 0xf4, 0x5d, 0x2c, 0xd9, 0xf7, 0x99, 0x67, 0x3e, 0x07, 0x29, 0xa5, 0x9e, 0xe5, 0xbf, 0xc5, 0xa7, 0x52, 0x70, 0xab, 0x7b, 0x49, 0x38, 0xce, 0x31, 0xe4, 0xe6, 0x8b, 0xba, 0xe5, 0x7e, 0xfc, 0x75, 0x5a, 0xbe, 0xb7, 0x48, 0xf3, 0x9b, 0x6f, 0x1b, 0xfe, 0xd4, 0x1a, 0x04, 0x5f, 0x63, 0x6f, 0x07, 0xf8, 0x47, 0x5b, 0x6b, 0x72, 0x57, 0xed, 0xcf, 0x34, 0x48, 0x6e, 0x7f, 0xda, 0xc2, 0xdc, 0xc6, 0x07, 0xfd, 0xf0, 0xbf, 0x4a, 0x93, 0xfe, 0x17, 0xd7, 0xed, 0x05, 0xe1, 0x63, 0xe6, 0xeb, 0x5f, 0x0a, 0xb4, 0xbb, 0xf8, 0x7b, 0x2e, 0x99, 0x3e, 0xe9, 0x3f, 0xf1, 0xc9, 0xa6, 0x3f, 0xa5, 0x7d, 0x2d, 0x45, 0x6c, 0xb8, 0x4f, 0x11, 0x05, 0xfb, 0xac, 0xc7, 0x10, 0x9a, 0xda, 0xf2, 0x84, 0x97, 0xcd, 0x3a, 0x7a, 0xfc, 0xd9, 0x8b, 0xe3, 0x0c, 0x34, 0xdf, 0xef, 0xb2, 0xdc, 0x3b, 0x4f, 0x7b, 0x46, 0xa4, 0x5f, 0xc9, 0xaa, 0x9a, 0x7c, 0x95, 0x8f, 0x9a, 0x5b, 0xf6, 0xe8, 0xf1, 0xcd, 0xa0, 0xf3, 0x2e, 0xbe, 0x05, 0xf8, 0xca, 0xde, 0xd9, 0x79, 0x92, 0x42, 0xd7, 0x1f, 0x20, 0xf5, 0xe6, 0xd4, 0x0f, 0xcc, 0x8a, 0x17, 0xfe, 0x0a, 0x8d, 0xe0, 0xab, 0x31, 0xe5, 0x6a, 0x1e, 0x1d, 0xf1, 0x95, 0x9d, 0xe2, 0x71, 0x2c, 0x22, 0xda, 0x06, 0xf2, 0xcf, 0xa6, 0x5a, 0x65, 0x3f, 0x98, 0x15, 0xf4, 0xb5, 0x66, 0x78, 0xcf, 0xc5, 0xf6, 0x1e, 0x00, 0xf0, 0xa6, 0xa1, 0xad, 0x6a, 0x93, 0x7d, 0x9f, 0x4f, 0xd2, 0xe0, 0x6b, 0x89, 0xdf, 0xa9, 0x0a, 0xa3, 0x38, 0x03, 0xb9, 0x3d, 0x00, 0xee, 0x48, 0x15, 0x35, 0x32, 0x9c, 0xf2, 0x8c, 0x1d, 0x4f, 0xed, 0x3d, 0x12, 0xbb, 0x73, 0xa3, 0x06, 0x92, 0x5d, 0x7d, 0xd7, 0x0b, 0x7c, 0xee, 0x5d, 0x2c, 0xe3, 0x21, 0xaf, 0x35, 0x4f, 0xfb, 0x2f, 0xde, 0x6d, 0x24, 0xa1, 0x5a, 0xa2, 0x6d, 0xbd, 0x97, 0xbc, 0xa7, 0x7f, 0x95, 0x8f, 0x91, 0xbe, 0x31, 0x7c, 0x76, 0xd1, 0xff, 0x00, 0x6e, 0x1f, 0x1d, 0x7c, 0x39, 0xf0, 0x6f, 0x87, 0x57, 0x51, 0x8f, 0x4d, 0xb9, 0xd4, 0xda, 0xef, 0x56, 0x86, 0xea, 0x21, 0x1c, 0x88, 0xb1, 0x8f, 0xf6, 0x59, 0x97, 0x88, 0xbc, 0xe3, 0x90, 0xc4, 0x7c, 0xc3, 0xa1, 0xaf, 0xb2, 0xd1, 0x16, 0x24, 0x55, 0x55, 0x0a, 0xaa, 0x30, 0x00, 0x18, 0x00, 0x57, 0xc5, 0x1f, 0x03, 0x3f, 0x64, 0x7b, 0x0f, 0xda, 0xee, 0xf3, 0xc4, 0x5e, 0x3d, 0xf1, 0x24, 0x17, 0x9e, 0x1b, 0xd2, 0x75, 0xab, 0xe6, 0x6d, 0x26, 0xcf, 0x49, 0x11, 0x5b, 0xe5, 0x14, 0x90, 0xcc, 0x41, 0x8d, 0x94, 0x8e, 0x00, 0xc8, 0x00, 0xb3, 0x07, 0x63, 0xd7, 0x9e, 0xea, 0xf3, 0xf6, 0x09, 0xf1, 0x47, 0x80, 0x20, 0x91, 0xbe, 0x1e, 0x7c, 0x52, 0xf1, 0x0e, 0x91, 0x1c, 0x24, 0x49, 0x6f, 0xa7, 0xde, 0x4a, 0xe2, 0x09, 0x1c, 0x1f, 0xe3, 0x78, 0x88, 0x5c, 0x75, 0xff, 0x00, 0x96, 0x2d, 0xe9, 0x8a, 0xf9, 0x3e, 0x17, 0xc7, 0xe7, 0xb0, 0x8d, 0x6c, 0xde, 0xae, 0x13, 0xdb, 0xfb, 0x76, 0x9a, 0x94, 0x65, 0x18, 0x49, 0xc2, 0x0b, 0x96, 0x16, 0xa7, 0x2d, 0x93, 0xd6, 0x5f, 0x15, 0xdf, 0x36, 0x88, 0xfa, 0xee, 0x2b, 0xcb, 0xf2, 0x09, 0xca, 0x8e, 0x4f, 0x47, 0x19, 0xec, 0x1e, 0x1d, 0x34, 0xe1, 0x28, 0x4a, 0x71, 0x53, 0x9b, 0xe6, 0x9d, 0xea, 0x47, 0x76, 0xb4, 0x87, 0xc1, 0x65, 0xcb, 0xab, 0x29, 0x7e, 0xd3, 0x7e, 0x14, 0xf1, 0x17, 0xec, 0xc5, 0xf1, 0xa4, 0xfc, 0x5c, 0xf0, 0x85, 0x9a, 0xdd, 0xe9, 0x37, 0xd1, 0x79, 0x5a, 0xfd, 0x91, 0x62, 0x23, 0x67, 0x6f, 0x94, 0xbb, 0x05, 0xc1, 0x0a, 0xdf, 0x23, 0x6e, 0x19, 0xdb, 0x22, 0xe4, 0xe4, 0x36, 0x0f, 0xd0, 0xbf, 0x09, 0xbe, 0x2f, 0x68, 0x3f, 0x1b, 0x7c, 0x22, 0x9a, 0xdf, 0x87, 0x6f, 0x0d, 0xe5, 0x8b, 0x48, 0x61, 0x7d, 0xd1, 0x98, 0xde, 0x19, 0x00, 0x05, 0x91, 0x94, 0xf4, 0x60, 0x18, 0x7a, 0x8e, 0x41, 0x04, 0x8e, 0x6b, 0xc0, 0xef, 0xbe, 0x26, 0x7c, 0x76, 0xfd, 0x9f, 0x67, 0x69, 0x3c, 0x69, 0xa2, 0xe9, 0xff, 0x00, 0x11, 0x7c, 0x3d, 0x32, 0xe2, 0x7b, 0x8d, 0x2a, 0x20, 0x24, 0x80, 0x77, 0xe1, 0x23, 0x52, 0x00, 0x1d, 0x77, 0xc5, 0xb4, 0xf4, 0xdc, 0x2b, 0xc3, 0x7c, 0x09, 0xfb, 0x55, 0xe9, 0x1f, 0x01, 0x7e, 0x36, 0xcd, 0xaa, 0x78, 0x26, 0x1d, 0x72, 0x2f, 0x06, 0xeb, 0x12, 0x2b, 0xea, 0x9a, 0x1d, 0xfc, 0x71, 0xa9, 0x80, 0x93, 0xf3, 0x79, 0x25, 0x64, 0x60, 0x4a, 0xf3, 0xb4, 0xb6, 0xd3, 0x8f, 0x94, 0xe4, 0x73, 0x5c, 0xb1, 0xe2, 0xec, 0x26, 0x49, 0x98, 0xba, 0x8f, 0x9e, 0x9d, 0x1a, 0xd2, 0xbc, 0xe9, 0x54, 0x8b, 0x8c, 0xe9, 0xc9, 0xff, 0x00, 0xcb, 0xc8, 0x59, 0xb8, 0xca, 0x12, 0x7f, 0x1a, 0x4d, 0xb4, 0xf5, 0x5b, 0xb4, 0x76, 0x4b, 0x83, 0xb1, 0x79, 0xee, 0x5a, 0xa9, 0xae, 0x4a, 0xb5, 0xa8, 0xc6, 0xd4, 0xeb, 0x53, 0x9a, 0x94, 0x2a, 0x45, 0x7f, 0xcb, 0xb9, 0xdd, 0x29, 0x46, 0x71, 0x5f, 0x03, 0x92, 0x8a, 0x6b, 0x47, 0xb2, 0x67, 0xe8, 0xa5, 0x15, 0xf3, 0x48, 0xff, 0x00, 0x82, 0xa7, 0xfc, 0x3d, 0xff, 0x00, 0xa0, 0x3f, 0x8c, 0xbf, 0xf0, 0x12, 0xdb, 0xff, 0x00, 0x8f, 0xd4, 0x37, 0x3f, 0xb7, 0x6f, 0x8a, 0x7e, 0x26, 0x8f, 0xb2, 0xfc, 0x37, 0xf8, 0x6b, 0xad, 0xea, 0x33, 0x4e, 0x71, 0x15, 0xee, 0xa2, 0x85, 0x6d, 0xd0, 0x7a, 0xb0, 0x43, 0xb0, 0x7d, 0x4c, 0xa0, 0x7d, 0x6b, 0xee, 0x1f, 0x88, 0x19, 0x0b, 0x56, 0xa3, 0x5f, 0xda, 0x4b, 0xa4, 0x61, 0x19, 0x4a, 0x4f, 0xd1, 0x24, 0xd9, 0xf0, 0x51, 0xf0, 0xeb, 0x88, 0x13, 0xbd, 0x6c, 0x3f, 0xb3, 0x8f, 0x59, 0x4e, 0x51, 0x84, 0x57, 0x9b, 0x72, 0x69, 0x7e, 0xa7, 0xd3, 0x53, 0x4c, 0xb6, 0xf0, 0xb4, 0x92, 0x32, 0xc7, 0x1c, 0x60, 0xb3, 0x33, 0x1c, 0x2a, 0x81, 0xd4, 0x93, 0x5e, 0x33, 0xf1, 0x5b, 0xf6, 0xf3, 0xf8, 0x7f, 0xf0, 0xce, 0x46, 0xb5, 0xb7, 0xd4, 0x24, 0xf1, 0x2e, 0xa9, 0x9d, 0x8b, 0x6b, 0xa4, 0x81, 0x30, 0xdd, 0xd0, 0x03, 0x2e, 0x76, 0x75, 0xe3, 0x00, 0xb1, 0x1e, 0x95, 0xc3, 0xc3, 0xfb, 0x21, 0x7c, 0x45, 0xf8, 0xf1, 0x32, 0xdd, 0x7c, 0x54, 0xf1, 0xc5, 0xc4, 0x36, 0x2c, 0x43, 0x7f, 0x62, 0xe9, 0x24, 0x08, 0xd4, 0x7a, 0x12, 0x00, 0x8c, 0x11, 0xeb, 0xb6, 0x43, 0xfe, 0xd5, 0x7b, 0x37, 0xc2, 0x9f, 0xd9, 0xaf, 0xc1, 0x3f, 0x05, 0xa2, 0x53, 0xa0, 0x68, 0x36, 0x76, 0xf7, 0x4a, 0x30, 0x6f, 0x25, 0x1e, 0x75, 0xd3, 0x7a, 0xfe, 0xf1, 0xb2, 0xc3, 0x3e, 0x8b, 0x81, 0xed, 0x59, 0xfd, 0x7f, 0x3f, 0xcc, 0x74, 0xc1, 0xd1, 0x58, 0x6a, 0x6f, 0xed, 0x55, 0xf7, 0xa7, 0x6f, 0x2a, 0x71, 0x76, 0x4f, 0xfc, 0x52, 0xf9, 0x1a, 0x7f, 0x67, 0xf0, 0xee, 0x5b, 0xae, 0x36, 0xbb, 0xc5, 0x54, 0x5f, 0x62, 0x97, 0xbb, 0x4e, 0xfd, 0x9d, 0x59, 0x2b, 0xb5, 0xfe, 0x08, 0xfc, 0xcf, 0x11, 0xbd, 0xd6, 0x3e, 0x38, 0x7e, 0xd5, 0xf0, 0xfd, 0x92, 0xd7, 0x4d, 0x4f, 0x86, 0x7e, 0x13, 0xbc, 0x38, 0x96, 0xe2, 0x66, 0x61, 0x7b, 0x2c, 0x47, 0xa8, 0xe7, 0x12, 0x36, 0x47, 0xf7, 0x56, 0x30, 0x73, 0x82, 0xd8, 0x26, 0xbd, 0x9b, 0xe0, 0x1f, 0xec, 0xcd, 0xe1, 0x7f, 0xd9, 0xe3, 0x46, 0x68, 0x74, 0x5b, 0x53, 0x36, 0xa1, 0x70, 0x81, 0x6e, 0xb5, 0x1b, 0x8c, 0x35, 0xc5, 0xcf, 0x7c, 0x67, 0xf8, 0x57, 0x3f, 0xc2, 0xb8, 0x1c, 0x0c, 0xe4, 0xf3, 0x5e, 0x85, 0x45, 0x7a, 0x19, 0x67, 0x0b, 0xd0, 0xc3, 0x57, 0xfa, 0xee, 0x2a, 0x72, 0xaf, 0x5f, 0xf9, 0xe7, 0x67, 0xcb, 0xdd, 0x42, 0x29, 0x28, 0xc1, 0x7a, 0x2b, 0xf7, 0x6c, 0xf3, 0xf3, 0x4e, 0x2c, 0xaf, 0x89, 0xc3, 0xfd, 0x47, 0x0b, 0x4e, 0x38, 0x7c, 0x3e, 0xfc, 0x90, 0xba, 0xe6, 0xec, 0xe7, 0x26, 0xdc, 0xa6, 0xff, 0x00, 0xc4, 0xed, 0xd9, 0x20, 0xaf, 0x99, 0x3f, 0x6d, 0x1b, 0x88, 0xf5, 0xdf, 0xda, 0x77, 0xe0, 0x86, 0x8f, 0x6e, 0x0d, 0xcd, 0xe5, 0xb6, 0xaf, 0xf6, 0xcb, 0x8b, 0x75, 0x5d, 0xdb, 0x61, 0x37, 0x16, 0xdf, 0x39, 0x1e, 0x98, 0x86, 0x53, 0xf4, 0x43, 0x5f, 0x4d, 0xd7, 0xcd, 0x3f, 0x13, 0xff, 0x00, 0xe5, 0x27, 0x7f, 0x0e, 0x7f, 0xec, 0x5e, 0x9b, 0xff, 0x00, 0x45, 0xea, 0x35, 0xc7, 0xc7, 0x3e, 0xfe, 0x02, 0x96, 0x1b, 0xa5, 0x5a, 0xd4, 0x62, 0xdf, 0x64, 0xea, 0x45, 0xdd, 0x7d, 0xc7, 0x67, 0x00, 0xfb, 0x99, 0x85, 0x5c, 0x57, 0x5a, 0x54, 0x6b, 0xcd, 0x2e, 0xed, 0x52, 0x92, 0xb3, 0xfb, 0xcf, 0xa5, 0xa8, 0xa2, 0x8a, 0xfb, 0x23, 0xe2, 0x42, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x02, 0x8a, 0x28, 0xa0, 0x0f, 0x95, 0xbf, 0x68, 0x69, 0xee, 0x3f, 0x66, 0x7f, 0xdb, 0x13, 0x47, 0xf8, 0x9c, 0xd6, 0xda, 0x83, 0x78, 0x5b, 0x5e, 0xb4, 0x1a, 0x7e, 0xb5, 0x2c, 0x1f, 0x3f, 0xef, 0x36, 0x18, 0xc2, 0x91, 0xd8, 0x05, 0x4b, 0x77, 0x03, 0xf8, 0x8c, 0x4d, 0x8a, 0xf6, 0xfd, 0x2b, 0xf6, 0x9e, 0xf8, 0x73, 0xac, 0xe9, 0xd0, 0xdd, 0x43, 0xe3, 0x8f, 0x0a, 0xa4, 0x73, 0x2e, 0xe5, 0x59, 0xf5, 0x38, 0xa0, 0x90, 0x0f, 0xf6, 0x92, 0x46, 0x56, 0x53, 0xec, 0xc0, 0x1a, 0xec, 0x35, 0xbd, 0x0a, 0xc7, 0xc4, 0xda, 0x54, 0xd6, 0x3a, 0x95, 0x9d, 0xae, 0xa1, 0x63, 0x70, 0xbb, 0x65, 0xb7, 0xb9, 0x89, 0x65, 0x8a, 0x51, 0xd7, 0x0c, 0xac, 0x08, 0x3f, 0x8d, 0x79, 0x3c, 0xff, 0x00, 0xb0, 0x27, 0xc2, 0x4b, 0x89, 0x9e, 0x46, 0xf0, 0x8a, 0x86, 0x91, 0x8b, 0x10, 0xba, 0x95, 0xe2, 0xa8, 0x27, 0xd0, 0x09, 0x70, 0x07, 0xb0, 0xe2, 0xbe, 0x23, 0xfb, 0x27, 0x38, 0xcb, 0xf1, 0x55, 0xa7, 0x94, 0x3a, 0x72, 0xa5, 0x5a, 0x4e, 0x6e, 0x35, 0x1c, 0xa2, 0xe3, 0x37, 0x6e, 0x6e, 0x57, 0x15, 0x2b, 0xa9, 0x5a, 0xf6, 0x69, 0x59, 0xdf, 0x5d, 0x59, 0xf7, 0x9f, 0xdb, 0x19, 0x2e, 0x63, 0x85, 0xa1, 0x0c, 0xe5, 0x55, 0x8d, 0x5a, 0x31, 0x54, 0xd4, 0xa9, 0xa8, 0xc9, 0x4a, 0x0a, 0xfc, 0xbc, 0xca, 0x4e, 0x36, 0x71, 0xbd, 0x93, 0x4d, 0xdd, 0x5b, 0x4d, 0x11, 0xd6, 0x5e, 0xfe, 0xd2, 0xdf, 0x0e, 0xec, 0x2d, 0x64, 0x9a, 0x4f, 0x1d, 0x78, 0x45, 0x92, 0x35, 0xdc, 0x44, 0x7a, 0xb4, 0x12, 0x31, 0xfa, 0x2a, 0xb1, 0x62, 0x7d, 0x80, 0x26, 0xbc, 0xf7, 0xc5, 0x9f, 0xf0, 0x52, 0x0f, 0x85, 0xfe, 0x1b, 0x85, 0x1a, 0xd3, 0x50, 0xd5, 0x35, 0xe7, 0x66, 0x2a, 0xd1, 0xd8, 0x58, 0x3a, 0xb4, 0x7e, 0xe4, 0xcd, 0xe5, 0x82, 0x3e, 0x84, 0xd6, 0xbd, 0xb7, 0xec, 0x0d, 0xf0, 0x96, 0xd6, 0x74, 0x91, 0x7c, 0x22, 0x85, 0xa3, 0x3b, 0x80, 0x7d, 0x46, 0xed, 0xd4, 0xfd, 0x41, 0x94, 0x83, 0xf4, 0x22, 0xbb, 0xff, 0x00, 0x0a, 0x7c, 0x21, 0xf0, 0x9f, 0x81, 0x2f, 0x56, 0xe7, 0x45, 0xf0, 0xce, 0x81, 0xa4, 0xdd, 0x2a, 0x79, 0x7e, 0x7d, 0xa6, 0x9f, 0x14, 0x32, 0x95, 0xf4, 0x2e, 0xaa, 0x18, 0xe7, 0xdc, 0xf3, 0x5a, 0xba, 0x7c, 0x55, 0x5b, 0xdd, 0x94, 0xe8, 0x52, 0x5d, 0xd2, 0xa9, 0x51, 0xfc, 0x93, 0xe4, 0x5f, 0x7d, 0xfe, 0x46, 0x2a, 0xa7, 0x09, 0x51, 0xf7, 0xa3, 0x0c, 0x45, 0x67, 0xda, 0x4e, 0x9d, 0x35, 0xe8, 0xda, 0xf6, 0x8f, 0xe6, 0xad, 0xf3, 0x3e, 0x6b, 0xf1, 0x17, 0xed, 0x31, 0xf1, 0x0b, 0xf6, 0xb4, 0x95, 0x74, 0x0f, 0x86, 0xbe, 0x1c, 0xd4, 0xfc, 0x3f, 0xa0, 0x6a, 0x12, 0x34, 0x17, 0x1e, 0x20, 0xbb, 0x46, 0x05, 0x10, 0x63, 0x78, 0xf3, 0x17, 0x31, 0xc4, 0x40, 0x3c, 0xaa, 0xb3, 0xb9, 0xe3, 0x04, 0x57, 0xd1, 0x9f, 0x04, 0xbe, 0x1b, 0x49, 0xf0, 0x83, 0xe1, 0x6e, 0x93, 0xe1, 0xb9, 0xb5, 0x4b, 0x8d, 0x6a, 0x4d, 0x2e, 0x37, 0x43, 0x79, 0x32, 0xed, 0x69, 0xb7, 0x48, 0xcf, 0xd3, 0x2d, 0x80, 0x37, 0x6d, 0x03, 0x27, 0x01, 0x45, 0x75, 0x54, 0x57, 0x6e, 0x4f, 0xc3, 0xf5, 0x30, 0xb8, 0x89, 0x63, 0xb1, 0xb5, 0xe5, 0x5a, 0xb4, 0x97, 0x2f, 0x33, 0x5c, 0xb1, 0x8c, 0x6e, 0x9f, 0x2c, 0x60, 0x9d, 0x96, 0xa9, 0x36, 0xdd, 0xdf, 0x9e, 0xf7, 0xe1, 0xce, 0xb8, 0x8a, 0x9e, 0x2b, 0x0d, 0x1c, 0x06, 0x07, 0x0f, 0x1a, 0x14, 0x22, 0xf9, 0xb9, 0x53, 0xe6, 0x94, 0xa5, 0x66, 0xb9, 0xa5, 0x36, 0xae, 0xda, 0x4d, 0xa4, 0x95, 0x96, 0xbb, 0x6d, 0x62, 0xbe, 0x4f, 0xf1, 0xb9, 0xbc, 0xfd, 0x86, 0xbf, 0x68, 0xfb, 0x8f, 0x14, 0xc3, 0x05, 0xf5, 0xcf, 0xc3, 0xaf, 0x1b, 0x48, 0x4e, 0xa4, 0x91, 0x0d, 0xcb, 0x63, 0x72, 0xcc, 0xcc, 0x48, 0x1e, 0xaa, 0x49, 0x65, 0x1c, 0x65, 0x59, 0xd4, 0x64, 0xad, 0x7d, 0x61, 0x54, 0xfc, 0x43, 0xe1, 0xdb, 0x0f, 0x16, 0xe8, 0xb7, 0x1a, 0x6e, 0xa9, 0x67, 0x6d, 0xa8, 0x58, 0x5d, 0xae, 0xc9, 0xad, 0xe7, 0x8c, 0x49, 0x1c, 0x83, 0xdc, 0x1e, 0x3d, 0xfd, 0x88, 0xad, 0xb8, 0x83, 0x25, 0x96, 0x3e, 0x94, 0x27, 0x42, 0x7e, 0xce, 0xb5, 0x27, 0xcd, 0x4e, 0x5b, 0xd9, 0xec, 0xd3, 0x5d, 0x63, 0x25, 0xa4, 0x97, 0x6f, 0x43, 0x1e, 0x1d, 0xcf, 0x23, 0x97, 0xd5, 0x9c, 0x31, 0x10, 0xf6, 0x94, 0x2a, 0xc7, 0x96, 0xa4, 0x2f, 0x6b, 0xc7, 0x74, 0xd3, 0xe9, 0x28, 0xbd, 0x62, 0xfb, 0xfa, 0x95, 0xfc, 0x1d, 0xe3, 0x8d, 0x1f, 0xe2, 0x0e, 0x87, 0x1e, 0xa5, 0xa1, 0xea, 0x56, 0x7a, 0xa5, 0x8c, 0xdf, 0x76, 0x6b, 0x69, 0x43, 0xae, 0x7d, 0x0e, 0x3a, 0x30, 0xee, 0x0e, 0x08, 0xef, 0x5a, 0x95, 0xf3, 0x8f, 0x88, 0xbf, 0xe0, 0x9e, 0x56, 0xba, 0x5f, 0x88, 0xa4, 0xd4, 0x3e, 0x1f, 0xf8, 0xd7, 0xc4, 0x1e, 0x00, 0xfb, 0x50, 0xc4, 0xf0, 0xda, 0xbc, 0x93, 0x23, 0x0e, 0xa0, 0x2b, 0x2c, 0xb1, 0xb8, 0x1e, 0xcc, 0xcd, 0xf8, 0x55, 0x76, 0xfd, 0x87, 0x3c, 0x7f, 0x20, 0xdb, 0x27, 0xc7, 0x8f, 0x19, 0x32, 0x37, 0x0c, 0xa5, 0x6e, 0x79, 0x1d, 0xc7, 0xfc, 0x7d, 0xd7, 0x95, 0x1c, 0xeb, 0x3f, 0xa6, 0xb9, 0x2b, 0x65, 0xdc, 0xd2, 0x5f, 0x6a, 0x15, 0x69, 0xf2, 0xbf, 0x35, 0xce, 0xe3, 0x24, 0xbc, 0x9a, 0xba, 0xf3, 0x3d, 0x69, 0x64, 0x7c, 0x3b, 0x51, 0xf3, 0xd1, 0xcc, 0xb9, 0x22, 0xf6, 0x8c, 0xe9, 0x54, 0xe6, 0x5e, 0x4f, 0x91, 0x4a, 0x2d, 0xf9, 0xa7, 0x67, 0xe4, 0x7b, 0xe7, 0x8e, 0x3e, 0x24, 0x68, 0x3f, 0x0d, 0x74, 0xcf, 0xb6, 0x6b, 0xfa, 0xc6, 0x9f, 0xa4, 0x5b, 0xf3, 0xb5, 0xae, 0xa7, 0x58, 0xcc, 0x98, 0xea, 0x14, 0x1e, 0x58, 0xfb, 0x28, 0x26, 0xbe, 0x5d, 0xf1, 0x67, 0x8b, 0xf5, 0x0f, 0xf8, 0x28, 0x47, 0xc4, 0xcd, 0x2f, 0x41, 0xd0, 0xed, 0x75, 0x8d, 0x3f, 0xe1, 0xae, 0x8f, 0x31, 0x9f, 0x55, 0xbe, 0x71, 0xe5, 0x0b, 0xd6, 0x1d, 0x00, 0xea, 0x33, 0xc6, 0x11, 0x79, 0x23, 0x79, 0x62, 0x06, 0x30, 0x3b, 0x9f, 0x05, 0xff, 0x00, 0xc1, 0x36, 0xbc, 0x03, 0xa0, 0x6a, 0xb1, 0xdf, 0xeb, 0x17, 0x1a, 0xe7, 0x89, 0xee, 0xb1, 0x99, 0x56, 0xfa, 0xe4, 0x2c, 0x12, 0x3f, 0xf7, 0xb6, 0xa2, 0xab, 0xfe, 0x0c, 0xec, 0x3d, 0x73, 0x5e, 0xef, 0xe1, 0xef, 0x0e, 0xd8, 0x78, 0x4f, 0x46, 0xb7, 0xd3, 0xb4, 0xbb, 0x3b, 0x5d, 0x3e, 0xc2, 0xd5, 0x76, 0x43, 0x6f, 0x6f, 0x18, 0x8e, 0x38, 0xc7, 0x5e, 0x14, 0x71, 0xd7, 0x27, 0xea, 0x6b, 0x0a, 0xf9, 0x6e, 0x71, 0x9d, 0x5a, 0x8e, 0x67, 0x18, 0xd0, 0xc3, 0xdd, 0x39, 0x42, 0x32, 0xe7, 0x9c, 0xec, 0xd3, 0xe5, 0x94, 0xac, 0x92, 0x8b, 0xea, 0xa2, 0x9b, 0x6b, 0x4b, 0xdb, 0x53, 0xa3, 0x0f, 0x9a, 0x64, 0xb9, 0x1d, 0xeb, 0x65, 0x52, 0x95, 0x7c, 0x4d, 0x9a, 0x8d, 0x49, 0x47, 0x92, 0x10, 0xba, 0x6b, 0x9a, 0x30, 0xbc, 0x9c, 0xa4, 0xba, 0x39, 0x34, 0x93, 0xd6, 0xd7, 0xd0, 0x4f, 0x0e, 0x78, 0x7a, 0xcb, 0xc2, 0x3a, 0x05, 0x9e, 0x97, 0xa6, 0xdb, 0xc7, 0x69, 0x61, 0xa7, 0xc2, 0xb6, 0xf6, 0xf0, 0xa7, 0xdd, 0x8d, 0x14, 0x60, 0x0f, 0x5e, 0x83, 0xa9, 0xe4, 0xd5, 0xda, 0x28, 0xaf, 0xb9, 0x84, 0x23, 0x08, 0xa8, 0x41, 0x59, 0x2d, 0x12, 0x5d, 0x11, 0xf0, 0x33, 0x9c, 0xa7, 0x27, 0x39, 0xbb, 0xb7, 0xab, 0x6f, 0x76, 0xc2, 0xab, 0x6b, 0x3a, 0x3d, 0xaf, 0x88, 0x74, 0x7b, 0xad, 0x3e, 0xfa, 0x18, 0xee, 0x6c, 0xef, 0xa1, 0x7b, 0x79, 0xe1, 0x71, 0xf2, 0xcb, 0x1b, 0x82, 0xac, 0xa7, 0xd8, 0x82, 0x45, 0x59, 0xa2, 0x89, 0x45, 0x49, 0x38, 0xc9, 0x5d, 0x30, 0x8c, 0x9c, 0x5a, 0x94, 0x5d, 0x9a, 0x3e, 0x73, 0xf1, 0x67, 0xfc, 0x13, 0x6b, 0xc2, 0x72, 0x6a, 0x47, 0x51, 0xf0, 0x8e, 0xb5, 0xe2, 0x0f, 0x06, 0x6a, 0x51, 0xed, 0x36, 0xed, 0x6d, 0x70, 0x67, 0x86, 0xdc, 0x8e, 0xac, 0x03, 0x11, 0x2e, 0x4f, 0xfd, 0x75, 0x18, 0xaa, 0x30, 0x7c, 0x05, 0xfd, 0xa1, 0xbc, 0x1a, 0xf2, 0x59, 0xe8, 0x5f, 0x14, 0xf4, 0x9d, 0x43, 0x4d, 0x56, 0xdd, 0x1c, 0xfa, 0xb4, 0x66, 0x4b, 0x96, 0xfa, 0xf9, 0x90, 0x4c, 0x47, 0xd3, 0xcc, 0x22, 0xbe, 0x9a, 0xa2, 0xbe, 0x46, 0xa7, 0x02, 0xe5, 0x2a, 0x6e, 0xa6, 0x12, 0x32, 0xa1, 0x27, 0xbb, 0xa5, 0x39, 0x53, 0xfc, 0x22, 0xd4, 0x7f, 0x03, 0xec, 0xa9, 0xf1, 0xf6, 0x70, 0xe0, 0xa9, 0xe2, 0xe5, 0x1c, 0x44, 0x56, 0xca, 0xac, 0x21, 0x52, 0xdf, 0x39, 0x27, 0x2f, 0xc7, 0xf1, 0x3c, 0xa7, 0xf6, 0x7e, 0xf0, 0xa7, 0xc5, 0xcf, 0x0e, 0xeb, 0xb7, 0xcd, 0xf1, 0x13, 0xc4, 0xde, 0x1e, 0xd7, 0xb4, 0xd9, 0x20, 0xc5, 0xb2, 0x58, 0xc0, 0x16, 0x68, 0xe5, 0xdc, 0x39, 0x24, 0x43, 0x10, 0xdb, 0xb7, 0x77, 0x07, 0x71, 0x24, 0x8e, 0x98, 0xe7, 0xd5, 0xa8, 0xa2, 0xbe, 0x8b, 0x2d, 0xc0, 0x47, 0x07, 0x41, 0x50, 0x8c, 0xe5, 0x34, 0xaf, 0xac, 0xe4, 0xe5, 0x2d, 0x7b, 0xb7, 0xaf, 0xa1, 0xf3, 0x79, 0x96, 0x61, 0x2c, 0x6d, 0x77, 0x88, 0x94, 0x21, 0x06, 0xed, 0xa4, 0x22, 0xa1, 0x1d, 0x3b, 0x45, 0x69, 0xea, 0x14, 0x51, 0x45, 0x77, 0x1e, 0x78, 0x57, 0xc8, 0x3f, 0x1a, 0x6f, 0x3c, 0x69, 0xe0, 0x1f, 0xdb, 0x9a, 0xe7, 0xc6, 0x71, 0xf8, 0x0b, 0xc5, 0x1e, 0x32, 0xd3, 0xf4, 0xab, 0x08, 0xed, 0xb4, 0x7f, 0xb0, 0xc7, 0x2a, 0xc3, 0x18, 0x7b, 0x70, 0xaf, 0x99, 0x12, 0x29, 0x01, 0x01, 0xa4, 0xb8, 0xf9, 0x08, 0x07, 0x2e, 0x0e, 0x70, 0x00, 0x3f, 0x5f, 0x51, 0x5f, 0x3f, 0xc4, 0x59, 0x1b, 0xcd, 0x28, 0xd3, 0xa7, 0x1a, 0xae, 0x9c, 0xa9, 0xce, 0x35, 0x13, 0x49, 0x3d, 0x63, 0x7b, 0x5d, 0x49, 0x34, 0xf5, 0x77, 0xd5, 0x6e, 0x93, 0x3e, 0x8b, 0x86, 0xf3, 0xe5, 0x95, 0x56, 0xab, 0x52, 0x74, 0x55, 0x58, 0xd4, 0x84, 0xa9, 0xb8, 0xb6, 0xd7, 0xbb, 0x2b, 0x5e, 0xce, 0x2d, 0x34, 0xda, 0x56, 0xd1, 0xec, 0xda, 0x3e, 0x67, 0x4f, 0xf8, 0x29, 0x7e, 0x8f, 0xe1, 0xa7, 0x6b, 0x5f, 0x17, 0x78, 0x23, 0xc6, 0x1e, 0x1d, 0xd5, 0x17, 0xad, 0xa8, 0x89, 0x24, 0x20, 0x7a, 0x9f, 0x34, 0xc4, 0xdf, 0xf8, 0xed, 0x3b, 0xfe, 0x1e, 0x9f, 0xf0, 0xfb, 0xfe, 0x80, 0xfe, 0x32, 0xff, 0x00, 0xc0, 0x4b, 0x6f, 0xfe, 0x3f, 0x5f, 0x4b, 0x51, 0x5e, 0x6f, 0xf6, 0x3f, 0x11, 0x2d, 0x23, 0x98, 0xc5, 0xaf, 0x3a, 0x09, 0xbf, 0x9d, 0xa7, 0x15, 0xf7, 0x25, 0xe8, 0x7a, 0x9f, 0xdb, 0x5c, 0x36, 0xf5, 0x96, 0x5b, 0x24, 0xfc, 0xab, 0xc9, 0x2f, 0x95, 0xe9, 0xc9, 0xfd, 0xed, 0xfa, 0x9f, 0x33, 0x2f, 0xfc, 0x14, 0x17, 0x5a, 0xf1, 0x69, 0x69, 0xbc, 0x1d, 0xf0, 0x97, 0xc5, 0xde, 0x22, 0xd3, 0x7e, 0xea, 0xdd, 0x90, 0xeb, 0xf3, 0x7b, 0x88, 0xa2, 0x95, 0x7f, 0xf1, 0xfa, 0x48, 0xf5, 0x3f, 0xda, 0x5f, 0xe2, 0x91, 0x13, 0x5a, 0xdb, 0xf8, 0x63, 0xc0, 0x36, 0xad, 0xf3, 0x46, 0x2e, 0x02, 0x49, 0x23, 0x0f, 0xf6, 0x83, 0x09, 0x98, 0x1f, 0xaa, 0xaf, 0xd0, 0x57, 0xd3, 0x54, 0x51, 0xfe, 0xac, 0xe6, 0x15, 0xff, 0x00, 0xdf, 0xf3, 0x0a, 0xb2, 0x5d, 0xa9, 0xa8, 0xd2, 0x5f, 0x7c, 0x53, 0x95, 0xbf, 0xed, 0xef, 0x98, 0x7f, 0xad, 0x59, 0x75, 0x0f, 0xf9, 0x17, 0xe5, 0xb4, 0xa2, 0xfb, 0xd4, 0x72, 0xaa, 0xfe, 0xe9, 0x35, 0x0b, 0xff, 0x00, 0xdb, 0xb6, 0xf2, 0x3e, 0x65, 0x8b, 0xf6, 0x50, 0xf8, 0xc9, 0xe3, 0x79, 0xa4, 0xbc, 0xf1, 0x2f, 0xc6, 0x6b, 0xed, 0x26, 0xf3, 0x21, 0x52, 0x2d, 0x14, 0x4d, 0xe4, 0x32, 0xfa, 0x95, 0x46, 0xb7, 0x50, 0x7e, 0x88, 0x7e, 0xb5, 0xed, 0x5f, 0x03, 0xbe, 0x1c, 0x6b, 0x1f, 0x0b, 0x3c, 0x11, 0xfd, 0x97, 0xad, 0xf8, 0xab, 0x50, 0xf1, 0x85, 0xe0, 0xb8, 0x79, 0x56, 0xfa, 0xf1, 0x0a, 0xc8, 0xa8, 0x42, 0xe2, 0x3e, 0x5d, 0xd8, 0x81, 0x82, 0x72, 0xcc, 0x4f, 0xcc, 0x7a, 0x0c, 0x01, 0xd8, 0x51, 0x5e, 0x86, 0x57, 0xc2, 0xf8, 0x1c, 0x05, 0x6f, 0xac, 0x51, 0xe7, 0x95, 0x4b, 0x34, 0xe5, 0x2a, 0x93, 0x93, 0x77, 0xee, 0xa5, 0x27, 0x1b, 0xf9, 0xd8, 0xf3, 0x73, 0x6e, 0x2b, 0xc7, 0xe6, 0x14, 0x7e, 0xad, 0x5b, 0x92, 0x34, 0xee, 0x9a, 0x8c, 0x29, 0xd3, 0x82, 0x56, 0xda, 0xce, 0x31, 0x52, 0xb7, 0x95, 0xc2, 0x8a, 0x28, 0xaf, 0xa2, 0x3e, 0x6c, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0xf3, 0xaf, 0xda, 0x13, 0xf6, 0x9e, 0xf0, 0xe7, 0xec, 0xd7, 0x63, 0xa6, 0xcd, 0xaf, 0x47, 0xa9, 0xdc, 0x3e, 0xac, 0xf2, 0x2d, 0xbc, 0x36, 0x30, 0xac, 0x92, 0x30, 0x8f, 0x6e, 0xf6, 0x3b, 0x99, 0x54, 0x01, 0xbd, 0x7b, 0xe7, 0xe6, 0xe9, 0xd6, 0xb9, 0x4f, 0x84, 0xff, 0x00, 0xf0, 0x50, 0x2f, 0x02, 0xfc, 0x5c, 0xf1, 0x94, 0x3a, 0x25, 0xac, 0x3a, 0xe6, 0x95, 0x71, 0x70, 0xac, 0x63, 0x9b, 0x52, 0x86, 0x18, 0xad, 0xc9, 0x03, 0x3b, 0x4b, 0xac, 0xad, 0xb4, 0x9e, 0x83, 0x38, 0x04, 0x90, 0x33, 0x92, 0x01, 0xdc, 0xfd, 0xa9, 0xff, 0x00, 0x66, 0x4b, 0x7f, 0xda, 0x33, 0xc3, 0xb6, 0x2d, 0x16, 0xa3, 0x73, 0xa4, 0xeb, 0xda, 0x09, 0x92, 0x6d, 0x2a, 0xea, 0x36, 0xc4, 0x69, 0x23, 0xec, 0x24, 0x38, 0x1c, 0xe0, 0xf9, 0x6b, 0x86, 0x52, 0x0a, 0x90, 0x08, 0xcf, 0x2a, 0x7e, 0x13, 0xf8, 0xf9, 0xe1, 0xbf, 0x8b, 0x5e, 0x0e, 0x87, 0xec, 0x3e, 0x3e, 0xb8, 0xf1, 0x75, 0xc6, 0x9b, 0x1d, 0xc2, 0xf9, 0x52, 0xde, 0xdf, 0x4d, 0x79, 0x61, 0x24, 0xbb, 0x58, 0xa9, 0x49, 0x0b, 0x34, 0x65, 0xf6, 0xef, 0x20, 0x03, 0xb8, 0x0d, 0xd9, 0x03, 0x9a, 0xfc, 0x7f, 0x8d, 0xb8, 0xab, 0x88, 0x32, 0x4c, 0x7b, 0xaf, 0x18, 0x73, 0x61, 0x7d, 0xde, 0x5b, 0x42, 0xe9, 0xe8, 0xb9, 0x94, 0xe7, 0x7b, 0xc1, 0xde, 0xf6, 0x76, 0x7a, 0x5a, 0xd7, 0xb3, 0x3f, 0x68, 0xe0, 0x5e, 0x12, 0xe1, 0xcc, 0xf7, 0x2f, 0x54, 0x27, 0x53, 0x97, 0x17, 0xef, 0x29, 0x5e, 0x76, 0x6b, 0x57, 0xca, 0xe1, 0x0e, 0x5b, 0x4d, 0x5a, 0xd7, 0x5c, 0xc9, 0xde, 0xf7, 0xb5, 0xd1, 0xfa, 0x4d, 0xe2, 0xcf, 0x89, 0x5e, 0x1d, 0xf0, 0x1c, 0x90, 0xae, 0xb9, 0xaf, 0xe8, 0xba, 0x2b, 0x5c, 0x02, 0x62, 0x5b, 0xfb, 0xe8, 0xad, 0xcc, 0x80, 0x75, 0x2b, 0xbd, 0x86, 0x7f, 0x0a, 0xf3, 0x1f, 0x1d, 0xfe, 0xdf, 0xff, 0x00, 0x0b, 0xfc, 0x0e, 0xb7, 0x08, 0xba, 0xe4, 0x9a, 0xdd, 0xd5, 0xbb, 0x05, 0x30, 0x69, 0x76, 0xed, 0x36, 0xff, 0x00, 0x75, 0x91, 0xb6, 0xc4, 0xc0, 0x7a, 0x87, 0xaf, 0x01, 0xfd, 0x8d, 0xff, 0x00, 0x66, 0x8f, 0x0f, 0x7c, 0x48, 0xf1, 0x37, 0x88, 0x2d, 0xfe, 0x25, 0xe8, 0x9a, 0xc4, 0x7a, 0xfc, 0x6b, 0x14, 0xb6, 0xf6, 0x7a, 0xad, 0xf4, 0xb6, 0xb3, 0xdd, 0x87, 0xde, 0x64, 0x98, 0x44, 0x3c, 0xb9, 0x8e, 0xd2, 0xa3, 0xe6, 0x25, 0x97, 0xe7, 0xf5, 0x19, 0xaf, 0xab, 0xbc, 0x0f, 0xfb, 0x35, 0x78, 0x07, 0xe1, 0xca, 0xdb, 0x1d, 0x1f, 0xc2, 0x3a, 0x1d, 0xbc, 0xd6, 0x72, 0x79, 0xb0, 0x5c, 0xc9, 0x6c, 0x2e, 0x2e, 0xa2, 0x6f, 0x51, 0x34, 0x9b, 0xa4, 0xc8, 0xed, 0xf3, 0x71, 0x5e, 0xe6, 0x57, 0x9c, 0x71, 0x16, 0x73, 0x86, 0x58, 0xac, 0x24, 0x69, 0x50, 0xa7, 0x2b, 0xaf, 0x7b, 0x9e, 0x73, 0x56, 0x76, 0x77, 0x8d, 0xa0, 0x93, 0xea, 0xae, 0xf6, 0xb6, 0x96, 0x77, 0x3c, 0x1c, 0xdb, 0x25, 0xe1, 0xbc, 0x93, 0x12, 0xf0, 0x98, 0xc9, 0x56, 0xaf, 0x52, 0x29, 0x3f, 0x73, 0x92, 0x14, 0xe5, 0x75, 0x75, 0x69, 0x5e, 0x6d, 0xad, 0x6c, 0xec, 0xb7, 0xbe, 0xb7, 0x56, 0x3c, 0x87, 0xfe, 0x1e, 0x9f, 0xf0, 0xfb, 0xfe, 0x80, 0xfe, 0x32, 0xff, 0x00, 0xc0, 0x4b, 0x6f, 0xfe, 0x3f, 0x49, 0xad, 0x7f, 0xc1, 0x4f, 0xfc, 0x1a, 0x7c, 0x34, 0x6e, 0x34, 0x5d, 0x1f, 0x5e, 0xd4, 0x75, 0x87, 0x9d, 0x61, 0x87, 0x4c, 0xb9, 0x45, 0xb7, 0x69, 0x01, 0xfe, 0x2d, 0xe8, 0x64, 0x5c, 0x76, 0xc0, 0xcb, 0x12, 0x47, 0x18, 0xe6, 0xbd, 0xeb, 0xc0, 0x5f, 0x13, 0x74, 0x0f, 0x8a, 0x1a, 0x7d, 0xc5, 0xd7, 0x87, 0xf5, 0x6b, 0x3d, 0x5a, 0xde, 0xd6, 0x66, 0xb7, 0x99, 0xe0, 0x6c, 0xf9, 0x6e, 0x3a, 0x83, 0xdf, 0xdc, 0x1e, 0x84, 0x72, 0x32, 0x2b, 0xe4, 0xef, 0xdb, 0xbf, 0xe1, 0x5d, 0xc5, 0xb7, 0xed, 0x55, 0xe0, 0x3d, 0x57, 0x4b, 0xd4, 0x7f, 0xb0, 0x6e, 0x3c, 0x65, 0x24, 0x3a, 0x71, 0xbe, 0xb7, 0x2c, 0x27, 0xb6, 0xb8, 0x49, 0x52, 0x23, 0x71, 0xc1, 0x5e, 0x91, 0xcd, 0x10, 0x18, 0x60, 0x7f, 0x76, 0x79, 0x1d, 0x6b, 0xcb, 0xe2, 0x2c, 0x67, 0x11, 0xe5, 0xf9, 0x6f, 0xf6, 0x86, 0x17, 0x1b, 0x0a, 0xd1, 0x6e, 0x31, 0xf7, 0x69, 0x45, 0x59, 0x49, 0xf2, 0xa9, 0x45, 0xf3, 0xca, 0x2d, 0xa6, 0xd2, 0x49, 0xe9, 0xae, 0xbb, 0x1e, 0xb7, 0x0d, 0x60, 0xb8, 0x67, 0x31, 0xcc, 0xff, 0x00, 0xb3, 0xb1, 0x58, 0x1a, 0x94, 0x24, 0x94, 0xa5, 0xef, 0x55, 0x93, 0xbb, 0x8a, 0xe6, 0x71, 0x92, 0xf6, 0x71, 0x92, 0x4e, 0x29, 0xb6, 0xd6, 0xba, 0x68, 0xb5, 0x2b, 0xfc, 0x5e, 0xfd, 0xa5, 0xbe, 0x3c, 0x78, 0x33, 0x40, 0xb4, 0xf1, 0x9e, 0xa5, 0x06, 0x9f, 0xe0, 0xfd, 0x12, 0xf2, 0xf9, 0x2d, 0x2d, 0x74, 0x69, 0xad, 0x63, 0x6b, 0x89, 0xf2, 0xb2, 0x3e, 0x5d, 0x64, 0x53, 0x2a, 0x80, 0x23, 0x21, 0x89, 0x31, 0x9c, 0xb2, 0xe1, 0x70, 0x72, 0x3e, 0xd6, 0xaf, 0x9b, 0xfc, 0x2d, 0xff, 0x00, 0x04, 0xd9, 0xf0, 0xf9, 0xd6, 0xe3, 0xd5, 0xbc, 0x61, 0xe2, 0x6f, 0x10, 0xf8, 0xc3, 0x56, 0x5b, 0x81, 0x34, 0xcf, 0x3b, 0x88, 0xa1, 0xbb, 0x03, 0x18, 0x59, 0x03, 0x79, 0x92, 0x37, 0xb9, 0xf3, 0x06, 0x7d, 0xab, 0xe9, 0x0a, 0xf7, 0x78, 0x2f, 0x2e, 0xce, 0x30, 0xf3, 0xaf, 0x57, 0x35, 0x94, 0xad, 0x3e, 0x5e, 0x58, 0xce, 0xa2, 0xa8, 0xd3, 0x5c, 0xdc, 0xcf, 0xdd, 0x4a, 0x31, 0x4e, 0xeb, 0xdd, 0x8e, 0x8a, 0xdb, 0xbd, 0xdf, 0xcf, 0xf1, 0xc6, 0x65, 0x92, 0xe2, 0x61, 0x87, 0xa3, 0x94, 0xc6, 0x17, 0x87, 0x3f, 0x34, 0xa1, 0x4d, 0xd3, 0x8b, 0x4f, 0x97, 0x95, 0x7b, 0xcd, 0xce, 0x4e, 0x36, 0x77, 0x94, 0xb5, 0x77, 0xd9, 0x6c, 0x8a, 0x28, 0xa2, 0xbe, 0xec, 0xfc, 0xfc, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x28, 0xa2, 0x8a, 0x00, 0x2b, 0xe6, 0x3f, 0xf8, 0x28, 0x45, 0xa1, 0xf1, 0x77, 0x8e, 0xfe, 0x10, 0xf8, 0x52, 0xea, 0x69, 0x97, 0x47, 0xf1, 0x16, 0xba, 0xd1, 0xde, 0x45, 0x1b, 0x6d, 0x2f, 0xfb, 0xcb, 0x68, 0x83, 0x03, 0xd9, 0x82, 0xcf, 0x28, 0x07, 0xfd, 0xaa, 0xfa, 0x72, 0xbc, 0x77, 0xf6, 0xb8, 0xfd, 0x99, 0x35, 0x0f, 0xda, 0x0a, 0xd7, 0x40, 0xbe, 0xd1, 0x75, 0xdf, 0xec, 0x3d, 0x7b, 0xc2, 0xd2, 0xcb, 0x71, 0x61, 0x23, 0x2b, 0x04, 0x77, 0x73, 0x19, 0x19, 0x75, 0xf9, 0xa3, 0x2a, 0xd1, 0x29, 0x0c, 0xa1, 0xb1, 0xcf, 0x1d, 0xc7, 0xca, 0xf1, 0xb6, 0x07, 0x11, 0x8c, 0xc9, 0xab, 0x61, 0xf0, 0xd0, 0xe7, 0x93, 0x70, 0x7c, 0xa9, 0xa5, 0xcc, 0x94, 0xe2, 0xe4, 0xb5, 0x69, 0x6b, 0x14, 0xd5, 0xba, 0xec, 0x7d, 0x77, 0x02, 0xe3, 0xf0, 0xf8, 0x2c, 0xee, 0x8e, 0x23, 0x15, 0x3e, 0x48, 0xa5, 0x35, 0xcc, 0xd3, 0x7c, 0xad, 0xc2, 0x51, 0x8b, 0xd1, 0x37, 0xa4, 0x9a, 0x77, 0xe9, 0xbf, 0x42, 0x0f, 0xda, 0x3f, 0xf6, 0x68, 0xf8, 0x77, 0xe2, 0x4d, 0x42, 0x4f, 0x1e, 0x78, 0x9a, 0xf3, 0x52, 0xf0, 0xed, 0xc6, 0x95, 0xe5, 0xcd, 0x77, 0xa9, 0x58, 0xdd, 0x18, 0x5a, 0x55, 0x4d, 0xaa, 0x81, 0x86, 0xd6, 0xe4, 0x7c, 0xaa, 0x0c, 0x60, 0x39, 0xc8, 0x19, 0x3c, 0x54, 0xcb, 0xfb, 0x7f, 0x7c, 0x23, 0x76, 0x03, 0xfe, 0x12, 0xe1, 0xc9, 0xc7, 0x3a, 0x65, 0xe0, 0xff, 0x00, 0xda, 0x35, 0xe7, 0x5e, 0x20, 0xf8, 0x53, 0xfb, 0x4a, 0x47, 0xe1, 0xc9, 0xa2, 0xba, 0xf1, 0x37, 0x83, 0x3c, 0x55, 0x66, 0xa8, 0x16, 0x4d, 0x2a, 0x5b, 0x68, 0x24, 0x17, 0xea, 0x31, 0xf2, 0x37, 0x9b, 0x6c, 0x8a, 0xd9, 0xef, 0xb9, 0xc6, 0x7d, 0x73, 0x5c, 0xdd, 0xdf, 0xc3, 0x9f, 0x8b, 0x57, 0xb6, 0xb2, 0x42, 0xff, 0x00, 0x00, 0x3e, 0x0f, 0xaa, 0x4c, 0xa5, 0x18, 0xc7, 0x65, 0x69, 0x1b, 0x00, 0x46, 0x38, 0x65, 0xbb, 0x05, 0x4f, 0xb8, 0x20, 0x8a, 0xf8, 0xac, 0x5e, 0x79, 0x8f, 0xc3, 0x62, 0x67, 0x5b, 0x2a, 0xc0, 0x4a, 0x8b, 0xa9, 0x67, 0x3e, 0x7a, 0x13, 0x9b, 0x94, 0xb5, 0xd6, 0xf4, 0xa6, 0xd7, 0xad, 0xd5, 0xee, 0xdb, 0xd6, 0xe7, 0xdc, 0x60, 0xf2, 0x1c, 0xbf, 0x15, 0x85, 0x85, 0x0c, 0xdf, 0x30, 0x8d, 0x65, 0x4e, 0xea, 0x1c, 0x98, 0x88, 0x41, 0x42, 0x3a, 0x69, 0x6a, 0xd0, 0x52, 0xe9, 0xa5, 0x9f, 0x2d, 0x92, 0x5a, 0x58, 0xfa, 0x43, 0xe0, 0x3f, 0xc3, 0xbf, 0x00, 0xf8, 0x3f, 0x47, 0xbc, 0xd4, 0xfc, 0x03, 0x6f, 0xa7, 0x2d, 0x8e, 0xbc, 0xeb, 0x34, 0xf3, 0xd9, 0xdd, 0x35, 0xc4, 0x73, 0x32, 0xee, 0xc0, 0xcb, 0x33, 0x05, 0xdb, 0xbd, 0xbe, 0x41, 0x80, 0x32, 0x78, 0x15, 0xc0, 0xff, 0x00, 0xc1, 0x46, 0xbc, 0x1f, 0x69, 0xad, 0xfe, 0xcd, 0x97, 0xda, 0xc4, 0x81, 0x93, 0x50, 0xf0, 0xdd, 0xd5, 0xbd, 0xd5, 0x9c, 0xa8, 0x70, 0xc8, 0xcf, 0x32, 0x42, 0xc3, 0x3d, 0x70, 0x44, 0x99, 0xfa, 0xaa, 0xfa, 0x57, 0x03, 0xf0, 0xc2, 0xd3, 0xe3, 0xe7, 0xc1, 0x9f, 0x0d, 0xb6, 0x93, 0xe1, 0x9f, 0x85, 0x3e, 0x0b, 0xd2, 0xf4, 0xf9, 0x27, 0x6b, 0x96, 0x88, 0x5f, 0x79, 0xa5, 0xa4, 0x60, 0x01, 0x62, 0xcf, 0x7e, 0xcc, 0x4e, 0x15, 0x47, 0x5e, 0x80, 0x54, 0x7f, 0x18, 0x22, 0xfd, 0xa3, 0xbe, 0x35, 0xfc, 0x3a, 0xd4, 0x7c, 0x33, 0xaa, 0xf8, 0x03, 0xc3, 0x36, 0xf6, 0x1a, 0x9f, 0x95, 0xe6, 0xc9, 0x69, 0x79, 0x0a, 0xcc, 0xbe, 0x5c, 0xa9, 0x28, 0xda, 0x5a, 0xed, 0x87, 0xde, 0x40, 0x0e, 0x41, 0xe3, 0x3f, 0x5a, 0xbc, 0x7e, 0x75, 0x0a, 0xfc, 0x3f, 0x57, 0x2d, 0x58, 0x0a, 0xb1, 0x9c, 0xa9, 0xc9, 0x28, 0xc2, 0x85, 0x45, 0x05, 0x36, 0x9b, 0x5c, 0xbe, 0xea, 0xb2, 0xe6, 0xd6, 0xf6, 0x5a, 0xea, 0x67, 0x97, 0xe4, 0x73, 0xc3, 0xf1, 0x15, 0x2c, 0xcd, 0xe6, 0x34, 0xa5, 0x08, 0xd4, 0x8b, 0x72, 0x9e, 0x22, 0x9b, 0xa8, 0xe0, 0x9a, 0x4f, 0x9b, 0xde, 0x77, 0x7c, 0x97, 0x56, 0xbb, 0x56, 0xd0, 0xfa, 0x63, 0xe0, 0xcf, 0x88, 0x2e, 0xbc, 0x5b, 0xf0, 0x7f, 0xc2, 0x9a, 0xad, 0xf3, 0xf9, 0x97, 0xba, 0x9e, 0x8f, 0x67, 0x77, 0x70, 0xe0, 0x63, 0x7c, 0x92, 0x40, 0x8c, 0xc7, 0x1e, 0xe4, 0x9a, 0xe9, 0x2b, 0x9c, 0xf8, 0x3d, 0xe1, 0xbb, 0xaf, 0x06, 0xfc, 0x24, 0xf0, 0xb6, 0x8f, 0x7c, 0xaa, 0x97, 0xda, 0x56, 0x91, 0x69, 0x67, 0x70, 0xaa, 0xdb, 0x95, 0x64, 0x8e, 0x14, 0x46, 0x00, 0xf7, 0x19, 0x07, 0x9a, 0xe8, 0xeb, 0xf5, 0x0c, 0xbf, 0xda, 0x7d, 0x56, 0x97, 0xb5, 0xbf, 0x37, 0x2c, 0x6f, 0x7d, 0xef, 0x65, 0x7b, 0xf9, 0xdc, 0xfc, 0xa7, 0x32, 0xf6, 0x7f, 0x5b, 0xab, 0xec, 0xad, 0xcb, 0xcd, 0x2b, 0x5b, 0x6b, 0x5d, 0xda, 0xde, 0x56, 0x0a, 0x28, 0xa2, 0xbb, 0x0e, 0x30, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x00, 0xa2, 0x8a, 0x28, 0x03, 0xff, 0xd9, 0x00, 0x00, 0x00, 0x00, 0x00 }; <file_sep>/HARDWARE/TIMER/timer.c #include "timer.h" #include "led.h" #include "lcd.h" #include "ov7670.h" ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK战舰STM32开发板 //定时器 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/8 //版本:V1.3 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved //******************************************************************************** //V1.1 20120904 //1,增加TIM3_PWM_Init函数。 //2,增加LED0_PWM_VAL宏定义,控制TIM3_CH2脉宽 //V1.2 20120904 //1,新增TIM5_Cap_Init函数 //2,新增TIM5_IRQHandler中断服务函数 //V1.3 20120908 //1,新增TIM4_PWM_Init函数 ////////////////////////////////////////////////////////////////////////////////// //定时器3中断服务程序 void TIM3_IRQHandler(void) { if (TIM3->SR & 0X0001)//溢出中断 { LED1 = !LED1; } TIM3->SR &= ~(1 << 0);//清除中断标志位 } //通用定时器3中断初始化 //这里时钟选择为APB1的2倍,而APB1为36M //arr:自动重装值。 //psc:时钟预分频数 //这里使用的是定时器3! void TIM3_Int_Init(u16 arr, u16 psc) { RCC->APB1ENR |= 1 << 1; //TIM3时钟使能 TIM3->ARR = arr; //设定计数器自动重装值//刚好1ms TIM3->PSC = psc; //预分频器7200,得到10Khz的计数时钟 TIM3->DIER |= 1 << 0; //允许更新中断 TIM3->CR1 |= 0x01; //使能定时器3 MY_NVIC_Init(1, 3, TIM3_IRQn, 2);//抢占1,子优先级3,组2 } //TIM3 PWM部分初始化 //PWM输出初始化 //arr:自动重装值 //psc:时钟预分频数 void TIM3_PWM_Init(u16 arr, u16 psc) { //此部分需手动修改IO口设置 RCC->APB1ENR |= 1 << 1; //TIM3时钟使能 RCC->APB2ENR |= 1 << 3; //使能PORTB时钟 GPIOB->CRL &= 0XFF0FFFFF; //PB5输出 GPIOB->CRL |= 0X00B00000; //复用功能输出 RCC->APB2ENR |= 1 << 0; //开启辅助时钟 AFIO->MAPR &= 0XFFFFF3FF; //清除MAPR的[11:10] AFIO->MAPR |= 1 << 11; //部分重映像,TIM3_CH2->PB5 TIM3->ARR = arr; //设定计数器自动重装值 TIM3->PSC = psc; //预分频器不分频 TIM3->CCMR1 |= 7 << 12; //CH2 PWM2模式 TIM3->CCMR1 |= 1 << 11; //CH2预装载使能 TIM3->CCER |= 1 << 4; //OC2 输出使能 TIM3->CR1 = 0x8000; //ARPE使能 TIM3->CR1 |= 0x01; //使能定时器3 } //定时器5通道1输入捕获配置 //arr:自动重装值 //psc:时钟预分频数 void TIM5_Cap_Init(u16 arr, u16 psc) { RCC->APB1ENR |= 1 << 3; //TIM5 时钟使能 RCC->APB2ENR |= 1 << 2; //使能PORTA时钟 GPIOA->CRL &= 0XFFFFFFF0; //PA0 清除之前设置 GPIOA->CRL |= 0X00000008; //PA0 输入 GPIOA->ODR |= 0 << 0; //PA0 下拉 TIM5->ARR = arr; //设定计数器自动重装值 TIM5->PSC = psc; //预分频器 TIM5->CCMR1 |= 1 << 0; //CC1S=01 选择输入端 IC1映射到TI1上 TIM5->CCMR1 |= 0 << 4; //IC1F=0000 配置输入滤波器 不滤波 TIM5->CCMR1 |= 0 << 10; //IC2PS=00 配置输入分频,不分频 TIM5->CCER |= 0 << 1; //CC1P=0 上升沿捕获 TIM5->CCER |= 1 << 0; //CC1E=1 允许捕获计数器的值到捕获寄存器中 TIM5->DIER |= 1 << 1; //允许捕获中断 TIM5->DIER |= 1 << 0; //允许更新中断 TIM5->CR1 |= 0x01; //使能定时器2 MY_NVIC_Init(2, 0, TIM5_IRQn, 2);//抢占2,子优先级0,组2 } //捕获状态 //[7]:0,没有成功的捕获;1,成功捕获到一次. //[6]:0,还没捕获到高电平;1,已经捕获到高电平了. //[5:0]:捕获高电平后溢出的次数 u8 TIM5CH1_CAPTURE_STA = 0; //输入捕获状态 u16 TIM5CH1_CAPTURE_VAL; //输入捕获值 //定时器5中断服务程序 void TIM5_IRQHandler(void) { u16 tsr; tsr = TIM5->SR; if ((TIM5CH1_CAPTURE_STA & 0X80) == 0)//还未成功捕获 { if (tsr & 0X01)//溢出 { if (TIM5CH1_CAPTURE_STA & 0X40)//已经捕获到高电平了 { if ((TIM5CH1_CAPTURE_STA & 0X3F) == 0X3F)//高电平太长了 { TIM5CH1_CAPTURE_STA |= 0X80;//标记成功捕获了一次 TIM5CH1_CAPTURE_VAL = 0XFFFF; } else TIM5CH1_CAPTURE_STA++; } } if (tsr & 0x02)//捕获1发生捕获事件 { if (TIM5CH1_CAPTURE_STA & 0X40) //捕获到一个下降沿 { TIM5CH1_CAPTURE_STA |= 0X80; //标记成功捕获到一次高电平脉宽 TIM5CH1_CAPTURE_VAL = TIM5->CCR1; //获取当前的捕获值. TIM5->CCER &= ~(1 << 1); //CC1P=0 设置为上升沿捕获 } else //还未开始,第一次捕获上升沿 { TIM5CH1_CAPTURE_STA = 0; //清空 TIM5CH1_CAPTURE_VAL = 0; TIM5CH1_CAPTURE_STA |= 0X40; //标记捕获到了上升沿 TIM5->CNT = 0; //计数器清空 TIM5->CCER |= 1 << 1; //CC1P=1 设置为下降沿捕获 } } } TIM5->SR = 0;//清除中断标志位 } //TIM4 CH1 PWM输出设置 //PWM输出初始化 //arr:自动重装值 //psc:时钟预分频数 void TIM4_PWM_Init(u16 arr, u16 psc) { //此部分需手动修改IO口设置 RCC->APB1ENR |= 1 << 2; //TIM4时钟使能 RCC->APB2ENR |= 1 << 3; //使能PORTB时钟 GPIOB->CRL &= 0XF0FFFFFF; //PB6输出 GPIOB->CRL |= 0X0B000000; //复用功能输出 TIM4->ARR = arr; //设定计数器自动重装值 TIM4->PSC = psc; //预分频器分频设置 TIM4->CCMR1 |= 7 << 4; //CH1 PWM2模式 TIM4->CCMR1 |= 1 << 3; //CH1 预装载使能 TIM4->CCER |= 1 << 1; //OC1 低电平有效 TIM4->CCER |= 1 << 0; //OC1 输出使能 TIM4->CR1 = 0x0080; //ARPE使能 TIM4->CR1 |= 0x01; //使能定时器3 } //基本定时器6中断初始化 //这里时钟选择为APB1的2倍,而APB1为36M //arr:自动重装值。 //psc:时钟预分频数 //这里使用的是定时器3! void TIM6_Int_Init(u16 arr, u16 psc) { RCC->APB1ENR |= 1 << 4;//TIM6时钟使能 TIM6->ARR = arr; //设定计数器自动重装值//刚好1ms TIM6->PSC = psc; //预分频器7200,得到10Khz的计数时钟 TIM6->DIER |= 1 << 0; //允许更新中断 TIM6->CR1 |= 0x01; //使能定时器3 MY_NVIC_Init(1, 3, TIM6_IRQn, 2);//抢占1,子优先级3,组2 } u8 USB_SPS; // 每秒发送帧数(编码速度+USB发送速度) u8 SPSCount; u8 OV0_FPS; // #0摄像头刷新率(采集速度) u8 FPS0Count; //定时器6中断服务程序 void TIM6_IRQHandler(void) { if (TIM6->SR & 0X0001)//溢出中断 { u8 col0xpos = 10; u8 col0width = 100; u8 col1xpos = col0xpos + col0width; LCD_Clear(WHITE); POINT_COLOR = RED; USB_SPS = SPSCount; SPSCount = 0; LCD_ShowString(col0xpos, 50, col0width, 16, 16, "USB_SPS:"); LCD_ShowNum(col1xpos, 50, USB_SPS, 2, 16); OV0_FPS = FPS0Count; FPS0Count = 0; LCD_ShowString(col0xpos, 70, col0width, 16, 16, "OV0_FPS:"); LCD_ShowNum(col1xpos, 70, OV0_FPS, 2, 16); LCD_ShowString(col0xpos, 90, col0width, 16, 16, "buf0:"); LCD_ShowNum(10, 110, ovbuf0.addr, 10, 16); LCD_ShowNum(10, 130, ovbuf0.bsize, 10, 16); LCD_ShowNum(10, 150, ovbuf0.sta, 10, 16); LCD_ShowString(col0xpos, 170, col0width, 16, 16, "buf1:"); LCD_ShowNum(10, 190, ovbuf1.addr, 10, 16); LCD_ShowNum(10, 210, ovbuf1.bsize, 10, 16); LCD_ShowNum(10, 230, ovbuf1.sta, 10, 16); } TIM6->SR &= ~(1 << 0);//清除中断标志位 } <file_sep>/HARDWARE/OV7670/ov7670.c #include "sys.h" #include "ov7670.h" #include "ov7670cfg.h" #include "timer.h" #include "delay.h" #include "usart.h" #include "sccb.h" #include "exti.h" #include "sram.h" ////////////////////////////////////////////////////////////////////////// //本程序参考自网友guanfu_wang代码。 //ALIENTEK战舰STM32开发板 //OV7670 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/14 //版本:V1.0 ////////////////////////////////////////////////////////////////////////// const u32 ov_maxbuf = OV_MAXBUF; // #0摄像头缓冲区 OV_BUF ovbuf0 = { 0, 0, 0 }; OV_BUF ovbuf1 = { OV_MAXBUF, 0, 0}; u8 ov0_sta = 0; ////////////////////////////////////////////////////////////////////////// //初始化OV7670 //返回0:成功 //返回其他值:错误代码 u8 OV7670_Init (void) { u8 temp; u16 i = 0, icount = 0; //设置IO RCC->APB2ENR |= 1 << 2; // 先使能外设PORTA时钟 RCC->APB2ENR |= 1 << 3; // 先使能外设PORTB时钟 RCC->APB2ENR |= 1 << 4; // 先使能外设PORTC时钟 RCC->APB2ENR |= 1 << 5; // 先使能外设PORTD时钟 RCC->APB2ENR |= 1 << 8; // 先使能外设PORTG时钟 // VSYNC 帧同步信号 GPIOA->CRH &= 0XFFFFFFF0; GPIOA->CRH |= 0X00000008; // PA8 输入( 上拉/下拉输入模式 ) GPIOA->ODR |= 1 << 8; // WEN , RCLK 信号 GPIOB->CRL &= 0XFFF00FFF; GPIOB->CRL |= 0X00033000; // PB3/4 输出 GPIOB->ODR |= 3 << 3; // D[7:0] 数据信号 GPIOC->CRL = 0X88888888; // PC0~7 输入(上拉下/拉输入模式) GPIOC->ODR |= 0x00ff; // WRST 信号 GPIOD->CRL &= 0XF0FFFFFF; // PD6 输出 GPIOD->CRL |= 0X03000000; GPIOD->ODR |= 1 << 6; // RRST , OE 信号 GPIOG->CRH &= 0X00FFFFFF; GPIOG->CRH |= 0X33000000; GPIOG->ODR = 7 << 14; // PG14/15 输出高 JTAG_Set (SWD_ENABLE); SCCB_Init (); // 初始化SCCB 的IO口 if (SCCB_WR_Reg (0x12, 0x80)) return 1; // 复位SCCB //delay_ms (50); delay_ms (1); // 软硬件复位1ms稳定 // 读取产品型号 temp = SCCB_RD_Reg (0x0b); if (temp != 0x73)return 2; temp = SCCB_RD_Reg (0x0a); if (temp != 0x76)return 2; // 初始化序列 icount = sizeof( ov7670_init_reg_tbl ) / sizeof( ov7670_init_reg_tbl[0] ); for (i = 0; i < icount; i++) { SCCB_WR_Reg (ov7670_init_reg_tbl[i][0], ov7670_init_reg_tbl[i][1]); delay_ms (2); } return 0x00; } //////////////////////////////////////////////////////////////////////////// //OV7670功能设置 //白平衡设置 //0:自动 //1:太阳sunny //2,阴天cloudy //3,办公室office //4,家里home void OV7670_Light_Mode (u8 mode) { u8 reg13val = 0XE7;//默认就是设置为自动白平衡 u8 reg01val = 0; u8 reg02val = 0; switch (mode) { case 1://sunny reg13val = 0XE5; reg01val = 0X5A; reg02val = 0X5C; break; case 2://cloudy reg13val = 0XE5; reg01val = 0X58; reg02val = 0X60; break; case 3://office reg13val = 0XE5; reg01val = 0X84; reg02val = 0X4c; break; case 4://home reg13val = 0XE5; reg01val = 0X96; reg02val = 0X40; break; } SCCB_WR_Reg (0X13, reg13val);//COM8设置 SCCB_WR_Reg (0X01, reg01val);//AWB蓝色通道增益 SCCB_WR_Reg (0X02, reg02val);//AWB红色通道增益 } //色度设置(饱和度) //0:-2 //1:-1 //2,0 //3,1 //4,2 void OV7670_Color_Saturation (u8 sat) { u8 reg4f5054val = 0X80;//默认就是sat=2,即不调节色度的设置 u8 reg52val = 0X22; u8 reg53val = 0X5E; switch (sat) { case 0://-2 reg4f5054val = 0X40; reg52val = 0X11; reg53val = 0X2F; break; case 1://-1 reg4f5054val = 0X66; reg52val = 0X1B; reg53val = 0X4B; break; case 3://1 reg4f5054val = 0X99; reg52val = 0X28; reg53val = 0X71; break; case 4://2 reg4f5054val = 0XC0; reg52val = 0X33; reg53val = 0X8D; break; } SCCB_WR_Reg (0X4F, reg4f5054val); //色彩矩阵系数1 SCCB_WR_Reg (0X50, reg4f5054val); //色彩矩阵系数2 SCCB_WR_Reg (0X51, 0X00); //色彩矩阵系数3 SCCB_WR_Reg (0X52, reg52val); //色彩矩阵系数4 SCCB_WR_Reg (0X53, reg53val); //色彩矩阵系数5 SCCB_WR_Reg (0X54, reg4f5054val); //色彩矩阵系数6 SCCB_WR_Reg (0X58, 0X9E); //MTXS } //亮度设置 //0:-2 //1:-1 //2,0 //3,1 //4,2 void OV7670_Brightness (u8 bright) { u8 reg55val = 0X00;//默认就是bright=2 switch (bright) { case 0://-2 reg55val = 0XB0; break; case 1://-1 reg55val = 0X98; break; case 3://1 reg55val = 0X18; break; case 4://2 reg55val = 0X30; break; } SCCB_WR_Reg (0X55, reg55val); //亮度调节 } //对比度设置 //0:-2 //1:-1 //2,0 //3,1 //4,2 void OV7670_Contrast (u8 contrast) { u8 reg56val = 0X40;//默认就是contrast=2 switch (contrast) { case 0://-2 reg56val = 0X30; break; case 1://-1 reg56val = 0X38; break; case 3://1 reg56val = 0X50; break; case 4://2 reg56val = 0X60; break; } SCCB_WR_Reg (0X56, reg56val); //对比度调节 } //特效设置 //0:普通模式 //1,负片 //2,黑白 //3,偏红色 //4,偏绿色 //5,偏蓝色 //6,复古 void OV7670_Special_Effects (u8 eft) { u8 reg3aval = 0X04;//默认为普通模式 u8 reg67val = 0XC0; u8 reg68val = 0X80; switch (eft) { case 1://负片 reg3aval = 0X24; reg67val = 0X80; reg68val = 0X80; break; case 2://黑白 reg3aval = 0X14; reg67val = 0X80; reg68val = 0X80; break; case 3://偏红色 reg3aval = 0X14; reg67val = 0Xc0; reg68val = 0X80; break; case 4://偏绿色 reg3aval = 0X14; reg67val = 0X40; reg68val = 0X40; break; case 5://偏蓝色 reg3aval = 0X14; reg67val = 0X80; reg68val = 0XC0; break; case 6://复古 reg3aval = 0X14; reg67val = 0XA0; reg68val = 0X40; break; } SCCB_WR_Reg (0X3A, reg3aval);//TSLB设置 SCCB_WR_Reg (0X68, reg67val);//MANU,手动U值 SCCB_WR_Reg (0X67, reg68val);//MANV,手动V值 } // 设置图像输出窗口 // 对QVGA设置。 void OV7670_Window_Set (u16 sx, u16 sy, u16 width, u16 height) { u16 endx; u16 endy; u8 temp; endx = sx + width * 2; //V*2 endy = sy + height * 2; if (endy > 784)endy -= 784; temp = SCCB_RD_Reg (0X03); //读取Vref之前的值 temp &= 0XF0; temp |= ((endx & 0X03) << 2) | (sx & 0X03); SCCB_WR_Reg (0X03, temp); //设置Vref的start和end的最低2位 SCCB_WR_Reg (0X19, sx >> 2); //设置Vref的start高8位 SCCB_WR_Reg (0X1A, endx >> 2); //设置Vref的end的高8位 temp = SCCB_RD_Reg (0X32); //读取Href之前的值 temp &= 0XC0; temp |= ((endy & 0X07) << 3) | (sy & 0X07); SCCB_WR_Reg (0X17, sy >> 3); //设置Href的start高8位 SCCB_WR_Reg (0X18, endy >> 3); //设置Href的end的高8位 } // 从OV7670缓冲区读取图像存入双缓冲等待编码发送 void OV7670_CaptureFrame(void) { u32 i; u8 color[2]; u32 elecount; POV_BUF povbuf; if (ov0_sta == 2) { elecount = 320 * 240; if (!ovbuf0.sta) { povbuf = &ovbuf0; } else if (!ovbuf1.sta){ povbuf = &ovbuf1; } else{ goto EXITPROC; // 双缓冲区已满 } OV7670_RRST = 0; // 开始复位读指针 OV7670_RCK = 0; OV7670_RCK = 1; OV7670_RCK = 0; OV7670_RRST = 1; // 复位读指针结束 OV7670_RCK = 1; for (i = 0; i < elecount; ++i) { OV7670_RCK = 0; color[1] = GPIOC->IDR & 0xff; OV7670_RCK = 1; OV7670_RCK = 0; color[0] = GPIOC->IDR & 0xff; OV7670_RCK = 1; // 写入像素 FSMC_SRAM_WriteBuffer(color, povbuf->addr + i * 2, 2); } povbuf->bsize = elecount * 2; // 开始编码 /*代码:JPG编码*/ povbuf->sta = 1; FPS0Count++; EXITPROC: ov0_sta = 0; // 开始下一次采集 } } <file_sep>/HARDWARE/SRAM/sram.h #ifndef __SRAM_H #define __SRAM_H #include <stm32f10x.h> ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK战舰STM32开发板 //外部SRAM 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/16 //版本:V1.0 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved ////////////////////////////////////////////////////////////////////////////////// void FSMC_SRAM_Init(void); void FSMC_SRAM_WriteBuffer(u8* pBuffer, u32 WriteAddr, u32 BytesToWrite); void FSMC_SRAM_ReadBuffer(u8* pBuffer, u32 ReadAddr, u32 BytesToWrite); #endif <file_sep>/HARDWARE/TIMER/timer.h #ifndef __TIMER_H #define __TIMER_H #include "sys.h" ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK战舰STM32开发板 //定时器 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/8 //版本:V1.3 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved //******************************************************************************** //V1.1 20120904 //1,增加TIM3_PWM_Init函数。 //2,增加LED0_PWM_VAL宏定义,控制TIM3_CH2脉宽 //V1.2 20120904 //1,新增TIM5_Cap_Init函数 //2,新增TIM5_IRQHandler中断服务函数 //V1.3 20120908 //1,新增TIM4_PWM_Init函数 ////////////////////////////////////////////////////////////////////////////////// //通过改变TIM3->CCR2的值来改变占空比,从而控制LED0的亮度 #define LED0_PWM_VAL TIM3->CCR2 //TIM4 CH1作为PWM DAC的输出通道 #define PWM_DAC_VAL TIM4->CCR1 void TIM3_Int_Init(u16 arr,u16 psc); void TIM3_PWM_Init(u16 arr,u16 psc); void TIM5_Cap_Init(u16 arr,u16 psc); void TIM4_PWM_Init(u16 arr,u16 psc); void TIM6_Int_Init(u16 arr,u16 psc); #endif <file_sep>/USB/CONFIG/usb_desc.c /******************** xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ******************** * File Name : usb_desc.c * Author : * Version : * Date : * Description : Usb Camera Descriptors *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" #include "usb_desc.h" #include "sram.h" /* USB Standard Device Descriptor */ const u8 Camera_DeviceDescriptor[CAMERA_SIZ_DEVICE_DESC] = { CAMERA_SIZ_DEVICE_DESC, /* bLength */ USB_DEVICE_DESCRIPTOR_TYPE, /* bDescriptorType */ 0x00, 0x02, /* bcdUSB 2.10 */ 0xEF, /* bDeviceClass */ 0x02, /* bDeviceSubClass */ 0x01, /* bDeviceProtocol */ 0x40, /* bMaxPacketSize 40 */ 0x92, 0x19, /* idVendor = 0x1985*/ 0x01, 0x01, /* idProduct = 0x1017*/ 0x00, 0x01, /* bcdDevice */ 1, /* iManufacturer */ 2, /* iProduct */ 3, /* iSerialNumber */ 0x01 /* bNumConfigurations */ }; #ifdef CAMERA_FORMAT_MJPEG const u8 Camera_ConfigDescriptor[CAMERA_SIZ_CONFIG_DESC] = { /* Configuration Descriptor */ 0x09, /* bLength */ USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType */ CAMERA_SIZ_CONFIG_DESC, /* wTotalLength 0x90 bytes*/ 0x00, 0x02, /* bNumInterfaces */ 0x01, /* bConfigurationValue */ 0x00, /* iConfiguration */ 0x80, /* bmAttributes BUS Powred, no remote wakeup*/ 0xFA, /* bMaxPower = 500 mA*/ /* 09 byte, total size 9*/ /* 1. Standard Video Interface Collection IAD */ 0x08, /* bLength */ USB_ASSOCIATION_DESCRIPTOR_TYPE, /* bDescriptorType */ 0x00, /* bFirstInterface: Interface number of the VideoControl interface that is associated with this function*/ 0x02, /* Number of contiguous Video interfaces that are associated with this function */ 0x0E, /* bFunction Class: CC_VIDEO*/ 0x03, /* bFunction sub Class: SC_VIDEO_INTERFACE_COLLECTION */ 0x00, /* bFunction protocol : PC_PROTOCOL_UNDEFINED*/ 0x02, /* iFunction */ /* 08 bytes, total size 17*/ /* 1.1 Video control Interface Descriptor */ /* 1.1.1 Standard VideoControl Interface(VC) Descriptor */ 0x09, /* bLength */ 0x04, /* bDescriptorType */ 0x00, /* bInterfaceNumber */ 0x00, /* bAlternateSetting */ 0x00, /* bNumEndpoints:1 endpoint (interrupt endpoint) */ 0x0e, /* bInterfaceClass : CC_VIDEO */ 0x01, /* bInterfaceSubClass : SC_VIDEOCONTROL */ 0x00, /* bInterfaceProtocol : PC_PROTOCOL_UNDEFINED */ 0x02, /* iInterface:Index to string descriptor that contains the string <Your Product Name> */ /* 09 bytes, total size 26*/ /* 1.1.2 Class-specific VideoControl Interface Descriptor */ 0x0d, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x01, /* bDescriptorSubType : VC_HEADER subtype */ 0x10, 0x01, /* bcdUVC : Revision of class specification that this device is based upon. For this example, the device complies with Video Class specification version 1.1 */ 0x1e, 0x00, /* wTotalLength : 30 */ 0x80, 0x8d, 0x5b, 0x00, /* dwClockFrequency : 0x005b8d80 -> 6,000,000 == 6MHz*/ 0x01, /* bInCollection : Number of streaming interfaces. */ 0x01, /* baInterfaceNr(1) : VideoStreaming interface 1 belongs to this VideoControl interface.*/ /* 13 Bytes, totoal size 39 */ /* 1.1.3 Video Input Terminal Descriptor (Composite) */ 0x08, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x02, /* bDescriptorSubType : VC_INPUT_TERMINAL subtype */ 0x02, /* bTerminalID: ID of this input terminal */ 0x01, 0x04, /* wTerminalType: 0x0401 COMPOSITE_CONNECTOR type. This terminal is the composite connector. */ 0x00, /* bAssocTerminal: No association */ 0x00, /* iTerminal: Unused*/ /* 8 Bytes, totoal size 47 */ /* 1.1.4 Video Output Terminal Descriptor */ 0x09, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x03, /* bDescriptorSubType : VC_OUTPUT_TERMINAL subtype */ 0x03, /* bTerminalID: ID of this output terminal */ 0x01, 0x01, /* wTerminalType: 0x0101 TT_STREAMING type. This terminal is a USB streaming terminal. */ 0x00, /* bAssocTerminal: No association */ 0x02, /* bSourceID: The input pin of this unit is connected to the output pin of unit 2. */ 0x00, /* iTerminal: Unused*/ /* 9 bytes, total size 56 */ /* 1.2 Video Streaming Interface Descriptor */ /* 1.2.1 Operational Alternate Setting 0 */ /* 1.2.1.1 Standard VideoStream Interface Descriptor*/ 0x09, /* bLength */ 0x04, /* bDescriptorType : INTERFACE */ 0x01, /* bInterfaceNumber: Index of this interface */ 0x00, /* bAlternateSetting: Index of this alternate setting */ 0x00, /* bNumEndpoints : 0 endpoints – no bandwidth used*/ 0x0e, /* bInterfaceClass : CC_VIDEO */ 0x02, /* bInterfaceSubClass : SC_VIDEOSTREAMING */ 0x00, /* bInterfaceProtocol : PC_PROTOCOL_UNDEFINED */ 0x00, /* iInterface : unused */ /* 9 bytes, total size 65 */ /* 1.2.1.2 Class-specific VideoStream Header Descriptor (Input) */ 0x0e, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x01, /* bDescriptorSubType : VC_HEADER subtype */ 0x01, /* bNumFormats : One format descriptor follows. */ 0x3f, 0x00, /* wTotalLength :63 */ 0x81, /* bEndpointAddress : 0x81 */ 0x00, /* bmInfo : No dynamic format change supported. */ 0x03, /* bTerminalLink : This VideoStreaming interface supplies terminal ID 3 (Output Terminal). */ 0x00, /* bStillCaptureMethod : Device supports still image capture method 0. */ 0x00, /* bTriggerSupport : Hardware trigger supported for still image capture */ 0x00, /* bTriggerUsage : Hardware trigger should initiate a still image capture. */ 0x01, /* bControlSize : Size of the bmaControls field */ 0x00, /* bmaControls : No VideoStreaming specific controls are supported.*/ /* 14 Bytes, totoal size 79 */ /* 1.2.1.3 Class-specific VideoStream Format(MJPEG) Descriptor */ 0x0b, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ VS_FORMAT_MJPEG, /* bDescriptorSubType : VS_FORMAT_MJPEG subtype */ 0x01, /* bFormatIndex : First (and only) format descriptor */ 0x01, /* bNumFrameDescriptors : One frame descriptor for this format follows. */ 0x01, /* bmFlags : Uses fixed size samples.. */ 0x01, /* bDefaultFrameIndex : Default frame index is 1. */ 0x00, /* bAspectRatioX : Non-interlaced stream – not required. */ 0x00, /* bAspectRatioY : Non-interlaced stream – not required. */ 0x00, /* bmInterlaceFlags : Non-interlaced stream */ 0x00, /* bCopyProtect : No restrictions imposed on the duplication of this video stream. */ /* 11 bytes, total size 90 */ /* 1.2.1.4 Class-specific VideoStream Frame Descriptor */ 0x26, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x07, /* bDescriptorSubType : VS_FRAME_MJPEG */ 0x01, /* bFrameIndex : First (and only) frame descriptor */ 0x02, /* bmCapabilities : Still images using capture method 0 are supported at this frame setting.D1: Fixed frame-rate. */ MAKE_WORD((IMG_WIDTH / IMG_VIDEO_SCALE)), /* wWidth : Width of frame, pixels. */ MAKE_WORD((IMG_HEIGHT / IMG_VIDEO_SCALE)), /* wHeight : Height of frame, pixels. */ MAKE_DWORD(MIN_BIT_RATE), /* dwMinBitRate : Min bit rate in bits/s */ MAKE_DWORD(MAX_BIT_RATE), /* dwMaxBitRate : Max bit rate in bits/s */ MAKE_DWORD(MAX_FRAME_SIZE), /* dwMaxVideoFrameBufSize : Maximum video or still frame size, in bytes. */ MAKE_DWORD(FRAME_INTERVEL), /* dwDefaultFrame Interval time, unit=100ns */ 0x00, /* bFrameIntervalType : Continuous frame interval */ MAKE_DWORD(FRAME_INTERVEL), /* dwMinFrameInterval: dwDefaultFrame Interval time, unit=100ns */ MAKE_DWORD(FRAME_INTERVEL), /* dwMaxFrameInterval: dwDefaultFrame Interval time, unit=100ns */ 0x00, 0x00, 0x00, 0x00, /* dwFrameIntervalStep : No frame interval step supported. */ /* 38 bytes, total size 128 */ /* 1.2.2 Operational Alternate Setting 1 */ /* 1.2.2.1 Standard VideoStream Interface Descriptor */ 0x09, /* bLength */ 0x04, /* bDescriptorType: INTERFACE descriptor type */ 0x01, /* bInterfaceNumber: Index of this interface */ 0x01, /* bAlternateSetting: Index of this alternate setting */ 0x01, /* bNumEndpoints: endpoints, 1 – data endpoint */ 0x0e, /* bInterfaceClass: CC_VIDEO */ 0x02, /* bInterfaceSubClass: SC_VIDEOSTREAMING */ 0x00, /* bInterfaceProtocol: PC_PROTOCOL_UNDEFINED */ 0x00, /* iInterface: Unused */ /* 9 bytes, total size 137 */ /* 1.2.2.2 Standard VideoStream Isochronous Video Data Endpoint Descriptor */ 0x07, /* bLength */ 0x05, /* bDescriptorType: ENDPOINT */ 0x81, /* bEndpointAddress: IN endpoint 1 */ 0x05, /* bmAttributes: Isochronous transfer type. Asynchronous synchronization type. */ MAKE_WORD(PACKET_SIZE), /* wMaxPacketSize: Max packet size, in bytes */ 0x01 /* bInterval: One frame interval (主机发送IN轮询包时间间隔,单位1ms,参考USB_Video_Class_1.1文档3.10.1.1节 ) */ /* 7 bytes, total size 144 */ }; #endif #ifdef CAMERA_FORMAT_UNCOMPRESSED const u8 Camera_ConfigDescriptor[CAMERA_SIZ_CONFIG_DESC] = { /* Configuration Descriptor */ 0x09, /* bLength */ USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType */ CAMERA_SIZ_CONFIG_DESC, /* wTotalLength 0x90 bytes*/ 0x00, 0x02, /* bNumInterfaces */ 0x01, /* bConfigurationValue */ 0x00, /* iConfiguration */ 0x80, /* bmAttributes BUS Powred, no remote wakeup*/ 0xFA, /* bMaxPower = 500 mA*/ /* 09 byte, total size 9*/ /* 1. Standard Video Interface Collection IAD */ 0x08, /* bLength */ USB_ASSOCIATION_DESCRIPTOR_TYPE, /* bDescriptorType */ 0x00, /* bFirstInterface: Interface number of the VideoControl interface that is associated with this function*/ 0x02, /* Number of contiguous Video interfaces that are associated with this function */ 0x0E, /* bFunction Class: CC_VIDEO*/ 0x03, /* bFunction sub Class: SC_VIDEO_INTERFACE_COLLECTION */ 0x00, /* bFunction protocol : PC_PROTOCOL_UNDEFINED*/ 0x02, /* iFunction */ /* 08 bytes, total size 17*/ /* 1.1 Video control Interface Descriptor */ /* 1.1.1 Standard VideoControl Interface(VC) Descriptor */ 0x09, /* bLength */ 0x04, /* bDescriptorType */ 0x00, /* bInterfaceNumber */ 0x00, /* bAlternateSetting */ 0x00, /* bNumEndpoints:1 endpoint (interrupt endpoint) */ 0x0e, /* bInterfaceClass : CC_VIDEO */ 0x01, /* bInterfaceSubClass : SC_VIDEOCONTROL */ 0x00, /* bInterfaceProtocol : PC_PROTOCOL_UNDEFINED */ 0x02, /* iInterface:Index to string descriptor that contains the string <Your Product Name> */ /* 09 bytes, total size 26*/ /* 1.1.2 Class-specific VideoControl Interface Descriptor */ 0x0d, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x01, /* bDescriptorSubType : VC_HEADER subtype */ 0x10, 0x01, /* bcdUVC : Revision of class specification that this device is based upon. For this example, the device complies with Video Class specification version 1.1 */ 0x1e, 0x00, /* wTotalLength : 30 */ 0x80, 0x8d, 0x5b, 0x00, /* dwClockFrequency : 0x005b8d80 -> 6,000,000 == 6MHz*/ 0x01, /* bInCollection : Number of streaming interfaces. */ 0x01, /* baInterfaceNr(1) : VideoStreaming interface 1 belongs to this VideoControl interface.*/ /* 13 Bytes, totoal size 39 */ /* 1.1.3 Video Input Terminal Descriptor (Composite) */ 0x08, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x02, /* bDescriptorSubType : VC_INPUT_TERMINAL subtype */ 0x02, /* bTerminalID: ID of this input terminal */ 0x01, 0x04, /* wTerminalType: 0x0401 COMPOSITE_CONNECTOR type. This terminal is the composite connector. */ 0x00, /* bAssocTerminal: No association */ 0x00, /* iTerminal: Unused*/ /* 8 Bytes, totoal size 47 */ /* 1.1.4 Video Output Terminal Descriptor */ 0x09, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x03, /* bDescriptorSubType : VC_OUTPUT_TERMINAL subtype */ 0x03, /* bTerminalID: ID of this output terminal */ 0x01, 0x01, /* wTerminalType: 0x0101 TT_STREAMING type. This terminal is a USB streaming terminal. */ 0x00, /* bAssocTerminal: No association */ 0x02, /* bSourceID: The input pin of this unit is connected to the output pin of unit 2. */ 0x00, /* iTerminal: Unused*/ /* 9 bytes, total size 56 */ /* 1.2 Video Streaming Interface Descriptor */ /* 1.2.1 Operational Alternate Setting 0 */ /* 1.2.1.1 Standard VideoStream Interface Descriptor*/ 0x09, /* bLength */ 0x04, /* bDescriptorType : INTERFACE */ 0x01, /* bInterfaceNumber: Index of this interface */ 0x00, /* bAlternateSetting: Index of this alternate setting */ 0x00, /* bNumEndpoints : 0 endpoints – no bandwidth used*/ 0x0e, /* bInterfaceClass : CC_VIDEO */ 0x02, /* bInterfaceSubClass : SC_VIDEOSTREAMING */ 0x00, /* bInterfaceProtocol : PC_PROTOCOL_UNDEFINED */ 0x00, /* iInterface : unused */ /* 9 bytes, total size 65 */ /* 1.2.1.2 Class-specific VideoStream Header Descriptor (Input) */ 0x0e, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ 0x01, /* bDescriptorSubType : VC_HEADER subtype */ 0x01, /* bNumFormats : One format descriptor follows. */ 0x4f, 0x00, /* wTotalLength :79 */ 0x81, /* bEndpointAddress : 0x81 */ 0x00, /* bmInfo : No dynamic format change supported. */ 0x03, /* bTerminalLink : This VideoStreaming interface supplies terminal ID 3 (Output Terminal). */ 0x00, /* bStillCaptureMethod : Device supports still image capture method 0. */ 0x00, /* bTriggerSupport : Hardware trigger supported for still image capture */ 0x00, /* bTriggerUsage : Hardware trigger should initiate a still image capture. */ 0x01, /* bControlSize : Size of the bmaControls field */ 0x00, /* bmaControls : No VideoStreaming specific controls are supported.*/ /* 14 Bytes, totoal size 79 */ /* 1.2.1.3 Class-specific VideoStream Format(MJPEG) Descriptor */ 0x1b, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ VS_FORMAT_UNCOMPRESSED, /* bDescriptorSubType : VS_FORMAT_UNCOMPRESSED subtype */ 0x01, /* bFormatIndex : First (and only) format descriptor */ 0x01, /* bNumFrameDescriptors : One frame descriptor for this format follows. */ YUV422, /* guidFormat: YUY2 */ YUV_BITS_PER_PIX, /* bBitsPerPixel: 16 */ 0x01, /* bDefaultFrameIndex : Default frame index is 1. */ 0x00, /* bAspectRatioX : Non-interlaced stream – not required. */ 0x00, /* bAspectRatioY : Non-interlaced stream – not required. */ 0x00, /* bmInterlaceFlags : Non-interlaced stream */ 0x00, /* bCopyProtect : No restrictions imposed on the duplication of this video stream. */ /* 27 bytes, total size 106 */ /* 1.2.1.4 Class-specific VideoStream Frame Descriptor */ 0x26, /* bLength */ 0x24, /* bDescriptorType : CS_INTERFACE */ VS_FRAME_UNCOMPRESSED, /* bDescriptorSubType : VS_FRAME_UNCOMPRESSED */ 0x01, /* bFrameIndex : First (and only) frame descriptor */ 0x02, /* bmCapabilities : Still images using capture method 0 are supported at this frame setting.D1: Fixed frame-rate. */ MAKE_WORD((IMG_WIDTH / IMG_VIDEO_SCALE)), /* wWidth : Width of frame, pixels. */ MAKE_WORD((IMG_HEIGHT / IMG_VIDEO_SCALE)), /* wHeight : Height of frame, pixels. */ MAKE_DWORD(MIN_BIT_RATE), /* dwMinBitRate : Min bit rate in bits/s */ MAKE_DWORD(MAX_BIT_RATE), /* dwMaxBitRate : Max bit rate in bits/s */ MAKE_DWORD(MAX_FRAME_SIZE), /* dwMaxVideoFrameBufSize : Maximum video or still frame size, in bytes. */ MAKE_DWORD(FRAME_INTERVEL), /* dwDefaultFrame Interval time, unit=100ns */ 0x00, /* bFrameIntervalType : Continuous frame interval */ MAKE_DWORD(FRAME_INTERVEL), /* dwMinFrameInterval: dwDefaultFrame Interval time, unit=100ns */ MAKE_DWORD(FRAME_INTERVEL), /* dwMaxFrameInterval: dwDefaultFrame Interval time, unit=100ns */ 0x00, 0x00, 0x00, 0x00, /* dwFrameIntervalStep : No frame interval step supported. */ /* 38 bytes, total size 144 */ /* 1.2.2 Operational Alternate Setting 1 */ /* 1.2.2.1 Standard VideoStream Interface Descriptor */ 0x09, /* bLength */ 0x04, /* bDescriptorType: INTERFACE descriptor type */ 0x01, /* bInterfaceNumber: Index of this interface */ 0x01, /* bAlternateSetting: Index of this alternate setting */ 0x01, /* bNumEndpoints: endpoints, 1 – data endpoint */ 0x0e, /* bInterfaceClass: CC_VIDEO */ 0x02, /* bInterfaceSubClass: SC_VIDEOSTREAMING */ 0x00, /* bInterfaceProtocol: PC_PROTOCOL_UNDEFINED */ 0x00, /* iInterface: Unused */ /* 9 bytes, total size 153 */ /* 1.2.2.2 Standard VideoStream Isochronous Video Data Endpoint Descriptor */ 0x07, /* bLength */ 0x05, /* bDescriptorType: ENDPOINT */ 0x81, /* bEndpointAddress: IN endpoint 1 */ 0x05, /* bmAttributes: Isochronous transfer type. Asynchronous synchronization type. */ MAKE_WORD(PACKET_SIZE), /* wMaxPacketSize: Max packet size, in bytes */ 0x01 /* bInterval: One frame interval */ /* 7 bytes, total size 160 */ }; #endif /* USB String Descriptors */ const u8 Camera_StringLangID[CAMERA_SIZ_STRING_LANGID] = { CAMERA_SIZ_STRING_LANGID, USB_STRING_DESCRIPTOR_TYPE, 0x09, 0x04 /* LangID = 0x0409: U.S. English */ }; const u8 Camera_StringVendor[CAMERA_SIZ_STRING_VENDOR] = { CAMERA_SIZ_STRING_VENDOR, /* Size of Vendor string */ USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType*/ /* Manufacturer: */ 'W', 0, 'a', 0, 'h', 0, 'a', 0, 'h', 0, 'a', 0 }; const u8 Camera_StringProduct[CAMERA_SIZ_STRING_PRODUCT] = { CAMERA_SIZ_STRING_PRODUCT, /* bLength */ USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */ /* Product name: */ 'W', 0, 'a', 0, 'h', 0, 'a', 0, 'h', 0, 'a', 0, 'W', 0, 'e', 0, 'b', 0, 'c', 0, 'a', 0, 'm', 0 }; u8 Camera_StringSerial[CAMERA_SIZ_STRING_SERIAL] = { CAMERA_SIZ_STRING_SERIAL, /* bLength */ USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */ /* 序列号 */ '1', 0, '.', 0, '1', 0 }; /************************END OF FILE***************************************/ <file_sep>/USB/CONFIG/hw_config.c /******************** (C) COPYRIGHT 2008 STMicroelectronics ******************** * File Name : hw_config.c * Author : MCD Application Team * Version : V2.2.0 * Date : 06/13/2008 * Description : Hardware Configuration & Setup ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "sys.h" #include "hw_config.h" #include "usb_lib.h" #include "usb_desc.h" #include "platform_config.h" #include "usb_pwr.h" #include "lcd.h" #include "ov7670.h" #include "sram.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ //配置USB时钟,USBclk=48Mhz void Set_USBClock(void) { RCC->CFGR &= ~(1 << 22); //USBclk=PLLclk/1.5=48Mhz RCC->APB1ENR |= 1 << 23; //USB时钟使能 } /******************************************************************************* * Function Name : Enter_LowPowerMode. * Description : Power-off system clocks and power while entering suspend mode. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Enter_LowPowerMode(void) { /* Set the device state to suspend */ bDeviceState = SUSPENDED; /* Request to enter STOP mode with regulator in low power mode */ //PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI); } /******************************************************************************* * Function Name : Leave_LowPowerMode. * Description : Restores system clocks and power while exiting suspend mode. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Leave_LowPowerMode(void) { DEVICE_INFO *pInfo = &Device_Info; /* Set the device state to the correct state */ if (pInfo->Current_Configuration != 0) { /* Device configured */ bDeviceState = CONFIGURED; } else { bDeviceState = ATTACHED; } } //USB中断配置 void USB_Interrupts_Config(void) { EXTI->IMR |= 1 << 18;// 开启线18上的中断 EXTI->RTSR |= 1 << 18;//line 18上事件上升降沿触发 MY_NVIC_Init(1, 0, USB_LP_CAN1_RX0_IRQn, 2);//组2,优先级次之 MY_NVIC_Init(0, 0, USBWakeUp_IRQn, 2); //组2,优先级最高 } extern u8 SPSCount; // timer.c中定义 #define CAMERA_SIZ_STREAMHD 2 // PAYLOAD Header Size u32 sendsize; // 已发送字节数 u8 packetbuf[PACKET_SIZE] = { 0x02, 0x01, 0x0 }; // 数据包缓冲区 OV_BUF* povbuf; // 正在发送的JPG缓冲区 void myMemcpy(const u8* src, u8* dst, u32 bsize) { u32 i = 0; for (i = 0; i < bsize; ++i) dst[i] = src[i]; } /******************************************************************************* * Function Name : UsbCamera_Fillbuf * Description : 准备待发送的视频流缓冲区 * Input : * Output : * Return : *******************************************************************************/ void UsbCamera_Fillbuf(void) { u32 datalen = 0; // 本次发送字节数 if (0 == sendsize) // 图像首包 { if (ovbuf0.sta) { povbuf = &ovbuf0; } else if (ovbuf1.sta){ povbuf = &ovbuf1; } else{ return; } // 初始化PayloadDataHeaderr packetbuf[1] &= 0x01; // 清除BFH packetbuf[1] ^= 0x01; // 切换FID // 读取发送数据 datalen = PACKET_SIZE - CAMERA_SIZ_STREAMHD; FSMC_SRAM_ReadBuffer(packetbuf + CAMERA_SIZ_STREAMHD, povbuf->addr, datalen); sendsize = datalen; datalen += CAMERA_SIZ_STREAMHD; } else{ // 图像后续包 datalen = PACKET_SIZE - CAMERA_SIZ_STREAMHD; // 判断是否为最后一包 if (sendsize + datalen > povbuf->bsize) { datalen = povbuf->bsize - sendsize; packetbuf[1] |= 0x02; // EOF置位 } // 读取发送数据 FSMC_SRAM_ReadBuffer(packetbuf + CAMERA_SIZ_STREAMHD, povbuf->addr + sendsize, datalen); sendsize += datalen; datalen += CAMERA_SIZ_STREAMHD; } // 复制数据到PMA if (_GetENDPOINT(ENDP1) & EP_DTOG_TX) { // User use buffer0 UserToPMABufferCopy(packetbuf, ENDP1_BUF0Addr, datalen); SetEPDblBuf0Count(ENDP1, EP_DBUF_IN, datalen); } else{ // User use buffer1 UserToPMABufferCopy(packetbuf, ENDP1_BUF1Addr, datalen); SetEPDblBuf1Count(ENDP1, EP_DBUF_IN, datalen); } _ToggleDTOG_TX(ENDP1); // 反转DTOG_TX _SetEPTxStatus(ENDP1, EP_TX_VALID); // 允许数据发送 if (sendsize >= povbuf->bsize) { povbuf->sta = 0; ++SPSCount; sendsize = 0; } return; } /******************************************************************************* * Function Name : Get_SerialNum. * Description : Create the serial number string descriptor. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Get_SerialNum(void) { u32 Device_Serial0, Device_Serial1, Device_Serial2; Device_Serial0 = *(u32*)(0x1FFFF7E8); Device_Serial1 = *(u32*)(0x1FFFF7EC); Device_Serial2 = *(u32*)(0x1FFFF7F0); if (Device_Serial0 != 0) { Camera_StringSerial[2] = (u8)(Device_Serial0 & 0x000000FF); Camera_StringSerial[4] = (u8)((Device_Serial0 & 0x0000FF00) >> 8); Camera_StringSerial[6] = (u8)((Device_Serial0 & 0x00FF0000) >> 16); Camera_StringSerial[8] = (u8)((Device_Serial0 & 0xFF000000) >> 24); Camera_StringSerial[10] = (u8)(Device_Serial1 & 0x000000FF); Camera_StringSerial[12] = (u8)((Device_Serial1 & 0x0000FF00) >> 8); Camera_StringSerial[14] = (u8)((Device_Serial1 & 0x00FF0000) >> 16); Camera_StringSerial[16] = (u8)((Device_Serial1 & 0xFF000000) >> 24); Camera_StringSerial[18] = (u8)(Device_Serial2 & 0x000000FF); Camera_StringSerial[20] = (u8)((Device_Serial2 & 0x0000FF00) >> 8); Camera_StringSerial[22] = (u8)((Device_Serial2 & 0x00FF0000) >> 16); Camera_StringSerial[24] = (u8)((Device_Serial2 & 0xFF000000) >> 24); } } /******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/ <file_sep>/USB/CONFIG/usb_desc.h /******************** (C) COPYRIGHT 2008 STMicroelectronics ******************** * File Name : usb_desc.h * Author : MCD Application Team * Version : V2.2.1 * Date : 09/22/2008 * Description : Descriptor Header for Virtual COM Port Device ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_DESC_H #define __USB_DESC_H /* Includes ------------------------------------------------------------------*/ #include "usb_type.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ #define UNCOMPRESS 0 #define MAKE_WORD(x) (u8)((x)&0xFF),(u8)(((x)>>8)&0xFF) #define MAKE_DWORD(x) (u8)((x)&0xFF),(u8)(((x)>>8)&0xFF),(u8)(((x)>>16)&0xFF),(u8)(((x)>>24)&0xFF) /* Exported define -----------------------------------------------------------*/ //#define CAMERA_FORMAT_MJPEG // 定义此宏使用JPEG视频流 #define CAMERA_FORMAT_UNCOMPRESSED // 定义此宏使用未压缩的视频流 // Video Descriptor Types(描述符类型) #define USB_DEVICE_DESCRIPTOR_TYPE 0x01 // DEVICE #define USB_CONFIGURATION_DESCRIPTOR_TYPE 0x02 // CONFIGRATION #define USB_STRING_DESCRIPTOR_TYPE 0x03 // STRING #define USB_INTERFACE_DESCRIPTOR_TYPE 0x04 // INTERFACE #define USB_ENDPOINT_DESCRIPTOR_TYPE 0x05 // EP #define USB_ASSOCIATION_DESCRIPTOR_TYPE 0x0B // IAD // Video String Descriptor Size(字符描述符大小) #define CAMERA_SIZ_DEVICE_DESC 18 #define CAMERA_SIZ_STRING_LANGID 4 #define CAMERA_SIZ_STRING_VENDOR 14 #define CAMERA_SIZ_STRING_PRODUCT 26 #define CAMERA_SIZ_STRING_SERIAL 26 // Video Class-Specific VS Interface Descriptor Subtypes(视频流类型) #define VS_FORMAT_UNCOMPRESSED 0x04 #define VS_FRAME_UNCOMPRESSED 0x05 #define VS_FORMAT_MJPEG 0x06 // YUV Format(GUID used to identify stream-encoding format, 16 Bytes) #define YUV422 0x59,0x55,0x59,0x32,\ 0x00,0x00,\ 0x10,0x00,\ 0x80, 0x00,\ 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 #define YUY2 YUV422 // GUID: 32595559-0000-0010-8000-00AA00389B71 #define YUV420 0x4e, 0x56, 0x31, 0x32,\ 0x00,0x00,\ 0x10, 0x00,\ 0x80,0x00,\ 0x00,0xaa,0x00,0x38,0x9b,0x71 #define NV12 YUV420 // GUID:3231564E-0000-0010-8000-00AA00389B71 #define YUV_BITS_PER_PIX 0x10 #ifdef CAMERA_FORMAT_MJPEG // MJPEG视频流帧率,带宽控制(15帧/s) #define IMG_WIDTH 640 #define IMG_HEIGHT 480 #define IMG_VIDEO_SCALE 2 // MJPEG size = IMG_WIDTH / IMG_VIDEO_SCALE #define IMG_MJPG_FRAMERATE 15 // 预定义MJPEG视频帧率 #define MIN_BIT_RATE (20*1024*IMG_MJPG_FRAMERATE) #define MAX_BIT_RATE (500*1024*IMG_MJPG_FRAMERATE) #define MAX_FRAME_SIZE (200*1024) // 每帧最大字节数,对应Host要求的Buffer Size #define FRAME_INTERVEL (10000000ul/IMG_MJPG_FRAMERATE) // 帧间间隔时间,单位100ns #define PACKET_SIZE 0xB0 // 176 #endif #ifdef CAMERA_FORMAT_UNCOMPRESSED // UNCOMPRESSED视频流帧率,带宽控制(5帧/s) #define IMG_WIDTH 640 #define IMG_HEIGHT 480 #define IMG_VIDEO_SCALE 2 // MJPEG size = IMG_WIDTH / IMG_VIDEO_SCALE #define IMG_UNCOMP_FRAMERATE 15 // 预定义MJPEG视频帧率 #define MIN_BIT_RATE (20*1024*IMG_UNCOMP_FRAMERATE) // 每帧最小字节*帧率 #define MAX_BIT_RATE (400*1024*IMG_UNCOMP_FRAMERATE) // 每帧最大字节*帧率 #define MAX_FRAME_SIZE (200*1024) // 最大每帧字节数,对应Host要求的Buffer Size #define FRAME_INTERVEL (10000000ul/IMG_UNCOMP_FRAMERATE) // 帧间间隔时间,单位100ns #define PACKET_SIZE 0xB0 // 176 #endif /* Exported functions ------------------------------------------------------- */ extern const u8 Camera_DeviceDescriptor[CAMERA_SIZ_DEVICE_DESC]; #ifdef CAMERA_FORMAT_MJPEG #define CAMERA_SIZ_CONFIG_DESC 144 extern const u8 Camera_ConfigDescriptor[CAMERA_SIZ_CONFIG_DESC]; // MPEG视频流使用的配置描述符 #endif #ifdef CAMERA_FORMAT_UNCOMPRESSED #define CAMERA_SIZ_CONFIG_DESC 160 extern const u8 Camera_ConfigDescriptor[CAMERA_SIZ_CONFIG_DESC]; // UNCOMPRESSED视频流使用的描述符 #endif extern const u8 Camera_StringLangID[CAMERA_SIZ_STRING_LANGID]; extern const u8 Camera_StringVendor[CAMERA_SIZ_STRING_VENDOR]; extern const u8 Camera_StringProduct[CAMERA_SIZ_STRING_PRODUCT]; extern u8 Camera_StringSerial[CAMERA_SIZ_STRING_SERIAL]; #endif /* __USB_DESC_H */ /******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/ <file_sep>/HARDWARE/SRAM/sram.c #include "sram.h" //#include "usart.h" ////////////////////////////////////////////////////////////////////////////////// //本程序只供学习使用,未经作者许可,不得用于其它任何用途 //ALIENTEK战舰STM32开发板 //外部SRAM 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/16 //版本:V1.0 //版权所有,盗版必究。 //Copyright(C) 广州市星翼电子科技有限公司 2009-2019 //All rights reserved ////////////////////////////////////////////////////////////////////////////////// //使用NOR/SRAM的 Bank1.sector3,地址位HADDR[27,26]=10 //对IS61LV25616/IS62WV25616,地址线范围为A0~A17 //对IS61LV51216/IS62WV51216,地址线范围为A0~A18 #define Bank1_SRAM3_ADDR ((u32)(0x68000000)) //初始化外部SRAM void FSMC_SRAM_Init(void) { RCC->AHBENR |= 1 << 8; //使能FSMC时钟 RCC->APB2ENR |= 1 << 5; //使能PORTD时钟 RCC->APB2ENR |= 1 << 6; //使能PORTE时钟 RCC->APB2ENR |= 1 << 7; //使能PORTF时钟 RCC->APB2ENR |= 1 << 8; //使能PORTG时钟 //PORTD复用推挽输出 GPIOD->CRH &= 0X00000000; GPIOD->CRH |= 0XBBBBBBBB; GPIOD->CRL &= 0XFF00FF00; GPIOD->CRL |= 0X00BB00BB; //PORTE复用推挽输出 GPIOE->CRH &= 0X00000000; GPIOE->CRH |= 0XBBBBBBBB; GPIOE->CRL &= 0X0FFFFF00; GPIOE->CRL |= 0XB00000BB; //PORTF复用推挽输出 GPIOF->CRH &= 0X0000FFFF; GPIOF->CRH |= 0XBBBB0000; GPIOF->CRL &= 0XFF000000; GPIOF->CRL |= 0X00BBBBBB; //PORTG复用推挽输出 PG10->NE3 GPIOG->CRH &= 0XFFFFF0FF; GPIOG->CRH |= 0X00000B00; GPIOG->CRL &= 0XFF000000; GPIOG->CRL |= 0X00BBBBBB; //寄存器清零 //bank1有NE1~4,每一个有一个BCR+TCR,所以总共八个寄存器。 //这里我们使用NE3 ,也就对应BTCR[4],[5]。 FSMC_Bank1->BTCR[4] = 0X00000000; FSMC_Bank1->BTCR[5] = 0X00000000; FSMC_Bank1E->BWTR[4] = 0X00000000; //操作BCR寄存器 使用异步模式,模式A(读写共用一个时序寄存器) //BTCR[偶数]:BCR寄存器;BTCR[奇数]:BTR寄存器 FSMC_Bank1->BTCR[4] |= 1 << 12;//存储器写使能 FSMC_Bank1->BTCR[4] |= 1 << 4; //存储器数据宽度为16bit //操作BTR寄存器 FSMC_Bank1->BTCR[5] |= 3 << 8; //数据保持时间(DATAST)为3个HCLK 4/72M=55ns(对EM的SRAM芯片) FSMC_Bank1->BTCR[5] |= 0 << 4; //地址保持时间(ADDHLD)未用到 FSMC_Bank1->BTCR[5] |= 0 << 0; //地址建立时间(ADDSET)为2个HCLK 1/36M=27ns //闪存写时序寄存器 FSMC_Bank1E->BWTR[4] = 0x0FFFFFFF;//默认值 //使能BANK1区域3 FSMC_Bank1->BTCR[4] |= 1 << 0; } //在指定地址(WriteAddr+Bank1_SRAM3_ADDR)开始,连续写入n个字节. //pBuffer:字节指针 //WriteAddr:要写入的地址 //n:要写入的字节数 void FSMC_SRAM_WriteBuffer(u8* pBuffer, u32 WriteAddr, u32 n) { for (; n != 0; n--) { *(vu8*)(Bank1_SRAM3_ADDR + WriteAddr) = *pBuffer; WriteAddr++; pBuffer++; } } //在指定地址((WriteAddr+Bank1_SRAM3_ADDR))开始,连续读出n个字节. //pBuffer:字节指针 //ReadAddr:要读出的起始地址 //n:要写入的字节数 void FSMC_SRAM_ReadBuffer(u8* pBuffer, u32 ReadAddr, u32 n) { for (; n != 0; n--) { *pBuffer++ = *(vu8*)(Bank1_SRAM3_ADDR + ReadAddr); ReadAddr++; } } <file_sep>/USB/CONFIG/usb_prop.h /******************** (C) COPYRIGHT 2008 STMicroelectronics ******************** * File Name : usb_prop.h * Author : MCD Application Team * Version : V2.2.1 * Date : 09/22/2008 * Description : All processing related to Virtual COM Port Demo (Endpoint 0) ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __usb_prop_H #define __usb_prop_H /* Includes ------------------------------------------------------------------*/ #include "usb_type.h" #include "usb_core.h" /* Exported types ------------------------------------------------------------*/ typedef struct { u32 bitrate; u8 format; u8 paritytype; u8 datatype; }LINE_CODING; /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported define -----------------------------------------------------------*/ #define UsbCamera_GetConfiguration NOP_Process //#define UsbCamera_SetConfiguration NOP_Process #define UsbCamera_GetInterface NOP_Process #define UsbCamera_SetInterface NOP_Process #define UsbCamera_GetStatus NOP_Process #define UsbCamera_ClearFeature NOP_Process #define UsbCamera_SetEndPointFeature NOP_Process #define UsbCamera_SetDeviceFeature NOP_Process //#define UsbCamera_SetDeviceAddress NOP_Process #define GET_CUR 0x81 #define SET_CUR 0x01 #define SET_INTERFACE 0x0b #define REPORT_DESCRIPTOR 0x22 /* Exported functions ------------------------------------------------------- */ void UsbCamera_init(void); void UsbCamera_Reset(void); void UsbCamera_SetConfiguration(void); void UsbCamera_SetDeviceAddress(void); void UsbCamera_Status_In(void); void UsbCamera_Status_Out(void); RESULT UsbCamera_Data_Setup(u8); RESULT UsbCamera_NoData_Setup(u8); RESULT UsbCamera_Get_Interface_Setting(u8 Interface, u8 AlternateSetting); u8 *UsbCamera_GetDeviceDescriptor(u16); u8 *UsbCamera_GetConfigDescriptor(u16); u8 *UsbCamera_GetStringDescriptor(u16); u8* VideoCommitControl_Command(u16 Length); u8* VideoProbeControl_Command(u16 Length); #endif /* __usb_prop_H */ /******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/ <file_sep>/USB/CONFIG/usb_pwr.h /******************** (C) COPYRIGHT 2008 STMicroelectronics ******************** * File Name : usb_pwr.h * Author : MCD Application Team * Version : V2.2.0 * Date : 06/13/2008 * Description : Connection/disconnection & power management header ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_PWR_H #define __USB_PWR_H #include "usb_type.h" #include "usb_core.h" /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ typedef enum _RESUME_STATE { RESUME_EXTERNAL, RESUME_INTERNAL, RESUME_LATER, RESUME_WAIT, RESUME_START, RESUME_ON, RESUME_OFF, RESUME_ESOF } RESUME_STATE; //1、接入态(Attached):全 / 高速设备D + 引脚外接1.5k上拉电阻,低速设备D - 引脚外接1.5k上拉电阻,设备接入主机后,主机通过检测信号线上的电平变化来发现设备的接入,并获取设备速度; //2、供电态(Powered):就是给设备供电,分为设备接入时的默认供电值,配置阶段后的供电值(按数据中要求的最大值,可通过编程设置) //3、缺省态(Default):USB在被配置之前,通过缺省地址0与主机进行通信; //4、地址态(Address):经过了配置,USB设备被复位后,就可以按主机分配给它的唯一地址来与主机通信,这种状态就是地址态; //5、配置态(Configured):通过各种标准的USB请求命令来获取设备的各种信息,并对设备的某此信息进行改变或设置。 //6、挂起态(Suspended):总线供电设备在3ms内没有总线动作,即USB总线处于空闲状态的话,该设备就要自动进入挂起状态,在进入挂起状态后,总的电流功耗不超过280UA。 typedef enum _DEVICE_STATE { UNCONNECTED, // ATTACHED, // 接入态 POWERED, // 供电态 SUSPENDED, // 挂起态 ADDRESSED, // 地址态 CONFIGURED // 配置态 } DEVICE_STATE; /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void Suspend (void); void Resume_Init (void); void Resume (RESUME_STATE eResumeSetVal); RESULT PowerOn (void); RESULT PowerOff (void); /* External variables --------------------------------------------------------*/ extern vu32 bDeviceState; /* USB device status */ extern volatile u8 fSuspendEnabled; /* true when suspend is possible */ #endif /*__USB_PWR_H*/ /******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/ <file_sep>/HARDWARE/OV7670/ov7670.h #ifndef _OV7670_H #define _OV7670_H #include "sys.h" #include "sccb.h" ////////////////////////////////////////////////////////////////////////// //本程序参考自网友guanfu_wang代码。 //ALIENTEK战舰STM32开发板 //OV7670 驱动代码 //正点原子@ALIENTEK //技术论坛:www.openedv.com //修改日期:2012/9/14 //版本:V1.0 ////////////////////////////////////////////////////////////////////////// #define OV7670_VSYNC PAin(8) // 同步信号检测IO #define OV7670_WRST PDout(6) // 写指针复位 #define OV7670_WREN PBout(3) // 写入FIFO使能 #define OV7670_RCK PBout(4) // 读数据时钟 #define OV7670_RRST PGout(14) // 读指针复位 #define OV7670_CS PGout(15) // 片选信号(OE) #define OV7670_DATA GPIOC->IDR&0x00FF //数据输入端口 ////////////////////////////////////////////////////////////////////////// #define OV_MAXBUF 320 * 240 * 2 extern const u32 ov_maxbuf; typedef struct _OV_BUF { u32 addr; u32 bsize; u8 sta; // 可读? } OV_BUF, *POV_BUF; // 频率计数 extern u8 OV0_FPS; // timer.c中定义 extern u8 FPS0Count; // timer.c中定义 extern u8 USB_SPS; // timer.c中定义 extern u8 SPSCount; // timer.c中定义 // #0摄像头缓冲区 extern OV_BUF ovbuf0; extern OV_BUF ovbuf1; extern u8 ov0_sta; ////////////////////////////////////////////////////////////////////////// u8 OV7670_Init (void); void OV7670_Light_Mode (u8 mode); void OV7670_Color_Saturation (u8 sat); void OV7670_Brightness (u8 bright); void OV7670_Contrast (u8 contrast); void OV7670_Special_Effects (u8 eft); void OV7670_Window_Set (u16 sx, u16 sy, u16 width, u16 height); void OV7670_CaptureFrame(void); #endif <file_sep>/USER/test.c #include "sys.h" #include "usart.h" #include "delay.h" #include "led.h" #include "beep.h" #include "key.h" #include "exti.h" #include "timer.h" #include "lcd.h" #include "rtc.h" #include "wkup.h" #include "dac.h" #include "24cxx.h" #include "usb_lib.h" #include "hw_config.h" #include "usb_pwr.h" #include "usb_desc.h" #include "ov7670.h" #include "sram.h" void usb_port_set(u8 enable); int main(void) { u8 lightmode = 0, saturation = 2, brightness = 2, contrast = 2; u8 effect = 0; u8 errcode; Stm32_Clock_Init(9); // 系统时钟设置 delay_init(72); // 延时初始化 uart_init(72, 9600); // 串口1初始化 LCD_Init(); // 初始化液晶 LED_Init(); // LED初始化 KEY_Init(); // 按键初始化 FSMC_SRAM_Init(); // 初始化外部SRAM ////////////////////////////////////////////////////////////////////////// //// 初始化OV7670 //errcode = OV7670_Init(); //if (errcode) //{ // POINT_COLOR = RED; // LCD_ShowString(10, 50, 200, 16, 16, "OV7670 Error!!"); // delay_ms(1000); // return -1; //} else{ // POINT_COLOR = RED; // LCD_ShowString(10, 50, 200, 16, 16, "OV7670 Init OK"); //} //delay_ms(1000); //OV7670_Light_Mode(lightmode); //OV7670_Color_Saturation(saturation); //OV7670_Brightness(brightness); //OV7670_Contrast(contrast); //OV7670_Special_Effects(effect); //OV7670_Window_Set(176, 10, 320, 240); //设置窗口 //OV7670_CS = 0; //// 使能定时器捕获(使用外部中断线8捕获帧同步信号) //EXTI8_Init(); ////////////////////////////////////////////////////////////////////////// // 重新启动USB模块 usb_port_set(0); delay_ms(300); usb_port_set(1); // USB配置 USB_Interrupts_Config(); Set_USBClock(); USB_Init(); delay_ms(300); ////////////////////////////////////////////////////////////////////////// // 10Khz计数频率,1秒钟中断定时器,统计各种刷新率 TIM6_Int_Init (10000, 7199); while (1) { OV7670_CaptureFrame(); } } // 设置USB 连接/断线 // enable:0,断开 // 1,允许连接 void usb_port_set(u8 enable) { RCC->APB2ENR |= 1 << 2; // 使能PORTA时钟 if (enable) // 退出断电模式(0 == PDWN) { _SetCNTR(_GetCNTR()&(~(1 << 1))); // 退出断电模式 } else { // 进入断电模式(1 == PDWN) _SetCNTR(_GetCNTR() | (1 << 1)); // 断电模式 GPIOA->CRH &= 0XFFF00FFF; // 清除PA11和PA12 GPIOA->CRH |= 0X00033000; // 00:通用推挽输出模式 ; 11 :输出模式,最大速度50MH PAout(12) = 0; } }
99066864ac9b645b1ae51c3b3f2ef284477c6673
[ "Markdown", "C" ]
20
C
funte/USB_wabcam
b972eaacfeaceb27db492a4ffab48ca5173e84a4
a06a4a3543cb99dbcfb88a3bc7dff46028f8a7c9
refs/heads/master
<repo_name>tbzy/Test<file_sep>/ppfilt/maskfunc/convert_to_fort.sh sed 's/E/d/g' maskr.15 | awk '{ print " mfunc(", NR-1, ") = ", $2 }' <file_sep>/ppfilt/_abbrev_.inc !//////////////////////////////////////////////////////////////////////// !! Abbrev words for Fortran (Last updated: 2014-9-2) #ifndef __ABBREV_INC__ #define __ABBREV_INC__ #define _bool_ logical #define _char_ character #define _int_ integer #define _real_ real(8) #define _dble_ real(8) #define _complex_ complex(8) #define _Bool_ logical #define _Char_ character #define _Int_ integer #define _Real_ real(8) #define _Dble_ real(8) #define _Complex_ complex(8) #define _sub_ subroutine #define _endsub_ end subroutine #define _func_ function #define _endfunc_ end function #define _endmod_ end module #define _put_ write(6,*) #define _printf_(x) write(6,x) #define _using_(x) use x, only: #define _switch_ selectcase #define _endsw_ endselect #define ___ implicit none #define _in_ intent(in) #define _alloc_ allocatable #define _param_ parameter #define _opt_ optional #define _dim_ dimension #define _ptr_ pointer #define _proc_ procedure #define _(x) x = x #define __(x) type(x) #define _fi endif #define _norm_(x) sqrt(sum((x)**2)) #define _normalize_(x) ((x) / _norm_(x)) #define _proj_(p,x) ((p) * sum((p)*(x)) / sum((p)**2)) #define _limit_(x,xmin,xmax) x = min(max(x,xmin),xmax) #define _pbc_(x,box) x = x - (box) * nint((x) / max(0.1d0,(box))) ! #define _pbc_(x,box) x = x - (box) * nint((x) / (box)) #define _dealloc_(x) if (allocated(x)) deallocate(x) #define _optval_(x,xopt,val) x = val; if (present(xopt)) x = xopt #define _onstep_(i,n,div) (div > 0 .and. mod(i, max((n)/max(div,1),1)) == 0) #define _Re_(x) dble(x) /* dreal(x) may also be used */ #define _Im_(x) dimag(x) #define _line_ repeat("-",70) #define _dline_ repeat("=",70) #define _section_(x) put; put _dline_; put x #define _routine_(x) put; put repeat(".",60); put x, ":" ; put #define _flush_ flush(6) #define _stop_(x) stop __FILE__ // " : " // x #define _0_ 0.0d0 #define _zi_ ( 0.0d0, 1.0d0 ) #define _pi_ 3.1415926535897931d0 #define _twopi_ 6.2831853071795862d0 #define _fourpi_ 12.566370614359172d0 #define _sqrt2_ 1.4142135623730951d0 #define _sqrt3_ 1.7320508075688772d0 #define _sqrtpi_ 1.7724538509055159d0 #define _sqrt2pi_ 2.5066282746310002d0 #define _atomtype_t Char(4) /* Amber=>4, DLPOLY=>8 (8 may be better) */ #define _atomname_t Char(4) #define _pottype_t Char(8) /* potential type */ #define _filename_t Char(50) !! [ Physical units ] !! #define _au_to_kcal_ 627.509d0 /* latest value */ #define _au_to_kcal_ 627.488d0 /* for comparison with Amber */ #define _au_to_eV_ 27.21138d0 #define _au_to_Angs_ 0.5291772d0 #define _au_to_amu_ 5.4858d-4 #define _au_to_fsec_ 0.0241888d0 #define _au_to_psec_ 0.0241888d-3 #define _au_to_nsec_ 0.0241888d-6 #define _au_to_wavenum_ 219474.6d0 #define _rad_to_deg_ ( 180.0d0 / _pi_ ) #define _kB_in_au_ 3.166815d-6 /* Boltzmann constant */ #define _au_to_kcalperAngs_ ( _au_to_kcal_ / _au_to_Angs_ ) /* force */ #define _au_to_kcalperAngs2_ ( _au_to_kcal_ / _au_to_Angs_**2 ) /* force const */ #define _au_to_kcalAngs12_ ( _au_to_kcal_ * _au_to_Angs_**12 ) /* LJ A coef */ #define _au_to_kcalAngs6_ ( _au_to_kcal_ * _au_to_Angs_**6 ) /* LJ B coef */ !! [ Amber internal units ] #define _amb_to_psec_ ( 1.0d0 / 20.455d0 ) #define _kB_in_amb_ ( 8.31441d-3 / 4.184d0 ) !! [ 1-4 scale factor (default: Amber) ] #define _scale_es14_ ( 1.0d0 / 1.2d0 ) #define _scale_lj14_ ( 1.0d0 / 2.0d0 ) !! [ Misc ] #define _f2003_ /* use Fortran2003 features */ !* #define __extern__ /* define this when subroutines are put in external scope */ !! [ Debug ] #define _debug_ .true. ! #define __log(x) put "x", " = ", x ; ! #define __log(x) /* no debug output in production run */ #endif /* __abbrev_inc__ */ !//////////////////////////////////////////////////////////////////////// <file_sep>/ppfilt/abbrev.inc !//////////////////////////////////////////////////////////////////////// !! Abbrev words for Fortran (Last updated: 2014-9-2) #ifndef __abbrev_inc__ #define __abbrev_inc__ #include "_abbrev_.inc" #define Bool logical #define Char character #define Int integer #define Dble real(8) #define Dcmplx complex(8) #define Dcomplex complex(8) #define sub subroutine #define endsub end subroutine #define endfunc end function #define endmod end module #define put write(6,*) #define printf(x) write(6,x) #define using(x) use x, only: #endif /* __abbrev_inc__ */ !////////////////////////////////////////////////////////////////////////
3c07a40e3304a39ce0ee7febd5f3b3460331706f
[ "C++", "Shell" ]
3
Shell
tbzy/Test
b7cfe6d6d703312057db66c2bd35644fba88b615
94265e70c4e2daa3104263a5b6767f3a94cc99ad
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import ConfigParser import json import os.path import sys import urllib2 class getWeather(): def get_city_id(self, city): city_list = ConfigParser.ConfigParser() url = "http://openweathermap.org/data/2.0/find/name?q="+city+"&units=metric" if args.default: city_list.read('./config.ini') try: city_id = city_list.get('default city','city_id') except: print 'Error, unable to load city_id from configuration' sys.exit() return city_id try: f = urllib2.urlopen(url) except: print 'Error, unable to access http://openweathermap.org/data/2.0/find/name?q='+city sys.exit() json_data = f.read() jdata_decoded = json.loads(json_data) #Check if data has been provided try: count = jdata_decoded['count'] except: print "No information could be found for provided city, exiting..." sys.exit() if ( count > 1 ): print 'More then one site returned, please select from the following:' counter = 0 while (counter < count): city_id = jdata_decoded['list'][counter]['id'] country = jdata_decoded['list'][counter]['sys']['country'] print "["+str(counter)+"] " + "City: "+city+", Country: "+country+ " ("+str(city_id)+")" counter = counter + 1 user_selection = input("Please choose a number: ") if 0 <= user_selection < count: return jdata_decoded['list'][user_selection]['id'] else: print 'Error: '+str(user_selection)+' not a valid option, exiting...' sys.exit() elif count == 1 : return jdata_decoded['list'][0]['id'] else: print "No information found for provided site. Exiting" sys.exit() def get_json_data(self,city): city_id = self.get_city_id(city) if args.farenheight: url = "http://openweathermap.org/data/2.0/weather/city/"+str(city_id)+"?type=json&units=imperial" else: url = "http://openweathermap.org/data/2.0/weather/city/"+str(city_id)+"?type=json&units=metric" try: f = urllib2.urlopen(url) except: return None s = f.read() return s def get_weather(self, city): json_data = self.get_json_data(city) jdata_decoded = json.loads(json_data) w_data = {} w_data['id'] = str(jdata_decoded['id']) w_data['name'] = str(jdata_decoded['name']) w_data['date'] = str(jdata_decoded['date']) w_data['temp'] = str(jdata_decoded['main']['temp']) w_data['pressure'] = str(jdata_decoded['main']['pressure']) w_data['humidity'] = str(jdata_decoded['main']['humidity'])+"%" w_data['wind'] = str(jdata_decoded['wind']['speed'])+" m/s" w_data['clouds'] = str(jdata_decoded['clouds']['all'])+" m/s" w_data['img'] = (jdata_decoded['weather'][0]['icon']) w_data['weather'] = str(jdata_decoded['weather'][0]['main']) return w_data def check_args(self): if args.default and args.city: print 'Error: unable to lookup city when using default option' sys.exit() if not args.city and not args.default: print 'Error: too few arguments' sys.exit() def main(self, city): weather_data = self.get_weather(city) if args.city: print 'Weather in '+city+'' else: print 'Weather in '+city+'' if args.farenheight: print 'Temperature :',weather_data['temp']+ " F" else: print 'Temperature :',weather_data['temp']+ " C" print 'Pressure :',weather_data['pressure'] print 'Humidity :',weather_data['humidity'] print 'Wind :',weather_data['wind'] print 'Clouds :',weather_data['clouds'] print 'Currently :',weather_data['weather'] if __name__ == "__main__": app = getWeather() #Start option settings# parser = argparse.ArgumentParser() parser.add_argument("city", nargs='?', help="Search this city for weather information") parser.add_argument("-f","--farenheight", action="store_true", help="Set metics to Farenheight") parser.add_argument("-c","--celcius", action="store_true", help="Set metics to Celcius") parser.add_argument("-d","--default", action="store_true", help="Weather for default city") args = parser.parse_args() app.check_args() #End option settings# app.main(str(args.city)) <file_sep>[default city] city_id = 5526337 city_name = Midland,TX <file_sep>#!/usr/bin/python from os.path import expanduser from ConfigParser import SafeConfigParser home = expanduser("~") parser = SafeConfigParser() parser.read(home+"/.gtk_weather/config.ini") print parser.get('default city', 'city_id')
929f54efffe5ff968178aa36cdb1b3b94c5bc656
[ "Python", "INI" ]
3
Python
DMaiorino/gtk_weather
6736915f471d9a5a74409048f502989de43e4c1c
be343ba560d80f6483e2e65dc0ad009a8e5f52a1
refs/heads/master
<repo_name>jneumann/home-page<file_sep>/home.js (function () { // Open links based on number pressed (0-8) document.onkeypress = function ( evt ) { var href = '', linksChildren = document.getElementsByClassName('links')[0].children; if (evt.keyCode == 49) { href = linksChildren[0].children[0].href; } if (evt.keyCode == 50) { href = linksChildren[1].children[0].href; } if (evt.keyCode == 51) { href = linksChildren[2].children[0].href; } if (evt.keyCode == 52) { href = linksChildren[3].children[0].href; } if (evt.keyCode == 53) { href = linksChildren[4].children[0].href; } if (evt.keyCode == 54) { href = linksChildren[5].children[0].href; } if (evt.keyCode == 55) { href = linksChildren[6].children[0].href; } if (evt.keyCode == 56) { href = linksChildren[7].children[0].href; } if (evt.keyCode == 57) { href = linksChildren[8].children[0].href; } if (evt.keyCode == 58) { href = linksChildren[9].children[0].href; } if( href ) { window.open( href, '_blank' ); } }; })(); <file_sep>/functions/podio.php <?php require('../config.php'); class Podio { function __construct() { } function getTasks() { return false; } function getWorkWeek() { return false; } } <file_sep>/functions/twitter.php <?php require('config.php'); require('vendor/autoload.php'); $twitter = new TwitterAPIExchange($config['twitter']); $url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'; $requestMethod = 'GET'; $fields = array( 'count' => '5' ); $twitter = new TwitterAPIExchange($config['twitter']); $res = $twitter->buildOauth($url, $requestMethod) ->performRequest(); $res = json_decode($res); $resArray = array(); for($i = 0; $i < 5; $i++) { array_push($resArray, $res[$i]); } return $resArray; <file_sep>/README.md # My Homepage This is the homepage that I use for my life. It currently has the following integrations: * [Fitbit](http://dev.fitbit.com/) * Average steps for the last 7 days * Update Fitbit with new goal of 110% of 7 day average * [Twitter](http://dev.twitter.com/) * Latest posts * [Podio](https://developers.podio.com/) - See my latest unread tasks * See my latest unread tasks * See projects for this week * [Class Dojo](http://classdojo.com/) - Class Dojo doesn't have an official API, but I managed to figure out how to get the JSON files that that the main site was loading * See child's points * See latest messages from teachers * Personal Bookmarks To Do: * See which twitch streamers that I follow are live * "Quick View" analytics for sites that I run * Facebook Integration <file_sep>/index.php <?php require('config.php'); require('vendor/autoload.php'); date_default_timezone_set("US/Central"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <script src="home.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/main.css"> </head> <body> <div class="container"> <!-- Add your site or application content here --> <div class="title"> <h1>Welcome Home</h1> </div> <div class="links row hidden-xs"> <div class="col-lg-2 col-md-2 col-sm-4"> <a href="http://bitbucket.com"> <img src="images/Bitbucket.svg" /> Bitbucket </a> </div> <div class="col-lg-2 col-md-2 col-sm-4"> <a href="http://github.com"> <img src="images/github.svg" /> Github </a> </div> <div class="col-lg-2 col-md-2 col-sm-4"> <a href="http://podio.com"> <img src="images/Podio.svg" /> Podio </a> </div> <div class="col-lg-2 col-md-2 col-sm-4"> <a href="http://sites.hdg/info.php"> <img src="images/php.svg" /> PhpInfo </a> </div> <div class="col-lg-2 col-md-2 col-sm-4"> <a href="http://news.ycombinator.com"> <img src="images/y-combinator.svg" /> Hacker News </a> </div> <div class="col-lg-2 col-md-2 col-sm-4"> <a href="http://feedly.com"> <img src="http://s.cafebazaar.ir/1/upload/icons/com.devhd.feedly.png" /> Feedly </a> </div> </div> <hr class="hidden-xs" /> <div class="row"> <div class="weather col-md-4 col-lg-3 clearfix"> <?php $cu = curl_init(); curl_setopt($cu, CURLOPT_URL, 'https://api.forecast.io/forecast/0b99f4b010921b26f03d8c216358378d/41.3510,-88.8391'); curl_setopt($cu, CURLOPT_HTTPHEADER, $config['classdojo']); curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1); $weather = curl_exec($cu); curl_close($cu); $weather = json_decode($weather); ?> <h1>Weather</h1> <div class="col-sm-6"> <h3>Today</h3> <i class="wi wi-forecast-io-<?php echo $weather->daily->data[0]->icon; ?>"></i> <p> <?php echo $weather->daily->data[0]->summary . '<br />'; echo round($weather->currently->apparentTemperature, 0) . '&#176;<br />'; ?> </p> </div> <div class="col-sm-6"> <h3>Tomorrow</h3> <i class="wi wi-forecast-io-<?php echo $weather->daily->data[1]->icon; ?>"></i> <p> <?php echo $weather->daily->data[1]->summary . '<br />'; echo round($weather->daily->data[1]->apparentTemperatureMin, 0) . '&#176; -' . round($weather->daily->data[1]->apparentTemperatureMax, 0) . '&#176;<br />'; ?> </p> </div> </div> <div class="twitter col-md-8 col-lg-9"> <h1>Twitter</h1> <div class=""> <?php $tweets = require('functions/twitter.php'); foreach($tweets as $k => $v) { echo "<div class='row'>"; echo "<div class='col-sm-12'>"; echo "<a href='http://twitter.com/" . $v->user->screen_name . "' target='_blank'>"; echo "<img src='" . $v->user->profile_image_url . "' />"; echo "</a>"; echo '<h3>'; echo "<a href='http://twitter.com/" . $v->user->screen_name . "' target='_blank' style='color:#000'>"; echo $v->user->name; echo "</a>"; echo '</h3>'; if(isset($v->entities->urls['0']->url)) { echo "<a href='" . $v->entities->urls['0']->url . "' target='_blank'>"; } echo $v->text; if(isset($v->entities->urls['0']->url)) { echo "</a>"; } echo "</div>"; echo "</div>"; } ?> </div> </div> </div> <div class="row"> <div class="col-md-6"> <h1>Podio</h1> <?php Podio::setup($config['podio']['client-id'], $config['podio']['client-secret']); Podio::authenticate_with_app($config['podio']['ww-app-id'], $config['podio']['ww-app-secret']); $ww = PodioItem::filter($config['podio']['ww-app-id']); foreach($ww as $week) { if ($week->title == '<NAME>') { $week_start = $week->fields['1']->values['start']; if((time()-(60*60*24*7)) < strtotime($week_start->format('Y-m-d H:i:s'))) { // var_dump( $week->fields ); foreach( (array) $week->fields as $week) { foreach( (array) $week as $day) { if (is_object($day) && $day->type == 'app') { echo '<h4>' . $day->label . '</h4>'; foreach($day->values as $proj) { echo '<a href="' . $proj->link . '" target="_blank">'; echo $proj->title; echo '</a>'; echo '<br />'; } } } } } } } ?> </div> <div class="classdojo col-md-6"> <div class="col-sm-12"> <h1>Class Dojo</h1> </div> <?php $cu = curl_init(); curl_setopt($cu, CURLOPT_URL, 'https://home.classdojo.com/api/parent/5603218c458be92d1d471717/student'); curl_setopt($cu, CURLOPT_HTTPHEADER, $config['classdojo']); curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($cu); curl_close($cu); $cu = curl_init(); curl_setopt($cu, CURLOPT_URL, 'https://home.classdojo.com/api/storyPost'); curl_setopt($cu, CURLOPT_HTTPHEADER, $config['classdojo']); curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1); $mes = curl_exec($cu); curl_close($cu); $res = json_decode($res); $res = $res->_items[0]; $mes = json_decode($mes); $mes = $mes->_items[0]; ?> <div class="col-sm-6"> <?php echo '<h3>Teacher</h3> ' . $res->teacher->title . ' ' . $res->teacher->lastName . '<br />'; ?> </div> <div class="col-sm-6"> <?php echo '<h3>Points</h3> ' . $res->currentPoints . '<br />'; ?> </div> <div class="col-sm-12"> <?php echo '<h3>Latest Message (' . date('m/d/Y', strtotime($mes->createdAt)) . ')</h3>'; if (isset($mes->attachments[0]->path)) { echo '<img src="' . $mes->attachments[0]->path . '" />'; } echo '<p>' . $mes->body . '</p>'; ?> </div> </div> </div> <hr class="hidden-xs" /> <div class="fitbit row"> <h1>Fitbit</h1> </div> </div> </body> </html>
57be31900135f8e3cd83485770f1abfe4ac64745
[ "JavaScript", "Markdown", "PHP" ]
5
JavaScript
jneumann/home-page
a9b8f079819f3250c9c3c04d3d9be733bba47af0
aff73aee4e4d1d39a7c0a0ebe63aee48f9712226
refs/heads/master
<file_sep># College-Work College projects This repository contains the projects done in college all which are done in java <file_sep>import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Boolean valid = true; String num1 = request.getParameter("Number_1"); String num2 = request.getParameter("Number_2"); String num3 = request.getParameter("Number_3"); String num4 = request.getParameter("Number_4"); String num5 = request.getParameter("Number_5"); String num6 = request.getParameter("Number_6"); int Numbers[] = new int[6]; try { Numbers[0] = Integer.parseInt(num1); Numbers[1] = Integer.parseInt(num2); Numbers[2] = Integer.parseInt(num3); Numbers[3] = Integer.parseInt(num4); Numbers[4] = Integer.parseInt(num5); Numbers[5] = Integer.parseInt(num6); } catch (NumberFormatException e) { out.println("<HTML>"); out.println("<HEAD><TITLE>Invalid Input </TITLE></HEAD>"); out.println("<BODY>"); out.println("You left A Space Empty Please Return And Fill This Space"); out.println("</BODY></HTML>"); } for (int i = 0 ; i <Numbers.length; i++) { if(Numbers[i] < 1 || Numbers[i] > 47) { valid = false; } } if(valid == false) { out.println("<HTML>"); out.println("<HEAD><TITLE>Invalid Input </TITLE></HEAD>"); out.println("<BODY>"); out.println("Values Entered Are Not Valid(Must be between 1-47)"); out.println("</BODY></HTML>"); } else if(valid == true) { Arrays.sort(Numbers); out.println("<HTML>"); out.println("<HEAD><TITLE>Lotto Numbers </TITLE></HEAD>"); out.println("<BODY>"); out.println("Numbers:" + Arrays.toString(Numbers)); out.println("</BODY></HTML>"); out.close(); } } } <file_sep>package Applications; //name of class public class Student { //Variable for student number private String number; //Variable for student name private String name; //Variable for student year of entry private int year; //Variable for the course code private String code; //Empty Constructor public Student() { number = " "; name = " "; year = 0; code = " "; } //Constructor with Variables being taken in public Student (String number , String name , int year , String code) { this.number = number; this.name = name; //Error checking for year if (year < 2013 || year > 2017) { this.year = 0000; System.out.println("ERROR Year is not between 2013 and 2017"); } else this.year = year; //Error checking for the course code if (!code.startsWith("DT")) { this.code = "ERROR"; System.out.println("ERROR Course Code does not start with DT"); } else this.code = code; } //Getter and Setter methods public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } //Equals method for checking if incoming student parameter matches the student number or student code public boolean equals(Object obj) { //Bollean to determine if incoming information matches boolean found = false; //Casts the Generic object to that of type Student Student aStudent = (Student) obj; //Checks to see if the current student number matches the incoming student number if (getNumber().equalsIgnoreCase(aStudent.getNumber())) { found = true; } //Checks to see if the current course code matches the incoming student number if(getCode().equals(aStudent.getCode())) { found = true; } return found; } //Methods of comparing Students alphabetically public boolean greater(String number) { if(this.number.compareTo(number) >= 0) { return true; } else return false; } public boolean lesser(String number) { if(this.number.compareTo(number) <= 0) { return true; } else return false; } //To String method for displaying student information public String toString() { return "Student Number:" + this.number + "\n" + "Student Name:" + this.name + "\n" + "Student Year Of Entry:" + this.year + "\n" + "Programme Code:" + this.code + "\n"; } } <file_sep>package Applications; import java.util.Scanner; import DataStructures.LinearNode; import DataStructures.LinkedList; //Name of the the Class public class MyCollege { //Global Scanner Scanner scan = new Scanner(System.in); //Global Linked list which can be accessed by every method in the class LinkedList<Student> students; //Global Variable for determining the size of the linked list int size; //Global variable for the password pin String pin; //Method that creates the linked list public MyCollege() { //Declaration of Linked list and setting it to accept objects of type Student students = new LinkedList<Student>(); } //Method for creating Pin public void createPin() { //Greeting message System.out.println("Greeting user before you can use this program we would like you to input a pin"); System.out.println("We are doing this to ensure that no unauthorised personnel to delete information stored"); System.out.println("Please rememeber this pin"); //Setting pin to user input pin = scan.nextLine(); } //Method that adds students to Linked list public void addStudent() { //Variable for Student number String number; //Variable for Student name String name ; //Variable for year of entry int year; //Variable For Programme code String code; //Asks users how many students they wish to input System.out.println(" "); do { System.out.println("Greetings what amount of students would you like to manage?(20 max.)"); size = scan.nextInt(); scan.nextLine(); }while(size > 20); //Students information is input System.out.println(" "); { for (int i = 0 ; i < size ; i++) { System.out.println(" "); System.out.println("What is the student number"); number = scan.nextLine(); System.out.println("What is the student name"); name = scan.nextLine(); System.out.println("What year did the student join"); year = scan.nextInt(); scan.nextLine(); System.out.println("What is the code of the programme the student is joining"); code = scan.nextLine(); //Student is created Student aStudent = new Student (number , name , year , code); //Student is then added students.add(aStudent); } } } //Displays the students public void Display() { System.out.println(" "); System.out.println("Student Details:"); //Calls the linked list toString System.out.println(students.toString()); } //Deletes students from the linked list public void delete() { //Requirement of pin to delete students String pin1; System.out.println("To delete Students from a course This progranm requires the pin from An adminstrator"); System.out.println("Enter pin"); pin1 = scan.nextLine(); //if pin is correct allows student to be deleted if (pin1.equals(pin)) { System.out.println("ACCESS GRANTED"); //Variable for student number String number; //Asks for student he user wishes to delete System.out.println("What is the student number you wish to delete"); number = scan.nextLine(); //Creates an empty student with only the student number Student aStudent = new Student (number , "" , 0 , ""); System.out.println("Student will now be removed"); //Removes student students.remove(aStudent); } //If incorrect denial message is shown and next methid is called if (!pin1.equals(pin)) { System.out.println("ACCESS DENIED "); } } //Follows the same practice as the delete student method public void deleteprogramme() { String pin1; System.out.println("To delete Students from a course This progranm requires the pin from An adminstrator"); System.out.println("Enter pin"); pin1 = scan.nextLine(); if (pin1.equals(pin)) { System.out.println("ACCESS GRANTED"); //Variable for programme code String code; System.out.println("What is the programme code you wish to delete"); code = scan.nextLine(); //Creates an empty student with only the student code Student aStudent = new Student (" " , "" , 0, code); System.out.println("Students in this programme will now be removed"); //Loop to ensure that every student with the same code is deleted for (int i = 0; i <size; i++) { students.remove(aStudent); } } if (!pin1.equals(pin)) { System.out.println("ACCESS DENIED "); } } //Main method calling other methods public static void main(String[] args) { MyCollege a = new MyCollege() ; a.createPin(); a.Display(); a.delete(); a.Display(); a.deleteprogramme(); a.Display(); } } <file_sep>/* */ /* Program to demonstrate the implmentation of a */ /* linked list of numbers. */ /* */ /**************************************************************/ #define _CRT_SECURE_NO_WARNINGS #define bool int #define false 0 #define true (!false) //Libraries #include <stdio.h> #include <stdlib.h> #include <string.h> //Preprocessor Variable #define SIZE 1 //Stucture template for data part of a LinearNode struct car { char Reg[20]; char Year[20]; char County[20]; char RegNo[20]; char Model[20]; char Make[20]; char Colour[20]; char reserved[20]; int owners; bool booked; double deposit; }; //Stucture template for one node struct LinearNode { struct car *element; struct LinearNode *next; }; // Function prototypes void addCar(); //adding Cars to end of the list void sellCar(); // delete a specific node void saveToFile(); void reserve(); void viewAllCars(); void SpecificCar(); void menu(); void end(); bool isEmpty(); // Global Variables struct LinearNode *front = NULL; struct LinearNode *last = NULL; int counter = 0; FILE *fp; /**************MAIN FUNCTION*******************/ int main(void) { fp = fopen("car.dat", "rb"); struct LinearNode *aNode; struct car *aCar; if (fp == NULL) { printf("No Cars In File Please Go To Menu Option 1 And Add Cars\n"); menu(); } else { printf("Retriving cars from file...\n"); while (fread(&aCar, sizeof(struct car), 1, fp)); { aCar = (struct car *)malloc(sizeof(struct car)); aNode = (struct LinearNode *)malloc(sizeof(struct LinearNode)); aNode->element = aCar; aNode->next = NULL; if (isEmpty()) { front = aNode; last = aNode; } else { last->next = aNode; last = aNode; } } menu(); } getchar(); getchar(); } /////////////////Add Cars//////////////////////// void addCar() { char Year1[20]; char County2[20]; struct LinearNode *aNode; struct car *aCar; if (counter >= 5) { printf("The ShowRoom Is Full No More Cars Can Be Added\n"); } else // add SIZE nodes to the list for (int i = 0; i<SIZE; i++) { //////////STEP ONE:CREATE SPACE FOR DATA I.E THE BOX THAT CONTAINS INFORMATION///////////// //Create space for data part of node aCar = (struct car *)malloc(sizeof(struct car)); { //Input value into the data part printf("Enter The Year of Manufacteuring:\n"); scanf("%s", Year1); printf("Enter County of Ownership:\n"); scanf("%s", County2); do { printf("Enter The Registration Numbers for the Car (MAX 4 NUMBERS): \n"); scanf("%s", aCar->RegNo); } while (strlen(aCar->RegNo) > 4); aCar->Reg[0] = Year1[2]; aCar->Reg[1] = Year1[3]; aCar->Reg[2] = County2[0]; aCar->Reg[3] = aCar->RegNo[0]; aCar->Reg[4] = aCar->RegNo[1]; aCar->Reg[5] = aCar->RegNo[2]; aCar->Reg[6] = aCar->RegNo[3]; aCar->Reg[7] = '\0'; printf("Enter The Car Model: \n"); scanf("%s", &aCar->Model); printf("Enter The car Make: \n"); scanf("%s", &aCar->Make); printf("Enter The Car Colour: \n"); scanf("%s", &aCar->Colour); printf("Enter the number of previous owners:\n"); scanf("%d", &aCar->owners); strcpy(aCar->reserved, "Unreserved"); aCar->deposit = 0; aCar->booked = false; // create space for new node that will contain data aNode = (struct LinearNode *)malloc(sizeof(struct LinearNode)); if (aCar->owners > 3) { printf("This Car Cannot Be Added As It Has Too Many Previous Owners\n"); aCar = NULL; aNode = NULL; } //////////////STEP TWO: CREATE SPACE FOR THE NODE I.E THE POINTER OF THE INFORMATION/////////// if (aNode == NULL && aCar == NULL) { printf("You Will Be Returned To The Menu\n"); } else ///////STEP 3 : ADD DATA TO THE NODE WHICH CONNECTS THE BOXES////////////// { // add data part to the node aNode->element = aCar; aNode->next = NULL; //////STEP 4 : ADD THE NODE TO THE LIST////////////// //add node to end of the list if (isEmpty()) { front = aNode; last = aNode; } else { last->next = aNode; last = aNode; } //end else }//end else }//end else }//end for counter = counter++; } //end addNodes ////////////////View Cars///////////////////// void viewAllCars() { int choice; char color[20]; bool found = false; struct LinearNode *current = front; printf("\n"); if (isEmpty()) printf("No Cars Present\n"); else { printf("Would you Like To See All Cars or Cars By Colour\n"); printf("Enter 1 To see All Cars\n"); printf("Enter 2 to see Cars By Colour\n"); scanf("%d", &choice); if (choice == 1) { while (current != NULL) { printf("Car Information:\n"); printf("==================\n"); printf("Car Registartion Number:%s\n", current->element->Reg); printf("Car Make:%s\n", current->element->Make); printf("Car Model:%s\n", current->element->Model); printf("Car Colour:%s\n", current->element->Colour); printf("Amount Of Previous Owners:%d\n", current->element->owners); printf("Reserved:%s\n", current->element->reserved); printf("Deposit:%f\n", current->element->deposit); current = current->next; } //end while } //end if if (choice == 2) { printf("What Coulor Car would you like to see\n"); scanf("%s", color); while (current != NULL) { if (strcmp(color, current->element->Colour) == 0) { found = true; printf("Car Information\n"); printf("==================\n"); printf("Car Registartion Number:%s\n", current->element->Reg); printf("Car Make:%s\n", current->element->Make); printf("Car Model:%s\n", current->element->Model); printf("Car Colour:%s\n", current->element->Colour); printf("Amount Of Previous Owners:%d\n", current->element->owners); printf("Reserved:%s\n", current->element->reserved); printf("Deposit:%f\n", current->element->deposit); } current = current->next; } if (!found) { printf("No car Of This Colour Can Be Found\n"); } } }//end else } //end viewAllNodes ///////////////Sell Cars///////////////////// void sellCar() { struct LinearNode *current, *previous = front; bool notFound = true; char registration[20]; printf("\n"); if (isEmpty()) printf("Error - there are no nodes in the list\n"); else { current = previous = front; printf("Enter Registration Number of car you wish to sell\n"); scanf("%s", &registration); if (strcmp(registration, current->element->Reg) == 0 && current->element->booked == false) { printf("Car has been found however it is not reserved thus cannot be sold\n"); } else while (notFound && current != NULL) { if (strcmp(registration, current->element->Reg) == 0 && current->element->booked == true) notFound = false; else { previous = current; current = current->next; }//end else } //end while if (notFound) printf("This Car Cannot Be Found %s\n", registration); else { if (current == front) { //delete front node front = front->next; free(current); } //end else else if (current == last) {//delete last node free(current); previous->next = NULL; last = previous; } else {//delete node in middle of list previous->next = current->next; free(current); } //end else printf("This Car has been Sold\n"); }//end else }//end else }// end deleteNode //////////////Saving to File//////////////// void saveToFile() { fp = fopen("car.dat", "wb"); struct LinearNode *current = front; while (current != NULL) { fwrite(&current->element, sizeof(struct car), 1, fp); current = current->next; } //end while fclose(fp); }//Save to file /////////////Reserve/Unreserve Car/////////// void reserve() { struct LinearNode *current = front; int choice; int amount; bool found = false; char reg[20]; printf("Would you Like To Reserve/Unreserve a Car\n"); printf("Enter 1 To Reserve\n"); printf("Enter 2 To Unreserve\n"); scanf("%d", &choice); if (choice == 1) { printf("Enter Car Registration Number\n"); scanf("%s", reg); while (current != NULL) { if (strcmp(reg, current->element->Reg) == 0 && current->element->booked == true) { printf("Car has been Found but has already been booked you cannot book this vehicle\n"); } if (strcmp(reg, current->element->Reg) == 1) { printf("Car has not been Found\n"); } else if (strcmp(reg, current->element->Reg) == 0) { found = true; printf("Car has been Found\n"); current->element->booked = true; if (current->element->booked = true) { strcpy(current->element->reserved, "Reserved"); do { printf("Enter Deposit Amount ( Must Be More Than 500 And Less Than 1500 \n"); scanf("%d", &amount); } while (amount < 500 || amount > 1500); current->element->deposit = amount; } printf("Car has been reserved\n"); } current = current->next; } } if (choice == 2) { printf("Enter Car Registration Number\n"); scanf("%s", reg); while (current != NULL) { if (strcmp(reg, current->element->Reg) == 0) { printf("Car has been Found\n"); current->element->booked = false; strcpy(current->element->reserved, "Unreserved"); current->element->deposit = 0; } if (strcmp(reg, current->element->Reg) == 1) { printf("Car has not been Found\n"); } current = current->next; } printf("Car has been Unreserved\n"); } } /////////////View a a specific Car///////////// void SpecificCar() { struct LinearNode *current = front; char reg[20]; bool found = false; printf("Enter Car Registration Number\n"); scanf("%s", &reg); while (current != NULL) { if (strcmp(reg, current->element->Reg) == 0) { found = true; printf("Car Information\n"); printf("==================\n"); printf("Car Registartion Number:%s\n", current->element->Reg); printf("Car Make:%s\n", current->element->Make); printf("Car Model:%s\n", current->element->Model); printf("Car Colour:%s\n", current->element->Colour); printf("Amount Of Previous Owners:%d\n", current->element->owners); printf("Reserved:%s\n", current->element->reserved); printf("Deposit:%f\n", current->element->deposit); } current = current->next; } if (!found) { printf("Car Can't Be Found\n"); } } ////////////Check if List is empty/////////////// bool isEmpty() { if (front == NULL) return true; else return false; } /////////////Menu/////////////////////////////// void menu() { int option; do { printf("\n"); printf("==================\n"); printf("1. Add A New Car To The ShowRoom\n"); printf("2. Sell A Car From The ShowRoom\n"); printf("3. Reserve/Unreserve A Car From The ShowRoom\n"); printf("4. View All The Cars From ShowRoom\n"); printf("5. View A Specific Car From The ShowRoom\n"); printf("6. Extra\n"); printf("7.Exit System\n"); do { printf("Please Select Menu Option\n"); scanf("%d", &option); } while (option != 1 && option != 2 && option != 3 && option != 4 && option != 5 && option != 6 && option != 7); if (option == 1) { addCar(); } if (option == 2) { sellCar(); } if (option == 3) { reserve(); } if (option == 4) { viewAllCars(); } if (option == 5) { SpecificCar(); } /*if (option == 6) { extra(); }*/ } while (option != 7); if (option == 7) { saveToFile(front); end(); } } ///////////Farewell Messaage/////////////////// void end() { //farewell message printf("Thank you for working with us\n"); }<file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> void main() { float accountbalance, servicecharge, total; servicecharge = 0; accountbalance = 0; for (int i = 0; i < 5; i++) { servicecharge = 0; printf("Enter an account balance:"); scanf("%f", &accountbalance); if (accountbalance == -100) { servicecharge = 10.00; total = accountbalance - servicecharge; } else if(accountbalance < -100 && accountbalance > -500) { servicecharge = 100.00; total = accountbalance - servicecharge; } else if(accountbalance <= -500) { servicecharge = (accountbalance * 2)*-1; total = accountbalance - servicecharge; } else if (accountbalance >0) { servicecharge = 0; total = accountbalance - servicecharge; } printf("Account balance = %5.2f, Service Charge = %5.2f, total = %5.2f\n", accountbalance, servicecharge, total); } getchar(); getchar(); }
269ba9d15f060fcf22e6987762b3f535f76276b0
[ "Markdown", "Java", "C" ]
6
Markdown
Lordjiggyx/College-Work
13c63dff856fbb38783eca4ea64db06424da152a
1a1e75ca82af96c85c9bb1ac51f39b71b62ba48f
refs/heads/master
<file_sep># Generated by Django 2.0.7 on 2019-03-17 15:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0002_auto_20190317_1753'), ] operations = [ migrations.AlterField( model_name='article', name='content', field=models.TextField(default=''), ), ] <file_sep>from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home_view(request, *args, **kwargs): # return HttpResponse("<h1>Hello World</h1>") #string of html code return render(request, "home.html", {}) def contact_view(request, *arg, **kwargs): return render(request, "contact.html", {}) #string html code def about_view(request, *arg, **kwargs): my_context = { "title" : "abc this is about us", "this_is_true": True, "my_number" : 123, "my_list" : [123, 4242, 123123], "my_html": "<h1>Hello world</h1>" } return render(request, "about.html", my_context) #string html code <file_sep># Generated by Django 2.0.7 on 2019-03-17 15:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0003_auto_20190317_1754'), ] operations = [ migrations.AlterField( model_name='article', name='content', field=models.TextField(default='some content'), ), ] <file_sep>from django.shortcuts import render, get_object_or_404 from .forms import ProductForm from .models import Product # Create your views here. def product_delete_view(request, id): obj = get_object_or_404(Product, id=id) #POST request if request.method == "POST": #confirming delete obj.delete() context = { "object": obj } return render(request, "products/products_delete.html") def product_create_view(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() form = ProductForm() context = { 'form': form } return render(request, "products/products_create.html", context) def dynamic_lookup_view(request, my_id): obj = Product.objects.get(id=my_id) context = { "object": obj } return render(request, "products/products_detail.html", context) def product_list_view(request): queryset = Product.objects.all() context = { "object_list": queryset } return render(request, "products/products_list.html", context)
5fde258cfb6b301fd0cd03579b53e57fe158801d
[ "Python" ]
4
Python
loaywatany/django-project
750063defe82f1ccdab3f6a6772af5cbb41049b4
6758b05f91215ade441acc55004f73ed4b6c8f62
refs/heads/master
<repo_name>Earthstar/straight-white-bot<file_sep>/PRIVACY.md # Privacy Policy This is the privacy policy for (https://www.facebook.com/straightwhiteboy). ## Information Collection, Use, and Sharing The Straight White Boy Simulator app may record the text of any messages sent to it for debugging purposes. The app records an identification number of the user as part of normal operation. This data will not be shared with or sold to outside organizations. ## Security Data sent to this app is not accessible to anyone except the app maintainer under normal circumstances. The data is not secured in any particular fashion. ## Updates Updates to the privacy policy, etc. will be posted to the [Straight White Boy Simulator](https://www.facebook.com/straightwhiteboy) page.<file_sep>/README.md This repository contains a Facebook Messenger bot that simulates the experience of chatting with a Straight White Boy. Based off of [this](http://hashbang.gr/your-own-facebook-messenger-bot-powered-by-nodejs/) tutorial. Inspired by the tumblr [Straight White Boys Texting](http://straightwhiteboystexting.org/)<file_sep>/src/scripts/ocrImages.py from PIL import Image from pytesseract import pytesseract import random def is_swb_color(color_tuple): ''' color_tuple - a length 3 tuple of RGB colors returns True if the color corresponds to the color of the "swb" correspondent or 231, 230, 235 ''' r, g, b = color_tuple return r == 231 and g == 230 and b == 235 def is_recipient_color(color_tuple): ''' color_tuple - a length 3 tuple of RGB colors returns True if the color corresponds to the color of the "recipient" correspondent or 43, 140, 247 ''' # r, g, b = color_tuple # return r == 43 and g == 140 and b == 247 return fuzzy_match_color((43, 140, 247), color_tuple) def fuzzy_match_color(expected, actual): epsilon = 10 for i in xrange(len(expected)): expected_value = expected[i] actual_value = actual[i] actual_matches_expected = ((expected_value - epsilon) < actual_value) and ((expected_value + epsilon) > actual_value) if not actual_matches_expected: return False return True def is_color_in_row(pixel_access, width, y, color_def): ''' pixel_access - loaded image that can be accessed by pixel width - width of image y - row to search color_def - function to identify color ''' for x in xrange(width): rgb_pixel = pixel_access[x, y] if color_def(rgb_pixel): return True return False def is_swb_color_in_row(pixel_access, width, y): return is_color_in_row(pixel_access, width, y, is_swb_color) def is_recipient_color_in_row(pixel_access, width, y): return is_color_in_row(pixel_access, width, y, is_recipient_color) def process_image(): image = Image.open("screenshots/1ttp39.jpg") width, height = image.size pixel_access = image.load() # When searching the image, either we haven't found a band, or we're in a swb color band # or we're in a recipient color band # possible values are None, "swb" and "recipient" search_mode = None # it's a goddamned state machine # y increases from top to bottom of image lower_y = None # list of tuples of (lower_y, upper y) image_band_dimensions = [] for y in xrange(height): if search_mode == None: if is_swb_color_in_row(pixel_access, width, y): lower_y = y search_mode = 'swb' continue if is_recipient_color_in_row(pixel_access, width, y): lower_y = y search_mode = 'recipient' continue # I'm making the assumption that you're always going to have some space b/w the text bubbles if search_mode == "swb": if (not is_swb_color_in_row(pixel_access, width, y)): search_mode = None image_band_dimensions.append((lower_y, y)) continue if search_mode == 'recipient': if (not is_recipient_color_in_row(pixel_access, width, y)): search_mode = None image_band_dimensions.append((lower_y, y)) continue image_bands = [] for band_dimension in image_band_dimensions: box = (0, band_dimension[0], width, band_dimension[1]) region = image.crop(box) # region.show() image_bands.append(region) for band in image_bands: image_name = str(int(round(random.random() * 10000))) + '.jpg' print image_name band.save('screenshots/processed/' + image_name) print pytesseract.image_to_string(band) print pytesseract.image_to_string(image) process_image() # recipient_bubble = Image.open("screenshots/processed/8473.jpg") <file_sep>/index.js var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var generateBoyResponse = require('./src/generateBoyResponse'); var app = express(); var verify_token = process.env.VERIFY_TOKEN; var token = process.env.PAGE_ACCESS_TOKEN; var PORT = process.env.PORT || 1337; app.use(bodyParser.json()); app.get('/', function (req, res) { res.send('Hello World! This is the bot\'s root endpoint!'); }); app.get('/webhook/', function (req, res) { if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === verify_token) { console.log("Validating webhook"); res.status(200).send(req.query['hub.challenge']); } else { console.error("Failed validation. Make sure the validation tokens match."); res.sendStatus(403); } }); app.post('/webhook/', function (req, res) { var data = req.body; // Make sure this is a page subscription if (data.object == 'page') { // Iterate over each entry // There may be multiple if batched data.entry.forEach(function(pageEntry) { pageEntry.messaging.forEach(function(messagingEvent) { if (messagingEvent.message) { handleMessageEvent(messagingEvent); } else { console.log("Received messaging event that isn't handled", messagingEvent); } }); }); } res.sendStatus(200); }); app.listen(PORT, function () { console.log('Facebook Messenger echoing bot started on port:' + PORT); }); // Handles FB messaging events of type 'message' function handleMessageEvent(event) { var senderId = event.sender.id; var message = event.message; var messageText = message.text; var messageAttachments = message.attachments; var botResponse; if (messageText) { botResponse = generateBoyResponse(senderId, messageText); } else if (messageAttachments) { botResponse = 'thats hot. more?'; } var textMessage = formatTextMessage(senderId, botResponse); callSendAPI(textMessage); } function formatTextMessage(recipientId, messageText) { return { recipient: { id: recipientId }, message: { text: messageText } }; } function callSendAPI(messageData) { console.log(messageData); request({ uri: 'https://graph.facebook.com/v2.6/me/messages', qs: { access_token: token }, method: 'POST', json: messageData }, function (error, response, body) { if (!error && response.statusCode == 200) { var recipientId = body.recipient_id; var messageId = body.message_id; console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId); } else { console.error("Unable to send message."); console.error('Response status: ', response.statusCode); console.error('Response body: ', response.body); console.error(error); } }); } <file_sep>/src/constants.js module.exports = { HOPEFUL_STATE: 'hopeful', AGGRESSIVE_STATE: 'aggressive' };<file_sep>/src/scripts/scrapeTumblr.py import requests from urlparse import urlparse import os.path from PIL import Image from StringIO import StringIO from bs4 import BeautifulSoup from lxml import html def get_image_urls_on_page(pageNum): ''' Returns the url of all images from a page on tumblr pageNum - an integer of page to scrape. one-indexed ''' page = requests.get('http://straightwhiteboystexting.org/page/' + str(pageNum)) tree = html.fromstring(page.content) images = tree.xpath('//div[contains(@class,"post")]//img') image_urls = [] for image in images: image_urls.append(image.get('src')) return image_urls def load_image(url): image_request = requests.get(url) image = Image.open(StringIO(image_request.content)) file_name = get_image_name(url) image.save('screenshots/' + file_name, 'JPEG') def get_image_name(url): path = urlparse(url).path directory, file = os.path.split(path) return file def main(): hasImages = True index = 376 while hasImages: print 'On page: ' + str(index) image_urls = get_image_urls_on_page(index) if len(image_urls) == 0: hasImages = False for image_url in image_urls: print image_url if '.jpg' in image_url: load_image(image_url) index += 1 main()
5f39f7a9bc6d3b3572358e98e55c79455eadd2ee
[ "Markdown", "Python", "JavaScript" ]
6
Markdown
Earthstar/straight-white-bot
6466a5352998543c845c76b0e9173c7bc9692725
4396b2731e0031d88cd246ea11a5dfe3179fa95d
refs/heads/master
<file_sep>package com.bing.listviewitemdemo; /** * Description * Created by bing on 2015/10/4. */ public class ItemData { private String firstItem; private String secondItemTop; private String secondItemBottom; private String thirdItemText; private int thirdItemImg; public ItemData(String firstItem) { this.firstItem = firstItem; } public ItemData(String secondItemTop, String secondItemBottom) { this.secondItemTop = secondItemTop; this.secondItemBottom = secondItemBottom; } public ItemData(String thirdItemText, int thirdItemImg) { this.thirdItemText = thirdItemText; this.thirdItemImg = thirdItemImg; } public String getFirstItem() { return firstItem; } public void setFirstItem(String firstItem) { this.firstItem = firstItem; } public String getSecondItemTop() { return secondItemTop; } public void setSecondItemTop(String secondItemTop) { this.secondItemTop = secondItemTop; } public String getSecondItemBottom() { return secondItemBottom; } public void setSecondItemBottom(String secondItemBottom) { this.secondItemBottom = secondItemBottom; } public String getThirdItemText() { return thirdItemText; } public void setThirdItemText(String thirdItemText) { this.thirdItemText = thirdItemText; } public int getThirdItemImg() { return thirdItemImg; } public void setThirdItemImg(int thirdItemImg) { this.thirdItemImg = thirdItemImg; } } <file_sep>package com.bing.folatbuttondemo; import android.app.Application; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.view.View; import android.widget.Toast; import java.io.IOException; import java.io.OutputStream; /** * Description * Created by bing on 2015/10/10. */ public class BackService extends Service { private Process process; private FloatButton floatButton; @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { floatButton = new FloatButton(this); floatButton.setBackgroundResource(R.mipmap.ic_launcher); showButton(); floatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "floatButton", Toast.LENGTH_LONG).show(); } }); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return null; } public void showButton() { if (floatButton != null) { if (!floatButton.isShown()) { floatButton.show(); } } } public void hideButton() { if (floatButton != null) { if (floatButton.isShown()) { floatButton.dismiss(); } } } /** * 结束进程 */ private void killProcess(String packageName) { try { if (process == null) { process = Runtime.getRuntime().exec("sh"); } OutputStream out = process.getOutputStream(); String cmd = "am force-stop " + packageName; out.write(cmd.getBytes()); out.flush(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>#博客管理 * [1.自定义Drawable实现圆形图片](http://blog.csdn.net/zhesir/article/details/48859581) * [2.listview与viewpager组合(一)](http://blog.csdn.net/zhesir/article/details/48878445) * [3.listview与viewpager组合(二)](http://blog.csdn.net/zhesir/article/details/48878687) * [4.Picasso的简单使用](http://blog.csdn.net/zhesir/article/details/48879481) * [5.fragment与activity通信](http://blog.csdn.net/zhesir/article/details/48896315) * [6.ListView实现不同的item](http://blog.csdn.net/zhesir/article/details/48896923) * [7.startActivityForResult使用方式](http://blog.csdn.net/zhesir/article/details/48948655) * [8.android等待对话框](http://blog.csdn.net/zhesir/article/details/49029419) * [9.启动服务两种方式,并与activity通信](http://blog.csdn.net/zhesir/article/details/49130379) <file_sep>package com.bing.servicedemo; /** * Description activity与service连接的桥梁 * Created by bing on 2015/10/13. */ public interface Iprint { void print(); } <file_sep>include ':app', ':testaidldemo' <file_sep>package com.bing.fragmentwithactivity; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; /** * Description * Created by bing on 2015/10/4. */ public class FragmentA extends Fragment implements View.OnClickListener { private TextView textView; private Button button; private OnReceiverDataListener onReceiverDataListener; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_a_main, container, false); textView = (TextView) view.findViewById(R.id.tv_fragmentA); button = (Button) view.findViewById(R.id.btn_fragmentA); button.setOnClickListener(this); /**接收来自Activity的数据**/ Bundle bundle = getArguments(); textView.setText(bundle.getString("data")); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); onReceiverDataListener = (OnReceiverDataListener) activity; } @Override public void onClick(View v) { if (v.getId() == R.id.btn_fragmentA) { onReceiverDataListener.loadData("数据来自fragmentA"); } } public interface OnReceiverDataListener { void loadData(String str); } } <file_sep>package com.bing.folatbuttondemo; import android.content.Context; import android.graphics.PixelFormat; import android.graphics.Rect; import android.view.Gravity; import android.view.MotionEvent; import android.view.WindowManager; import android.widget.ImageView; import android.widget.Toast; /** * Description * Created by bing on 2015/10/10. */ public class FloatButton extends ImageView { private boolean isShown = false; private WindowManager windowManager; // 此windowManagerParams变量为获取的全局变量,用以保存悬浮窗口的属性 private WindowManager.LayoutParams windowManagerParams; private float mRawX; private float mRawY; private float mStartY; private float mStartX; private boolean isOut = false; private OnClickListener listenner = null; public FloatButton(Context context) { super(context); windowManager = (WindowManager) getContext().getApplicationContext().getSystemService(Context.WINDOW_SERVICE); windowManagerParams = new WindowManager.LayoutParams(); } @Override public boolean onTouchEvent(MotionEvent event) { // 获取到状态栏的高度 Rect frame = new Rect(); getWindowVisibleDisplayFrame(frame); // 当前值以屏幕左上角为原点 mRawX = event.getRawX(); mRawY = event.getRawY(); final int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: // 以当前父视图左上角为原点 mStartX = event.getX(); mStartY = event.getY(); isOut = false; break; case MotionEvent.ACTION_MOVE: updateViewPosition(); if (Math.abs(event.getX() - mStartX) > 5 || Math.abs(event.getY() - mStartY) > 5) { isOut = true; } break; case MotionEvent.ACTION_UP: updateViewPosition(); if (!isOut && Math.abs(event.getX() - mStartX) < 5 && Math.abs(event.getY() - mStartY) < 5) { if (listenner != null) { listenner.onClick(this); Toast.makeText(getContext(),"clicked",Toast.LENGTH_LONG).show(); } } break; } return true; } private void updateViewPosition() { // 更新浮动窗口位置参数 windowManagerParams.x = (int) (mRawX - mStartX); windowManagerParams.y = (int) (mRawY - mStartY); if (this.isShown()) { windowManager.updateViewLayout(this, windowManagerParams); // 刷新显示 } } public void setOnClickListener(OnClickListener onClickListener) { this.listenner = onClickListener; } public void dismiss() { windowManager.removeView(this); isShown = false; } public void show() { windowManagerParams.type = WindowManager.LayoutParams.TYPE_PHONE; // 设置window type windowManagerParams.format = PixelFormat.RGBA_8888; // 设置图片格式,效果为背景透明 // 设置Window flag windowManagerParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; /* * 注意,flag的值可以为: LayoutParams.FLAG_NOT_TOUCH_MODAL 不影响后面的事件 * LayoutParams.FLAG_NOT_FOCUSABLE 不可聚焦 LayoutParams.FLAG_NOT_TOUCHABLE * 不可触摸 */ windowManagerParams.gravity = Gravity.LEFT | Gravity.TOP; // 以屏幕左上角为原点,设置x、y初始值 windowManagerParams.x = DisplayUtil.screenWidth - this.getWidth(); windowManagerParams.y = DisplayUtil.screenHeight - this.getHeight(); // 设置悬浮窗口长宽数据 windowManagerParams.width = WindowManager.LayoutParams.WRAP_CONTENT; windowManagerParams.height = WindowManager.LayoutParams.WRAP_CONTENT; // 显示myFloatView图像 windowManager.addView(this, windowManagerParams); isShown = true; } public boolean isShown() { return isShown; } } <file_sep>package com.bing.waitdialogdemo; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private WaitDialog waitDialog; private ProgressDialog progressDialog; private Button button1, button2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initProgressDialog(); initWaitDialog(); button1 = (Button) findViewById(R.id.btn_main_one); button2 = (Button) findViewById(R.id.btn_main_two); button1.setOnClickListener(this); button2.setOnClickListener(this); } private void initProgressDialog() { progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setIndeterminate(false);//循环滚动 progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage("loading..."); progressDialog.setCancelable(false);//false不能取消显示,true可以取消显示 } private void initWaitDialog() { waitDialog = new WaitDialog(MainActivity.this); waitDialog.setText("loading..."); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_main_one: progressDialog.show(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); progressDialog.dismiss(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); break; case R.id.btn_main_two: waitDialog.show(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); waitDialog.dismiss(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); break; } } } <file_sep>package com.bing.testaidldemo; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.printservice.PrintService; import android.util.Log; import android.widget.Toast; /** * Description * Created by bing on 2015/10/13. */ public class RemoteService extends Service { @Override public void onCreate() { super.onCreate(); Toast.makeText(getApplicationContext(), "onCreate", Toast.LENGTH_SHORT).show(); } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(getApplicationContext(), "onDestroy", Toast.LENGTH_SHORT).show(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Toast.makeText(getApplicationContext(), "onStart", Toast.LENGTH_SHORT).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(getApplicationContext(), "onStartCommand", Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { Toast.makeText(getApplicationContext(), "onBind", Toast.LENGTH_SHORT).show(); return stub; } public void printToast() { Toast.makeText(getApplicationContext(), "aidl的使用", Toast.LENGTH_SHORT).show(); } Iprint.Stub stub = new Iprint.Stub() { @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { } @Override public void print() throws RemoteException { printToast(); } }; // class PrintService extends Iprint.Stub { // // @Override // public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { // // } // // @Override // public void print() throws RemoteException { // printToast(); // } // } } <file_sep>package com.bing.activityforresultdemo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Button button; private TextView textView; private static final int REQUEST_CODE = 0x001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.btn_main); textView = (TextView) findViewById(R.id.tv_main); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivityForResult(intent, REQUEST_CODE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intentData) { super.onActivityResult(requestCode, resultCode, intentData); if (requestCode == REQUEST_CODE && resultCode == SecondActivity.RESULT_CODE) { textView.setText(intentData.getStringExtra("data")); } } }
f1b22e81bd657e2b9a4369cecd1e6883619f291d
[ "Markdown", "Java", "Gradle" ]
10
Java
bingsl/BlogSource
023f990ccfac40d3a95986fe3b9b01cef55536dd
5abc8db4d2bfca5d196e3ed17c76a852f0ed6b35
refs/heads/master
<file_sep>#include <stdio.h> #include<stdlib.h> int main() { int a = 1, b = 2; scanf_s("%d", &a); scanf_s("%d", &b); printf("a=%d, b=%d\n", a, b); system("pause"); return 0; }
fd92e30e270a654f45b0b10825679b25b134cebf
[ "C" ]
1
C
xxiaotianxin/xiaotianxin
f19ce40f52c1125d06eb7435ba048d81644d2bbb
3c8b0e3157d0cb521cc187445091a6558a7b1415
refs/heads/master
<file_sep>import React, { Component, createContext, useEffect, useState } from 'react'; import { auth, createUserProfileDocument, firestore } from '../firebase'; export const UserContext = createContext(); const UserProvider = ({ children }) => { const [user, setUser] = useState(null); var unsubscribeFromAuth = null; useEffect(() => { unsubscribeFromAuth = auth.onAuthStateChanged(async authUser => { if (authUser) { const userRef = await createUserProfileDocument(authUser); userRef.onSnapshot(snapshot => { setUser({ uid: snapshot.id, ...snapshot.data() }); }); } setUser(authUser); }); return () => { unsubscribeFromAuth(); }; }, []); return <UserContext.Provider value={user}>{children}</UserContext.Provider>; }; export default UserProvider; <file_sep>import React, { useState } from 'react'; const AddComment = ({ onCreate }) => { const [content, setContent] = useState(''); const handleSubmit = event => { event.preventDefault(); onCreate({ content }); setContent(''); }; return ( <form onSubmit={handleSubmit} className="AddComment"> <input type="text" name="content" placeholder="Comment" value={content} onChange={event => setContent(event.target.value)} /> <input className="create" type="submit" value="Create Comment" /> </form> ); }; export default AddComment; <file_sep>import React, { useEffect, useState, createContext } from 'react'; import { firestore } from '../firebase'; import { collectIdsAndDocs } from '../utilities'; export const PostsContext = createContext(); const PostsProvider = ({ children }) => { const [posts, setPosts] = useState([]); var unsubscribeFromFirestore = null; useEffect(() => { unsubscribeFromFirestore = firestore .collection('posts') .onSnapshot(snapshot => { const posts = snapshot.docs.map(collectIdsAndDocs); setPosts(posts); }); return () => { unsubscribeFromFirestore(); }; }, []); return ( <PostsContext.Provider value={posts}>{children}</PostsContext.Provider> ); }; export default PostsProvider; <file_sep>import React, { useState } from 'react'; import { signInWithGoogle } from '../firebase'; const SignIn = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = event => { event.preventDefault(); setEmail(''); setPassword(''); }; return ( <form className="SignIn" onSubmit={handleSubmit}> <h2>Sign In</h2> <input type="email" name="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} /> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" value={password} onChange={e => setPassword(e.target.value)} /> <input type="submit" value="Sign In" /> <button onClick={signInWithGoogle}>Sign In With Google</button> </form> ); }; export default SignIn;
faca65726772b9d9962e6904462f36ab057258f6
[ "JavaScript" ]
4
JavaScript
vdtrung1706/think-piece-react-firebase
0b518c8ff04e5905a2a5ca9bdbd16f93f1b96736
58ba4e02ebb6ba373bed15a7c5eab89a45491f93
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Classes; import java.io.*; import java.io.IOException; import java.util.ArrayList; /** * * @author jpfreire */ public class Exporta { public String exportAluno(ArrayList<Aluno> alunos) { File file = new File("base/Alunos.csv"); int lenght = alunos.size(); System.out.println(lenght); String response = ""; try { FileWriter fw = new FileWriter(file); BufferedWriter bf = new BufferedWriter(fw); for (int i = 0; i < lenght; i++) { Aluno temp = alunos.get(i); bf.write(temp.getCod() + ";" + temp.getNome() + ";" + temp.getCpf() + "\n"); } bf.flush(); bf.close(); response = "success"; } catch (IOException e) { response = e.toString(); } return response; } public String exportCurso(ArrayList<Curso> cursos) { File file = new File("base/Cursos.csv"); int lenght = cursos.size(); String response = ""; try { FileWriter fw = new FileWriter(file); BufferedWriter bf = new BufferedWriter(fw); for (int i = 0; i < lenght; i++) { Curso temp = cursos.get(i); bf.write(temp.getCod() + ";" + temp.getNome() + ";" + temp.getCargaH() + "\n"); } bf.flush(); bf.close(); response = "success"; } catch (IOException e) { response = e.toString(); } return response; } public String exportMatricula(ArrayList<Matricula> matriculas) { File file = new File("base/Matriculas.csv"); int lenght = matriculas.size(); String response = ""; try { FileWriter fw = new FileWriter(file, true); BufferedWriter bf = new BufferedWriter(fw); for (int i = 0; i < lenght; i++) { Matricula temp = matriculas.get(i); bf.write(temp.getNumMatricula() + ";" + temp.getDataMatricula() + ";" + temp.getAluno().getNome() + ";" + temp.getCurso().getNome() + "\n"); } bf.flush(); bf.close(); response = "success"; } catch (IOException e) { response = e.toString(); } return response; } public String exportMatriculaSubstitui(ArrayList<Matricula> matriculas) { File file = new File("base/Matriculas.csv"); int lenght = matriculas.size(); String response = ""; try { FileWriter fw = new FileWriter(file); BufferedWriter bf = new BufferedWriter(fw); for (int i = 0; i < lenght; i++) { Matricula temp = matriculas.get(i); bf.write(temp.getNumMatricula() + ";" + temp.getDataMatricula() + ";" + temp.getAluno().getNome() + ";" + temp.getCurso().getNome() + "\n"); } bf.flush(); bf.close(); response = "success"; } catch (IOException e) { response = e.toString(); } return response; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Classes; /** * * @author jpfreire */ public class Aluno { private int cod; private String nome; private String cpf; public Aluno(int cod, String nome, String cpf){ this.cod = cod; this.nome = nome; this.cpf = cpf; } public Aluno(){ this.cod =-1; this.nome = ""; this.cpf = ""; } /** * @return the cod */ public int getCod() { return cod; } /** * @param cod the cod to set */ public void setCod(int cod) { this.cod = cod; } /** * @return the nome */ public String getNome() { return nome; } /** * @param nome the nome to set */ public void setNome(String nome) { this.nome = nome; } /** * @return the cpf */ public String getCpf() { return cpf; } /** * @param cpf the cpf to set */ public void setCpf(String cpf) { this.cpf = cpf; } } <file_sep>compile.on.save=true user.properties.file=/home/jpfreire/snap/netbeans/common/data/11.0/build.properties
4cee08b66047ab101a3cf74b113b24892fc2901e
[ "Java", "INI" ]
3
Java
jpfreire96/exercicio-lps
2db8cd0706c71670c7a213eca81071fc2ffc441f
284cd923fb2db271ea6b05fecd0461d676f051fc
refs/heads/main
<repo_name>Kakkarrot/personal-site<file_sep>/src/assets/deadlockDetectionAlgorithm.cpp /* Author: <NAME> Compiling Instructions: 1. Ensure that input.txt is in the same directory. 2. Compile the program using "g++ deadLockDetectionAlgorithm.cpp -o dda" without quotes. 3. Run the executable using "./dda input.txt" without quotes. */ #include <iostream> #include <string> #include <cstring> #include <fstream> #include <sstream> #include <unordered_map> #include <vector> #include <map> using namespace std; struct myEdge{ int start, finish; }; unordered_map<int, unordered_map<int, int> > outgoingEdges; //node and adjacent neighbors unordered_map<int, unordered_map<int, int> > incomingEdges; //node and adjacent neighbors vector<int> removeSoon; //nodes that have no incoming edges void printVector(vector<int> v); void printMap(unordered_map<int, unordered_map<int, int> > map); void printMap (unordered_map<int, int> map); void getRemoves(); void completeRemoval(); void clearStructures(); void deadlock(); int main(int argc, char ** argv) { if (argc != 2) { printf("Please specify the input file. \n"); exit(-1); } ifstream in; in.open(argv[1]); int offset = 1000000; int process, resource; string currentLine, arrow; stringstream ss; //reading in the input file while (getline(in, currentLine)) { /* multiple test cases can be handled at once, up to a maximum of 20 they must be separated with a # and each case can have a maximum of 100 000 edges once the end of an input is detected, then the algorithm will begin below is an example 1 -> 2 # end of case 1 1 -> 2 */ if (currentLine[0] == '#') { while (true) { getRemoves(); //get the processes that are not deadlocked if (removeSoon.size() == 0) { deadlock(); //print out processes that are in a deadlock clearStructures(); break; } completeRemoval(); } } ss.str(currentLine); ss >> process;ss >> arrow;ss >> resource; resource += offset; //shifting the resource value ss.clear(); //insert input into the graph if(arrow.find("->") != string::npos) { //process requests for a resource if (outgoingEdges.find(process) == outgoingEdges.end()){ //new process not already in graph outgoingEdges.insert(make_pair(process, unordered_map<int, int>())); outgoingEdges[process].insert(make_pair(resource, 0)); } else { //existing process already in graph outgoingEdges[process].insert(make_pair(resource, 0)); } if (incomingEdges.find(resource) == incomingEdges.end()){ //new resource not already in graph incomingEdges.insert(make_pair(resource, unordered_map<int, int>())); incomingEdges[resource].insert(make_pair(process, 0)); } else { //existing resource already in graph incomingEdges[resource].insert(make_pair(process, 0)); } } else { //process is holding the resource if (outgoingEdges.find(resource) == outgoingEdges.end()) { //new resource not already in graph outgoingEdges.insert(make_pair(resource, unordered_map<int, int>())); outgoingEdges[resource].insert(make_pair(process, 0)); } else { //existing resource already in graph outgoingEdges[resource].insert(make_pair(process, 0)); } if (incomingEdges.find(process) == incomingEdges.end()) { //new process not already in graph incomingEdges.insert(make_pair(process, unordered_map<int, int>())); incomingEdges[process].insert(make_pair(resource, 0)); } else { //existing process already in graph incomingEdges[process].insert(make_pair(resource, 0)); } } } while (true) { //same code as before to handle the last test case if a file has multiple test cases getRemoves(); if (removeSoon.size() == 0) { deadlock(); clearStructures(); break; } completeRemoval(); } } //clears all data structures for the next test case void clearStructures(){ outgoingEdges.clear(); incomingEdges.clear(); removeSoon.clear(); } //prints out all deadlocked processes void deadlock(){ cout << "Deadlocked processes: "; if (outgoingEdges.size() != 0) { map<int, unordered_map<int, int> > sorted (outgoingEdges.begin(), outgoingEdges.end()); int i = 0; for (auto itr = sorted.begin(); itr != sorted.end(); ++itr) { if (itr->first < 1000000) { cout << itr->first << " "; i++; if (i%10 == 0) cout << '\n'; } } cout << '\n'; } else { cout << "none" << '\n'; } } //removes the processes that have been identified to not be part of the deadlock void completeRemoval(){ unordered_map<int, int> :: iterator itr; for (int i = 0; i < removeSoon.size(); i++) { int node = removeSoon[i]; for (itr = incomingEdges[node].begin(); itr != incomingEdges[node].end(); itr++) { int edge = itr->first; outgoingEdges[edge].erase(node); if (outgoingEdges[edge].size() == 0) { //no more outgoing edges outgoingEdges.erase(edge); } } incomingEdges.erase(node); } removeSoon.clear(); } //only looks at incomingEdges and checks outgoingEdges //find the processes that cannot be part of the deadlock void getRemoves() { unordered_map<int, unordered_map<int, int> > :: iterator itr; for (itr = incomingEdges.begin(); itr != incomingEdges.end(); itr++) { if (outgoingEdges.find(itr->first) == outgoingEdges.end()) { //no outgoing edges removeSoon.push_back(itr->first); } } } //utility function for printing the contents of a vector void printVector(vector<int> v) { for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << '\n'; } //utility function for printing the contents of an unordered map void printMap(unordered_map<int, unordered_map<int, int> > map){ unordered_map<int, unordered_map<int, int> > :: iterator itr; unordered_map<int, int> :: iterator itr2; cout << "-------------------------------------\n"; for (itr = map.begin(); itr != map.end(); itr++) { cout << itr->first << ": "; for (itr2 = map[itr->first].begin(); itr2 != map[itr->first].end(); itr2++) { cout << itr2->first << " "; } cout << '\n'; } } //utility function for printing the contents of an unordered map void printMap (unordered_map<int, int> map) { unordered_map<int, int> :: iterator itr; cout << "-------------------------------------\n"; for (itr = map.begin(); itr != map.end(); itr++) { cout << itr->first << '\n'; } } <file_sep>/src/app/app-routing.module.ts import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {AboutMeComponent} from './about-me/about-me.component'; import {EducationComponent} from './education/education.component'; import {WorkExperienceComponent} from './work-experience/work-experience.component'; import {RecentWorkComponent} from './recent-work/recent-work.component'; import {ContactInformationComponent} from './contact-information/contact-information.component'; import {ExtracurricularsComponent} from './extracurriculars/extracurriculars.component'; const routes: Routes = [ {path: 'about', component: AboutMeComponent}, {path: 'education', component: EducationComponent}, {path: 'experience', component: WorkExperienceComponent}, {path: 'projects', component: RecentWorkComponent}, {path: 'extracurriculars', component: ExtracurricularsComponent}, {path: 'contact', component: ContactInformationComponent}, {path: '**', redirectTo: '/about', pathMatch: 'full'} ]; @NgModule({ imports: [RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})], exports: [RouterModule] }) export class AppRoutingModule { } export const routingComponents = [ AboutMeComponent, EducationComponent, WorkExperienceComponent, RecentWorkComponent, ContactInformationComponent, ExtracurricularsComponent ]; <file_sep>/src/app/contact-information/contact-information.component.ts import {Component, OnInit} from '@angular/core'; import {HomeNavBarComponent} from '../home-nav-bar/home-nav-bar.component'; @Component({ selector: 'app-contact-information', templateUrl: './contact-information.component.html', styleUrls: ['./contact-information.component.scss'] }) export class ContactInformationComponent implements OnInit { constructor(private bar: HomeNavBarComponent) { } ngOnInit() { this.bar.displaySection = 'Contact Information'; } } <file_sep>/src/app/recent-work/recent-work.component.ts import { Component, OnInit } from '@angular/core'; import { HomeNavBarComponent } from '../home-nav-bar/home-nav-bar.component'; @Component({ selector: 'app-recent-work', templateUrl: './recent-work.component.html', styleUrls: ['./recent-work.component.scss'] }) export class RecentWorkComponent implements OnInit { SARP1 = 'As my experience in software engineering slowly accumulated, the questions that plagued my mind began to ' + 'change. When I first started out, my designs only accounted for the features that I developed, ' + 'or how I envisioned the final product. Architecture was never a primary concern and performance ' + 'was rarely an issue. However, as my projects increase in magnitude, with no more time to spare, ' + 'I found myself invested in not only the final product but also the development process. '; SARP2 = 'I took some time to research a few common design patterns, with a focus on web applications. ' + 'Issues that interested me included scalability, data-consistency, but most importantly, ' + 'the ability to develop across a team with a given architecture. The paper can be found below. '; OVRP1 = 'Ever since high school, I have been an avid trader in the equity markets. I started off ' + 'with stocks and ETFs, and took positions based on a mix of fundamental and technical analysis. ' + 'However, it was not long after that I was introduced to a various other financial instruments, ' + 'one of which being options. There were several appealing characteristics about options, which ' + 'made them appear vastly superior to all the other financial instruments out there. One, was the ' + 'ability to realize profits regardless of market conditions, while the other was how incredibly ' + 'complicated the mathematics of these derivative instruments could become. '; OVRP2 = 'During my time on the University of Calgary Trading Team, I learned of the Rotman ' + 'International Trading Competition, which featured a Black-Scholes options case. Although ' + 'I had always known how to navigate the Greeks when executing trades, I had yet to work ' + 'out the mathematics behind them. Aside from the algorithmic trading cases, this was the ' + 'only other case that allowed for API order entry. I built what would become the most robust ' + 'options case model that the team had access to, going as far as to identify new ' + 'opportunities which the team had no prior knowledge on or ability to trade. This was ' + 'only the starting point for me. Later, I would go on to apply the concepts from the case ' + 'to real markets, ultimately producing the paper below. '; deadlock1 = 'In a system of only processes and resources - where there is only one instance of every resource - if there ' + 'exists a cycle, then there must be a deadlock. '; deadlock2 = 'In the above picture, there are 2 resources (R1, R2) and 3 processes (P1, P2, P3). An outgoing edge from a process to a ' + 'resource means that a process is waiting for the resource, while an outgoing edge from a resource to a process means that the' + ' resource is held by the process. Since there is a cycle, there is a deadlock in the system. P3 and P2 are in a deadlock. I wrote' + ' a C++ program on linux that checks the aforementioned system for deadlocks. The input file for the above system must be ' + 'configured as follows: '; deadlockInput = '1 <- 1\n3 <- 1\n3 -> 2\n2 <- 2\n2 -> 1'; deadlockInput2 = 'The program only supports inputs where process and resource numbers range from 0 to 100 000 inclusive ' + 'where input cases can have up to a maximum of 100 000 lines of input (graph edges). '; deadlock3 = 'All process numbers are on the left hand side of the arrow and all resource numbers are on the right hand ' + 'side of the arrow. If there is a cycle, my program will print out a sorted list of all deadlocked processes. ' + 'The program and a sample input file can be found below. '; technicalAnalysis1 = 'A non-traditional way of valuing equities is through technical analysis. ' + 'Technical analysis does not look at the value of the underlying assets, but instead relies on an efficient market ' + 'hypothesis and price action of the equity powered by supply and demand. By itself, technical ' + 'analysis provides little insight into the value of a company, but it can support an investment thesis. '; technicalAnalysis2 = 'During my time as a sector head with Finesse Wealth Management (FMW), ' + 'my team looked to value stocks fundamentally but wished to incorporate some technical analysis ' + 'to not only support the investment thesis but also identify ideal entry and exit prices. Eventually, ' + 'it became a standard in FMW to include both fundamental analysis and technical analysis in stock pitches. ' + 'However, I soon found that not everyone had a good background in technical analysis, ' + 'as it was not usually covered in classes, and I would spend a fair bit of time every week teaching ' + 'different parts of it to different people. Thus, I put together a comprehensive guide to technical ' + 'analysis and distributed it within FMW. The guide can be found below: '; DMAD = 'For the purpose of book keeping and auditing, companies must keep records of their expenses. ' + 'One way of doing this is keeping receipts. However, receipts tend to get damaged and faded over time. ' + 'To solve this problem, my team and I decided to develop an expense handler, so that companies will be ' + 'able to store and process their receipts electronically. This completely eliminates the need for a paper copy. '; DMAD2 = 'A simplifed overview of the system in mind includes a secretary and an employee. ' + 'When employees recieve a receipt, they will take a picture of it and fill in a few details. ' + 'Then they will store the picture of the receipt and associated details in a company database. ' + 'The secretary can process these receipts in the database and generate a report for auditing purposes later if necessary. '; DMAD3 = 'I decided to take on the design aspect of the project. With the system requirements in mind, ' + 'I created an enhanced entity relationship diagram (EERD) and mapped it to a relational schema. ' + 'Both the EERD and relational schema can be found below: '; constructor(private bar: HomeNavBarComponent) { } ngOnInit() { // tslint:disable-next-line:indent this.bar.displaySection = 'Recent Work'; } } <file_sep>/src/app/about-me/about-me.component.ts import {Component, OnInit} from '@angular/core'; import {HomeNavBarComponent} from '../home-nav-bar/home-nav-bar.component'; @Component({ selector: 'app-about-me', templateUrl: './about-me.component.html', styleUrls: ['./about-me.component.scss'] }) export class AboutMeComponent implements OnInit { bioIntro = 'My name is Willie and I am an undergraduate student at the University of Calgary. ' + 'Currently, I am studying towards a combined BSc/BComm degree in Software Engineering and Finance respectively. ' + 'I chose this degree path because I discovered a passion for both software development and equity research. '; bioSoftware = 'As a child, I learned that most of the best technology products have a user friendly interface. ' + 'Therefore, a good idea could quickly be dismissed if it had a unsatisfactory design - "quality over quantity."'; bioStocks = 'During my high school years, I discovered that I also had an interest in investing. ' + 'One thing led to another and eventually, I enrolled in and completed a 2-year education program on stocks and options. ' + 'Using what I learned, I trade weekly and often experiment with different types of investing software - ' + 'sometimes even writing a little bit of code when my imagination permits. '; bioSelf = 'Outside of software and finance, I am very active. I play basketball, do gymnastics, and go hiking primarily, ' + 'but I am also open to most kinds of physical activity. When I need to rest, I often indulge in a book. ' + 'Of the many books that I have read to date, my favourite book is still "The Seven Habits of Highly Effective People" - ' + 'by <NAME>. I like this book because it is about self improvement; I believe that I can always work to better myself, ' + 'and by doing so, my work will naturally improve as well. '; constructor(private bar: HomeNavBarComponent) { } ngOnInit() { this.bar.displaySection = 'About Me'; window.scrollTo(2000, 2000); } } <file_sep>/src/app/home-nav-bar/home-nav-bar.component.ts import {Component, ViewChild } from '@angular/core'; import {Injectable} from '@angular/core'; import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout'; import {Observable} from 'rxjs'; import { Router, NavigationEnd } from '@angular/router'; import {map, filter, withLatestFrom } from 'rxjs/operators'; import { MatSidenav } from '@angular/material'; @Component({ selector: 'app-home-nav-bar', templateUrl: './home-nav-bar.component.html', styleUrls: ['./home-nav-bar.component.scss'] }) @Injectable() export class HomeNavBarComponent { @ViewChild ('drawer', {static: false}) drawer: MatSidenav; constructor(private breakpointObserver: BreakpointObserver, router: Router) { router.events.pipe( withLatestFrom(this.isHandset$), filter(([a, b]) => b && a instanceof NavigationEnd) ).subscribe(_ => this.drawer.close()); } name = '<NAME>'; displaySection = ''; isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches) ); } <file_sep>/src/app/work-experience/work-experience.component.ts import { Component, OnInit } from '@angular/core'; import { HomeNavBarComponent } from '../home-nav-bar/home-nav-bar.component'; @Component({ selector: 'app-work-experience', templateUrl: './work-experience.component.html', styleUrls: ['./work-experience.component.scss'] }) export class WorkExperienceComponent implements OnInit { constructor(private bar: HomeNavBarComponent) { } ngOnInit() { this.bar.displaySection = "Work Experience"; } } <file_sep>/src/app/extracurriculars/extracurriculars.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ExtracurricularsComponent } from './extracurriculars.component'; describe('ExtracurricularsComponent', () => { let component: ExtracurricularsComponent; let fixture: ComponentFixture<ExtracurricularsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ExtracurricularsComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ExtracurricularsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/app.component.ts import {Component, OnInit} from '@angular/core'; import {NavigationEnd, Router} from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'Personal Site'; window: Element; constructor(private router: Router) { } ngOnInit(): void { this.router.events.subscribe(event => { // Scroll to top if accessing a page, not via browser history stack if (event instanceof NavigationEnd) { const contentContainer = document.querySelector('.mat-sidenav-content') || this.window; contentContainer.scrollTo(0, 0); } }); } }
f89dce23cc90ec15a1010da176ed5311d3be0641
[ "TypeScript", "C++" ]
9
C++
Kakkarrot/personal-site
45c837d30cd7c9f31dc60d9c50e81bcc93b8360f
70025a6b531997347fa0e9f5a230825fabefc479
refs/heads/master
<repo_name>JoelBuhrman/WakeUpBuddy<file_sep>/app/src/main/java/com/example/joelbuhrman/wakeupbuddy/BuddiesAdapter.java package com.example.joelbuhrman.wakeupbuddy; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; /** * Created by JoelBuhrman on 16-06-21. */ public class BuddiesAdapter extends BaseAdapter { String[] buddiesNames; Context context; private static LayoutInflater inflater = null; public BuddiesAdapter(Context applicationContext, String[] buddiesNames) { this.context = applicationContext; this.buddiesNames = buddiesNames; inflater = (LayoutInflater) context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return buddiesNames.length; } @Override public Object getItem(int i) { return i; } @Override public long getItemId(int i) { return i; } @Override public View getView(final int i, View view, ViewGroup viewGroup) { View rowView = inflater.inflate(R.layout.custom_list_row, null); TextView name= (TextView)rowView.findViewById(R.id.custom_list_row_name); name.setText(buddiesNames[i]); name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context, "You Clicked "+buddiesNames[i], Toast.LENGTH_LONG).show(); } }); return rowView; } }
cf3da8edc4ac2a2f0f5e09527ee4017c0f4ae6d0
[ "Java" ]
1
Java
JoelBuhrman/WakeUpBuddy
0feb9f776a226b0618107d122de6c5c3da5dae2a
ae9630ded2d4c48e6386846f40d9a0a507245297
refs/heads/master
<repo_name>Paul-Kyle-Turner/Quicksort-Random<file_sep>/main.py import numpy as np import timeit import pandas as pd import matplotlib.pyplot as plt import random import statistics import math def quick_sort(partition_func, ar, p, r): if p < r: q = partition_func(ar, p, r) quick_sort(partition_func, ar, p, q-1) quick_sort(partition_func, ar, q+1, r) def random_partition(ar, p, r): i = random.randint(p, r) print(i) ar[r], ar[i] = ar[i], ar[r] return partition(ar, p, r) def partition(ar, p, r): i = (p - 1) pivot = ar[r] for j in range(p, r): if ar[j] <= pivot: i = i + 1 ar[i], ar[j] = ar[j], ar[i] ar[(i + 1)], ar[r] = ar[r], ar[(i + 1)] return i + 1 def create_random_array(number_of_elements): return np.random.randint(-10000, 10000, number_of_elements) def quick_sort_time(start, stop, by, partition_function='partition', file='non_random_times.txt', two_to_the=False): SETUP_CODE = ''' from __main__ import create_random_array from __main__ import partition from __main__ import random_partition from __main__ import quick_sort import random import numpy as np''' TEST_CODE = ''' a = create_random_array(a_size) quick_sort(partition, a, 0, len(a) - 1)''' times = list() if two_to_the: for i in range(start, stop): q = int(math.pow(2, i)) print(i) print(q) time = timeit.repeat(setup=SETUP_CODE, stmt=TEST_CODE.replace('a_size', str(q)).replace('partition', partition_function), number=10000) print(time) a_time = statistics.mean(time) print(a_time) times.append(a_time) else: for i in range(start, stop, by): print(i) time = timeit.repeat(setup=SETUP_CODE, stmt=TEST_CODE.replace('a_size', str(i)).replace('partition', partition_function), number=10000) print(time) a_time = statistics.mean(time) print(a_time) times.append(a_time) with open(file, "w+") as file: for t in times: file.write('%s\n' % t) return times if __name__ == '__main__': starts = 1 stops = 11 bys = 1 quick = quick_sort_time(starts, stops, bys, two_to_the=True) quick_random = quick_sort_time(starts, stops, bys, partition_function='random_partition', file='random_quick.txt', two_to_the=True) data = pd.DataFrame({'x': range(starts, stops, bys), 'non_random': quick, 'random': quick_random}) plt.plot('x', 'non_random', data=data) plt.plot('x', 'random', data=data) plt.legend() plt.show()
e693b2271f5eb5bcd9e364cfe304aba0b94e90cc
[ "Python" ]
1
Python
Paul-Kyle-Turner/Quicksort-Random
badf42494f7ec69a53f0e452b924bb158c406421
c9e732cae40c71ae4723d8fe466ae2fbf3ecd1ee
refs/heads/master
<repo_name>parpat/distboruvka<file_sep>/Dockerfile #FROM golang:onbuild FROM golang:latest RUN mkdir /app ADD . /app/ WORKDIR /app/ #RUN go build -o main . CMD ["/app/cmd/node/node"] #Service listens on port 7575. EXPOSE 7575 <file_sep>/cmd/node/node.go package main import ( "fmt" "log" "math" "math/rand" "strconv" "strings" "sync" "time" stats "github.com/montanaflynn/stats" distb "github.com/parpat/distboruvka" ) //GATEWAY is the last octet of the docker subnetwork const GATEWAY string = "1" const PushSumIterations = 30 var psData [PushSumIterations]float64 func processMessages(reqs chan distb.Message) { for m := range reqs { //update edge message counter if m.SourceID != "gateway" { //fmt.Println("Received From: ", m.SourceID) updateMessageCounter(m.SourceID) } switch m.Type { case "ReqAdjEdges": go sendEdges() case "MSTBranch": go markBranch(m.Edges[0]) case "PushSum": TnumPushMsg++ pushSum(m.S, m.W) case "DumTraffic": go dumTraffic(m.SourceID) case "TrafficData": go sendTrafficData() case "IsHighTraffic": log.Println("sending HIGH TRAFFIC REPLY") distb.SendMessage(distb.Message{SourceID: ThisNode.ID, HighTraffic: IsHighTraffic, Type: "IsHighTrafficReply"}, ThisNode.ID, m.SourceID) case "IsHighTrafficReply": adjTrafficChan <- m.HighTraffic } } } //TODO:Send sorted edges func sendEdges() { msg := distb.Message{Edges: *ThisNode.AdjacencyList} distb.SendMessage(msg, ThisNode.ID, GATEWAY) } func markBranch(e distb.Edge) { idx := ThisNode.FindEdgeIdx(e.Weight) (*ThisNode.AdjacencyList)[idx].SE = "Branch" fmt.Printf("%v is now a Branch\n", e.Weight) } //Keep pushing dummy traffic to random nodes func dumTraffic(inID string) { //Choose random neighbor rand.Seed(time.Now().UnixNano()) //ThisNode.RLock() //defer ThisNode.RUnlock() randAdjEdge := (*ThisNode.AdjacencyList)[0] if len(*ThisNode.AdjacencyList) > 1 { randAdjEdge = (*ThisNode.AdjacencyList)[rand.Intn(len(*ThisNode.AdjacencyList))] } /* if len(*ThisNode.AdjacencyList) > 1 { for { randAdjEdge = (*ThisNode.AdjacencyList)[rand.Intn(len(*ThisNode.AdjacencyList))] if randAdjEdge.AdjNodeID != inID { break } } } else { // drop message return }*/ //fmt.Println("Dum message sent to: ", randAdjEdge.AdjNodeID) time.Sleep(time.Millisecond * 20) randAdjEdge.Send(&distb.Message{Type: "DumTraffic"}) updateMessageCounter(randAdjEdge.AdjNodeID) } func sendTrafficData() { ThisNode.RLock() msg := distb.Message{BufferA: TnumMsg, BufferB: TnumPushMsg, HighTraffic: IsHighTraffic, Edges: HighRiskEdges} ThisNode.RUnlock() distb.SendMessage(msg, ThisNode.ID, GATEWAY) } func dummyInjector() { for { time.Sleep(time.Millisecond * 5000) dumTraffic("999") } } func updateMessageCounter(adjnode string) { ThisNode.Lock() ThisNode.AdjacencyMap[adjnode].MessageCount++ ThisNode.Unlock() } //pushSum protocol is a form of network aggregation used to calculate //the average value between nodes in a distributed fashion. The propagation //of data is achieved using simple gossip protocol by selecting a uniformly random neighbor //to send data to. var lastRatio = 0.0 var ratioConvergeCount = 0 var converged = false var convergenceDiff = 0.000000001 var pushSumCounter = 0 //keeps track of the number of samples func pushSum(st, wt float64) { if !PushSumActive { //In case first node to start push sum then hold barrier if err := distb.Barrier.Hold(); err != nil { log.Printf("could not hold barrier (%v)\n", err) } go watchBarrier() lastRatio = 0.0 ratioConvergeCount = 0 converged = false //Keep same traffic snapshot until number of samples complete psStateLock.Lock() if Ti == 0 { Ti, BEi = getCurrMaxTraffic() } else if pushSumCounter >= PushSumIterations { Ti, BEi = getCurrMaxTraffic() pushSumCounter = 0 log.Println("Push Sum counter reset") } PushSumActive = true //S = Ti max traffic edge Edge S = float64(TnumMsg) //total traffic on node W = 1 psStateLock.Unlock() } S += st W += wt ratio := S / W //Stop disseminating messages once converged //Converged when ratio does not change more than 10^-8 for 3 consecutive values diff := ratio - lastRatio lastRatio = ratio if math.Abs(diff) < convergenceDiff { ratioConvergeCount++ if ratioConvergeCount >= 3 { converged = true if err := distb.Barrier.Release(); err != nil { log.Printf("could not Release barrier (%v)\n", err) } else { log.Println("Barrier Released") } fmt.Println("CONVERGED PUSH-SUM") distb.SendMessage(distb.Message{Type: "Average", Avg: ratio}, ThisNode.ID, GATEWAY) return } } else { ratioConvergeCount = 0 } //Choose random neighbor rand.Seed(time.Now().UnixNano()) randAdjEdge := (*ThisNode.AdjacencyList)[rand.Intn(len(*ThisNode.AdjacencyList))] //Send pair (0.5S, 0.5W) sh := S / 2 wh := W / 2 msgPush := &distb.Message{Type: "PushSum", S: sh, W: wh, SourceID: ThisNode.ID} //time.Sleep(time.Millisecond * 1) fmt.Println("PUSH-SUM Send to: ", randAdjEdge.AdjNodeID) randAdjEdge.Send(msgPush) updateMessageCounter(randAdjEdge.AdjNodeID) S += sh W += wh fmt.Println("Current Average: ", S/W) } func watchBarrier() { log.Println("Waiting on Barrier") if err := distb.Barrier.Wait(); err != nil { log.Fatalf("could not wait on barrier (%v)", err) } psStateLock.Lock() defer psStateLock.Unlock() PushSumActive = false pushSumCounter++ psData[pushSumCounter-1] = S / W if pushSumCounter >= PushSumIterations { calcStats() findHighRiskEdges() } else { log.Println("Did not calc stats; counter: ", pushSumCounter) highTrafficCheck = true } log.Println("Ending PushSum, Converged: ", S/W) log.Println("Traffic at convergence: ", Ti) log.Println("Total Num messages: ", TnumMsg) } func calcStats() { //psStateLock.RLock() //defer psStateLock.RUnlock() statsData := stats.Float64Data(psData[:]) stdDev, err := statsData.StandardDeviation() fmt.Printf("Std_Dev: %.3f\n", stdDev) if err != nil { log.Println("Couldnt calc StandardDeviation") } mean, _ := statsData.Mean() fmt.Printf("Mean: %.3f\n", mean) threshold := (2.0 * stdDev) + mean lowThreshold := (1.1 * stdDev) + mean ThisNode.Lock() defer ThisNode.Unlock() if float64(TnumMsg) >= threshold { fmt.Printf("High traffic! Node: %v Edge: %v\n", Ti, BEi) IsHighTraffic = true } else if float64(TnumMsg) >= (lowThreshold) { fmt.Printf("Unlikely Bottleneck! Node: %v Edge: %v\n", Ti, BEi) IsHighTraffic = true } highTrafficCheck = true } func getCurrMaxTraffic() (float64, int) { var max = 0 var edgeWeight = 0 ThisNode.Lock() defer ThisNode.Unlock() TnumMsg = 0 for _, e := range ThisNode.AdjacencyMap { TnumMsg += e.MessageCount log.Printf("Traffic at link TO %s IS %d\n", e.AdjNodeID, e.MessageCount) if max < e.MessageCount { max = e.MessageCount edgeWeight = e.Weight } } log.Println("Max Traffic: ", max) log.Println("Node Total: ", TnumMsg) return float64(max), edgeWeight } func findHighRiskEdges() { ThisNode.RLock() isThisHT := IsHighTraffic ThisNode.RUnlock() if isThisHT { for _, e := range *ThisNode.AdjacencyList { e.Send(&distb.Message{SourceID: ThisNode.ID, Type: "IsHighTraffic"}) log.Println("--> HIGH TRAFFIC CHECK --->", e.AdjNodeID) isAdjNodeHT := <-adjTrafficChan log.Println("<-- HIGH TRAFFIC CHECK REPLY<---", isAdjNodeHT) if isAdjNodeHT { HighRiskEdges = append(HighRiskEdges, e) } } } } var ( //ThisNode local attributes of the node ThisNode *distb.Node requests chan distb.Message Logger *log.Logger S float64 W float64 Ti float64 BEi int TnumMsg int HighRiskEdges distb.Edges startpush bool PushSumActive bool psStateLock = &sync.RWMutex{} IsHighTraffic bool highTrafficCheck bool adjTrafficChan chan bool TnumPushMsg int ) func init() { hostName, hostIP := distb.GetHostInfo() octets := strings.Split(hostIP, ".") log.Printf("My ID is: %s\n", octets[3]) nodeID := octets[3] edges, adjMap := distb.GetGraphDOTFile("/home/parth/workspace/networkgen/graph.dot", nodeID) ThisNode = &distb.Node{ ID: nodeID, Name: hostName, AdjacencyList: &edges, AdjacencyMap: adjMap} log.Printf("ADJLIST: %v\n", *ThisNode.AdjacencyList) //logfile, err := os.Create("/logs/log" + strconv.Itoa(nodeID)) // if err != nil { // log.Fatal(err) // } //Logger = log.New(logfile, "logger: ", log.Lshortfile) _ = Logger //Initializing sum var S, _ = strconv.ParseFloat(nodeID, 64) W = 1 //Checking if current process will begin pushSum //if pushSumStart == nodeID { // startpush = true //} //channel for findHighRiskEdges that concurrently queries adj nodes //and waits for reply adjTrafficChan = make(chan bool) } func main() { requests = make(chan distb.Message, 25) notListening := make(chan bool) go distb.ListenAndServeTCP(notListening, requests) //Process incomming messages go processMessages(requests) go distb.SetNodeInfo(ThisNode.Name, ThisNode.ID) time.Sleep(time.Second * 100) //go dummyInjector() // Consistently generate messages dumTraffic("999") // For starting with one message <-notListening } <file_sep>/quickFind/qf_test.go package quickFind import ( "fmt" "testing" ) var ( qftestSuite = []struct{ from, to int }{ {4, 3}, {3, 8}, {6, 5}, {9, 4}, {2, 1}, {5, 0}, {7, 2}, {6, 1}, } ) //TODO: Proper testing func TestUnion(t *testing.T) { qfTestT := InitializeQF(10) for _, pair := range qftestSuite { fmt.Println(qfTestT.Connected(pair.from, pair.to)) qfTestT.Union(pair.from, pair.to) fmt.Println(qfTestT.Connected(pair.from, pair.to)) fmt.Printf("Total components:%v\n", qfTestT.GetComponents()) } } <file_sep>/edge.go package distboruvka import ( "encoding/gob" "log" "net" "sync" ) //Edge is the overlay link between nodes type Edge struct { AdjNodeID string Weight int //Edge weight SE string //Edge state Origin string MessageCount int } //Edge States const ( Basic string = "Basic" //not yet decided whether the edge is part //of the MST or not Branch string = "Branch" //The edge is part of the MST Rejected string = "Rejected" //The edge is NOT part of the MST ) //Edges is a sortable edgelist type Edges []Edge func (e Edges) Len() int { return len(e) } func (e Edges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e Edges) Less(i, j int) bool { return e[i].Weight < e[j].Weight } //Reusing this encoder variable creates a race condition when multiple //routines invoke *Edge.Send() and write assign NewEncoder writes //var enc *gob.Encoder //Send message to the adjacent node of the edge func (e *Edge) Send(m *Message) { conn, err := net.Dial("tcp", SUBNET+e.AdjNodeID+":"+PORT) if err != nil { log.Println(err) log.Printf("conn null? %v\n", conn == nil) } else { m.SourceID = e.Origin enc := gob.NewEncoder(conn) err = enc.Encode(m) if err != nil { log.Fatal(err) } } } //Node is the container's info type Node struct { ID string Name string AdjacencyList *Edges sync.RWMutex AdjacencyMap map[string]*Edge //AdacencyMap holds edge for each adjacent node } //FindEdgeIdx returns the index in the adjacency list func (n *Node) FindEdgeIdx(weight int) int { for i, e := range *n.AdjacencyList { if e.Weight == weight { return i } } return 0 } <file_sep>/bdi.sh docker rmi distboruvka cd cmd/node go build -race cd ../.. docker build -t distboruvka . <file_sep>/communication.go package distboruvka import ( "encoding/gob" "fmt" "log" "net" ) //SUBNET of docker network const SUBNET string = "172.17.0." //PORT is main comm port const PORT string = "7575" //Message is the template for commuication type Message struct { Type string SourceID string Edges Edges S float64 W float64 Avg float64 BufferA int // Total Num of Messages BufferB int //Push-Sum Messages HighTraffic bool } //SendMessage sends the message to a destination in the docker network func SendMessage(m Message, srcID, destID string) { cliconn, err := net.Dial("tcp", SUBNET+destID+":"+PORT) if err != nil { log.Println(err) //log.Printf("conn null? %v\n", conntwo == nil) } else { m.SourceID = srcID enc := gob.NewEncoder(cliconn) if err = enc.Encode(m); err != nil { log.Println(err) } else { //log.Printf("%v Sent\n", m.Type) } } } //ServeConn receives and decodes gob Message func ServeConn(c net.Conn, reqs chan Message) { defer c.Close() var msg Message dec := gob.NewDecoder(c) err := dec.Decode(&msg) if err != nil { fmt.Print(err) } //log.Println(c.RemoteAddr()) reqs <- msg //fmt.Printf("Receieved message: %v\n", msg.Type) } //ListenAndServeTCP listens for tcp requests and serves connections by //putting messages in the request queue func ListenAndServeTCP(listening chan bool, requests chan Message) { defer func() { listening <- false }() l, err := net.Listen("tcp", ":"+PORT) //fmt.Println("Listening") log.Println("Listening") if err != nil { log.Fatal(err) } for { conn, err := l.Accept() if err != nil { log.Fatal(err) } //fmt.Println("serving Conn") // Handle the connection in a new goroutine. go ServeConn(conn, requests) } } <file_sep>/quickFind/qf.go package quickFind //QF holds the IDs of components type QF struct { ID []int } //InitializeQF initializes the DS by putting each element in its own compoenent func InitializeQF(n int) QF { q := QF{make([]int, n)} for i := 0; i < n; i++ { q.ID[i] = i } return q } //Find returns the ID of component for which the vertex belongs to func (q *QF) Find(p int) int { return q.ID[p] } //Connected checks if the elements have the same parent func (q *QF) Connected(e1, e2 int) bool { return q.Find(e1) == q.Find(e2) } //Union merges the components of the two elements. func (q *QF) Union(s, t int) { sid := q.ID[s] tid := q.ID[t] for i := 0; i < len(q.ID); i++ { if q.ID[i] == sid { q.ID[i] = tid } } } //GetComponents returns the total number of components func (q *QF) GetComponents() map[int]int { componentTrees := make(map[int]int) for _, c := range q.ID { componentTrees[c]++ } return componentTrees } <file_sep>/cmd/mediator/mediator.go package main import ( "encoding/csv" "fmt" "log" "math/rand" "os" "sort" "strconv" "time" distb "github.com/parpat/distboruvka" "github.com/parpat/distboruvka/quickFind" ) var ( requests chan distb.Message ) func initBoruvka() { nodes := distb.GetNodes() //1 Initialize a forest T to be a set of one-vertex trees, one for each vertex of the graph. forest := quickFind.InitializeQF(len(nodes)) T := *new(distb.Edges) //2 While T has more than one component: for comps := forest.GetComponents(); len(comps) > 1; comps = forest.GetComponents() { //if //fmt.Printf("Components: %v\n", comps) // 3 For each component C of T: for c := range comps { // 4 Begin with an empty set of edges S S := *new(distb.Edges) // 5 For each vertex v in C: fmt.Printf("Iterating component: %v\n", c) for _, n := range nodes { id, _ := strconv.Atoi(n.ID) if forest.ID[id-2] == c { distb.SendMessage(distb.Message{Type: "ReqAdjEdges"}, "gateway", n.ID) m := <-requests // 6 Find the cheapest edge from v to a vertex outside of C, and add it to S for _, cedge := range m.Edges { currnode, _ := strconv.Atoi(cedge.Origin) adjnode, _ := strconv.Atoi(cedge.AdjNodeID) if forest.Find(currnode-2) != forest.Find(adjnode-2) { S = append(S, cedge) break } } } //fmt.Printf("%s's min Edge: -%v> %v\n ", m.Edges[0].Origin, m.Edges[0].Weight, m.Edges[0].AdjNodeID) } if S != nil { sort.Sort(S) fmt.Printf("S: %v\n", S) T = append(T, S[0]) } } // 8 Combine trees connected by edges to form bigger components for _, combEdge := range T { currnode, _ := strconv.Atoi(combEdge.Origin) currnode -= 2 adjnode, _ := strconv.Atoi(combEdge.AdjNodeID) adjnode -= 2 if forest.Find(currnode) != forest.Find(adjnode) { forest.Union(currnode, adjnode) fmt.Printf("Combined nodes %v %v\n", currnode, adjnode) } } } removeDuplicates(&T) sort.Sort(T) //Sending mst branches to their endpoints for _, mste := range T { mstBranchmsg := distb.Message{Type: "MSTBranch", Edges: distb.Edges{mste}} distb.SendMessage(mstBranchmsg, "gateway", mste.Origin) distb.SendMessage(mstBranchmsg, "gateway", mste.AdjNodeID) fmt.Printf("MST Edge W: %d\n", mste.Weight) } //return T } func removeDuplicates(dup *distb.Edges) { found := make(map[int]bool) j := 0 for i, de := range *dup { if !found[de.Weight] { found[de.Weight] = true (*dup)[j] = (*dup)[i] j++ } } *dup = (*dup)[:j] } //calcAverage initiated the push-sum protocol among the nodes //the results should be send back to the mediator after convergence func calcAverage(csvFile *os.File) { defer csvFile.Close() rand.Seed(time.Now().UnixNano()) for i := 0; i < 30; i++ { //Intn[,n) n := rand.Intn(90) + 2 log.Println("Seed PS at: ", n) distb.SendMessage(distb.Message{Type: "PushSum", S: 0, W: 0}, "gateway", strconv.Itoa(n)) m := <-requests avgstr := fmt.Sprintf("%.3f", m.Avg) log.Printf("Average at: %d is %s\n", i, avgstr) csvFile.WriteString(avgstr + ",\n") time.Sleep(time.Millisecond * 90) } } func getTrafficInfo(numNodes int, tcsvFile *os.File) { csvw := csv.NewWriter(tcsvFile) for i := 2; i <= (2 + numNodes - 1); i++ { distb.SendMessage(distb.Message{Type: "TrafficData"}, "gateway", strconv.Itoa(i)) m := <-requests fmt.Printf("----Node %d Total Visits: %d\n High Traffic? %v\n PS-Msgs: %d\n Edges: %v\n", i, m.BufferA, m.HighTraffic, m.BufferB, m.Edges) if err := csvw.Write([]string{strconv.Itoa(m.BufferA), strconv.FormatBool(m.HighTraffic), strconv.Itoa(m.BufferB)}); err != nil { log.Fatalln("error writing record to csv:", err) } /*timeout := make(chan bool, 1) go func() { time.Sleep(5 * time.Second) timeout <- true }() select { case m := <-requests: fmt.Printf("%d: %d High Traffic? %v\n", i, m.BufferA, m.HighTraffic) case <-timeout: log.Print("Request Timeout ", i) } */ } // Write any buffered data to the underlying writer (csvfile). csvw.Flush() if err := csvw.Error(); err != nil { log.Fatal(err) } } func main() { notListening := make(chan bool) requests = make(chan distb.Message) go distb.ListenAndServeTCP(notListening, requests) //go initBoruvka() cF, err := os.Create("data.csv") if err != nil { log.Fatal("Cant open csv") } calcAverage(cF) nNodes, err := strconv.Atoi(os.Args[1]) if err != nil { log.Fatal(err) } tF, err := os.Create("trafficdata.csv") if err != nil { log.Fatal("Cant open csv") } getTrafficInfo(nNodes, tF) //<-notListening } <file_sep>/config_test.go package distboruvka import ( "testing" ) func TestGetGraphDOTFile(t *testing.T) { e, _ := GetGraphDOTFile("sample.dot", "2") t.Log(e) } <file_sep>/config.go package distboruvka import ( "bytes" "io/ioutil" "log" "os/exec" "sort" "strconv" "strings" "time" "github.com/awalterschulze/gographviz" v3 "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/contrib/recipes" "golang.org/x/net/context" ) //ETCDEndpoint to etcd clusters const ETCDEndpoint string = "http://172.17.0.1:2379" //GetEdgesFromFile config func GetEdgesFromFile(fname string, id string) (Edges, map[string]*Edge) { rawContent, err := ioutil.ReadFile(fname) if err != nil { log.Fatal(err) } strs := strings.Split(string(rawContent), "\n") //wakeup, err := strconv.Atoi(strs[0]) //pushSumStart := strs[0] //if err != nil { // log.Print(err) //} //fmt.Printf("pushSumStart: %s\n", pushSumStart) strs = strs[1:] var edges Edges adjmap := make(map[string]*Edge) for _, line := range strs { if line != "" { vals := strings.Split(line, " ") s := vals[0] d := vals[1] w, _ := strconv.Atoi(vals[2]) if s == id { edge := Edge{SE: "Basic", Weight: w, AdjNodeID: d, Origin: s} edges = append(edges, edge) adjmap[d] = &edge } else if d == id { edge := Edge{SE: "Basic", Weight: w, AdjNodeID: s, Origin: d} edges = append(edges, edge) adjmap[s] = &edge } //fmt.Printf("My edge %v\n", edges) } } sort.Sort(edges) return edges, adjmap } //GetHostInfo get the current node's IP and hostname func GetHostInfo() (string, string) { HostIP, err := exec.Command("hostname", "-i").Output() if err != nil { log.Fatal(err) } HostIP = bytes.TrimSuffix(HostIP, []byte("\n")) HostName, err := exec.Command("hostname").Output() if err != nil { log.Fatal(err) } HostName = bytes.TrimSuffix(HostName, []byte("\n")) return string(HostName), string(HostIP) } var ( cli *v3.Client Barrier *recipe.Barrier ) func init() { cfg := v3.Config{ Endpoints: []string{ETCDEndpoint}, //Target endpoint timeout DialTimeout: time.Second * 5, } var err error cli, err = v3.New(cfg) if err != nil { log.Fatal(err) } Barrier = recipe.NewBarrier(cli, "DistBarrier") } //SetNodeInfo sets this node's current host(container)name and last IP octet func SetNodeInfo(name, id string) { _, err := cli.Put(context.Background(), "/nodes/"+name, id) if err != nil { log.Fatal(err) } else { log.Println("NodeInfo registered to ETCD ") } } //GetNodes retrieves the nodes list from etcd func GetNodes() []Node { var nodes []Node resp, err := cli.Get(context.Background(), "/nodes", v3.WithPrefix()) if err != nil { log.Println("Failed to obtain node: ", err) } else { log.Println("Refreshed node list") if resp.Kvs == nil { log.Println("IsNil") } for _, ev := range resp.Kvs { cName := bytes.TrimPrefix(ev.Key, []byte("/nodes/")) nodes = append(nodes, Node{Name: string(cName[:]), ID: string(ev.Value[:])}) log.Printf("Key: %s Value: %q\n", ev.Key, ev.Value) } } return nodes } func GetGraphDOTFile(fname string, id string) (Edges, map[string]*Edge) { graphstr, err := ioutil.ReadFile(fname) if err != nil { log.Fatal(err) } log.Print(string(graphstr)) g, err := gographviz.Read(graphstr) if err != nil { log.Fatal(err) } var edges Edges adjmap := make(map[string]*Edge) for _, e := range g.Edges.Edges { eID, err := strconv.Atoi(e.Attrs["label"]) if err != nil { log.Print(err) eID = 0 } eSrci, err := strconv.Atoi(e.Src) if err != nil { log.Fatal(err) } eSrci += 2 eSrc := strconv.Itoa(eSrci) eDsti, err := strconv.Atoi(e.Dst) if err != nil { log.Fatal(err) } eDsti += 2 eDst := strconv.Itoa(eDsti) if eSrc == id { edge := Edge{SE: "Basic", Weight: eID, AdjNodeID: eDst, Origin: eSrc} edges = append(edges, edge) adjmap[eDst] = &edge } else if eDst == id { edge := Edge{SE: "Basic", Weight: eID, AdjNodeID: eSrc, Origin: eDst} edges = append(edges, edge) adjmap[eSrc] = &edge } } sort.Sort(edges) return edges, adjmap }
7976c8ab16ea13d2c0be247edc3053241c53dcef
[ "Go", "Dockerfile", "Shell" ]
10
Dockerfile
parpat/distboruvka
0f716c3ec6a15a11e335bd403238c7ed328841dd
97b9901cc32c3a96a65e5d0efb5b320017f307fd
refs/heads/master
<repo_name>Trelefele/AutoDetalingWebSite<file_sep>/AutoDetalingUI/Models/Contact.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace AutoDetalingUI.Models { public class Contact { public int Id { get; set; } [Phone] [Display(Name = "Numer Telefonu:")] public string PhoneNumber { get; set; } [EmailAddress] [Display(Name = "Adres Email:")] public string Email { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } } }<file_sep>/AutoDetalingUI/Models/ApplicationUser.cs using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; namespace AutoDetalingUI.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { [Display(Name = "Imię:")] public string Name { get; set; } [Display(Name = "Nazwisko:")] public string Surname { get; set; } #region name and surname [NotMapped] [Display(Name = "Pan/Pani:")] public string FullName { get { return Name + " " + Surname; } } #endregion public virtual ICollection<Service> Services { get; set; } //virtual to lazy loading public virtual Contact Contact { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } }<file_sep>/AutoDetalingUI/Models/AdContext.cs using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace AutoDetalingUI.Models { public class AdContext : IdentityDbContext { public AdContext() : base("DefaultConnection") { } public static AdContext Create() { return new AdContext(); } DbSet<ApplicationUser> ApplicationUsers { get; set; } DbSet<Service> Services { get; set; } public DbSet<Contact> Contacts { get; set; } } }<file_sep>/AutoDetalingUI/Models/Service.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace AutoDetalingUI.Models { public class Service { public Service() { } [Display(Name = "Id Uslugi:")] [Key] public int Id; [Display(Name = "Rodzaj Usługi:")] public string CategoryId { get; set; } public int ApplicationUserId { get; set; } [Display(Name = "Początek usługi:")] public System.DateTime Start { get; set; } [Display(Name = "Koniec usługi:")] public System.DateTime End { get; set; } [Display(Name = "Cena Usługi:")] public float Price { get; set; } [Display(Name = "Opis Klienta:")] public string CustomerDescription { get; set; } /*constrains to other classes*/ public virtual ApplicationUser ApplicationUser { get; set; } public virtual Category Category { get; set; } } }
d3fac2eb202abacf0c63d09f1b00527be3ddc5ab
[ "C#" ]
4
C#
Trelefele/AutoDetalingWebSite
bc0014fe51fa73aa4ca27935fc191264c4d2d4a5
46ff4261f1814c2ec680689596b692d439c22852
refs/heads/main
<file_sep>from django.contrib import admin from . models import Stock # Register your models here. # in order for models to appear in the admin section you must register them admin.site.register(Stock) <file_sep>altgraph==0.17 appdirs==1.4.4 asgiref==3.3.1 astroid==2.5.1 certifi==2020.12.5 chardet==4.0.0 colorama==0.4.4 distlib==0.3.1 dj-database-url==0.5.0 Django==3.1.7 django-heroku==0.3.1 djangorestframework==3.12.2 filelock==3.0.12 future==0.18.2 gunicorn==20.0.4 idna==2.10 isort==5.7.0 lazy-object-proxy==1.5.2 mccabe==0.6.1 pefile==2019.4.18 Pillow==8.1.2 psycopg2==2.8.6 pygame==2.0.1 pyinstaller==4.2 pyinstaller-hooks-contrib==2021.1 pylint==2.7.2 python-decouple==3.4 pytz==2021.1 pywin32-ctypes==0.2.0 requests==2.25.1 six==1.15.0 sqlparse==0.4.1 toml==0.10.2 urllib3==1.26.4 virtualenv==20.4.3 whitenoise==5.2.0 wrapt==1.12.1 <file_sep>from django.shortcuts import render, redirect from .models import Stock from .forms import StockForm from django.contrib import messages # Create your views here. def home(request): # when you create a page, create a view # pk_fcecccc2b1054292b671060ad9f9418 import requests # you need to request the API import json # then parse it using JSON if request.method == 'POST': ticker = request.POST['ticker'] # this becomes the data that the user enters into the form (search bar) api_request = requests.get("https://cloud.iexapis.com/stable/stock/" + ticker + "/quote?token=<PASSWORD>") # you can then concatenate ticker into the URL try: api = json.loads(api_request.content) # parses api_request and throws an error if it returns nothing except Exception as e: api = "Error..." # this is returned if the API isn't returned return render(request, 'home.html', {'api' : api}) else: return render(request, 'home.html', {'ticker' : 'Enter a Ticker Symbol above'}) # if user hasn't submitted anything return to homepage and post text return render(request, 'home.html', {'api' : api}) # then you need to pass a request object, the page you want and the brackets are the content you want to access def about(request): return render(request, 'about.html', {}) def add_stock(request): import requests import json if request.method == 'POST': # if a post request has been made to the database form = StockForm(request.POST or None) # creates a stock form regardless of whether a post request has been made if form.is_valid(): # if form fits criteria i.e. if ticker symbol is 5 characters or less form.save() messages.success(request, ("Stock Has Been Added")) # if form exists post this message return redirect('add_stock') else: ticker = Stock.objects.all() output = [] nums = [] for ticker_item in ticker: api_request = requests.get("https://cloud.iexapis.com/stable/stock/" + str(ticker_item) + "/quote?token=<PASSWORD>") try: api = json.loads(api_request.content) # parses api_request and throws an error if it returns nothing output.append(api) # save output to the list print(api) except Exception as e: api = "Error..." # this is returned if the API isn't returned return render(request, 'add_stock.html', {'ticker' : ticker, 'output' : output}) # outputs api data def delete(request, stock_id): item = Stock.objects.get(pk=stock_id) # you must first grab the item's id from database, pk is the id number item.delete() # you then need to call delete on the item messages.success(request, ('Your stock has been deleted.')) return redirect(delete_stock) def delete_stock(request): ticker = Stock.objects.all() return render(request, 'delete_stock.html', {'ticker': ticker})
bdc3cfc25a88a8fd730b538d6585b4ae4269ce9d
[ "Python", "Text" ]
3
Python
Emmanuel678912/stockportfolio
0eb054e83e311b310ee5624506718e91bc74940f
179910ebee286f9502f2af489847c78ab2622110
refs/heads/master
<repo_name>NickRock/SaveLove<file_sep>/savelove.lua savelove = {} function savelove:set(fname, highscore) if not love.filesystem.exists(fname) then love.filesystem.newFile(fname) highscore = 0 else for lines in love.filesystem.lines(fname) do highscore = lines end end return tonumber(highscore) end function savelove:save(fname, highscore) love.filesystem.write(fname, highscore) end return savelove
b995e49334480ef5940b975f36664ec32bc0b32d
[ "Lua" ]
1
Lua
NickRock/SaveLove
4e91d12e4ab673ae7a0c908f596d1671c51bb0e3
d8716d9124c41ef9c2df3a97c08bea77900b214b
refs/heads/master
<repo_name>chanjuanmoon/vue-<file_sep>/vuejs01/12-前端模块化/01-为什么要用前端模块化/aaa.js /** * 1.(function(){})() 闭包解决全局变量冲突 * 2.将函数返回的对象赋值给变量,可以实现代码复用 */ var ModuleA = (function(){ var obj = {}; var num1 = 10; var num2 = 100; var flag = true; function sum(){ console.log(num1 + num2); } if(flag){ sum(); } obj.flag = flag; obj.num1 = num1; obj.sum = sum(); return obj; })()<file_sep>/vuejs01/12-前端模块化/02-es6模块化/bbb.js var name='小红'; var flag = false;<file_sep>/storedemo/README.md # vuex学习 - state - vuex数据源,我们需要保存的数据就保存在这里,可以在页面中通过 this.$store.state来获取我们定义的数据 ``` state:{ count:1 }, this.$store.state.count ``` - getters - 相当于vue中的computed计算属性,getter返回值会根据它依赖被缓存起来 且只有当它的依赖值发生改变才会被重新计算,getters可以用于监听 state中值的变化,返回计算后的结果 ``` getters:{ getStateCount:function (state) { return state.count+1; } }, ``` - mutations - 数据在页面中获取到了,要修改state中值唯一的方法就是提交 mutation来修改 ``` //vue文件 <button @click="addFun" >+</button> <button @click="reductionFun" >-</button> methods:{ addFun(){ this.$store.commit('add');//同步 }, reductionFun(){ this.$store.commit('reduction');//同步 } } //store/store.js mutations:{ add(state){ state.count++; }, reduction(state){ state.count--; } }, ``` - actions - 官方建议我们去提交一个actions,在actions中提交mutation 再去修改state中的值 ``` //vue文件 <button @click="addFun" >+</button> <button @click="reductionFun" >-</button> methods:{ addFun(){ this.$store.dispatch("addFun"); }, reductionFun(){ this.$store.dispatch('reductionFun'); } } //store/store.js文件 actions:{ addFun(context){//接收一个store实例具有相同方法的属性context对象 context.commit('add'); }, reductionFun(context){ context.commit('reduction'); } } ``` # storedemo ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Run your tests ``` npm run test ``` ### Lints and fixes files ``` npm run lint ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). <file_sep>/vuejs01/08-书籍购物车案例/main.js const app = new Vue({ el:'#app', data:{ books:[ { id:1, name:'《算法导论》', date:'2006-9', price:85.90, count:1 }, { id:2, name:'《Unix编程艺术》', date:'2006-2', price:59.00, count:1 }, { id:3, name:'《编程珠玑》', date:'2008-10', price:35.00, count:1 }, { id:4, name:'《代码大全》', date:'2006-3', price:128.00, count:1 }, ] }, methods:{ increment(index){ this.books[index].count ++; }, decrement(index){ this.books[index].count --; }, removeHandel(index){ this.books.splice(index,1); } }, filters:{ showPrice(price){ return '¥'+price.toFixed(2); } }, computed:{ totalPrice(){ //1.普通循环 // let totalPrice = 0; // for(let i =0;i<this.books.length;i++){ // totalPrice +=this.books[i].price * this.books[i].count; // } // return totalPrice; //2.for in // let totalPrice = 0; // for(let i in this.books){ // const book = this.books[i]; // totalPrice += book.price * book.count; // } // return totalPrice; //3.for of // let totalPrice = 0; // for(let item of this.books){ // totalPrice += item.price * item.count; // } // return totalPrice; //高阶函数 return this.books.reduce(function(pre,book){ return pre +book.price * book.count; },0); } } }) //编程范式:命令式编程/声明式编程 //编程范式:面向对象编程(第一公民:对象)/函数式编程(第一公民:函数) //filter/map/reduce const nums = [10,20,4,89,45,222,111,888,333]; //高阶函数实现 let totalNums = nums.filter(n=>n<100).map(n=>n*2).reduce((pre,n)=>pre+n); console.log(totalNums); /** * 需求: * 1.将数组中小于100的数取出 * 2.所有小于100 的数 *2 * 3.求和 * */ /** * filter函数的使用 * filter中的回调函数有一个要求:必须返回一个boolean值 * true:当返回值为true时,函数内部会自动将这次回调的n加入到新的数组中 * false:当返回false时,函数内部会过滤掉这次的n */ //1.将数组中小于100的数取出 let filterNums = nums.filter(function(n){ return n < 100; }) console.log(filterNums); /** * map函数的使用 */ // 2.所有小于100 的数 *2 filterNums = filterNums.map(function(n){ return n*2; }) console.log(filterNums); /** * reduce函数的使用 * */ //3.求和 let total = filterNums.reduce(function(preValue,n){ return preValue + n; },0) console.log(total);<file_sep>/storedemo/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import testStore from '../views/testStore' Vue.use(Router) export default new Router({ routes:[ { path:'/', name:'testStore', component:testStore } ] })
2ecc4699849a6f09a6a0f3319106bc5026f44bf5
[ "JavaScript", "Markdown" ]
5
JavaScript
chanjuanmoon/vue-
9a8e246f199097c8b8ad91e869bd8dc15461f823
18951bffbda70ca041b4da2b389640f1ff43cbcd
refs/heads/master
<repo_name>andrebododea/gauss_jordan_opencl<file_sep>/matrix_multiplication_example/build_and_run.sh #!/bin/bash # export OPENCL_PATH=/home/s1350924/opencl/fbdev # export OPENC;_PATH=/usr/local/lib/mgd/ export OPENCL_PATH=/usr/local/lib/mali/fbdev export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OPENCL_PATH gcc -o gauss_jordan gauss_jordan.c -I/usr/include -L$OPENCL_PATH -Wl,-rpath,$OPENCL_PATH -lOpenCL && ./gauss_jordan <file_sep>/gauss_elimination_serial/gauss_elim.cpp #include <iostream> #include <algorithm> #include <iterator> int main() { int n = 3; /* Allocate memory for the resulting augmented matrix // // This will be an n*2 x n matrix */ float mat_with_identity[n][n+1]; // Test matrix which will be inverted float orig_mat[3][4] = { {2.0, 1.0, -1.0, 0.0}, {-3.0, -1.0, 2.0, 0.0}, {-2.0, 1.0, 2.0, 0.0} }; // Create vector float identity_mat[3] = {8.0, -11.0, -3.0}; // Conjoin the matrix with vector for (int i = 0; i < n; i++) { orig_mat[i][n]= identity_mat[i]; } // Print the starting matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n+1; j++) { std::cout << orig_mat[i][j] << " _ " <<' '; } std::cout << std::endl; } std::cout << std::endl; std::cout << std::endl; /********************************************/ /*** Gaussian elimination ***/ /********************************************/ float a; bool a_is_zero; int nonzero_row; // Loop through rows for Step 1 for (int currentRow = 0; currentRow < n; currentRow++) { a = orig_mat[currentRow][currentRow]; /** KERNEL #1 **/ // Do step 1 for each element of the current row: R_i = R_i/a_ii for(int col = 0; col < n+1; col++){ orig_mat[currentRow][col] = orig_mat[currentRow][col]/ a; } /** KERNEL #2 **/ // n^2 loop for Step 2 for (int col = 0; col < n+1; col++) { // Skip the row if step 1 has already been applied to it for (int row = 0; row < n; row++) { if(row != currentRow) { float R_j = orig_mat[row][currentRow]; // std::cout << orig_mat[row][col] << " - " << R_j << " * " << orig_mat[currentRow][col] << std::endl; orig_mat[row][col] = orig_mat[row][col] - R_j * orig_mat[currentRow][col]; } } } } float solution_vector[n]; // store solution vector as an array for (int i = 0; i < n; i++) { solution_vector[i] = orig_mat[i][n]; } // Print the end matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n+1; j++) { std::cout << orig_mat[i][j] << " _ " <<' '; } std::cout << std::endl; } std::cout << std::endl; std::cout << std::endl; //Print the solution vector std::cout << "Solution vector: "<< std::endl; for (int i = 0; i < n; i++) { std::cout << orig_mat[i][n] << ", "<< ' '; } std::cout << std::endl; return 0; } <file_sep>/gauss_elim_parallel/gaussian_elim_host.c //////////////////////////////////////////////////////////////////////////////// #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <CL/cl.h> #include <stdbool.h> // Header to allow call from gp.cc #include "opencl_gaussian_elimination.h" //////////////////////////////////////////////////////////////////////////////// #define WA 21 #define HA 20 #define WB 20 #define HB WA #define WC WB #define HC HA //////////////////////////////////////////////////////////////////////////////// // Allocates a matrix with random double entries. void randomMemInit(double* data, int size) { int i; for (i = 0; i < size; ++i) data[i] = rand() / (double)RAND_MAX; } long LoadOpenCLKernel(char const* path, char **buf) { FILE *fp; size_t fsz; long off_end; int rc; /* Open the file */ fp = fopen(path, "r"); if( NULL == fp ) { return -1L; } /* Seek to the end of the file */ rc = fseek(fp, 0L, SEEK_END); if( 0 != rc ) { return -1L; } /* Byte offset to the end of the file (size) */ if( 0 > (off_end = ftell(fp)) ) { return -1L; } fsz = (size_t)off_end; /* Allocate a buffer to hold the whole file */ *buf = (char *) malloc( fsz+1); if( NULL == *buf ) { return -1L; } /* Rewind file pointer to start of file */ rewind(fp); /* Slurp file into buffer */ if( fsz != fread(*buf, 1, fsz, fp) ) { free(*buf); return -1L; } /* Close the file */ if( EOF == fclose(fp) ) { free(*buf); return -1L; } /* Make sure the buffer is NUL-terminated, just in case */ (*buf)[fsz] = '\0'; /* Return the file size */ return (long)fsz; } // double * run_gauss_elim(k_vector, L_matrix, n) int main() { int err; // error code returned from api calls cl_device_id device_id; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue cl_program program; // compute program cl_kernel kernel1; // compute kernel cl_kernel kernel2; // compute kernel // OpenCL device memory for matrices cl_mem d_A; cl_mem d_C; // set seed for rand() srand(2014); //Allocate host memory for matrices A and B unsigned int size_A = WA * HA; unsigned int mem_size_A = sizeof(double) * size_A; double* h_A = (double*) malloc(mem_size_A); //Initialize host memory randomMemInit(h_A, size_A); //Allocate host memory for the result C unsigned int size_C = WC * HC; unsigned int mem_size_C = sizeof(double) * size_C; double* h_C = (double*) malloc(mem_size_C); printf("Initializing OpenCL device...\n"); cl_uint dev_cnt = 0; clGetPlatformIDs(0, 0, &dev_cnt); cl_platform_id platform_ids[100]; clGetPlatformIDs(dev_cnt, platform_ids, NULL); // Connect to a compute device int gpu = 1; err = clGetDeviceIDs(platform_ids[0], gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU, 1, &device_id, NULL); if (err != CL_SUCCESS) { printf("Error: Failed to create a device group!\n"); return EXIT_FAILURE; } // Create a compute context context = clCreateContext(0, 1, &device_id, NULL, NULL, &err); if (!context) { printf("Error: Failed to create a compute context!\n"); return EXIT_FAILURE; } // Create a command commands commands = clCreateCommandQueue(context, device_id, 0, &err); if (!commands) { printf("Error: Failed to create a command commands!\n"); return EXIT_FAILURE; } // Create the compute program from the source file char *KernelSource; long lFileSize; lFileSize = LoadOpenCLKernel("gaussian_elim_kernel.cl", &KernelSource); if( lFileSize < 0L ) { perror("File read failed"); return 1; } program = clCreateProgramWithSource(context, 1, (const char **) & KernelSource, NULL, &err); if (!program) { printf("Error: Failed to create compute program!\n"); return EXIT_FAILURE; } // Build the program executable err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (err != CL_SUCCESS) { size_t len; char buffer[2048]; printf("Error: Failed to build program executable!\n"); clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len); printf("%s\n", buffer); exit(1); } // Create the input and output arrays in device memory for our calculation d_C = clCreateBuffer(context, CL_MEM_READ_WRITE, mem_size_A, NULL, &err); d_A = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, mem_size_A, h_A, &err); if (!d_A || !d_C) { printf("Error: Failed to allocate device memory!\n"); exit(1); } //Launch OpenCL kernel size_t localWorkSize[2], globalWorkSize[2]; int wA = WA; int wC = WC; // Set local and global work sizes localWorkSize[0] = 7; localWorkSize[1] = 7; globalWorkSize[0] = 21; globalWorkSize[1] = 21; //print out the results /* printf("\n\nMatrix C (Results)\n"); int i; for(i = 0; i < size_C; i++) { printf("%f ", h_C[i]); if(((i + 1) % WC) == 0) printf("\n"); } printf("\n"); */ // BEGIN GAUSSIAN ELIMINATION // Create the compute kernel in the program we wish to run kernel1 = clCreateKernel(program, "step_1_row_operation", &err); if (!kernel1 || err != CL_SUCCESS) { printf("Error: Failed to create compute kernel!\n"); exit(1); } kernel2 = clCreateKernel(program, "step_2_col_operation", &err); if (!kernel2 || err != CL_SUCCESS) { printf("Error: Failed to create compute kernel!\n"); exit(1); } /** QUERY WORKGROUP SIZE FOR KERNEL 1 **/ size_t workgroup_size; err = clGetKernelWorkGroupInfo(kernel1, device_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &workgroup_size, NULL); if (err != CL_SUCCESS) { printf("Unable to get kernel1 work-group size"); } printf("Kernel1 work group size is: %d\n", workgroup_size); /** QUERY WORKGROUP SIZE FOR KERNEL 2 **/ err = clGetKernelWorkGroupInfo(kernel2, device_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &workgroup_size, NULL); if (err != CL_SUCCESS) { printf("Unable to get kernel2 work-group size"); } printf("Kernel2 work group size is: %d\n", workgroup_size); /* * Query the device to find out it's prefered double vector width. * Although we are only printing the value here, it can be used to select between * different versions of a kernel. */ cl_double doubleVectorWidth; clGetDeviceInfo(device_id, CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_double), &doubleVectorWidth, NULL); printf("Prefered vector width for doubles: %d", doubleVectorWidth); //Launch OpenCL kernel for(int currentRow = 0; currentRow < HA; currentRow++){ /************/ /* Kernel 1 */ /************/ // Setting arguments for the kernel err = clSetKernelArg(kernel1, 0, sizeof(cl_mem), (void *)&d_C); err |= clSetKernelArg(kernel1, 1, sizeof(cl_mem), (void *)&d_A); err |= clSetKernelArg(kernel1, 2, sizeof(int), (void *)&wA); err |= clSetKernelArg(kernel1, 3, sizeof(int), (void *)&currentRow); if (err != CL_SUCCESS) { printf("Error: Failed to set kernel arguments! %d\n", err); exit(1); } // This is where execution of the kernel is actually done err = clEnqueueNDRangeKernel(commands, kernel1, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); if (err != CL_SUCCESS) { printf("Error: Failed to execute kernel1! %d\n", err); exit(1); } //Retrieve result from device err = clEnqueueReadBuffer(commands, d_A, CL_TRUE, 0, mem_size_A, h_A, 0, NULL, NULL); if (err != CL_SUCCESS) { printf("Error: Failed to read output array! %d\n", err); exit(1); } /************/ /* Kernel 2 */ /************/ err = clSetKernelArg(kernel2, 0, sizeof(cl_mem), (void *)&d_C); err |= clSetKernelArg(kernel2, 1, sizeof(cl_mem), (void *)&d_A); err |= clSetKernelArg(kernel2, 2, sizeof(int), (void *)&wA); err |= clSetKernelArg(kernel2, 3, sizeof(int), (void *)&currentRow); if (err != CL_SUCCESS) { printf("Error: Failed to set kernel arguments! %d\n", err); exit(1); } // This is where execution of the kernel is actually done err = clEnqueueNDRangeKernel(commands, kernel2, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); if (err != CL_SUCCESS) { printf("Error: Failed to execute kernel2! %d\n", err); exit(1); } //Retrieve result from device err = clEnqueueReadBuffer(commands, d_A, CL_TRUE, 0, mem_size_A, h_A, 0, NULL, NULL); if (err != CL_SUCCESS) { printf("Error: Failed to read output array! %d\n", err); exit(1); } } //print out the results printf("\n\nMatrix A (Results)\n"); int i; for(i = 0; i < size_A; i++) { printf("%f ", h_A[i]); if(((i + 1) % WA) == 0) printf("\n"); } printf("\n"); //Shutdown and cleanup free(h_A); free(h_C); clReleaseMemObject(d_A); clReleaseMemObject(d_C); clReleaseProgram(program); clReleaseKernel(kernel1); clReleaseKernel(kernel2); clReleaseCommandQueue(commands); clReleaseContext(context); return 0; } <file_sep>/gauss_jordan_test.cpp #include <iostream> #include <algorithm> #include <iterator> int main() { int n = 4; /* Allocate memory for the resulting augmented matrix // // This will be an n*2 x n matrix */ float mat_with_identity[n][n*2]; // Test matrix which will be inverted float orig_mat[4][4] = { {3.0, 2.0, 6.0, 2.0}, {7.0, 2.0, 4.0, 12.0}, {20.0, 90.0, 8.0, 5.0}, {99.0, 28.0, 64.0, 61.0} }; // Create identity matrix float identity_mat[4][4] = { {1.0, 0.0, 0.0, 0.0}, {0.0, 1.0, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0}, {0.0, 0.0, 0.0, 1.0} }; // Conjoin the matrix with the identity matrix: mat_with_identity = [orig_mat | identity_mat] for (int i = 0; i < n; i++) { for (int j = 0; j < n*2; j++) { if (j < n) { mat_with_identity[i][j] = orig_mat[i][j]; } else { mat_with_identity[i][j] = identity_mat[i][j - n]; } } } // Print the starting matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n*2; j++) { std::cout << mat_with_identity[i][j] << " _ " <<' '; } std::cout << std::endl; } std::cout << std::endl; std::cout << std::endl; /********************************************/ /*** Gauss-Jordan matrix inversion ***/ /*******************************************/ float a; bool a_is_zero; int nonzero_row; // Loop through rows for Step 1 for (int currentRow = 0; currentRow < n; currentRow++) { a = mat_with_identity[currentRow][currentRow]; /** KERNEL #1 **/ // Do step 1 for each element of the current row: R_i = R_i/a_ii for(int col = 0; col < n*2; col++){ mat_with_identity[currentRow][col] = mat_with_identity[currentRow][col]/ a; } /** KERNEL #2 **/ // n^2 loop for Step 2 for (int row = 0; row < n; row++) { // Skip the row if step 1 has already been applied to it if(row != currentRow) { float R_j = mat_with_identity[row][currentRow]; for (int col = 0; col < n*2; col++) { // std::cout << mat_with_identity[row][col] << " - " << R_j << " * " << mat_with_identity[currentRow][col] << std::endl; mat_with_identity[row][col] = mat_with_identity[row][col] - R_j * mat_with_identity[currentRow][col]; } } } } // Print the finished matrix (left half should be identity matrix now) /* for (int i = 0; i < n; i++) { for (int j = 0; j < n*2; j++) { std::cout << mat_with_identity[i][j] << " _ " <<' '; } std::cout << std::endl; } std::cout << std::endl; std::cout << std::endl; */ float inverted_matrix[n][n]; // Get rid of the identity matrix // Can parallelize: have the inner for loop be kernel, then run n threads to transfer one matrix to another for (int i = 0; i < n; i++) { // KERNEL for (int j = 0; j < n; j++) { inverted_matrix[i][j] = mat_with_identity[i][j+n]; } std::cout << std::endl; } std::cout << std::endl; std::cout << std::endl; // Print the final inverted matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { std::cout << inverted_matrix[i][j] << " | " <<' '; } std::cout << std::endl; } std::cout << std::endl; std::cout << std::endl; return 0; }
0c073faa7ac8d33f467199df5ecf4e7b5a0b1d36
[ "C", "C++", "Shell" ]
4
Shell
andrebododea/gauss_jordan_opencl
a1391394bea56e4f9d0032ed7266bee24379e72e
f64f1f920b3a021674be633854350de1232c672d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; namespace FineArts.Entities { public class Teacher { public int Id { get; set; } public string FirstName { get; set; } // Propiedad public string LastName { get; set; } public string Class { get; set; } public List<Student> Students { get; set; } } } <file_sep>using System; using Microsoft.EntityFrameworkCore; using FineArts.Entities; namespace FineArts.Dal { public class FineArtsContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=FineArts"); } public DbSet<Teacher> Teachers { get; set; } public DbSet<Student> Students { get; set; } } } <file_sep>using System; using FineArts.Entities; using FineArts.Dal; using System.Collections.Generic; // List<T>. namespace FineArts.Bll { public class TeacherService { public static bool SeedData() { bool HasTestData = false; var Repository = new Repository(); if (!Repository.HasTeachers()) { var Teachers = new Teacher[] { new Teacher { FirstName="Esther", LastName="Valle", Class="3C", Students = new List<Student> { new Student { FirstName="Kevin", LastName="Liu", DateOfBirth=new DateTime(2005,10,10) }, new Student { FirstName="Martin", LastName="Weber", DateOfBirth=new DateTime(2005,09,07) }, new Student { FirstName="George", LastName="Li", DateOfBirth=new DateTime(2005,08,10) }, new Student { FirstName="Lisa", LastName="Miller", DateOfBirth=new DateTime(2005,05,04) }, new Student { FirstName="Run", LastName="Liu", DateOfBirth=new DateTime(2005,10,23) } } }, new Teacher { FirstName="David", LastName="Waite", Class="4B", Students= new List<Student> { new Student { FirstName="Sean", LastName="Stewart", DateOfBirth=new DateTime(2003,02,18) }, new Student { FirstName="Olinda", LastName="Turner", DateOfBirth=new DateTime(2003,05,17) }, new Student { FirstName="Jon", LastName="Orton", DateOfBirth=new DateTime(2002,08,10) }, new Student { FirstName="Toby", LastName="Nixon", DateOfBirth=new DateTime(2002,12,15) }, new Student { FirstName="Daniela", LastName="Guinot", DateOfBirth=new DateTime(2002,08,01) } } }, new Teacher { FirstName="Belinda", LastName="Newman", Class="2A", Students=new List<Student> { new Student { FirstName="Vijay", LastName="Sundaram", DateOfBirth=new DateTime(2007,02,03) }, new Student { FirstName="Eric", LastName="Gruber", DateOfBirth=new DateTime(2007,05,26) }, new Student { FirstName="Chris", LastName="Meyer", DateOfBirth=new DateTime(2006,05,09) }, new Student { FirstName="Yuhong", LastName="Li", DateOfBirth=new DateTime(2007,05,28) }, new Student { FirstName="Yan", LastName="Li", DateOfBirth=new DateTime(2007,03,31) } } } }; HasTestData = Repository.AddTeachers(Teachers); } return HasTestData; }//Initilizar datos de prueba. public List<Teacher> GetTeachers() { var Repository = new Repository(); return Repository.GetTeachers(); } public List<Student> GetStudentsByTeacher(int teacherId) { var Repository = new Repository(); return Repository.GetStudentsByTeacherId(teacherId); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FineArts.Entities; namespace FineArts.Dal { public class Repository { public bool HasTeachers() { using var Context = new FineArtsContext(); return Context.Teachers.Any(); } public List<Teacher> GetTeachers() { using var Context = new FineArtsContext(); // SELECT * FROM Teachers return Context.Teachers.ToList(); } // CRUD (Create - Read Update Delete) public bool AddTeachers(Teacher[] teachers) { using var Context = new FineArtsContext(); Context.AddRange(teachers); return Context.SaveChanges() > 0; } public List<Student> GetStudentsByTeacherId(int teacherId) { using var Context = new FineArtsContext(); return Context.Students // LINQ .Where(student => student.TeacherId == teacherId) .ToList(); } } }
f914dd29bf7e17219d26be08df7233b8bba34284
[ "C#" ]
4
C#
Je5e/FineArts
369d2874dd2a676f652b1b51b339d4949c932cad
9cb9687730127dde4ac0a12175a50b2f21bfc9d5
refs/heads/master
<file_sep>#include "type_hash.h" namespace rediscpp { type_hash::type_hash() { } type_hash::type_hash(const timeval_type & current) : type_interface(current) { } type_hash::~type_hash() { } size_t type_hash::hdel(const std::vector<std::string*> & fields) { size_t removed = 0; for (auto it = fields.begin(), end = fields.end(); it != end; ++it) { auto & field = **it; auto vit = value.find(field); if (vit != value.end()) { value.erase(vit); ++removed; } } return removed; } bool type_hash::hexists(const std::string field) const { return value.find(field) != value.end(); } bool type_hash::empty() const { return value.empty(); } std::pair<std::string,bool> type_hash::hget(const std::string field) const { auto it = value.find(field); if (it != value.end()) { return std::make_pair(it->second, true); } return std::make_pair(std::string(), false); } std::pair<std::unordered_map<std::string, std::string>::const_iterator,std::unordered_map<std::string, std::string>::const_iterator> type_hash::hgetall() const { return std::make_pair(value.begin(), value.end()); } size_t type_hash::size() const { return value.size(); } bool type_hash::hset(const std::string & field, const std::string & val, bool nx) { auto it = value.find(field); if (it != value.end()) { if (nx) { return false; } it->second = val; return false; } else { value[field] = val; return true;//created } } }; <file_sep>#include "server.h" #include "client.h" #include "master.h" #include "log.h" namespace rediscpp { ///データベースのキー数取得 ///@note Available since 1.0.0. bool server_type::api_dbsize(client_type * client) { auto db = readable_db(client); client->response_integer(db->get_dbsize()); return true; } ///データベースの全キー消去 ///@note Available since 1.0.0. bool server_type::api_flushall(client_type * client) { for (int i = 0, n = databases.size(); i < n; ++i) { auto db = writable_db(i, client); db->clear(); } client->response_ok(); return true; } ///選択しているデータベースの全キー消去 ///@note Available since 1.0.0. bool server_type::api_flushdb(client_type * client) { auto db = writable_db(client); db->clear(); client->response_ok(); return true; } ///サーバのシャットダウン ///@note NOSAVE, SAVEオプションは無視する ///@note Available since 1.0.0. bool server_type::api_shutdown(client_type * client) { lputs(__FILE__, __LINE__, info_level, "shutdown start"); shutdown = true; client->response_ok(); return true; } ///サーバの時間 ///@note Available since 2.6.0. ///@note Time complexity: O(1) bool server_type::api_time(client_type * client) { timeval_type tv = client->get_time(); client->response_start_multi_bulk(2); client->response_integer(tv.tv_sec); client->response_integer(tv.tv_usec); return true; } ///スレーブ開始 ///@note Available since 1.0.0 bool server_type::api_slaveof(client_type * client) { auto host = client->get_argument(1); auto port = client->get_argument(2); //lprintf(__FILE__, __LINE__, debug_level, "SLAVEOF %s %s", host.c_str(), port.c_str()); std::transform(host.begin(), host.end(), host.begin(), tolower); std::transform(port.begin(), port.end(), port.begin(), tolower); client->response_ok(); client->flush(); slaveof(host, port); return true; } ///同期データ要求 ///@note Available since 1.0.0 bool server_type::api_sync(client_type * client) { //全ロック std::vector<std::shared_ptr<database_read_locker>> lockers(databases.size()); for (size_t i = 0; i < databases.size(); ++i) { lockers[i].reset(new database_read_locker(databases[i].get(), NULL)); } char path[] = "/tmp/redis.save.rdb.XXXXXX"; int fd = mkstemp(path); if (fd < 0) { throw std::runtime_error("ERR could not create tmp file"); } close(fd); std::string path_ = path; if (!save(path_)) { throw std::runtime_error("ERR failed to sync"); } mutex_locker locker(slave_mutex); client->set_slave(); slaves.insert(client->get()); client->response_file(path_); return true; } ///クライアント情報設定 ///@note Available since 1.0.0 bool server_type::api_replconf(client_type * client) { auto & arguments = client->get_arguments(); for (size_t i = 1, n = arguments.size(); i + 1 < n; i += 2) { auto field = arguments[i]; auto & value = arguments[i+1]; std::transform(field.begin(), field.end(), field.begin(), tolower); if (field == "listening-port") { bool is_valid; uint16_t port = atou16(value, is_valid); if (is_valid) { client->listening_port = port; } } } client->response_ok(); return true; } ///モニター設定 ///@note Available since 1.0.0 bool server_type::api_monitor(client_type * client) { client->response_ok(); client->set_monitor(); append_client(client->get()); return true; } } <file_sep>#include "server.h" #include "client.h" #include "type_zset.h" namespace rediscpp { ///複数のメンバーを追加 ///@note Available since 1.2.0. bool server_type::api_zadd(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = writable_db(client); auto & scores = client->get_scores(); auto & members = client->get_members(); std::shared_ptr<type_zset> zset = db->get_zset(key, current); bool created = false; if (!zset) { zset.reset(new type_zset(current)); created = true; } std::vector<type_zset::score_type> scores_(scores.size()); for (size_t i = 0, n = scores.size(); i < n; ++i) { bool is_valid = true; scores_[i] = atod(*scores[i], is_valid); if (!is_valid || isnan(scores_[i])) { throw std::runtime_error("ERR score is not valid number"); } } int64_t added = zset->zadd(scores_, members); if (created) { db->replace(key, zset); } else { zset->update(current); } client->response_integer(added); return true; } ///要素数を取得 ///@note Available since 1.2.0. bool server_type::api_zcard(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_integer0(); return 0; } client->response_integer(zset->size()); return true; } ///要素数を取得 ///@note Available since 2.0.0. bool server_type::api_zcount(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); std::string minimum = client->get_argument(2); std::string maximum = client->get_argument(3); bool inclusive_minimum = true; bool inclusive_maximum = true; if (!minimum.empty() && *minimum.begin() == '(') { inclusive_minimum = false; minimum = minimum.substr(1); } if (!maximum.empty() && *maximum.begin() == '(') { inclusive_maximum = false; maximum = maximum.substr(1); } bool is_valid = true; type_zset::score_type minimum_score = atod(minimum, is_valid); if (!is_valid || isnan(minimum_score)) { throw std::runtime_error("ERR min is not valid"); } type_zset::score_type maximum_score = atod(maximum, is_valid); if (!is_valid || isnan(maximum_score)) { throw std::runtime_error("ERR max is not valid"); } auto db = readable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_integer0(); return 0; } size_t size = zset->zcount(minimum_score, maximum_score, inclusive_minimum, inclusive_maximum); client->response_integer(size); return true; } ///スコアを加算 ///@note Available since 1.2.0. bool server_type::api_zincrby(client_type * client) { auto & key = client->get_argument(1); std::string increment = client->get_argument(2); auto member = client->get_argument(3); auto current = client->get_time(); bool is_valid = true; type_zset::score_type increment_score = atod(increment, is_valid); if (!is_valid || isnan(increment_score)) { throw std::runtime_error("ERR increment is not valid"); } auto db = writable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); bool created = false; if (!zset) { zset.reset(new type_zset(current)); created = true; } type_zset::score_type result_score = zset->zincrby(member, increment_score); if (isnan(result_score)) { throw std::runtime_error("ERR nan by increment"); } if (created) { db->replace(key, zset); } else { zset->update(current); } client->response_bulk(format("%g", result_score)); return true; } ///積集合 ///@note Available since 2.0.0. bool server_type::api_zinterstore(client_type * client) { return api_zoperaion_internal(client, 0); } ///和集合 ///@note Available since 2.0.0. bool server_type::api_zunionstore(client_type * client) { return api_zoperaion_internal(client, 1); } ///集合演算 ///@param[in] type 0 : inter, 1 : union bool server_type::api_zoperaion_internal(client_type * client, int type) { auto & arguments = client->get_arguments(); auto & destination = client->get_argument(1); bool is_valid; int64_t numkey = atoi64(client->get_argument(2), is_valid); size_t parsed = 3; if (!is_valid || numkey < 1 || arguments.size() < parsed + numkey) { throw std::runtime_error("ERR numkey is invalid"); } std::vector<const std::string*> keys; keys.resize(numkey); for (size_t i = 0; i < keys.size(); ++i) { keys[i] = & arguments[i+parsed]; } parsed += numkey; std::vector<type_zset::score_type> weights(numkey, 1.0); if (parsed < arguments.size()) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "WEIGHTS") { ++parsed; if (arguments.size() < parsed + numkey) { throw std::runtime_error("ERR weight is too few"); } for (size_t i = 0; i < weights.size(); ++i) { weights[i] = atod(arguments[i+parsed], is_valid); if (!is_valid || isnan(weights[i])) { throw std::runtime_error("ERR weight is invalid"); } } parsed += weights.size(); } } type_zset::aggregate_types aggregate = type_zset::aggregate_sum; if (parsed < arguments.size()) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "AGGREGATE") { ++parsed; if (arguments.size() < parsed + 1) { throw std::runtime_error("ERR aggregate type not found"); } std::string type = arguments[parsed]; std::transform(type.begin(), type.end(), type.begin(), toupper); if (type == "SUM") { } else if (type == "MAX") { aggregate = type_zset::aggregate_max; } else if (type == "MIN") { aggregate = type_zset::aggregate_min; } else { throw std::runtime_error("ERR aggregate type not valid"); } ++parsed; } } if (parsed != arguments.size()) { throw std::runtime_error("ERR syntax error too many arguments"); } auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_zset> zset(new type_zset(current)); bool first = true; auto wit = weights.begin(); for (auto it = keys.begin(), end = keys.end(); it != end; ++it, ++wit) { auto & key = **it; std::shared_ptr<type_zset> rhs = db->get_zset(key, current); if (first || type) { first = false; if (rhs) { zset->zunion(*rhs, *wit, aggregate); } } else { if (rhs) { zset->zinter(*rhs, *wit, aggregate); } else { zset->clear(); } } } db->replace(destination, zset); client->response_integer(zset->size()); return true; } ///要素の範囲取得(スコア順&同じスコアはメンバーの辞書順) ///@note Available since 1.2.0. bool server_type::api_zrange(client_type * client) { return api_zrange_internal(client, false); } ///要素の範囲取得(逆順) ///@note Available since 1.2.0. bool server_type::api_zrevrange(client_type * client) { return api_zrange_internal(client, true); } bool server_type::api_zrange_internal(client_type * client, bool rev) { auto & arguments = client->get_arguments(); auto & key = client->get_argument(1); auto current = client->get_time(); bool withscores = false; if (5 == arguments.size()) { std::string keyword = arguments[4]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "WITHSCORES") { withscores = true; } else { throw std::runtime_error("ERR syntax error"); } } else if (4 != arguments.size()) { throw std::runtime_error("ERR syntax error"); } bool is_valid; int64_t start = atoi64(client->get_argument(2), is_valid); if (!is_valid) { throw std::runtime_error("ERR start is not valid integer"); } int64_t stop = atoi64(client->get_argument(3), is_valid); if (!is_valid) { throw std::runtime_error("ERR stop is not valid integer"); } auto db = readable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_null(); return true; } size_t size = zset->size(); start = pos_fix(start, size); stop = std::min<int64_t>(size, pos_fix(stop, size) + 1); if (stop <= start) { client->response_null(); return true; } auto range = zset->zrange(start, stop); size_t count = std::distance(range.first, range.second); if (count == 0) { throw std::runtime_error("ERR zset structure corrupted"); } client->response_start_multi_bulk(withscores ? count * 2 : count); if (rev) { auto it = range.second; --it; while (true) { client->response_bulk((*it)->member); if (withscores) { client->response_bulk(format("%g", (*it)->score)); } if (range.first == it) { break; } --it; } } else { for (auto it = range.first; it != range.second; ++it) { client->response_bulk((*it)->member); if (withscores) { client->response_bulk(format("%g", (*it)->score)); } } } return true; } ///要素のスコア範囲取得(スコア順&同じスコアはメンバーの辞書順) ///@note Available since 1.0.5. bool server_type::api_zrangebyscore(client_type * client) { return api_zrangebyscore_internal(client, false); } ///要素のスコア範囲取得(逆順) ///@note Available since 1.0.5. bool server_type::api_zrevrangebyscore(client_type * client) { return api_zrangebyscore_internal(client, true); } bool server_type::api_zrangebyscore_internal(client_type * client, bool rev) { auto & arguments = client->get_arguments(); auto & key = client->get_argument(1); auto current = client->get_time(); std::string minimum = client->get_argument(2); std::string maximum = client->get_argument(3); bool inclusive_minimum = true; bool inclusive_maximum = true; if (!minimum.empty() && *minimum.begin() == '(') { inclusive_minimum = false; minimum = minimum.substr(1); } if (!maximum.empty() && *maximum.begin() == '(') { inclusive_maximum = false; maximum = maximum.substr(1); } bool is_valid = true; type_zset::score_type minimum_score = atod(minimum, is_valid); if (!is_valid || isnan(minimum_score)) { throw std::runtime_error("ERR min is not valid"); } type_zset::score_type maximum_score = atod(maximum, is_valid); if (!is_valid || isnan(maximum_score)) { throw std::runtime_error("ERR max is not valid"); } size_t parsed = 4; bool withscores = false; if (parsed < arguments.size()) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "WITHSCORES") { withscores = true; ++parsed; } } bool limit = false; int64_t limit_offset = 0; int64_t limit_count = 0; if (parsed < arguments.size()) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "LIMIT") { limit = true; ++parsed; if (arguments.size() < parsed + 2) { throw std::runtime_error("ERR syntax error, not found limit parameter"); } limit_offset = atoi64(client->get_argument(parsed), is_valid); if (!is_valid || limit_offset < 0) { throw std::runtime_error("ERR limit offset is not valid integer"); } ++parsed; limit_count = atoi64(client->get_argument(parsed), is_valid); if (!is_valid || limit_count < 0) { throw std::runtime_error("ERR limit count is not valid integer"); } ++parsed; } } if (parsed != arguments.size()) { throw std::runtime_error("ERR syntax error"); } auto db = readable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_null(); return true; } auto range = zset->zrangebyscore(minimum_score, maximum_score, inclusive_minimum, inclusive_maximum); if (limit) { if (!rev) { for (int64_t i = 0; i < limit_offset && range.first != range.second; ++i) { ++range.first; } auto end = range.first; for (int64_t i = 0; i < limit_count && end != range.second; ++i) { ++end; } range.second = end; } else { for (int64_t i = 0; i < limit_offset && range.first != range.second; ++i) { --range.second; } auto begin = range.second; for (int64_t i = 0; i < limit_count && begin != range.first; ++i) { --begin; } range.first = begin; } } size_t count = std::distance(range.first, range.second); if (count == 0) { client->response_null(); return true; } client->response_start_multi_bulk(withscores ? count * 2 : count); if (rev) { auto it = range.second; --it; while (true) { client->response_bulk((*it)->member); if (withscores) { client->response_bulk(format("%g", (*it)->score)); } if (range.first == it) { break; } --it; } } else { for (auto it = range.first; it != range.second; ++it) { client->response_bulk((*it)->member); if (withscores) { client->response_bulk(format("%g", (*it)->score)); } } } return true; } ///要素の順序位置を取得 ///@note Available since 2.0.0. bool server_type::api_zrank(client_type * client) { return api_zrank_internal(client, false); } ///要素の順序位置を取得(逆順) ///@note Available since 2.0.0 bool server_type::api_zrevrank(client_type * client) { return api_zrank_internal(client, true); } bool server_type::api_zrank_internal(client_type * client, bool rev) { auto & arguments = client->get_arguments(); auto & key = client->get_argument(1); auto current = client->get_time(); auto & member = client->get_argument(2); auto db = readable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_null(); return true; } size_t rank; if (!zset->zrank(member, rank, rev)) { client->response_null(); return true; } client->response_integer(rank); return true; } ///スコアを取得 ///@note Available since 1.2.0. bool server_type::api_zscore(client_type * client) { auto & arguments = client->get_arguments(); auto & key = client->get_argument(1); auto current = client->get_time(); auto & member = client->get_argument(2); auto db = readable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_null(); return true; } type_zset::score_type score; if (!zset->zscore(member, score)) { client->response_null(); return true; } client->response_bulk(format("%g", score)); return true; } ///要素を削除 ///@note Available since 1.2.0. bool server_type::api_zrem(client_type * client) { auto & arguments = client->get_arguments(); auto & key = client->get_argument(1); auto current = client->get_time(); auto & members = client->get_members(); auto db = writable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_integer0(); return true; } size_t removed = zset->zrem(members); if (removed) { zset->update(current); if (zset->empty()) { db->erase(key, current); } } client->response_integer(removed); return true; } ///ランクで要素を削除 ///@note Available since 1.2.0. bool server_type::api_zremrangebyrank(client_type * client) { auto & arguments = client->get_arguments(); auto & key = client->get_argument(1); auto current = client->get_time(); bool is_valid; int64_t start = atoi64(client->get_argument(2), is_valid); if (!is_valid) { throw std::runtime_error("ERR start is not valid integer"); } int64_t stop = atoi64(client->get_argument(3), is_valid); if (!is_valid) { throw std::runtime_error("ERR stop is not valid integer"); } auto db = writable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_integer0(); return true; } size_t size = zset->size(); start = pos_fix(start, size); stop = std::min<int64_t>(size, pos_fix(stop, size) + 1); if (stop <= start) { client->response_integer0(); return true; } auto range = zset->zrange(start, stop); std::list<std::string> members_; size_t count = 0; for (; range.first != range.second; ++range.first) { ++count; members_.push_back((*range.first)->member); } std::vector<std::string*> members; members.reserve(count); for (auto it = members_.begin(), end = members_.end(); it != end; ++it) { members.push_back(&*it); } size_t removed = zset->zrem(members); if (removed) { zset->update(current); if (zset->empty()) { db->erase(key, current); } } client->response_integer(removed); return true; } ///スコアの範囲で要素を削除 ///Available since 1.2.0. bool server_type::api_zremrangebyscore(client_type * client) { auto & arguments = client->get_arguments(); auto & key = client->get_argument(1); auto current = client->get_time(); std::string minimum = client->get_argument(2); std::string maximum = client->get_argument(3); bool inclusive_minimum = true; bool inclusive_maximum = true; if (!minimum.empty() && *minimum.begin() == '(') { inclusive_minimum = false; minimum = minimum.substr(1); } if (!maximum.empty() && *maximum.begin() == '(') { inclusive_maximum = false; maximum = maximum.substr(1); } bool is_valid = true; type_zset::score_type minimum_score = atod(minimum, is_valid); if (!is_valid || isnan(minimum_score)) { throw std::runtime_error("ERR min is not valid"); } type_zset::score_type maximum_score = atod(maximum, is_valid); if (!is_valid || isnan(maximum_score)) { throw std::runtime_error("ERR max is not valid"); } auto db = writable_db(client); std::shared_ptr<type_zset> zset = db->get_zset(key, current); if (!zset) { client->response_integer0(); return true; } auto range = zset->zrangebyscore(minimum_score, maximum_score, inclusive_minimum, inclusive_maximum); std::list<std::string> members_; size_t count = 0; for (; range.first != range.second; ++range.first) { ++count; members_.push_back((*range.first)->member); } std::vector<std::string*> members; members.reserve(count); for (auto it = members_.begin(), end = members_.end(); it != end; ++it) { members.push_back(&*it); } size_t removed = zset->zrem(members); if (removed) { zset->update(current); if (zset->empty()) { db->erase(key, current); } } client->response_integer(removed); return true; } }; <file_sep>#include "database.h" #include "client.h" #include "expire_info.h" #include "type_hash.h" #include "type_list.h" #include "type_set.h" #include "type_string.h" #include "type_zset.h" namespace rediscpp { database_write_locker::database_write_locker(database_type * database_, client_type * client, bool rdlock) : database(database_) , locker(new rwlock_locker(database_->rwlock, client && client->in_exec() ? no_lock_type : (rdlock ? read_lock_type : write_lock_type))) { } database_read_locker::database_read_locker(database_type * database_, client_type * client) : database(database_) , locker(new rwlock_locker(database_->rwlock, client && client->in_exec() ? no_lock_type : read_lock_type)) { } database_type::database_type() { } size_t database_type::get_dbsize() const { return values.size(); } void database_type::clear() { values.clear(); } std::shared_ptr<type_interface> database_type::get(const std::string & key, const timeval_type & current) const { auto it = values.find(key); if (it == values.end()) { return std::shared_ptr<type_interface>(); } auto & value = it->second; if (value.first->is_expired(current)) { //values.erase(it); return std::shared_ptr<type_interface>(); } return value.second; } std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_interface>> database_type::get_with_expire(const std::string & key, const timeval_type & current) const { auto it = values.find(key); if (it == values.end()) { return std::make_pair(std::shared_ptr<expire_info>(), std::shared_ptr<type_interface>()); } auto & value = it->second; if (value.first->is_expired(current)) { //values.erase(it); return std::make_pair(std::shared_ptr<expire_info>(), std::shared_ptr<type_interface>()); } return value; } template<typename T> std::shared_ptr<T> get_as(const database_type & db, const std::string & key, const timeval_type & current) { std::shared_ptr<type_interface> val = db.get(key, current); if (!val) { return std::shared_ptr<T>(); } std::shared_ptr<T> value = std::dynamic_pointer_cast<T>(val); if (!value) { throw std::runtime_error("ERR type mismatch"); } return value; } template<typename T> std::pair<std::shared_ptr<expire_info>,std::shared_ptr<T>> get_as_with_expire(const database_type & db, const std::string & key, const timeval_type & current) { std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_interface>> val = db.get_with_expire(key, current); if (!val.second) { return std::make_pair(std::shared_ptr<expire_info>(), std::shared_ptr<T>()); } std::shared_ptr<T> value = std::dynamic_pointer_cast<T>(val.second); if (!value) { throw std::runtime_error("ERR type mismatch"); } return std::make_pair(val.first, value); } std::shared_ptr<type_string> database_type::get_string(const std::string & key, const timeval_type & current) const { return get_as<type_string>(*this, key, current); } std::shared_ptr<type_list> database_type::get_list(const std::string & key, const timeval_type & current) const { return get_as<type_list>(*this, key, current); } std::shared_ptr<type_hash> database_type::get_hash(const std::string & key, const timeval_type & current) const { return get_as<type_hash>(*this, key, current); } std::shared_ptr<type_set> database_type::get_set(const std::string & key, const timeval_type & current) const { return get_as<type_set>(*this, key, current); } std::shared_ptr<type_zset> database_type::get_zset(const std::string & key, const timeval_type & current) const { return get_as<type_zset>(*this, key, current); } std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_string>> database_type::get_string_with_expire(const std::string & key, const timeval_type & current) const { return get_as_with_expire<type_string>(*this, key, current); } std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_list>> database_type::get_list_with_expire(const std::string & key, const timeval_type & current) const { return get_as_with_expire<type_list>(*this, key, current); } std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_hash>> database_type::get_hash_with_expire(const std::string & key, const timeval_type & current) const { return get_as_with_expire<type_hash>(*this, key, current); } std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_set>> database_type::get_set_with_expire(const std::string & key, const timeval_type & current) const { return get_as_with_expire<type_set>(*this, key, current); } std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_zset>> database_type::get_zset_with_expire(const std::string & key, const timeval_type & current) const { return get_as_with_expire<type_zset>(*this, key, current); } bool database_type::erase(const std::string & key, const timeval_type & current) { auto it = values.find(key); if (it == values.end()) { return false; } auto value = it->second; if (value.first->is_expired(current)) { values.erase(it); return false; } values.erase(it); return true; } bool database_type::insert(const std::string & key, const expire_info & expire, std::shared_ptr<type_interface> value, const timeval_type & current) { auto it = values.find(key); if (it == values.end()) { bool result = values.insert(std::make_pair(key, std::make_pair(std::shared_ptr<expire_info>(new expire_info(expire)), value))).second; if (result && expire.is_expiring()) { regist_expiring_key(expire.at(), key); } return result; } else { if (it->second.first->is_expired(current)) { it->second.first->set(expire); it->second.second = value; if (expire.is_expiring()) { regist_expiring_key(expire.at(), key); } return true; } return false; } } void database_type::replace(const std::string & key, const expire_info & expire, std::shared_ptr<type_interface> value) { auto & dst = values[key]; dst.first.reset(new expire_info(expire)); dst.second = value; if (expire.is_expiring()) { regist_expiring_key(expire.at(), key); } } bool database_type::insert(const std::string & key, std::shared_ptr<type_interface> value, const timeval_type & current) { auto it = values.find(key); if (it == values.end()) { return values.insert(std::make_pair(key, std::make_pair(std::shared_ptr<expire_info>(new expire_info()), value))).second; } else { if (it->second.first->is_expired(current)) { it->second.first->persist(); it->second.second = value; return true; } return false; } } void database_type::replace(const std::string & key, std::shared_ptr<type_interface> value) { auto & dst = values[key]; dst.first.reset(new expire_info()); dst.second = value; } std::string database_type::randomkey(const timeval_type & current) { while (!values.empty()) { auto it = values.begin(); std::advance(it, rand() % values.size()); if (it->second.first->is_expired(current)) { values.erase(it); continue; } return it->first; } return std::string(); } void database_type::regist_expiring_key(timeval_type tv, const std::string & key) const { mutex_locker locker(expire_mutex); expires.insert(std::make_pair(tv, key)); } void database_type::flush_expiring_key(const timeval_type & current) { mutex_locker locker(expire_mutex); if (expires.empty()) { return; } auto it = expires.begin(), end = expires.end(); for (; it != end && it->first < current; ++it) { auto vit = values.find(it->second); if (vit != values.end() && vit->second.first->is_expired(current)) { values.erase(vit); } } expires.erase(expires.begin(), it); } void database_type::match(std::unordered_set<std::string> & result, const std::string & pattern) const { if (pattern == "*") { for (auto it = values.begin(), end = values.end(); it != end; ++it) { auto & key = it->first; result.insert(key); } } else { for (auto it = values.begin(), end = values.end(); it != end; ++it) { auto & key = it->first; if (pattern_match(pattern, key)) { result.insert(key); } } } } }; <file_sep>#include "timeval.h" #include <sys/time.h> namespace rediscpp { timeval_type::timeval_type() { update(); } void timeval_type::update() { int r = gettimeofday(this, NULL); if (r < 0) { throw std::runtime_error("ERR could not get time"); } } timeval_type::timeval_type(const timeval_type & rhs) { tv_sec = rhs.tv_sec; tv_usec = rhs.tv_usec; } timeval_type::timeval_type(time_t sec, suseconds_t usec) { tv_sec = sec; tv_usec = usec; } timeval_type & timeval_type::operator=(const timeval_type & rhs) { tv_sec = rhs.tv_sec; tv_usec = rhs.tv_usec; return *this; } bool timeval_type::operator==(const timeval_type & rhs) const { return (tv_sec == rhs.tv_sec) && (tv_usec == rhs.tv_usec); } bool timeval_type::operator<(const timeval_type & rhs) const { return (tv_sec != rhs.tv_sec) ? tv_sec < rhs.tv_sec : tv_usec < rhs.tv_usec; } timeval_type & timeval_type::operator+=(const timeval_type & rhs) { tv_sec += rhs.tv_sec; tv_usec += rhs.tv_usec; if (1000000 <= tv_usec) { tv_usec -= 1000000; ++tv_sec; } return *this; } timeval_type & timeval_type::operator-=(const timeval_type & rhs) { tv_sec -= rhs.tv_sec; if (rhs.tv_usec <= tv_usec) { tv_usec -= rhs.tv_usec; } else { --tv_sec; tv_usec += 1000000 - rhs.tv_usec; } return *this; } void timeval_type::add_msec(int64_t msec) { *this += timeval_type(msec / 1000, (msec % 1000) * 1000); } } <file_sep>#include "master.h" #include "server.h" #include "file.h" namespace rediscpp { master_type::master_type(server_type & server_, std::shared_ptr<socket_type> & client_, const std::string & password_) : client_type(server_, client_, password_) , state(waiting_pong_state) , sync_file_size(0) { } master_type::~master_type() { sync_file.reset(); if (!sync_file_path.empty()) { ::unlink(sync_file_path.c_str()); sync_file_path.clear(); } } void server_type::slaveof(const std::string & host, const std::string & port, bool now) { if (thread_pool.empty() || now) { if (master) { if (host == "no" && port == "one") { lprintf(__FILE__, __LINE__, debug_level, "shutdown master now"); //@todo もう少し安全な停止を考える master->client->shutdown(true, true); } else { //@todo 既にslaveの場合、slaveになる必要があるので、何か処理を考える必要がある lprintf(__FILE__, __LINE__, debug_level, "could not shutdown master now"); } } else { std::shared_ptr<address_type> address(new address_type()); if (!address->set_hostname(host)) { lprintf(__FILE__, __LINE__, error_level, "failed to set master hostname : %s", host.c_str()); return; } bool is_valid = false; uint16_t port_ = atou16(port,is_valid); if (!is_valid || !address->set_port(port_)) { lprintf(__FILE__, __LINE__, error_level, "failed to set master port : %s", port.c_str()); return; } std::shared_ptr<socket_type> connection = socket_type::create(*address); connection->set_extra(this); connection->set_callback(client_callback); connection->set_nonblocking(); if (!connection->connect(address)) { lprintf(__FILE__, __LINE__, error_level, "failed to connect master"); return; } std::shared_ptr<client_type> client(new master_type(*this, connection, password)); client->set(client); connection->set_extra2(client.get()); //@note 送信バッファに設定することで、接続済みのイベントを取得して、送信する std::string ping("*1\r\n$4\r\nPING\r\n"); connection->send(ping.c_str(), ping.size()); append_client(client); } } else { std::shared_ptr<job_type> job(new job_type(job_type::slaveof_type)); job->arg1 = host; job->arg2 = port; jobs.push(job); event->send(); } } void master_type::process() { if (state == writer_state) { client_type::process(); return; } if (events & EPOLLIN) {//recv client->recv(); } if (events & EPOLLOUT) {//send client->send(); } while (true) { switch (state) { case waiting_pong_state: if (client->should_recv()) { std::string line; if (parse_line(line)) { if (line == "+PONG") { state = request_replconf_state; continue; } else if (line.substr(0, 7) == "-NOAUTH") { state = request_auth_state; continue; } else { lprintf(__FILE__, __LINE__, error_level, "failed to get ping response"); state = shutdown_state; continue; } } } return; case request_auth_state: { std::string auth = format("*2\r\n$4\r\nAUTH\r\n$%d\r\n", password.size()) + password + <PASSWORD>"; if (!client->send(auth.c_str(), auth.size())) { lprintf(__FILE__, __LINE__, error_level, "failed to send auth"); state = shutdown_state; continue; } client->send(); state = waiting_auth_state; } return; case waiting_auth_state: if (client->should_recv()) { std::string line; if (parse_line(line)) { if (line.substr(0,1) == "+") { state = request_replconf_state; continue; } else { lprintf(__FILE__, __LINE__, error_level, "failed to get auth response"); state = shutdown_state; continue; } } } return; case request_replconf_state: { std::string port = format("%d", server.listening_port); std::string replconf = format("*3\r\n$8\r\nREPLCONF\r\n$14\r\nlistening-port\r\n$%zd\r\n%s\r\n", port.size(), port.c_str()); if (!client->send(replconf.c_str(), replconf.size())) { lprintf(__FILE__, __LINE__, error_level, "failed to send replconf"); state = shutdown_state; continue; } client->send(); state = waiting_replconf_state; } return; case waiting_replconf_state: if (client->should_recv()) { std::string line; if (parse_line(line)) { if (line.substr(0,1) == "+") { state = request_sync_state; continue; } else { lprintf(__FILE__, __LINE__, error_level, "failed to get replconf response"); state = shutdown_state; continue; } } } return; case request_sync_state: { std::string sync("*1\r\n$4\r\nSYNC\r\n"); if (!client->send(sync.c_str(), sync.size())) { lprintf(__FILE__, __LINE__, error_level, "failed to send sync"); state = shutdown_state; continue; } client->send(); state = waiting_sync_state; } return; case waiting_sync_state: if (!sync_file_size) { std::string line; if (parse_line(line)) { bool is_valid = false; if (line.substr(0,1) == "$") { sync_file_size = atoi64(line.substr(1), is_valid); } if (!sync_file_size || !is_valid) { lprintf(__FILE__, __LINE__, error_level, "failed to get sync file size"); state = shutdown_state; } else { //@todo テンポラリファイルにする必要がある char path[] = "/tmp/redis.sync.rdb.XXXXXX"; int fd = mkstemp(path); if (fd < 0) { lprintf(__FILE__, __LINE__, error_level, "failed to create tmp file"); state = shutdown_state; continue; } close(fd); sync_file_path = path; sync_file = file_type::create(sync_file_path); } continue; } } else if (sync_file) { if (client->should_recv()) { auto & buf = client->get_recv(); size_t size = std::min(sync_file_size, buf.size()); auto end = buf.begin() + size; std::vector<uint8_t> tmp(buf.begin(), end); sync_file->write(tmp); sync_file->flush(); buf.erase(buf.begin(), end); sync_file_size -= size; } if (sync_file_size == 0) { sync_file.reset(); //load if (!server.load(sync_file_path)) { lprintf(__FILE__, __LINE__, error_level, "failed to load sync file"); state = shutdown_state; continue; } ::unlink(sync_file_path.c_str()); sync_file_path.clear(); state = writer_state; lprintf(__FILE__, __LINE__, debug_level, "now waiting master request"); continue; } } else { lprintf(__FILE__, __LINE__, error_level, "failed to get sync file object"); state = shutdown_state; continue; } return; case writer_state: client_type::process(); return; case shutdown_state: default: lprintf(__FILE__, __LINE__, error_level, "master shutdown now"); client->shutdown(true, true); return; } } } }; <file_sep>#ifndef INCLUDE_REDIS_CPP_EXPIRE_INFO_H #define INCLUDE_REDIS_CPP_EXPIRE_INFO_H #include "timeval.h" namespace rediscpp { class expire_info { timeval_type expire_time;///<0,0なら有効期限無し、消失する日時を保存する public: expire_info() : expire_time(0, 0) { } expire_info(const expire_info & rhs) : expire_time(rhs.expire_time) { } expire_info(const timeval_type & current) : expire_time(0, 0) { } ~expire_info(){} expire_info & operator=(const expire_info & rhs) { if (this != &rhs) { expire_time = rhs.expire_time; } return *this; } void set(const expire_info & rhs) { if (this != &rhs) { expire_time = rhs.expire_time; } } bool is_expired(const timeval_type & current) const; void expire(const timeval_type & at); void persist(); bool is_expiring() const; timeval_type ttl(const timeval_type & current) const; timeval_type at() const { expire_time; } }; }; #endif <file_sep>#include "client.h" #include "type_hash.h" #include "type_list.h" #include "type_set.h" #include "type_string.h" #include "type_zset.h" #include "server.h" #include "file.h" namespace rediscpp { client_type::client_type(server_type & server_, std::shared_ptr<socket_type> & client_, const std::string & password_) : server(server_) , client(client_) , argument_count(0) , argument_index(0) , argument_size(argument_is_undefined) , password(<PASSWORD>_) , db_index(0) , transaction(false) , writing_transaction(false) , multi_executing(false) , current_time(0, 0) , write_mutex(true) , events(0) , blocked(false) , blocked_till(0, 0) , listening_port(0) , slave(false) , monitor(false) , wrote(false) { write_cache.reserve(1500); } void client_type::process() { if (is_blocked()) { parse(); if (client->should_send()) { client->send(); } if (!is_blocked()) { client->mod(); } return; } if (events & EPOLLIN) {//recv //lputs(__FILE__, __LINE__, info_level, "client EPOLLIN"); client->recv(); if (client->should_recv()) { parse(); } if (client->done()) { return; } if (client->should_send()) { client->send(); } } if (events & EPOLLOUT) {//send //lputs(__FILE__, __LINE__, info_level, "client EPOLLOUT"); client->send(); } if (is_slave()) { if (!client->is_sendfile() && sending_file) { lputs(__FILE__, __LINE__, info_level, "slave file done"); sending_file.reset(); flush(); client->send(); } } } void client_type::inline_command_parser(const std::string & line) { size_t end = line.size(); for (size_t offset = 0; offset < end && offset != line.npos;) { size_t space = line.find(' ', offset); if (space != line.npos) { arguments.push_back(line.substr(offset, space - offset)); offset = line.find_first_not_of(' ', space + 1); } else { arguments.push_back(line.substr(offset)); break; } } } bool client_type::parse() { bool time_updated = false; try { while (true) { if (argument_count == 0) { std::string arg_count; if (!parse_line(arg_count)) { break; } if (arg_count.empty()) { continue; } char type = *arg_count.begin(); if (type == '*') { argument_count = atoi(arg_count.c_str() + 1); argument_index = 0; if (argument_count <= 0) { lprintf(__FILE__, __LINE__, info_level, "unsupported protocol %s", arg_count.c_str()); flush(); return false; } arguments.clear(); arguments.resize(argument_count); } else if (type == '+' || type == '-') {//response from slave continue; } else { inline_command_parser(arg_count); argument_index = argument_count = arg_count.size(); if (!time_updated) { time_updated = true; current_time.update(); } if (!execute()) { response_error("ERR unknown"); } arguments.clear(); argument_count = 0; argument_index = 0; argument_size = argument_is_undefined; } } else if (argument_index < argument_count) { if (argument_size == argument_is_undefined) { std::string arg_size; if (!parse_line(arg_size)) { break; } if (!arg_size.empty() && *arg_size.begin() == '$') { argument_size = atoi(arg_size.c_str() + 1); if (argument_size < -1) { lprintf(__FILE__, __LINE__, info_level, "unsupported protocol %s", arg_size.c_str()); flush(); return false; } if (argument_size < 0) { argument_size = argument_is_undefined; ++argument_index; } } else { lprintf(__FILE__, __LINE__, info_level, "unsupported protocol %s", arg_size.c_str()); flush(); return false; } } else { std::string arg_data; if (!parse_data(arg_data, argument_size)) { break; } auto & arg = arguments[argument_index]; arg = arg_data; argument_size = argument_is_undefined; ++argument_index; } } else { if (!time_updated) { time_updated = true; current_time.update(); } if (!execute()) { response_error("ERR unknown"); } arguments.clear(); argument_count = 0; argument_index = 0; argument_size = argument_is_undefined; } } } catch (blocked_exception e) { } flush(); return true; } void client_type::response_status(const std::string & state) { response_raw("+" + state + "\r\n"); } void client_type::response_error(const std::string & state) { response_raw("-" + state + "\r\n"); } void client_type::response_ok() { response_raw("+OK\r\n"); } void client_type::response_pong() { response_raw("+PONG\r\n"); } void client_type::response_queued() { response_raw("+QUEUED\r\n"); } void client_type::response_integer0() { response_raw(":0\r\n"); } void client_type::response_integer1() { response_raw(":1\r\n"); } void client_type::response_integer(int64_t value) { response_raw(format(":%"PRId64"\r\n", value)); } void client_type::response_bulk(const std::string & bulk, bool not_null) { if (not_null) { response_raw(format("$%zd\r\n", bulk.size())); response_raw(bulk); response_raw("\r\n"); } else { response_null(); } } void client_type::response_null() { response_raw("$-1\r\n"); } void client_type::response_null_multi_bulk() { response_raw("*-1\r\n"); } void client_type::response_start_multi_bulk(size_t count) { response_raw(format("*%zd\r\n", count)); } void client_type::response_raw(const std::string & raw) { mutex_locker locker(write_mutex); if (client->is_sendfile()) { write_cache.insert(write_cache.end(), raw.begin(), raw.end()); return; } if (raw.size() <= write_cache.capacity() - write_cache.size()) { write_cache.insert(write_cache.end(), raw.begin(), raw.end()); } else if (raw.size() <= write_cache.capacity()) { flush(); write_cache.insert(write_cache.end(), raw.begin(), raw.end()); } else { flush(); client->send(raw.c_str(), raw.size()); } } void client_type::request(const arguments_type & args) { if (args.size()) { lprintf(__FILE__, __LINE__, info_level, "request %s", args[0].c_str()); response_start_multi_bulk(args.size()); for (auto it = args.begin(), end = args.end(); it != end; ++it) { response_bulk(*it); } } else { response_null_multi_bulk(); } } void client_type::flush() { if (!client->is_sendfile()) { mutex_locker locker(write_mutex); if (!write_cache.empty()) { client->send(&write_cache[0], write_cache.size()); write_cache.clear(); } } client->send(); } bool client_type::parse_line(std::string & line) { auto & buf = client->get_recv(); if (buf.size() < 2) { return false; } auto begin = buf.begin(); auto end = buf.end(); --end; auto it = std::find(begin, end, '\r'); if (it != end) { line.assign(begin, it); std::advance(it, 2); buf.erase(begin, it); return true; } return false; } bool client_type::parse_data(std::string & data, int size) { auto & buf = client->get_recv(); if (buf.size() < size + 2) { return false; } auto begin = buf.begin(); auto end = begin; std::advance(end, size); data.assign(begin, end); std::advance(end, 2); buf.erase(begin, end); return true; } bool client_type::execute() { try { if (is_monitor()) { throw std::runtime_error("ERR monitor not accept command"); } if (arguments.empty()) { throw std::runtime_error("ERR syntax error"); } auto & command = arguments.front(); //lprintf(__FILE__, __LINE__, debug_level, "command %s", command.c_str()); std::transform(command.begin(), command.end(), command.begin(), toupper); if (require_auth(command)) { throw std::runtime_error("NOAUTH Authentication required."); } auto it = server.api_map.find(command); if (it != server.api_map.end()) { if (queuing(command, it->second)) { response_queued(); return true; } return execute(it->second); } //lprintf(__FILE__, __LINE__, info_level, "not supported command %s", command.c_str()); } catch (blocked_exception & e) { throw; } catch (std::exception & e) { response_error(e.what()); return true; } catch (...) { lputs(__FILE__, __LINE__, info_level, "unknown exception"); return false; } return false; } bool client_type::execute(const api_info & info) { //引数確認 if (arguments.size() < info.min_argc) { response_error("ERR syntax error too few arguments"); return true; } if (info.max_argc < arguments.size()) { response_error("ERR syntax error too much arguments"); return true; } try { size_t argc = arguments.size(); size_t pattern_length = info.arg_types.size(); size_t arg_pos = 0; keys.clear(); values.clear(); members.clear(); fields.clear(); scores.clear(); keys.reserve(argc); values.reserve(argc); members.reserve(argc); fields.reserve(argc); scores.reserve(argc); for (; arg_pos < pattern_length && arg_pos < argc; ++arg_pos) { if (info.arg_types[arg_pos] == '*') { break; } switch (info.arg_types[arg_pos]) { case 'c'://command case 't'://time case 'n'://numeric case 'p'://pattern break; case 'k'://key keys.push_back(&arguments[arg_pos]); break; case 'v'://value values.push_back(&arguments[arg_pos]); break; case 'f'://field fields.push_back(&arguments[arg_pos]); break; case 'm'://member members.push_back(&arguments[arg_pos]); break; case 's'://scre scores.push_back(&arguments[arg_pos]); break; case 'd'://db index { int64_t index = atoi64(arguments[arg_pos]); if (index < 0 || server.databases.size() <= index) { throw std::runtime_error("ERR db index is wrong range"); } } break; } } //後方一致 std::list<std::string*> back_keys; std::list<std::string*> back_values; std::list<std::string*> back_fields; std::list<std::string*> back_members; std::list<std::string*> back_scores; if (arg_pos < argc && arg_pos < pattern_length && info.arg_types[arg_pos] == '*') { for (; 0 < argc && arg_pos < pattern_length; --argc, --pattern_length) { if (info.arg_types[pattern_length-1] == '*') { break; } switch (info.arg_types[pattern_length-1]) { case 'c'://command case 't'://time case 'n'://numeric case 'p'://pattern break; case 'k'://key back_keys.push_front(&arguments[argc-1]); break; case 'v'://value back_values.push_front(&arguments[argc-1]); break; case 'f'://field back_fields.push_back(&arguments[argc-1]); break; case 'm'://member back_members.push_back(&arguments[argc-1]); break; case 's'://scre back_scores.push_back(&arguments[argc-1]); break; case 'd'://db index { int64_t index = atoi64(arguments[argc-1]); if (index < 0 || server.databases.size() <= index) { throw std::runtime_error("ERR db index is wrong range"); } } break; } } } if (arg_pos < argc) { size_t star_count = 0; for (size_t i = arg_pos; i < pattern_length; ++i) { if (info.arg_types[i] == '*') { ++star_count; } else { throw std::runtime_error("ERR syntax error too few arguments"); } } if (!star_count || arg_pos < star_count) { throw std::runtime_error("ERR command structure error"); } if ((argc - arg_pos) % star_count != 0) { throw std::runtime_error("ERR syntax error"); } for (size_t s = 0; s < star_count; ++s) { switch (info.arg_types[arg_pos+s-star_count]) { case 'k': for (size_t pos = arg_pos + s; pos < argc; pos += star_count) { keys.push_back(&arguments[pos]); } break; case 'v': for (size_t pos = arg_pos + s; pos < argc; pos += star_count) { values.push_back(&arguments[pos]); } break; case 'f': for (size_t pos = arg_pos + s; pos < argc; pos += star_count) { fields.push_back(&arguments[pos]); } break; case 'm': for (size_t pos = arg_pos + s; pos < argc; pos += star_count) { members.push_back(&arguments[pos]); } break; case 's': for (size_t pos = arg_pos + s; pos < argc; pos += star_count) { scores.push_back(&arguments[pos]); } break; case 'c': break; default: throw std::runtime_error("ERR command pattern error"); } } } if (!back_keys.empty()) keys.insert(keys.end(), back_keys.begin(), back_keys.end()); if (!back_values.empty()) values.insert(values.end(), back_values.begin(), back_values.end()); if (!back_fields.empty()) fields.insert(fields.end(), back_fields.begin(), back_fields.end()); if (!back_members.empty()) members.insert(members.end(), back_members.begin(), back_members.end()); if (!back_scores.empty()) scores.insert(scores.end(), back_scores.begin(), back_scores.end()); wrote = info.writing; bool result = (server.*(info.function))(this); if (server.monitoring) { std::string info = format("%d.%06d [%d %s]", current_time.tv_sec, current_time.tv_usec, db_index, client->get_peer_info().c_str()); for (auto it = arguments.begin(), begin = it, end = arguments.end(); it != end; ++it) { info += format(" \"%s\"", it->c_str()); } server.propagete(info); } if (wrote) { mutex_locker locker(server.slave_mutex); if (!server.slaves.empty()) { server.propagete(arguments); } } keys.clear(); values.clear(); fields.clear(); members.clear(); scores.clear(); return result; } catch (...) { keys.clear(); values.clear(); fields.clear(); members.clear(); scores.clear(); throw; } } void client_type::response_file(const std::string & path) { flush(); sending_file = file_type::open(path, false, true); size_t size = sending_file->size(); std::string header = format("$%zd\r\n", size); client->send(header.c_str(), header.size()); client->sendfile(sending_file->get_fd(), size); } }; <file_sep>#ifndef INCLUDE_REDIS_CPP_CLIENT_H #define INCLUDE_REDIS_CPP_CLIENT_H #include "network.h" #include "thread.h" #include "type_interface.h" namespace rediscpp { typedef std::vector<std::string> arguments_type; class server_type; struct api_info; class file_type; class client_type { friend class server_type; protected: server_type & server; std::shared_ptr<socket_type> client; arguments_type arguments; std::vector<std::string*> keys; std::vector<std::string*> values; std::vector<std::string*> fields; std::vector<std::string*> members; std::vector<std::string*> scores; int argument_count; int argument_index; int argument_size; std::string password; static const int argument_is_null = -1; static const int argument_is_undefined = -2; int db_index; bool transaction; bool writing_transaction; bool multi_executing; std::list<arguments_type> transaction_arguments; std::set<std::tuple<std::string,int,timeval_type>> watching; mutex_type write_mutex; std::vector<uint8_t> write_cache; timeval_type current_time; int events;//for thread bool blocked;//for list timeval_type blocked_till; std::weak_ptr<client_type> self; uint16_t listening_port; bool slave; bool monitor; bool wrote; std::shared_ptr<file_type> sending_file; public: client_type(server_type & server_, std::shared_ptr<socket_type> & client_, const std::string & password_); virtual ~client_type(){} bool parse(); const arguments_type & get_arguments() const { return arguments; } const std::string & get_argument(int index) const { return arguments[index]; } const std::vector<std::string*> & get_keys() const { return keys; } const std::vector<std::string*> & get_values() const { return values; } const std::vector<std::string*> & get_fields() const { return fields; } const std::vector<std::string*> & get_members() const { return members; } const std::vector<std::string*> & get_scores() const { return scores; } void response_status(const std::string & state); void response_error(const std::string & state); void response_ok(); void response_pong(); void response_queued(); void response_integer(int64_t value); void response_integer0(); void response_integer1(); void response_bulk(const std::string & bulk, bool not_null = true); void response_null(); void response_null_multi_bulk(); void response_start_multi_bulk(size_t count); void response_raw(const std::string & raw); void response_file(const std::string & path); void request(const arguments_type & args); void flush(); void close_after_send() { client->close_after_send(); } bool require_auth(const std::string & auth); bool auth(const std::string & password_); void select(int index) { db_index = index; } int get_db_index() { return db_index; } bool multi(); bool exec(); void discard(); bool in_exec() const; bool queuing(const std::string & command, const api_info & info); void unwatch() { watching.clear(); } void watch(const std::string & key); std::set<std::tuple<std::string,int,timeval_type>> & get_watching() { return watching; } size_t get_transaction_size() { return transaction_arguments.size(); } bool unqueue(); timeval_type get_time() const { return current_time; } virtual void process(); void set(std::shared_ptr<client_type> self_) { self = self_; } std::shared_ptr<client_type> get() { return self.lock(); } bool is_blocked() const { return blocked; } timeval_type get_blocked_till() const { return blocked_till; } void start_blocked(int64_t sec) { blocked = true; if (0 < sec) { blocked_till = current_time; blocked_till.add_msec(sec * 1000); } else { blocked_till.epoc(); } } void end_blocked() { blocked = false; } bool still_block() const { return blocked && (blocked_till.is_epoc() || current_time < blocked_till); } virtual bool is_master() const { return false; } void set_slave() { slave = true; } bool is_slave() const { return slave; } void set_monitor() { monitor = true; } bool is_monitor() const { return monitor; } protected: void inline_command_parser(const std::string & line); bool parse_line(std::string & line); bool parse_data(std::string & data, int size); bool execute(); bool execute(const api_info & info); }; }; #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_TYPE_HASH_H #define INCLUDE_REDIS_CPP_TYPE_HASH_H #include "type_interface.h" namespace rediscpp { class type_hash : public type_interface { std::unordered_map<std::string, std::string> value; public: type_hash(); type_hash(const timeval_type & current); virtual ~type_hash(); virtual type_types get_type() const { return hash_type; } virtual void output(std::shared_ptr<file_type> & dst) const; virtual void output(std::string & dst) const; static std::shared_ptr<type_hash> input(std::shared_ptr<file_type> & src); static std::shared_ptr<type_hash> input(std::pair<std::string::const_iterator,std::string::const_iterator> & src); size_t hdel(const std::vector<std::string*> & fields); bool hexists(const std::string field) const; bool empty() const; std::pair<std::string,bool> hget(const std::string field) const; std::pair<std::unordered_map<std::string, std::string>::const_iterator,std::unordered_map<std::string, std::string>::const_iterator> hgetall() const; size_t size() const; bool hset(const std::string & field, const std::string & val, bool nx = false); }; }; #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_FILE_H #define INCLUDE_REDIS_CPP_FILE_H #include "common.h" #include "crc64.h" #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> namespace rediscpp { class file_type { int fd; uint64_t crc; bool checking_crc; std::string path; bool unlink_on_close; file_type(); file_type(const file_type & rhs); file_type(int fd_, bool checking_crc_ = false) : fd(fd_) , crc(0) , checking_crc(checking_crc_) , unlink_on_close(false) { } public: ~file_type() { if (0 <= fd) { close(fd); if (unlink_on_close) { int r = ::unlink(path.c_str()); if (r < 0) { lprintf(__FILE__, __LINE__, error_level, "failed: unlink(%s) : %s", path.c_str(), string_error(errno).c_str()); } } } } static std::shared_ptr<file_type> create(const std::string & path, bool checking_crc_ = false) { int fd = ::open(path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC | O_LARGEFILE, 0666); if (fd < 0) { lprintf(__FILE__, __LINE__, error_level, "failed: create(%s) : %s", path.c_str(), string_error(errno).c_str()); return std::shared_ptr<file_type>(); } return std::shared_ptr<file_type>(new file_type(fd, checking_crc_)); } static std::shared_ptr<file_type> open(const std::string & path, bool checking_crc_ = false, bool unlink_on_close_ = false) { int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_LARGEFILE); if (fd < 0) { lprintf(__FILE__, __LINE__, error_level, "failed: open(%s) : %s", path.c_str(), string_error(errno).c_str()); return std::shared_ptr<file_type>(); } std::shared_ptr<file_type> result(new file_type(fd, checking_crc_)); if (unlink_on_close_) { result->unlink_on_close = true; result->path = path; } return result; } int get_fd() const { return fd; } void write(const std::string & str) { write(str.c_str(), str.size()); } void write(const std::vector<uint8_t> & data) { if (!data.empty()) { write(&data[0], data.size()); } } void printf(const char * fmt, ...) { va_list args; va_start(args, fmt); std::string str = vformat(fmt, args); va_end(args); write(str); } void write8(uint8_t value) { write(&value, 1); } void write16(uint16_t value) { write(&value, 2); } void write32(uint32_t value) { write(&value, 4); } void write64(uint64_t value) { write(&value, 8); } void write(const void * ptr, size_t len) { if (len) { if (checking_crc) { crc = crc64::update(crc, ptr, len); } ssize_t r = ::write(fd, ptr, len); if (r != len) { lprintf(__FILE__, __LINE__, error_level, "failed: write(%"PRId64") : %s", len, string_error(errno).c_str()); throw std::runtime_error("file io error"); } } } void write_crc() { write64(htobe64(crc)); } bool check_crc() { uint64_t check = htobe64(crc); return read64() == check; } void read(void * ptr, size_t len) { if (len) { ssize_t r = ::read(fd, ptr, len); if (r != len) { lprintf(__FILE__, __LINE__, error_level, "failed: read(%"PRId64") : %s", len, string_error(errno).c_str()); throw std::runtime_error("file io error"); } if (checking_crc) { crc = crc64::update(crc, ptr, len); } } } uint8_t read8() { uint8_t value; read(&value, 1); return value; } uint16_t read16() { uint16_t value; read(&value, 2); return value; } uint32_t read32() { uint32_t value; read(&value, 4); return value; } uint64_t read64() { uint64_t value; read(&value, 8); return value; } void flush() { int r = ::fsync(fd); if (r < 0) { lprintf(__FILE__, __LINE__, error_level, "failed: fsync : %s", string_error(errno).c_str()); } } size_t size() { struct stat st; int r = ::fstat(fd, &st); if (r < 0) { lprintf(__FILE__, __LINE__, error_level, "failed: fstat : %s", string_error(errno).c_str()); return 0; } return st.st_size; } }; }; #endif <file_sep>#include "crc64.h" namespace rediscpp { namespace crc64 { //crc 64 jones http://www0.cs.ucl.ac.uk/staff/d.jones/crcnote.pdf //redis test e9c6d914c4b8d9ca = crc64("123456789") static uint64_t table[256]; static bool initialized = false; void initialize() { if (!initialized) { for (int i = 0; i < 256; ++i) { uint64_t c = i; for (int j = 0; j < 8; ++j) { if (c & 1) { c = 0x95AC9329AC4BC9B5ULL ^ (c >> 1); } else { c >>= 1; } } table[i] = c; } initialized = true; } } uint64_t update(uint64_t crc, const void * buf_, size_t len) { const uint8_t * buf = reinterpret_cast<const uint8_t*>(buf_); uint64_t c = crc; for (int i = 0; i < len; ++i) { c = table[(c ^ buf[i]) & 0xff] ^ (c >> 8); } return c; } } }; <file_sep>#include "server.h" #include "client.h" #include "type_list.h" namespace rediscpp { ///ブロックしつつ左側から取得 ///@note Available since 2.0.0. bool server_type::api_blpop(client_type * client) { return api_bpop_internal(client, true, false); } ///ブロックしつつ右側から取得 ///@note Available since 2.0.0. bool server_type::api_brpop(client_type * client) { return api_bpop_internal(client, false, false); } ///ブロックしつつ右側から取得し、左に追加 ///@note Available since 2.2.0. bool server_type::api_brpoplpush(client_type * client) { return api_bpop_internal(client, false, true); } ///ブロックしつつ取得し、対象があれば左に追加する ///@note 追加するとき、空かリストでなければ、取得せずにエラーを返す bool server_type::api_bpop_internal(client_type * client, bool left, bool rpoplpush) { auto & keys = client->get_keys(); auto current = client->get_time(); auto db = writable_db(client); bool in_blocking = client->is_blocked(); auto kend = (rpoplpush ? keys.begin() : keys.end()); if (rpoplpush) { ++kend; } for (auto it = keys.begin(), end = kend; it != end; ++it) { auto & key = **it; if (in_blocking) { //ブロック中はリスト以外が設定されても待つ std::shared_ptr<type_interface> value = db->get(key, current); if (!value || !std::dynamic_pointer_cast<type_list>(value)) { continue; } } std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { continue; } if (!list->empty()) { bool created = false; try { if (rpoplpush) { auto &destkey = **keys.rbegin(); std::shared_ptr<type_list> dest = db->get_list(destkey, current); const std::string & result = list->rpop(); if (!dest) { created = true; dest.reset(new type_list(current)); dest->lpush(result); db->replace(destkey, dest); } else { dest->lpush(result); dest->update(current); } client->response_bulk(result); } else { const std::string & result = left ? list->lpop() : list->rpop(); client->response_bulk(result); } if (list->empty()) { db->erase(key, current); } } catch (std::exception e) {//rpoplpushで挿入先がリストで無い場合など client->response_error(e.what()); } if (in_blocking) {//ブロック中に付解除 client->end_blocked(); unblocked(client->get()); } //新規追加の場合は通知する if (created) { if (client->in_exec()) { notify_list_pushed(); } else { excecute_blocked_client(); } } return true; } } if (client->in_exec()) {//非ブロック client->response_null(); return true; } if (in_blocking && !client->still_block()) {//タイムアウト client->end_blocked(); client->response_null(); return true; } if (!in_blocking) {//最初のブロックが起きた場合 auto & arguments = client->get_arguments(); int64_t timeout = atoi64(arguments.back()); client->start_blocked(timeout); timer->insert(timeout, 0);//タイマーを追加 //ブロックリストに追加 blocked(client->get()); } throw blocked_exception("blocking"); } ///取得し、対象があれば左に追加する ///@note 追加するとき、空かリストでなければ、取得せずにエラーを返す bool server_type::api_rpoplpush(client_type * client) { auto current = client->get_time(); auto db = writable_db(client); bool in_blocking = client->is_blocked(); auto & key = client->get_argument(1); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list || list->empty()) { client->response_null(); return true; } auto & destkey = client->get_argument(2); std::shared_ptr<type_list> dest = db->get_list(destkey, current); const std::string & result = list->rpop(); bool created = false; if (!dest) { created = true; dest.reset(new type_list(current)); dest->lpush(result); db->replace(destkey, dest); } else { dest->lpush(result); dest->update(current); } if (list->empty()) { db->erase(key, current); } client->response_bulk(result); //新規追加の場合は通知する if (created) { if (client->in_exec()) { notify_list_pushed(); } else { excecute_blocked_client(); } } return true; } ///左側へ追加 ///@note Available since 1.0.0. bool server_type::api_lpush(client_type * client) { return api_lpush_internal(client, true, false); } ///左側へリストがあれば追加 ///@note Available since 2.2.0. bool server_type::api_lpushx(client_type * client) { return api_lpush_internal(client, true, true); } ///右側へ追加 ///@note Available since 1.0.0. bool server_type::api_rpush(client_type * client) { return api_lpush_internal(client, false, false); } ///右側へリストがあれば追加 ///@note Available since 2.2.0. bool server_type::api_rpushx(client_type * client) { return api_lpush_internal(client, false, true); } ///リストへ追加 bool server_type::api_lpush_internal(client_type * client, bool left, bool exist) { auto & key = client->get_argument(1); auto current = client->get_time(); auto & values = client->get_values(); auto db = writable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); bool created = false; if (!list) { if (exist) { client->response_integer0(); return true; } list.reset(new type_list(current)); if (left) { list->lpush(values); } else { list->rpush(values); } db->replace(key, list); created = true; } else { if (left) { list->lpush(values); } else { list->rpush(values); } list->update(current); } client->response_integer(list->size()); //新規追加時の通知 if (created) { if (client->in_exec()) { notify_list_pushed(); } else { excecute_blocked_client(); } } return true; } ///リストの指定の値があれば、その前か後ろへ追加 bool server_type::api_linsert(client_type * client) { auto side = client->get_argument(2); std::transform(side.begin(), side.end(), side.begin(), toupper); auto before = (side == "BEFORE"); if (!before && side != "AFTER") { throw std::runtime_error("ERR syntax error"); } auto & key = client->get_argument(1); auto & pivot = client->get_argument(3); auto & value = client->get_argument(4); auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list || !list->linsert(pivot, value, before)) { client->response_integer(0); return true; } list->update(current); client->response_integer(list->size()); return true; } ///左から取得 ///@note Available since 1.0.0. bool server_type::api_lpop(client_type * client) { return api_lpop_internal(client, true); } ///右から取得 ///@note Available since 1.0.0. bool server_type::api_rpop(client_type * client) { return api_lpop_internal(client, false); } ///リストから取得 bool server_type::api_lpop_internal(client_type * client, bool left) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { client->response_null(); return true; } const std::string & value = left ? list->lpop() : list->rpop(); if (list->empty()) { db->erase(key, current); } else { list->update(current); } client->response_bulk(value); return true; } ///リストの長さ ///@note Available since 1.0.0. bool server_type::api_llen(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { client->response_integer(0); return true; } client->response_integer(list->size()); return true; } ///指定位置の値を取得 ///@note Available since 1.0.0. bool server_type::api_lindex(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { client->response_null(); return true; } int64_t index = atoi64(client->get_argument(2)); if (index < 0) { index += list->size(); } if (index < 0 || list->size() <= index) { client->response_null(); return true; } auto it = list->get_it(index); client->response_bulk(*it); return true; } ///指定位置の範囲を取得 ///@note Available since 1.0.0. bool server_type::api_lrange(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { client->response_null_multi_bulk(); return true; } int64_t start = pos_fix(atoi64(client->get_argument(2)), list->size()); int64_t end = std::min<int64_t>(list->size(), pos_fix(atoi64(client->get_argument(3)), list->size()) + 1); if (end <= start) { client->response_null_multi_bulk(); return true; } size_t count = end - start; auto range = list->get_range(start, end); client->response_start_multi_bulk(count); for (auto it = range.first, end = range.second; it != end; ++it) { client->response_bulk(*it); } return true; } ///リストから指定の値を削除 bool server_type::api_lrem(client_type * client) { auto & key = client->get_argument(1); int64_t count = atoi64(client->get_argument(2)); auto & value = client->get_argument(3); auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { client->response_integer0(); return true; } int64_t removed = list->lrem(count, value); if (list->empty()) { db->erase(key, current); } else { list->update(current); } client->response_integer(removed); return true; } ///リストの有効範囲を指定して残りを削除する bool server_type::api_ltrim(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { client->response_ok(); return true; } int64_t start = pos_fix(atoi64(client->get_argument(2)), list->size()); int64_t end = std::min<int64_t>(list->size(), pos_fix(atoi64(client->get_argument(3)), list->size()) + 1); list->trim(start, end); if (list->empty()) { db->erase(key, current); } else { list->update(current); } client->response_ok(); return true; } ///リストの指定位置の値を変更する bool server_type::api_lset(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto & value = client->get_argument(3); auto db = writable_db(client); std::shared_ptr<type_list> list = db->get_list(key, current); if (!list) { client->response_ok(); return true; } int64_t index = pos_fix(atoi64(client->get_argument(2)), list->size()); if (!list->set(index, value)) { throw std::runtime_error("ERR index out of range"); } list->update(current); client->response_ok(); return true; } }; <file_sep>AC_PREREQ(2.59) AC_INIT([rediscpp], [1.0], [<EMAIL>]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([src/main.cpp]) AC_CONFIG_HEADERS([config.h]) AC_CHECK_LIB(pthread, pthread_create, [LIBS="$LIBS -lpthread"]) # Checks for programs. AC_PROG_CXX AM_PROG_CC_C_O AC_CONFIG_FILES([Makefile src/Makefile]) AC_CONFIG_SUBDIRS([src]) AC_PROG_RANLIB AC_OUTPUT <file_sep>#include "server.h" #include "client.h" #include "log.h" namespace rediscpp { bool client_type::multi() { transaction = true; writing_transaction = false; transaction_arguments.clear(); return true; } bool client_type::exec() { multi_executing = true; transaction = false; return true; } bool client_type::in_exec() const { return multi_executing; } bool client_type::queuing(const std::string & command, const api_info & info) { if (!transaction) { return false; } if (command == "EXEC" || command == "DISCARD") { return false; } //トランザクション中で、書き込みロックが必要かを調べる if (!writing_transaction) { bool writing = info.writing; if (info.parser) { writing = (server.*(info.parser))(this); } writing_transaction = writing; } transaction_arguments.push_back(arguments); return true; } ///トランザクションの開始 ///@note Available since 1.2.0. bool server_type::api_multi(client_type * client) { client->multi(); client->response_ok(); return true; } bool client_type::unqueue() { if (transaction_arguments.empty()) { return false; } transaction_arguments.front().swap(arguments); transaction_arguments.pop_front(); return true; } ///トランザクションの実行 ///@note Available since 1.2.0. bool server_type::api_exec(client_type * client) { //監視していた値が変更されていないか確認する auto & watching = client->get_watching(); auto current = client->get_time(); //全体ロックを行う std::map<int,std::shared_ptr<database_write_locker>> dbs; for (int i = 0; i < databases.size(); ++i) { dbs[i].reset(new database_write_locker(writable_db(i, client, !client->writing_transaction))); } for (auto it = watching.begin(), end = watching.end(); it != end; ++it) { auto & watch = *it; auto key = std::get<0>(watch); auto index = std::get<1>(watch); auto & db = *dbs[index]; auto value = db->get(key, current); if (!value) { client->response_null_multi_bulk(); client->discard(); return true; } auto watching_time = std::get<2>(watch); if (watching_time < value->get_last_modified_time()) { client->response_null_multi_bulk(); client->discard(); return true; } } auto count = client->get_transaction_size(); client->exec(); if (count) { client->response_start_multi_bulk(count); for (auto i = 0; i < count; ++i) { client->unqueue(); if (!client->execute()) { client->response_error("ERR unknown"); } } } else { client->response_null_multi_bulk(); } client->discard(); return true; } void client_type::discard() { transaction = false; transaction_arguments.clear(); multi_executing = false; unwatch(); } ///トランザクションの中止 ///@note Available since 2.0.0. bool server_type::api_discard(client_type * client) { client->discard(); client->response_ok(); return true; } void client_type::watch(const std::string & key) { watching.insert(std::tuple<std::string,int,timeval_type>(key, db_index, timeval_type())); } ///値の変更の監視 ///@note Available since 2.2.0. bool server_type::api_watch(client_type * client) { auto & arguments = client->get_arguments(); for (int i = 1, n = arguments.size(); i < n; ++i) { client->watch(arguments[i]); } client->response_ok(); return true; } ///値の変更の監視の中止 ///@note Available since 2.2.0. bool server_type::api_unwatch(client_type * client) { client->unwatch(); client->response_ok(); return true; } } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <memory> #include <stdexcept> #include <pthread.h> #include <signal.h> #include <string.h> #include <errno.h> std::string string_error(int error_number) { char buf[1024] = {0}; return std::string(strerror_r(error_number, & buf[0], sizeof(buf))); } class condition_type; class mutex_type { friend class condition_type; pthread_mutex_t mutex; mutex_type(const mutex_type & rhs); public: mutex_type(bool recursive = false) { pthread_mutexattr_t attr_; pthread_mutexattr_t * attr = & attr_; int err = pthread_mutexattr_init(&attr_); if (err) { throw std::runtime_error("pthread_mutexattr_init:" + string_error(err)); } err = pthread_mutexattr_settype(attr, recursive ? PTHREAD_MUTEX_RECURSIVE_NP : PTHREAD_MUTEX_ERRORCHECK_NP); if (err) { throw std::runtime_error("pthread_mutexattr_settype:" + string_error(err)); } err = pthread_mutex_init(&mutex, attr); if (err) { throw std::runtime_error("pthread_mutex_init:" + string_error(err)); } } ~mutex_type() { int err = pthread_mutex_destroy(&mutex); switch (err) { case 0: break; //case EBUSY://mutex は現在ロックされている。 default: //throw std::runtime_error("pthread_mutex_destroy:" + string_error(err)); break; } } void lock() { int err = pthread_mutex_lock(&mutex); switch (err) { case 0: return; //case EINVAL://mutex が適切に初期化されていない。 //case EDEADLK://mutex は既に呼び出しスレッドによりロックされている。 (「エラー検査を行なう」 mutexes のみ) default: throw std::runtime_error("pthread_mutex_lock:" + string_error(err)); } } bool trylock() { int err = pthread_mutex_trylock(&mutex); switch (err) { case 0: return true; case EBUSY://現在ロックされているので mutex を取得できない。 return false; //case EINVAL://mutex が適切に初期化されていない。 //case EDEADLK://mutex は既に呼び出しスレッドによりロックされている。 (「エラー検査を行なう」 mutexes のみ) default: throw std::runtime_error("pthread_mutex_trylock:" + string_error(err)); } } void unlock() { int err = pthread_mutex_unlock(&mutex); switch (err) { case 0: return; //case EINVAL://mutex が適切に初期化されていない。 //case EPERM://呼び出しスレッドは mutex を所有していない。(「エラーを検査する」 mutex のみ) default: throw std::runtime_error("pthread_mutex_unlock:" + string_error(err)); } } }; class mutex_locker { mutex_type & mutex; public: mutex_locker(mutex_type & mutex_, bool nolock = false) : mutex(mutex_) { if (!nolock) { mutex.lock(); } } ~mutex_locker() { mutex.unlock(); } }; class condition_type { pthread_cond_t cond; mutex_type & mutex; condition_type(); condition_type(const condition_type & rhs); public: condition_type(mutex_type & mutex_) : mutex(mutex_) { int err = pthread_cond_init(&cond, NULL); if (err) { throw std::runtime_error("pthread_cond_init:" + string_error(err)); } } ~condition_type() { int err = pthread_cond_destroy(&cond); } ///@note mutexはロック済みで呼ぶこと void wait() { pthread_cond_wait(&cond, &mutex.mutex); } void signal() { pthread_cond_signal(&cond); } void broadcast() { pthread_cond_broadcast(&cond); } }; class thread_type { pthread_t thread; bool joinable; mutex_type mutex; condition_type cond; bool shutdowning; bool created; public: thread_type() : joinable(true) , cond(mutex) , shutdowning(false) , created(false) { } bool create(bool detached = false) { if (created) { return false; } created = true; pthread_attr_t * attr = NULL; pthread_attr_t attr_; if (detached) { pthread_attr_init(&attr_); pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_DETACHED); attr = & attr_; joinable = false; } mutex_locker locker(mutex); int err = pthread_create(&thread, attr, start_routine, this); if (err) { throw std::runtime_error("pthread_create:" + string_error(err)); } cond.wait(); return true; } virtual ~thread_type() { join(); } bool join() { if (!created) { return true; } if (joinable) { int err = pthread_join(thread, NULL); if (err) { switch (err) { case ESRCH://th で指定された ID に対応するスレッドが見つからなかった。 joinable = false; break; case EINVAL://th で指定されたスレッドはすでにデタッチされている。すでに別のスレッドがスレッド th の終了を待っている。 case EDEADLK://自身を待とうとしている default: return false; } } else { joinable = false; } } return true; } void shutdown() { mutex_locker locker(mutex); shutdowning = true; } private: static void * start_routine(void * self) { try { thread_type * my = reinterpret_cast<thread_type*>(self); { mutex_locker locker(my->mutex); my->cond.signal(); } while (true) { { mutex_locker locker(my->mutex); if (my->shutdowning) { break; } } my->run(); } } catch (std::exception e) { } catch (...) { } pthread_exit(NULL); return NULL; } virtual void run() = 0; }; int loop = 1; std::string command; class thread_tester : public thread_type { public: int index_; int count_; thread_tester(int index) : index_(index) , count_(0) { } virtual void run() { char buf[1024]; sprintf(buf, command.c_str(), index_, count_++); system(buf); if (loop <= count_) { shutdown(); } } }; int main(int argc, char *argv[]) { size_t thread = 1; for (int i = 1; i < argc; ++i) { if (*argv[i] == '-') { switch (argv[i][1]) { case 't': ++i; if (i < argc) { thread = atoi(argv[i]); } continue; case 'l': ++i; if (i < argc) { loop = atoi(argv[i]); } continue; } } command += argv[i]; command += " "; } std::vector<std::shared_ptr<thread_tester> > threads(thread); int index = 0; for (auto it = threads.begin(), end = threads.end(); it != end; ++it) { it->reset(new thread_tester(index++)); } for (auto it = threads.begin(), end = threads.end(); it != end; ++it) { auto & thread = *it; thread->create(); } for (auto it = threads.begin(), end = threads.end(); it != end; ++it) { auto & thread = *it; thread->join(); } return 0; } <file_sep>#ifndef INCLUDE_REDIS_CPP_THREAD_H #define INCLUDE_REDIS_CPP_THREAD_H #include "common.h" #include "timeval.h" #include "log.h" #include <pthread.h> #include <signal.h> namespace rediscpp { class condition_type; class mutex_type { friend class condition_type; pthread_mutex_t mutex; mutex_type(const mutex_type & rhs); public: mutex_type(bool recursive = false) { pthread_mutexattr_t attr_; pthread_mutexattr_t * attr = & attr_; int err = pthread_mutexattr_init(&attr_); if (err) { throw std::runtime_error("pthread_mutexattr_init:" + string_error(err)); } err = pthread_mutexattr_settype(attr, recursive ? PTHREAD_MUTEX_RECURSIVE_NP : PTHREAD_MUTEX_ERRORCHECK_NP); if (err) { throw std::runtime_error("pthread_mutexattr_settype:" + string_error(err)); } err = pthread_mutex_init(&mutex, attr); if (err) { throw std::runtime_error("pthread_mutex_init:" + string_error(err)); } } ~mutex_type() { int err = pthread_mutex_destroy(&mutex); switch (err) { case 0: break; //case EBUSY://mutex は現在ロックされている。 default: //throw std::runtime_error("pthread_mutex_destroy:" + string_error(err)); break; } } void lock() { int err = pthread_mutex_lock(&mutex); switch (err) { case 0: return; //case EINVAL://mutex が適切に初期化されていない。 //case EDEADLK://mutex は既に呼び出しスレッドによりロックされている。 (「エラー検査を行なう」 mutexes のみ) default: throw std::runtime_error("pthread_mutex_lock:" + string_error(err)); } } bool trylock() { int err = pthread_mutex_trylock(&mutex); switch (err) { case 0: return true; case EBUSY://現在ロックされているので mutex を取得できない。 return false; //case EINVAL://mutex が適切に初期化されていない。 //case EDEADLK://mutex は既に呼び出しスレッドによりロックされている。 (「エラー検査を行なう」 mutexes のみ) default: throw std::runtime_error("pthread_mutex_trylock:" + string_error(err)); } } void unlock() { int err = pthread_mutex_unlock(&mutex); switch (err) { case 0: return; //case EINVAL://mutex が適切に初期化されていない。 //case EPERM://呼び出しスレッドは mutex を所有していない。(「エラーを検査する」 mutex のみ) default: throw std::runtime_error("pthread_mutex_unlock:" + string_error(err)); } } }; class mutex_locker { mutex_type & mutex; public: mutex_locker(mutex_type & mutex_, bool nolock = false) : mutex(mutex_) { if (!nolock) { mutex.lock(); } } ~mutex_locker() { mutex.unlock(); } }; class condition_type { pthread_cond_t cond; mutex_type & mutex; condition_type(); condition_type(const condition_type & rhs); public: condition_type(mutex_type & mutex_) : mutex(mutex_) { int err = pthread_cond_init(&cond, NULL); if (err) { throw std::runtime_error("pthread_cond_init:" + string_error(err)); } } ~condition_type() { int err = pthread_cond_destroy(&cond); } ///@note mutexはロック済みで呼ぶこと void wait() { pthread_cond_wait(&cond, &mutex.mutex); } ///@note mutexはロック済みで呼ぶこと bool timedwait(int usec) { timeval_type tv; tv += timeval_type(usec / 1000000, usec % 1000000); timespec ts = tv.get_timespec(); int err = pthread_cond_timedwait(&cond, &mutex.mutex, &ts); switch (err) { case 0: return true; //case EINTR://pthread_cond_timedwait がシグナルによって割り込まれた。 //case ETIMEDOUT://条件変数が abstime で指定された時限までに送信されなかった。 default: return false; } } void signal() { pthread_cond_signal(&cond); } void broadcast() { pthread_cond_broadcast(&cond); } }; template<typename T> class sync_queue { mutex_type mutex; condition_type cond; std::queue<T> queue; public: sync_queue() : cond(mutex) { } void push(T value) { mutex_locker locker(mutex); queue.push(value); cond.broadcast(); } bool empty() { mutex_locker locker(mutex); return queue.empty(); } T pop(int usec) { mutex_locker locker(mutex); while (true) { if (queue.empty()) { if (usec < 0) { cond.wait(); continue; } else if (0 < usec) { cond.timedwait(usec); usec = 0; continue; } else { return T(); } } T value = queue.front(); queue.pop(); return value; } } }; enum rwlock_types { write_lock_type, read_lock_type, no_lock_type, }; class rwlock_type { pthread_rwlock_t lock; rwlock_type(const rwlock_type & rhs); public: rwlock_type(bool recursive = false) { int err = pthread_rwlock_init(&lock, NULL); if (err) { throw std::runtime_error("pthread_rwlock_init:" + string_error(err)); } } ~rwlock_type() { int err = pthread_rwlock_destroy(&lock); switch (err) { case 0: break; default: //throw std::runtime_error("pthread_rwlock_destroy:" + string_error(err)); break; } } void rdlock() { int err = pthread_rwlock_rdlock(&lock); switch (err) { case 0: return; default: throw std::runtime_error("pthread_rwlock_rdlock:" + string_error(err)); } } bool tryrdlock() { int err = pthread_rwlock_tryrdlock(&lock); switch (err) { case 0: return true; case EBUSY://書き込みが読み取り / 書き込みロックを保持しているか、読み取り / 書き込みロックで書き込みスレッドがブロックされているため、読み取りのための読み取り / 書き込みロックを獲得できません。 return false; default: throw std::runtime_error("pthread_rwlock_tryrdlock:" + string_error(err)); } } void wrlock() { int err = pthread_rwlock_wrlock(&lock); switch (err) { case 0: return; default: throw std::runtime_error("pthread_rwlock_wrlock:" + string_error(err)); } } bool trywrlock() { int err = pthread_rwlock_trywrlock(&lock); switch (err) { case 0: return true; case EBUSY://読み取りまたは書き込みでロック済みのため、書き込みのための読み取り / 書き込みロックを獲得できません。 return false; default: throw std::runtime_error("pthread_rwlock_trywrlock:" + string_error(err)); } } void unlock() { int err = pthread_rwlock_unlock(&lock); switch (err) { case 0: return; default: throw std::runtime_error("pthread_rwlock_unlock:" + string_error(err)); } } }; class rwlock_locker { rwlock_type & rwlock; rwlock_types type; public: rwlock_locker(rwlock_type & rwlock_, rwlock_types type_) : rwlock(rwlock_) , type(type_) { switch (type) { case write_lock_type: rwlock.wrlock(); break; case read_lock_type: rwlock.rdlock(); break; } } ~rwlock_locker() { switch (type) { case write_lock_type: case read_lock_type: rwlock.unlock(); break; } } }; class thread_type { pthread_t thread; bool joinable; mutex_type mutex; condition_type cond; bool shutdowning; bool created; public: thread_type() : joinable(true) , cond(mutex) , shutdowning(false) , created(false) { } bool create(bool detached = false) { if (created) { return false; } created = true; pthread_attr_t * attr = NULL; pthread_attr_t attr_; if (detached) { pthread_attr_init(&attr_); pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_DETACHED); attr = & attr_; joinable = false; } mutex_locker locker(mutex); int err = pthread_create(&thread, attr, start_routine, this); if (err) { throw std::runtime_error("pthread_create:" + string_error(err)); } cond.wait(); return true; } virtual ~thread_type() { join(); } bool join() { if (!created) { return true; } if (joinable) { int err = pthread_join(thread, NULL); if (err) { switch (err) { case ESRCH://th で指定された ID に対応するスレッドが見つからなかった。 joinable = false; break; case EINVAL://th で指定されたスレッドはすでにデタッチされている。すでに別のスレッドがスレッド th の終了を待っている。 case EDEADLK://自身を待とうとしている default: return false; } } else { joinable = false; } } return true; } void shutdown() { mutex_locker locker(mutex); shutdowning = true; } private: static void * start_routine(void * self) { try { thread_type * my = reinterpret_cast<thread_type*>(self); { mutex_locker locker(my->mutex); my->cond.signal(); } while (true) { { mutex_locker locker(my->mutex); if (my->shutdowning) { break; } } my->run(); } } catch (std::exception e) { } catch (...) { } lprintf(__FILE__, __LINE__, error_level, "thread exit"); pthread_exit(NULL); return NULL; } virtual void run() = 0; }; } #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_LOG_H #define INCLUDE_REDIS_CPP_LOG_H #include "common.h" #include <stdarg.h> namespace rediscpp { enum log_levels { emergency_level, alert_level, critical_level, error_level, warning_level, notice_level, info_level, debug_level, }; void lputs(const char * file, int line, log_levels level, const std::string & msg); void lprintf(const char * file, int line, log_levels level, const char * fmt, ...); void lvprintf(const char * file, int line, log_levels level, const char * fmt, va_list args); }; #endif <file_sep>#include "server.h" #include "client.h" #include "type_string.h" #include "type_hash.h" #include "type_list.h" #include "type_set.h" #include "type_zset.h" namespace rediscpp { ///キーをすべて列挙する ///@note Available since 1.0.0. bool server_type::api_keys(client_type * client) { auto db = readable_db(client); auto & pattern = client->get_argument(1); std::unordered_set<std::string> keys; db->match(keys, pattern); client->response_start_multi_bulk(keys.size()); for (auto it = keys.begin(), end = keys.end(); it != end; ++it) { client->response_bulk(*it); } return true; } ///キーを削除する ///@note Available since 1.0.0. bool server_type::api_del(client_type * client) { int64_t removed = 0; auto db = writable_db(client); auto current = client->get_time(); auto & keys = client->get_keys(); for (auto it = keys.begin(), end = keys.end(); it != end; ++it) { auto & key = **it; if (db->erase(key, current)) { ++removed; } } client->response_integer(removed); return true; } ///キーの存在確認 ///@note Available since 1.0.0. bool server_type::api_exists(client_type * client) { auto db = readable_db(client); auto & keys = client->get_keys(); auto current = client->get_time(); for (auto it = keys.begin(), end = keys.end(); it != end; ++it) { auto & key = **it; if (db->get(key, current)) { client->response_integer1(); } else { client->response_integer0(); } return true; } return false; } ///キーの有効期限設定 ///@note Available since 1.0.0. bool server_type::api_expire(client_type * client) { return api_expire_internal(client, true, true); } ///キーの有効期限設定 ///@note Available since 1.0.0. bool server_type::api_expireat(client_type * client) { return api_expire_internal(client, true, false); } ///キーの有効期限設定 ///@note Available since 2.6.0. bool server_type::api_pexpire(client_type * client) { return api_expire_internal(client, false, true); } ///キーの有効期限設定 ///@note Available since 2.6.0. bool server_type::api_pexpireat(client_type * client) { return api_expire_internal(client, false, false); } bool server_type::api_expire_internal(client_type * client, bool sec, bool ts) { auto current = client->get_time(); timeval_type tv(0,0); int64_t time = atoi64(client->get_argument(2)); if (ts) { tv = client->get_time(); if (sec) { tv.tv_sec += time; } else { tv.add_msec(time); } } else { if (sec) { tv.tv_sec = time; } else {//msec tv.tv_sec = time / 1000; tv.tv_usec = (time % 1000) * 1000; } } auto & key = client->get_argument(1); auto db = writable_db(client); auto value = db->get_with_expire(key, current); if (!value.second) { client->response_integer0(); return true; } value.first->expire(tv); db->regist_expiring_key(tv, key); client->response_integer1(); return true; } ///キーの有効期限消去 ///@note Available since 2.2.0. bool server_type::api_persist(client_type * client) { auto db = writable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get_with_expire(key, current); if (!value.second) { client->response_integer0(); } else { value.first->persist(); client->response_integer1(); } return true; } ///キーの有効期限確認 ///@note Available since 1.0.0. bool server_type::api_ttl(client_type * client) { return api_ttl_internal(client, true); } ///キーの有効期限確認 ///@note Available since 2.6.0. bool server_type::api_pttl(client_type * client) { return api_ttl_internal(client, false); } bool server_type::api_ttl_internal(client_type * client, bool sec) { auto db = readable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get_with_expire(key, current); if (!value.second) { client->response_integer(-2); return true; } if (!value.first->is_expiring()) { client->response_integer(-1); return true; } timeval_type ttl = value.first->ttl(current); uint64_t result = ttl.tv_sec * 1000 + ttl.tv_usec / 1000; if (sec) { result /= 1000; } client->response_integer(result); return true; } ///キーの移動 ///@note Available since 1.0.0. bool server_type::api_move(client_type * client) { int dst_index = atoi64(client->get_argument(2)); if (dst_index == client->get_db_index()) { client->response_integer0(); return 0; } int src_index = client->get_db_index(); std::map<int,std::shared_ptr<database_write_locker>> dbs; auto min_index = std::min(src_index, dst_index); auto max_index = std::max(src_index, dst_index); dbs[min_index].reset(new database_write_locker(writable_db(min_index, client))); dbs[max_index].reset(new database_write_locker(writable_db(max_index, client))); auto & key = client->get_argument(1); auto current = client->get_time(); auto & src_db = *dbs[src_index]; auto & dst_db = *dbs[dst_index]; auto value = src_db->get_with_expire(key, current); if (!value.second) { client->response_integer0(); return true; } if (dst_db->get(key, current)) { client->response_integer0(); return true; } if (!dst_db->insert(key, *value.first, value.second, current)) { client->response_integer0(); return false; } src_db->erase(key, current); client->response_integer1(); return true; } ///ランダムなキーの取得 ///@note Available since 1.0.0. bool server_type::api_randomkey(client_type * client) { auto db = writable_db(client); auto current = client->get_time(); auto value = db->randomkey(current); if (value.empty()) { client->response_null(); } else { client->response_bulk(value); } return true; } ///キー名の変更 ///@note Available since 1.0.0. bool server_type::api_rename(client_type * client) { auto db = writable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get_with_expire(key, current); if (!value.second) { throw std::runtime_error("ERR not exist"); } auto newkey = client->get_argument(2); if (key == newkey) { throw std::runtime_error("ERR same key"); } db->erase(key, current); db->replace(newkey, *value.first, value.second); client->response_ok(); return true; } ///キー名の変更(上書き不可) ///@note Available since 1.0.0. bool server_type::api_renamenx(client_type * client) { auto db = writable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get_with_expire(key, current); if (!value.second) { throw std::runtime_error("ERR not exist"); } auto & newkey = client->get_argument(2); if (key == newkey) { throw std::runtime_error("ERR same key"); } auto dst_value = db->get(newkey, current); if (dst_value) { client->response_integer0(); return true; } if (!db->insert(newkey, *value.first, value.second, current)) { throw std::runtime_error("ERR internal error"); } db->erase(key, current); client->response_integer1(); return true; } ///型 ///@note Available since 1.0.0. bool server_type::api_type(client_type * client) { auto db = readable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get(key, current); if (!value) { client->response_status("none"); return true; } static const std::string types[5] = { std::string("string"), std::string("list"), std::string("set"), std::string("zset"), std::string("hash"), }; client->response_status(types[value->get_type()]); return true; } template<typename T1, typename T2> struct compare_first { bool operator()(const std::pair<T1,T2> & lhs, const std::pair<T1,T2> & rhs) { return lhs.first < rhs.first; } }; struct pattern_type { bool constant; bool has_field; std::string prefix; std::string suffix; std::string field; pattern_type() : constant(true) , has_field(false) { } pattern_type(const pattern_type & rhs) : constant(rhs.constant) , has_field(rhs.has_field) , prefix(rhs.prefix) , suffix(rhs.suffix) , field(rhs.field) { } pattern_type(const std::string & pattern) : constant(true) , has_field(false) { auto asterisk = pattern.find('*'); if (asterisk != std::string::npos) { constant = false; prefix = pattern.substr(0, asterisk); suffix = pattern.substr(asterisk + 1); auto arrow = suffix.find("->"); if (arrow != std::string::npos) { has_field = true; field = suffix.substr(arrow + 2); suffix = suffix.substr(0, arrow); } } else { prefix = pattern; } } std::string get_key(const std::string & key) const { return constant ? prefix : prefix + key + suffix; } }; static void sort(database_write_locker & db, std::vector<std::string> & values, bool by, const std::string & by_pattern, bool numeric, timeval_type current) { pattern_type pattern(by_pattern); const bool nosort = by && pattern.constant; if (nosort) { return; } std::vector<std::pair<long double,std::string>> num_list; std::vector<std::pair<std::string,std::string>> alp_list; if (numeric) { num_list.reserve(values.size()); } else { alp_list.reserve(values.size()); } for (auto it = values.begin(), end = values.end(); it != end; ++it) { auto & value = *it; std::string comp_value; if (by) { auto by_key = pattern.get_key(value); auto by_value = db->get(by_key, current); if (!pattern.has_field) { auto by_value_str = std::dynamic_pointer_cast<type_string>(by_value); if (by_value_str) { comp_value = by_value_str->get(); } } else { auto by_value_hash = std::dynamic_pointer_cast<type_hash>(by_value); if (by_value_hash) { auto pair = by_value_hash->hget(pattern.field); if (pair.second) { comp_value = pair.second; } } } } else { comp_value = value; } if (numeric) { bool is_valid; long double num = atold(comp_value, is_valid); if (isnan(num)) { num = 0; } num_list.push_back(std::make_pair(num, value)); } else { alp_list.push_back(std::make_pair(comp_value, value)); } } values.clear(); if (numeric) { std::stable_sort(num_list.begin(), num_list.end(), compare_first<long double,std::string>()); for (auto it = num_list.begin(), end = num_list.end(); it != end; ++it) { values.push_back(it->second); } } else { std::stable_sort(alp_list.begin(), alp_list.end(), compare_first<std::string,std::string>()); for (auto it = alp_list.begin(), end = alp_list.end(); it != end; ++it) { values.push_back(it->second); } } } ///ソート ///@note ソート関数でstoreがあるか調べる bool server_type::api_sort_store(client_type * client) { auto & key = client->get_argument(1); auto & arguments = client->get_arguments(); size_t parsed = 2; bool by = false; const size_t size = arguments.size(); if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "BY") { ++parsed; if (size <= parsed) { throw std::runtime_error("ERR not found BY pattern"); } by = true; ++parsed; } } if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "LIMIT") { parsed += 3; if (size < parsed) { throw std::runtime_error("ERR syntax error, not found limit parameter"); } } } while (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "GET") { parsed += 2; if (size < parsed) { throw std::runtime_error("ERR syntax error, not found get pattern"); } } else { break; } } if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "ASC" || keyword == "DESC") { ++parsed; } } if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "ALPHA") { ++parsed; } } bool store = false; if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "STORE") { parsed += 2; if (size < parsed) { throw std::runtime_error("ERR not found STORE destination"); } store = true; client->wrote = true; } } if (parsed != size) { throw std::runtime_error("ERR syntax error"); } return store; } ///ソート ///@note Available since 1.0.0. bool server_type::api_sort(client_type * client) { auto & key = client->get_argument(1); auto & arguments = client->get_arguments(); size_t parsed = 2; bool by = false; std::string by_pattern; const size_t size = arguments.size(); if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "BY") { ++parsed; if (size <= parsed) { throw std::runtime_error("ERR not found BY pattern"); } by_pattern = arguments[parsed]; by = true; ++parsed; } } bool limit = false; int64_t limit_offset = 0; int64_t limit_count = 0; bool is_valid = false; if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "LIMIT") { limit = true; ++parsed; if (size < parsed + 2) { throw std::runtime_error("ERR syntax error, not found limit parameter"); } limit_offset = atoi64(client->get_argument(parsed), is_valid); if (!is_valid || limit_offset < 0) { throw std::runtime_error("ERR limit offset is not valid integer"); } ++parsed; limit_count = atoi64(client->get_argument(parsed), is_valid); if (!is_valid || limit_count < 0) { throw std::runtime_error("ERR limit count is not valid integer"); } ++parsed; } } std::vector<pattern_type> get_pattern; while (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "GET") { ++parsed; if (size < parsed + 1) { throw std::runtime_error("ERR syntax error, not found get pattern"); } std::string pattern = arguments[parsed]; get_pattern.push_back(pattern_type(pattern)); ++parsed; } else { break; } } bool asc = true; if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "ASC") { ++parsed; } else if (keyword == "DESC") { ++parsed; asc = false; } } bool numeric = true; if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "ALPHA") { ++parsed; numeric = false; } } bool store = false; std::string destination; if (parsed < size) { std::string keyword = arguments[parsed]; std::transform(keyword.begin(), keyword.end(), keyword.begin(), toupper); if (keyword == "STORE") { ++parsed; if (size < parsed + 1) { throw std::runtime_error("ERR not found STORE destination"); } destination = arguments[parsed]; store = true; ++parsed; } } if (parsed != size) { throw std::runtime_error("ERR syntax error"); } auto current = client->get_time(); auto db = writable_db(client, !store); auto value = db->get(key, current); size_t values_size = 0; std::vector<std::string> values; if (value) { std::shared_ptr<type_list> list = std::dynamic_pointer_cast<type_list>(value); std::shared_ptr<type_set> set = std::dynamic_pointer_cast<type_set>(value); std::shared_ptr<type_zset> zset = std::dynamic_pointer_cast<type_zset>(value); if (list) { auto range = list->get_range(); values.reserve(list->size()); values.insert(values.end(), range.first, range.second); } else if (set) { auto range = set->smembers(); values.reserve(set->size()); values.insert(values.end(), range.first, range.second); } else if (zset) { auto range = zset->zrange(); values.reserve(zset->size()); for (auto it = range.first, end = range.second; it != end; ++it) { values.push_back((*it)->member); } } else { throw std::runtime_error("ERR sort only list, set, zset"); } sort(db, values, by, by_pattern, numeric, current); } std::list<bool> nulls; std::list<std::string> list_values; size_t list_count = 0; if (get_pattern.empty()) { get_pattern.push_back(pattern_type("#")); } if (!asc) { std::reverse(values.begin(), values.end()); } if (limit) { if (limit_count) { if (limit_offset + limit_count < values.size()) { values.erase(values.begin() + (limit_offset + limit_count), values.end()); } } if (limit_offset) { if (values.size() <= limit_offset) { values.clear(); } else { values.erase(values.begin(), values.begin() + limit_offset); } } } for (auto it = values.begin(), end = values.end(); it != end; ++it) { auto & value = *it; for (auto it = get_pattern.begin(), end = get_pattern.end(); it != end; ++it) { auto & pattern = *it; auto key = pattern.get_key(value); if (key == "#") { list_values.push_back(value); ++list_count; nulls.push_back(false); continue; } auto val = db->get(key, current); if (!pattern.has_field) { auto strval = std::dynamic_pointer_cast<type_string>(val); if (strval) { list_values.push_back(strval->get()); ++list_count; nulls.push_back(false); continue; } } else { auto hashval = std::dynamic_pointer_cast<type_hash>(val); if (hashval) { auto v = hashval->hget(pattern.field); if (v.second) { list_values.push_back(v.first); ++list_count; nulls.push_back(false); continue; } } } list_values.push_back(std::string()); ++list_count; nulls.push_back(true); } } values.clear(); std::shared_ptr<type_list> result(new type_list()); result->move(std::move(list_values), list_count); if (store) { client->response_integer(result->size()); } else { client->response_start_multi_bulk(result->size()); auto range = result->get_range(); if (nulls.empty()) { for (auto it = range.first; it != range.second; ++it) { client->response_bulk(*it); } } else { auto nit = nulls.begin(); for (auto it = range.first; it != range.second; ++it, ++nit) { client->response_bulk(*it, !*nit); } } } return true; } ///データをダンプ ///@note Available since 2.6.0. bool server_type::api_dump(client_type * client) { auto db = readable_db(client); auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto value = db->get(key, current); if (!value) { client->response_null(); return true; } std::string dst; dst.push_back(value->get_type()); dump(dst, value); dump_suffix(dst); client->response_bulk(dst); return true; } ///データをリストア ///@note Available since 2.6.0. bool server_type::api_restore(client_type * client) { auto & key = *client->get_keys()[0]; auto & src = *client->get_values()[0]; auto time = client->get_argument(2); bool is_valid; int64_t timeval = atoi64(time, is_valid); if (!is_valid || timeval < 0) { throw std::runtime_error("ERR invalid ttl"); } auto current = client->get_time(); expire_info expire(current); std::shared_ptr<type_interface> value = restore(src, current); timeval_type tv(0,0); if (0 < timeval) { tv = current; tv.add_msec(timeval); expire.expire(tv); } auto db = writable_db(client); db->insert(key, expire, value, current); client->response_ok(); return true; } } <file_sep>noinst_PROGRAMS = rediscpp noinst_HEADERS = rediscpp_SOURCES = \ network.cpp \ server.cpp \ client.cpp \ master.cpp \ database.cpp \ log.cpp \ timeval.cpp \ crc64.cpp \ serialize.cpp \ common.cpp \ api_connection.cpp \ api_server.cpp \ api_transactions.cpp \ api_keys.cpp \ api_strings.cpp \ api_lists.cpp \ api_hashes.cpp \ api_sets.cpp \ api_zsets.cpp \ expire_info.cpp \ type_interface.cpp \ type_hash.cpp \ type_list.cpp \ type_set.cpp \ type_string.cpp \ type_zset.cpp \ main.cpp rediscpp_CPPFLAGS = -D_LARGEFILE64_SOURCE -D__STDC_FORMAT_MACROS -std=c++0x <file_sep>#include "server.h" #include "client.h" #include "type_hash.h" namespace rediscpp { ///複数のフィールドを削除 ///@note Available since 2.0.0. bool server_type::api_hdel(client_type * client) { auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto & fields = client->get_fields(); auto db = writable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); if (!hash) { client->response_integer0(); return true; } int64_t removed = hash->hdel(fields); if (hash->empty()) { db->erase(key, current); } else { hash->update(current); } client->response_integer(removed); return true; } ///フィールドの存在確認 ///@note Available since 2.0.0. bool server_type::api_hexists(client_type * client) { auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto & field = *client->get_fields()[0]; auto db = readable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); if (!hash) { client->response_integer0(); return true; } client->response_integer(hash->hexists(field) ? 1 : 0); return true; } ///値の取得 ///@note Available since 2.0.0. bool server_type::api_hget(client_type * client) { auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto & field = *client->get_fields()[0]; auto db = readable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); if (!hash) { client->response_null(); return true; } auto r = hash->hget(field); if (!r.second) { client->response_null(); return true; } client->response_bulk(r.first); return true; } ///複数の値の取得 ///@note Available since 2.0.0. bool server_type::api_hmget(client_type * client) { auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto db = readable_db(client); auto & fields = client->get_fields(); std::shared_ptr<type_hash> hash = db->get_hash(key, current); if (!hash) { client->response_null(); return true; } client->response_start_multi_bulk(fields.size()); for (auto it = fields.begin(), end = fields.end(); it != end; ++it) { auto & field = **it; auto r = hash->hget(field); if (!r.second) { client->response_null(); } else { client->response_bulk(r.first); } } return true; } ///長さの取得 ///@note Available since 2.0.0. bool server_type::api_hlen(client_type * client) { auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); if (!hash) { client->response_integer0(); return true; } client->response_integer(hash->size()); return true; } ///キーと値の全取得 ///@note Available since 2.0.0. bool server_type::api_hgetall(client_type * client) { return api_hgetall_internal(client, true, true); } ///キーの全取得 ///@note Available since 2.0.0. bool server_type::api_hkeys(client_type * client) { return api_hgetall_internal(client, true, false); } ///値の全取得 ///@note Available since 2.0.0. bool server_type::api_hvals(client_type * client) { return api_hgetall_internal(client, false, true); } bool server_type::api_hgetall_internal(client_type * client, bool keys, bool vals) { auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); if (!hash) { client->response_null(); return true; } size_t size = hash->size(); if (!size) { client->response_null(); return true; } auto r = hash->hgetall(); if (keys && vals) { client->response_start_multi_bulk(hash->size() * 2); for (auto it = r.first, end = r.second; it != end; ++it) { client->response_bulk(it->first); client->response_bulk(it->second); } } else { client->response_start_multi_bulk(hash->size()); if (keys) { for (auto it = r.first, end = r.second; it != end; ++it) { client->response_bulk(it->first); } } else { for (auto it = r.first, end = r.second; it != end; ++it) { client->response_bulk(it->second); } } } return true; } ///値の加算 ///@note Available since 2.0.0. bool server_type::api_hincrby(client_type * client) { auto current = client->get_time(); auto & key = *client->get_keys()[0]; auto & field = *client->get_fields()[0]; auto & increment = client->get_argument(3); bool is_valid = true; int64_t intval = atoi64(increment, is_valid); if (!is_valid) { throw std::runtime_error("ERR increment is not valid integer"); } auto db = writable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); std::string oldval = "0"; if (hash) { auto r = hash->hget(field); if (r.second) { oldval = r.first; } } int64_t newval = incrby(oldval, intval); std::string newstr = format("%"PRId64, newval); if (!hash) { hash.reset(new type_hash(current)); hash->hset(field, newstr); db->replace(key, hash); } else { hash->hset(field, newstr); hash->update(current); } client->response_integer(newval); return true; } ///値の加算 ///@note Available since 2.6.0. bool server_type::api_hincrbyfloat(client_type * client) { auto current = client->get_time(); auto & key = *client->get_keys()[0]; auto & field = *client->get_fields()[0]; auto & increment = client->get_argument(3); auto db = writable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); std::string oldval = "0"; if (hash) { auto r = hash->hget(field); if (r.second) { oldval = r.first; } } std::string newstr = incrbyfloat(oldval, increment); if (!hash) { hash.reset(new type_hash(current)); hash->hset(field, newstr); db->replace(key, hash); } else { hash->hset(field, newstr); hash->update(current); } client->response_bulk(newstr); return true; } ///値の設定 ///@note Available since 2.0.0. bool server_type::api_hset(client_type * client) { return api_hset_internal(client, false); } ///存在しなければ値の設定 ///@note Available since 2.0.0. bool server_type::api_hsetnx(client_type * client) { return api_hset_internal(client, true); } bool server_type::api_hset_internal(client_type * client, bool nx) { auto current = client->get_time(); auto & key = *client->get_keys()[0]; auto & field = *client->get_fields()[0]; auto & value = *client->get_values()[0]; auto db = writable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); bool create = true; if (hash) { create = hash->hset(field, value, nx); if (create || !nx) { hash->update(current); } } else { hash.reset(new type_hash(current)); hash->hset(field, value); db->replace(key, hash); } client->response_integer(create ? 1 : 0); return true; } bool server_type::api_hmset(client_type * client) { auto & key = *client->get_keys()[0]; auto current = client->get_time(); auto & fields = client->get_fields(); auto & values = client->get_values(); auto db = writable_db(client); std::shared_ptr<type_hash> hash = db->get_hash(key, current); if (!hash) { hash.reset(new type_hash(current)); db->replace(key, hash); } for (auto it = fields.begin(), end = fields.end(), vit = values.begin(), vend = values.end(); it != end && vit != vend; ++it, ++vit) { auto & field = **it; auto & value = **vit; hash->hset(field, value); } hash->update(current); client->response_ok(); return true; } }; <file_sep>#include "common.h" namespace rediscpp { std::string string_error(int error_number) { char buf[1024] = {0}; return std::string(strerror_r(error_number, & buf[0], sizeof(buf))); } std::string vformat(const char * fmt, va_list args) { char buf[1024]; int ret = vsnprintf(buf, sizeof(buf), fmt, args); if (0 <= ret && static_cast<size_t>( ret ) + 1 < sizeof(buf)) return std::string(buf); std::vector<char> buf2( ret + 16, 0 ); ret = vsnprintf(&buf2[0], buf2.size(), fmt, args); if (0 <= ret && static_cast<size_t>( ret ) + 1 < buf2.size()) return std::string(&buf2[0]); return std::string(); } std::string format(const char * fmt, ...) { va_list args; va_start( args, fmt ); std::string ret = vformat( fmt, args ); va_end( args ); return ret; } int64_t atoi64(const std::string & str) { return strtoll(str.c_str(), NULL, 10); } int64_t atoi64(const std::string & str, bool & is_valid) { if (str.empty()) { is_valid = false; return 0; } char * endptr = NULL; errno = 0; int64_t result = strtoll(str.c_str(), &endptr, 10); const char * end = str.c_str() + str.size(); is_valid = (endptr == end && errno == 0); return result; } uint16_t atou16(const std::string & str, bool & is_valid) { if (str.empty()) { is_valid = false; return 0; } char * endptr = NULL; errno = 0; int32_t result = strtoul(str.c_str(), &endptr, 10); const char * end = str.c_str() + str.size(); is_valid = (endptr == end && errno == 0 && 0 <= result && result <= 0xFFFF); return static_cast<uint16_t>(result); } long double atold(const std::string & str, bool & is_valid) { if (str.empty()) { is_valid = false; return 0; } char * endptr = NULL; errno = 0; long double result = strtold(str.c_str(), &endptr); const char * end = str.c_str() + str.size(); is_valid = (endptr == end && errno == 0); return result; } double atod(const std::string & str, bool & is_valid) { if (str.empty()) { is_valid = false; return 0; } char * endptr = NULL; errno = 0; long double result = strtod(str.c_str(), &endptr); const char * end = str.c_str() + str.size(); is_valid = (endptr == end && errno == 0); return result; } static bool pattern_match(const char * pbegin, const char * pend, const char * tbegin, const char * tend, bool nocase) { while (pbegin < pend) { switch (*pbegin) { case '*': for (const char * t = tend; tbegin <= t; --t) { if (pattern_match(pbegin + 1, pend, t, tend, nocase)) { return true; } } return false; case '?': if (tbegin == tend) { return false; } ++tbegin; ++pbegin; break; case '[': { if (tbegin == tend) { return false; } char c = *tbegin; if (nocase) { c = toupper(c); } ++pbegin; bool bend = false; bool match = false; bool should_not_match = false; if (pbegin < pend && *pbegin == '^') { should_not_match = true; ++pbegin; } const char * bfirst = pbegin; for (; pbegin < pend && !bend; ++pbegin) { switch (*pbegin) { case ']': bend = true; break; case '\\': ++pbegin; if (pbegin == pend) { return false; } if ((nocase ? toupper(*pbegin) : *pbegin) == c) { match = true; } break; case '-': if (bfirst == pbegin || pbegin + 1 == pend || pbegin[1] == ']') { if ('-' == c) { match = true; } } else { char start = pbegin[-1]; char end = pbegin[1]; if (nocase) { start = toupper(start); end = toupper(end); } if (end < start) std::swap(start, end); if (start <= c && c <= end) { match = true; } } break; default: if ((nocase ? toupper(*pbegin) : *pbegin) == c) { match = true; } break; } } if (should_not_match) { match = ! match; } if (!match) { return false; } ++tbegin; } break; case '\\': if (pbegin + 1 < pend) { ++pbegin; } default: if (tbegin == tend) { return false; } if (nocase) { if (toupper(*pbegin) != toupper(*tbegin)) { return false; } } else { if (*pbegin != *tbegin) { return false; } } ++tbegin; ++pbegin; break; } } return tbegin == tend; } bool pattern_match(const std::string & pattern, const std::string & target, bool nocase) { return pattern_match(pattern.c_str(), pattern.c_str() + pattern.size(), target.c_str(), target.c_str() + target.size(), nocase); } } <file_sep>#include "server.h" #include "client.h" #include "type_string.h" namespace rediscpp { ///取得 ///@note Available since 1.0.0. bool server_type::api_get(client_type * client) { auto db = readable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get_string(key, current); if (!value) { client->response_null(); return true; } client->response_bulk(value->get()); return true; } ///設定 ///@param[in] key キー名 ///@param[in] value 値 ///@param[in] [EX seconds] 存在したら、期限を設定 ///@param[in] [PX milliseconds] 存在したら、ミリ秒で期限を設定 ///@param[in] [NX] 存在しない場合にのみ設定する ///@param[in] [XX] 存在する場合にのみ設定する ///@note Available since 1.0.0. bool server_type::api_set(client_type * client) { int64_t expire = -1;//in millisec bool nx = false; bool xx = false; auto & arguments = client->get_arguments(); for (int i = 3, size = arguments.size(); i < size; ++i) { auto & option = arguments[i]; if (option == "EX") { ++i; if (i == size) { throw std::runtime_error("ERR syntax error"); } auto & arg = arguments[i]; expire = atoi64(arg) * 1000; } else if (option == "PX") { ++i; if (i == size) { throw std::runtime_error("ERR syntax error"); } auto & arg = arguments[i]; expire = atoi64(arg); } else if (option == "NX") { if (xx) { throw std::runtime_error("ERR syntax error"); } nx = true; } else if (option == "XX") { if (nx) { throw std::runtime_error("ERR syntax error"); } xx = true; } else { throw std::runtime_error("ERR syntax error"); } } return api_set_internal(client, nx, xx, expire); } ///設定 ///@param[in] key キー名 ///@param[in] value 値 ///@note Available since 1.0.0. bool server_type::api_setnx(client_type * client) { return api_set_internal(client, true, false, -1); } ///設定 ///@param[in] key キー名 ///@param[in] seconds 期限を設定 ///@param[in] value 値 ///@note Available since 2.0.0. bool server_type::api_setex(client_type * client) { int64_t expire = atoi64(client->get_argument(2)) * 1000; return api_set_internal(client, false, false, expire); } ///設定 ///@param[in] key キー名 ///@param[in] value 値 ///@note Available since 1.0.0. bool server_type::api_psetex(client_type * client) { int64_t expire = atoi64(client->get_argument(2)); return api_set_internal(client, false, false, expire); } bool server_type::api_set_internal(client_type * client, bool nx, bool xx, int64_t expire) { auto db = writable_db(client); auto current = client->get_time(); auto & key = *client->get_keys()[0]; auto & value = *client->get_values()[0]; if (nx) {//存在を確認する if (db->get(key, current)) { client->response_null(); return true; } } else if (xx) { if (!db->get(key, current)) { client->response_null(); return true; } } std::shared_ptr<type_string> str(new type_string(current)); str->set(value); expire_info info; if (0 <= expire) { timeval_type tv = current; tv.add_msec(expire); info.expire(tv); db->regist_expiring_key(tv, key); } db->replace(key, info, str); client->response_ok(); return true; } ///値の長さを取得 ///@param[in] key キー名 ///@note Available since 2.2.0. bool server_type::api_strlen(client_type * client) { auto & key = client->get_argument(1); auto db = readable_db(client); auto current = client->get_time(); auto value = db->get_string(key, current); if (!value) { client->response_integer0(); return true; } client->response_integer(value->get().size()); return true; } ///追加 ///@param[in] key キー名 ///@note Available since 2.0.0. bool server_type::api_append(client_type * client) { auto & key = client->get_argument(1); auto & value = client->get_argument(2); auto db = writable_db(client); auto current = client->get_time(); auto now = db->get_string(key, current); if (now) { int64_t len = now->append(value); now->update(current); client->response_integer(len); } else { std::shared_ptr<type_string> str(new type_string(current)); str->set(value); db->replace(key, str); client->response_integer(value.size()); } return true; } ///範囲内の値を取得する ///@param[in] key キー名 ///@param[in] start 文字の開始位置 ///@param[in] end 文字の終了位置 ///@note オフセット位置がマイナスは終端からの位置となる ///@note 範囲外は文字の範囲にクリップされる ///@note 範囲は[start,end]となる ///@note Available since 2.4.0. bool server_type::api_getrange(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); auto value = db->get_string(key, current); if (!value) { client->response_null(); return true; } const auto & string = value->get(); int64_t start = pos_fix(atoi64(client->get_argument(2)), string.size()); int64_t end = std::min<int64_t>(string.size(), pos_fix(atoi64(client->get_argument(3)), string.size()) + 1); if (end <= start) { client->response_null(); } else { client->response_bulk(string.substr(start, end - start)); } return true; } ///値の一部を設定する ///@param[in] key キー名 ///@param[in] offset オフセット位置 ///@param[in] value 設定する値 ///@note オフセット位置がマイナスはエラーとなる ///@note オフセットが現在の文字長を超える場合は、NULLが挿入される ///@note Available since 2.2.0. bool server_type::api_setrange(client_type * client) { auto & key = client->get_argument(1); int64_t offset = atoi64(client->get_argument(2)); if (offset < 0) { throw std::runtime_error("ERR syntax error"); } auto & newstr = client->get_argument(3); auto current = client->get_time(); auto db = writable_db(client); auto value = db->get_string(key, current); bool create = (!value); if (create) { value.reset(new type_string(current)); } int64_t len = value->setrange(offset, newstr); if (create) { db->replace(key, value); } else { value->update(current); } client->response_integer(len); return true; } ///値を設定し、以前の値を取得する ///@param[in] key キー名 ///@param[in] value 設定する値 ///@note Available since 1.0.0. bool server_type::api_getset(client_type * client) { auto & key = client->get_argument(1); auto & newstr = client->get_argument(2); auto current = client->get_time(); auto db = writable_db(client); auto value = db->get_string(key, current); bool create = (!value); if (create) { value.reset(new type_string(current)); value->set(newstr); db->replace(key, value); client->response_null(); } else { client->response_bulk(value->ref()); value->set(newstr); value->update(current); } return true; } ///複数の値を取得する ///@param[in] key キー名 ///@note 型が違ってもnullを返す ///@note Available since 1.0.0. bool server_type::api_mget(client_type * client) { auto db = readable_db(client); auto & keys = client->get_keys(); auto current = client->get_time(); client->response_start_multi_bulk(keys.size()); for (auto it = keys.begin(), end = keys.end(); it != end; ++it) { auto & key = **it; auto value = std::dynamic_pointer_cast<type_string>(db->get(key, current)); if (!value) { client->response_null(); } else { client->response_bulk(value->get()); } } } ///複数の値を設定する ///@param[in] key キー名 ///@param[in] value 値 ///@note Available since 1.0.1. bool server_type::api_mset(client_type * client) { auto db = writable_db(client); auto & keys = client->get_keys(); auto & values = client->get_values(); auto current = client->get_time(); for (auto kit = keys.begin(), kend = keys.end(), vit = values.begin(), vend = values.end(); kit != kend && vit != vend; ++kit, ++vit) { auto & key = **kit; auto & value = **vit; std::shared_ptr<type_string> str(new type_string(current)); str->set(value); db->replace(key, str); } client->response_ok(); } ///複数の値がすべて存在しない場合に設定する ///@param[in] key キー名 ///@param[in] value 値 ///@note 他の型の値があると設定しない ///@note Available since 1.0.1. bool server_type::api_msetnx(client_type * client) { auto db = writable_db(client); auto & keys = client->get_keys(); auto & values = client->get_values(); auto current = client->get_time(); for (auto it = keys.begin(), end = keys.end(); it != end; ++it) { auto & key = **it; if (db->get(key, current)) { client->response_integer0(); return true; } } for (auto kit = keys.begin(), kend = keys.end(), vit = values.begin(), vend = values.end(); kit != kend && vit != vend; ++kit, ++vit) { auto & key = **kit; auto & value = **vit; std::shared_ptr<type_string> str(new type_string(current)); str->set(value); db->replace(key, str); } client->response_integer1(); return true; } ///1減らす ///@param[in] key キー名 ///@param[in] value 値 ///@return 演算結果 ///@note 文字列型でないか、int64_tの範囲内でないか、演算結果がオーバーフローする場合にはエラーを返す ///@note Available since 1.0.0. bool server_type::api_decr(client_type * client) { return api_incrdecr_internal(client, -1); } ///1増やす ///@param[in] key キー名 ///@param[in] value 値 ///@return 演算結果 ///@note 文字列型でないか、int64_tの範囲内でないか、演算結果がオーバーフローする場合にはエラーを返す ///@note Available since 1.0.0. bool server_type::api_incr(client_type * client) { return api_incrdecr_internal(client, 1); } ///指定量減らす ///@param[in] key キー名 ///@param[in] value 値 ///@param[in] decrement 減らす量 ///@return 演算結果 ///@note 文字列型でないか、int64_tの範囲内でないか、演算結果がオーバーフローする場合にはエラーを返す ///@note 最小値を減らそうとすると、オーバーフローするのでエラーとする ///@note Available since 1.0.0. bool server_type::api_decrby(client_type * client) { auto & count = client->get_argument(2); bool is_valid = true; int64_t intval = atoi64(count, is_valid); if (!is_valid) { throw std::runtime_error("ERR decrement is not valid integer"); } if (intval == std::numeric_limits<int64_t>::min()) { throw std::runtime_error("ERR decrement is out of range"); } return api_incrdecr_internal(client, -intval); } ///指定量増やす ///@param[in] key キー名 ///@param[in] value 値 ///@param[in] increment 増やす量 ///@return 演算結果 ///@note 文字列型でないか、int64_tの範囲内でないか、演算結果がオーバーフローする場合にはエラーを返す ///@note Available since 1.0.0. bool server_type::api_incrby(client_type * client) { auto & count = client->get_argument(2); bool is_valid = true; int64_t intval = atoi64(count, is_valid); if (!is_valid) { throw std::runtime_error("ERR increment is not valid integer"); } return api_incrdecr_internal(client, intval); } int64_t server_type::incrby(const std::string & value, int64_t count) { bool is_valid; int64_t newval = count; int64_t oldval = atoi64(value, is_valid); if (!is_valid) { throw std::runtime_error("ERR not valid integer"); } if (count < 0) { if (oldval < oldval + count) { throw std::runtime_error("ERR underflow"); } } else if (0 < count) { if (oldval + count < oldval) { throw std::runtime_error("ERR overflow"); } } return newval + oldval; } std::string server_type::incrbyfloat(const std::string & value, const std::string & increment) { bool is_valid; long double count = atold(increment, is_valid); if (!is_valid) { throw std::runtime_error("ERR increment is not valid float"); } long double newval = count; long double oldval = atold(value, is_valid); if (!is_valid) { throw std::runtime_error("ERR not valid float"); } newval = count + oldval; if (isnanl(newval) || isinfl(newval)) { throw std::runtime_error("ERR result is not finite"); } return format("%Lg", newval); } ///加減算を実行する bool server_type::api_incrdecr_internal(client_type * client, int64_t count) { auto db = writable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get_string(key, current); bool created = false; if (!value) { value.reset(new type_string(current)); value->set("0"); created = true; } int64_t newval = value->incrby(count); if (!created) { value->update(current); } else { db->replace(key, value); } client->response_integer(newval); return true; } ///浮動小数点演算で加算する ///@param[in] key キー名 ///@param[in] value 値 ///@param[in] increment 増やす量 ///@return 演算結果 ///@note 文字列型でないか、long doubleの範囲内でないか、演算結果が非有限・非数になる場合にはエラーを返す ///@note Available since 1.0.0. bool server_type::api_incrbyfloat(client_type * client) { auto db = writable_db(client); auto & key = client->get_argument(1); auto current = client->get_time(); auto value = db->get_string(key, current); auto & increment = client->get_argument(2); std::string newstr = incrbyfloat(value ? value->ref() : "0", increment); std::shared_ptr<type_string> str(new type_string(current)); str->set(newstr); db->replace(key, str); client->response_bulk(newstr); return true; } ///範囲内のビット数を計算する ///@param[in] key キー名 ///@param[in] start 開始位置(省略可能) ///@param[in] end 終了位置(省略可能) ///@note Available since 2.6.0. bool server_type::api_bitcount(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); auto value = db->get_string(key, current); if (!value) { client->response_integer0(); return true; } const auto & string = value->get(); auto & arguments = client->get_arguments(); int64_t start = pos_fix(arguments.size() < 3 ? 0 : atoi64(client->get_argument(2)), string.size()); int64_t end = std::min<int64_t>(string.size(), pos_fix(arguments.size() < 4 ? -1 : atoi64(client->get_argument(3)), string.size()) + 1); if (end <= start) { client->response_integer0(); } else { int64_t count = 0; for (auto it = string.begin() + start, send = string.begin() + end; it != send; ++it) { count += bits_table[static_cast<uint8_t>(*it)]; } client->response_integer(count); } return true; } ///ビット演算を行って、指定のキーに出力する ///@param[in] operation 演算 ///@param[in] destkey 出力先キー名 ///@param[in] key キー名 ///@note 応答は最大の値のサイズ。キーの最大サイズが0の場合には出力先は削除と同じ状態となる。 ///@note Available since 2.6.0. bool server_type::api_bitop(client_type * client) { auto operation = client->get_argument(1); std::transform(operation.begin(), operation.end(), operation.begin(), toupper); if (operation != "AND" && operation != "OR" && operation != "XOR" && operation != "NOT") { throw std::runtime_error("ERR operation is invalid"); } auto & destkey = client->get_argument(2); auto & keys = client->get_keys(); if (operation == "NOT" && keys.size() != 2) { throw std::runtime_error("ERR not operation require single key"); } auto current = client->get_time(); auto db = writable_db(client); std::vector<const std::string*> srcvalues; srcvalues.reserve(keys.size() - 1); size_t min_size = std::numeric_limits<size_t>::max(); size_t max_size = 0; for (auto it = keys.begin() + 1, end = keys.end(); it != end; ++it) { auto & key = **it; auto srcvalue = db->get_string(key, current); if (srcvalue) { srcvalues.push_back(&srcvalue->ref()); size_t size = srcvalue->ref().size(); min_size = std::min(min_size, size); max_size = std::max(max_size, size); } else { min_size = 0; } } std::string deststrval(max_size, '\0'); if (operation == "NOT") { if (!srcvalues.empty()) { auto & src = **srcvalues.begin(); auto dit = deststrval.begin(); for (auto it = src.begin(), end = src.end(); it != end; ++it, ++dit) { *dit = ~ *it; } } } else { if (!srcvalues.empty()) { if (operation == "AND") { auto sit = srcvalues.begin(); std::copy((**sit).begin(), (**sit).begin() + min_size, deststrval.begin()); ++sit; for (auto send = srcvalues.end(); sit != send; ++sit) { auto & src = **sit; auto dit = deststrval.begin(); for (auto it = src.begin(), end = src.begin() + min_size; it != end; ++it, ++dit) { *dit &= *it; } } } else if (operation == "OR") { auto sit = srcvalues.begin(); std::copy((**sit).begin(), (**sit).end(), deststrval.begin()); ++sit; for (auto send = srcvalues.end(); sit != send; ++sit) { auto & src = **sit; auto dit = deststrval.begin(); for (auto it = src.begin(), end = src.end(); it != end; ++it, ++dit) { *dit |= *it; } } } else if (operation == "XOR") { auto sit = srcvalues.begin(); std::copy((**sit).begin(), (**sit).end(), deststrval.begin()); ++sit; for (auto send = srcvalues.end(); sit != send; ++sit) { auto & src = **sit; auto dit = deststrval.begin(); for (auto it = src.begin(), end = src.end(); it != end; ++it, ++dit) { *dit ^= *it; } } } } } if (max_size == 0) { db->erase(destkey, current); } else { std::shared_ptr<type_string> str(new type_string(current)); str->set(deststrval); db->replace(destkey, str); } client->response_integer(max_size); return true; } ///指定位置のビットを取得する ///@param[in] key キー名 ///@param[in] offset 位置 ///@note Available since 2.2.0. bool server_type::api_getbit(client_type * client) { auto & key = client->get_argument(1); int64_t offset = atoi64(client->get_argument(2)); if (offset < 0) { throw std::runtime_error("ERR offset is out of range"); } auto current = client->get_time(); auto db = readable_db(client); auto value = db->get_string(key, current); if (!value) { client->response_integer0(); return true; } const auto & string = value->get(); int64_t offset_byte = offset / 8; if (string.size() <= offset_byte) { client->response_integer0(); return true; } uint8_t target_value = static_cast<uint8_t>(string[offset_byte]); int64_t offset_bit = offset % 8; if (target_value & (0x80 >> offset_bit)) { client->response_integer1(); } else { client->response_integer0(); } return true; } ///指定位置のビットを設定する ///@param[in] key キー名 ///@param[in] offset 位置 ///@note 以前のビットを返す ///@note Available since 2.2.0. bool server_type::api_setbit(client_type * client) { auto & key = client->get_argument(1); int64_t offset = atoi64(client->get_argument(2)); if (offset < 0) { throw std::runtime_error("ERR offset is out of range"); } int64_t set = atoi64(client->get_argument(3)); if (set != 1 && set != 0) { throw std::runtime_error("ERR bit is invalid"); } auto current = client->get_time(); auto db = writable_db(client); auto value = db->get_string(key, current); int64_t offset_byte = offset / 8; int64_t offset_bit = offset % 8; if (!value) { std::string string(offset_byte + 1, '\0'); if (set) { *string.rbegin() = static_cast<char>(0x80 >> offset_bit); } std::shared_ptr<type_string> str(new type_string(current)); str->set(string); db->replace(key, str); client->response_integer0(); return true; } auto & string = value->ref(); if (string.size() <= offset_byte) { string.resize(offset_byte + 1, '\0'); } char target_bit = static_cast<char>(0x80 >> offset_bit); char & target_byte = string[offset_byte]; char old = target_byte & target_bit; if (set) { target_byte |= target_bit; } else { target_byte &= ~target_bit; } value->update(current); if (old) { client->response_integer1(); } else { client->response_integer0(); } return true; } } <file_sep>#include "type_set.h" namespace rediscpp { type_set::type_set() { } type_set::type_set(const timeval_type & current) : type_interface(current) { } type_set::~type_set(){} size_t type_set::sadd(const std::vector<std::string*> & members) { size_t added = 0; for (auto it = members.begin(), end = members.end(); it != end; ++it) { auto & member = **it; if (value.insert(member).second) { ++added; } } return added; } size_t type_set::scard() const { return value.size(); } bool type_set::sismember(const std::string & member) const { return value.find(member) != value.end(); } std::pair<std::set<std::string>::const_iterator,std::set<std::string>::const_iterator> type_set::smembers() const { return std::make_pair(value.begin(), value.end()); } size_t type_set::srem(const std::vector<std::string*> & members) { size_t removed = 0; for (auto it = members.begin(), end = members.end(); it != end; ++it) { auto & member = **it; auto vit = value.find(member); if (vit != value.end()) { value.erase(vit); ++removed; } } return removed; } bool type_set::erase(const std::string & member) { auto vit = value.find(member); if (vit != value.end()) { value.erase(vit); return true; } return false; } bool type_set::insert(const std::string & member) { return value.insert(member).second; } std::string type_set::random_key(const std::string & low, const std::string & high) { if (low.empty() || high.empty() || ! (low < high)) { throw std::runtime_error(format("random_key argument [%s] and [%s]", low.c_str(), high.c_str())); } std::string result = low; size_t len = result.size(); size_t high_len = high.size(); size_t index = 0; size_t min_len = std::min(len, high_len);; for (; index < min_len; ++index) { if (result[index] != high[index]) { break; } } if (index < min_len) { //abcd, abs uint8_t diff = high[index] - result[index]; uint8_t r = rand() % (diff + 1); if (r == 0) { return low; } result[index] += r; result.resize(index + 1); return result; } //abc, abcx uint8_t diff = high[index]; uint8_t r = rand() % (diff + 1); if (r) { result.push_back(static_cast<char>(r)); } return result; } std::set<std::string>::const_iterator type_set::srandmember() const { auto it = value.begin(); std::advance(it, rand() % value.size()); return it; /* if (value.empty()) { return value.end(); } auto front = value.begin(); auto back = value.end(); --back; while (front != back) { std::string middle = random_key(*front, *back); if (middle == *front) { return front; } if (middle == *back) { return back; } auto it = value.lower_bound(middle);//middle = (front,back), it = (front,back] if (it == back) { return rand() & 1 ? front : back; } if (rand() & 1) { front = it; } else { back = it; } } return front; /*/ } ///重複を許してcount個の要素を選択する bool type_set::type_set::srandmember(size_t count, std::vector<std::set<std::string>::const_iterator> & result) const { result.clear(); if (count == 0) { if (value.empty()) { return true; } count = 1; } result.reserve(count); for (size_t i = 0; i < count; ++i) { result.push_back(srandmember()); } return true; } ///重複を許さずにcount個の要素を選択する bool type_set::srandmember_distinct(size_t count, std::vector<std::set<std::string>::const_iterator> & result) const { result.clear(); if (value.size() < count) { return false; } result.reserve(count); auto it = value.begin(); for (size_t i = 0; i < count; ++i, ++it) { result.push_back(it); } for (size_t i = count, n = value.size(); i < n; ++i, ++it) { int pickup = rand() % (i + 1); if (pickup < count) { result[pickup] = it; } } return true; } bool type_set::empty() const { return value.empty(); } size_t type_set::size() const { return value.size(); } void type_set::clear() { value.clear(); } void type_set::sunion(const type_set & rhs) { if (this == &rhs) { return; } value.insert(rhs.value.begin(), rhs.value.end()); } void type_set::sdiff(const type_set & rhs) { if (this == &rhs) { clear(); return; } std::set<std::string> lhs; lhs.swap(value); std::set_difference(lhs.begin(), lhs.end(), rhs.value.begin(), rhs.value.end(), std::inserter(value, value.begin())); } void type_set::sinter(const type_set & rhs) { if (this == &rhs) { return; } std::set<std::string> lhs; lhs.swap(value); std::set_intersection(lhs.begin(), lhs.end(), rhs.value.begin(), rhs.value.end(), std::inserter(value, value.begin())); } }; <file_sep>#ifndef INCLUDE_REDIS_CPP_TYPE_SET_H #define INCLUDE_REDIS_CPP_TYPE_SET_H #include "type_interface.h" namespace rediscpp { class type_set : public type_interface { std::set<std::string> value; public: type_set(); type_set(const timeval_type & current); virtual ~type_set(); virtual type_types get_type() const { return set_type; } virtual void output(std::shared_ptr<file_type> & dst) const; virtual void output(std::string & dst) const; static std::shared_ptr<type_set> input(std::shared_ptr<file_type> & src); static std::shared_ptr<type_set> input(std::pair<std::string::const_iterator,std::string::const_iterator> & src); size_t sadd(const std::vector<std::string*> & members); size_t scard() const; bool sismember(const std::string & member) const; std::pair<std::set<std::string>::const_iterator,std::set<std::string>::const_iterator> smembers() const; size_t srem(const std::vector<std::string*> & members); bool erase(const std::string & member); bool insert(const std::string & member); private: static std::string random_key(const std::string & low, const std::string & high); public: std::set<std::string>::const_iterator srandmember() const; bool srandmember(size_t count, std::vector<std::set<std::string>::const_iterator> & result) const; bool srandmember_distinct(size_t count, std::vector<std::set<std::string>::const_iterator> & result) const; bool empty() const; size_t size() const; void clear(); void sunion(const type_set & rhs); void sdiff(const type_set & rhs); void sinter(const type_set & rhs); }; }; #endif <file_sep>#include "type_list.h" namespace rediscpp { type_list::type_list() : count(0) { } type_list::type_list(const timeval_type & current) : type_interface(current) , count(0) { } type_list::~type_list() { } void type_list::move(std::list<std::string> && value, size_t count_) { value.swap(value); count = count_; } void type_list::lpush(const std::vector<std::string*> & elements) { for (auto it = elements.begin(), end = elements.end(); it != end; ++it) { value.insert(value.begin(), **it); } count += elements.size(); } void type_list::rpush(const std::vector<std::string*> & elements) { for (auto it = elements.begin(), end = elements.end(); it != end; ++it) { value.insert(value.end(), **it); } count += elements.size(); } bool type_list::linsert(const std::string & pivot, const std::string & element, bool before) { auto it = std::find(value.begin(), value.end(), pivot); if (it == value.end()) { return false; } if (!before) { ++it; } value.insert(it, element); ++count; return true; } void type_list::lpush(const std::string & element) { value.push_front(element); ++count; } void type_list::rpush(const std::string & element) { value.push_back(element); ++count; } std::string type_list::lpop() { if (count == 0) { throw std::runtime_error("lpop failed. list is empty"); } std::string result = value.front(); value.pop_front(); --count; return result; } std::string type_list::rpop() { if (count == 0) { throw std::runtime_error("rpop failed. list is empty"); } std::string result = value.back(); value.pop_back(); --count; return result; } size_t type_list::size() const { return count; } bool type_list::empty() const { return count == 0; } std::list<std::string>::const_iterator type_list::get_it(size_t index) const { if (count <= index) { return value.end(); } if (index <= count / 2) { std::list<std::string>::const_iterator it = value.begin(); for (auto i = 0; i < index; ++i) { ++it; } return it; } std::list<std::string>::const_iterator it = value.end(); for (auto i = count; index < i; --i) { --it; } return it; } std::list<std::string>::iterator type_list::get_it_internal(size_t index) { if (count <= index) { return value.end(); } if (index <= count / 2) { std::list<std::string>::iterator it = value.begin(); for (auto i = 0; i < index; ++i) { ++it; } return it; } std::list<std::string>::iterator it = value.end(); for (auto i = count; index < i; --i) { --it; } return it; } bool type_list::set(int64_t index, const std::string & newval) { if (index < 0 || count <= index) return false; auto it = get_it_internal(index); *it = newval; return true; } std::pair<std::list<std::string>::const_iterator,std::list<std::string>::const_iterator> type_list::get_range(size_t start, size_t end) const { start = std::min(count, start); end = std::min(count, end); if (end <= start) { return std::make_pair(value.end(), value.end()); } std::list<std::string>::const_iterator sit = get_it(start); if (count <= end) { return std::make_pair(sit, value.end()); } if (start == end) { return std::make_pair(sit, sit); } std::list<std::string>::const_iterator eit; if (end - start < count - end) { eit = sit; for (size_t i = start; i < end; ++i) { ++eit; } } else { eit = get_it(end); } return std::make_pair(sit, eit); } std::pair<std::list<std::string>::const_iterator,std::list<std::string>::const_iterator> type_list::get_range() const { return std::make_pair(value.begin(), value.end()); } std::pair<std::list<std::string>::iterator,std::list<std::string>::iterator> type_list::get_range_internal(size_t start, size_t end) { start = std::min(count, start); end = std::min(count, end); if (end <= start) { return std::make_pair(value.end(), value.end()); } std::list<std::string>::iterator sit = get_it_internal(start); if (count <= end) { return std::make_pair(sit, value.end()); } if (start == end) { return std::make_pair(sit, sit); } std::list<std::string>::iterator eit; if (end - start < count - end) { eit = sit; for (size_t i = start; i < end; ++i) { ++eit; } } else { eit = get_it_internal(end); } return std::make_pair(sit, eit); } ///@param[in] count 0ならすべてを消す、正ならfrontから指定数を消す、負ならbackから指定数を消す ///@return 削除数 size_t type_list::lrem(int64_t count_, const std::string & target) { size_t removed = 0; if (count_ == 0) { for (auto it = value.begin(); it != value.end();) { if (*it == target) { it = value.erase(it); ++removed; } else { ++it; } } } else if (0 < count_) { for (auto it = value.begin(); it != value.end();) { if (*it == target) { it = value.erase(it); ++removed; if (count_ == removed) { break; } } else { ++it; } } } else { count_ = - count_; if (!value.empty()) { auto it = value.end(); --it; while (true) { if (*it == target) { it = value.erase(it); ++removed; if (count_ == removed) { break; } } if (it == value.begin()) { break; } --it; } } } count -= removed; return removed; } ///[start,end)の範囲になるように前後を削除する void type_list::trim(size_t start, size_t end) { start = std::min(count, start); end = std::min(count, end); if (end <= start) { value.clear(); count = 0; return; } auto range = get_range_internal(start, end); count = end - start; value.erase(value.begin(), range.first); value.erase(range.second, value.end()); } }; <file_sep>#include "expire_info.h" namespace rediscpp { bool expire_info::is_expired(const timeval_type & current) const { return ! expire_time.is_epoc() && expire_time <= current; } void expire_info::expire(const timeval_type & at) { expire_time = at; } void expire_info::persist() { expire_time.epoc(); } bool expire_info::is_expiring() const { return ! expire_time.is_epoc(); } timeval_type expire_info::ttl(const timeval_type & current) const { if (is_expiring()) { if (current < expire_time) { return expire_time - current; } } return timeval_type(0,0); } }; <file_sep>#include "server.h" #include "client.h" namespace rediscpp { bool client_type::require_auth(const std::string & auth) { if (password.empty()) { return false; } if (auth == "AUTH" || auth == "QUIT") { return false; } return true; } bool client_type::auth(const std::string & password_) { if (password.empty()) { return false; } if (password == password_) { password.clear(); return true; } return false; } ///認証 ///@param[in] password ///@note Available since 1.0.0. bool server_type::api_auth(client_type * client) { lputs(__FILE__, __LINE__, debug_level, "AUTH"); if (client->require_auth(std::string())) { if (!client->auth(client->get_argument(1))) { throw std::runtime_error("ERR not match"); } } client->response_ok(); return true; } ///エコー ///@param[in] message ///@note Available since 1.0.0. bool server_type::api_echo(client_type * client) { client->response_bulk(client->get_argument(1)); return true; } ///Ping ///@note Available since 1.0.0. bool server_type::api_ping(client_type * client) { client->response_pong(); return true; } ///終了 ///@note Available since 1.0.0. bool server_type::api_quit(client_type * client) { client->response_ok(); client->close_after_send(); return true; } ///データベース選択 ///@param[in] index ///@note Available since 1.0.0. bool server_type::api_select(client_type * client) { client->select(atoi64(client->get_argument(1))); client->response_status("OK"); return true; } } <file_sep>#include "log.h" #include <stdio.h> #include <time.h> #include <stdlib.h> namespace rediscpp { void lputs(const char * file, int line, log_levels level, const std::string & msg) { static const char * levels[] = { "emergency", "alert", "critical", "error", "warning", "notice", "info", "debug", }; time_t t = time(NULL); static bool tzset_called = false; if (!tzset_called) { tzset(); tzset_called = true; } tm tm; memset(&tm, 0, sizeof(tm)); char current_time_str[128] = ""; if (localtime_r(&t, &tm)) { strftime(current_time_str, sizeof(current_time_str), "%F %T", &tm); } printf("%s %s(%d) [%s] %s\n", current_time_str, file, line, levels[level], msg.c_str()); } void lprintf(const char * file, int line, log_levels level, const char * fmt, ...) { va_list args; va_start( args, fmt ); lvprintf(file, line, level, fmt, args); va_end( args ); } void lvprintf(const char * file, int line, log_levels level, const char * fmt, va_list args) { lputs(file, line, level, vformat( fmt, args )); } } <file_sep>#include "network.h" #include <sys/types.h> #include <netdb.h> #include <unistd.h> #include <sys/socket.h> #include <sys/sendfile.h> #include <fcntl.h> #include <limits.h> #include <algorithm> namespace rediscpp { address_type::sockaddr_any::sockaddr_any() { memset(this, 0, sizeof(*this)); } address_type::address_type() { } bool address_type::set_hostname(const std::string & hostname) { if (hostname.empty()) { return false; } if (*hostname.begin() == '/') { if (hostname.length() < sizeof(addr.un.sun_path)) { addr.un.sun_family = AF_UNIX; strcpy(addr.un.sun_path, hostname.c_str()); return true; } return false; } uint16_t families[2] = { AF_INET, AF_INET6 }; for (int i = 0; i < 2; ++i) { addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = families[i]; hints.ai_socktype = SOCK_STREAM; addrinfo *res = 0; int r = getaddrinfo(hostname.c_str(), 0, &hints, &res); std::shared_ptr<addrinfo> keeper; if (res) keeper.reset(res, freeaddrinfo); if (r || !res) { if (r == EAI_AGAIN || (r == EAI_SYSTEM && errno == EINTR)) { keeper.reset(); res = 0; r = getaddrinfo(hostname.c_str(), 0, &hints, &res); if (res) keeper.reset(res, freeaddrinfo); if (r || !res) return false; } else { return false; } } for (addrinfo * ai = res; ai != NULL; ai = ai->ai_next) { if (ai->ai_family == AF_INET && families[i] == AF_INET) { addr.in.sin_family = AF_INET; addr.in.sin_addr = reinterpret_cast<sockaddr_in*>( ai->ai_addr )->sin_addr; return true; } else if (ai->ai_family == AF_INET6 && families[i] == AF_INET6) { addr.in6.sin6_family = AF_INET6; addr.in6.sin6_addr = reinterpret_cast<sockaddr_in6*>( ai->ai_addr )->sin6_addr; return true; } } } return false; } bool address_type::set_port(uint16_t port) { if (addr.in.sin_family == AF_INET) { addr.in.sin_port = htons(port); return true; } if (addr.in6.sin6_family == AF_INET6) { addr.in6.sin6_port = htons(port); return true; } return false; } uint16_t address_type::get_port() const { if (addr.in.sin_family == AF_INET) { return ntohs(addr.in.sin_port); } if (addr.in6.sin6_family == AF_INET6) { return ntohs(addr.in6.sin6_port); } return 0; } sa_family_t address_type::get_family() const { if (addr.un.sun_family == AF_UNIX) { return AF_UNIX; } if (addr.in.sin_family == AF_INET) { return AF_INET; } if (addr.in6.sin6_family == AF_INET6) { return AF_INET6; } return 0; } void address_type::set_family(sa_family_t family) { if (family == AF_UNIX) { addr.un.sun_family = AF_UNIX; } if (family == AF_INET) { addr.in.sin_family = AF_INET; } if (family == AF_INET6) { addr.in6.sin6_family = AF_INET6; } } const sockaddr * address_type::get_sockaddr() const { return reinterpret_cast<const sockaddr *>(&addr); } sockaddr * address_type::get_sockaddr() { return reinterpret_cast<sockaddr *>(&addr); } size_t address_type::get_sockaddr_size() const { if (addr.un.sun_family == AF_UNIX) { return sizeof(addr.un); } if (addr.in.sin_family == AF_INET) { return sizeof(addr.in); } if (addr.in6.sin6_family == AF_INET6) { return sizeof(addr.in6); } return 0; } std::string address_type::get_info() const { if (addr.un.sun_family == AF_UNIX) { return std::string(addr.un.sun_path); } if (addr.in.sin_family == AF_INET || addr.in6.sin6_family == AF_INET6) { char host[128]; char port[16]; int r = getnameinfo(get_sockaddr(), get_sockaddr_size(), host, sizeof(host), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV); if (r < 0) { lprintf(__FILE__, __LINE__, error_level, "failed getnameinfo : %s", string_error(errno).c_str()); return std::string(); } return format("%s:%s", host, port); } return std::string(); } socket_type::socket_type(int fd_) : pollable_type(fd_) , finished_to_read(false) , finished_to_write(false) , shutdowning(-1) , broken(false) , sending_file_id(-1) , sending_file_size(0) , sent_file_size(0) { } socket_type::~socket_type() { close(); } std::shared_ptr<socket_type> socket_type::create(const address_type & address, bool stream) { int fd = ::socket(address.get_family(), stream ? SOCK_STREAM : SOCK_DGRAM, 0); if (fd < 0) { lputs(__FILE__, __LINE__, error_level, "::socket failed : " + string_error(errno)); return std::shared_ptr<socket_type>(); } std::shared_ptr<socket_type> result = std::shared_ptr<socket_type>(new socket_type(fd)); result->self = result; return result; } bool socket_type::set_nonblocking(bool nonblocking) { int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { lputs(__FILE__, __LINE__, error_level, "::fcntl(F_GETFL) failed : " + string_error(errno)); return false; } if (((flags & O_NONBLOCK) != 0) != nonblocking) { flags ^= O_NONBLOCK; int r = fcntl(fd, F_SETFL, flags); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::fcntl(F_SETFL) failed : " + string_error(errno)); return false; } } return true; } bool socket_type::set_reuse(bool reuse) { int option = reuse ? 1 : 0; int r = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::setsockopt(SO_REUSEADDR) failed : " + string_error(errno)); return false; } return true; } bool socket_type::set_nodelay(bool nodelay) { int option = nodelay ? 1 : 0; int r = setsockopt(fd, SOL_TCP, TCP_NODELAY, &option, sizeof(option)); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::setsockopt(TCP_NODELAY) failed : " + string_error(errno)); return false; } return true; } bool socket_type::bind(std::shared_ptr<address_type> address) { int r = ::bind(fd, address->get_sockaddr(), address->get_sockaddr_size()); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::bind failed : " + string_error(errno)); return false; } local = address; return true; } bool socket_type::connect(std::shared_ptr<address_type> address) { peer = address; int r = 0; int interupt_count = 0; while (true) { r = ::connect(fd, address->get_sockaddr(), address->get_sockaddr_size()); if (r < 0 && errno == EINTR) { if (interupt_count < 3) { ++interupt_count; continue; } } break; } if (r < 0) { switch (errno) { case EINPROGRESS: case EALREADY: //connecting break; default: lputs(__FILE__, __LINE__, error_level, "::connect failed : " + string_error(errno)); return false; } }// else connected if (!set_keepalive(true, 60, 30, 4)) { return false; } return true; } bool socket_type::set_keepalive(bool keepalive, int idle, int interval, int count) { int option = keepalive ? 1 : 0; int r = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&option, sizeof(option)); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::setsockopt(SO_KEEPALIVE) failed : " + string_error(errno)); return false; } if (!keepalive) { return true; } r = setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void*)&idle, sizeof(idle)); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::setsockopt(TCP_KEEPIDLE) failed : " + string_error(errno)); return false; } r = setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void*)&interval, sizeof(interval)); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::setsockopt(TCP_KEEPINTVL) failed : " + string_error(errno)); return false; } r = setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, (void*)&count, sizeof(count)); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::setsockopt(TCP_KEEPCNT) failed : " + string_error(errno)); return false; } return true; } bool socket_type::listen(int queue_count) { int r = ::listen(fd, queue_count); if (r < 0) { lputs(__FILE__, __LINE__, error_level, "::listen failed : " + string_error(errno)); return false; } return true; } std::shared_ptr<socket_type> socket_type::accept() { std::shared_ptr<address_type> addr(new address_type()); addr->set_family(local->get_family()); socklen_t addr_len = static_cast<socklen_t>(addr->get_sockaddr_size()); int interupt_count = 0; int cs = 0; while (true) { cs = ::accept(fd, addr->get_sockaddr(), &addr_len); if (cs < 0 && errno == EINTR) { if (interupt_count < 3) { ++interupt_count; continue; } } break; } if (cs < 0) { return std::shared_ptr<socket_type>(); } std::shared_ptr<socket_type> child(new socket_type(cs)); child->self = child; child->peer = addr; return child; } bool socket_type::send(const void * buf, size_t len) { if (len == 0) { return true; } if (is_sendfile()) { lprintf(__FILE__, __LINE__, error_level, "failed to send on sending file"); return false; } send_buffers.push_back(std::make_pair<std::vector<uint8_t>, size_t>(std::vector<uint8_t>(), 0)); std::vector<uint8_t> & last = send_buffers.back().first; last.assign(reinterpret_cast<const uint8_t*>(buf), reinterpret_cast<const uint8_t*>(buf) + len); return true; } bool socket_type::shutdown(bool reading, bool writing) { if (is_read_shutdowned()) { reading = true; } if (is_write_shutdowned()) { writing = true; } int shut = (reading) ? (writing ? SHUT_RDWR : SHUT_RD) : (writing ? SHUT_WR : -1); if (shut == shutdowning) { return true; } shutdowning = shut; int r = ::shutdown(fd, shutdowning); if (r < 0) { switch (errno) { case EBADF: case ENOTCONN: return true; } lprintf(__FILE__, __LINE__, error_level, "::shutdown failed : %s", string_error(errno).c_str()); return false; } return true; } bool socket_type::send() { if (fd < 0) { return false; } if (!send_buffers.empty()) { #if 1 while (!send_buffers.empty()) { auto & src = send_buffers.front(); auto & buf = src.first; auto & offset = src.second; if (buf.size() <= offset) { send_buffers.pop_front(); continue; } int interupt_count = 0; ssize_t r; while (true) { r = ::send(fd, &buf[offset], static_cast<int>(buf.size() - offset), MSG_NOSIGNAL); if (r < 0 && errno == EINTR) { if (interupt_count < 3) { ++interupt_count; continue; } } break; } if (r < 0) { if (errno == EAGAIN) { return false; } if (errno == EPIPE) { close(); return false; } send_buffers.clear(); broken = true; lprintf(__FILE__, __LINE__, error_level, "send(%d) failed:%s", fd, string_error(errno).c_str()); return false; } if (0 < r) { auto len = buf.size() - offset; if (r < len) { offset += r; break; } else { r -= len; send_buffers.pop_front(); } } } #else std::vector<iovec> send_vectors(std::min<size_t>(IOV_MAX, send_buffers.size())); for (size_t i = 0, n = send_buffers.size(); i < n; ++i) { auto & src = send_buffers[i]; iovec & iv = send_vectors[i]; iv.iov_base = & src.first[0] + src.second; iv.iov_len = src.first.size() - src.second; } ssize_t r; int interupt_count = 0; while (true) { r = ::writev(fd, &send_vectors[0], static_cast<int>(send_vectors.size())); if (r < 0 && errno == EINTR) { if (interupt_count < 3) { ++interupt_count; continue; } } break; } if (r < 0) { if (errno == EAGAIN) { return false; } broken = true; lprintf(__FILE__, __LINE__, error_level, "writev(%d) failed:%s", fd, string_error(errno).c_str()); return false; } while (0 < r && ! send_buffers.empty()) { auto & front_buffer = send_buffers.front(); auto & buf = front_buffer.first; auto & offset = front_buffer.second; auto len = buf.size() - offset; if (r < len) { offset += r; r = 0; break; } else { r -= len; send_buffers.pop_front(); } } #endif } else if (is_sendfile()) { ssize_t r; int interupt_count = 0; size_t count = sending_file_size - sent_file_size; while (true) { r = ::sendfile(fd, sending_file_id, NULL, count); if (r < 0 && errno == EINTR) { if (interupt_count < 3) { ++interupt_count; continue; } } break; } if (r < 0) { if (errno == EAGAIN) { return false; } broken = true; lprintf(__FILE__, __LINE__, error_level, "failed: sendfile(%d):%s", fd, string_error(errno).c_str()); return false; } sent_file_size += r; } if (send_buffers.empty() && !is_sendfile()) { if (finished_to_write) { shutdown(false, true); return true; } } return true; } bool socket_type::recv() { if (fd < 0) { return false; } if (finished_to_read) { return true; } uint8_t buf[1500]; int interupt_count = 0; while (true) { ssize_t r = ::read(fd, buf, sizeof(buf)); if (0 < r) { recv_buffer.insert(recv_buffer.end(), &buf[0], &buf[0] + r); } else if (r == 0) { finished_to_read = true; break; } else { if (errno == EINTR) { if (interupt_count < 3) { ++interupt_count; continue; } } break; } } return true; } void socket_type::close_after_send() { finished_to_write = true; send(); } void socket_type::sendfile(int in_fd, size_t size) { sending_file_id = in_fd; sending_file_size = size; sent_file_size = 0; } uint32_t socket_type::get_events() { if (local) {//server return EPOLLIN; } return EPOLLIN | EPOLLET | EPOLLONESHOT | (should_send() ? EPOLLOUT : 0); } void pollable_type::close() { if (0 <= fd) { auto poll = this->poll.lock(); if (poll) { auto self = this->self.lock(); if (self) { poll->remove(self); } } ::close(fd); fd = -1; } } void pollable_type::mod() { auto poll_ = poll.lock(); if (poll_) { auto self_ = self.lock(); if (self_) { poll_->modify(self_); } } } std::shared_ptr<poll_type> poll_type::create() { std::shared_ptr<poll_type> poll(new poll_type()); poll->self = poll; return poll; } poll_type::poll_type() : fd(-1) , count(0) { fd = ::epoll_create1(EPOLL_CLOEXEC); if (fd < 0) { throw std::runtime_error(std::string("poll_type::epoll_create failed:") + string_error(errno)); } } poll_type::~poll_type() { close(); } void poll_type::close() { if (0 <= fd) { ::close(fd); fd = -1; } } ///@param[in] op EPOLL_CTL_ADD, EPOLL_CTL_MOD, EPOLL_CTL_DEL bool poll_type::operation(std::shared_ptr<pollable_type> pollable, int op) { if (!pollable) { lprintf(__FILE__, __LINE__, error_level, "empty object"); return false; } auto & events = pollable->events; auto newevents = pollable->get_events(); events.events = newevents; int r = epoll_ctl(fd, op, pollable->get_handle(), op == EPOLL_CTL_DEL ? NULL : &events); //lprintf(__FILE__, __LINE__, error_level, "epoll_ctl(%d,%s)", pollable->get_handle(), op == EPOLL_CTL_ADD ? "add" : (op == EPOLL_CTL_MOD ? "mod" : (op == EPOLL_CTL_DEL ? "del" : "unknown"))); if (r < 0) { lprintf(__FILE__, __LINE__, error_level, "epoll_ctl(%d) failed:%s", pollable->get_handle(), string_error(errno).c_str()); return false; } switch (op) { case EPOLL_CTL_ADD: ++count; //lprintf(__FILE__, __LINE__, error_level, "epoll_ctl add %d", count); pollable->set_poll(self.lock()); break; case EPOLL_CTL_DEL: if (0 < count) { --count; } //lprintf(__FILE__, __LINE__, error_level, "epoll_ctl del %d", count); pollable->set_poll(std::shared_ptr<poll_type>()); break; //case EPOLL_CTL_MOD: //lputs(__FILE__, __LINE__, error_level, "epoll_ctl mod"); //break; } return true; } bool poll_type::wait(std::vector<epoll_event> & events, int timeout_milli_sec) { if (count < events.size()) { events.resize(count); } if (events.empty()) { return true; } int r = epoll_wait(fd, &events[0], events.size(), timeout_milli_sec); if (r < 0) { events.clear(); if (errno == EINTR) { //lputs(__FILE__, __LINE__, error_level, "EINTR"); return true; } lprintf(__FILE__, __LINE__, error_level, "epoll_wait failed:%s", string_error(errno).c_str()); return false; } if (r < events.size()) { events.resize(r); } for (auto it = events.begin(), end = events.end(); it != end; ++it) { auto & event = *it; auto pollable = reinterpret_cast<pollable_type*>(it->data.ptr); if (pollable) { auto socket = dynamic_cast<socket_type*>(pollable); if (socket && 0 <= socket->get_handle() && (it->events & EPOLLOUT)) { socket->send(); } } } return true; } } <file_sep>#ifndef INCLUDE_REDIS_CPP_TYPE_LIST_H #define INCLUDE_REDIS_CPP_TYPE_LIST_H #include "type_interface.h" namespace rediscpp { class type_list : public type_interface { std::list<std::string> value; size_t count; public: type_list(); type_list(const timeval_type & current); virtual ~type_list(); void move(std::list<std::string> && value, size_t count_); virtual type_types get_type() const { return list_type; } virtual void output(std::shared_ptr<file_type> & dst) const; virtual void output(std::string & dst) const; static std::shared_ptr<type_list> input(std::shared_ptr<file_type> & src); static std::shared_ptr<type_list> input(std::pair<std::string::const_iterator,std::string::const_iterator> & src); void lpush(const std::vector<std::string*> & elements); void rpush(const std::vector<std::string*> & elements); bool linsert(const std::string & pivot, const std::string & element, bool before); void lpush(const std::string & element); void rpush(const std::string & element); std::string lpop(); std::string rpop(); size_t size() const; bool empty() const; std::list<std::string>::const_iterator get_it(size_t index) const; bool set(int64_t index, const std::string & newval); std::pair<std::list<std::string>::const_iterator,std::list<std::string>::const_iterator> get_range(size_t start, size_t end) const; std::pair<std::list<std::string>::const_iterator,std::list<std::string>::const_iterator> get_range() const; size_t lrem(int64_t count_, const std::string & target); void trim(size_t start, size_t end); private: std::list<std::string>::iterator get_it_internal(size_t index); std::pair<std::list<std::string>::iterator,std::list<std::string>::iterator> get_range_internal(size_t start, size_t end); }; }; #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_DATABASE_H #define INCLUDE_REDIS_CPP_DATABASE_H #include "network.h" #include "thread.h" #include "type_interface.h" #include "expire_info.h" namespace rediscpp { class client_type; class database_type; class database_write_locker { database_type * database; std::shared_ptr<rwlock_locker> locker; public: database_write_locker(database_type * database_, client_type * client, bool rdlock); database_type * get() { return database; } database_type * operator->() { return database; } }; class database_read_locker { database_type * database; std::shared_ptr<rwlock_locker> locker; public: database_read_locker(database_type * database_, client_type * client); const database_type * get() { return database; } const database_type * operator->() { return database; } }; class database_type { friend class database_write_locker; friend class database_read_locker; std::unordered_map<std::string,std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_interface>>> values; mutable mutex_type expire_mutex; mutable std::multimap<timeval_type,std::string> expires; rwlock_type rwlock; database_type(const database_type &); public: typedef std::unordered_map<std::string,std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_interface>>>::const_iterator const_iterator; database_type(); size_t get_dbsize() const; void clear(); std::shared_ptr<type_interface> get(const std::string & key, const timeval_type & current) const; std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_interface>> get_with_expire(const std::string & key, const timeval_type & current) const; std::shared_ptr<type_string> get_string(const std::string & key, const timeval_type & current) const; std::shared_ptr<type_list> get_list(const std::string & key, const timeval_type & current) const; std::shared_ptr<type_hash> get_hash(const std::string & key, const timeval_type & current) const; std::shared_ptr<type_set> get_set(const std::string & key, const timeval_type & current) const; std::shared_ptr<type_zset> get_zset(const std::string & key, const timeval_type & current) const; std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_string>> get_string_with_expire(const std::string & key, const timeval_type & current) const; std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_list>> get_list_with_expire(const std::string & key, const timeval_type & current) const; std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_hash>> get_hash_with_expire(const std::string & key, const timeval_type & current) const; std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_set>> get_set_with_expire(const std::string & key, const timeval_type & current) const; std::pair<std::shared_ptr<expire_info>,std::shared_ptr<type_zset>> get_zset_with_expire(const std::string & key, const timeval_type & current) const; bool erase(const std::string & key, const timeval_type & current); bool insert(const std::string & key, const expire_info & expire, std::shared_ptr<type_interface> value, const timeval_type & current); void replace(const std::string & key, const expire_info & expire, std::shared_ptr<type_interface> value); bool insert(const std::string & key, std::shared_ptr<type_interface> value, const timeval_type & current); void replace(const std::string & key, std::shared_ptr<type_interface> value); std::string randomkey(const timeval_type & current); void regist_expiring_key(timeval_type tv, const std::string & key) const; void flush_expiring_key(const timeval_type & current); void match(std::unordered_set<std::string> & result, const std::string & pattern) const; std::pair<const_iterator,const_iterator> range() const { return std::make_pair(values.begin(), values.end()); } }; }; #endif <file_sep>Redis CPP ========= Redis server that implemented by CPP. Not released yet. No License yet. # Detail * multi thread with epoll * using rwlock for database * NO persistence ## Not support API * CONFIG GET, SET, RESETSTAT * No configuration feature yet * MIGRATE * No another server feature yet * INFO, SLOWLOG * No system feature yet * DEBUG OBJECT, OBJECT * No some structure * DEBUG SEGFAULT * No need * Scripting APIs * No lua * Pub/Sub APIs * No channel message * CLIENT KILL, LIST, GETNAME, SETNAME * Could not get fixed client list by multi thread * BGREWRITEAOF, BGSAVE, LASTSAVE, SAVE * No support persistence # TODO * not implemented api * optimize using rvalue * file refactoring * test code * config file * daemonize * master/slave test * memory usage checking * drop key on low memory <file_sep>#include "type_string.h" namespace rediscpp { type_string::type_string() : int_value(0) , int_type(false) { } type_string::type_string(const timeval_type & current) : type_interface(current) , int_value(0) , int_type(false) { } std::string type_string::get() const { if (int_type && string_value.empty()) { return format("%"PRId64, int_value); } return string_value; } type_string::~type_string() { } std::string & type_string::ref() { to_str(); return string_value; } void type_string::set(const std::string & str) { string_value = str; int_type = false; } int64_t type_string::append(const std::string & str) { to_str(); string_value += str; return string_value.size(); } int64_t type_string::setrange(size_t offset, const std::string & str) { to_str(); size_t new_size = offset + str.size(); if (string_value.size() < new_size) { string_value.resize(new_size); } std::copy(str.begin(), str.end(), string_value.begin() + offset); return string_value.size(); } void type_string::to_int() { if (!int_type) { int_value = atoi64(string_value, int_type); } } void type_string::to_str() { if (int_type) { string_value = format("%"PRId64, int_value); int_type = false; } } int64_t type_string::incrby(int64_t count) { to_int(); if (!int_type) { throw std::runtime_error("ERR not valid integer"); } if (count < 0) { if (int_value < int_value + count) { throw std::runtime_error("ERR underflow"); } } else if (0 < count) { if (int_value + count < int_value) { throw std::runtime_error("ERR overflow"); } } int_value += count; return int_value; } }; <file_sep>#ifndef INCLUDE_REDIS_CPP_TIMEVAL_H #define INCLUDE_REDIS_CPP_TIMEVAL_H #include "common.h" namespace rediscpp { class timeval_type : public timeval { public: timeval_type(); timeval_type(const timeval_type & rhs); timeval_type(time_t sec, suseconds_t usec); timeval_type & operator=(const timeval_type & rhs); void update(); void add_msec(int64_t msec); bool operator==(const timeval_type & rhs) const; bool operator<(const timeval_type & rhs) const; timeval_type & operator+=(const timeval_type & rhs); timeval_type & operator-=(const timeval_type & rhs); bool operator!=(const timeval_type & rhs) const { return !(*this == rhs); } bool operator>=(const timeval_type & rhs) const { return !(*this < rhs); } bool operator>(const timeval_type & rhs) const { return (rhs < *this); } bool operator<=(const timeval_type & rhs) const { return !(rhs < *this); } timeval_type operator+(const timeval_type & rhs) const { return timeval_type(*this) += rhs; } timeval_type operator-(const timeval_type & rhs) const { return timeval_type(*this) -= rhs; } uint64_t get_ms() const { return static_cast<uint64_t>(tv_sec) * 1000ULL + static_cast<uint64_t>(tv_usec / 1000); } timespec get_timespec() const { timespec ts; ts.tv_sec = tv_sec; ts.tv_nsec = tv_usec * 1000; return ts; } bool is_epoc() const { return tv_sec == 0 && tv_usec == 0; } void epoc() { tv_sec = 0; tv_usec = 0; } }; } #endif <file_sep>#include "type_zset.h" #include "log.h" namespace rediscpp { type_zset::value_type::value_type() : score(0) { } type_zset::value_type::value_type(const value_type & rhs) : member(rhs.member) , score(rhs.score) { } type_zset::value_type::value_type(const std::string & member_) : member(member_) , score(0) { } type_zset::value_type::value_type(const std::string & member_, score_type score_) : member(member_) , score(score_) { } bool type_zset::score_eq(score_type lhs, score_type rhs) { if (::finite(lhs) && ::finite(rhs)) { return lhs == rhs; } if (isnan(lhs) || isnan(rhs)) { return false; } if (isinf(lhs) && isinf(rhs)) { return (lhs < 0) == (rhs < 0); } return false; } bool type_zset::score_less(score_type lhs, score_type rhs) { if (::finite(lhs) && ::finite(rhs)) { return lhs < rhs; } if (isnan(lhs) || isnan(rhs)) { return false; } if (isinf(lhs) && isinf(rhs)) { return lhs < 0 && 0 < rhs; } if (isinf(lhs)) { return lhs < 0;//-inf < not -inf } if (isinf(rhs)) { return 0 < rhs;//not inf < +inf } return false; } bool type_zset::score_comparer::operator()(const std::shared_ptr<value_type> & lhs, const std::shared_ptr<value_type> & rhs) const { score_type ls = lhs->score; score_type rs = rhs->score; if (!score_eq(ls, rs)) { return score_less(ls, rs); } return lhs->member < rhs->member; } type_zset::type_zset() { } type_zset::type_zset(const timeval_type & current) : type_interface(current) { } type_zset::~type_zset() { } bool type_zset::erase_sorted(const std::shared_ptr<value_type> & rhs) { auto it = sorted.find(rhs); if (it != sorted.end()) { sorted.erase(it); return true; } lprintf(__FILE__, __LINE__, alert_level, "zset structure broken, %s not found value by score %f", rhs->member.c_str(), rhs->score); return false; } size_t type_zset::zadd(const std::vector<score_type> & scores, const std::vector<std::string*> & members) { if (scores.size() != members.size()) { return 0; } size_t created = 0; auto sit = scores.begin(); for (auto it = members.begin(), end = members.end(); it != end; ++it, ++sit) { auto & member = **it; auto score = *sit; std::shared_ptr<value_type> v(new value_type(member, score)); auto vit = value.find(member); if (vit == value.end()) { ++created; value.insert(std::make_pair(member, v)); sorted.insert(v); } else { auto old = vit->second; erase_sorted(old); vit->second = v; sorted.insert(v); } } return created; } size_t type_zset::zrem(const std::vector<std::string*> & members) { size_t removed = 0; for (auto it = members.begin(), end = members.end(); it != end; ++it) { auto & member = **it; auto vit = value.find(member); if (vit != value.end()) { erase_sorted(vit->second); value.erase(vit); ++removed; } } return removed; } size_t type_zset::zcard() const { return value.size(); } size_t type_zset::size() const { return value.size(); } bool type_zset::empty() const { return value.empty(); } void type_zset::clear() { value.clear(); sorted.clear(); } std::pair<type_zset::const_iterator,type_zset::const_iterator> type_zset::zrangebyscore(score_type minimum, score_type maximum, bool inclusive_minimum, bool inclusive_maximum) const { if (maximum < minimum) { return std::make_pair(sorted.end(), sorted.end()); } std::shared_ptr<value_type> min_value(new value_type(std::string(), minimum)); std::shared_ptr<value_type> max_value(new value_type(std::string(), maximum)); auto first = sorted.lower_bound(min_value); auto last = sorted.lower_bound(max_value); if (!inclusive_minimum) { while (first != sorted.end()) { if (!score_eq((*first)->score, minimum)) { break; } ++first; } } if (inclusive_maximum) { while (last != sorted.end()) { if (score_eq((*last)->score, maximum)) { ++last; } else { break; } } } return std::make_pair(first, last); } std::pair<type_zset::const_iterator,type_zset::const_iterator> type_zset::zrange(size_t start, size_t stop) const { if (stop <= start) { return std::make_pair(sorted.end(), sorted.end()); } return std::make_pair(get_it(start), get_it(stop)); } std::pair<type_zset::const_iterator,type_zset::const_iterator> type_zset::zrange() const { return std::make_pair(sorted.begin(), sorted.end()); } type_zset::const_iterator type_zset::get_it(size_t index) const { if (sorted.size() <= index) { return sorted.end(); } if (index <= sorted.size() / 2) { const_iterator it = sorted.begin(); for (auto i = 0; i < index; ++i) { ++it; } return it; } const_iterator it = sorted.end(); for (auto i = sorted.size(); index < i; --i) { --it; } return it; } size_t type_zset::zcount(score_type minimum, score_type maximum, bool inclusive_minimum, bool inclusive_maximum) const { auto range = zrangebyscore(minimum, maximum, inclusive_minimum, inclusive_maximum); return std::distance(range.first, range.second); } bool type_zset::zrank(const std::string & member, size_t & rank, bool rev) const { auto it = value.find(member); if (it == value.end()) { return false; } auto sit = sorted.find(it->second); rank = std::distance(sorted.begin(), sit); if (rev) { rank = value.size() - 1 - rank; } return true; } bool type_zset::zscore(const std::string & member, score_type & score) const { auto it = value.find(member); if (it == value.end()) { return false; } score = it->second->score; return true; } ///@retval nan 中断 type_zset::score_type type_zset::zincrby(const std::string & member, score_type increment) { if (isnan(increment)) { return increment; } auto it = value.find(member); if (it == value.end()) { std::shared_ptr<value_type> v(new value_type(member, increment)); value.insert(std::make_pair(member, v)); sorted.insert(v); return increment; } score_type after = (it->second->score + increment); if (isnan(after)) { return after; } erase_sorted(it->second); it->second->score = after; sorted.insert(it->second); return after; } ///和集合 void type_zset::zunion(const type_zset & rhs, type_zset::score_type weight, aggregate_types aggregate) { if (this == &rhs) { return; } if (rhs.empty()) { return; } auto lit = value.begin(), lend = value.end(); auto rit = rhs.value.begin(), rend = rhs.value.end(); while (lit != lend && rit != rend) { if (lit->first == rit->first) {//union score_type after = lit->second->score; switch (aggregate) { case aggregate_min: after = std::min(after, rit->second->score * weight); break; case aggregate_max: after = std::max(after, rit->second->score * weight); break; case aggregate_sum: after += rit->second->score * weight; break; } if (isnan(after)) { throw std::runtime_error("ERR nan score result found"); } erase_sorted(lit->second); lit->second->score = after; sorted.insert(lit->second); ++lit; ++rit; } else if (lit->first < rit->first) {//only left ++lit; } else {//only right, insert std::shared_ptr<value_type> v(new value_type(*(rit->second))); score_type after = v->score * weight; if (isnan(after)) { throw std::runtime_error("ERR nan score result found"); } v->score = after; value.insert(lit, std::make_pair(v->member, v)); sorted.insert(v); ++rit; } } while (rit != rend) {//insert std::shared_ptr<value_type> v(new value_type(*(rit->second))); v->score *= weight; if (isnan(v->score)) { throw std::runtime_error("ERR nan score result found"); } value.insert(lit, std::make_pair(v->member, v)); sorted.insert(v); ++rit; } } ///積集合 void type_zset::zinter(const type_zset & rhs, score_type weight, aggregate_types aggregate) { if (this == &rhs) { return; } if (empty()) { return; } if (rhs.empty()) { clear(); return; } auto lit = value.begin(); auto rit = rhs.value.begin(), rend = rhs.value.end(); while (lit != value.end() && rit != rend) { if (lit->first == rit->first) {//inter score_type after = lit->second->score; switch (aggregate) { case aggregate_min: after = std::min(after, rit->second->score * weight); break; case aggregate_max: after = std::max(after, rit->second->score * weight); break; case aggregate_sum: after += rit->second->score * weight; break; } if (isnan(after)) { throw std::runtime_error("ERR nan score result found"); } erase_sorted(lit->second); lit->second->score = after; sorted.insert(lit->second); ++lit; ++rit; } else if (lit->first < rit->first) {//only left, erase erase_sorted(lit->second); auto eit = lit; ++lit; value.erase(eit); } else {//only right ++rit; } } for (auto it = lit; it != value.end(); ++it) {//erase erase_sorted(it->second); } value.erase(lit, value.end()); } }; <file_sep>#include "type_interface.h" namespace rediscpp { type_interface::type_interface() { } type_interface::type_interface(const timeval_type & current) : modified(current) { } type_interface::~type_interface() { } timeval_type type_interface::get_last_modified_time() const { return modified; } void type_interface::update(const timeval_type & current) { modified = current; } }; <file_sep>#include "server.h" #include "crc64.h" int main(int argc, char *argv[]) { rediscpp::crc64::initialize(); int thread = 3; std::string host = "127.0.0.1"; std::string port = "6379"; std::string config; for (int i = 1; i < argc; ++i) { if (*argv[i] == '-') { switch (argv[i][1]) { case 't': ++i; if (i < argc) { thread = atoi(argv[i]); } break; case 'h': ++i; if (i < argc) { host = argv[i]; } break; case 'p': ++i; if (i < argc) { port = argv[i]; } break; } } else { config = argv[i]; } } rediscpp::server_type server; if (!server.start(host, port, thread)) { return -1; } return 0; } <file_sep>#ifndef INCLUDE_REDIS_CPP_CRC64_H #define INCLUDE_REDIS_CPP_CRC64_H #include "common.h" #include <stdarg.h> namespace rediscpp { namespace crc64 { void initialize(); uint64_t update(uint64_t crc, const void * buf, size_t len); }; }; #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_TYPE_ZSET_H #define INCLUDE_REDIS_CPP_TYPE_ZSET_ #include "type_interface.h" namespace rediscpp { class type_zset : public type_interface { public: typedef double score_type; enum aggregate_types { aggregate_min = -1, aggregate_sum, aggregate_max, }; private: struct value_type { std::string member; score_type score; value_type(); value_type(const value_type & rhs); value_type(const std::string & member_); value_type(const std::string & member_, score_type score_); }; static bool score_eq(score_type lhs, score_type rhs); static bool score_less(score_type lhs, score_type rhs); struct score_comparer { bool operator()(const std::shared_ptr<value_type> & lhs, const std::shared_ptr<value_type> & rhs) const; }; std::map<std::string, std::shared_ptr<value_type>> value;//値でユニークな集合 std::set<std::shared_ptr<value_type>, score_comparer> sorted;//スコアで並べた状態 public: typedef std::set<std::shared_ptr<value_type>, score_comparer>::const_iterator const_iterator; type_zset(); type_zset(const timeval_type & current); virtual ~type_zset(); virtual type_types get_type() const { return zset_type; } virtual void output(std::shared_ptr<file_type> & dst) const; virtual void output(std::string & dst) const; static std::shared_ptr<type_zset> input(std::shared_ptr<file_type> & src); static std::shared_ptr<type_zset> input(std::pair<std::string::const_iterator,std::string::const_iterator> & src); size_t zadd(const std::vector<score_type> & scores, const std::vector<std::string*> & members); size_t zrem(const std::vector<std::string*> & members); size_t zcard() const; size_t size() const; bool empty() const; void clear(); std::pair<const_iterator,const_iterator> zrangebyscore(score_type minimum, score_type maximum, bool inclusive_minimum, bool inclusive_maximum) const; std::pair<const_iterator,const_iterator> zrange(size_t start, size_t stop) const; std::pair<const_iterator,const_iterator> zrange() const; size_t zcount(score_type minimum, score_type maximum, bool inclusive_minimum, bool inclusive_maximum) const; bool zrank(const std::string & member, size_t & rank, bool rev) const; bool zscore(const std::string & member, score_type & score) const; score_type zincrby(const std::string & member, score_type increment); void zunion(const type_zset & rhs, type_zset::score_type weight, aggregate_types aggregate); void zinter(const type_zset & rhs, score_type weight, aggregate_types aggregate); private: const_iterator get_it(size_t index) const; bool erase_sorted(const std::shared_ptr<value_type> & rhs); }; }; #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_TYPE_INTERFACE_H #define INCLUDE_REDIS_CPP_TYPE_INTERFACE_H #include "common.h" #include "timeval.h" namespace rediscpp { class type_string; class type_list; class type_hash; class type_set; class type_zset; class file_type; enum type_types { string_type = 0, list_type = 1, set_type = 2, zset_type = 3, hash_type= 4, }; class type_interface { timeval_type modified;///<最後に修正した時間(WATCH用) public: type_interface(); type_interface(const timeval_type & current); virtual ~type_interface(); virtual type_types get_type() const = 0; virtual void output(std::shared_ptr<file_type> & dst) const = 0; virtual void output(std::string & dst) const = 0; timeval_type get_last_modified_time() const; void update(const timeval_type & current); static void write_len(std::shared_ptr<file_type> & dst, uint32_t len); static void write_string(std::shared_ptr<file_type> & dst, const std::string & str); static void write_double(std::shared_ptr<file_type> & dst, double val); static void write_len(std::string & dst, uint32_t len); static void write_string(std::string & dst, const std::string & str); static void write_double(std::string & dst, double val); static uint32_t read_len(std::shared_ptr<file_type> & src); static std::string read_string(std::shared_ptr<file_type> & src); static double read_double(std::shared_ptr<file_type> & src); static uint32_t read_len(std::pair<std::string::const_iterator,std::string::const_iterator> & src); static std::string read_string(std::pair<std::string::const_iterator,std::string::const_iterator> & src); static double read_double(std::pair<std::string::const_iterator,std::string::const_iterator> & src); }; }; #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_SERVER_H #define INCLUDE_REDIS_CPP_SERVER_H #include "network.h" #include "timeval.h" #include "thread.h" #include "type_interface.h" #include "database.h" namespace rediscpp { class server_type; class client_type; class master_type; typedef std::vector<std::string> arguments_type; class blocked_exception : public std::exception { std::string what_; public: blocked_exception() : std::exception(){} blocked_exception(const blocked_exception & rhs){} blocked_exception(const char * const & msg) : what_(msg){} virtual ~blocked_exception() throw() {} virtual const char* what() const throw() { return what_.c_str(); } }; typedef bool (server_type::*api_function_type)(client_type * client); struct api_info { api_function_type function; api_function_type parser; size_t min_argc; size_t max_argc; //c : command, s : string, k : key, v : value, d : db index, t : time, i : integer, f : float std::string arg_types; bool writing; api_info() : function(NULL) , parser(NULL) , min_argc(1) , max_argc(1) , arg_types("c") , writing(false) { } api_info & set(api_function_type function_) { function = function_; return *this; } api_info & argc(size_t argc = 1) { min_argc = max_argc = argc; return *this; } api_info & argc(size_t min_argc_, int max_argc_) { min_argc = min_argc_; max_argc = max_argc_; return *this; } api_info & argc_gte(size_t argc = 1) { min_argc = argc; max_argc = std::numeric_limits<size_t>::max(); return *this; } api_info & type(const std::string & arg_types_) { arg_types = arg_types_; if (min_argc == 1 && max_argc == 1) { min_argc = max_argc = arg_types.size(); } return *this; } api_info & write() { writing = true; return *this; } api_info & set_parser(api_function_type function_) { parser = function_; return *this; } }; class worker_type : public thread_type { server_type & server; public: worker_type(server_type & server_); virtual void run(); }; class job_type { public: enum job_types { add_type, del_type, list_pushed_type,///<listに値が何か追加された場合 slaveof_type, propagate_type,///<monitor, slave向けの情報 }; job_types type; std::shared_ptr<client_type> client; std::string arg1; std::string arg2; arguments_type arguments; job_type(job_types type_, std::shared_ptr<client_type> client_) : type(type_) , client(client_) { } job_type(job_types type_) : type(type_) { } }; class server_type { friend class client_type; friend class master_type; std::shared_ptr<poll_type> poll; std::shared_ptr<event_type> event; std::shared_ptr<timer_type> timer; std::map<socket_type*,std::shared_ptr<client_type>> clients; mutex_type blocked_mutex; std::set<std::shared_ptr<client_type>> blocked_clients; std::shared_ptr<socket_type> listening; uint16_t listening_port; std::map<std::string,std::string> store; std::string password; std::vector<std::shared_ptr<database_type>> databases; std::vector<std::shared_ptr<worker_type>> thread_pool; sync_queue<std::shared_ptr<job_type>> jobs; volatile bool shutdown; std::vector<uint8_t> bits_table; std::shared_ptr<master_type> master; volatile bool slave;///<slaveof後でサーバがslaveの状態 mutex_type slave_mutex; std::set<std::shared_ptr<client_type>> slaves; volatile bool monitoring; std::set<std::shared_ptr<client_type>> monitors; static void client_callback(pollable_type * p, int events); static void server_callback(pollable_type * p, int events); static void event_callback(pollable_type * p, int events); static void timer_callback(pollable_type * p, int events); void on_server(socket_type * s, int events); void on_client(socket_type * s, int events); void on_event(event_type * e, int events); void on_timer(timer_type * e, int events); public: server_type(); ~server_type(); void startup_threads(int threads); void shutdown_threads(); bool start(const std::string & hostname, const std::string & port, int threads); void process(); database_write_locker writable_db(int index, client_type * client, bool rdlock = false); database_read_locker readable_db(int index, client_type * client); database_write_locker writable_db(client_type * client, bool rdlock = false); database_read_locker readable_db(client_type * client); bool save(const std::string & path); bool load(const std::string & path); private: void remove_client(std::shared_ptr<client_type> client, bool now = false); void append_client(std::shared_ptr<client_type> client, bool now = false); void slaveof(const std::string & host, const std::string & port, bool now = false); void propagete(const std::string & info, bool now = false); void propagete(const arguments_type & info, bool now = false); std::map<std::string,api_info> api_map; void build_api_map(); void blocked(std::shared_ptr<client_type> client); void unblocked(std::shared_ptr<client_type> client); void excecute_blocked_client(bool now = false); void notify_list_pushed(); int64_t pos_fix(int64_t pos, int64_t size) { if (pos < 0) { pos = - pos; if (size < pos) { return 0; } else { return size - pos; } } else { if (size < pos) { return size; } return pos; } } int64_t incrby(const std::string & value, int64_t count); std::string incrbyfloat(const std::string & value, const std::string & count); static void dump(std::string & dst, const std::shared_ptr<type_interface> & value); static void dump_suffix(std::string & dst); static std::shared_ptr<type_interface> restore(const std::string & src, const timeval_type & current); //connection api bool api_auth(client_type * client); bool api_ping(client_type * client); bool api_quit(client_type * client); bool api_echo(client_type * client); bool api_select(client_type * client); //server api bool api_dbsize(client_type * client); bool api_flushall(client_type * client); bool api_flushdb(client_type * client); bool api_shutdown(client_type * client); bool api_time(client_type * client); bool api_slaveof(client_type * client); bool api_sync(client_type * client); bool api_replconf(client_type * client); bool api_monitor(client_type * client); //transactions api bool api_multi(client_type * client); bool api_exec(client_type * client); bool api_discard(client_type * client); bool api_watch(client_type * client); bool api_unwatch(client_type * client); //keys api bool api_keys(client_type * client); bool api_del(client_type * client); bool api_exists(client_type * client); bool api_expire(client_type * client); bool api_expireat(client_type * client); bool api_pexpire(client_type * client); bool api_pexpireat(client_type * client); bool api_expire_internal(client_type * client, bool sec, bool ts); bool api_persist(client_type * client); bool api_ttl(client_type * client); bool api_pttl(client_type * client); bool api_ttl_internal(client_type * client, bool sec); bool api_move(client_type * client); bool api_randomkey(client_type * client); bool api_rename(client_type * client); bool api_renamenx(client_type * client); bool api_type(client_type * client); bool api_sort(client_type * client); bool api_sort_store(client_type * client); bool api_dump(client_type * client); bool api_restore(client_type * client); //strings api bool api_get(client_type * client); bool api_set_internal(client_type * client, bool nx, bool xx, int64_t expire); bool api_set(client_type * client); bool api_setnx(client_type * client); bool api_setex(client_type * client); bool api_psetex(client_type * client); bool api_strlen(client_type * client); bool api_append(client_type * client); bool api_getrange(client_type * client); bool api_setrange(client_type * client); bool api_getset(client_type * client); bool api_mget(client_type * client); bool api_mset(client_type * client); bool api_msetnx(client_type * client); bool api_decr(client_type * client); bool api_decrby(client_type * client); bool api_incr(client_type * client); bool api_incrby(client_type * client); bool api_incrdecr_internal(client_type * client, int64_t count); bool api_incrbyfloat(client_type * client); bool api_bitcount(client_type * client); bool api_bitop(client_type * client); bool api_getbit(client_type * client); bool api_setbit(client_type * client); //lists api bool api_blpop(client_type * client); bool api_brpop(client_type * client); bool api_brpoplpush(client_type * client); bool api_lindex(client_type * client); bool api_linsert(client_type * client); bool api_llen(client_type * client); bool api_lpop(client_type * client); bool api_lpush(client_type * client); bool api_lpushx(client_type * client); bool api_lrange(client_type * client); bool api_lrem(client_type * client); bool api_lset(client_type * client); bool api_ltrim(client_type * client); bool api_rpop(client_type * client); bool api_rpoplpush(client_type * client); bool api_rpush(client_type * client); bool api_rpushx(client_type * client); bool api_lpush_internal(client_type * client, bool left, bool exist); bool api_lpop_internal(client_type * client, bool left); bool api_bpop_internal(client_type * client, bool left, bool rpoplpush); //hashes api bool api_hdel(client_type * client); bool api_hexists(client_type * client); bool api_hget(client_type * client); bool api_hgetall(client_type * client); bool api_hincrby(client_type * client); bool api_hincrbyfloat(client_type * client); bool api_hkeys(client_type * client); bool api_hlen(client_type * client); bool api_hmget(client_type * client); bool api_hmset(client_type * client); bool api_hset(client_type * client); bool api_hsetnx(client_type * client); bool api_hvals(client_type * client); bool api_hgetall_internal(client_type * client, bool keys, bool vals); bool api_hset_internal(client_type * client, bool nx); //sets api bool api_sadd(client_type * client); bool api_scard(client_type * client); bool api_sdiff(client_type * client); bool api_sdiffstore(client_type * client); bool api_sinter(client_type * client); bool api_sinterstore(client_type * client); bool api_sismember(client_type * client); bool api_smembers(client_type * client); bool api_smove(client_type * client); bool api_spop(client_type * client); bool api_srandmember(client_type * client); bool api_srem(client_type * client); bool api_sunion(client_type * client); bool api_sunionstore(client_type * client); bool api_soperaion_internal(client_type * client, int type, bool store); //sorted sets api bool api_zadd(client_type * client); bool api_zcard(client_type * client); bool api_zcount(client_type * client); bool api_zincrby(client_type * client); bool api_zinterstore(client_type * client); bool api_zrange(client_type * client); bool api_zrangebyscore(client_type * client); bool api_zrank(client_type * client); bool api_zrem(client_type * client); bool api_zremrangebyrank(client_type * client); bool api_zremrangebyscore(client_type * client); bool api_zrevrange(client_type * client); bool api_zrevrangebyscore(client_type * client); bool api_zrevrank(client_type * client); bool api_zscore(client_type * client); bool api_zunionstore(client_type * client); bool api_zoperaion_internal(client_type * client, int type); bool api_zrange_internal(client_type * client, bool rev); bool api_zrangebyscore_internal(client_type * client, bool rev); bool api_zrank_internal(client_type * client, bool rev); }; } #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_MASTER_H #define INCLUDE_REDIS_CPP_MASTER_H #include "client.h" namespace rediscpp { class master_type : public client_type { friend class server_type; enum status { waiting_pong_state, request_auth_state, waiting_auth_state, request_replconf_state, waiting_replconf_state, request_sync_state, waiting_sync_state, writer_state, shutdown_state, }; status state; size_t sync_file_size; std::string sync_file_path; std::shared_ptr<file_type> sync_file; public: master_type(server_type & server_, std::shared_ptr<socket_type> & client_, const std::string & password_); virtual ~master_type(); virtual void process(); virtual bool is_master() const { return true; } }; }; #endif <file_sep>#ifndef INCLUDE_REDIS_CPP_COMMON_H #define INCLUDE_REDIS_CPP_COMMON_H #ifndef _BSD_SOURCE #define _BSD_SOURCE #endif #include <endian.h> #include <functional> #include <string.h> #include <string> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <queue> #include <unordered_map> #include <unordered_set> #include <tuple> #include <memory> #include <exception> #include <stdexcept> #include <limits> #include <algorithm> #include <iterator> #include <stdarg.h> #include <inttypes.h> #include <math.h> namespace rediscpp { std::string string_error(int error_number); std::string vformat(const char * fmt, va_list args); std::string format(const char * fmt, ...); int64_t atoi64(const std::string & str); int64_t atoi64(const std::string & str, bool & is_valid); uint16_t atou16(const std::string & str, bool & is_valid); long double atold(const std::string & str, bool & is_valid); double atod(const std::string & str, bool & is_valid); bool pattern_match(const std::string & pattern, const std::string & target, bool nocase = false); }; #endif <file_sep>#include "server.h" #include "client.h" #include "master.h" #include "log.h" #include "file.h" #include <ctype.h> #include <signal.h> namespace rediscpp { server_type::server_type() : shutdown(false) , slave(false) , slave_mutex(true) , listening_port(0) { signal(SIGPIPE, SIG_IGN); databases.resize(1); for (auto it = databases.begin(), end = databases.end(); it != end; ++it) { it->reset(new database_type()); } build_api_map(); bits_table.resize(256); for (int i = 0; i < 256; ++i) { int count = 0; for (int j = 0; j < 8; ++j) { if (i & (1 << j)) { ++count; } } bits_table[i] = count; } } bool server_type::start(const std::string & hostname, const std::string & port, int threads) { std::shared_ptr<address_type> addr(new address_type); addr->set_hostname(hostname.c_str()); bool is_valid; listening_port = atou16(port, is_valid); addr->set_port(listening_port); listening = socket_type::create(*addr); listening->set_reuse(); if (!listening->bind(addr)) { return false; } if (!listening->listen(512)) { return false; } listening->set_extra(this); listening->set_callback(server_callback); listening->set_nonblocking(); timer = timer_type::create(); timer->set_extra(this); timer->set_callback(timer_callback); event = event_type::create(); event->set_extra(this); event->set_callback(event_callback); poll = poll_type::create(); poll->append(listening); poll->append(timer); poll->append(event); const int base_poll_count = 3;//listening, timer & event if (threads) { startup_threads(threads); } while (true) { try { process(); //メインスレッドだけの機能 if (shutdown) { if (poll->get_count() == base_poll_count) { lputs(__FILE__, __LINE__, info_level, "quit server, no client now"); break; } } //ガベージコレクト { timeval_type tv; for (int i = 0, n = databases.size(); i < n; ++i) { auto db = writable_db(i, NULL); db->flush_expiring_key(tv); } } } catch (std::exception e) { lprintf(__FILE__, __LINE__, info_level, "exception:%s", e.what()); } catch (...) { lputs(__FILE__, __LINE__, info_level, "exception"); } } if (thread_pool.size()) { } return true; } void server_type::client_callback(pollable_type * p, int events) { socket_type * s = dynamic_cast<socket_type *>(p); if (!s) { return; } server_type * server = reinterpret_cast<server_type *>(s->get_extra()); if (!server) { return; } server->on_client(s, events); } void server_type::server_callback(pollable_type * p, int events) { socket_type * s = dynamic_cast<socket_type *>(p); if (!s) { return; } server_type * server = reinterpret_cast<server_type *>(s->get_extra()); if (!server) { return; } server->on_server(s, events); } void server_type::event_callback(pollable_type * p, int events) { event_type * e = dynamic_cast<event_type *>(p); if (!e) { return; } server_type * server = reinterpret_cast<server_type *>(e->get_extra()); if (!server) { return; } server->on_event(e, events); } void server_type::timer_callback(pollable_type * p, int events) { timer_type * t = dynamic_cast<timer_type *>(p); if (!t) { return; } server_type * server = reinterpret_cast<server_type *>(t->get_extra()); if (!server) { return; } server->on_timer(t, events); } void server_type::on_server(socket_type * s, int events) { std::shared_ptr<socket_type> cs = s->accept(); if (!cs) { return; } //新規受け付けは停止中 if (shutdown) { cs->shutdown(true, true); cs->close(); return; } cs->set_callback(client_callback); cs->set_nonblocking(); cs->set_nodelay(); std::shared_ptr<client_type> ct(new client_type(*this, cs, password)); ct->set(ct); cs->set_extra(this); cs->set_extra2(ct.get()); ct->process(); if (cs->done()) { cs->close(); } else { append_client(ct); } } void server_type::on_event(event_type * e, int events) { e->recv(); while (true) { auto job = jobs.pop(0); if (!job) { break; } switch (job->type) { case job_type::add_type: append_client(job->client, true); break; case job_type::del_type: remove_client(job->client, true); break; case job_type::list_pushed_type: excecute_blocked_client(true); break; case job_type::slaveof_type: slaveof(job->arg1, job->arg2, true); break; case job_type::propagate_type: if (job->arguments.empty()) { propagete(job->arg1, true); } else { propagete(job->arguments, true); } break; } } e->mod(); } void server_type::on_timer(timer_type * t, int events) { if (t->recv()) { excecute_blocked_client(); } t->mod(); } void server_type::on_client(socket_type * s, int events) { std::shared_ptr<client_type> client = reinterpret_cast<client_type *>(s->get_extra2())->get(); if (!client) { lprintf(__FILE__, __LINE__, info_level, "unknown client"); return; } if ((events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP)) || s->is_broken()) { //lprintf(__FILE__, __LINE__, info_level, "client closed"); remove_client(client); return; } client->events = events; client->process(); if (s->done()) { remove_client(client); } else if (!client->is_blocked()) { s->mod(); } } void server_type::append_client(std::shared_ptr<client_type> client, bool now) { if (thread_pool.empty() || now) { if (!client->is_master() && !client->is_monitor() && !client->is_slave()) { poll->append(client->client); } else if (client->is_monitor()) { monitors.insert(client); monitoring = true; } else if (client->is_master()) { if (master) { master->client->shutdown(true, true); } master = std::dynamic_pointer_cast<master_type>(client); poll->append(client->client); } else { client->client->mod(); } clients[client->client.get()] = client; } else { std::shared_ptr<job_type> job(new job_type(job_type::add_type, client)); jobs.push(job); event->send(); } } void server_type::remove_client(std::shared_ptr<client_type> client, bool now) { if (thread_pool.empty() || now) { if (client->is_blocked()) { unblocked(client); } client->client->close(); if (client->is_master()) { if (client.get() == master.get()) { master.reset(); } slave = false; } if (client->is_monitor()) { monitors.erase(client); monitoring = ! monitors.empty(); } if (client->is_slave()) { mutex_locker locker(slave_mutex); slaves.erase(client); } clients.erase(client->client.get()); } else { std::shared_ptr<job_type> job(new job_type(job_type::del_type, client)); jobs.push(job); event->send(); } } void server_type::excecute_blocked_client(bool now) { if (thread_pool.empty() || now) { std::set<std::shared_ptr<client_type>> clients; { mutex_locker locker(blocked_mutex); clients = blocked_clients; } bool set_timer = false; timeval_type tv; for (auto it = clients.begin(), end = clients.end(); it != end; ++it) { auto & client = *it; client->process(); if (client->is_blocked()) { lprintf(__FILE__, __LINE__, debug_level, "still blocked"); timeval_type ctv = client->get_blocked_till(); if (!ctv.is_epoc()) { if (!set_timer || ctv < tv) { set_timer = true; if (client->current_time < ctv) { tv = ctv - client->current_time; } } } } } //次にタイムアウトが起きるクライアントを起こすイベントを設定する if (set_timer) { if (tv.tv_sec == 0 && tv.tv_usec == 0) { tv.tv_usec = 1; } timer->start(tv.tv_sec, tv.tv_usec * 1000, true); } } else { notify_list_pushed(); } } void server_type::propagete(const std::string & info, bool now) { if (thread_pool.empty() || now) { timeval_type tv; for (auto it = monitors.begin(), end = monitors.end(); it != end; ++it) { auto & to = *it; to->response_status(info); to->flush(); to->client->mod(); } } else { std::shared_ptr<job_type> job(new job_type(job_type::propagate_type)); job->arg1 = info; jobs.push(job); event->send(); } } void server_type::propagete(const arguments_type & info, bool now) { if (thread_pool.empty() || now) { mutex_locker locker(slave_mutex); for (auto it = slaves.begin(), end = slaves.end(); it != end; ++it) { auto & to = *it; to->request(info); to->flush(); } } else { std::shared_ptr<job_type> job(new job_type(job_type::propagate_type)); job->arguments = info; jobs.push(job); event->send(); } } void server_type::notify_list_pushed() { std::shared_ptr<job_type> job(new job_type(job_type::list_pushed_type, std::shared_ptr<client_type>())); jobs.push(job); event->send(); } void server_type::build_api_map() { //connection API api_map["AUTH"].set(&server_type::api_auth).argc(2).type("cc"); api_map["ECHO"].set(&server_type::api_echo).argc(2).type("cc"); api_map["PING"].set(&server_type::api_ping); api_map["QUIT"].set(&server_type::api_quit); api_map["SELECT"].set(&server_type::api_select).argc(2).type("cd"); //serve API //BGREWRITEAOF, BGSAVE, LASTSAVE, SAVE //CLIENT KILL, LIST, GETNAME, SETNAME //CONFIG GET, SET, RESETSTAT //DEBUG OBJECT, SETFAULT //INFO, SLOWLOG, api_map["DBSIZE"].set(&server_type::api_dbsize); api_map["FLUSHALL"].set(&server_type::api_flushall).write(); api_map["FLUSHDB"].set(&server_type::api_flushdb).write(); api_map["SHUTDOWN"].set(&server_type::api_shutdown).argc(1,2).type("cc"); api_map["TIME"].set(&server_type::api_time); api_map["SLAVEOF"].set(&server_type::api_slaveof).type("ccc"); api_map["SYNC"].set(&server_type::api_sync); api_map["REPLCONF"].set(&server_type::api_replconf).argc_gte(3).type("ccc**"); api_map["MONITOR"].set(&server_type::api_monitor); //transaction API api_map["MULTI"].set(&server_type::api_multi); api_map["EXEC"].set(&server_type::api_exec); api_map["DISCARD"].set(&server_type::api_discard); api_map["WATCH"].set(&server_type::api_watch).argc_gte(2).type("ck*"); api_map["UNWATCH"].set(&server_type::api_unwatch); //keys API //DUMP, OBJECT //MIGRATE, RESTORE api_map["KEYS"].set(&server_type::api_keys).type("cp"); api_map["DEL"].set(&server_type::api_del).argc_gte(2).type("ck*").write(); api_map["EXISTS"].set(&server_type::api_exists).type("ck"); api_map["EXPIRE"].set(&server_type::api_expire).type("ckt").write(); api_map["EXPIREAT"].set(&server_type::api_expireat).type("ckt").write(); api_map["PERSIST"].set(&server_type::api_persist).type("ck").write(); api_map["TTL"].set(&server_type::api_ttl).type("ck"); api_map["PTTL"].set(&server_type::api_pttl).type("ck"); api_map["MOVE"].set(&server_type::api_move).type("ckd").write(); api_map["RANDOMKEY"].set(&server_type::api_randomkey); api_map["RENAME"].set(&server_type::api_rename).type("ckk").write(); api_map["RENAMENX"].set(&server_type::api_renamenx).type("ckk").write(); api_map["TYPE"].set(&server_type::api_type).type("ck"); api_map["SORT"].set(&server_type::api_sort).argc_gte(2).type("ck*").set_parser(&server_type::api_sort_store); api_map["DUMP"].set(&server_type::api_dump).type("ck"); api_map["RESTORE"].set(&server_type::api_restore).type("cktv"); //strings api api_map["GET"].set(&server_type::api_get).type("ck"); api_map["SET"].set(&server_type::api_set).argc(3,8).type("ckvccccc").write(); api_map["SETEX"].set(&server_type::api_setex).type("cktv").write(); api_map["SETNX"].set(&server_type::api_setnx).type("ckv").write(); api_map["PSETEX"].set(&server_type::api_psetex).type("cktv").write(); api_map["STRLEN"].set(&server_type::api_strlen).type("ck"); api_map["APPEND"].set(&server_type::api_append).type("ckv").write(); api_map["GETRANGE"].set(&server_type::api_getrange).type("cknn"); api_map["SUBSTR"].set(&server_type::api_getrange).type("cknn");//aka GETRANGE api_map["SETRANGE"].set(&server_type::api_setrange).type("cknv").write(); api_map["GETSET"].set(&server_type::api_getset).type("ckv").write(); api_map["MGET"].set(&server_type::api_mget).argc_gte(2).type("ck*"); api_map["MSET"].set(&server_type::api_mset).argc_gte(3).type("ckv**").write(); api_map["MSETNX"].set(&server_type::api_msetnx).argc_gte(3).type("ckv**").write(); api_map["DECR"].set(&server_type::api_decr).type("ck").write(); api_map["DECRBY"].set(&server_type::api_decrby).type("ckn").write(); api_map["INCR"].set(&server_type::api_incr).type("ck").write(); api_map["INCRBY"].set(&server_type::api_incrby).type("ckn").write(); api_map["INCRBYFLOAT"].set(&server_type::api_incrbyfloat).type("ckn").write(); api_map["BITCOUNT"].set(&server_type::api_bitcount).argc(2,4).type("cknn"); api_map["BITOP"].set(&server_type::api_bitop).argc_gte(4).type("cckk*"); api_map["GETBIT"].set(&server_type::api_getbit).type("ckn"); api_map["SETBIT"].set(&server_type::api_setbit).type("cknv").write(); //lists api api_map["BLPOP"].set(&server_type::api_blpop).argc_gte(3).type("ck*t").write(); api_map["BRPOP"].set(&server_type::api_brpop).argc_gte(3).type("ck*t").write(); api_map["BRPOPLPUSH"].set(&server_type::api_brpoplpush).type("ckkt").write(); api_map["LPUSH"].set(&server_type::api_lpush).argc_gte(3).type("ckv*").write(); api_map["RPUSH"].set(&server_type::api_rpush).argc_gte(3).type("ckv*").write(); api_map["LPUSHX"].set(&server_type::api_lpushx).type("ckv").write(); api_map["RPUSHX"].set(&server_type::api_rpushx).type("ckv").write(); api_map["LPOP"].set(&server_type::api_lpop).type("ck").write(); api_map["RPOP"].set(&server_type::api_rpop).type("ck").write(); api_map["LINSERT"].set(&server_type::api_linsert).type("ckccv").write(); api_map["LINDEX"].set(&server_type::api_lindex).type("ckn"); api_map["LLEN"].set(&server_type::api_llen).type("ck"); api_map["LRANGE"].set(&server_type::api_lrange).type("cknn"); api_map["LREM"].set(&server_type::api_lrem).type("cknv").write(); api_map["LSET"].set(&server_type::api_lset).type("cknv").write(); api_map["LTRIM"].set(&server_type::api_ltrim).type("cknn").write(); api_map["RPOPLPUSH"].set(&server_type::api_rpoplpush).type("ckk").write(); //hashes api api_map["HDEL"].set(&server_type::api_hdel).argc_gte(3).type("ckf*").write(); api_map["HEXISTS"].set(&server_type::api_hexists).type("ckf"); api_map["HGET"].set(&server_type::api_hget).type("ckf"); api_map["HGETALL"].set(&server_type::api_hgetall).type("ck"); api_map["HKEYS"].set(&server_type::api_hkeys).type("ck"); api_map["HVALS"].set(&server_type::api_hvals).type("ck"); api_map["HINCRBY"].set(&server_type::api_hincrby).type("ckfn").write(); api_map["HINCRBYFLOAT"].set(&server_type::api_hincrbyfloat).type("ckfn").write(); api_map["HLEN"].set(&server_type::api_hlen).type("ck"); api_map["HMGET"].set(&server_type::api_hmget).argc_gte(3).type("ckf*"); api_map["HMSET"].set(&server_type::api_hmset).argc_gte(4).type("ckfv**").write(); api_map["HSET"].set(&server_type::api_hset).type("ckfv").write(); api_map["HSETNX"].set(&server_type::api_hsetnx).type("ckfv").write(); //sets api api_map["SADD"].set(&server_type::api_sadd).argc_gte(3).type("ckm*").write(); api_map["SCARD"].set(&server_type::api_scard).argc(2).type("ck"); api_map["SISMEMBER"].set(&server_type::api_sismember).argc(3).type("ckm"); api_map["SMEMBERS"].set(&server_type::api_smembers).argc(2).type("ck"); api_map["SMOVE"].set(&server_type::api_smove).argc(4).type("ckkm").write(); api_map["SPOP"].set(&server_type::api_spop).argc(2).type("ck").write(); api_map["SRANDMEMBER"].set(&server_type::api_srandmember).argc_gte(2).type("ckn"); api_map["SREM"].set(&server_type::api_srem).argc_gte(3).type("ckm*").write(); api_map["SDIFF"].set(&server_type::api_sdiff).argc_gte(2).type("ck*"); api_map["SDIFFSTORE"].set(&server_type::api_sdiffstore).argc_gte(3).type("ckk*").write(); api_map["SINTER"].set(&server_type::api_sinter).argc_gte(2).type("ck*"); api_map["SINTERSTORE"].set(&server_type::api_sinterstore).argc_gte(3).type("ckk*").write(); api_map["SUNION"].set(&server_type::api_sunion).argc_gte(2).type("ck*"); api_map["SUNIONSTORE"].set(&server_type::api_sunionstore).argc_gte(3).type("ckk*").write(); //zsets api api_map["ZADD"].set(&server_type::api_zadd).argc_gte(4).type("cksm**").write(); api_map["ZCARD"].set(&server_type::api_zcard).argc(2).type("ck"); api_map["ZCOUNT"].set(&server_type::api_zcount).argc(4).type("cknn"); api_map["ZINCRBY"].set(&server_type::api_zincrby).argc(4).type("cknm").write(); api_map["ZINTERSTORE"].set(&server_type::api_zinterstore).argc_gte(4).type("cknc*").write();//@note タイプが多すぎてパース出来ない api_map["ZUNIONSTORE"].set(&server_type::api_zunionstore).argc_gte(4).type("cknc*").write();//@note タイプが多すぎてパース出来ない api_map["ZRANGE"].set(&server_type::api_zrange).argc_gte(4).type("cknnc"); api_map["ZREVRANGE"].set(&server_type::api_zrevrange).argc_gte(4).type("cknnc"); api_map["ZRANGEBYSCORE"].set(&server_type::api_zrangebyscore).argc_gte(4).type("cknncccc"); api_map["ZREVRANGEBYSCORE"].set(&server_type::api_zrevrangebyscore).argc_gte(4).type("cknncccc"); api_map["ZRANK"].set(&server_type::api_zrank).argc(3).type("ckm"); api_map["ZREVRANK"].set(&server_type::api_zrevrank).argc(3).type("ckm"); api_map["ZREM"].set(&server_type::api_zrem).argc_gte(3).type("ckm*").write(); api_map["ZREMRANGEBYRANK"].set(&server_type::api_zremrangebyrank).argc(4).type("cknn").write(); api_map["ZREMRANGEBYSCORE"].set(&server_type::api_zremrangebyscore).argc(4).type("cknn").write(); api_map["ZSCORE"].set(&server_type::api_zscore).argc(3).type("ckm"); } server_type::~server_type() { shutdown_threads(); } void server_type::startup_threads(int threads) { thread_pool.resize(threads); for (auto it = thread_pool.begin(), end = thread_pool.end(); it != end; ++it) { it->reset(new worker_type(*this)); (*it)->create(); } } void server_type::shutdown_threads() { if (thread_pool.empty()) { return; } for (auto it = thread_pool.begin(), end = thread_pool.end(); it != end; ++it) { auto & thread = *it; thread->shutdown(); } //@todo レベルトリガの別イベントを発生させて、終了を通知しても良い for (auto it = thread_pool.begin(), end = thread_pool.end(); it != end; ++it) { auto & thread = *it; thread->join(); } thread_pool.clear(); } void server_type::process() { try { std::vector<epoll_event> events(1); poll->wait(events, 1000); for (auto it = events.begin(), end = events.end(); it != end; ++it) { auto pollable = reinterpret_cast<pollable_type*>(it->data.ptr); if (pollable) { pollable->trigger(it->events); } } } catch (const std::exception & e) { lprintf(__FILE__, __LINE__, info_level, "exception %s", e.what()); } catch (...) { lprintf(__FILE__, __LINE__, info_level, "exception"); } } worker_type::worker_type(server_type & server_) : server(server_) { } void worker_type::run() { server.process(); } database_write_locker server_type::writable_db(int index, client_type * client, bool rdlock) { if (slave && !rdlock) { if (client) { if (!client->is_master()) { throw std::runtime_error("ERR could not change on slave mode"); } } } return database_write_locker(databases.at(index).get(), client, rdlock); } database_read_locker server_type::readable_db(int index, client_type * client) { return database_read_locker(databases.at(index).get(), client); } database_write_locker server_type::writable_db(client_type * client, bool rdlock) { return writable_db(client->get_db_index(), client, rdlock); } database_read_locker server_type::readable_db(client_type * client) { return readable_db(client->get_db_index(), client); } void server_type::blocked(std::shared_ptr<client_type> client) { if (!client) return; mutex_locker locker(blocked_mutex); blocked_clients.insert(client); } void server_type::unblocked(std::shared_ptr<client_type> client) { if (!client) return; mutex_locker locker(blocked_mutex); blocked_clients.insert(client); } } <file_sep>#ifndef INCLUDE_REDIS_CPP_TYPE_STRING_H #define INCLUDE_REDIS_CPP_TYPE_STRING_H #include "type_interface.h" namespace rediscpp { class type_string : public type_interface { std::string string_value; int64_t int_value; bool int_type; public: type_string(); type_string(const timeval_type & current); virtual ~type_string(); virtual type_types get_type() const { return string_type; } virtual void output(std::shared_ptr<file_type> & dst) const; virtual void output(std::string & dst) const; static std::shared_ptr<type_string> input(std::shared_ptr<file_type> & src); static std::shared_ptr<type_string> input(std::pair<std::string::const_iterator,std::string::const_iterator> & src); std::string get() const; std::string & ref(); void set(const std::string & str); int64_t append(const std::string & str); int64_t setrange(size_t offset, const std::string & str); bool is_int() const { return int_type; } int64_t incrby(int64_t value); private: void to_int(); void to_str(); }; }; #endif <file_sep>#include "server.h" #include "client.h" #include "type_set.h" namespace rediscpp { ///複数のメンバーを追加 ///@note Available since 1.0.0. bool server_type::api_sadd(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto & members = client->get_members(); auto db = writable_db(client); std::shared_ptr<type_set> set = db->get_set(key, current); bool created = false; if (!set) { set.reset(new type_set(current)); created = true; } int64_t added = set->sadd(members); if (created) { db->replace(key, set); } else { set->update(current); } client->response_integer(added); return true; } ///メンバーの数を取得 ///@note Available since 1.0.0. bool server_type::api_scard(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_set> set = db->get_set(key, current); if (!set) { client->response_integer0(); return true; } int64_t size = set->scard(); client->response_integer(size); return true; } ///メンバー確認 ///@note Available since 1.0.0. bool server_type::api_sismember(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto & member = *client->get_members()[0]; auto db = readable_db(client); std::shared_ptr<type_set> set = db->get_set(key, current); if (set && set->sismember(member)) { client->response_integer1(); } else { client->response_integer0(); } return true; } ///全てのメンバーを取得 ///@note Available since 1.0.0. bool server_type::api_smembers(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = readable_db(client); std::shared_ptr<type_set> set = db->get_set(key, current); if (!set) { client->response_null(); return true; } auto range = set->smembers(); client->response_start_multi_bulk(set->size()); for (auto it = range.first, end = range.second; it != end; ++it) { client->response_bulk(*it); } return true; } ///メンバーを移動 ///@note Available since 1.0.0. bool server_type::api_smove(client_type * client) { auto & srckey = client->get_argument(1); auto & destkey = client->get_argument(2); auto & member = *client->get_members()[0]; auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_set> srcset = db->get_set(srckey, current); std::shared_ptr<type_set> dstset = db->get_set(destkey, current); if (!srcset) { client->response_integer0(); return true; } if (srckey == destkey) { srcset->update(current); client->response_integer1(); return true; } if (!srcset->erase(member)) { client->response_integer0(); return true; } bool inserted = false; if (!dstset) { dstset.reset(new type_set(current)); inserted = dstset->insert(member); db->replace(destkey, dstset); } else { inserted = dstset->insert(member); if (inserted) { dstset->update(current); } } if (srcset->empty()) { db->erase(srckey, current); } else { srcset->update(current); } if (inserted) { client->response_integer1(); } else { client->response_integer0(); } return true; } ///メンバーをランダムに取り出し ///@note Available since 1.0.0. bool server_type::api_spop(client_type * client) { auto & key = client->get_argument(1); auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_set> set = db->get_set(key, current); if (!set || set->empty()) { client->response_null(); return true; } std::vector<std::set<std::string>::const_iterator> randmember; set->srandmember(1, randmember); std::string member = *randmember[0]; set->erase(member); if (set->empty()) { db->erase(key, current); } else { set->update(current); } client->response_bulk(member); return true; } ///メンバーをランダムに取得 ///@note Available since 1.0.0. bool server_type::api_srandmember(client_type * client) { auto & key = client->get_argument(1); auto & argumens = client->get_arguments(); auto current = client->get_time(); auto db = readable_db(client); bool is_valid = true; int64_t count = atoi64(3 <= argumens.size() ? client->get_argument(2) : "0", is_valid); if (!is_valid) { throw std::runtime_error("ERR count is not valid integer"); } std::shared_ptr<type_set> set = db->get_set(key, current); if (!set || set->empty()) { client->response_null(); return true; } std::vector<std::set<std::string>::const_iterator> randmembers; if (0 < count) { set->srandmember_distinct(count, randmembers); } else { set->srandmember(-count, randmembers); } client->response_start_multi_bulk(randmembers.size()); for (auto it = randmembers.begin(), end = randmembers.end(); it != end; ++it) { client->response_bulk(**it); } return true; } ///メンバーを削除 ///@note Available since 1.0.0. bool server_type::api_srem(client_type * client) { auto & key = client->get_argument(1); auto & argumens = client->get_arguments(); auto current = client->get_time(); auto & members = client->get_members(); auto db = writable_db(client); std::shared_ptr<type_set> set = db->get_set(key, current); if (!set || set->empty()) { client->response_integer0(); return true; } size_t removed = set->srem(members); if (set->empty()) { db->erase(key, current); } else { set->update(current); } client->response_integer(removed); return true; } bool server_type::api_sdiff(client_type * client) { return api_soperaion_internal(client, -1, false); } bool server_type::api_sdiffstore(client_type * client) { return api_soperaion_internal(client, -1, true); } bool server_type::api_sunion(client_type * client) { return api_soperaion_internal(client, 1, false); } bool server_type::api_sunionstore(client_type * client) { return api_soperaion_internal(client, 1, true); } bool server_type::api_sinter(client_type * client) { return api_soperaion_internal(client, 0, false); } bool server_type::api_sinterstore(client_type * client) { return api_soperaion_internal(client, 0, true); } ///集合演算 ///@note Available since 1.0.0. ///@param[in] type -1 : diff, 0 : inter, 1 : union ///@param[in] store 保存するかどうか bool server_type::api_soperaion_internal(client_type * client, int type, bool store) { auto & keys = client->get_keys(); auto & argumens = client->get_arguments(); auto current = client->get_time(); auto db = writable_db(client); std::shared_ptr<type_set> result(new type_set(current)); auto it = keys.begin(); auto end = keys.end(); std::string destination; if (store) { destination = **it; ++it; if (it == end) { throw std::runtime_error("ERR only destination"); } } { std::shared_ptr<type_set> set = db->get_set(**it, current); if (set) { result->sunion(*set); } ++it; } if (type < 0) { for (; it != end; ++it) { std::shared_ptr<type_set> set = db->get_set(**it, current); if (set) { result->sdiff(*set); } } } else if (0 < type) { for (; it != end; ++it) { std::shared_ptr<type_set> set = db->get_set(**it, current); if (set) { result->sunion(*set); } } } else { for (; it != end; ++it) { std::shared_ptr<type_set> set = db->get_set(**it, current); if (set) { result->sinter(*set); } } } if (store) { if (result->empty()) { db->erase(destination, current); } else { db->replace(destination, result); } client->response_integer(result->size()); return true; } if (result->empty()) { client->response_null(); return true; } auto range = result->smembers(); client->response_start_multi_bulk(result->size()); for (auto it = range.first, end = range.second; it != end; ++it) { client->response_bulk(*it); } return true; } }; <file_sep>#ifndef INCLUDE_REDIS_CPP_NETWORK_H #define INCLUDE_REDIS_CPP_NETWORK_H #include <stdint.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/un.h> #include <sys/epoll.h> #include <sys/uio.h> #include <sys/eventfd.h> #include <sys/timerfd.h> #include "common.h" #include "thread.h" #include "log.h" namespace rediscpp { class address_type { union sockaddr_any { sockaddr_un un; sockaddr_in in; sockaddr_in6 in6; sockaddr_any(); }; sockaddr_any addr; public: address_type(); bool set_hostname(const std::string & hostname); bool set_port(uint16_t port); uint16_t get_port() const; sa_family_t get_family() const; void set_family(sa_family_t family); sockaddr * get_sockaddr(); const sockaddr * get_sockaddr() const; size_t get_sockaddr_size() const; std::string get_info() const; }; class poll_type; class pollable_type { friend class poll_type; pollable_type(); pollable_type(const pollable_type &); public: typedef std::function<void(pollable_type * p,int)> callback_function_type; private: callback_function_type callback_function; std::weak_ptr<poll_type> poll; protected: int fd; epoll_event events; void * extra; void * extra2; std::weak_ptr<pollable_type> self; public: pollable_type(int fd_) : fd(fd_) , extra(0) , extra2(0) { memset(&events, 0, sizeof(events)); events.data.ptr = this; } virtual ~pollable_type() { if (0 <= fd) { lprintf(__FILE__, __LINE__, error_level, "fd is not closed"); ::close(fd); fd = -1; } } void close(); void trigger(int flag) { if (callback_function) { callback_function(this, flag); } } void set_callback(callback_function_type function) { callback_function = function; } void set_poll(std::shared_ptr<poll_type> poll_) { poll = poll_; } void set_extra(void * extra_) { extra = extra_; } void * get_extra() { return extra; } void set_extra2(void * extra2_) { extra2 = extra2_; } void * get_extra2() { return extra2; } int get_handle() const { return fd; } virtual uint32_t get_events() = 0; void mod(); }; class socket_type : public pollable_type { friend class poll_type; std::shared_ptr<address_type> local; std::shared_ptr<address_type> peer;///<リモートアドレス bool finished_to_read; bool finished_to_write; int shutdowning; bool broken; std::deque<uint8_t> recv_buffer; std::deque<std::pair<std::vector<uint8_t>,size_t>> send_buffers; int sending_file_id; size_t sending_file_size; size_t sent_file_size; socket_type(); socket_type(int s); public: ~socket_type(); bool shutdown(bool reading, bool writing); static std::shared_ptr<socket_type> create(const address_type & address, bool stream = true); bool set_nonblocking(bool nonblocking = true); bool set_reuse(bool reuse = true); bool set_nodelay(bool nodelay = true); bool set_keepalive(bool keepalive, int idle, int interval, int count); bool bind(std::shared_ptr<address_type> address); bool connect(std::shared_ptr<address_type> address); bool listen(int queue_count); std::shared_ptr<socket_type> accept(); bool is_broken() const { return broken; } public: bool should_send() const { return (! send_buffers.empty() || is_sendfile()) && ! is_write_shutdowned(); } bool should_recv() const { return ! recv_buffer.empty() && ! is_read_shutdowned(); } bool send(); bool recv(); bool send(const void * buf, size_t len); void sendfile(int in_fd, size_t size); bool is_sendfile() const { return sent_file_size < sending_file_size; } std::deque<uint8_t> & get_recv() { return recv_buffer; } bool recv_done() const { return finished_to_read; } std::shared_ptr<socket_type> get() { return std::dynamic_pointer_cast<socket_type>(self.lock()); } void close_after_send(); bool is_read_shutdowned() const { return shutdowning == SHUT_RD || shutdowning == SHUT_RDWR; } bool is_write_shutdowned() const { return shutdowning == SHUT_WR || shutdowning == SHUT_RDWR; } virtual uint32_t get_events(); bool done() const { return recv_done() && ! should_recv() && ! should_send(); } std::string get_peer_info() { return peer ? peer->get_info() : std::string(); } }; class event_type : public pollable_type { mutex_type mutex; event_type(const event_type &); event_type(); event_type(int fd_) : pollable_type(fd_) { } public: ~event_type() { close(); } static std::shared_ptr<event_type> create() { int fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); if (fd < 0) { switch (errno) { //case EINVAL: //case EMFILE: //case ENFILE: //case ENODEV: //case ENOMEM: default: throw std::runtime_error("::eventfd failed:" + string_error(errno)); } } std::shared_ptr<event_type> result(new event_type(fd)); result->self = result; return result; } bool send() { mutex_locker locker(mutex); uint64_t increment = 1; int r = write(fd, &increment, sizeof(increment)); if (r == sizeof(increment)) { return true; } if (r < 0) { switch (errno) { case EAGAIN://加算結果がオーバーフローする return true; default: lprintf(__FILE__, __LINE__, error_level, "::write failed:%s", string_error(errno).c_str()); return false; } } lprintf(__FILE__, __LINE__, error_level, "::write failed: r(%d) < sizeof(uint64_t)", r); return false; } bool recv() { mutex_locker locker(mutex); int interupt_count = 0; while (true) { uint64_t counter = 0; int r = read(fd, &counter, sizeof(counter)); if (r == sizeof(counter)) { return 0 < counter; } if (r < 0) { switch (errno) { case EINTR: if (interupt_count < 3) { ++interupt_count; continue; } return false; case EAGAIN://イベントが発生していない return false; default: lprintf(__FILE__, __LINE__, error_level, "::read failed:%s", string_error(errno).c_str()); return false; } } lprintf(__FILE__, __LINE__, error_level, "::read failed: r(%d) < sizeof(uint64_t)", r); break; } return false; } virtual uint32_t get_events() { return EPOLLIN | EPOLLET | EPOLLONESHOT; } }; class timer_type : public pollable_type { mutex_type mutex; timer_type(const timer_type &); timer_type(); timer_type(int fd_) : pollable_type(fd_) , mutex(true) { } public: ~timer_type() { close(); } static std::shared_ptr<timer_type> create(bool monotonic = true) { int fd = timerfd_create(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, TFD_CLOEXEC | TFD_NONBLOCK); if (fd < 0) { switch (errno) { default: throw std::runtime_error("::timerfd_create failed:" + string_error(errno)); } } std::shared_ptr<timer_type> result(new timer_type(fd)); result->self = result; return result; } bool get(time_t & initial_sec, long & initial_nsec, time_t & periodic_sec, long & periodic_nsec) { itimerspec its; int r = 0; { mutex_locker locker(mutex); r = timerfd_gettime(fd, &its); } if (r < 0) { switch (errno) { default: lprintf(__FILE__, __LINE__, error_level, "::timerfd_gettime failed:%s", string_error(errno).c_str()); return false; } } initial_sec = its.it_value.tv_sec; initial_nsec = its.it_value.tv_nsec; periodic_sec = its.it_interval.tv_sec; periodic_nsec = its.it_interval.tv_nsec; return true; } bool set(time_t initial_sec, long initial_nsec, time_t periodic_sec, long periodic_nsec) { itimerspec its; its.it_value.tv_sec = initial_sec; its.it_value.tv_nsec = initial_nsec; its.it_interval.tv_sec = periodic_sec; its.it_interval.tv_nsec = periodic_nsec; int r = 0; { mutex_locker locker(mutex); r = timerfd_settime(fd, 0, &its, NULL); } if (r < 0) { switch (errno) { default: lprintf(__FILE__, __LINE__, error_level, "::timerfd_settime failed:%s", string_error(errno).c_str()); return false; } } return true; } bool stop() { return set(0, 0, 0, 0); } bool start(time_t sec, long nsec, bool once) { return set(sec, nsec, once ? 0 : sec, once ? 0 : nsec); } bool insert(time_t sec, long nsec) { time_t initial_sec, periodic_sec; long initial_nsec, periodic_nsec; mutex_locker locker(mutex); //lprintf(__FILE__, __LINE__, debug_level, "timer insert %d[sec]", (int)sec); if (!get(initial_sec, initial_nsec, periodic_sec, periodic_nsec)) { return false; } const bool started = (initial_sec != 0 && initial_nsec != 0); if (!started) { //lprintf(__FILE__, __LINE__, debug_level, "timer not started, start %d[sec]", (int)sec); return start(sec, nsec, true); } if (sec < initial_sec || (sec == initial_sec && nsec < nsec)) {//more fast first interval //lprintf(__FILE__, __LINE__, debug_level, "timer started but too late %d[sec], start %d[sec]", (int)initial_sec, (int)sec); return set(sec, nsec, periodic_sec, periodic_nsec); } //lprintf(__FILE__, __LINE__, debug_level, "timer started and near %d[sec], start %d[sec]", (int)initial_sec, (int)sec); return true; } bool is_start() { time_t initial_sec, periodic_sec; long initial_nsec, periodic_nsec; if (!get(initial_sec, initial_nsec, periodic_sec, periodic_nsec)) { return false; } return initial_sec != 0 && initial_nsec != 0; } bool is_periodic() { time_t initial_sec, periodic_sec; long initial_nsec, periodic_nsec; if (!get(initial_sec, initial_nsec, periodic_sec, periodic_nsec)) { return false; } return initial_nsec != 0 && periodic_nsec != 0; } bool recv() { mutex_locker locker(mutex); int interupt_count = 0; while (true) { uint64_t counter = 0; int r = read(fd, &counter, sizeof(counter)); if (r == sizeof(counter)) { return true; } if (r < 0) { switch (errno) { case EINTR: if (interupt_count < 3) { ++interupt_count; continue; } return false; case EAGAIN://イベントが発生していない return false; default: lprintf(__FILE__, __LINE__, error_level, "::read failed:%s", string_error(errno).c_str()); return false; } } lprintf(__FILE__, __LINE__, error_level, "::read failed: r(%d) < sizeof(uint64_t)", r); break; } return false; } virtual uint32_t get_events() { return EPOLLIN | EPOLLET | EPOLLONESHOT; } }; class poll_type { int fd; int count; std::weak_ptr<poll_type> self; poll_type(); public: static std::shared_ptr<poll_type> create(); ~poll_type(); void close(); private: bool operation(std::shared_ptr<pollable_type> pollable, int op); public: int get_count() const { return count; } bool append(std::shared_ptr<pollable_type> pollable) { return operation(pollable, EPOLL_CTL_ADD); } bool modify(std::shared_ptr<pollable_type> pollable) { return operation(pollable, EPOLL_CTL_MOD); } bool remove(std::shared_ptr<pollable_type> pollable) { return operation(pollable, EPOLL_CTL_DEL); } bool wait(std::vector<epoll_event> & events, int timeout_milli_sec = 0); }; } #endif <file_sep>#include "server.h" #include "client.h" #include "master.h" #include "log.h" #include "file.h" #include "type_string.h" #include "type_list.h" #include "type_set.h" #include "type_zset.h" #include "type_hash.h" namespace rediscpp { enum constants { version = 6, op_eof = 255, op_selectdb = 254, op_expire = 253, op_expire_ms = 252, len_6bit = 0 << 6, len_14bit = 1 << 6, len_32bit = 2 << 6, double_nan = 253, double_pinf = 254, double_ninf = 255, }; void type_interface::write_len(std::shared_ptr<file_type> & dst, uint32_t len) { if (len < 0x40) {//6bit (8-2) dst->write8(len/* | len_6bit*/); } else if (len < 0x4000) {//14bit (16-2) dst->write8((len >> 8) | len_14bit); dst->write8(len & 0xFF); } else { dst->write8(len_32bit); dst->write(&len, 4); } } void type_interface::write_string(std::shared_ptr<file_type> & dst, const std::string & str) { write_len(dst, str.size()); dst->write(str); } void type_interface::write_double(std::shared_ptr<file_type> & dst, double val) { if (isnan(val)) { dst->write8(double_nan); } else if (isinf(val)) { dst->write8(val < 0 ? double_ninf : double_pinf); } else { const std::string & str = std::move(format("%.17g", val)); dst->write8(str.size()); write_string(dst, str); } } void type_interface::write_len(std::string & dst, uint32_t len) { if (len < 0x40) {//6bit (8-2) dst.push_back(len/* | len_6bit*/); } else if (len < 0x4000) {//14bit (16-2) dst.push_back((len >> 8) | len_14bit); dst.push_back(len & 0xFF); } else { dst.push_back(len_32bit); dst.insert(dst.end(), reinterpret_cast<char*>(&len), reinterpret_cast<char*>(&len) + 4); } } void type_interface::write_string(std::string & dst, const std::string & str) { write_len(dst, str.size()); dst.insert(dst.end(), str.begin(), str.end()); } void type_interface::write_double(std::string & dst, double val) { if (isnan(val)) { dst.push_back(double_nan); } else if (isinf(val)) { dst.push_back(val < 0 ? double_ninf : double_pinf); } else { const std::string & str = std::move(format("%.17g", val)); dst.push_back(str.size()); write_string(dst, str); } } uint32_t type_interface::read_len(std::shared_ptr<file_type> & src) { uint8_t head = src->read8(); switch (head & 0xC0) { case len_6bit: return head & 0x3F; case len_14bit: return ((head & 0x3F) << 8) | src->read8(); case len_32bit: return src->read32(); default: throw std::runtime_error("length invalid"); } } std::string type_interface::read_string(std::shared_ptr<file_type> & src) { uint32_t len = read_len(src); if (!len) return std::move(std::string()); std::string str(len, '\0'); src->read(&str[0], len); return std::move(str); } double type_interface::read_double(std::shared_ptr<file_type> & src) { uint8_t head = src->read8(); switch (head) { case double_nan: return strtod("nan", NULL); case double_ninf: return strtod("-inf", NULL); case double_pinf: return strtod("inf", NULL); case 0: throw std::runtime_error("invalid double"); } std::string str(head, '\0'); src->read(&str[0], head); bool is_valid = true; double d = atod(str, is_valid); if (!is_valid) { throw std::runtime_error("invalid double"); } return d; } uint32_t type_interface::read_len(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { auto & it = src.first; auto & end = src.second; if (it == end) { throw std::runtime_error("not enough"); } uint8_t head = *it++; switch (head & 0xC0) { case len_6bit: return head & 0x3F; case len_14bit: if (it == end) { throw std::runtime_error("not enough"); } return ((head & 0x3F) << 8) | (*it++); case len_32bit: { uint32_t value = 0; for (int i = 0; i < 4; ++i) { if (it == end) { throw std::runtime_error("not enough"); } value |= (*it++) << (8 * i); } return value; } default: throw std::runtime_error("length invalid"); } } std::string type_interface::read_string(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { auto & it = src.first; auto & end = src.second; uint32_t len = read_len(src); if (!len) return std::move(std::string()); if (std::distance(it, end) < len) { throw std::runtime_error("not enough"); } std::string str(it, it + len); it += len; return std::move(str); } double type_interface::read_double(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { auto & it = src.first; auto & end = src.second; if (it == end) { throw std::runtime_error("not enough"); } uint8_t head = *it++; switch (head) { case double_nan: return strtod("nan", NULL); case double_ninf: return strtod("-inf", NULL); case double_pinf: return strtod("inf", NULL); case 0: throw std::runtime_error("invalid double"); } if (std::distance(it, end) < head) { throw std::runtime_error("not enough"); } std::string str(it, it + head); it += head; bool is_valid = true; double d = atod(str, is_valid); if (!is_valid) { throw std::runtime_error("invalid double"); } return d; } void type_string::output(std::shared_ptr<file_type> & dst) const { write_string(dst, get()); } void type_string::output(std::string & dst) const { write_string(dst, get()); } std::shared_ptr<type_string> type_string::input(std::shared_ptr<file_type> & src) { auto strval = read_string(src); std::shared_ptr<type_string> result(new type_string()); result->set(strval); return result; } std::shared_ptr<type_string> type_string::input(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { auto strval = read_string(src); std::shared_ptr<type_string> result(new type_string()); result->set(strval); return result; } void type_list::output(std::shared_ptr<file_type> & dst) const { write_len(dst, size()); for (auto it = value.begin(), end = value.end(); it != end; ++it) { write_string(dst, *it); } } void type_list::output(std::string & dst) const { write_len(dst, size()); for (auto it = value.begin(), end = value.end(); it != end; ++it) { write_string(dst, *it); } } std::shared_ptr<type_list> type_list::input(std::shared_ptr<file_type> & src) { std::shared_ptr<type_list> result(new type_list()); std::list<std::string> & value = result->value; size_t & size = result->count; size = read_len(src); for (size_t i = 0, n = size; i < n; ++i) { value.push_back(read_string(src)); } return result; } std::shared_ptr<type_list> type_list::input(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { std::shared_ptr<type_list> result(new type_list()); std::list<std::string> & value = result->value; size_t & size = result->count; size = read_len(src); for (size_t i = 0, n = size; i < n; ++i) { value.push_back(read_string(src)); } return result; } void type_set::output(std::shared_ptr<file_type> & dst) const { write_len(dst, size()); for (auto it = value.begin(), end = value.end(); it != end; ++it) { write_string(dst, *it); } } void type_set::output(std::string & dst) const { write_len(dst, size()); for (auto it = value.begin(), end = value.end(); it != end; ++it) { write_string(dst, *it); } } std::shared_ptr<type_set> type_set::input(std::shared_ptr<file_type> & src) { std::shared_ptr<type_set> result(new type_set()); std::set<std::string> & value = result->value; size_t size = read_len(src); for (size_t i = 0, n = size; i < n; ++i) { value.insert(read_string(src)); } return result; } std::shared_ptr<type_set> type_set::input(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { std::shared_ptr<type_set> result(new type_set()); std::set<std::string> & value = result->value; size_t size = read_len(src); for (size_t i = 0, n = size; i < n; ++i) { value.insert(read_string(src)); } return result; } void type_zset::output(std::shared_ptr<file_type> & dst) const { write_len(dst, size()); for (auto it = sorted.begin(), end = sorted.end(); it != end; ++it) { auto & pair = *it; write_string(dst, pair->member); write_double(dst, pair->score); } } void type_zset::output(std::string & dst) const { write_len(dst, size()); for (auto it = sorted.begin(), end = sorted.end(); it != end; ++it) { auto & pair = *it; write_string(dst, pair->member); write_double(dst, pair->score); } } std::shared_ptr<type_zset> type_zset::input(std::shared_ptr<file_type> & src) { size_t size = read_len(src); std::vector<double> scores(size); std::vector<std::string> members_(size); std::vector<std::string *> members(size); for (size_t i = 0, n = size; i < n; ++i) { auto member = read_string(src); auto score = read_double(src); scores[i] = score; members_[i] = member; members[i] = &members_[i]; } std::shared_ptr<type_zset> result(new type_zset()); result->zadd(scores, members); return result; } std::shared_ptr<type_zset> type_zset::input(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { size_t size = read_len(src); std::vector<double> scores(size); std::vector<std::string> members_(size); std::vector<std::string *> members(size); for (size_t i = 0, n = size; i < n; ++i) { auto member = read_string(src); auto score = read_double(src); scores[i] = score; members_[i] = member; members[i] = &members_[i]; } std::shared_ptr<type_zset> result(new type_zset()); result->zadd(scores, members); return result; } void type_hash::output(std::shared_ptr<file_type> & dst) const { write_len(dst, size()); for (auto it = value.begin(), end = value.end(); it != end; ++it) { auto & pair = *it; write_string(dst, pair.first); write_string(dst, pair.second); } } void type_hash::output(std::string & dst) const { write_len(dst, size()); for (auto it = value.begin(), end = value.end(); it != end; ++it) { auto & pair = *it; write_string(dst, pair.first); write_string(dst, pair.second); } } std::shared_ptr<type_hash> type_hash::input(std::shared_ptr<file_type> & src) { std::shared_ptr<type_hash> result(new type_hash()); size_t size = read_len(src); for (size_t i = 0, n = size; i < n; ++i) { auto field = read_string(src); auto value = read_string(src); result->hset(field, value); } return result; } std::shared_ptr<type_hash> type_hash::input(std::pair<std::string::const_iterator,std::string::const_iterator> & src) { std::shared_ptr<type_hash> result(new type_hash()); size_t size = read_len(src); for (size_t i = 0, n = size; i < n; ++i) { auto field = read_string(src); auto value = read_string(src); result->hset(field, value); } return result; } void server_type::dump(std::string & dst, const std::shared_ptr<type_interface> & value) { dst.reserve(1024); value->output(dst); } std::shared_ptr<type_interface> server_type::restore(const std::string & src, const timeval_type & current) { std::shared_ptr<type_interface> value; if (src.empty()) { return value; } std::pair<std::string::const_iterator, std::string::const_iterator> range(src.begin(), src.end()); switch (*range.first++) { case string_type: value = type_string::input(range); break; case list_type: value = type_list::input(range); break; case set_type: value = type_set::input(range); break; case zset_type: value = type_zset::input(range); break; case hash_type: value = type_hash::input(range); break; } if (std::distance(range.first, range.second) != 2 + 8) { throw std::runtime_error("suffix error"); } uint16_t ver = *range.first++; ver |= (*range.first++) << 8; if (version < ver) { throw std::runtime_error("version error"); } uint64_t src_crc = 0; for (int i = 0; i < 8; ++i) { uint64_t val = static_cast<uint64_t>(*range.first++) & 0xFF; val <<= i * 8; src_crc |= val; } uint64_t crc = crc64::update(0, &src[0], src.size() - 8); if (src_crc != crc) { throw std::runtime_error(format("crc error %"PRIx64" != %"PRIx64, src_crc, crc)); } return value; } bool server_type::save(const std::string & path) { std::shared_ptr<file_type> f = file_type::create(path, true); if (!f) { return false; } try { timeval_type current; f->printf("REDIS%04d", version); for (size_t i = 0, n = databases.size(); i < n; ++i ) { auto & db = *databases[i]; auto range = db.range(); if (range.first == range.second) { continue; } //selectdb i f->write8(op_selectdb); type_interface::write_len(f, i); for (auto it = range.first; it != range.second; ++it) { auto & kv = *it; auto & key = kv.first; auto & expire = kv.second.first; auto & value = kv.second.second; if (expire->is_expired(current)) { continue; } if (expire->is_expiring()) { f->write8(op_expire_ms); f->write64(expire->at().get_ms()); } f->write8(value->get_type()); type_interface::write_string(f, key); std::string value_str; dump(value_str, value); f->write(value_str); } } f->write8(op_eof); f->write_crc(); } catch (std::exception e) { ::unlink(path.c_str()); return false; } return true; } bool server_type::load(const std::string & path) { std::shared_ptr<file_type> f = file_type::open(path, true); if (!f) { return false; } try { timeval_type current; char buf[128] = {0}; f->read(buf, 9); if (memcmp(buf, "REDIS", 5)) { lprintf(__FILE__, __LINE__, info_level, "Not found REDIS header"); throw std::runtime_error("Not found REDIS header"); } int ver = atoi(buf + 5); if (ver < 0 || version < ver) { lprintf(__FILE__, __LINE__, info_level, "Not found REDIS version %d", ver); throw std::runtime_error("Not compatible REDIS version"); } //全ロック std::vector<std::shared_ptr<database_write_locker>> lockers(databases.size()); for (size_t i = 0; i < databases.size(); ++i) { lockers[i].reset(new database_write_locker(databases[i].get(), NULL, false)); } //@todo ファイルから読むのがslaveof以外でおきるなら、ここは修正が必要 slave = true; for (int i = 0, n = databases.size(); i < n; ++i) { auto & db = *(lockers[i]); db->clear(); } uint8_t op = 0; uint32_t db_index = 0; auto db = databases[db_index]; uint64_t expire_at = 0; while (op != op_eof) { op = f->read8(); switch (op) { case op_eof: if (!f->check_crc()) { lprintf(__FILE__, __LINE__, info_level, "corrupted crc"); throw std::runtime_error("corrupted crc"); } continue; case op_selectdb: db_index = type_interface::read_len(f); if (databases.size() <= db_index) { lprintf(__FILE__, __LINE__, info_level, "db index out of range"); throw std::runtime_error("db index out of range"); } db = databases[db_index]; continue; case op_expire_ms: expire_at = f->read64(); continue; default: { std::string key = type_interface::read_string(f); std::shared_ptr<type_interface> value; switch (op) { case string_type: value = type_string::input(f); break; case list_type: value = type_list::input(f); break; case set_type: value = type_set::input(f); break; case zset_type: value = type_zset::input(f); break; case hash_type: value = type_hash::input(f); break; } expire_info expire(current); if (expire_at) { expire.expire(timeval_type(expire_at / 1000, (expire_at % 1000) * 1000)); expire_at = 0; } db->insert(key, expire, value, current); } break; } } } catch (const std::exception & e) { lprintf(__FILE__, __LINE__, info_level, "exception:%s", e.what()); return false; } catch (...) { lprintf(__FILE__, __LINE__, info_level, "exception"); return false; } return true; } void server_type::dump_suffix(std::string & dst) { dst.push_back(version & 0xFF); dst.push_back((version >> 8) & 0xFF); uint64_t crc = crc64::update(0, &dst[0], dst.size()); dst.insert(dst.end(), reinterpret_cast<char*>(&crc), reinterpret_cast<char*>(&crc) + 8); } }
db6e03765c63599b45c19466dc7b6da0713207e8
[ "Markdown", "Makefile", "C++", "M4Sugar" ]
49
C++
Arcen/rediscpp
8217dfbf457fb2a4cc94222e6db9cda47c72d53d
d363beed6d35ad4d78742b2a9d795045a606e9c5
refs/heads/master
<file_sep>ExpressApp ========== Simple ExpressApp using Express Framework <file_sep>var express = require('express'); var app = express(); var path = require('path'); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req, res) { res.render('sam', { title:'Homepage', name:'Robin', age:25, details: { first: "first is the best", second: "second who cares!!", third: "third not fine" } }) }); app.get('/about', function(req, res) { res.render('about', { title: 'About', name: '<NAME>' }); }); app.get('/contact', function(req, res) { res.render('about', { title: 'Contact' }); }); app.get('/drop', function(req, res) { res.render('about', { title: 'Drop' }) }); app.listen(3001);
40f1b8dceb819d02514767ee1044d5ba64d4abae
[ "Markdown", "JavaScript" ]
2
Markdown
BastinRobin/ExpressApp
7aabfc0e5abec6c1e3945a42b2240f347531521b
654f714e729ca38c53e596e759333e1d2214bc1b
refs/heads/master
<repo_name>ChristineBasta/mt_gender_1<file_sep>/prepare_translation.py def prepare_translations(file_eng, file_trans, file_to_evaluate): eng_file = open(file_eng, 'r') trans_file = open(file_trans, 'r') evaluating_file = open(file_to_evaluate, 'w+') while True: line1 = eng_file.readline() line2 = trans_file.readline() line1=line1.replace('\n','') line2=line2.replace(' .','.') line2=line2.replace(' , ', ', ') line_to_write= line1+" ||| "+line2 evaluating_file.write(line_to_write) if not line1 and not line2: break def original_sent(file_eng, eng_to_append): eng_file = open(file_eng, 'r') evaluating_file = open(eng_to_append, 'w+') while True: line1 = eng_file.readline() fields = line1.split("\t") if len(fields)>1: print(fields[2]) line_to_write = fields[2]+'\n' evaluating_file.write(line_to_write) if not line1: break if __name__ == "__main__": original_sent('data/aggregates/en.txt', 'data/aggregates/en_sen_only.txt') #original_sent('data/aggregates/en_pro.txt', 'data/aggregates/en_pro_sen_only.txt') #original_sent('data/aggregates/en_anti.txt', 'data/aggregates/en_anti_sen_only.txt') #prepare_translations('data/aggregates/en_sen_only.txt','translations/winomtspeech/st_winomtspeech_ende.hyp', 'translations/winomtspeech/en-de.txt') #prepare_translations('data/aggregates/en_sen_only.txt', 'translations/winomtspeech/st_winomtspeech_enes.hyp','translations/winomtspeech/en-es.txt') #prepare_translations('data/aggregates/en_sen_only.txt', 'translations/winomtspeech/st_winomtspeech_enfr.hyp','translations/winomtspeech/en-fr.txt') #prepare_translations('data/aggregates/en_sen_only.txt', 'translations/winomtspeech/st_winomtspeech_enit.hyp','translations/winomtspeech/en-it.txt') prepare_translations('data/aggregates/en_sen_only.txt', 'data/aggregates/en_sen_only.txt', 'translations/winomtspeech/en-en.txt') <file_sep>/requirements.txt docopt tqdm spacy # Russian & Ukranian morphology git+https://github.com/kmike/pymorphy2 pymorphy2-dicts-ru pymorphy2-dicts-uksudo apt-get install libgoogle-perftools-dev libsparsehash-dev
2d60138f76bca8c1dca6e679802b6aa42b6a7277
[ "Python", "Text" ]
2
Python
ChristineBasta/mt_gender_1
c03249c66bd1fd523263c2fbcf188073fcaa93f2
189f0bf33b01b6bf82c0d61143daaac7f1f59aa5
refs/heads/master
<repo_name>Evandro18/GOLANG-gRPC<file_sep>/README.md # GOLANG-gRPC First Golang gRPC <file_sep>/server/main.go package main import ( "context" "fmt" "log" "os" "os/signal" "go.mongodb.org/mongo-driver/bson" "net" salespb "../proto" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/reflection" "google.golang.org/grpc/status" ) var db *mongo.Client var salesdb *mongo.Collection var mongoCtx context.Context type SalesServer struct{} func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) fmt.Println("Starting server on port :4040...") listener, err := net.Listen("tcp", ":4040") if err != nil { panic(err) } srv := grpc.NewServer() salespb.RegisterSalesServiceServer(srv, &SalesServer{}) reflection.Register(srv) fmt.Println("Connecting to MongoDB...") mongoCtx = context.Background() db, err := mongo.Connect(mongoCtx, options.Client().ApplyURI("mongodb://poc-sales:poc-sales@127.0.0.1:27017/poc-sales")) if err != nil { log.Fatal(err) } err = db.Ping(mongoCtx, nil) if err != nil { log.Fatalf("Could not connect to mongoDB %v\n", err) } else { fmt.Println("Connected to MongoDB") } salesdb = db.Database("poc-sales").Collection("sales") go func() { if e := srv.Serve(listener); e != nil { panic(e) } }() fmt.Println("Server succesfully started on port :50051") c := make(chan os.Signal) signal.Notify(c, os.Interrupt) <-c fmt.Println("\nStopping server...") srv.Stop() listener.Close() fmt.Println("Closing mongoDb connection...") db.Disconnect(mongoCtx) fmt.Println("Bye Bye") } type SaleItem struct { ID primitive.ObjectID `bson:"_id,omitempty"` Product string `bson:"product"` Quantity int64 `bson:"quantity"` } // AddSale {} func (s *SalesServer) AddSale(ctx context.Context, request *salespb.Request) (*salespb.Response, error) { sale := request.GetSale() data := SaleItem{ Product: sale.GetProduct(), Quantity: sale.GetQuantity(), } result, err := salesdb.InsertOne(mongoCtx, data) if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Internal error: %v", err), ) } oid := result.InsertedID.(primitive.ObjectID) sale.Id = oid.Hex() response := &salespb.Response{} response.Sale = sale return response, nil } // ListSales {} func (s *SalesServer) ListSales(req *salespb.ListSalesReq, stream salespb.SalesService_ListSalesServer) error { data := &SaleItem{} cursor, err := salesdb.Find(mongoCtx, bson.M{}) if err != nil { status.Errorf( codes.Internal, fmt.Sprintf("Internal error: %v", err), ) } defer cursor.Close(mongoCtx) for cursor.Next(mongoCtx) { err := cursor.Decode(data) if err != nil { return status.Errorf(codes.Unavailable, fmt.Sprintf("Could not decode data: %v", err)) } stream.Send(&salespb.ListSalesRes{ Sale: &salespb.Sale{ Id: data.ID.Hex(), Product: data.Product, Quantity: data.Quantity, }, }) } if err := cursor.Err(); err != nil { return status.Errorf(codes.Internal, fmt.Sprintf("Unkown cursor error: %v", err)) } return nil } func (s *SalesServer) ListById(ctx context.Context, req *salespb.RequestById) (*salespb.Sale, error) { oid, err := primitive.ObjectIDFromHex(req.GetId()) if err != nil { status.Errorf( codes.Internal, fmt.Sprintf("Inválid Id: %v", err), ) } result := salesdb.FindOne(mongoCtx, bson.M{"_id": oid}) data := &SaleItem{} if err := result.Decode(&data); err != nil { return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find sale with Object Id %s: %v", req.GetId(), err)) } response := &salespb.Sale{ Id: oid.Hex(), Product: data.Product, Quantity: data.Quantity, } return response, nil } <file_sep>/client/main.go package main import ( "fmt" "io" "log" "net/http" salespb "../proto" "github.com/gin-gonic/gin" "google.golang.org/grpc" ) type Sale struct { // ID string `bson:"_id,omitempty"` Product string `json:"product"` Quantity int64 `json:"quantity"` } func main() { conn, err := grpc.Dial("localhost:4040", grpc.WithInsecure()) if err != nil { panic(err) } client := salespb.NewSalesServiceClient(conn) g := gin.Default() g.GET("/sales", func(ctx *gin.Context) { req := &salespb.ListSalesReq{} stream, err := client.ListSales(ctx, req) if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{ "error": fmt.Sprint(err), }) } for { res, err := stream.Recv() if err == io.EOF { break } if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{ "error": fmt.Sprint(err), }) } ctx.JSON(http.StatusOK, res) } }) g.GET("/sales/:Id", func(ctx *gin.Context) { req := &salespb.RequestById{} Id := ctx.Param("Id") req.Id = Id response, err := client.ListById(ctx, req) if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{ "error": fmt.Sprint(err), }) } ctx.JSON(http.StatusOK, response) }) g.POST("/sale", func(ctx *gin.Context) { var json Sale if err := ctx.ShouldBindJSON(&json); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } sale := &salespb.Sale{} sale.Product = json.Product sale.Quantity = json.Quantity req := &salespb.Request{Sale: sale} if response, err := client.AddSale(ctx, req); err == nil { ctx.JSON(http.StatusOK, response.Sale) } else { ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) } }) if err := g.Run(":8080"); err != nil { log.Fatalf("Failed to run server: %v", err) } }
2a5c5e12c07e539a1f97ced69cb055db205330e5
[ "Markdown", "Go" ]
3
Markdown
Evandro18/GOLANG-gRPC
bdd8ce5f4e3455a25cfb8d6329c2a17946e8755a
379e29e9edb10322642280efcd27c2a96b69210c
refs/heads/master
<repo_name>JohnMurray/pinatra<file_sep>/index.php <?php include 'lib/pinatra.php'; Pinatra::configure(function ($conf) { $config['base_path'] = '/bank'; return $config; }); Pinatra::before('*', function () { //header('test: me'); }); Pinatra::after('*', function () { //echo 'DONE'; }); // Some test routes Pinatra::get('/hello/:name', function($name) { return $this->json([ 'key' => 'hello-route has been matched!', 'name' => $name ]); }); Pinatra::post('/form-submit', function ($data) { var_dump($data); }); Pinatra::head('/hello/:name', function($name) { header("x-name: ${name}"); }); Pinatra::delete('/hello/:name', function ($name) { header("x-deleted: ${name}"); return 'deleted!'; }); Pinatra::put('/hello/:name', function ($data, $name) { header("x-deleted: ${name}"); var_dump($data); }); Pinatra::run(); ?> <file_sep>/lib/traits/json_utils.php <?php /** * Something to try and make serving JSON content just a litle simpler */ trait JSONUtils { public function json($object) { // set appropriate headers header('Content-Type: application/json', true); // TODO: pretty-print JSON based on config settings // return the serialized object return json_encode($object); } } ?> <file_sep>/lib/pinatra.php <?php require 'traits/singleton.php'; require 'traits/json_utils.php'; require 'traits/routing.php'; require 'traits/body_utils.php'; /** * The main class for our Sinatra clone. Where all of the * (not-so-much-)magic happens! :-] */ class Pinatra { use singleton; use JSONUtils; use Routing; use HTMLBodyUtils; protected $before_hooks = []; protected $after_hooks = []; protected $routes = []; protected $config = []; private function __construct() { $this->config = [ 'base_path' => '' ]; } /** * Public: Register a user-defined handler with a particular regex to * match with and a callback that will handle the results. */ private function register($method, $match, $callback) { $match = $this->compute_regex($match); $this->routes[$method][$match] = $callback; } /** * Public: Register a callback that will be run before any routes * for a particular request. A match is also given such * that it can be applied to a number of routes. */ private function register_before($match, $callback) { if (empty($match)) $match = '*'; $match = $this->compute_regex($match); $this->before_hooks[$match] = $callback; } /** * Public: Register a callback that will be run after any routes * for a particular request. A match is also given such * that it can be applied to a number of routes. */ private function register_after($match, $callback) { if (empty($match)) $match = '*'; $match = $this->compute_regex($match); $this->after_hooks[$match] = $callback; } /** * Public: Allow the user to change any configuration options * that will be used by Pinatra. Also, any custom options * that they just want to provide can also be stored. */ private function user_configuration($callback) { $this->config = $callback($this->config); } /* * REGISTRATION METHODS * * This is pretty self-explanatory... honestly. */ public static function configure($callback) { $app = Pinatra::instance(); $app->user_configuration($callback); } public static function head($match, $callback) { $app = Pinatra::instance(); $app->register('head', $match, $callback); } public static function get($match, $callback) { $app = Pinatra::instance(); $app->register('get', $match, $callback); } public static function put($match, $callback) { $app = Pinatra::instance(); $app->register('put', $match, $callback); } public static function post($match, $callback) { $app = Pinatra::instance(); $app->register('post', $match, $callback); } public static function delete($match, $callback) { $app = Pinatra::instance(); $app->register('delete', $match, $callback); } public static function before($match, $callback) { $app = Pinatra::instance(); $app->register_before($match, $callback); } public static function after($match, $callback) { $app = Pinatra::instance(); $app->register_after($match, $callback); } /** * Method that is called when we actually want to process an incoming * request based on the method and uri provided. This method (expecting * to be given a URI and method) can also be used for re-routing requests * internally. * * TODO: This method needs refactoring (badly) */ public static function handle_request($method, $uri) { $app = Pinatra::instance(); // find and call all before-hooks $before_matches = $app->find_all_routes($app->before_hooks, $uri); foreach ($before_matches as $match) { call_user_func_array( $match['callback']->bindTo($app), $match['arguments']); } // find and call route-handler $route_match = $app->find_route($app->routes, $method, $uri); if ($route_match !== null) { $request_body_data = $app->get_body_data($method); if ($request_body_data !== null) { array_unshift($route_match['arguments'], $request_body_data); } $route_res = call_user_func_array( $route_match['callback']->bindTo($app), $route_match['arguments']); if ($method !== 'head') { print($route_res); } var_dump($_PUT); } // find and call all after-hooks $after_matches = $app->find_all_routes($app->after_hooks, $uri); foreach ($after_matches as $match) { call_user_func_array( $match['callback']->bindTo($app), $match['arguments']); } } /** * Used to start the application (after everything has been initialized) */ public static function run() { $app = Pinatra::instance(); $uri = str_replace( $app->config['base_path'], '', $_SERVER['REQUEST_URI']); $method = strtolower($_SERVER['REQUEST_METHOD']); Pinatra::handle_request($method, $uri); } } ?> <file_sep>/README.md # Pinatra __Update:__ I finished everything that I had planned to do... So, unless someone else finds this project interesting, I believe that I am done working on it for now. Mainly because there are better/more-mature projects out there. If the name of this project isn't enough to let you know what it is, this is a Sinatra clone in PHP. Currently this is not a serious project, just a little something for me to try and learn a little more about PHP. My background is mainly in Ruby and I have a strong love for Sinatra. So, I'm taking about the task to implement the basic feature-set that is present in Sinatra. Mainly the minimalistic route matching and hooks that Sinatra exposes for whipping up dandy little web-apps/api's very quickly. ## Getting Started A simple hello-world example in good 'ole Sinatra fashion: ```php # index.php require 'pinatra.php'; Pinatra::get('/hi', function () { return 'Hello World!'; }); Pinatra::run(); ``` ```bash php -S 0.0.0.0:8181 ``` Before hooks: ```php // before everything, set a custom header Pinatra::before('*', function () { header("MyApp: v${version}"); }); // before user's view their profile, force an update of // their stream (silly example) Pinatra::before('/user-profile/:id', function($id) { update_user_stream($id); }); ``` After hooks: ```php // update site's hit-counter (also silly, but you get the point right?) Pinatra::after('*', function () { update_site_hit_counter(); }); ``` ## Compatability This little framework is only compatible with PHP v5.4.x since it was just for fun and I don't care about any sort of backwards compatability. ## On the Calendar The items that I will be adding/implementing next are (roughly) as follows: + ~~Parametric URIs (variables actually passed to the handler functions)~~ + ~~Refactoring of handle_request function~~ + ~~Configuration blocks~~ + ~~Testing before and after hooks~~ (working) + ~~POST functionality~~ + ~~PUT functionality~~ + ~~DELETE functionality~~ + ~~HEAD functionality~~ ## Contributing This project is dead. <file_sep>/lib/traits/body_utils.php <?php /** * Something to parse and return the HTML request body based on * the method. Additionally, this could (future/theoretically) also * be a good place to detect the content-type of the request body * and intelligently parse and return that data (form-data, json, * xml, etc). */ trait HTMLBodyUtils { /** * Private: Gets the data for the current request. This may require * a little extra work if the HTTP method/verb is no POST * as PHP doesn't do it's automatic parsing of the request- * body. * * method - The HTTP method (or verb) * * Returns an associative array */ private function get_body_data($method) { switch ($method) { case 'post': return $_POST; case 'put': case 'delete': $request_body = file_get_contents('php://input'); $body_values = []; parse_str($request_body, $body_values); return $body_values; default: return null; } } } ?> <file_sep>/lib/traits/routing.php <?php /** * If we're going to rip off Sinatra properly, then we'll need to have some * proper URI's as well. This means a proper parser for those URIs. The kind * of URIs that I am talking about are of the type: * * /blogs * /blogs/:id * /blogs/:blog_id/comments/:comment_id * /* * /*.css * etc. * * We're going to take URIs of those styles and transfer them into proper * (Perl) regular expressions for matching against real-URIs. */ trait Routing { private $URIParser_PLACEHOLDER = '([^\/]+)'; private $URIParser_GLOB = '.*?'; /** * Private: Generate a PHP (Perl) regular expression given the * Sinatra-style expression in the get/post/put/etc. functions. */ private function compute_regex($match) { // get the URI parts of the match-pattern given $parts = array_filter(explode('/', $match), function ($val) { return !empty($val); }); // build our pattern-matching regex from given route $regex= '/^'; foreach ($parts as $part) { if ($part[0] === ':') { $regex .= '\/' . $this->URIParser_PLACEHOLDER; } else if ($part[0] === '*'){ $regex .= '\/' . $this->URIParser_GLOB; } else { $regex .= '\/' . $part; } } $regex .= '\/?$/'; return $regex; } /** * Private: Find the first-matched handler for a given URI * * Returns a callback and a list of arguments (parsed from the URI) */ private function find_route($routes, $method, $uri) { $matches = $this->find_all_routes($routes[$method], $uri, 1); return array_shift($matches); } /** * Private: Find all-matched handler for a given URI * * Returns a callback and a list of arguments (parsed from the URI) */ private function find_all_routes($routes, $uri, $max = -1) { $return_values = []; if ($uri != null && !empty($uri)) { $uri = strtolower($uri); $count = 0; foreach($routes as $match => $callback) { $match_groups = []; $match_value = preg_match_all( $match, $uri, $match_groups, PREG_SET_ORDER); if ($match_value !== 0) { array_push($return_values, [ 'callback' => $callback, 'arguments' => array_slice($match_groups[0], 1) ]); if ($max == ++$count) break; } } } return $return_values; } } ?>
f2b73e536b5338fa63357ec6bad57c9a4515c9ec
[ "Markdown", "PHP" ]
6
PHP
JohnMurray/pinatra
19e7bec08b245c3c49bde77e1daf1b82b1ab1a87
5d11cb53e1fe362508b046d14737e87a468e1888
refs/heads/master
<repo_name>woratat/ES<file_sep>/Homework/script.js let profile = document.querySelector('.profile'); function promiseCallApi(){ axios.get('https://reqres.in/api/users/5').then(res =>{ profile.src = res.data.data.avatar document.getElementById('name').innerText = res.data.data.first_name+" "+res.data.data.last_name document.getElementById('email').innerText = res.data.data.email }).catch(err =>{ console.log(`err`, err) }) } const testFunction = async() =>{ try { let response = await axios.get('https://reqres.in/api/users/5') profile.src = response.data.data.avatar document.getElementById('name').innerText = response.data.data.first_name+" "+response.data.data.last_name document.getElementById('email').innerText = response.data.data.email } catch (error) { console.log('error :>>', error) } } promiseCallApi() // testFunction() <file_sep>/promise.js // let promise = new Promise (function (resolve, reject){ // resolve("Success") // }); // promise.then(function (x){ // console.log('response ==> ',x) // }); // let promiseReject = new Promise((resolve, reject)=>{ // reject('error') // }) // promiseReject.then(x => { // console.log('then response ==> ',x) // }).catch(err => { // console.log('catch response ==> ',err) // }) function count1(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ console.log('count1') resolve() //return ค่า },3000) //3sec }) } function count2(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ console.log('count2') // resolve() //return ค่า reject('error 101') },2000) //2sec }) } function count3(){ console.log('count3') } count1().then(x =>{ return count2() }).then(x2=>{ count3() }).catch(err =>{ console.log(`error ==> `, err) }) <file_sep>/await.js function taskOne() { return new Promise((resolve,reject)=>{ setTimeout(function () { console.log("this is task 1"); resolve() }, 500); }) } function taskTwo() { return new Promise((resolve,reject)=>{ setTimeout(function () { console.log("this is task 2"); resolve() }, 2000); }) } function taskThree() { return new Promise((resolve,reject)=>{ setTimeout(function () { console.log("this is task 3"); resolve() }, 1000); }) } async function main(){ //จะ await ตรงไหน function นั้นต้องเป็น promise เท่านั้นไม่งั้นไม่เกิดประโยชน์ await taskOne() await taskTwo() await taskThree() } main()
cd3d5acaca001335e9cc16d865c9f0a038ae97c9
[ "JavaScript" ]
3
JavaScript
woratat/ES
47d116085abed7b60b92e6b6f3812e185eb616bc
3ae1b5d261ee824b6ea6519ee5bb6ea023e46455
refs/heads/master
<repo_name>smmehl0311/zoho<file_sep>/public/scripts/components/utils.js import {checkToken} from '../service/apiClient'; export const checkUserAndAuthToken = ({user, loginSuccess, setIsLoginLoading}) => { const authSplit = document.cookie.split('auth-token='); const semicolonSplit = authSplit.length > 1 ? authSplit[1].split(';') : void 0; const authToken = semicolonSplit ? semicolonSplit[0] : void 0; console.log('authToken', authToken) if (authToken && !user) { setIsLoginLoading(true); const username = authToken.split(':')[0]; checkToken() .then(() => { loginSuccess(username); setIsLoginLoading(false); }) .catch(err => console.log(err)); } };
4b85fff4b4291fe2c069ab1726159bd9e6396998
[ "JavaScript" ]
1
JavaScript
smmehl0311/zoho
7045213653ba2672505f7010f2aaa209115013a7
8ff76f3b9c2a293ba17930d6182069dc323e0744
refs/heads/master
<repo_name>sandeepreddy1945/SpringMongoDemo<file_sep>/README.md # SpringMongoDemo Using Mongo DB ## A Sample Project Used to Configure Spring and Mongo DB ## Components Used Include Spring, Swagger and Monogo DB Dependencies. <file_sep>/src/main/java/com/app/mongo/rest/SpringMongoRestController.java /** * */ package com.app.mongo.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.app.mongo.model.Customer; import com.app.mongo.repo.CustomerRepository; import com.app.mongo.service.SpringMongoService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * @author Sandeep * */ @Api @RestController public class SpringMongoRestController { @Autowired private CustomerRepository customerRepository; @Autowired private SpringMongoService springMongoService; @ApiOperation(value = "Add Customer") @RequestMapping(path = "api/customer/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Customer> addCustomer(@RequestBody Customer customer) { customer = customerRepository.save(customer); return new ResponseEntity<Customer>(customer, HttpStatus.ACCEPTED); } @ApiOperation(value = "List All Customers") @RequestMapping(path = "api/customer/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<Customer>> listAllCustomers() { List<Customer> customers = customerRepository.findAll(); return new ResponseEntity<List<Customer>>(customers, HttpStatus.OK); } @ApiOperation(value = "List All Customers Queried by Last Name") @RequestMapping(path = "api/customer/list/:lastName", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<Customer>> listAllCustomersByLastName(@RequestParam String lastName) { List<Customer> customers = customerRepository.findByLastName(lastName); return new ResponseEntity<List<Customer>>(customers, HttpStatus.OK); } @ApiOperation(value = "First Customers Queried by Last Name") @RequestMapping(path = "api/customer/query/:lastName", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Customer> listAllCustomersByLastNameQuery(@RequestParam String lastName) { Customer customers = springMongoService.findByLastName(lastName); return new ResponseEntity<Customer>(customers, HttpStatus.OK); } } <file_sep>/src/main/java/com/app/mongo/service/SpringMongoService.java package com.app.mongo.service; import com.app.mongo.model.Customer; /** * * @author <NAME> * */ public interface SpringMongoService { public Customer findByLastName(String name); } <file_sep>/build.gradle buildscript { ext { springBootVersion = '2.0.3.RELEASE' } repositories { mavenCentral() maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath "gradle.plugin.com.benjaminsproule:swagger-gradle-plugin:1.0.4" } } apply plugin: 'java' apply plugin: 'eclipse-wtp' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' apply plugin: 'war' apply plugin: "com.benjaminsproule.swagger" group = 'com.app.mongo' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() jcenter() } configurations { providedRuntime } dependencies { compile('org.springframework.boot:spring-boot-starter-actuator') compile('org.springframework.boot:spring-boot-starter-amqp') compile('org.springframework.boot:spring-boot-starter-aop') compile('org.springframework.boot:spring-boot-starter-data-mongodb') compile('org.springframework.boot:spring-boot-starter-data-mongodb-reactive') compile('org.springframework.boot:spring-boot-starter-jersey') compile('org.springframework.boot:spring-boot-starter-web') compileOnly('org.projectlombok:lombok') compile('io.springfox:springfox-swagger2:+') compile('io.springfox:springfox-swagger-ui:+') providedRuntime('org.springframework.boot:spring-boot-starter-tomcat') testCompile('org.springframework.boot:spring-boot-starter-test') testCompile('de.flapdoodle.embed:de.flapdoodle.embed.mongo') } defaultTasks 'clean','build','generateSwaggerDocumentation' // clone and npm run start this https://github.com/swagger-api/swagger-editor for generating the client code from yaml generated. swagger { apiSource { springmvc = true locations = [ 'com.app.mongo.rest' ] basePath = '/' outputFormats = ['yaml','json'] info { title = 'Mongo Rest Test' version = '1' description = 'Placeholder description' license { name = 'Apache 2.0' url = 'http://www.apache.org/licenses/LICENSE-2.0.html' } } swaggerDirectory = "${buildDir}/swagger" } }
582e5601cad6e15592d3fc51357279b6845e74b1
[ "Markdown", "Java", "Gradle" ]
4
Markdown
sandeepreddy1945/SpringMongoDemo
a52d3b09eb568203e314fff19da33c2c9c7983ec
9392d28ec459d3bdb0ee51ad32fced1f9ade0806
refs/heads/master
<file_sep># angular5-pwa-example Angular 5 implement PWA like example ## Example use Run `npm install` for install all dependences. Run `ng build --prod --aot` to create the building for prodution. Install http-server npm package `npm install http-server -g` https://www.npmjs.com/package/http-server Start server with the dist folder created before `http-server ./dist/`. And open in localhost http://127.0.0.1:8080/<file_sep>import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpRequest, HttpHeaders, HttpParams } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private http: HttpClient) { } title = 'app'; public people: Array<any>; ngOnInit() { this.getPeople(); } /** * Method to call the sw api */ getPeople() { this.http.get('https://swapi.co/api/people/', { }) .subscribe( response => { this.people = response["results"] ; console.log(this.people); }, error => { console.log(error); }, () => { console.log('call finished'); } ); } }
7ee0d5a82d9dd0cd100c535ccada3c2b1df41fd6
[ "Markdown", "TypeScript" ]
2
Markdown
Pedro4D/angular5-pwa-example
d3057444c20ee5499a5a27785ceae98d3f885520
79cd422ad79d2cfcf7578792f6b0a6a6661c8f82
refs/heads/master
<repo_name>TonyCWeng/node-fun<file_sep>/animal_fun.js const fs = require('fs'); const http = require('http'); const qs = require('querystring'); const cache = {}; // fs.readFile('./animals.txt', 'utf-8', (err, data) => { // if (err) { // console.log(err); // } else { // console.log(data); // var animals = data; // } // }); // fs.readFile('./animals.txt', 'utf-8', (err, data) => { // if (err) { // console.log(err); // } else { // // console.log(data); // var animals = data; // animals.split('\n').filter(animal => animal.startsWith("a")).join('\n'); // console.log(animals); // } // }); // fs.writeFile('./example.txt', 'a', err => { // if (err) { // console.log(err); // } else { // console.log("file successfully written!"); // } // }); // console.log(process.argv[4]); // process.argv should consist of array of two arguments: the absolute // paths of the Node executeable and the file. // function filterAnimals(animals, letter) { // return animals // .split('\n') // .filter(animal => animal.startsWith(letter)) // .join('\n'); // } // var letter = process.argv[2].toUpperCase(); // // fs.readFile('./animals.txt', 'utf-8', (err, data) => { // if (err) { // console.log(err); // return; // } // const animals = filterAnimals(data, letter); // // fs.writeFile(`${letter}_animals.txt`, animals, err => { // if (err) { // console.log(err); // return; // } // console.log(`successfully created ${letter}_animals.txt`); // }); // }); // const server = http.createServer((req, res) => { // res.write('hello world'); // res.end(); // }); // server.listen(8000, () => console.log("I'm listening on port 8000")); const animalServer = http.createServer((req, res) => { const query = req.url.split('?')[1]; if (query !== undefined) { const letter = qs.parse(query).letter.toUpperCase(); if (cache[letter] !== undefined) { res.end(cache[letter]); } } })
e04a430e56015842b0a5ca2d08d15bbfc6b5975c
[ "JavaScript" ]
1
JavaScript
TonyCWeng/node-fun
d85891158870fcc1bc64129b88b25c9ea9f5d1bb
f1020b056cacf034e4899a73c413d5ae83ce41a4
refs/heads/master
<repo_name>VitaliyKotov/priority_queue<file_sep>/index.js const MaxHeap = require('./src/max-heap'); const Node = require('./src/node'); const h = new MaxHeap(); const a = new Node(0,0); const b = new Node(1,1); const c = new Node(2,2); const d = new Node(3,3); const e = new Node(4,4); const f = new Node(5,5); window.a = a; window.b = b; window.c = c; window.d = d; window.e = e; window.f = f; window.h = h;
5e3c2c6e56af0c1fa227200d1858f4531cc1409c
[ "JavaScript" ]
1
JavaScript
VitaliyKotov/priority_queue
58ad28617e9c92ce77613f768145f98dc7ab0dfb
7c4c8813fad387979b4da325dc7c2e0245d4237d
refs/heads/master
<repo_name>rvieracds/RSQ_Assist_Android<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/entities/CreditsSummary.kt package com.codigodelsur.speechrecognition.entities class CreditsSummary(val mMonth: String, val mPotencialCredits: Double, val mCompletedCredits: Double)<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/recyclerAdapters/SearchAdapter.kt package com.codigodelsur.speechrecognition.recyclerAdapters import android.content.Context import android.graphics.Color import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import com.codigodelsur.speechrecognition.R import com.codigodelsur.speechrecognition.ViewSearchesActivity import com.codigodelsur.speechrecognition.database.SullivanDatabase import com.codigodelsur.speechrecognition.entities.Search import com.codigodelsur.speechrecognition.utils.DateUtils import kotlinx.android.synthetic.main.list_item_search.view.* class SearchAdapter(val context: Context, private var mSearches: List<Search>, private var mClickListener: BtnClickListener?) : RecyclerView.Adapter<SearchAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { val search = mSearches[position] holder.searchId = search.id holder.searchDate.text = DateUtils.dateToString(search.date) holder.searchSource.text = search.source holder.searchTerms.text = search.terms holder.searchListener = mClickListener if(search.isCompleted){ holder.search_item.setBackgroundColor(Color.WHITE) } } override fun getItemCount(): Int { return mSearches.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item_search, parent, false)) } fun updateSearches(searches: List<Search>?) { mSearches = searches ?: ArrayList() notifyDataSetChanged() } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var searchId: Long? = null val searchDate = view.search_date val searchSource = view.search_source val searchTerms = view.search_terms val search_item = view.search_item var searchListener: BtnClickListener? = null val button = view.view_topics_button val click = button.setOnClickListener { searchListener?.onBtnClick(searchId) } } open interface BtnClickListener { fun onBtnClick(searchId: Long?) } }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/database/SullivanDatabase.kt package com.codigodelsur.speechrecognition.database import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import android.content.Context import com.codigodelsur.speechrecognition.entities.Search import com.codigodelsur.speechrecognition.entities.Topic @Database(entities = arrayOf(Search::class, Topic::class), version = 1) @TypeConverters(Converters::class) abstract class SullivanDatabase : RoomDatabase() { abstract fun searchDao(): SearchDao abstract fun topicDao(): TopicDao companion object { private var INSTANCE: SullivanDatabase? = null fun getInstance(context: Context): SullivanDatabase? { if (INSTANCE == null) { synchronized(SullivanDatabase::class) { INSTANCE = Room.databaseBuilder(context.applicationContext, SullivanDatabase::class.java, "sullivan.db") .build() } } return INSTANCE } fun destroyInstance() { INSTANCE = null } } }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/recyclerAdapters/CreditAdapter.kt package com.codigodelsur.speechrecognition.recyclerAdapters import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.TextView import com.codigodelsur.speechrecognition.R import com.codigodelsur.speechrecognition.entities.CreditsSummary import kotlinx.android.synthetic.main.list_item_mensual_credits.view.* class CreditAdapter(val context: Context, private var mCreditsSummaries: List<CreditsSummary>, private val mOnCheckListener: CreditsSummaryOnCheckListener) : RecyclerView.Adapter<CreditAdapter.ViewHolder>() { var mIsSelectAllCheckboxChecked = false override fun onBindViewHolder(holder: ViewHolder, position: Int) { val creditsSummary = mCreditsSummaries[position] holder.month.text = creditsSummary.mMonth holder.potencialCredits.text = creditsSummary.mPotencialCredits.toString() holder.completedCredits.text = creditsSummary.mCompletedCredits.toString() holder.checkBox.isChecked = mIsSelectAllCheckboxChecked holder.listener = mOnCheckListener } override fun getItemCount(): Int { return mCreditsSummaries.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item_mensual_credits, parent, false)) } fun updateCreditsSummaries(creditsSummaries: List<CreditsSummary>?) { mCreditsSummaries = creditsSummaries ?: ArrayList() notifyDataSetChanged() } fun selectAll() { mIsSelectAllCheckboxChecked = true notifyDataSetChanged() } fun unselectAll() { mIsSelectAllCheckboxChecked = false notifyDataSetChanged() } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var listener: CreditsSummaryOnCheckListener? = null val month: TextView = view.credits_month val potencialCredits: TextView = view.potencial_credits_count val completedCredits: TextView = view.completed_credits_count val checkBox: CheckBox = view.credits_check_box val c = checkBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) onSummaryChecked() else onSummaryUnchecked() } private fun onSummaryChecked() { listener?.onCreditsSummaryChecked(completedCredits.text.toString().toDouble()) } private fun onSummaryUnchecked() { listener?.onCreditsSummaryUnchecked(completedCredits.text.toString().toDouble()) } } interface CreditsSummaryOnCheckListener { fun onCreditsSummaryChecked(completedCredits: Double) fun onCreditsSummaryUnchecked(completedCredits: Double) } }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/CreditsSummaryActivity.kt package com.codigodelsur.speechrecognition import android.arch.lifecycle.Observer import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.MenuItem import com.codigodelsur.speechrecognition.database.SullivanDatabase import com.codigodelsur.speechrecognition.entities.CreditsSummary import com.codigodelsur.speechrecognition.entities.Search import com.codigodelsur.speechrecognition.recyclerAdapters.CreditAdapter import com.codigodelsur.speechrecognition.utils.DateUtils import kotlinx.android.synthetic.main.activity_credits_summary.* import kotlinx.android.synthetic.main.toolbar.* class CreditsSummaryActivity : AppCompatActivity(), CreditAdapter.CreditsSummaryOnCheckListener { private var mDatabase: SullivanDatabase? = null private var mCreditsCount: Double? = null private lateinit var mRecyclerView: RecyclerView private lateinit var mAdapter: CreditAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_credits_summary) setSupportActionBar(toolbar) title = getString(R.string.credits_summary_screen_name) supportActionBar?.setDisplayHomeAsUpEnabled(true) mCreditsCount = 0.0 loadCreditsCount() mDatabase = SullivanDatabase.getInstance(this) mRecyclerView = findViewById(R.id.credits_summary_recyclerview) mRecyclerView.layoutManager = LinearLayoutManager(this) mAdapter = CreditAdapter(this, ArrayList(), this) mRecyclerView.adapter = mAdapter observeSearches() credits_summary_select_all_checkbox.setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) mAdapter.selectAll() else mAdapter.unselectAll() } get_credits_button.setOnClickListener { navigateToMainScreen() } instructions_button.setOnClickListener{ navigateToInstructionsScreen() } terms_button.setOnClickListener{ navigateToTermsScreen() } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> onBackPressed() } return true } private fun observeSearches() { mDatabase?.searchDao()?.getAll()?.observe(this, Observer { searches: List<Search>? -> val summaries = getSummaries(searches) mAdapter.updateCreditsSummaries(summaries) }) } private fun getSummaries(searches: List<Search>?): List<CreditsSummary> { val summaries = ArrayList<CreditsSummary>() val mensualCredits: HashMap<Int, DoubleArray> = HashMap() searches?.forEach { search -> val monthNumber = search.date.month val credits = if (mensualCredits.containsKey(monthNumber)) mensualCredits[monthNumber] else DoubleArray(2) if (search.isCompleted) { credits!![0] = credits[0].plus(0.5) credits[1] = credits[1].plus(0.5) } else { credits!![0] = credits[0].plus(0.5) } mensualCredits.put(monthNumber, credits) } for ((monthNumber, credits) in mensualCredits) { val monthName = DateUtils.getMonthName(monthNumber) summaries.add(CreditsSummary(mMonth = monthName, mPotencialCredits = credits[0], mCompletedCredits = credits[1])) } return summaries } private fun increaseCreditsCount(value: Double) { mCreditsCount = mCreditsCount?.plus(value) loadCreditsCount() } private fun decreaseCreditsCount(value: Double) { mCreditsCount = mCreditsCount?.minus(value) loadCreditsCount() } private fun loadCreditsCount() { total_credits_selected.text = String.format("%s %s", getString(R.string.total_credits_selected), mCreditsCount) } override fun onCreditsSummaryChecked(completedCredits: Double) { increaseCreditsCount(completedCredits) } override fun onCreditsSummaryUnchecked(completedCredits: Double) { decreaseCreditsCount(completedCredits) } private fun navigateToMainScreen() { val intent = Intent(this, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) finish() } private fun navigateToInstructionsScreen() { val intent = Intent(this, CreditsInstructionsActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) finish() } private fun navigateToTermsScreen() { val intent = Intent(this, CreditsTermsActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) finish() } } <file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/recyclerAdapters/TopicAdapter.kt package com.codigodelsur.speechrecognition.recyclerAdapters import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.codigodelsur.speechrecognition.R import com.codigodelsur.speechrecognition.entities.Topic import com.codigodelsur.speechrecognition.utils.DateUtils import kotlinx.android.synthetic.main.list_item_topic.view.* class TopicAdapter(val context: Context, private var mTopics: List<Topic>) : RecyclerView.Adapter<TopicAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { val topic = mTopics[position] holder.topicId = topic.id holder.topicDate.text = DateUtils.dateToString(topic.date) holder.topicTitle.text = topic.title } override fun getItemCount(): Int { return mTopics.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item_topic, parent, false)) } fun updateTopics(topics: List<Topic>?) { mTopics = topics ?: ArrayList() notifyDataSetChanged() } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var topicId: Long? = null val topicDate = view.topic_date val topicTitle = view.topic_title } }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/CreditsTermsActivity.kt package com.codigodelsur.speechrecognition import android.support.v7.app.AppCompatActivity class CreditsTermsActivity : AppCompatActivity() { }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/utils/DateUtils.kt package com.codigodelsur.speechrecognition.utils import java.text.SimpleDateFormat import java.util.* object DateUtils { @JvmStatic fun dateToString(date: Date): String { val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) return sdf.format(date) } @JvmStatic fun getMonthName(monthNumber: Int): String { return when (monthNumber) { 3 -> { "April 2018" } 4 -> { "May 2018" } 5 -> { "Jun 2018" } else -> { "Unknown" } } } }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/SearchFormActivity.kt package com.codigodelsur.speechrecognition import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import android.view.View.GONE import android.view.View.VISIBLE import com.codigodelsur.speechrecognition.database.DbWorkerThread import com.codigodelsur.speechrecognition.database.SullivanDatabase import kotlinx.android.synthetic.main.activity_search_form.* import kotlinx.android.synthetic.main.toolbar.* class SearchFormActivity : AppCompatActivity() { private var mDatabase: SullivanDatabase? = null private lateinit var mDbWorker: DbWorkerThread override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_search_form) setSupportActionBar(toolbar) mDatabase = SullivanDatabase.getInstance(this) mDbWorker = DbWorkerThread("DbWorkerThread") mDbWorker.start() title = getString(R.string.search_form_screen_name) supportActionBar?.setDisplayHomeAsUpEnabled(true) val searchId = intent.getLongExtra("searchId", 0) next_question_button.setOnClickListener { onNextButtonPressed(searchId) } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> customOnBackPressed() } return true } private fun onNextButtonPressed(searchId: Long) { if (first_form_view.visibility == VISIBLE) { first_form_view.visibility = GONE second_form_view.visibility = VISIBLE } else if (second_form_view.visibility == VISIBLE) { second_form_view.visibility = GONE form_completed_view.visibility = VISIBLE next_question_button.text = getString(R.string.continue_button) } else { setSearchCompleted(searchId) navigateToSearchesScreen() } } private fun customOnBackPressed() { if (first_form_view.visibility == VISIBLE) { onBackPressed() } else if (second_form_view.visibility == VISIBLE) { second_form_view.visibility = GONE first_form_view.visibility = VISIBLE } else { form_completed_view.visibility = GONE second_form_view.visibility = VISIBLE next_question_button.text = getString(R.string.next) } } private fun setSearchCompleted(searchId: Long) { val task = Runnable { mDatabase?.searchDao()?.setSearchCompleted(searchId) } mDbWorker.postTask(task) } private fun navigateToSearchesScreen() { val intent = Intent(this, ViewSearchesActivity::class.java) intent.flags = FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_NEW_TASK startActivity(intent) finish() } private fun navigateToMainScreen() { val intent = Intent(this, MainActivity::class.java) intent.flags = FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_NEW_TASK startActivity(intent) finish() } } <file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/database/TopicDao.kt package com.codigodelsur.speechrecognition.database import android.arch.lifecycle.LiveData import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import com.codigodelsur.speechrecognition.entities.Topic @Dao interface TopicDao { @Query("SELECT * FROM Topic") fun getAll(): LiveData<List<Topic>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(topic: Topic) @Query("DELETE FROM Topic") fun deleteAll() @Query("SELECT * FROM Topic WHERE searchId=:searchId") fun getSearchTopics(searchId: Long): LiveData<List<Topic>> }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/ViewSearchesActivity.kt package com.codigodelsur.speechrecognition import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.codigodelsur.speechrecognition.database.SullivanDatabase import com.codigodelsur.speechrecognition.entities.Search import com.codigodelsur.speechrecognition.recyclerAdapters.SearchAdapter import kotlinx.android.synthetic.main.toolbar.* import android.content.Intent import android.view.MenuItem import kotlinx.android.synthetic.main.activity_view_searches.* class ViewSearchesActivity : AppCompatActivity() , SearchAdapter.BtnClickListener { private var mDatabase: SullivanDatabase? = null private lateinit var mRecyclerView: RecyclerView private lateinit var mAdapter: SearchAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_searches) setSupportActionBar(toolbar) title = getString(R.string.searches_screen_name) supportActionBar?.setDisplayHomeAsUpEnabled(true) mDatabase = SullivanDatabase.getInstance(this) mRecyclerView = findViewById(R.id.searchesList) mRecyclerView.layoutManager = LinearLayoutManager(this) mAdapter = SearchAdapter(this, ArrayList(),this) mRecyclerView.adapter = mAdapter observeSearches() credits_summary_button.setOnClickListener { startActivity(Intent(this, CreditsSummaryActivity::class.java)) } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> onBackPressed() } return true } private fun observeSearches() { mDatabase?.searchDao()?.getAll()?.observe(this, android.arch.lifecycle.Observer { searches: List<Search>? -> mAdapter.updateSearches(searches) }) } override fun onBtnClick(searchId: Long?) { val intent = Intent(this, ViewTopicsActivity::class.java) if(searchId!=null) { intent.putExtra("searchId", searchId) startActivity(intent) } } } <file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/ViewRashesActivity.kt package com.codigodelsur.speechrecognition import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_view_rashes.* class ViewRashesActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_rashes) rashesTitle.text = "Hello Kotlin!" imageDisplay.setImageResource(R.drawable.impetigo); } } <file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/ViewTopicsActivity.kt package com.codigodelsur.speechrecognition import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.MenuItem import com.codigodelsur.speechrecognition.database.SullivanDatabase import com.codigodelsur.speechrecognition.entities.Topic import com.codigodelsur.speechrecognition.recyclerAdapters.TopicAdapter import kotlinx.android.synthetic.main.activity_view_topics.* import kotlinx.android.synthetic.main.toolbar.* class ViewTopicsActivity : AppCompatActivity() { private var mDatabase: SullivanDatabase? = null private lateinit var mRecyclerView: RecyclerView private lateinit var mAdapter: TopicAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_topics) setSupportActionBar(toolbar) title = getString(R.string.topics_screen_name) supportActionBar?.setDisplayHomeAsUpEnabled(true) mDatabase = SullivanDatabase.getInstance(this) mRecyclerView = findViewById(R.id.topicsList) mRecyclerView.layoutManager = LinearLayoutManager(this) mAdapter = TopicAdapter(this, ArrayList()) mRecyclerView.adapter = mAdapter val searchId = intent.getLongExtra("searchId", 0) observeTopics(searchId) completeFormButton.setOnClickListener { navigateToFormScreen(searchId) } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> onBackPressed() } return true } private fun observeTopics(searchId: Long) { mDatabase?.topicDao()?.getSearchTopics(searchId)?.observe(this, android.arch.lifecycle.Observer { topics: List<Topic>? -> mAdapter.updateTopics(topics) }) } private fun navigateToFormScreen(searchId: Long) { val intent = Intent(this, SearchFormActivity::class.java) intent.putExtra("searchId", searchId) startActivity(intent) } }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/CreditsInstructionsActivity.kt package com.codigodelsur.speechrecognition import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.toolbar.* class CreditsInstructionsActivity : AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_credits_instructions) setSupportActionBar(toolbar) title = getString(R.string.credits_instructions_screen_name) supportActionBar?.setDisplayHomeAsUpEnabled(true) } }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/entities/Topic.kt package com.codigodelsur.speechrecognition.entities import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.ForeignKey import android.arch.persistence.room.ForeignKey.CASCADE import android.arch.persistence.room.PrimaryKey import java.util.* @Entity(tableName = "Topic", foreignKeys = arrayOf(ForeignKey(entity = Search::class, parentColumns = arrayOf("id"), childColumns = arrayOf("searchId"), onDelete = CASCADE))) data class Topic( @PrimaryKey(autoGenerate = true) val id: Long?, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "date") val date: Date, var searchId: Long? )<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/database/SearchDao.kt package com.codigodelsur.speechrecognition.database import android.arch.lifecycle.LiveData import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy.REPLACE import android.arch.persistence.room.Query import com.codigodelsur.speechrecognition.entities.Search @Dao interface SearchDao { @Query("SELECT * FROM Search") fun getAll(): LiveData<List<Search>> @Query("SELECT * FROM Search WHERE id=:searchId") fun getSearchById(searchId: Long): LiveData<Search> @Query("SELECT * FROM Search WHERE is_completed = 0") fun getIncompletedSearches(): LiveData<List<Search>> @Insert(onConflict = REPLACE) fun insert(search: Search): Long @Query("DELETE FROM Search") fun deleteAll() @Query("UPDATE Search SET is_completed = 1 WHERE id=:searchId") fun setSearchCompleted(searchId: Long) }<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/MyocardialActivity.kt package com.codigodelsur.speechrecognition import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import kotlinx.android.synthetic.main.toolbar.* class MyocardialActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_myocardial) setSupportActionBar(toolbar) title = null supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> onBackPressed() } return true } } <file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/entities/Search.kt package com.codigodelsur.speechrecognition.entities import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import java.util.* @Entity(tableName = "Search") data class Search( @PrimaryKey(autoGenerate = true) val id: Long?, @ColumnInfo(name = "source") val source: String, @ColumnInfo(name = "terms") val terms: String, @ColumnInfo(name = "date") val date: Date, @ColumnInfo(name = "is_completed") val isCompleted: Boolean = false )<file_sep>/app/src/main/java/com/codigodelsur/speechrecognition/MainActivity.kt package com.codigodelsur.speechrecognition import android.app.Activity import android.app.SearchManager import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Handler import android.speech.RecognizerIntent import android.speech.tts.TextToSpeech import android.support.v7.app.AppCompatActivity import android.util.Log import com.codigodelsur.speechrecognition.database.DbWorkerThread import com.codigodelsur.speechrecognition.database.SullivanDatabase import com.codigodelsur.speechrecognition.entities.Search import com.codigodelsur.speechrecognition.entities.Topic import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.toolbar.* import java.util.* class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener { companion object { private const val REQUEST_SPEECH_RECOGNIZER = 3000 private const val TAG = "MainActivity" } private var mDatabase: SullivanDatabase? = null private lateinit var mDbWorker: DbWorkerThread private lateinit var mTopic: String private var myocardialTitle: String? = null private var eyeExamTitle: String? = null private var scrotalTitle: String? = null private var textToSpeech: TextToSpeech? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) mDatabase = SullivanDatabase.getInstance(this) mDbWorker = DbWorkerThread("DbWorkerThread") mDbWorker.start() observeDatabase() title = getString(R.string.app_name) myocardialTitle = getString(R.string.myocardial_title) eyeExamTitle = getString(R.string.eye_title) scrotalTitle = getString(R.string.scrotal_title) textToSpeech = TextToSpeech(this, this) textToSpeech?.language = Locale.US //DESCOMENTAR PARA CORRER EN EL EMULADOR/////////////////////////////////////////// val search = Search(id = null, terms = "Eye", date = Date(), source = "WEB") val activity = resolveActivity("Eye") if (activity != null) { val topic = Topic(id = null, title = mTopic, date = Date(), searchId = null) insertSearchAndTopicInDb(search, topic) Handler().postDelayed({ speak(getString(R.string.speech_success)) startActivity(Intent(this, activity)) }, 3000) } //////////////////////////////////////////////////////////////////////////////// searchButton.setOnClickListener { startSpeechRecognizer() } searchesButton.setOnClickListener { startActivity(Intent(this, ViewSearchesActivity::class.java)) } rashesButton.setOnClickListener { startActivity(Intent(this, ViewRashesActivity::class.java)) } } override fun onInit(p0: Int) { Log.d(TAG, "Text to speech initialized") } override fun onStart() { super.onStart() startSpeechRecognizer() } private fun speak(text: String) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { textToSpeech?.speak(text, TextToSpeech.QUEUE_ADD, null, null) } else { textToSpeech?.speak(text, TextToSpeech.QUEUE_ADD, null) } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) handleSearchIntent(intent) } private fun handleSearchIntent(intent: Intent?): Boolean { if ("com.google.android.gms.actions.SEARCH_ACTION" == intent?.action) { speak(getString(R.string.speech_searching)) val query = intent.getStringExtra(SearchManager.QUERY) val activity = resolveActivity(query) return if (activity != null) { Handler().postDelayed({ speak(getString(R.string.speech_success)) startActivity(Intent(this, activity)) }, 3000) true } else { Handler().postDelayed({ speak(getString(R.string.speech_error)) }, 3000) false } } return false } private fun startSpeechRecognizer() { val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_question)) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US") startActivityForResult(intent, REQUEST_SPEECH_RECOGNIZER) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_SPEECH_RECOGNIZER) { if (resultCode == Activity.RESULT_OK) { speak(getString(R.string.speech_searching)) val results = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) if (results != null) { results.forEach { result -> val search = Search(id = null, terms = result, date = Date(), source = "WEB") val activity = resolveActivity(result) if (activity != null) { val topic = Topic(id = null, title = mTopic, date = Date(), searchId = null) insertSearchAndTopicInDb(search, topic) Handler().postDelayed({ speak(getString(R.string.speech_success)) startActivity(Intent(this, activity)) }, 3000) return } } Handler().postDelayed({ speak(getString(R.string.speech_error)) }, 3000) } } } } private fun resolveActivity(recognizedText: String): Class<*>? { val words = recognizedText.split(" ") loop@ for (word in words) { Log.d(TAG, word) when { myocardialTitle?.contains(word, true) ?: false -> { mTopic = myocardialTitle as String return MyocardialActivity::class.java } eyeExamTitle?.contains(word, true) ?: false -> { mTopic = eyeExamTitle as String return EyeExamActivity::class.java } scrotalTitle?.contains(word, true) ?: false -> { mTopic = scrotalTitle as String return ScrotalActivity::class.java } } } return null } private fun insertSearchAndTopicInDb(search: Search, topic: Topic) { val task = Runnable { val searchId = mDatabase?.searchDao()?.insert(search) topic.searchId = searchId mDatabase?.topicDao()?.insert(topic) } mDbWorker.postTask(task) } private fun observeDatabase() { mDatabase?.searchDao()?.getAll()?.observe(this, android.arch.lifecycle.Observer { searches: List<Search>? -> for (search in searches!!) Log.d("Database", "Search| Id: ${search.id}, Terms: ${search.terms}, Date: ${search.date}, IsComplete: ${search.isCompleted}") }) mDatabase?.topicDao()?.getAll()?.observe(this, android.arch.lifecycle.Observer { topics: List<Topic>? -> topics?.forEach { topic -> Log.d("Database", "Topic| Id: ${topic.id}, Title: ${topic.title}, Date: ${topic.date}, searchId: ${topic.searchId}") } }) } override fun onDestroy() { super.onDestroy() textToSpeech?.shutdown() } }
a96498e18b9cc7b4f4cd8fa4b593a4d5d39e53e9
[ "Kotlin" ]
19
Kotlin
rvieracds/RSQ_Assist_Android
0209fb3662aac7915d93041c21260324efaa29bd
8d2e4451a26ef177f90ea99ef25635151adad640
refs/heads/main
<repo_name>YMY1666527646/ReClass.Net<file_sep>/ReClass.NET/Controls/DrawContextRequestEventArgs.cs using System; using xxxx.Memory; using xxxx.Nodes; using xxxx.UI; namespace xxxx.Controls { public class DrawContextRequestEventArgs : EventArgs { public DateTime CurrentTime { get; set; } = DateTime.UtcNow; public Settings Settings { get; set; } public IconProvider IconProvider { get; set; } public RemoteProcess Process { get; set; } public MemoryBuffer Memory { get; set; } public BaseNode Node { get; set; } public IntPtr BaseAddress { get; set; } } public delegate void DrawContextRequestEventHandler(object sender, DrawContextRequestEventArgs args); }
34ce0f404015fb79a79729ef9b4dc56094bd1f4c
[ "C#" ]
1
C#
YMY1666527646/ReClass.Net
569d19a927dd49d7bf911c6ca3051d10b3143319
0706cb76645a8a10909fd984a42e716df0dd7784
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace AGC { public class cTransaction: cBase { public cTransaction() { } #region "GET" public DataTable GET_BRANCH_STOCK(string _branchCode) { DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spGET_BRANCH_STOCK]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } return dt; } #region "SALES SECTION" public DataTable GET_BRANCH_SALES_BY_DATE(DateTime _salesDate) { DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spGET_SALES_BY_DATE]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SALESDATE", _salesDate); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } return dt; } public DataTable GET_BRANCH_TOP_SALES(string _itemCode, DateTime _startDate, DateTime _endDate) { DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spGET_TOP_BRANCH_SALES]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@STARTDATE", _startDate); cmd.Parameters.AddWithValue("@ENDDATE", _endDate); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } return dt; } public void INSERT_BRANCH_SALES(string _branchCode, string _salesNum, DateTime _salesDate, string _remarks, string _itemCode, int _quantity) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spINSERT_BRANCH_SALES]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cmd.Parameters.AddWithValue("@SALESNUM", _salesNum); cmd.Parameters.AddWithValue("@SALESDATE", _salesDate); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@QUANTITY", _quantity); cn.Open(); cmd.ExecuteNonQuery(); } } } #endregion /*BRANCH SALES SECTION ** */ public bool CHECK_EXIST_DELIVERY_ENTRY(string _branchCode) { bool x; using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[CHECK_EXIST_BRANCH_DELIVERY_ENTRY]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cn.Open(); x = (bool)cmd.ExecuteScalar(); } return x; } } public DataTable GET_BRANCH_DELIVERY(DateTime _deliveryDate) { DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spGET_BRANCH_DELIVERY]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DELIVERYDATE", _deliveryDate); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } return dt; } public DataTable GET_DELIVERY_NOT_YET_POSTED() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[TRANSACTION].[spGET_DELIVERY_NOT_YET_POSTED]"); return dt; } public DataTable GET_DELIVERY_FOR_POSTING() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[TRANSACTION].[spGET_DELIVERY_FOR_POSTING]"); return dt; } #endregion public void INSERT_BRANCH_DELIVERY(string _branchCode, string _deliveryNum, DateTime _deliveryDate, string _remarks, string _itemCode, int _quantity) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spINSERT_BRANCH_DELIVERY]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCH_CODE", _branchCode); cmd.Parameters.AddWithValue("@DELIVERY_NUM", _deliveryNum); cmd.Parameters.AddWithValue("@DELIVERY_DATE", _deliveryDate); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cmd.Parameters.AddWithValue("@ITEM_CODE", _itemCode); cmd.Parameters.AddWithValue("@QUANTITY", _quantity); cn.Open(); cmd.ExecuteNonQuery(); } } } public void CANCEL_BRANCH_DELIVERY(string _deliveryNum) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spCANCEL_BRANCH_DELIVERY]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DELIVERYNUM", _deliveryNum); cn.Open(); cmd.ExecuteNonQuery(); } } } public void UPDATE_BRANCH_DELIVERY_POSTING(string _deliveryNum) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spUPDATE_BRANCH_DELIVERY_POSTED]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DELIVERYNUM", _deliveryNum); cn.Open(); cmd.ExecuteNonQuery(); } } } //UPDATE LIST OF ITEM IN PARTICULAR DELIVERY RECIEPT THAT DOESN'T POSTED YET. public void UPDATE_DELIVERY_ADJUSTMENT(string _deliveryNum, string _itemCode, int _quantity) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spUPDATE_BRANCH_DELIVERY_ADJUSTMENT]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DELIVERYNUM", _deliveryNum); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@QUANTITY", _quantity); cn.Open(); cmd.ExecuteNonQuery(); } } } public void UPDATE_MINIMUM_STOCK_LEVEL(string _branchCode, string _itemCode, int _stockLevel) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spUPDATE_BRANCH_STOCK_MIN_LEVEL]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@STOCKLEVEL", _stockLevel); cn.Open(); cmd.ExecuteNonQuery(); } } } public void INSERT_BRANCH_RETURN_ITEM(string _branchCode, string _delReturnNum, DateTime _returnDate, string _remarks, string _itemCode, int _quantity) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spINSERT_BRANCH_DELIVERY_RETURN]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cmd.Parameters.AddWithValue("@DELRETURNNUM", _delReturnNum); cmd.Parameters.AddWithValue("@RETURNDATE", _returnDate); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@QUANTITY", _quantity); cn.Open(); cmd.ExecuteNonQuery(); } } } #region "INVENTORY SECTION /*USAGE CONDIMENTS ** */ public DataTable GET_STOCK_USAGE_BY_DATE(DateTime _usageDate) { DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[INVENTORY].[spGET_STOCK_USAGE_BY_DATE]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@USAGEDATE", _usageDate); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } return dt; } public bool CHECK_EXIST_STOCK_ADJUSTMENT_ENTRY(string _branchCode) { bool x; using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[CHECK_EXIST_BRANCH_STOCK_ADJUSTMENT_ENTRY]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cn.Open(); x = (bool)cmd.ExecuteScalar(); } return x; } } public DataTable GET_STOCK_ADJUSTMENT_FOR_POSTING() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[TRANSACTION].[spGET_ADJUSTMENT_FOR_POSTING]"); return dt; } public DataTable GET_STOCK_ADJUSTMENT_ITEM_NOT_YET_POSTED() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[TRANSACTION].[spGET_ADJUSTMENT_NOT_YET_POSTED]"); return dt; } public void UPDATE_BRANCH_STOCK_ADJUSTMENT_POSTING(string _adjustmentNum) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spUPDATE_BRANCH_STOCK_ADJUSTMENT_POSTED]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ADJUSTMENTNUM", _adjustmentNum); cn.Open(); cmd.ExecuteNonQuery(); } } } public void INSERT_CONSUME_BRANCH_ITEM(string _branchCode, string _consumeNum, DateTime _consumeDate, string _remarks, string _itemCode, int _quantity) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[INVENTORY].[spINSERT_STOCK_CONSUME]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cmd.Parameters.AddWithValue("@CONSUMENUM", _consumeNum); cmd.Parameters.AddWithValue("@CONSUMEDATE", _consumeDate); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@QUANTITY", _quantity); cn.Open(); cmd.ExecuteNonQuery(); } } } public void INSERT_UPDATE_BRANCH_ADJUSTMENT_STOCK(string _branchCode, string _stockAdjustmentNum,string _adjustmentCode, DateTime _adjustmentDate, string _remarks, string _itemCode, int _quantity) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spINSERT_UPDATE_BRANCH_STOCK_ADJUSTMENT]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cmd.Parameters.AddWithValue("@STOCKADJUSTMENTNUM", _stockAdjustmentNum); cmd.Parameters.AddWithValue("@ADJUSTMENTCODE", _adjustmentCode); cmd.Parameters.AddWithValue("@ADJUSTMENTDATE", _adjustmentDate); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@QUANTITY", _quantity); cn.Open(); cmd.ExecuteNonQuery(); } } } //CANCEL ADJUSTMENT public void CANCEL_STOCK_ADJUSTMENT(string _adjustmentNum) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spCANCEL_ADJUSTMENT]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@STOCKADJUSTMENTNUM", _adjustmentNum); cn.Open(); cmd.ExecuteNonQuery(); } } } public void INSERT_BRANCH_TRANSFER_INVENTORY(string _branchCodeSource, string _branchCodeDestination, string _transferNum, DateTime _transferDate, string _remarks, string _itemCode, int _quantity) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[TRANSACTION].[spINSERT_BRANCH_TRANSFER]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("BRANCHCODESOURCE", _branchCodeSource); cmd.Parameters.AddWithValue("BRANCHCODEDESTINATION", _branchCodeDestination); cmd.Parameters.AddWithValue("@TRANSFERNUM", _transferNum); cmd.Parameters.AddWithValue("@TRANSFERDATE", _transferDate); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@QUANTITY", _quantity); cn.Open(); cmd.ExecuteNonQuery(); } } } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class BranchMaster : System.Web.UI.Page { cMaster oMaster = new cMaster(); cUtil oUtil = new cUtil(); private static bool B_ACTION = false; private static int machEquip_ID = 0; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Display_Branch_Area(); Display_Supervisors_List(); Display_Branch_Incharge_List(); Display_Partners_List(); Display_Branch_List(); Display_Mode_Payment_List(); Display_Status_List(); Display_Days_List(); panelBranchInput.Visible = false; } } protected void lnkNew_Click(object sender, EventArgs e) { panelBranchInput.Visible = true; panelBranchList.Visible = false; Clear_Inputs(); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertMessage').hide();$('#alertMessageME').hide();$('#successMessageME').hide();</script>", false); lblContentText.Text = "Create New Branch Information"; B_ACTION = false; panMachineEquipment.Enabled = false; //This will clear list //Display_Branch_Machine_Equipment_List(txtBranchCode.Text); gvMachineEquipment.DataSource = null; gvMachineEquipment.DataBind(); } protected void lnkCancel_Click(object sender, EventArgs e) { panBranchEditName.Visible = false; lblBranchEditName.Visible = false; Response.Redirect(Request.RawUrl); } private void Display_Branch_Area() { DataTable dt = oUtil.GET_BRANCH_AREA(); ddBranchArea.DataSource = dt; ddBranchArea.DataTextField = dt.Columns["AreaName"].ToString(); ddBranchArea.DataValueField = dt.Columns["AreaID"].ToString(); ddBranchArea.DataBind(); ddBranchArea.Items.Insert(0, new ListItem("--SELECT AREA--")); } private void Display_Supervisors_List() { DataTable dt = oUtil.GET_SUPERVISOR_LIST(); ddSupervisor.DataSource = dt; ddSupervisor.DataTextField = dt.Columns["SupervisorName"].ToString(); ddSupervisor.DataValueField = dt.Columns["SupervisorID"].ToString(); ddSupervisor.DataBind(); ddSupervisor.Items.Insert(0, new ListItem("--SELECT SUPERVISOR--")); } private void Display_Partners_List() { DataTable dt = oMaster.GET_PARTNERS_LIST(); ddPartner.DataSource = dt; ddPartner.DataTextField = dt.Columns["PartnerName"].ToString(); ddPartner.DataValueField = dt.Columns["PartnerCode"].ToString(); ddPartner.DataBind(); ddPartner.Items.Insert(0, new ListItem("--SELECT PARTNER--")); } private void Display_Branch_Incharge_List() { DataTable dt = oUtil.GET_BRANCH_INCHARGE_LIST(); ddPersonIncharge.DataSource = dt; ddPersonIncharge.DataTextField = dt.Columns["branchInchargeName"].ToString(); ddPersonIncharge.DataValueField = dt.Columns["branchInchargeID"].ToString(); ddPersonIncharge.DataBind(); } private void Display_Mode_Payment_List() { DataTable dt = oUtil.GET_MODE_PAYMENT_LIST(); ddModePayment.DataSource = dt; ddModePayment.DataTextField = dt.Columns["paymentModeName"].ToString(); ddModePayment.DataValueField = dt.Columns["paymentModeCode"].ToString(); ddModePayment.DataBind(); ddModePayment.Items.Insert(0, new ListItem("")); } private void Display_Status_List() { DataTable dt = oUtil.GET_STATUS_LIST(); ddStatus.DataSource = dt; ddStatus.DataTextField = dt.Columns["statusName"].ToString(); ddStatus.DataValueField = dt.Columns["statusCode"].ToString(); ddStatus.DataBind(); } private void Display_Days_List() { DataTable dt = oUtil.GET_DAYS_LIST(); ddPaymentDay.DataSource = dt; ddPaymentDay.DataTextField = dt.Columns["day"].ToString(); ddPaymentDay.DataValueField = dt.Columns["day"].ToString(); ddPaymentDay.DataBind(); ddPaymentDay.Items.Insert(0, new ListItem("0")); } private void Display_Branch_List() { DataTable dt = oMaster.GET_BRANCH_LIST(); gvBranchList.DataSource = dt; gvBranchList.DataBind(); } private void Clear_Inputs() { txtBranchCode.Text = ""; txtBranchName.Text = ""; txtAddress.Text = ""; txtContactNumber.Text = ""; txtOpeningDate.Text = ""; txtRemarks.Text = ""; txtLessorName.Text = ""; txtBranchCode.Enabled = true; txtBranchCode.Focus(); ddStatus.Enabled = false; ddBranchArea.SelectedIndex = 0; ddPersonIncharge.SelectedIndex = 0; ddPartner.SelectedIndex = 0; ddSupervisor.SelectedIndex = 0; ddModePayment.SelectedIndex = 0; } protected void lnkSaveBranch_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtBranchCode.Text) || string.IsNullOrEmpty(txtBranchName.Text) || string.IsNullOrEmpty(txtOpeningDate.Text) || ddBranchArea.SelectedIndex == 0 || ddSupervisor.SelectedIndex == 0 || ddPartner.SelectedIndex == 0) { ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertMessage').fadeToggle(2000);</script>", false); } else { DateTime dtOpening = Convert.ToDateTime(txtOpeningDate.Text); int areaID = Convert.ToInt32(ddBranchArea.SelectedValue); int inchargeID = 1; int supervisorID = Convert.ToInt32(ddSupervisor.SelectedValue); //if (ddPersonIncharge.SelectedIndex != 0) //{ inchargeID = Convert.ToInt32(ddPersonIncharge.SelectedValue); //} //Check action if (B_ACTION == false) { oMaster.INSERT_BRANCH(txtBranchCode.Text, txtBranchName.Text, txtAddress.Text, txtContactNumber.Text, inchargeID, supervisorID, ddPartner.SelectedValue, dtOpening, areaID, txtLessorName.Text, ddModePayment.SelectedValue.ToString(), Convert.ToInt32(ddPaymentDay.Text), txtRemarks.Text); lblSuccessMessage.Text = txtBranchName.Text.ToUpper() + " successfully created."; } else { //Status bool bStatus; if (ddStatus.SelectedIndex == 0) {bStatus = true;} else { bStatus = false; } oMaster.UPDATE_BRANCH(txtBranchCode.Text, txtBranchName.Text, txtAddress.Text, txtContactNumber.Text, inchargeID, supervisorID, ddPartner.SelectedValue, dtOpening, areaID, txtLessorName.Text, ddModePayment.SelectedValue.ToString(), Convert.ToInt32(ddPaymentDay.Text),txtRemarks.Text, bStatus); lblSuccessMessage.Text = txtBranchName.Text.ToUpper() + " successfully updated."; } Clear_Inputs(); Display_Branch_List(); //Response.Redirect(Request.RawUrl); panelBranchInput.Visible = false; panelBranchList.Visible = true; ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertMessage').hide();$('#modalSuccess').modal('show');</script>", false); } } protected void lnkCancelNewBranch_Click(object sender, EventArgs e) { Clear_Inputs(); panelBranchInput.Visible = false; panelBranchList.Visible = true; panBranchEditName.Visible = false; } protected void gvBranchList_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); //IS_ACTION_CREATE = false; //panelInputs.Enabled = true; txtSearchBranch.Text = ""; panelBranchList.Visible = false; panelBranchInput.Visible = true; ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertMessage').hide();$('#alertMessageME').hide();$('#successMessageME').hide();</script>", false); txtBranchCode.Enabled = false; txtBranchName.Focus(); ddStatus.Enabled = true; txtBranchName.Text = row.Cells[2].Text; txtBranchCode.Text = row.Cells[1].Text; Display_Selected_Branch(row.Cells[1].Text); B_ACTION = true; lblContentText.Text = "<span class=\"fas fa-store-alt\"></span> Update Information" ; panBranchEditName.Visible = true; lblBranchEditName.Text = txtBranchName.Text; panMachineEquipment.Enabled = true; Display_Branch_Machine_Equipment_List(txtBranchCode.Text); } } private void Display_Selected_Branch(string _branchCode) { DataTable dt = new DataTable(); dt = oMaster.GET_BRANCH_LIST(); DataView dv = dt.DefaultView; dv.RowFilter = "BranchCode ='" + _branchCode + "'"; if (dv.Count > 0) { DataRowView dvr = dv[0]; txtAddress.Text = dvr.Row["branchAddress"].ToString(); txtContactNumber.Text = dvr.Row["branchContactNumbers"].ToString(); txtOpeningDate.Text = Convert.ToDateTime(dvr.Row["OpeningDate"]).ToShortDateString(); txtLessorName.Text = dvr.Row["lessorName"].ToString(); txtRemarks.Text = dvr.Row["Remarks"].ToString(); if ((bool)dvr.Row["isActive"]) { ddStatus.SelectedIndex = 0; } else { ddStatus.SelectedIndex = 1; } if (!string.IsNullOrEmpty(ddBranchArea.SelectedValue = dvr.Row["areaID"].ToString())) { ddBranchArea.SelectedValue = dvr.Row["areaID"].ToString(); } if (!string.IsNullOrEmpty(dvr.Row["partnerCode"].ToString())) { ddPartner.SelectedValue = dvr.Row["partnerCode"].ToString(); } if (!string.IsNullOrEmpty(dvr.Row["supervisorID"].ToString())) { ddSupervisor.SelectedValue = dvr.Row["supervisorID"].ToString(); } if (!string.IsNullOrEmpty(dvr.Row["branchInchargeID"].ToString())) { ddPersonIncharge.SelectedValue = dvr.Row["branchInchargeID"].ToString(); } if (!string.IsNullOrEmpty(dvr.Row["modePaymentCode"].ToString())) { ddModePayment.SelectedValue = dvr.Row["modePaymentCode"].ToString(); } if ((int)dvr.Row["paymentDay"] != 0) { ddPaymentDay.SelectedValue = dvr.Row["paymentDay"].ToString(); } else { ddPaymentDay.SelectedIndex = 0; } } } private void Display_Branch_Machine_Equipment_List(string _branchCode) { DataTable dt = oMaster.GET_BRANCH_MACHINE_EQUIPMENT_LIST(); DataView dv = dt.DefaultView; dv.RowFilter = "BranchCode ='" + _branchCode + "'"; gvMachineEquipment.DataSource = dv; gvMachineEquipment.DataBind(); } //Clear Machine Equipment private void clearMachineEquipmentInput() { // ddMachineEquipment.SelectedIndex = 0; //txtMEDescription.Text = ""; //txtSerial.Text = ""; //txtDateIssue.Text = ""; } protected void gvMachineEquipment_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex; gvMachineEquipment.EditIndex = rowIndex; Display_Branch_Machine_Equipment_List(txtBranchCode.Text); //Machine Equipment string machEquipCode = ((Label)gvMachineEquipment.Rows[rowIndex].FindControl("lblMachEquipCode")).Text; DropDownList ddMachineEquipName = ((DropDownList)gvMachineEquipment.Rows[rowIndex].FindControl("ddMachineEquipName")); DataTable dtME = oUtil.GET_MACHINE_EQUIPMENT_LIST(); ddMachineEquipName.DataSource = dtME; ddMachineEquipName.DataTextField = dtME.Columns["MachEquipName"].ToString(); ddMachineEquipName.DataValueField = dtME.Columns["MachEquipCode"].ToString(); ddMachineEquipName.DataBind(); ddMachineEquipName.SelectedValue = machEquipCode; ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertMessageME').hide();$('#successMessageME').hide();</script>", false); } else if (e.CommandName == "Create") { DropDownList ddMachineEquipment = ((DropDownList)gvMachineEquipment.HeaderRow.FindControl("ddMachineEquipment")); TextBox txtAdditionalDescription = ((TextBox)gvMachineEquipment.HeaderRow.FindControl("txtMEDescription")); TextBox txtSerial = ((TextBox)gvMachineEquipment.HeaderRow.FindControl("txtSerial")); TextBox txtDateIssue = ((TextBox)gvMachineEquipment.HeaderRow.FindControl("txtDateIssue")); //Validate if (!string.IsNullOrEmpty(txtDateIssue.Text)) { DateTime dtDateIssue = Convert.ToDateTime(txtDateIssue.Text); oMaster.INSERT_BRANCH_MACHINE_EQUIPMENT(txtBranchCode.Text, ddMachineEquipment.SelectedValue, txtAdditionalDescription.Text, txtSerial.Text, dtDateIssue); //Clear input ddMachineEquipment.SelectedIndex = 0; txtAdditionalDescription.Text = ""; txtSerial.Text = ""; txtDateIssue.Text = ""; Display_Branch_Machine_Equipment_List(txtBranchCode.Text); ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>$('#successMessageME').fadeToggle(2000);$('#alertMessageME').hide();</script>", false); lblSuccessMessageText.Text = "New Machine and Equipment successfully added."; } else { ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>$('#alertMessageME').fadeToggle(2000);$('#successMessageME').hide();</script>", false); lblAlertMessageText.Text = "Please fill up required input"; } } else if (e.CommandName == "CancelEdit") { gvMachineEquipment.EditIndex = -1; Display_Branch_Machine_Equipment_List(txtBranchCode.Text); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertMessageME').hide();$('#successMessageME').hide();</script>", false); } else if (e.CommandName == "DeleteRow") { machEquip_ID = Convert.ToInt32(e.CommandArgument); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertMessageME').hide();$('#successMessageME').hide();$('#modalConfirmDelete').modal('show');</script>", false); } //Update else if (e.CommandName == "UpdateRow") { int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex; int id = Convert.ToInt32(e.CommandArgument); string machEquipCode = ((DropDownList)gvMachineEquipment.Rows[rowIndex].FindControl("ddMachineEquipName")).SelectedValue; string addtDescription = ((TextBox)gvMachineEquipment.Rows[rowIndex].FindControl("txtDescription")).Text; string serial = ((TextBox)gvMachineEquipment.Rows[rowIndex].FindControl("txtSerial")).Text; string dateIssue = ((TextBox)gvMachineEquipment.Rows[rowIndex].FindControl("txtDateIssue")).Text; if (!string.IsNullOrEmpty(dateIssue)) { DateTime dtDateIssue = Convert.ToDateTime(dateIssue); oMaster.UPDATE_BRANCH_MACHINE_EQUIPMENT(id, machEquipCode, addtDescription, serial, dtDateIssue); gvMachineEquipment.EditIndex = -1; Display_Branch_Machine_Equipment_List(txtBranchCode.Text); ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>$('#alertMessageME').hide();$('#successMessageME').fadeToggle(2000);</script>", false); lblSuccessMessageText.Text = "Machine and Equipment successfully updated."; } else { ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>$('#alertMessageME').fadeToggle(2000);$('#successMessageME').hide();</script>", false); lblAlertMessageText.Text = "Please fill up required input."; } } } protected void lnkCancelMachineEquipment_Click(object sender, EventArgs e) { Response.Redirect(Request.RawUrl); } protected void gvMachineEquipment_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { DropDownList ddMachineEquipName = (e.Row.FindControl("ddMachineEquipment") as DropDownList); DataTable dtME = oUtil.GET_MACHINE_EQUIPMENT_LIST(); ddMachineEquipName.DataSource = dtME; ddMachineEquipName.DataTextField = dtME.Columns["MachEquipName"].ToString(); ddMachineEquipName.DataValueField = dtME.Columns["MachEquipCode"].ToString(); ddMachineEquipName.DataBind(); } } protected void lnkConfirmDelete_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtDeletedRemarks.Text)) { oMaster.DELETE_BRANCH_MACHINE_EQUIPMENT(machEquip_ID, txtDeletedRemarks.Text); ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>$('#alertMessageME').hide();$('#successMessageME').hide();$('#modalConfirmDelete').modal('hide');$('body').removeClass('modal-open');$('.modal-backdrop').remove();</script>", false); gvMachineEquipment.EditIndex = -1; Display_Branch_Machine_Equipment_List(txtBranchCode.Text); txtDeletedRemarks.Text = ""; } else { ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>$('#alertMessageME').hide();$('#successMessageME').hide();$('#modalConfirmDelete').modal('show');</script>", false); } } protected void lnkCloseDeleteMachineEquipment_Click(object sender, EventArgs e) { ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>$('#alertMessageME').hide();$('#successMessageME').hide();$('#modalConfirmDelete').modal('hide');$('body').removeClass('modal-open');$('.modal-backdrop').remove();</script>", false); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using System.Data; namespace AGC { public partial class repSalesSummary : System.Web.UI.Page { ReportDocument oReportDocument = new ReportDocument(); cSystem oSystem = new cSystem(); cMaster oMaster = new cMaster(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { txtStartDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); txtEndDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); displayBranchList(); } displayReport(); } private void displayBranchList() { DataTable dt = oMaster.GET_BRANCH_LIST(); ddBranchList.DataSource = dt; ddBranchList.DataTextField = dt.Columns["branchName"].ToString(); ddBranchList.DataValueField = dt.Columns["branchCode"].ToString(); ddBranchList.DataBind(); ddBranchList.Items.Insert(0, new ListItem("--Select Branch--")); } private void displayReport() { //IDENTIFY WHAT TYPE OF REPORT NEED TO DISPLAY DateTime dtStartDate = Convert.ToDateTime(txtStartDate.Text); DateTime dtEndDate = Convert.ToDateTime(txtEndDate.Text); ParameterRangeValue myRangeValue = new ParameterRangeValue(); myRangeValue.StartValue = dtStartDate; //txtDateStart.Text; myRangeValue.EndValue = dtEndDate; if (ddBranchList.SelectedIndex > 0) { oReportDocument.Load(Server.MapPath("~/Reports/repBranchSalesSummary.rpt")); oReportDocument.SetParameterValue("paramBranchCode", ddBranchList.SelectedValue); } else { oReportDocument.Load(Server.MapPath("~/Reports/repSalesSummaryTotal.rpt")); } oReportDocument.SetParameterValue("paramDateRange", myRangeValue); oReportDocument.SetDatabaseLogon("sa", "p@ssw0rd"); // Supply user credentials CrystalReportViewer1.ReportSource = oReportDocument; } protected void lnkPreview_Click(object sender, EventArgs e) { displayReport(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class BranchDeliveryPosting : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ViewState["BRANCHCODE"] = ""; DisplayForPosting(); // txtReturnDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); } } #region "Local Function" private void DisplayForPosting() { DataTable dt = oTransaction.GET_DELIVERY_FOR_POSTING(); gvDeliveryForPostingList.DataSource = dt; gvDeliveryForPostingList.DataBind(); } private void DisplayDeliveryDetails(string _deliveryNum) { DataTable dt = oTransaction.GET_DELIVERY_NOT_YET_POSTED(); DataView dv = dt.DefaultView; dv.RowFilter = "deliveryNum = '" + _deliveryNum + "'"; gvDRList.DataSource = dv; gvDRList.DataBind(); } #endregion #region "PRINT AREA" private void PRINT_NOW(string url) { string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); } protected void lnkPrint_Click(object sender, EventArgs e) { PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } #endregion protected void gvScheduleBranch_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); ViewState["DELIVERYNUM"] = row.Cells[0].Text; if (e.CommandName == "Post") { oTransaction.UPDATE_BRANCH_DELIVERY_POSTING(ViewState["DELIVERYNUM"].ToString()); DisplayForPosting(); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Delivery Number: " + ViewState["DELIVERYNUM"].ToString() + " successfully posted."; //Response.Redirect(Request.RawUrl); } else if (e.CommandName == "View") { DisplayDeliveryDetails(ViewState["DELIVERYNUM"].ToString()); lblDRNUM.Text = ViewState["DELIVERYNUM"].ToString(); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalView').modal('show');</script>", false); } else if (e.CommandName == "Cancel") { oTransaction.CANCEL_BRANCH_DELIVERY(ViewState["DELIVERYNUM"].ToString()); // DisplayForPosting(); Response.Redirect(Request.RawUrl); } } protected void lnkSave_Click(object sender, EventArgs e) { //if (!string.IsNullOrEmpty(ViewState["BRANCHCODE"].ToString())) //{ // // ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertErrorMessage').hide();</script>", false); // //string sBRINUM = oSystem.GENERATE_SERIES_NUMBER_TRANS("BRI"); // //Save Delivery // foreach (GridViewRow row in gvDRList.Rows) // { // if (row.RowType == DataControlRowType.DataRow) // { // string deliveryNum = row.Cells[0].Text; // string itemCode = row.Cells[1].Text; // TextBox txtQuantity = (TextBox)row.Cells[3].FindControl("txtDeliveryQty"); // int quantity; // if (string.IsNullOrEmpty(txtQuantity.Text)) // { quantity = 0; } // else // { // quantity = Convert.ToInt32(txtQuantity.Text); // } // if (quantity != 0) // { // oTransaction.UPDATE_DELIVERY_ADJUSTMENT(deliveryNum, itemCode, quantity); // } // } // } // ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); // lblSuccessMessage.Text = "Adjustment successfully updated."; // // Response.Redirect(Request.RawUrl); //} //else //{ // //Error message // ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); // lblErrorMessage.Text = "Please fill up required input."; //} } protected void lnkPostAll_Click(object sender, EventArgs e) { foreach (GridViewRow row in gvDeliveryForPostingList.Rows) { if (row.RowType == DataControlRowType.DataRow) { string drnum = row.Cells[0].Text; oTransaction.UPDATE_BRANCH_DELIVERY_POSTING(row.Cells[0].Text); DisplayForPosting(); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "All delivery successfully posted."; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class BranchStockAdjustment : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ViewState["BRANCHCODE"] = ""; DisplayStockAdjustmentList(); DisplayBranchList(); } } #region "Local Function" //List of Branch //Diplay on Gridview private void DisplayItems() { DataTable dt = oTransaction.GET_BRANCH_STOCK(ViewState["BRANCHCODE"].ToString()); DataView dv = dt.DefaultView; //dv.RowFilter = "itemCategoryCode ='IO'"; gvItems.DataSource = dv; gvItems.DataBind(); } private void DisplayBranchList() { DataTable dt = oMaster.GET_BRANCH_LIST(); gvBranchList.DataSource = dt; gvBranchList.DataBind(); } private void DisplayStockAdjustmentList() { DataTable dt = oUtility.GET_STOCK_ADJUSTMENT_LIST(); ddAdjustmentType.DataSource = dt; ddAdjustmentType.DataTextField = dt.Columns["AdjustmentName"].ToString(); ddAdjustmentType.DataValueField = dt.Columns["AdjustmentCode"].ToString(); ddAdjustmentType.DataBind(); ddAdjustmentType.Items.Insert(0, new ListItem("--SELECT Adjustment--")); } #endregion #region "PRINT AREA" private void PRINT_NOW(string url) { string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); } protected void lnkPrint_Click(object sender, EventArgs e) { PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } #endregion protected void gvScheduleBranch_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); if (e.CommandName == "Select") { if (!string.IsNullOrEmpty(txtAdjustmentDate.Text) && !string.IsNullOrWhiteSpace(txtAdjustmentDate.Text) && ddAdjustmentType.SelectedIndex != 0) { ViewState["BRANCHCODE"] = row.Cells[0].Text; ViewState["BRANCHNAME"] = row.Cells[1].Text; lblBranchNameStock.Text = "Branch Stock to Adjust: <b>" + ViewState["BRANCHNAME"].ToString() + "</b>"; txtSearch.Text = ""; DisplayItems(); //Check if this branch encoded and not yet posted adjustment in selected date. if (oTransaction.CHECK_EXIST_STOCK_ADJUSTMENT_ENTRY(ViewState["BRANCHCODE"].ToString())) { lnkViewPendingAdjustment.Visible = true; } else { lnkViewPendingAdjustment.Visible = false; } //Display Usage Stock that already encoded //DisplayEncodeUsageStock(Convert.ToDateTime(txtAdjustmentDate.Text), ViewState["BRANCHCODE"].ToString()); } else { ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); lblErrorMessage.Text = "Please fill up date input."; } } } protected void lnkSave_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtAdjustmentDate.Text) && !string.IsNullOrWhiteSpace(txtAdjustmentDate.Text) && !string.IsNullOrEmpty(ViewState["BRANCHCODE"].ToString())) { // ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertErrorMessage').hide();</script>", false); string sBSANUM = oSystem.GENERATE_SERIES_NUMBER_TRANS("BSA"); //Save Delivery foreach (GridViewRow row in gvItems.Rows) { if (row.RowType == DataControlRowType.DataRow) { string itemCode = row.Cells[0].Text; TextBox txtQuantity = (TextBox)row.Cells[2].FindControl("txtAdjustmentQty"); int quantity; if (string.IsNullOrEmpty(txtQuantity.Text)) { quantity = 0; } else { quantity = Convert.ToInt32(txtQuantity.Text); } if (quantity != 0) { oTransaction.INSERT_UPDATE_BRANCH_ADJUSTMENT_STOCK(ViewState["BRANCHCODE"].ToString(), sBSANUM, ddAdjustmentType.SelectedValue, Convert.ToDateTime(txtAdjustmentDate.Text), txtRemarks.Text, itemCode, quantity); } } } ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Branch Adjustment successfully process and waiting for posting."; //Reset DisplayStockAdjustmentList(); DisplayBranchList(); lnkViewPendingAdjustment.Visible = false; ViewState["BRANCHCODE"] = ""; gvItems.DataSource = null; gvItems.DataBind(); } else { //Error message ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); lblErrorMessage.Text = "Please fill up required input."; } } protected void lnkViewPendingAdjustment_Click(object sender, EventArgs e) { //DisplayDeliveryDetails(ViewState["DELIVERYNUM"].ToString()); //lblDRNUM.Text = ViewState["DELIVERYNUM"].ToString(); DataTable dt = oTransaction.GET_STOCK_ADJUSTMENT_ITEM_NOT_YET_POSTED(); DataView dv = dt.DefaultView; dv.RowFilter = "branchCode = '" + ViewState["BRANCHCODE"].ToString() + "'"; gvStockAdjustmentForPosting.DataSource = dv; gvStockAdjustmentForPosting.DataBind(); lblBranchNameAdjustment.Text = ViewState["BRANCHNAME"].ToString(); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalStockAdjustmentForPosting').modal('show');</script>", false); } } }<file_sep># AcesOfGrace Aces of Grace Corporation System <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class BranchSales : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ViewState["BRANCHCODE"] = ""; DisplayBranchList(); txtSalesDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); } } #region "Local Function" //List of Branch //Diplay on Gridview private void DisplayItems() { DataTable dt = oTransaction.GET_BRANCH_STOCK(ViewState["BRANCHCODE"].ToString()); DataView dv = dt.DefaultView; dv.RowFilter = "itemCategoryCode ='IS'"; gvItems.DataSource = dv; gvItems.DataBind(); } private void DisplayEncodedSales(DateTime _salesDate, string _branchCode) { DataTable dt = oTransaction.GET_BRANCH_SALES_BY_DATE(Convert.ToDateTime(txtSalesDate.Text)); DataView dv = dt.DefaultView; dv.RowFilter = "BranchCode ='" + _branchCode + "'"; gvItemSalesDone.DataSource = dv; gvItemSalesDone.DataBind(); } private void DisplayBranchList() { DataTable dt = oMaster.GET_BRANCH_LIST(); gvBranchList.DataSource = dt; gvBranchList.DataBind(); } #endregion #region "PRINT AREA" private void PRINT_NOW(string url) { string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); } protected void lnkPrint_Click(object sender, EventArgs e) { PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } #endregion protected void gvScheduleBranch_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); if (e.CommandName == "Select") { if (!string.IsNullOrEmpty(txtSalesDate.Text) || !string.IsNullOrWhiteSpace(txtSalesDate.Text)) { ViewState["BRANCHCODE"] = row.Cells[0].Text; lblBranchNameStock.Text = "<b> Sales of :" + row.Cells[1].Text + "</b>"; txtSearch.Text = ""; DisplayItems(); //DISPLAY IF BRANCH ALREADY ENCODED ON SELECTED DATE DisplayEncodedSales(Convert.ToDateTime(txtSalesDate.Text), ViewState["BRANCHCODE"].ToString()); } else { ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); lblErrorMessage.Text = "Please fill up date input."; } } } protected void lnkSave_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtSalesDate.Text) || txtSalesDate.Text.Trim().Length != 0 || !string.IsNullOrEmpty(Session["BRANCHCODE"].ToString())) { // ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#alertErrorMessage').hide();</script>", false); string sSBNUM = oSystem.GENERATE_SERIES_NUMBER_TRANS("SB"); //Save Delivery foreach (GridViewRow row in gvItems.Rows) { if (row.RowType == DataControlRowType.DataRow) { string itemCode = row.Cells[0].Text; TextBox txtQuantity = (TextBox)row.Cells[2].FindControl("txtConsumeStock"); int quantity; if (string.IsNullOrEmpty(txtQuantity.Text)) { quantity = 0; } else { quantity = Convert.ToInt32(txtQuantity.Text); } if (quantity != 0) { oTransaction.INSERT_BRANCH_SALES(ViewState["BRANCHCODE"].ToString(), sSBNUM, Convert.ToDateTime(txtSalesDate.Text), "", itemCode, quantity); //oTransaction.INSERT_CONSUME_BRANCH_ITEM(ViewState["BRANCHCODE"].ToString(), sICNUM, Convert.ToDateTime(txtSalesDate.Text), "", itemCode, quantity); } } } ////Hold for possible Print Directly //Session["G_DRBNUM"] = sDRNUM; //UPDATE SERIES NUMBER //oSystem.UPDATE_SERIES_NUMBER("SB"); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Branch Sales succesfully process."; DisplayEncodedSales(Convert.ToDateTime(txtSalesDate.Text), ViewState["BRANCHCODE"].ToString()); //Response.Redirect(Request.RawUrl); } else { //Error message ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); lblErrorMessage.Text = "Please fill up required input."; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class ItemMaster : System.Web.UI.Page { cMaster oMaster = new cMaster(); cUtil oUtil = new cUtil(); cSystem oSystem = new cSystem(); cAccounting oAccounting = new cAccounting(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Display_Item_List(); Display_Item_UOM_List(); Display_Item_Category_List(); Display_Payable_Account_List(); Display_Status_List(); panelItemInput.Visible = false; } } protected void lnkNew_Click(object sender, EventArgs e) { panelItemInput.Visible = true; panelItemList.Visible = false; Clear_Inputs(); lblContentText.Text = "Create New Product Item"; } protected void lnkCancel_Click(object sender, EventArgs e) { panItemEditName.Visible = false; lblItemEditName.Visible = false; Response.Redirect(Request.RawUrl); } private void Display_Item_UOM_List() { DataTable dt = oUtil.GET_ITEM_UOM_LIST(); ddUOM.DataSource = dt; ddUOM.DataTextField = dt.Columns["uomDescription"].ToString(); ddUOM.DataValueField = dt.Columns["uomCode"].ToString(); ddUOM.DataBind(); } private void Display_Item_Category_List() { DataTable dt = oUtil.GET_ITEM_CATEGORY_LIST(); ddItemCategory.DataSource = dt; ddItemCategory.DataTextField = dt.Columns["itemCategoryName"].ToString(); ddItemCategory.DataValueField = dt.Columns["itemCategoryCode"].ToString(); ddItemCategory.DataBind(); } private void Display_Payable_Account_List() { DataTable dt = oAccounting.GET_PAYABLE_ACCOUNT_LIST(); ddPayableAccount.DataSource = dt; ddPayableAccount.DataTextField = dt.Columns["payAccName"].ToString(); ddPayableAccount.DataValueField = dt.Columns["payAccCode"].ToString(); ddPayableAccount.DataBind(); } private void Display_Status_List() { DataTable dt = oUtil.GET_STATUS_LIST(); ddStatus.DataSource = dt; ddStatus.DataTextField = dt.Columns["statusName"].ToString(); ddStatus.DataValueField = dt.Columns["statusCode"].ToString(); ddStatus.DataBind(); } private void Display_Item_List() { DataTable dt = oMaster.GET_ITEMS_LIST(); gvItemList.DataSource = dt; gvItemList.DataBind(); } private void Clear_Inputs() { txtItemCode.Text = ""; txtItemName.Text = ""; txtItemCode.Enabled = true; txtItemCode.Focus(); ddStatus.Enabled = false; ddStatus.SelectedIndex = 0; ddItemCategory.SelectedIndex = 0; ddUOM.SelectedIndex = 0; ddPayableAccount.SelectedIndex = 0; } protected void lnkSaveBranch_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtItemCode.Text) && !string.IsNullOrEmpty(txtItemName.Text)) { //SAVE AND UPDATE oMaster.INSERT_UPDATE_ITEM(txtItemCode.Text, txtItemName.Text, ddItemCategory.SelectedValue, ddUOM.SelectedValue, ddStatus.SelectedValue, ddPayableAccount.SelectedValue, oSystem.GET_SERVER_DATE_TIME()); lblSuccessMessage.Text = "Item successfully updated."; ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); } else { lblErrorMessage.Text = "Required field must fill up."; ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); } } protected void lnkCancelNewBranch_Click(object sender, EventArgs e) { Clear_Inputs(); panelItemInput.Visible = false; panelItemList.Visible = true; panItemEditName.Visible = false; } protected void gvBranchList_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); txtSearchItem.Text = ""; panelItemList.Visible = false; panelItemInput.Visible = true; txtItemCode.Enabled = false; txtItemName.Focus(); ddStatus.Enabled = true; txtItemName.Text = row.Cells[2].Text; txtItemCode.Text = row.Cells[1].Text; Display_Selected_Item(row.Cells[1].Text); lblContentText.Text = "<span class=\"fas fa-store-alt\"></span> Update Information" ; panItemEditName.Visible = true; lblItemEditName.Text = txtItemName.Text; } } private void Display_Selected_Item(string _itemCode) { DataTable dt = new DataTable(); dt = oMaster.GET_ITEMS_LIST(); DataView dv = dt.DefaultView; dv.RowFilter = "ItemCode ='" + _itemCode + "'"; if (dv.Count > 0) { DataRowView dvr = dv[0]; //txtUnitCost.Text = dvr.Row["unitCost"].ToString(); //txtUnitPrice.Text = dvr.Row["unitPrice"].ToString(); ddStatus.SelectedValue = dvr.Row["statusCode"].ToString(); if (!string.IsNullOrEmpty(ddUOM.SelectedValue = dvr.Row["itemUOMInventory"].ToString()) || !string.IsNullOrWhiteSpace(ddUOM.SelectedValue = dvr.Row["itemUOMInventory"].ToString())) { ddUOM.SelectedValue = dvr.Row["itemUOMInventory"].ToString(); } if (!string.IsNullOrEmpty(ddItemCategory.SelectedValue = dvr.Row["itemCategoryCode"].ToString())) { ddItemCategory.SelectedValue = dvr.Row["itemCategoryCode"].ToString(); } if (!string.IsNullOrEmpty(ddPayableAccount.SelectedValue = dvr.Row["payAcccode"].ToString())) { ddPayableAccount.SelectedValue = dvr.Row["payAcccode"].ToString(); } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class ItemPartnerPriceSetup : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { //ViewState["BRANCHCODE"] = ""; Display_Partners_List(); } } #region "Local Function" //List of Branch //Diplay on Gridview #endregion //#region "PRINT AREA" //private void PRINT_NOW(string url) //{ // string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; // ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); //} //#endregion protected void lnkSave_Click(object sender, EventArgs e) { foreach (GridViewRow row in gvItems.Rows) { if (row.RowType == DataControlRowType.DataRow) { string itemCode = row.Cells[0].Text; string partnerCode = ddPartnerList.SelectedValue.ToString(); TextBox txtPartnerPrice = (TextBox)row.Cells[2].FindControl("txtPartnerPrice"); TextBox txtSellingPrice = (TextBox)row.Cells[2].FindControl("txtSellingPrice"); double dPartnerPrice, dSellingPrice; if (string.IsNullOrEmpty(txtPartnerPrice.Text)) { dPartnerPrice = 0; } else { dPartnerPrice = Convert.ToInt32(txtPartnerPrice.Text); } if (string.IsNullOrEmpty(txtSellingPrice.Text)) { dSellingPrice = 0; } else { dSellingPrice = Convert.ToInt32(txtSellingPrice.Text); } if (dPartnerPrice != 0) { oUtility.UPDATE_PARTNER_PRICE(partnerCode, itemCode, dPartnerPrice, dSellingPrice); } } } ddPartnerList.SelectedIndex = 0; Display_Partner_Price(ddPartnerList.SelectedValue); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Partner price successfully updated."; } private void Display_Partners_List() { DataTable dt = oMaster.GET_PARTNERS_LIST(); ddPartnerList.DataSource = dt; ddPartnerList.DataTextField = dt.Columns["PartnerName"].ToString(); ddPartnerList.DataValueField = dt.Columns["PartnerCode"].ToString(); ddPartnerList.DataBind(); ddPartnerList.Items.Insert(0, new ListItem("--SELECT PARTNER--")); } private void Display_Partner_Price(string _partnerCode) { DataTable dt = oUtility.GET_PARTNER_PRICE(_partnerCode); if (ddPartnerList.SelectedIndex > 0) { gvItems.DataSource = dt; lblPartnerName.Text = ddPartnerList.SelectedItem.ToString(); } else { gvItems.DataSource = null; lblPartnerName.Text = ""; } gvItems.DataBind(); } protected void ddPartnerList_SelectedIndexChanged(object sender, EventArgs e) { Display_Partner_Price(ddPartnerList.SelectedValue); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace AGC { public class cAccounting : cBase { public cAccounting() { } #region "GET LIST" public DataTable GET_PAYABLE_ACCOUNT_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[ACCOUNTING].[spGET_PAYABLE_ACCOUNT_LIST]"); return dt; } #endregion #region "TRANSACTION" #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class BranchItemDelivery : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { txtDeliveryDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); DisplayBranchDeliverySchedule(Convert.ToDateTime(txtDeliveryDate.Text)); ViewState["BRANCHCODE"] = ""; } } #region "Local Function" //List of Branch //Diplay on Gridview private void Display_Items() { DataTable dt = oMaster.GET_ITEMS_LIST(); gvItems.DataSource = dt; gvItems.DataBind(); // DisplayDeliveredBranch(); } #endregion protected void lnkSave_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtDeliveryDate.Text) && !string.IsNullOrWhiteSpace(txtDeliveryDate.Text) && !string.IsNullOrEmpty(ViewState["BRANCHCODE"].ToString())) { string sDRNUM = oSystem.GENERATE_SERIES_NUMBER_TRANS("DRB"); //Save Delivery foreach (GridViewRow row in gvItems.Rows) { if (row.RowType == DataControlRowType.DataRow) { string itemCode = row.Cells[0].Text; TextBox txtQuantity = (TextBox)row.Cells[2].FindControl("txtItemQuantity"); int quantity; if (string.IsNullOrEmpty(txtQuantity.Text)) { quantity = 0; } else { quantity = Convert.ToInt32(txtQuantity.Text); } if (quantity != 0) { oTransaction.INSERT_BRANCH_DELIVERY(ViewState["BRANCHCODE"].ToString(), sDRNUM, Convert.ToDateTime(txtDeliveryDate.Text), txtRemarks.Text, itemCode, quantity); } } } //Hold for possible Print Directly //Session["G_DRBNUM"] = sDRNUM; //UPDATE SERIES NUMBER //oSystem.UPDATE_SERIES_NUMBER("DRB"); //Clear txtRemarks.Text = ""; Display_Items(); ViewState["BRANCHCODE"] = ""; ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Creating new delivery successfully process."; //PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } else { //Error message ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); lblErrorMessage.Text = "Please fill up required input."; } } private void DisplayBranchDeliverySchedule(DateTime _selectedDate) { DataTable dt = oUtility.GET_BRANCH_SCHEDULE_LIST(); DataView dv = new DataView(dt); switch (_selectedDate.DayOfWeek) { case DayOfWeek.Monday: dv.RowFilter = "M = 1"; break; case DayOfWeek.Tuesday: dv.RowFilter = "T = 1"; break; case DayOfWeek.Wednesday: dv.RowFilter = "W = 1"; break; case DayOfWeek.Thursday: dv.RowFilter = "Th = 1"; break; case DayOfWeek.Friday: dv.RowFilter = "F = 1"; break; case DayOfWeek.Saturday: dv.RowFilter = "Sa = 1"; break; case DayOfWeek.Sunday: dv.RowFilter = "S = 1"; break; } gvScheduleBranch.DataSource = dv; gvScheduleBranch.DataBind(); } //Display all branch and identify list of Branch that had been schedule. //private void DisplayDeliveredBranch() //{ // foreach (GridViewRow row in gvScheduleBranch.Rows) // { // string branchCode = row.Cells[0].Text; // LinkButton lnkNewDelivery = row.FindControl("lnkNewDelivery") as LinkButton; // LinkButton lnkView = row.FindControl("lnkView") as LinkButton; // if (oTransaction.CHECK_EXIST_DELIVERY_ENTRY(Convert.ToDateTime(txtDeliveryDate.Text), branchCode)) // { // lnkNewDelivery.Enabled = false; // lnkNewDelivery.CssClass = "disabledLink"; // lnkNewDelivery.Visible = false; // lnkView.Visible = true; // //lnkEditDelivery.Visible = true; // } // } //} #region "PRINT AREA" private void PRINT_NOW(string url) { string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); } protected void lnkPrint_Click(object sender, EventArgs e) { PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } #endregion protected void gvScheduleBranch_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); if (e.CommandName == "Select") { //Display only item assign to this branch or partners Display_Items(); ViewState["BRANCHCODE"] = row.Cells[0].Text; ViewState["BRANCHNAME"] = row.Cells[1].Text; lblDeliveryBranchName.Text = "Delivery to " + "<b>" + row.Cells[1].Text + "</b>"; txtSearch.Text = ""; if (oTransaction.CHECK_EXIST_DELIVERY_ENTRY(ViewState["BRANCHCODE"].ToString())) { //lnkNewDelivery.Enabled = false; //lnkNewDelivery.CssClass = "disabledLink"; //lnkNewDelivery.Visible = false; //lnkView.Visible = true; //lnkEditDelivery.Visible = true; lnkViewPendingDelivery.Visible = true; } else { lnkViewPendingDelivery.Visible = false; } } else if (e.CommandName == "View") { Session["G_BRANCHCODE"] = row.Cells[0].Text; Session["G_DELIVERYDATE"] = Convert.ToDateTime(txtDeliveryDate.Text); //Display PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } //else if (e.CommandName == "Edit") // { // } } protected void lnkSearchDate_Click(object sender, EventArgs e) { try { DisplayBranchDeliverySchedule(Convert.ToDateTime(txtDeliveryDate.Text)); } catch { } } protected void gvScheduleBranch_RowDataBound(object sender, GridViewRowEventArgs e) { // DisplayDeliveredBranch(); } protected void lnkViewPendingDelivery_Click(object sender, EventArgs e) { DataTable dt = oTransaction.GET_DELIVERY_FOR_POSTING(); DataView dv = dt.DefaultView; dv.RowFilter = "branchCode = '" + ViewState["BRANCHCODE"].ToString() + "'"; gvDeliveryForPosting.DataSource = dv; gvDeliveryForPosting.DataBind(); lblBranchNameDelivery.Text = ViewState["BRANCHNAME"].ToString(); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalDeliveryForPosting').modal('show');</script>", false); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class Home : System.Web.UI.Page { cSystem oSystem = new cSystem(); cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { txtStartDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); txtEndDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); displayItemList(); txtTopNumber.Text = "5"; displayTopBranchSale(ddItemList.SelectedValue, Convert.ToDateTime(txtStartDate.Text), Convert.ToDateTime(txtEndDate.Text), Convert.ToInt32(txtTopNumber.Text)); } } //private void displayBranchList() //{ // DataTable dt = oMaster.GET_BRANCH_LIST(); // ddBranchList.DataSource = dt; // ddBranchList.DataTextField = dt.Columns["branchName"].ToString(); // ddBranchList.DataValueField = dt.Columns["branchCode"].ToString(); // ddBranchList.DataBind(); // ddBranchList.Items.Insert(0, new ListItem("--Select Branch--")); //} private void displayItemList() { DataTable dt = oMaster.GET_ITEMS_LIST(); DataView dv = dt.DefaultView; dv.RowFilter = "ItemCategoryCode = 'IS'"; dv.Sort = "arr"; ddItemList.DataSource = dv; ddItemList.DataTextField = dv.Table.Columns["ItemName"].ToString(); ddItemList.DataValueField = dv.Table.Columns["ItemCode"].ToString(); ddItemList.DataBind(); // ddItemList.Items.Insert(0, new ListItem("--Select Item--")); } private void displayTopBranchSale(string _itemCode, DateTime _startDate, DateTime _endDate, int _topNumber) { DataTable dt = oTransaction.GET_BRANCH_TOP_SALES(_itemCode, _startDate, _endDate); if (dt.Rows.Count > 0) { DataTable dtTop = dt.Rows.Cast<DataRow>().Take(_topNumber).CopyToDataTable(); gvTopSaleBranch.DataSource = dtTop; } else { gvTopSaleBranch.DataSource = null; } gvTopSaleBranch.DataBind(); } protected void lnkPreview_Click(object sender, EventArgs e) { displayTopBranchSale(ddItemList.SelectedValue, Convert.ToDateTime(txtStartDate.Text), Convert.ToDateTime(txtEndDate.Text), Convert.ToInt32(txtTopNumber.Text)); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace AGC { public class cMaster:cBase { public cMaster() { } #region "DISPLAY / GET" public DataTable GET_BRANCH_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[MASTER].[spGET_BRANCH_LIST]"); return dt; } public DataTable GET_BRANCH_MACHINE_EQUIPMENT_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[MASTER].[spGET_BRANCH_MACHINE_EQUIPMENT_LIST]"); return dt; } public DataTable GET_PARTNERS_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[MASTER].[spGET_PARTNERS_LIST]"); return dt; } #endregion #region "CREATE - UPDATE" /* INSERT - UPDATE ITEM */ public void INSERT_UPDATE_ITEM(string _itemCode, string _itemName, string _itemCategoryCode, string _itemInventoryCode, string _statusCode, string _payAccCode, DateTime _dateUpdate) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[MASTER].[spINSERT_UPDATE_ITEM]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@ITEMNAME", _itemName); cmd.Parameters.AddWithValue("@ITEMCATEGORYCODE", _itemCategoryCode); cmd.Parameters.AddWithValue("@ITEMUOMINVENTORY", _itemInventoryCode); cmd.Parameters.AddWithValue("@STATUSCODE", _statusCode); cmd.Parameters.AddWithValue("@PAYACCCODE", _payAccCode); cmd.Parameters.AddWithValue("@DU", _dateUpdate); cn.Open(); cmd.ExecuteNonQuery(); } } } /* INSERT - UPDATE OF NEW BRANCH INFORMATION */ public void INSERT_BRANCH(string _branchCode, string _branchName, string _branchAddress,string _branchContactNumbers, int _branchInchargeID, int _supervisorID, string _partnerCode, DateTime _openingDate, int _areaId, string _lessorName, string _modePaymentCode, int _paymentDay, string _remarks) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[MASTER].[spINSERT_BRANCH]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCH_CODE", _branchCode); cmd.Parameters.AddWithValue("@BRANCH_NAME", _branchName); cmd.Parameters.AddWithValue("@BRANCH_ADDRESS", _branchAddress); cmd.Parameters.AddWithValue("@BRANCH_CONTACT_NUMBER", _branchContactNumbers); cmd.Parameters.AddWithValue("@BRANCH_INCHARGE_ID", _branchInchargeID); cmd.Parameters.AddWithValue("@SUPERVISOR_ID", _supervisorID); cmd.Parameters.AddWithValue("@PARTNER_CODE", _partnerCode); cmd.Parameters.AddWithValue("@OPENING_DATE", _openingDate); cmd.Parameters.AddWithValue("@AREAID", _areaId); cmd.Parameters.AddWithValue("@LESSOR_NAME", _lessorName); cmd.Parameters.AddWithValue("@MODE_PAYMENT_CODE", _modePaymentCode); cmd.Parameters.AddWithValue("@PAYMENT_DAY", _paymentDay); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cn.Open(); cmd.ExecuteNonQuery(); } } } public void UPDATE_BRANCH(string _branchCode, string _branchName, string _branchAddress, string _branchContactNumbers, int _branchInchargeID, int _supervisorID, string _partnerCode, DateTime _openingDate, int _areaId, string _lessorName, string _modePaymentCode, int _paymentDay, string _remarks, bool _isActive) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[MASTER].[spUPDATE_BRANCH]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCH_CODE", _branchCode); cmd.Parameters.AddWithValue("@BRANCH_NAME", _branchName); cmd.Parameters.AddWithValue("@BRANCH_ADDRESS", _branchAddress); cmd.Parameters.AddWithValue("@BRANCH_CONTACT_NUMBER", _branchContactNumbers); cmd.Parameters.AddWithValue("@BRANCH_INCHARGE_ID", _branchInchargeID); cmd.Parameters.AddWithValue("@SUPERVISOR_ID", _supervisorID); cmd.Parameters.AddWithValue("@PARTNER_CODE", _partnerCode); cmd.Parameters.AddWithValue("@OPENING_DATE", _openingDate); cmd.Parameters.AddWithValue("@AREAID", _areaId); cmd.Parameters.AddWithValue("@LESSOR_NAME", _lessorName); cmd.Parameters.AddWithValue("@MODE_PAYMENT_CODE", _modePaymentCode); cmd.Parameters.AddWithValue("@PAYMENT_DAY", _paymentDay); cmd.Parameters.AddWithValue("@REMARKS", _remarks); cmd.Parameters.AddWithValue("@IS_ACTIVE", _isActive); cn.Open(); cmd.ExecuteNonQuery(); } } } /* INSERT - UPDATE OF BRANCH MACHINE AND EQUIPMENT */ public void INSERT_BRANCH_MACHINE_EQUIPMENT(string _branchCode, string _machEquipCode, string _addtDescription, string _serial, DateTime _dateIssue) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[MASTER].[spINSERT_BRANCH_MACHINE_EQUIPMENT]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCH_CODE", _branchCode); cmd.Parameters.AddWithValue("@MACHEQUIP_CODE",_machEquipCode); cmd.Parameters.AddWithValue("@ADDITIONAL_DESCRIPTION",_addtDescription); cmd.Parameters.AddWithValue("@SERIAL", _serial); cmd.Parameters.AddWithValue("@DATE_ISSUE",_dateIssue); cn.Open(); cmd.ExecuteNonQuery(); } } } public void UPDATE_BRANCH_MACHINE_EQUIPMENT(int _id, string _machEquipCode, string _addtDescription, string _serial, DateTime _dateIssue) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[MASTER].[spUPDATE_BRANCH_MACHINE_EQUIPMENT]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ID", _id); cmd.Parameters.AddWithValue("@MACHEQUIP_CODE", _machEquipCode); cmd.Parameters.AddWithValue("@ADDITIONAL_DESCRIPTION", _addtDescription); cmd.Parameters.AddWithValue("@SERIAL", _serial); cmd.Parameters.AddWithValue("@DATE_ISSUE", _dateIssue); cn.Open(); cmd.ExecuteNonQuery(); } } } public void DELETE_BRANCH_MACHINE_EQUIPMENT(int _id, string _deletedRemarks) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[MASTER].[spDELETE_BRANCH_MACHINE_EQUIPMENT]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ID", _id); cmd.Parameters.AddWithValue("@DELETED_REMARKS", _deletedRemarks); cn.Open(); cmd.ExecuteNonQuery(); } } } #endregion #region /*ITEMS SECTION*/ //GET LIST OF ITEM public DataTable GET_ITEMS_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[MASTER].[spGET_ITEMS_LIST]"); return dt; } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class BranchInventoryStock : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ViewState["BRANCHCODE"] = ""; DisplayBranchList(); } } #region "Local Function" //List of Branch //Diplay on Gridview private void DisplayItems() { DataTable dt = oTransaction.GET_BRANCH_STOCK(ViewState["BRANCHCODE"].ToString()); if (dt.Rows.Count > 0) { gvItems.DataSource = dt; } else { gvItems.DataSource = null; } gvItems.DataBind(); } private void DisplayBranchList() { DataTable dt = oMaster.GET_BRANCH_LIST(); ddBranch.DataSource = dt; ddBranch.DataTextField = dt.Columns["BranchName"].ToString(); ddBranch.DataValueField = dt.Columns["BranchCode"].ToString(); ddBranch.DataBind(); ddBranch.Items.Insert(0, new ListItem("--Select Branch--")); } #endregion #region "PRINT AREA" private void PRINT_NOW(string url) { string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); } protected void lnkPrint_Click(object sender, EventArgs e) { PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } #endregion protected void gvScheduleBranch_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); if (e.CommandName == "Select") { //Display only item assign to this branch or partners //Display_Items(); } if (e.CommandName == "View") { Session["G_BRANCHCODE"] = row.Cells[0].Text; // Session["G_DELIVERYDATE"] = Convert.ToDateTime(txtDeliveryDate.Text); //Display PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } } protected void ddBranch_SelectedIndexChanged(object sender, EventArgs e) { if (ddBranch.SelectedIndex != 0) { ViewState["BRANCHCODE"] = ddBranch.SelectedValue; DisplayItems(); } else { ViewState["BRANCHCODE"] = ""; } // txtSearch.Text = ""; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class BranchStockTransfer : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ViewState["BRANCHCODE"] = ""; DisplayBranchList(); DisplayBranchItemsSource(ddSource.SelectedValue); DisplayBranchItemsDestination(ddDestination.SelectedValue); // txtReturnDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); } } #region "Local Function" private void DisplayBranchItemsSource(string _branchCode) { DataTable dt = oTransaction.GET_BRANCH_STOCK(_branchCode); gvItemsSource.DataSource = dt; gvItemsSource.DataBind(); } private void DisplayBranchItemsDestination(string _branchCode) { DataTable dt = oTransaction.GET_BRANCH_STOCK(_branchCode); gvItemDestination.DataSource = dt; gvItemDestination.DataBind(); } private void DisplayBranchList() { DataTable dt = oMaster.GET_BRANCH_LIST(); ddSource.DataSource = dt; ddSource.DataTextField = dt.Columns["BranchName"].ToString(); ddSource.DataValueField = dt.Columns["BranchCode"].ToString(); ddSource.DataBind(); ddDestination.DataSource = dt; ddDestination.DataTextField = dt.Columns["BranchName"].ToString(); ddDestination.DataValueField = dt.Columns["BranchCode"].ToString(); ddDestination.DataBind(); } #endregion #region "PRINT AREA" private void PRINT_NOW(string url) { string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); } protected void lnkPrint_Click(object sender, EventArgs e) { PRINT_NOW("rep_BranchDeliveryReceiptSingle.aspx"); } #endregion protected void lnkSave_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtTransferDate.Text) || !string.IsNullOrWhiteSpace(txtTransferDate.Text)) { //2nd level of filter not same source and destination if (ddSource.SelectedValue != ddDestination.SelectedValue) { string transferNum = oSystem.GENERATE_SERIES_NUMBER_TRANS("BIT"); foreach (GridViewRow row in gvItemsSource.Rows) { string itemCode = row.Cells[0].Text; TextBox txtQty = row.FindControl("txtTransferQty") as TextBox; int QtyTransfer = 0; if (!string.IsNullOrEmpty(txtQty.Text) || !string.IsNullOrWhiteSpace(txtQty.Text)) { QtyTransfer = Convert.ToInt32(txtQty.Text); oTransaction.INSERT_BRANCH_TRANSFER_INVENTORY(ddSource.SelectedValue, ddDestination.SelectedValue, transferNum, Convert.ToDateTime(txtTransferDate.Text), "", itemCode, QtyTransfer); } } //Refresh record. DisplayBranchList(); DisplayBranchItemsSource(ddSource.SelectedValue); DisplayBranchItemsDestination(ddDestination.SelectedValue); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Branch Inventory successfully transferred."; } else { ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); lblErrorMessage.Text = "The same Source and Destination Branch is not allowed."; } } else { //Error message ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); lblErrorMessage.Text = "Please fill up transfer date."; } } protected void gvItemsSource_RowDataBound(object sender, GridViewRowEventArgs e) { foreach (GridViewRow row in gvItemsSource.Rows) { int iAvailableQty = Convert.ToInt32(row.Cells[2].Text); TextBox txtQty = row.FindControl("txtTransferQty") as TextBox; //Validate if the branch available quantity is not zero if (iAvailableQty > 0) { txtQty.Enabled = true; } else { txtQty.Enabled = false; } } } protected void ddSource_SelectedIndexChanged(object sender, EventArgs e) { DisplayBranchItemsSource(ddSource.SelectedValue.ToString()); } protected void ddDestination_SelectedIndexChanged(object sender, EventArgs e) { DisplayBranchItemsDestination(ddDestination.SelectedValue); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class ItemStockSetup : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ViewState["BRANCHCODE"] = ""; DisplayBranchList(); } } #region "Local Function" //List of Branch //Diplay on Gridview private void DisplayItems() { DataTable dt = oTransaction.GET_BRANCH_STOCK(ViewState["BRANCHCODE"].ToString()); if (dt.Rows.Count > 0) { gvItems.DataSource = dt; } else { gvItems.DataSource = null; } gvItems.DataBind(); } private void DisplayBranchList() { DataTable dt = oMaster.GET_BRANCH_LIST(); gvBranchList.DataSource = dt; gvBranchList.DataBind(); } #endregion #region "PRINT AREA" private void PRINT_NOW(string url) { string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); } #endregion protected void gvScheduleBranch_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); if (e.CommandName == "Select") { ViewState["BRANCHCODE"] = row.Cells[0].Text; lblBranchNameStock.Text = "Branch: <b>" + row.Cells[1].Text + "</b>"; txtSearch.Text = ""; DisplayItems(); } } protected void lnkSave_Click(object sender, EventArgs e) { // if (!string.IsNullOrEmpty(txtReturnDate.Text) && !string.IsNullOrWhiteSpace(txtReturnDate.Text) && !string.IsNullOrEmpty(ViewState["BRANCHCODE"].ToString()) && !string.IsNullOrWhiteSpace(txtReturnDate.Text)) // { //string sBRINUM = oSystem.GENERATE_SERIES_NUMBER_TRANS("BRI"); //Save Delivery foreach (GridViewRow row in gvItems.Rows) { if (row.RowType == DataControlRowType.DataRow) { string itemCode = row.Cells[0].Text; TextBox txtQuantity = (TextBox)row.Cells[2].FindControl("txtStockLevelWarning"); int quantity; if (string.IsNullOrEmpty(txtQuantity.Text)) { quantity = 0; } else { quantity = Convert.ToInt32(txtQuantity.Text); } if (quantity != 0) { oTransaction.UPDATE_MINIMUM_STOCK_LEVEL(ViewState["BRANCHCODE"].ToString(), itemCode, quantity); } } } // //Refresh ViewState["BRANCHCODE"] = ""; DisplayBranchList(); DisplayItems(); //// txtReturnDate.Text = oSystem.GET_SERVER_DATE_TIME().ToShortDateString(); // //Response.Redirect(Request.RawUrl); ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Item minimum stock level successfully updated."; // } // else // { // //Error message // ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalError').modal('show');</script>", false); // lblErrorMessage.Text = "Please fill up required input."; // } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace AGC { public class cSystem : cBase { public cSystem() { } public DataSet GET_USER_MENU() { DataSet ds = new DataSet(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[xSys].[GET_MENU]", cn)) { cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); } } return ds; } public DateTime GET_SERVER_DATE_TIME() { DateTime ServerDT; using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[xSys].[GET_SERVER_DATE_TIME]", cn)) { cn.Open(); ServerDT = (DateTime)cmd.ExecuteScalar(); } return ServerDT; } } #region "SERIES NUMBER OF TRANSACTION SECTION" /***** ************/ public int SERIESNUMBER { get; set; } //For Transaction Process public string GENERATE_SERIES_NUMBER_TRANS(string _prefixCode) { SERIESNUMBER = 0; string PrefixCode = ""; string AutoNumber = ""; bool bIsNumberOnly = false; //try //{ using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("xSys.GET_SERIES_NUMBER", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PREFIXCODE", _prefixCode); cn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { PrefixCode = dr["PrefixCode"].ToString(); bIsNumberOnly = (bool)dr["IsNumberOnly"]; if ((int)dr["Series"] > 0) { SERIESNUMBER = (int)dr["Series"] + 1; /*Format Transaction AutoNumber * UP TO 999999999 AutoNumbers */ if (SERIESNUMBER > 99999999) { if (bIsNumberOnly) { AutoNumber = SERIESNUMBER.ToString(); } else { AutoNumber = PrefixCode + SERIESNUMBER; } } else if (SERIESNUMBER > 9999999) { if (bIsNumberOnly) { AutoNumber = "0" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "0" + SERIESNUMBER; } } else if (SERIESNUMBER > 999999) { if (bIsNumberOnly) { AutoNumber = "00" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "00" + SERIESNUMBER; } } else if (SERIESNUMBER > 99999) { if (bIsNumberOnly) { AutoNumber = "000" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "000" + SERIESNUMBER; } } else if (SERIESNUMBER > 9999) { if (bIsNumberOnly) { AutoNumber = "0000" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "0000" + SERIESNUMBER; } } else if (SERIESNUMBER > 999) { if (bIsNumberOnly) { AutoNumber = "00000" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "00000" + SERIESNUMBER; } } else if (SERIESNUMBER > 99) { if (bIsNumberOnly) { AutoNumber = "000000" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "000000" + SERIESNUMBER; } } else if (SERIESNUMBER > 9) { if (bIsNumberOnly) { AutoNumber = "0000000" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "0000000" + SERIESNUMBER; } } else { if (bIsNumberOnly) { AutoNumber = "00000000" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "00000000" + SERIESNUMBER; } } } else { SERIESNUMBER = SERIESNUMBER + 1; if (bIsNumberOnly) { AutoNumber = "00000000" + SERIESNUMBER; } else { AutoNumber = PrefixCode + "00000000" + SERIESNUMBER; } } } } } } //} //catch { //} return AutoNumber; } public void UPDATE_SERIES_NUMBER(string _prefixCode) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("xSys.UPDATE_SERIES_NUMBER", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PREFIXCODE", _prefixCode); cn.Open(); cmd.ExecuteNonQuery(); } } } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace AGC { public class cUtil : cBase { public cUtil() { } //BRANCH AREA LOCATION public DataTable GET_BRANCH_AREA() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[UTIL].[spGET_BRANCH_AREA]"); return dt; } public DataTable GET_SUPERVISOR_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[UTIL].[spGET_SUPERVISOR_LIST]"); return dt; } public DataTable GET_BRANCH_INCHARGE_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[UTIL].[spGET_BRANCH_INCHARGE_LIST]"); return dt; } public DataTable GET_MODE_PAYMENT_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[UTIL].[spGET_MODE_PAYMENT]"); return dt; } public DataTable GET_STATUS_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT_StoredProc("[UTIL].[spGET_STATUS_LIST]"); return dt; } public DataTable GET_MACHINE_EQUIPMENT_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[UTIL].[spGET_MACHINE_EQUIPMENT_LIST]"); return dt; } public DataTable GET_DAYS_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[UTIL].[spGET_DAYS_LIST]"); return dt; } public DataTable GET_BRANCH_SCHEDULE_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[Util].[spGET_BRANCH_SCHEDULE_LIST]"); return dt; } public DataTable GET_ITEM_UOM_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[Util].[spGET_ITEM_UOM_LIST]"); return dt; } public DataTable GET_ITEM_CATEGORY_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[Util].[spGET_ITEM_CATEGORY_LIST]"); return dt; } public DataTable GET_STOCK_ADJUSTMENT_LIST() { DataTable dt = new DataTable(); dt = queryCommandDT("[UTIL].[spGET_STOCK_ADJUSTMENT_LIST]"); return dt; } //PARTNER PRICE public DataTable GET_PARTNER_PRICE(string _partnerCode) { DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[UTIL].[spGET_PARTNER_PRICE]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PARTNERCODE", _partnerCode); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } return dt; } //BRANCH PRICE public DataTable GET_BRANCH_PRICE(string _branchCode) { DataTable dt = new DataTable(); using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[UTIL].[spGET_BRANCH_PRICE]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } } return dt; } #region "TRANS DATA" //UPDATE FOR DELIVERY BRANCH SCHEDULE public void UPDATE_DELIVERY_BRANCH_SCHEDULE(int _schedID, bool _M, bool _T, bool _W, bool _TH, bool _F, bool _SA, bool _S, string _userCode) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[UTIL].[spUPDATE_BRANCH_DELIVERY_SCHEDULE]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SCHEDID", _schedID ); cmd.Parameters.AddWithValue("@M", _M); cmd.Parameters.AddWithValue("@T", _T); cmd.Parameters.AddWithValue("@W", _W); cmd.Parameters.AddWithValue("@TH", _TH); cmd.Parameters.AddWithValue("@F", _F); cmd.Parameters.AddWithValue("@SA", _SA); cmd.Parameters.AddWithValue("@S", _S); cmd.Parameters.AddWithValue("@USERCODE", _userCode); cn.Open(); cmd.ExecuteNonQuery(); } } } public void UPDATE_PARTNER_PRICE(string _partnerCode, string _itemCode, double _partnerPrice, double _sellingPrice) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[UTIL].[spUPDATE_PARTNER_PRICE]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PARTNERCODE", _partnerCode); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@PARTNERPRICE", _partnerPrice); cmd.Parameters.AddWithValue("@SELLINGPRICE", _sellingPrice); cn.Open(); cmd.ExecuteNonQuery(); } } } public void UPDATE_BRANCH_PRICE(string _branchCode, string _itemCode, double _branchPrice, double _sellingPrice) { using (SqlConnection cn = new SqlConnection(CS)) { using (SqlCommand cmd = new SqlCommand("[UTIL].[spUPDATE_BRANCH_PRICE]", cn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BRANCHCODE", _branchCode); cmd.Parameters.AddWithValue("@ITEMCODE", _itemCode); cmd.Parameters.AddWithValue("@BRANCHPRICE", _branchPrice); cmd.Parameters.AddWithValue("@SELLINGPRICE", _sellingPrice); cn.Open(); cmd.ExecuteNonQuery(); } } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace AGC { public partial class ItemBranchPriceSetup : System.Web.UI.Page { cMaster oMaster = new cMaster(); cTransaction oTransaction = new cTransaction(); cSystem oSystem = new cSystem(); cUtil oUtility = new cUtil(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ViewState["BRANCHCODE"] = ""; DisplayBranchList(); } } #region "Local Function" //List of Branch //Diplay on Gridview #endregion //#region "PRINT AREA" //private void PRINT_NOW(string url) //{ // string s = "window.open('" + url + "', 'popup_window', 'width=1024, height=768, left=0, top=0, resizable=yes');"; // ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "ReportScript", s, true); //} protected void gvScheduleBranch_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow); if (e.CommandName == "Select") { ViewState["BRANCHCODE"] = row.Cells[0].Text; lblBranchName.Text = "Branch: <b>" + row.Cells[1].Text + "</b>"; txtSearch.Text = ""; Display_Branch_Price(ViewState["BRANCHCODE"].ToString()); } } //#endregion protected void lnkSave_Click(object sender, EventArgs e) { foreach (GridViewRow row in gvItems.Rows) { if (row.RowType == DataControlRowType.DataRow) { string itemCode = row.Cells[0].Text; string branchCode = ViewState["BRANCHCODE"].ToString(); TextBox txtBranchPrice = (TextBox)row.Cells[2].FindControl("txtBranchPrice"); TextBox txtSellingPrice = (TextBox)row.Cells[3].FindControl("txtSellingPrice"); double dBranchPrice, dSellingPrice; if (string.IsNullOrEmpty(txtBranchPrice.Text)) { dBranchPrice = 0; } else { dBranchPrice = Convert.ToInt32(txtBranchPrice.Text); } if (string.IsNullOrEmpty(txtSellingPrice.Text)) { dSellingPrice = 0; } else { dSellingPrice = Convert.ToInt32(txtSellingPrice.Text); } if (dBranchPrice != 0) { oUtility.UPDATE_BRANCH_PRICE(branchCode, itemCode, dBranchPrice, dSellingPrice); } } } // ddPartnerList.SelectedIndex = 0; // Display_Partner_Price(ddPartnerList.SelectedValue); // ViewState["BRANCHCODE"] = ""; ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>$('#modalSuccess').modal('show');</script>", false); lblSuccessMessage.Text = "Partner price successfully updated."; } private void Display_Branch_Price(string _branchCode) { DataTable dt = oUtility.GET_BRANCH_PRICE(_branchCode); if (dt.Rows.Count > 0) { gvItems.DataSource = dt; } else { gvItems.DataSource = null; lblBranchName.Text = ""; } gvItems.DataBind(); } private void DisplayBranchList() { DataTable dt = oMaster.GET_BRANCH_LIST(); gvBranchList.DataSource = dt; gvBranchList.DataBind(); } } }
64026edeec47e460f0f60a5a495f047fdbe51342
[ "Markdown", "C#" ]
19
C#
russelxrussel/AcesOfGrace
7fcfe63ce50aff51dfbe0461524c1e8d62a2fbb8
9b96f6793cbc02be5686c1f604c929baf331cf3e
refs/heads/master
<repo_name>levinzonr/spring-copsboot<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/security/AuthorizationServerConfiguration.kt package cz.levinzonr.CopsBoot.security import cz.levinzonr.CopsBoot.security.Constants.RESOURCE_ID import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer import org.springframework.security.oauth2.provider.token.TokenStore @Configuration @EnableAuthorizationServer class AuthorizationServerConfiguration : AuthorizationServerConfigurerAdapter() { @Autowired private lateinit var authenticationManager: AuthenticationManager @Autowired private lateinit var userDetailsService: ApplicationUserDetailsService @Autowired private lateinit var passwordEncoder: PasswordEncoder @Autowired private lateinit var tokenStore: TokenStore @Autowired private lateinit var securityConfiguration: SecurityConfiguration override fun configure(security: AuthorizationServerSecurityConfigurer?) { super.configure(security) security?.passwordEncoder(passwordEncoder) } override fun configure(clients: ClientDetailsServiceConfigurer?) { super.configure(clients) clients?.inMemory() ?.withClient(securityConfiguration.clientId) ?.authorizedGrantTypes("password", "refresh_token") ?.scopes("mobile_app") ?.resourceIds(RESOURCE_ID) ?.secret(passwordEncoder.encode(securityConfiguration.clientSecret)) } override fun configure(endpoints: AuthorizationServerEndpointsConfigurer?) { super.configure(endpoints) endpoints ?.tokenStore(tokenStore) ?.authenticationManager(authenticationManager) ?.userDetailsService(userDetailsService) } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/CopsBootApplication.kt package cz.levinzonr.CopsBoot import cz.levinzonr.CopsBoot.services.UserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.oauth2.provider.token.TokenStore import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore import org.springframework.boot.CommandLineRunner import org.springframework.context.ApplicationContext import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication @SpringBootApplication class CopsBootApplication { @Autowired private lateinit var userService: UserService @Bean fun passwordEncoder() : PasswordEncoder { return BCryptPasswordEncoder() } @Bean fun tokenStore() : TokenStore { return InMemoryTokenStore() } companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(CopsBootApplication::class.java, *args) } } @Bean fun commandLineRunner(ctx: ApplicationContext): CommandLineRunner { return CommandLineRunner { userService.createOfficer("<EMAIL>", "199616") } } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/exceptions/RestControllerExceptionHandler.kt package cz.levinzonr.CopsBoot.exceptions import cz.levinzonr.CopsBoot.domain.models.FiledErrorMessage import org.springframework.http.HttpStatus import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.ResponseStatus @ControllerAdvice class RestControllerExceptionHandler { @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) fun handle(exception: MethodArgumentNotValidException) : Map<String, List<FiledErrorMessage>> { return error(exception .bindingResult .fieldErrors .map { FiledErrorMessage(it.field, it.defaultMessage ?: "Unkwond") } .toList()) } private fun error(errors: List<FiledErrorMessage>) : Map<String, List<FiledErrorMessage>> { return mapOf("errors" to errors) } }<file_sep>/src/test/kotlin/cz/levinzonr/CopsBoot/UserRepositoryTest.kt package cz.levinzonr.CopsBoot import cz.levinzonr.CopsBoot.domain.models.User import cz.levinzonr.CopsBoot.domain.models.UserRole import cz.levinzonr.CopsBoot.domain.repository.UserRepository import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @DataJpaTest class UserRepositoryTest { @Autowired private lateinit var userRepository: UserRepository @Test fun testStoreUser() { val roles = setOf(UserRole.OFFICER) val user = userRepository.save(User( email = "<EMAIL>", password = "<PASSWORD>", role = roles )) assert(user != null) assert(user.id != null) assert(userRepository.count() == 1L) } @Test fun testFindByEmail() { val rolse = setOf(UserRole.OFFICER) val user = userRepository.save(User( email = "<EMAIL>", password = "<PASSWORD>", role = rolse )) var found = userRepository.findByEmailIgnoreCase("email") assert(found == null) found = userRepository.findByEmailIgnoreCase("<EMAIL>") assert(found != null) } }<file_sep>/src/main/resources/application.properties copsboot-security.client-id=copsboot-mobile-client copsboot-security.client-secret=<KEY><file_sep>/src/test/kotlin/cz/levinzonr/CopsBoot/ApplicationUserDetailsServiceTest.kt package cz.levinzonr.CopsBoot class ApplicationUserDetailsServiceTest { }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/services/UserServiceImpl.kt package cz.levinzonr.CopsBoot.services import cz.levinzonr.CopsBoot.domain.models.User import cz.levinzonr.CopsBoot.domain.models.UserRole import cz.levinzonr.CopsBoot.domain.repository.UserRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service import java.util.* @Service class UserServiceImpl : UserService { @Autowired private lateinit var userRepository: UserRepository @Autowired private lateinit var passwordEncoder: PasswordEncoder override fun createOfficer(email: String, password: String) : User { val user = userRepository.save(User( email = email, password = passwordEncoder.encode(password), role = setOf(UserRole.OFFICER) )) return user } override fun getUserById(uuid: UUID): User? { return userRepository.findById(uuid).get() } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/FiledErrorMessage.kt package cz.levinzonr.CopsBoot.domain.models data class FiledErrorMessage( val fieldName: String, val errorMessage: String )<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/security/ApplicationUserDetails.kt package cz.levinzonr.CopsBoot.security import cz.levinzonr.CopsBoot.domain.models.UserRole import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.User import java.util.* class ApplicationUserDetails(user: cz.levinzonr.CopsBoot.domain.models.User) : User(user.email, user.password, createAuthorities(user.role)) { val userId: UUID = user.id ?: UUID.randomUUID() companion object { private const val ROLE_PREFIX = "ROLE_" fun createAuthorities(roles: Set<UserRole>) : Collection<SimpleGrantedAuthority> { return roles.map { SimpleGrantedAuthority("$ROLE_PREFIX ${it.name}") } } } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/base/EntityId.kt package cz.levinzonr.CopsBoot.domain.models.base import java.io.Serializable import java.time.Year interface EntityId<T> : Serializable { fun getId() : T fun asString() : String }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/UserDto.kt package cz.levinzonr.CopsBoot.domain.models import java.util.* class UserDto( val userId: UUID?, val email: String?, val roles: Set<UserRole>? )<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/security/SecurityConfiguration.kt package cz.levinzonr.CopsBoot.security import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.PropertySource @Configuration @ConfigurationProperties(prefix = "copsboot-security") class SecurityConfiguration{ var clientId: String = "" var clientSecret: String = "" }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/security/Constants.kt package cz.levinzonr.CopsBoot.security object Constants { const val RESOURCE_ID = "" }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/controllers/UserRestController.kt package cz.levinzonr.CopsBoot.controllers import cz.levinzonr.CopsBoot.domain.models.CreateOfficeParameters import cz.levinzonr.CopsBoot.domain.models.UserDto import cz.levinzonr.CopsBoot.exceptions.ValueNotFoundException import cz.levinzonr.CopsBoot.security.ApplicationUserDetails import cz.levinzonr.CopsBoot.services.UserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.crossstore.ChangeSetPersister import org.springframework.http.HttpStatus import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.* import javax.validation.Valid @RestController @RequestMapping("/api/users") class UserRestController { @Autowired private lateinit var userService: UserService @GetMapping("/me") fun getCurrentUser(@AuthenticationPrincipal applicationUserDetails: ApplicationUserDetails) : UserDto { val user = userService.getUserById(applicationUserDetails.userId) ?: throw ValueNotFoundException("No user by id ${applicationUserDetails.userId}") return user.toDto() } @PostMapping() @ResponseStatus(HttpStatus.CREATED) fun createOfficer(@Valid @RequestBody parameters: CreateOfficeParameters) : UserDto { val user = userService.createOfficer(parameters.email, parameters.password) return user.toDto() } }<file_sep>/src/test/kotlin/cz/levinzonr/CopsBoot/Oath2ConfigurationTest.kt package cz.levinzonr.CopsBoot import cz.levinzonr.CopsBoot.security.SecurityConfiguration import cz.levinzonr.CopsBoot.services.UserService import org.junit.Test import org.junit.runner.RunWith 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.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic import org.springframework.test.context.junit4.SpringRunner import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* import org.springframework.util.LinkedMultiValueMap import org.springframework.util.MultiValueMap @RunWith(SpringRunner::class) @SpringBootTest @AutoConfigureMockMvc class Oath2ConfigurationTest { @Autowired private lateinit var mockMvc: MockMvc @Autowired private lateinit var userService: UserService @Autowired private lateinit var securityConfiguration: SecurityConfiguration @Test fun getTokenTest() { userService.createOfficer("<EMAIL>", "199616") val clientId = securityConfiguration.clientId val clientSecret = securityConfiguration.clientSecret val params = LinkedMultiValueMap<String, String>() params.add("grant_type", "password") params.add("client_id", clientId) params.add("client_secret", clientSecret) params.add("username", "<EMAIL>") params.add("password", "<PASSWORD>") mockMvc.perform(post("/oauth/token").params(params) .with(httpBasic(clientId, clientSecret)) .accept("application/json;charset=UTF-8")) .andExpect(status().isOk) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("access_token").isString()).andExpect(jsonPath("token_type") .value("bearer")).andExpect(jsonPath("refresh_token").isString()) .andExpect(jsonPath("expires_in").isNumber()).andExpect(jsonPath("scope") .value("mobile_app")) } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/UserRole.kt package cz.levinzonr.CopsBoot.domain.models enum class UserRole { OFFICER, CAPTAIN, ADMIN }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/base/Entity.kt package cz.levinzonr.CopsBoot.domain.models.base interface Entity<T: EntityId<T>> { fun getId() : T }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/security/WebSecurityConfiguration.kt package cz.levinzonr.CopsBoot.security import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter @Configuration class WebSecurityConfiguration : WebSecurityConfigurerAdapter(){ @Bean fun provideAuthenticationManager() : AuthenticationManager { return authenticationManager() } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/DevelopmentDbInit.kt package cz.levinzonr.CopsBoot import cz.levinzonr.CopsBoot.services.UserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.ApplicationArguments import org.springframework.boot.ApplicationRunner import org.springframework.context.annotation.Profile import org.springframework.stereotype.Component @Component class DevelopmentDbInit : ApplicationRunner { @Autowired lateinit var userService: UserService override fun run(args: ApplicationArguments?) { } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/security/ResourceServerConfiguration.kt package cz.levinzonr.CopsBoot.security import cz.levinzonr.CopsBoot.security.Constants.RESOURCE_ID import org.springframework.context.annotation.Configuration 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.oauth2.config.annotation.web.configuration.EnableResourceServer import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.BeanIds @Configuration @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) class ResourceServerConfiguration : ResourceServerConfigurerAdapter() { override fun configure(resources: ResourceServerSecurityConfigurer?) { super.configure(resources) resources?.resourceId(RESOURCE_ID) } override fun configure(http: HttpSecurity?) { super.configure(http) http?.let { http.authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll() .and() .antMatcher("/api/**") .authorizeRequests() .antMatchers(HttpMethod.POST, "/api/users").permitAll() .anyRequest()?.authenticated() } } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/repository/UserRepository.kt package cz.levinzonr.CopsBoot.domain.repository import cz.levinzonr.CopsBoot.domain.models.User import org.springframework.data.repository.CrudRepository import java.util.* interface UserRepository : CrudRepository<User, UUID> { fun findByEmailIgnoreCase(email: String) : User? }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/User.kt package cz.levinzonr.CopsBoot.domain.models import java.util.* import javax.persistence.* @Entity data class User( @Id @GeneratedValue val id: UUID? = null, val name: String = "", val email: String = "", val password: String = "", @ElementCollection(fetch = FetchType.EAGER) @Enumerated(EnumType.STRING) val role: Set<UserRole> ) { fun toDto() : UserDto { return UserDto( userId = id, email = email, roles = role ) } }<file_sep>/src/test/kotlin/cz/levinzonr/CopsBoot/UserRestControllerTest.kt package cz.levinzonr.CopsBoot import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import cz.levinzonr.CopsBoot.controllers.UserRestController import cz.levinzonr.CopsBoot.domain.models.CreateOfficeParameters import cz.levinzonr.CopsBoot.services.UserService import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.MediaType import org.springframework.http.ResponseEntity.status import org.springframework.test.context.junit4.SpringRunner import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post @RunWith(SpringRunner::class) @WebMvcTest(UserRestController::class) class UserRestControllerTest { @Autowired private lateinit var mvc: MockMvc @MockBean private lateinit var userService: UserService @Test fun testCreate() { val params = CreateOfficeParameters("a", "a") val res = mvc.perform(post("/api/users") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(jacksonObjectMapper().writeValueAsString(params))) .andReturn() assert(res.response.status == 400) verify(userService, never()).createOfficer("a", "a") } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/security/ApplicationUserDetailsService.kt package cz.levinzonr.CopsBoot.security import cz.levinzonr.CopsBoot.domain.repository.UserRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.stereotype.Service @Service class ApplicationUserDetailsService : UserDetailsService { @Autowired private lateinit var userRepository: UserRepository override fun loadUserByUsername(username: String?): UserDetails { username?.let { val user = userRepository.findByEmailIgnoreCase(it) ?: throw UsernameNotFoundException("No user by name $it") return ApplicationUserDetails(user) } throw NullPointerException("Email cant ve null") } }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/services/UserService.kt package cz.levinzonr.CopsBoot.services import cz.levinzonr.CopsBoot.domain.models.User import org.springframework.stereotype.Service import java.util.* @Service interface UserService { fun createOfficer(email: String, password: String) : User fun getUserById(uuid: UUID) : User? }<file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/base/BaseEntityId.kt package cz.levinzonr.CopsBoot.domain.models.base import java.io.Serializable import javax.persistence.MappedSuperclass @MappedSuperclass abstract class BaseEntityId<T: Serializable>( private val id: T? = null ) : Serializable, EntityId<T> <file_sep>/src/main/kotlin/cz/levinzonr/CopsBoot/domain/models/CreateOfficeParameters.kt package cz.levinzonr.CopsBoot.domain.models import javax.validation.constraints.Email import javax.validation.constraints.Size data class CreateOfficeParameters( @Email val email: String, @Size(min = 6, max = 100) val password: String )
b180604792b42e62bfc7eed49e6f199106dcd0dc
[ "Kotlin", "INI" ]
27
Kotlin
levinzonr/spring-copsboot
3786238e95540aa58daafd19c78a0d192c980760
23a7ef7ee528de12298caa5aa510a647decb0d1b
refs/heads/master
<file_sep>package com.store.customer.entities; import javax.persistence.*; import javax.validation.constraints.NotNull; @Entity public class ShippingAddress { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long shippingId; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "customerId",nullable = false) private Customer customer; @Embedded @NotNull(message="error.shippingAddress") private Address shippingAddress; public ShippingAddress() { } public Long getShippingId() { return shippingId; } public void setShippingId(Long shippingId) { this.shippingId = shippingId; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Address getShippingAddress() { return shippingAddress; } public void setShippingAddress(Address shippingAddress) { this.shippingAddress = shippingAddress; } } <file_sep>server.port=8761 spring.application.name=eureka-server eureka.client.register-with-eureka=false eureka.client.fetch-registry=false spring.cloud.config.uri=http://localhost:8888 management.security.enabled=false eureka.instance.hostname=localhost client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/ <file_sep>package com.store.customer.entities; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.validation.constraints.NotNull; @Embeddable public class Address { @Column @NotNull(message = "error.address.string") private String addressString; @Column @NotNull(message = "error.city") private String city; @Column @NotNull(message = "error.pincode") private Long pinCode; @Column @NotNull(message = "error.state") private String state; @Column @NotNull(message = "error.country") private String countryName; @Column @NotNull(message="error.phoneNumber") private Long phoneNumber; public Address() { } public Long getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(Long phoneNumber) { this.phoneNumber = phoneNumber; } public String getAddressString() { return addressString; } public void setAddressString(String addressString) { this.addressString = addressString; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Long getPinCode() { return pinCode; } public void setPinCode(Long pinCode) { this.pinCode = pinCode; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } } <file_sep>package com.store.cutomer.ws; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.shared.Applications; import com.store.customer.entities.Customer; import com.store.customer.repository.CustomerRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.Collection; @RefreshScope @RestController @RequestMapping("/customer-service") public class CustomerWS { private CustomerRepo customerRepo; @Autowired private EurekaClient eurekaClient; @GetMapping("/applications") public Applications getApplications() { return eurekaClient.getApplications(); } @Autowired public CustomerWS(CustomerRepo customerRepo) { this.customerRepo = customerRepo; } @Value("${dataPath:Hello default}") private String dataPath; @GetMapping("/getMessage") public String getMessage(){ return dataPath; } @GetMapping("/customers") public Collection<Customer> getAllCustomers(){ return customerRepo.findAll(); } @PostMapping("/addCustomer") public Customer addCustomer(@Validated @RequestBody Customer customer){ Customer customer1= customerRepo.save(customer); customerRepo.flush(); return customer1; } } <file_sep>package com.store.apiOrEdgeService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /* @RestController @RequestMapping("onlineStore") */ public class EStoreEdgeService { /*@GetMapping("/sample") public String callMicroservice(){ return ""; }*/ } <file_sep>spring.application.name=mainConfigServer server.port=8888 spring.cloud.config.server.git.uri=file://${user.home}/Desktop/Config<file_sep>package com.store.customer.repository; import com.store.customer.entities.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; @RepositoryRestResource(collectionResourceRel ="customer",path = "customer-service") public interface CustomerRepo extends JpaRepository<Customer,Long> { } <file_sep>error.name=Name cannot be empty error.email=invalid email address error.pincode= error.state= error.address.string= error.country= error.phoneNumber= <file_sep>package com.store.customer.repository; import com.store.customer.entities.ShippingAddress; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(path="customer-service") public interface ShippingAddressRepo extends JpaRepository<ShippingAddress,Long> { } <file_sep>package com.store.inventory.InventoryService; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @ComponentScan public class InventoryServiceApplication { public static void main(String[] args) { SpringApplication.run(InventoryServiceApplication.class, args); } } class MainCommand implements CommandLineRunner{ @Override public void run(String... strings) throws Exception { } } @RestController @RequestMapping("/inventory") class CatalogService{ @GetMapping("/getCatalogs") public String getCatalogData(){ return "{data:catalogs}"; } } <file_sep>package com.store.customer.entities; import javax.persistence.*; @Entity public class Favorites { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String favId; @Column private String itemId; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "customerId",nullable = false) private Customer customer; public Favorites() { } public String getFavId() { return favId; } public void setFavId(String favId) { this.favId = favId; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
109d375e70f083a96e957854f93bc4cf5f9001b6
[ "Java", "INI" ]
11
Java
prakashtaak/Microservices
921c1e37bcf34ed4eda11ecb444cce6e76c1536a
730c55aa23cd2fb096d7f1b63c15ce27a4107b06
refs/heads/master
<repo_name>aktzk/singleton<file_sep>/Singleton.h #pragma once #include <mutex> #include <memory> /* singleton class howto ~ ClassName::Instance()->MethodName(args); */ template <class T> class Singleton { public: using unique_ptr = std::unique_ptr<T>; static unique_ptr& Instance(){ if (!pInstance) { std::lock_guard<std::mutex> lock(mConstructed); pInstance = make_unique(); } return pInstance; } static void Release(){ std::lock_guard<std::mutex> lock(mConstructed); if (pInstance){ pInstance->reset(); } } protected: Singleton() {} ~Singleton() {} private: Singleton(Singleton const&) {} Singleton& operator=(Singleton const&) {} template <typename... Args> static unique_ptr make_unique(Args&&... args) { struct tmp: T{tmp(): T(){} }; return unique_ptr(new tmp(std::forward<Args>(args)...)); } static unique_ptr &ref() { static unique_ptr p = make_unique(); return p; } static unique_ptr pInstance; static std::mutex mConstructed; }; template <class T> std::mutex Singleton<T>::mConstructed; template <class T> std::unique_ptr<T> Singleton<T>::pInstance = nullptr; <file_sep>/readme.md - オレオレライブラリのC++11~計画 の一貫としてシングルトンクラスをスマートポインタ仕様にした。
40f8d9a1f2fe61e474a947b58937a1e2edf58165
[ "Markdown", "C++" ]
2
C++
aktzk/singleton
c34204ee643b167c981ecc25a8cc2b13c6300d10
220fb93f2ca6c6c1c81c31834f571456d0d5f641
refs/heads/master
<file_sep>require 'ruboto' require 'custom_methods' confirm_ruboto_version(6, false) java_import "android.provider.ContactsContract" java_import "android.content.ContentResolver" java_import "android.content.Context" java_import "android.database.Cursor" java_import "android.widget.ArrayAdapter" java_import "android.widget.CursorAdapter" java_import "android.widget.SimpleCursorAdapter" java_import "android.text.method.ScrollingMovementMethod" java_import "android.view.WindowManager" java_import "android.view.Gravity" java_import "android.view.KeyEvent" java_import "android.text.util.Linkify" java_import "android.app.AlertDialog" java_import "android.content.DialogInterface" java_import "android.content.Intent" java_import "android.net.Uri" java_import "android.app.AlertDialog" ruboto_import "org.ruboto.callbacks.RubotoOnTabChangeListener" ruboto_import "org.ruboto.callbacks.RubotoOnKeyListener" ruboto_import_widgets :TextView, :NumberPicker, :TabHost, :LinearLayout, :Button, :ListView, :TabWidget, :FrameLayout, :EditText, :ToggleButton, :ScrollView, :Spinner def contacts_list @cur = contacts_cursor @contacts = [] if @cur.getCount > 0 while @cur.moveToNext do @contacts << @cur.getString(@cur.getColumnIndex(ContactsContract::Contacts::DISPLAY_NAME)) end end @contacts end def cr @cr ||= getContentResolver end def contacts_cursor @contacts_cursor ||= cr.query ContactsContract::Contacts::CONTENT_URI, nil, nil, nil, nil @contacts_cursor end #call the contact def call(number) intent = Intent.new(Intent::ACTION_CALL) intent.setData(Uri.parse("tel:#{number}")) self.startActivity(intent) end def call_number_from_contact(contact_cursor) count_phone_numbers = contact_cursor.getString(contact_cursor.getColumnIndex(ContactsContract::Contacts::HAS_PHONE_NUMBER)).to_i return nil if count_phone_numbers == 0 id = contact_cursor.getString(contact_cursor.getColumnIndex(ContactsContract::Contacts::LOOKUP_KEY)) phone_cursor = cr.query( ContactsContract::CommonDataKinds::Phone::CONTENT_URI, nil, ContactsContract::Contacts::LOOKUP_KEY + " = ?", [id], nil) if phone_cursor.getCount == 1 phone_cursor.moveToFirst phone = phone_cursor.getString(phone_cursor.getColumnIndex(ContactsContract::CommonDataKinds::Phone::DATA)) phoneType = phone_cursor.getString(phone_cursor.getColumnIndex(ContactsContract::CommonDataKinds::Phone::TYPE)) phone_cursor.close call(phone) else adapter = SimpleCursorAdapter.new(self, R::layout::simple_list_item_1, phone_cursor, [ContactsContract::CommonDataKinds::Phone::DATA, ContactsContract::CommonDataKinds::Phone::TYPE], [AndroidIds::text1]) AlertDialog::Builder.new(self). setTitle("Phones list"). setAdapter(adapter, @alert_dialog_phones_select_listener). create. show end end @alert_dialog_phones_select_listener = RubotoOnItemClickListener.new.handle_item_click do |i| # call_number(i) Log.i("Click", "rubuto has been clicked") end $activity.start_ruboto_activity "$index" do setTitle "Time My Call" # setup_content do # @tabs = tab_host do # linear_layout(:orientation => LinearLayout::VERTICAL, :height => :fill_parent) do # tab_widget(:id => AndroidIds::tabs) # frame_layout(:id => AndroidIds::tabcontent, :height => :fill_parent) do # linear_layout :id => 55555, :orientation => LinearLayout::VERTICAL, :width => :fill_parent do # #select time # linear_layout :orientation => LinearLayout::HORIZONTAL do # @hour_picker = number_picker.setRange(0, 24) # @minutes_picker = number_picker.setRange(0, 60) # @second_picker = number_picker.setRange(0, 60) # end # text_view :text => "Select the time when to cut off the call" # linear_layout :orientation => LinearLayout::HORIZONTAL do # text_view :text => "Auto recall" # toggle_button :width => :wrap_content # end # button :text => "call" # end # @contacts = list_view :id => 55556, :list => contacts_list # linear_layout(:id => 55557, :orientation => LinearLayout::VERTICAL) do # end # end # end # end # registerForContextMenu(@contacts) # # @tabs.setup # @tabs.addTab(@tabs.newTabSpec("main").setContent(55555).setIndicator("Main")) # @tabs.addTab(@tabs.newTabSpec("contacts").setContent(55556).setIndicator("Contacts")) # @tabs.addTab(@tabs.newTabSpec("history").setContent(55557).setIndicator("History")) # @tabs.setOnTabChangedListener(@on_tab_change_listener) # @tabs # # end # # Tab change # # @on_tab_change_listener = RubotoOnTabChangeListener.new.handle_tab_changed do |tab| # if tab == "scripts" # getSystemService(Context::INPUT_METHOD_SERVICE). # hideSoftInputFromWindow(@tabs.getWindowToken, 0) # end # end setup_content do linear_layout :orientation => LinearLayout::VERTICAL do linear_layout :orientation => LinearLayout::VERTICAL, :gravity => Gravity::CENTER_HORIZONTAL do text_view :text => "Select the time when to cut off the call" linear_layout :orientation => LinearLayout::HORIZONTAL, :gravity => Gravity::CENTER_HORIZONTAL do @hour_picker = number_picker.setRange(0, 24) @minutes_picker = number_picker.setRange(0, 60) @second_picker = number_picker.setRange(0, 60) end startManagingCursor(contacts_cursor); @adapter = SimpleCursorAdapter.new(self, R::layout::simple_list_item_1, contacts_cursor, [ContactsContract::Contacts::DISPLAY_NAME], [AndroidIds::text1]) @contact_spinner = spinner :prompt => 'Choose your contact' @contact_spinner.setAdapter(@adapter) toggle_button :width => :wrap_content, :textOff => 'Auto recall OFF', :textOn => 'Auto recall ON' button :text => "CALL" end end end handle_create_options_menu do |menu| add_menu("Exit") {finish} true end handle_click do |view| case view.getText when "CALL": contact_cursor = @contact_spinner.getSelectedItem if contact_cursor call_number_from_contact(contact_cursor) end end end end <file_sep>#subclasses_of stolen from ActiveSupport # File activesupport/lib/active_support/core_ext/object/extending.rb, line 29 def subclasses_of(*superclasses) #:nodoc: subclasses = [] superclasses.each do |sup| ObjectSpace.each_object(Class) do |k| if superclasses.any? { |superclass| k < superclass } && (k.name.blank? || eval("defined?(::#{k}) && ::#{k}.object_id == k.object_id")) subclasses << k end end subclasses.uniq! end subclasses end # subclasses_of needs blank? # File activesupport/lib/active_support/core_ext/object/blank.rb, line 12 class Object def blank? respond_to?(:empty?) ? empty? : !self end end
71cef5cada0fc8292d752cb8b8d05a0661fc3bf8
[ "Ruby" ]
2
Ruby
jrichardlai/time_my_call
5bddda9b23459919348892dae3e5dddf60fbb104
52344773bb8752c84e74907f135127e16523e407
refs/heads/main
<file_sep>#!/bin/bash nohup ./main.pl 1>/dev/null 2>&1 & echo $! > pid.txt <file_sep>#!/bin/bash sudo cp autoget-agent.service /usr/lib/systemd/system/ sudo systemctl enable autoget-agent sudo service autoget-agent start sudo service autoget-agent status echo "Installed" <file_sep>#!/bin/bash sudo service autoget-agent stop sudo rm /usr/lib/systemd/system/autoget-agent.service echo "Uninstalled" <file_sep># AUTOGET AGENT ANSIBLE INSTALL ``` ansible-playbook -vvv install.yml -i example/inventory.yaml ``` UNINSTALL ``` ansible-playbook -vvv uninstall.yml -i example/inventory.yaml ```
20020aa4fca6af36b7a1bd3e61bce6d3115f136e
[ "Markdown", "Shell" ]
4
Shell
databean-kr/autoget-agent-ansible
0954b86ca90773d6ec0b77465ef63010b7d7b07d
02f9f788eaf3cdb8ee1fcdf16575524c8d55038c
refs/heads/master
<repo_name>diy4869/barrage<file_sep>/src/index.ts /* * @Author: <NAME> * @Date: 2020-06-01 16:53:44 * @LastEditTime: 2020-06-04 15:52:53 */ import Barrage from '@/core/index' // new Barrage({ // width: 700, // height: 400, // container: document.querySelector('.container') // }) export default Barrage <file_sep>/babel.config.js /* * @Author: <NAME> * @Date: 2020-06-04 13:50:43 * @LastEditTime: 2020-06-04 13:55:24 */ module.exports = { presets: [ [ '@babel/preset-env' ] ] }<file_sep>/postcss.config.js /* * @Author: <NAME> * @Date: 2020-06-04 13:25:57 * @LastEditTime: 2020-06-04 14:46:53 */ module.exports = { plugins: { autoprefixer: {} } }<file_sep>/README.md # barrage 视频弹幕 <file_sep>/src/core/index.ts /* * @Author: <NAME> * @Date: 2020-06-03 11:31:54 * @LastEditTime: 2020-06-04 17:15:02 */ import '@/assets/barrage.scss' interface BarrageOptions { container: HTMLElement, width: number, height: number } export default class Barrage { options: BarrageOptions canvas?: CanvasRenderingContext2D constructor (options: BarrageOptions) { this.options = options this.init() } init (): void { const canvas = document.createElement('canvas') canvas.width = this.options.width canvas.height = this.options.height canvas.className = 'barrage' this.options.container.appendChild(canvas) this.canvas = canvas.getContext('2d') } random (max: number): number { return Math.floor(Math.random() * max) } draw (text: string): void { console.log(1) this.canvas.font = '20px sans-serif' this.canvas.fillText(text, this.random(700), this.random(400)) console.log(this.canvas) } } <file_sep>/webpack/webpack.config.ts /* * @Author: <NAME> * @Date: 2020-06-01 16:52:41 * @LastEditTime: 2020-06-04 16:50:26 */ import path = require('path') import webpack = require('webpack') import HtmlWebpackPlugin = require('html-webpack-plugin') import MiniCssExtractPlugin = require('mini-css-extract-plugin') import { CleanWebpackPlugin } from 'clean-webpack-plugin' const config: webpack.Configuration = { mode: 'development', entry: path.join(__dirname, '../src/index.ts'), output: { path: path.join(__dirname, '../dist'), filename: '[name].js', library: 'Barrage', libraryTarget: 'umd', libraryExport: 'default', umdNamedDefine: true }, module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, // 'style-loader', 'css-loader' ] }, { test: /\.(sass|scss)$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader' ] }, { test: /\.js$/, use: [ 'eslint-loader', 'babel-loader' ] }, { test: /\.ts$/, use: [ 'eslint-loader', 'ts-loader' ] } ] }, resolve: { enforceExtension: false, extensions: ['.js', '.ts'], alias: { '@': path.join(__dirname, '../src') } }, devServer: { contentBase: path.join(__dirname, 'src'), host: 'localhost', port: 8000, hot: true, compress: true, noInfo: true, quiet: true, overlay: { warnings: true, errors: false }, clientLogLevel: 'none' }, plugins: [ new HtmlWebpackPlugin({ title: 'hello world', filename: 'index.html', inject: true, template: path.join(__dirname, '../src/page/index.html') }), new MiniCssExtractPlugin({ filename: 'assets/css/[name].[contentHash:8].css' }), new CleanWebpackPlugin(), new webpack.HotModuleReplacementPlugin() ] } export default config
03e4f15476bffe3417e25d6c6ece4322113e0dd4
[ "JavaScript", "TypeScript", "Markdown" ]
6
TypeScript
diy4869/barrage
0d21e914d5557f6791b977787b71a374fc004c0e
2a5edb4a4dfff5ec0ebea7537c60dec6a05c3fb6
refs/heads/master
<repo_name>brianwvincent/midi_music_gen<file_sep>/code/midi_testing2.py from midiutil.MidiFile import MIDIFile # degrees = [60, 62, 64, 65, 67, 69, 71, 72] # MIDI note number # degrees = list(range(60, 75)) # degrees = [60, 64, 67] degrees = [62,65,69,72] track = 0 channel = 0 time = 0 # In beats duration = 4 # In beats tempo = 120 # In BPM volume = 100 # 0-127, as per the MIDI standard MyMIDI = MIDIFile(1) # One track MyMIDI.addTempo(track, time, tempo) # for pitch in degrees: # MyMIDI.addNote(track, channel, pitch, time, duration, volume) # time = time + 1 for pitch in degrees: MyMIDI.addNote(track, channel, pitch, time, duration, volume) with open("major-scale.mid", "wb") as output_file: MyMIDI.writeFile(output_file)<file_sep>/code/Driver_MusicGeneration.py import GeneticAlgorithm if __name__ == '__main__': ga = GeneticAlgorithm.GeneticAlgorithm() ga.runGA() <file_sep>/code/GeneticAlgorithm.py import Population import pandas as pd import numpy as np class GeneticAlgorithm: '''Class and its interface represents a general Genetic Algorithm''' def __init__(self, num_generations=50, population_size=21, crossover_prob=0.8, mutation_prob=0.1, **kwargs): self.statsFileName = 'MidiMusicStatsFile.csv' self.statsDf = pd.DataFrame() self.numOfGenerations = num_generations self.populationSize = population_size self.population = Population.Population(population_size) self.crossover_probability = crossover_prob self.mutation_probability = mutation_prob self.avgFitArray = np.empty(1) self.bestFitArray = np.empty(1) self.worstFitArray = np.empty(1) self.varianceFitArray = np.empty(1) self.stdDevFitArray = np.empty(1) self.completed = False for key,arg in kwargs: self.key = arg def _collectStats(self, generation): """Method collects population statistics and checks for stopping condition""" # calculate fitness of population f = self.population.calculateFitness() # collect population stats avg = self.population.getAvgPopulationFitness() best = self.population.getBestPopulationFitness() worst = self.population.getWorstPopulationFitness() stats = self.population.getPopulationFitnessStats() # append generation stats to numpy arrays self.avgFitArray = np.append(self.avgFitArray, avg) self.bestFitArray = np.append(self.bestFitArray, best) self.worstFitArray = np.append(self.worstFitArray, worst) self.varianceFitArray = np.append(self.varianceFitArray, stats['variance']) self.stdDevFitArray = np.append(self.stdDevFitArray, stats['std_dev']) # check if any agent has reached chord if self.population._chordReached(): self.completed = True self._writeToFile() # print stats to screen # print('Gen: {3}, AvgFitness: {0}, BestFitness: {1}, WorstFitness: {2}'.format(avg, best, worst, generation)) print('Gen: {5}, AvgFitness: {0}, BestFitness: {1}, WorstFitness: {2}, FitStdDev: {3}, FitVar: {4}'.format( avg, best, worst, stats['std_dev'], stats['variance'], generation)) # if solution has been reached # if best >= 1: # print('Chord Reached!!! ') # # # mark as successful # self.successful = True # # # write # self._writeToFile() # exit() def _writeToFile(self): # write top agent for agent in self.population.all_agents: if agent.manual_fitness == 1: agent.writeToFile() # write stats to DataFrame self.statsDf = pd.DataFrame({'Avg': self.avgFitArray, 'Best': self.bestFitArray, 'Worst': self.worstFitArray, 'FitStdDev': self.stdDevFitArray, 'FitVariance': self.varianceFitArray}) self.statsDf.to_csv(self.statsFileName) def runGA(self): # initialize current population self.population.initialize_population() # iterate through preset number of generations for ii, gen in enumerate(range(self.numOfGenerations)): # collect population stats and check stopping condition self._collectStats(gen) if self.completed: return # create empty population pprime = self.population.createEmptyPopulation() # repeat until new generation is full while not pprime.isFull(): # get elite agent(s) elite_agents = self.population.getEliteAgents() pprime.addIndividuals(elite_agents) # select 2 individuals based on some fitness agents = self.population.selectTwoIndividuals(pprime) # stochastic perform crossover if np.random.rand(1)[0] > (1 - self.crossover_probability): agents[0], agents[1] = self.population.performCrossover(agents[0], agents[1], self.population) # optionally mutate if np.random.rand(1)[0] > (1 - self.mutation_probability): agents[0] = self.population.performMutation(agents[0]) agents[1] = self.population.performMutation(agents[1]) # add both new individuals to new generation pprime.addIndividual(agents[0]) pprime.addIndividual(agents[1]) # replace old population with new self.population = pprime # if generation run has completed; no solution found self._writeToFile() <file_sep>/code/midi_testing.py import pygame import time if __name__ == '__main__': print('hello world!') pygame.mixer.init() pygame.mixer.music.load('major-scale.mid') # pygame.mixer.music.load('mary_had_a_little_lamb_pno.mid') pygame.mixer.music.play() time.sleep(4) pygame.mixer.music.stop()<file_sep>/code/Agent.py import pygame import numpy as np from midiutil.MidiFile import MIDIFile import time class Agent: def __init__(self): self.agent_unique_score = 0.76 self.manual_fitness = 0 self.agent_history = {'C_Maj': [], 'D_Min': [], 'E_Min': [], 'C_Maj_7': [], 'bitstring': [], 'manual_fitness': []} self.note_int_val = -1 self.note_numlist = list(range(60, 72)) self.note_bitstring = self._init_genome() self.filename = '' self.track = 0 self.channel = 0 self.time = 0 # in beats self.duration = 2 # in beats self.tempo = 60 # In BPM self.volume = 100 # 0-127, as per the MIDI standard def _init_genome(self): # choose starter notes temp_list = list(range(len(self.note_numlist))) n1 = np.random.choice(temp_list) n2 = np.random.choice(temp_list) result_list = [] result_str = '' for ii in temp_list: if ii == n1 or ii == n2: result_list.append(1) result_str += '1' else: result_list.append(0) result_str += '0' # calculate note int value self.note_int_val = int(result_str, 2) # return bit string return result_list def _play_midi_file(self): pygame.mixer.init() pygame.mixer.music.load(self.filename) pygame.mixer.music.play() time.sleep(3) pygame.mixer.music.stop() def _produce_phenotype(self): ''' Generate MIDI file''' MyMIDI = MIDIFile(1) # One track MyMIDI.addTempo(self.track, self.time, self.tempo) for ii, note in enumerate(self.note_bitstring): if note > 0: MyMIDI.addNote(self.track, self.channel, self.note_numlist[ii], self.time, self.duration, self.volume) with open(self.filename, "wb") as output_file: MyMIDI.writeFile(output_file) def _get_listener_score(self, population): val = 0 while val not in [1,2,3,4,5]: try: # generate MIDI file self._produce_phenotype() # play MIDI file self._play_midi_file() # val = int(input('Please provide a score: 5)Really Like 4)Like 3)Neutral 2)Dislike 1)Really Dislike, 0) Play Again')) val = int(input( 'Please provide a score: 1)Really Dislike, 2)Dislike, 3)Neutral, 4)Like, 5)Really Like, 6)Play Again, 7)Re-Create Population (file: {}) '.format(self.filename))) except: print('Sorry, you input an incorrect value, please provide score: 1-5') self.manual_fitness = val self.agent_history['manual_fitness'].append(val) return None def setAgentFileNumber(self, agent_number): self.filename = 'agent' + str(agent_number) + '.mid' def calcAgentFitness(self, population): # get listener's score s = self._get_listener_score(population) return s def isUniqueTo(self, other_agents): '''Method to determine if agent is unique to other agents''' total_bits = len(self.note_bitstring) for ii, agent in enumerate(other_agents): score = 0.0 for jj, myBit in enumerate(self.note_bitstring): otherBit = agent.note_bitstring[jj] if myBit == otherBit: score += 1 similarity = score / total_bits if similarity > self.agent_unique_score: return False # agent is unique to other agents return True def writeToFile(self): '''Method to write representation of Agent to file''' d = self.agent_history with open(self.filename, 'wb') as f: for ii in range(len(self.agent_history['bitstring'])): row = str(d['manual_fitness']) + ',' + str(d['C_Maj']) + ',' + str(d['D_Min']) + ',' + str(d['E_Min']) +\ ',' + str(d['C_Maj_7']) + ',' + str(d['bitstring']) + '\n' f.write(row) <file_sep>/code/Population.py from Agent import Agent import numpy as np import math import copy class Population: def __init__(self, numAgents): self.tournament_select_prob = 0.8 self.num_agents = numAgents self.all_agents = [] self.elite_agent_ii = -1 self.chord_reached = False self.population_fitness = 0 self.all_chords = [ {'note': 'C_Maj', 'bit_string': [1,0,0,0,1,0,0,1,0,0,0,0], 'bit_int': 2192, 'positive_bits': 3}, {'note': 'D_Min', 'bit_string': [0,0,1,0,0,1,0,0,0,1,0,0], 'bit_int': 580, 'positive_bits': 3}, {'note': 'E_Min', 'bit_string': [0,0,0,0,1,0,0,1,0,0,0,1], 'bit_int': 145, 'positive_bits': 3}, {'note': 'C_Maj_7', 'bit_string': [1,0,0,0,1,0,0,1,0,0,0,1], 'bit_int': 2193, 'positive_bits': 4}] def isFull(self): '''Check if population is full''' if len(self.all_agents) == self.num_agents: return True else: return False def selectTwoIndividuals(self, population): result_agents = [] rands = np.random.random(2) # get random numbers [0,1] # select 4 DIFFERENT agents at random agent_set = set() while len(agent_set) < 4: # get individual agent_set.add(np.random.choice(self.all_agents)) # perform tournament selection on first 2 agents if rands[0] < self.tournament_select_prob: result_agents.append(copy.deepcopy(list(agent_set)[0])) else: result_agents.append(copy.deepcopy(list(agent_set)[1])) # perform tournament selection on second 2 agents if rands[1] < self.tournament_select_prob: result_agents.append(copy.deepcopy(list(agent_set)[2])) else: result_agents.append(copy.deepcopy(list(agent_set)[3])) return result_agents def initialize_population(self): # instantiate all agents in population for ii in range(self.num_agents): self.all_agents.append(Agent()) def createEmptyPopulation(self): return Population(self.num_agents) def addIndividual(self, agent): """Method adds manually agent to population iff population is not full""" if not self.isFull(): self.all_agents.append(copy.deepcopy(agent)) def addIndividuals(self, agents): for agent in agents: self.addIndividual(agent) def performCrossover(self, agent1, agent2, population): # choose single point for crossover swap_point = np.random.choice(list(range(len(self.all_agents)))) # swap genome at chosen point on each agent genome1 = agent1.note_bitstring[swap_point:] genome2 = agent2.note_bitstring[swap_point:] agent1.note_bitstring[swap_point:] = genome2 agent2.note_bitstring[swap_point:] = genome1 # return agent crossover results return agent1, agent2 def performMutation(self, agent): # choose single point for mutation swap_point = np.random.choice(list(range(len(self.all_agents)))) # mutate at point bit = agent.note_bitstring[swap_point] bit = 1 - bit agent.note_bitstring[swap_point] = bit return agent def calculateFitness(self): '''Method to Calculate fitness of all Agents''' # keep track of fitness sum pop_fitness = 0 for ii, agent in enumerate(self.all_agents): # set agent file number agent.setAgentFileNumber(ii) # play agent notes and record fitness agent.calcAgentFitness(self) pop_fitness += agent.manual_fitness # calculate agent CHORD fitness for jj,chord in enumerate(self.all_chords): correct_num = 0.0 total_num = len(chord['bit_string']) for kk, bit in enumerate(chord['bit_string']): if bit == agent.note_bitstring[kk]: correct_num += 1 # assign chord fitness chord_fitness = correct_num / total_num c_name = chord['note'] agent.agent_history[c_name].append(chord_fitness) # check for success if chord_fitness == 1: self.chord_reached = True # record agent's note bitstring agent.agent_history['bitstring'].append(agent.note_bitstring) # assign population fitness as SUM of all fitness self.population_fitness = pop_fitness def _chordReached(self): return self.chord_reached def getEliteAgents(self): '''Function to return agents of highest fitness within a each species''' # get highest fitness in population best_fitness = self.getBestPopulationFitness() # get list of all agents with highest fitness best_agents = self.getAgentsWithFitness(best_fitness) # iterate and check their uniqueness if more than 1 best_agent if len(best_agents) > 1: result = [] for ii, agent in enumerate(best_agents): if ii==0: # always add first agent result.append(agent) else: if agent.isUniqueTo(result): result.append(agent) return result else: return best_agents def getPopulationFitness(self): '''Method returns fitness (Sum) of all Agents in population''' return self.population_fitness def getAvgPopulationFitness(self): """Method returns Average Population Fitness""" return round(self.population_fitness / float(self.num_agents), 2) def getBestPopulationFitness(self): """Method returns Best fitness of Agent of population""" all_fit = list(map(lambda x: x.manual_fitness, self.all_agents)) return max(all_fit) def getWorstPopulationFitness(self): """Method returns Worst fitness of Agent of population""" all_fit = list(map(lambda x: x.manual_fitness, self.all_agents)) return min(all_fit) def getPopulationFitnessStats(self): """Method returns a dictionary containing variaous statistics including Standard Deviation and Variance""" mean = self.getAvgPopulationFitness() var = sum(map(lambda agent: math.pow(agent.manual_fitness - mean, 2), self.all_agents)) std = math.sqrt(var) return {'variance': var, 'std_dev': std} def getAgentsWithFitness(self, fitness_score): '''Function to get all agents of fitness: fitness_score''' result = [] for ii, agent in enumerate(self.all_agents): if agent.manual_fitness == fitness_score: result.append(agent) return result
1c028cf90113e5c7d454a5e2082d338fb8097825
[ "Python" ]
6
Python
brianwvincent/midi_music_gen
4a4d7b5a634fc3ae6b49583997e8954771cd9148
5772490b6b1b1d03474f8eaa7162468d9235fa38
refs/heads/main
<file_sep>package br.com.mudi.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import br.com.mudi.models.Pedido; import br.com.mudi.models.StatusPedido; import br.com.mudi.repositories.PedidoRepository; @Controller @RequestMapping("/home") public class IndexController { @Autowired private PedidoRepository pedidoRepository; @GetMapping("/") public String index() { return "index"; } @GetMapping public String home(Model model) { List<Pedido> pedidos = pedidoRepository.findAll(); model.addAttribute("pedidos", pedidos); return "home"; } @GetMapping("/{status}") public String status(@PathVariable("status") String status, Model model) { List<Pedido> pedidos = pedidoRepository.findByStatus(StatusPedido.valueOf(status.toUpperCase())); model.addAttribute("pedidos", pedidos); model.addAttribute("status", status); return "home"; } @ExceptionHandler(IllegalArgumentException.class) public String onError() { return "redirect:/home"; } } <file_sep>package br.com.mudi.models; public enum StatusPedido { AGUARDANDO, APROVADO, ENTREGUE; }
fe55b1f57bf4f7c8da693a66e364f96154a0f7da
[ "Java" ]
2
Java
RaifePaiva/mudi_application_springMVC
4c27359026180de9359d82ec41df315e9f0631a7
38bdcbaed036bd3094213a66d6a0b8b4d0ec2825
refs/heads/master
<repo_name>roman1k/lambdas<file_sep>/src/demoFInterfaces/Main.java package demoFInterfaces; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { Calculator calculator = new Calculator() { @Override public void calcluate(int a, int b) { System.out.println(a+b); } }; calculator.calcluate(90,90); Calculator calculator1 = (a, b) -> { System.out.println(a+b); }; List<User> users = new ArrayList<>(); users.add(new User(1, "Oleg", true)); users.add(new User(2, "Vasya", false)); users.add(new User(3, "jonh", true)); users.add(new User(4, "Olya", true)); users.add(new User(5, "maryna", true)); users.add(new User(6, "Marta", true)); users.add(new User(6, "Marta", true)); // Stream<User> stream = users.stream(); // Stream<User> distinct = stream.distinct(); // List<User> collect = distinct.collect(Collectors.toList()); // System.out.println(collect); List<User> userList = users .stream() .distinct() .filter(user -> user.isStatus()) .filter(user -> user.getId()%2==0) .filter(user -> user.getName().length()>3) .sorted((o1, o2) -> o2.getId() - o1.getId()) .collect(Collectors.toList()); System.out.println(userList); Map<Integer, String> map = userList.stream().collect( Collectors.toMap( user -> user.getId(), user -> user.getName() )); System.out.println(map); } } <file_sep>/src/demoFInterfaces/Calculator.java package demoFInterfaces; public interface Calculator { void calcluate(int a, int b); }
99c12e3e61c21621c4aed08f048ef3ee5d794f5e
[ "Java" ]
2
Java
roman1k/lambdas
2bdd21de3127a5c37622f0de0ef4020e15006417
0cec99b3097e148c9343c19ea8ecdee44d97cdb6
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Pygments unit tests ~~~~~~~~~~~~~~~~~~ Usage:: python run.py [testfile ...] :copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import sys, os if sys.version_info >= (3,): # copy test suite over to "build/lib" and convert it print ('Copying and converting sources to build/lib/test...') from distutils.util import copydir_run_2to3 testroot = os.path.dirname(__file__) newroot = os.path.join(testroot, '..', 'build/lib/test') copydir_run_2to3(testroot, newroot) os.chdir(os.path.join(newroot, '..')) try: import nose except ImportError: print ("nose is required to run the test suites") sys.exit(1) nose.main()
adfb9b91518752b361713594eacd850557f7721b
[ "Python" ]
1
Python
erickt/pygments
05d4b6ce7e51501d2ac22919386017c08c9f5547
6223c688cbb6ef81ab3f73d6aa7da9fa796bb6c4
refs/heads/main
<file_sep># Code for knn min = -4 max = 8 def knn(): ks = [2, 8, 35] x = np.arange(min, max, ((max - min) / 300)) d = cdist(x.reshape(x.shape[0], 1), trainingData.values.reshape(trainingData.values.shape[0], 1), metric="minkowski") for k in ks: y = np.empty(x.shape) for i, val in enumerate(d): V = val[np.argpartition(val, range(k))[:(k)]][-1] y[i] = k / (trainingData.values.shape[0] * V * 2) plt.plot(x, y, label="k={}".format(k)) plt.ylabel('Density Function') plt.xlabel('x') plt.legend() plt.show() knn() <file_sep>#Code for exception maximization k = 4 def em(): covar = np.array( [np.identity(data.shape[1]) for _ in range(k)]) mu = np.random.uniform(data.min().min(), data.max().max(), size=(k, data.shape[1])) pi = np.random.uniform(size=(k,)) likelihood = np.empty((30,)) for i in range(30): alpha = e( covar, pi, mu, data.values) mu, covar, pi = m(data.values, alpha) if i + 1 in [1, 3, 5, 10, 30]: plt.figure(i) vis(data.values, i, mu, covar) likelihood[i] = logLikelihood(data.values, mu, covar, pi) def m(x, alpha): N = np.sum(alpha, axis=1) m = np.zeros((k, x.shape[1])) c = np.zeros((k, x.shape[1], x.shape[1])) for i in range(k): for j, val in enumerate(x): m[i] += (alpha[i, j] * val) m[i] /= N[i] for j, val in enumerate(x): c[i] += alpha[i, j] * np.outer(val - m[i], (val - m[i]).T) c[i] /= N[i] pi = N / x.shape[0] return m, c, pi def e(c, pi, m, x): alpha = np.empty((k, x.shape[0])) for i in range(k): alpha[i] = pi[i] * gaussian(x, m[i], c[i]) return alpha / np.sum(alpha, axis=0) def gaussian(data, m, c): res = np.empty(data.shape[0]) for i, x in enumerate(data): diff = x - m res[i] = np.exp(-.5 * diff.T.dot(np.linalg.inv(c)).dot(diff)) \ / np.sqrt((2 * math.pi) ** data.shape[1] * np.linalg.det(c)) return res def logLikelihood(x, m, c, pi): logLikelihood = np.empty((k, x.shape[0])) for i in range(k): logLikelihood[i] = pi[i] * gaussian(x, m[i], c[i]) return np.sum(np.log(np.sum(logLikelihood, axis=0))) def vis(data, iteration, m, c): x = np.arange(data[:, 0].min() - 1, data[:, 0].max() + 1, (data[:, 0].max() - data[:, 0].min() + 2) / 100) y = np.arange(data[:, 1].min() - 1, data[:, 1].max() + 1, (data[:, 1].max() - data[:, 1].min() + 2) / 100) Y, X = np.meshgrid(y, x) Z = np.empty((100, 100)) for i in range(k): for j in range(100): points = np.append(X[j], Y[j]).reshape(2, x.shape[0]).T Z[j] = gaussian(points, m[i], c[i]) em() <file_sep># Code for kde min = -4 max = 8 def kernel(x, data, sigma): return (np.sum(np.exp(-(x - data) ** 2 / (2 * sigma ** 2)))) / (np.sqrt(2 * math.pi) * len(data) * sigma) def kde(): sigmas = [0.03, 0.2,.8] x = np.arange(min, max, ((max - min) / 500)) plt.figure() for sigma in sigmas: y = np.empty(trainingData.values.shape[0]) for i, val in enumerate(trainingData.values): y[i] = kernel(val, trainingData.values, sigma) y = np.empty(x.shape) for i, val in enumerate(x): y[i] = kernel(val, trainingData.values, sigma) plt.plot(x, y, label="$\sigma=$" + str(sigma)) plt.ylabel('Density function') plt.xlabel('x') plt.legend() plt.show() kde() <file_sep>import numpy as np import matplotlib.pyplot as plt def markovChain(s0, p, g): s = s0.copy() result = np.zeros(g+1) result[0]=s[0] for i in range(1, g+1): s = s.dot(p) result[i]=s[0] return result s0 = np.array([1, 0]) s1 = np.array([0.026, 0.974]) p = np.array([[0.42, 0.58],[0.026, 0.974]]) n = np.arange(0, 19, 1) gen18 = markovChain(s0, p, 18) gen18prog = markovChain(s1, p, 18) plt.plot(n, gen18, 'b') plt.plot(n, gen18prog, 'r') plt.xlabel('Generations') plt.ylabel('Probability') plt.title('Virus through the generations Task 3') plt.grid(True) plt.show() <file_sep>import math import random #Task 1a #Function for calculating f'(x) def solveDerivative(x): #Calculate Derivative f'(x) result = 400 * math.pow(x, 3) + (2-400*(x+1)) * x-2 #print('f\'(', x,') =', result) #print result return result n = 20 #needs to be surprisingly small for decent results. learningRate = 0.000001 #Randomly determine starting x curX = random.randint(1, n-1) for curIteration in range(1, 10000): curResult = solveDerivative(curX) print(curIteration, " : f\'(", curX,") =", curResult) #negate to always move towards negative diff = learningRate * -curResult #apply to curX for next iteration curX += diff if curIteration % 2000 == 0: input("Press Enter to continue...") print("final X is", curX, "; with f\'(",curX,")= ", solveDerivative(curX) ) #Learning rate impacts the size of the "steps" we take in each iteration. Since we are approximating, we generally step over the lowest point at some point, and then start stepping back and forth over the lowest point. A smaller learning rate will lead to smaller steps.. #while moving towards the lowest point, but to a larger gap created by stepping back and forth over the lowest point once it has been found. #Larger learning rates lead to fast, unaccurate conclusions, smaller rarely come to a conclusion within 10k iterations. Choose the learning rate just right to get a accurate conclusion, while still arriving at the conclusion in most cases. #(conclusion meaning the lowest point)<file_sep> def markovChain(s0, p, g): s = s0.copy() result = np.zeros(g+1) result[0]=s[0] for i in range(1, g+1): s = s.dot(p) result[i]=s[0] return result s0 = np.array([1, 0]) s1 = np.array([0.026, 0.974]) p = np.array([[0.42, 0.58],[0.026, 0.974]]) n = np.arange(0, 19, 1) gen18 = markovChain(s0, p, 18) gen18prog = markovChain(s1, p, 18) <file_sep># Code for histogram trainingData = p.read_csv("nonParamTrain.txt", sep="\s{2}") testData = p.read_csv("nonParamTest.txt", sep="\s{2}") trainingData.columns = testData.columns = ["value"] def histo(): size = [0.02, 0.5, 2.0] for i, s in enumerate(size): plt.figure(i) trainingData.plot.hist(by="value", bins=math.ceil(trainingData.max().value / s)) plt.xlabel("x") plt.title("Histogram {}".format(s)) histo() plt.show() <file_sep>import math import random import numpy #Task 2a #Function for finding the maximum likelihood for given s within x = -100...100 def findMaximum(s): if s == 0: return "Undefined" values = [0]*100 for x in range(0, 100): values[x] = 1/s * math.exp(-x/s) max_value = numpy.max(values) return max_value print("Launching...") for s in range(-40,41): print("Maximum of s=", s, ": ", findMaximum(s)) print("Maximum of s=", 0.001, ": ", findMaximum(0.001))<file_sep>import os import math import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from scipy.interpolate import griddata d = '.\dataSets\Aufgabe3' arrayC1 = [] arrayC2 = [] C1Prob = 0 C2Prob = 0 C1Weights = [] C2Weights = [] #Reads files, saves them in the above variables def ReadFiles(): print("Launching...") for filename in os.listdir(d): if not filename.endswith('.txt'): continue filename = d+"\\"+filename; with open(filename, 'r') as f: for line in f.readlines(): #Results in an array with three elements, first is just empty, second is the first value, third is the second value+\n lineArray = line.split(' ') #print(lineArray) #So we do some formatting to clean up the mess lineArray[2] = lineArray[2][:-1] lineArray.pop(0) #print(lineArray) if(filename.endswith("1.txt")): arrayC1.append(float(lineArray[0])) arrayC1.append(float(lineArray[1])) if(filename.endswith("2.txt")): arrayC2.append(float(lineArray[0])) arrayC2.append(float(lineArray[1])) #print("Listing C1: \n", arrayC1) def CalcMean(data): total = 0 entryCount = 0 for entry in data: total += entry entryCount += 1 return total / entryCount #https://www.khanacademy.org/m ath/statistics-probability/summarizing-quantitative-data/variance-standard-deviation-population/a/calculating-standard-deviation-step-by-step def CalcDeviation(data, mean): distArray = [] distTotal = 0 for entry in data: distTotal += pow(mean - entry, 2) final = math.sqrt(distTotal / len(data)) return final def CalcLikelihood(x, mean, deviation): r1 = 1/math.sqrt(2*math.pi*pow(deviation, 2)) #print(r1) r2 = -pow(x-mean, 2) r2 = -pow(x, 2) +2*mean*x -pow(mean,2) #print(r2) r3 = 2*pow(deviation, 2) #print(r3) result = r1 * pow(math.e, r2/r3) return result def CalcMaxLikelihood(data, mean, deviation): result = 0.0 for entry in data: result += CalcLikelihood(entry, mean, deviation) return result ReadFiles() #for prob in arrayC1: # C1Prob += prob #for prob in arrayC2: # C2Prob += prob #C1Prob /= len(arrayC1) #C2Prob /= len(arrayC2) print("Size C1: ", len(arrayC1)) print("Size C2: ", len(arrayC2)) totalEntries = len(arrayC1) + len(arrayC2) C1Prior = len(arrayC1) / totalEntries C2Prior = len(arrayC2) / totalEntries print("\n C1 prior:", C1Prior, "; C2 prior:", C2Prior) #http://jrmeyer.github.io/machinelearning/2017/08/18/mle.html#:~:text=When%20using%20Maximum%20Likelihood%20Estimation,standard%20deviation%20of%20the%20data. C1Mean = CalcMean(arrayC1) C2Mean = CalcMean(arrayC2) print("\n C1 mean:", C1Mean, "; C2 mean:", C2Mean) C1Deviation = CalcDeviation(arrayC1, C1Mean) C2Deviation = CalcDeviation(arrayC2, C2Mean) print("\n C1 deviation:", C1Deviation, "; C2 deviation:", C2Deviation) print("TESTRESULT: ", CalcLikelihood(5, C1Mean, C1Deviation)) C1MaxLikelihood = CalcMaxLikelihood(arrayC1, C1Mean, C1Deviation) C2MaxLikelihood = CalcMaxLikelihood(arrayC2, C2Mean, C2Deviation) print("\n C1 MaxLikelihood:", C1MaxLikelihood, "; C2 MaxLikelihood:", C2MaxLikelihood) for entry in arrayC1: C1Weights.append(CalcLikelihood(entry, C1Mean, C1Deviation)) for entry in arrayC2: C2Weights.append(CalcLikelihood(entry, C2Mean, C2Deviation))
b19b0b8db07cf04728d593bc06023272f6c25fe1
[ "Python" ]
9
Python
KL4USIE/Statistical-Machine-Learning
a667d21fbcbbc3c27aa3099ab19403e94aea8b1f
34f58ea58c7ab130e029c2eb4e7d4f11cbb96300
refs/heads/master
<repo_name>vbatsiushkova/Framework<file_sep>/src/test/java/calculatoJUnitTest/CalculatorSqrtDoubleTest.java package calculatoJUnitTest; import junitparams.Parameters; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.StringContains.containsString; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorSqrtDoubleTest extends BaseCalculatorTestParameters { @Test @Parameters({ "9|3", "15|3.873" }) public void testSqrtDouble(double arg1, double expected) { double actual = round(calculator.sqrt(arg1)); assertThat("Sgrt of the " + arg1, actual, is(equalTo(expected))); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testSqrtExeption(){ thrown.expect(NumberFormatException.class); thrown.expectMessage(containsString(" ")); round(calculator.sqrt(-16)); } } <file_sep>/src/test/java/CalculatorTestNG/CalculatorIsPositiveTest.java package CalculatorTestNG; import org.testng.Assert; import org.testng.annotations.Test; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorIsPositiveTest extends BaseCalculatorTest { long arg1; boolean expected; public CalculatorIsPositiveTest(long arg1, boolean expected) { this.arg1 = arg1; this.expected = expected; } @Test public void testIsPositive() { boolean actual = calculator.isPositive(arg1); Assert.assertEquals(actual,expected); timeout.sleep(5); checkTime(); } } <file_sep>/src/test/java/calculatoJUnitTest/BaseCalculatorTestParameters.java package calculatoJUnitTest; import com.epam.tat.module4.Calculator; import junitparams.JUnitParamsRunner; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; /** * Created by Volha_Batsiushkova on 12/11/2017. */ @RunWith(JUnitParamsRunner.class) public class BaseCalculatorTestParameters { protected static Calculator calculator; @BeforeClass public static void setUp() { System.out.println("Config prepare calculator"); calculator = new Calculator(); } @AfterClass public static void closeClass() { System.out.println("Test is executed"); } protected double round(double value) { return (double) Math.round(value * 10000d) / 10000d; } @Rule public ExpectedException thrown = ExpectedException.none(); } <file_sep>/src/test/java/calculatoJUnitTest/CalculatorTgDoubleTest.java package calculatoJUnitTest; import junitparams.Parameters; import org.junit.Test; import static java.lang.Math.PI; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.StringContains.containsString; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorTgDoubleTest extends BaseCalculatorTestParameters { @Test @Parameters("30|0.5773") public void testCtg(double arg1, double expected) { double actual = round(calculator.tg(arg1)); assertThat("Tg of the " + arg1 , actual, is(equalTo(expected))); } @Test public void testCtgWithException() { thrown.expect(NumberFormatException.class); thrown.expectMessage(containsString(" ")); round(calculator.tg(PI/2)); } } <file_sep>/src/test/java/CalculatorTestNG/CalculatorSqrtDoubleTest.java package CalculatorTestNG; import org.testng.Assert; import org.testng.annotations.Test; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorSqrtDoubleTest extends BaseCalculatorTest { @Test(expectedExceptions = NumberFormatException.class) public void testSqrtNegativeNumber(){ double actual=calculator.sqrt(-16); } @Test(dataProvider = "sqrtDP", dataProviderClass = DataProvidersSource.class) public void testSqrtDouble(double arg1, double expected) { double actual = calculator.sqrt(arg1); Assert.assertEquals(actual,expected); } } <file_sep>/src/test/java/CalculatorTestNG/BaseCalculatorTest.java package CalculatorTestNG; import com.epam.tat.module4.Calculator; import com.epam.tat.module4.Timeout; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeSuite; import java.util.Date; /** * Created by Volha_Batsiushkova on 12/13/2017. */ public class BaseCalculatorTest { protected static Calculator calculator; protected static Timeout timeout ; private long startTime; private long endTime; @BeforeSuite public void runSuite() { calculator = new Calculator(); startTime = System.currentTimeMillis(); } @BeforeGroups(groups = { "Non-trigonometry", "trigonometry" }) public static void runGroups() { calculator = new Calculator(); } @BeforeClass public static void setUp() { calculator = new Calculator(); timeout = new Timeout(); } @AfterSuite public void afterClass(){ endTime = System.currentTimeMillis(); long executionTime = endTime-startTime; System.out.println("Time of test execution : " +executionTime); } protected double round(double value) { return (double) Math.round(value * 10000d) / 10000d; } protected void checkTime() { System.out.println("Current time: " + new Date(System.currentTimeMillis())); } } <file_sep>/src/test/java/CalculatorTestNG/CalculatorMultTest.java package CalculatorTestNG; import org.testng.Assert; import org.testng.annotations.Test; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorMultTest extends BaseCalculatorTest { @Test(dataProvider = "multDoubleDP", dataProviderClass = DataProvidersSource.class) public void testMultDouble(String arg1,String arg2, String expected) { double actual = calculator.mult(Double.valueOf(arg1), Double.valueOf(arg2)); Assert.assertEquals(actual, Double.valueOf(expected)); timeout.sleep(5); checkTime(); } @Test(dataProvider = "multLongDP", dataProviderClass = DataProvidersSource.class) public void testMultLong(String arg1,String arg2, String expected) { long actual = calculator.mult(Long.valueOf(arg1), Long.valueOf(arg2)); Assert.assertEquals(Long.valueOf(actual),Long.valueOf(expected)); timeout.sleep(5); checkTime(); } } <file_sep>/src/test/java/calculatoJUnitTest/CalculatorMultDoubleTest.java package calculatoJUnitTest; import junitparams.Parameters; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorMultDoubleTest extends BaseCalculatorTestParameters { @Test @Parameters(method = "multDoubleValues") public void testMultDouble(String arg1, String arg2, String expected) { double actual = round(calculator.mult(Double.valueOf(arg1), Double.valueOf(arg2))); assertThat("Mult " + arg1 + "on " + arg2, actual, is(equalTo(Double.valueOf(expected)))); } public Object[][] multDoubleValues() { return new Object[][] { { "12.56", "12.56", "157.7536"}, { -13.5, -10.5, 141.75}, }; } } <file_sep>/src/test/java/calculatoJUnitTest/CalculatorSubDoubleTest.java package calculatoJUnitTest; import junitparams.Parameters; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorSubDoubleTest extends BaseCalculatorTestParameters { @Test @Parameters(method = "subDoubleValues" ) public void testSubDouble(String arg1, String arg2,String expected ) { double actual = round(calculator.sub(Double.valueOf(arg1),Double.valueOf(arg2))); assertThat("Sub of the " + arg1 + " and "+arg2, actual, is(equalTo(Double.valueOf(expected)))); } public Object[][] subDoubleValues() { return new Object[][] { { "10.45", "20.15", "-9.70"}, { -10, -50, 40.0}, }; } } <file_sep>/src/test/java/CalculatorTestNG/CalculatorSubDoubleTest.java package CalculatorTestNG; import org.testng.Assert; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorSubDoubleTest extends BaseCalculatorTest { @Test @Parameters({"arg1", "arg2", "expected"}) public void testSubDouble(@Optional(value = "10.5") double arg1, @Optional(value = "14.1") double arg2,@Optional(value = "-3.6") double expected ) { double actual =round(calculator.sub(arg1,arg2)); Assert.assertEquals(actual,expected); timeout.sleep(5); checkTime(); System.out.println(Thread.currentThread().getId()); } } <file_sep>/src/test/java/CalculatorTestNG/MySuiteListener.java package CalculatorTestNG; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.xml.XmlSuite; /** * Created by Volha_Batsiushkova on 12/17/2017. */ public class MySuiteListener implements ISuiteListener { @Override public void onStart(ISuite suite) { suite.getXmlSuite().setParallel(XmlSuite.ParallelMode.CLASSES); suite.getXmlSuite().setThreadCount(4); } @Override public void onFinish(ISuite suite) { } } <file_sep>/src/test/java/calculatoJUnitTest/CalculatorIsNegativeTest.java package calculatoJUnitTest; import junitparams.Parameters; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorIsNegativeTest extends BaseCalculatorTestParameters { @Test @Parameters({ "-10|True", "50|False" }) public void testIsNegative(long arg1, boolean expected) { boolean actual = calculator.isNegative(arg1); assertThat("Tg of the " + arg1, actual, is(equalTo(expected))); } } <file_sep>/src/test/java/CalculatorTestNG/CalculatorDivDoubleTest.java package CalculatorTestNG; import org.testng.Assert; import org.testng.annotations.Test; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorDivDoubleTest extends BaseCalculatorTest { @Test(expectedExceptions = NumberFormatException.class) public void testdevisionOnZero() { System.out.println("Division by zero"); double actual = calculator.div( 1, 0); } @Test(dataProvider = "divDPDouble", dataProviderClass = DataProvidersSource.class, groups = "Non-trigonometry", dependsOnGroups = "trigonometry") public void testDivDouble(double arg1, double arg2, double expected) { System.out.println("Division by non-zero"); double actual = calculator.div(arg1, arg2); Assert.assertEquals(actual, expected); } } <file_sep>/src/test/java/calculatoJUnitTest/CalculatorSubLongTest.java package calculatoJUnitTest; import junitparams.Parameters; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; /** * Created by Volha_Batsiushkova on 12/10/2017. */ public class CalculatorSubLongTest extends BaseCalculatorTestParameters { @Test @Parameters(method = "subLongValues") public void testSubLong(String arg1, String arg2,String expected) { long actual = calculator.sub(Long.valueOf(arg1), Long.valueOf(arg2)); assertThat("Sub of the " + arg1 + "and "+arg2, actual, is(equalTo(Long.valueOf(expected)))); } public Object[][] subLongValues() { return new Object[][] { { "0", "155", "-155"}, { 25L, 10L, 15L}, }; } }
185a50ca5aa3b7437a254e8092cc7dce0e5717ae
[ "Java" ]
14
Java
vbatsiushkova/Framework
3743e2c035917e8ba320a22ce529c381595c4454
29b58b67f3de3b5d65ef572d79aecc04e8417bef
refs/heads/master
<repo_name>LuYueYan/shoot<file_sep>/src/master/CallbackMaster.ts class CallbackMaster { public static shareSuc: Function = null;//分享成功回调 public static shareTime = 0;//分享的时间 public static onHideFun: Function = null;//页面进入后台回调 //审核是否通过 public static hasChecked: boolean = false; public static saveShareSuc = null;//保存上次分享的回调 public static shareFailText = '分享到不同的群才能获得奖励哦~';//分享失败的弹窗文案 public constructor() { } public static init() { //右上角分享 let obj = { query: 'type=newUser&uid=' + userDataMaster.getMyInfo.uid }; platform.onShareAppMessage(obj); platform.onShow((option) => { //是否分享链接打开的 if (option && option.query && option.query.uid) { userDataMaster.shareUid = option.query.uid; if (option.query.type && option.query.type == 'energy') { //能量分享 userDataMaster.sourceEnergy.uid = option.query.suid || option.query.uid; userDataMaster.sourceEnergy.day = option.query.day; // if (Main.scene && Main.scene.getChildAt(0)) { // Main.scene.getChildAt(0).addChild(new getEnergyModal(userDataMaster.sourceEnergy.uid, userDataMaster.sourceEnergy.day)); // } } } if (new Date().getTime() - CallbackMaster.shareTime > 3000) { //超过三秒,算分享成功 CallbackMaster.shareSuc && CallbackMaster.shareSuc(); CallbackMaster.saveShareSuc = null; CallbackMaster.shareFailText = '分享到不同的群才能获得奖励哦~'; } else { CallbackMaster.saveShareSuc = CallbackMaster.shareSuc; //分享失败弹窗 let obj = { title: '温馨提示', content: CallbackMaster.shareFailText, confirmText: '再试一次', success(res) { if (res.confirm) { CallbackMaster.openShare(CallbackMaster.saveShareSuc) } else { CallbackMaster.shareFailText = '分享到不同的群才能获得奖励哦~'; } } } platform.showModal(obj); } CallbackMaster.shareSuc = null; }) platform.onHide(() => { soundMaster.soundChannel && soundMaster.soundChannel.stop(); //存储数据 CallbackMaster.onHideFun && CallbackMaster.onHideFun(); //存储游戏数据 let spirit_data = JSON.stringify(userDataMaster.MyCats); let mark_data = JSON.stringify(userDataMaster.myTravels); let info = { runCat: userDataMaster.runCat, dayEnergy: userDataMaster.dayEnergy, dayTry: userDataMaster.dayTry, travelList: userDataMaster.travelList, dayVideoEnergy: userDataMaster.dayVideoEnergy, degree: userDataMaster.degree }; let params = { uid: userDataMaster.getMyInfo.uid, energy: userDataMaster.myGold, spirit_data, mark_data, info: JSON.stringify(info) } ServiceMaster.post(ServiceMaster.setGameData, params, (res) => { if (res.code == 1 && res.data) { } }) }) } public static shareInfo = [ { imageUrl: 'https://lixi.h5.app81.com/minigame/game_lixi/share_img/share_1.jpg', title: '球球精灵要饿坏了,快点来喂养吧~' }, { imageUrl: 'https://lixi.h5.app81.com/minigame/game_lixi/share_img/share_2.jpg', title: '快来测试一下你的手速是几阶吧?听说单身10年的人手速才达到5阶' }, { imageUrl: 'https://lixi.h5.app81.com/minigame/game_lixi/share_img/share_3.jpg?t=1', title: '给你采集了一大袋能量果,快来领一份吧~' }, ] public static openShare(Callback: Function = null, judge = true, query = '', shareType = 0) { //参数1---回调函数 参数2---是否判断分享成功,默认判断 参数3----附加的参数 4--分享类型 // 好友助力 if (CallbackMaster.hasChecked) { //如果审核通过了 let s = CallbackMaster.shareInfo[0]; if (shareType == 0) { //默认随机分享 s = CallbackMaster.shareInfo[Math.floor(Math.random() * 2)]; } else { s.imageUrl = CallbackMaster.shareInfo[2].imageUrl; s.title = (userDataMaster.myInfo.nickName || '') + CallbackMaster.shareInfo[2].title; } let obj = { title: s.title, imageUrl: s.imageUrl, query: 'uid=' + userDataMaster.getMyInfo.uid + query }; platform.shareAppMessage(obj); CallbackMaster.shareTime = judge ? new Date().getTime() : 0; CallbackMaster.shareSuc = Callback; } } public static openHide(Callback: Function = null) { CallbackMaster.onHideFun = Callback; } public static recommandClick(type = 1, item) { //推荐位点击统计 let uid = userDataMaster.getMyInfo.uid; let params = { id: item.id, uid, appid: item.appid, type, module_id: item.module_id, module_ext_id: item.module_ext_id }; ServiceMaster.post( ServiceMaster.gameClick, params, function (suc) { if (suc.code == 1 && suc.data) { } }) } public static glowFilter(color=0x6d3ec5,alpha=0.8,blurX=35,blurY=35) { //发光滤镜 // var color: number = 0x33CCFF; /// 光晕的颜色,十六进制,不包含透明度 // var alpha: number = 0.8; /// 光晕的颜色透明度,是对 color 参数的透明度设定。有效值为 0.0 到 1.0。例如,0.8 设置透明度值为 80%。 // var blurX: number = 35; /// 水平模糊量。有效值为 0 到 255.0(浮点) // var blurY: number = 35; /// 垂直模糊量。有效值为 0 到 255.0(浮点) var strength: number = 2; /// 压印的强度,值越大,压印的颜色越深,而且发光与背景之间的对比度也越强。有效值为 0 到 255。暂未实现 var quality: number = egret.BitmapFilterQuality.HIGH; /// 应用滤镜的次数,建议用 BitmapFilterQuality 类的常量来体现 var inner: boolean = false; /// 指定发光是否为内侧发光,暂未实现 var knockout: boolean = false; /// 指定对象是否具有挖空效果,暂未实现 var glowFilter: egret.GlowFilter = new egret.GlowFilter(color, alpha, blurX, blurY, strength, quality, inner, knockout); return glowFilter; } }<file_sep>/src/modal/getLifeModal.ts class getLifeModal extends eui.Component implements eui.UIComponent { public closeBtn: eui.Button; public videoBtn: eui.Button; public shareBtn: eui.Button; public shareTimes: eui.Label; public constructor() { super(); } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); if (this.videoBtn) { this.init() } else { this.addEventListener(egret.Event.COMPLETE, this.init, this) } } public init() { this.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.closeFun, this); this.videoBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.videoFun, this); this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.shareFun, this); } public closeFun() { sceneMaster.closeModal(); } public videoFun() { AdMaster.useVideo(() => { suc(); }, () => { CallbackMaster.openShare(() => { suc(); }) }); function suc() { } } public shareFun() { CallbackMaster.openShare(() => { }) } }<file_sep>/bin-debug/master/CallbackMaster.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var CallbackMaster = (function () { function CallbackMaster() { } CallbackMaster.init = function () { //右上角分享 var obj = { query: 'type=newUser&uid=' + userDataMaster.getMyInfo.uid }; platform.onShareAppMessage(obj); platform.onShow(function (option) { //是否分享链接打开的 if (option && option.query && option.query.uid) { userDataMaster.shareUid = option.query.uid; if (option.query.type && option.query.type == 'energy') { //能量分享 userDataMaster.sourceEnergy.uid = option.query.suid || option.query.uid; userDataMaster.sourceEnergy.day = option.query.day; // if (Main.scene && Main.scene.getChildAt(0)) { // Main.scene.getChildAt(0).addChild(new getEnergyModal(userDataMaster.sourceEnergy.uid, userDataMaster.sourceEnergy.day)); // } } } if (new Date().getTime() - CallbackMaster.shareTime > 3000) { //超过三秒,算分享成功 CallbackMaster.shareSuc && CallbackMaster.shareSuc(); CallbackMaster.saveShareSuc = null; CallbackMaster.shareFailText = '分享到不同的群才能获得奖励哦~'; } else { CallbackMaster.saveShareSuc = CallbackMaster.shareSuc; //分享失败弹窗 var obj_1 = { title: '温馨提示', content: CallbackMaster.shareFailText, confirmText: '再试一次', success: function (res) { if (res.confirm) { CallbackMaster.openShare(CallbackMaster.saveShareSuc); } else { CallbackMaster.shareFailText = '分享到不同的群才能获得奖励哦~'; } } }; platform.showModal(obj_1); } CallbackMaster.shareSuc = null; }); platform.onHide(function () { soundMaster.soundChannel && soundMaster.soundChannel.stop(); //存储数据 CallbackMaster.onHideFun && CallbackMaster.onHideFun(); //存储游戏数据 var spirit_data = JSON.stringify(userDataMaster.MyCats); var mark_data = JSON.stringify(userDataMaster.myTravels); var info = { runCat: userDataMaster.runCat, dayEnergy: userDataMaster.dayEnergy, dayTry: userDataMaster.dayTry, travelList: userDataMaster.travelList, dayVideoEnergy: userDataMaster.dayVideoEnergy, degree: userDataMaster.degree }; var params = { uid: userDataMaster.getMyInfo.uid, energy: userDataMaster.myGold, spirit_data: spirit_data, mark_data: mark_data, info: JSON.stringify(info) }; ServiceMaster.post(ServiceMaster.setGameData, params, function (res) { if (res.code == 1 && res.data) { } }); }); }; CallbackMaster.openShare = function (Callback, judge, query, shareType) { if (Callback === void 0) { Callback = null; } if (judge === void 0) { judge = true; } if (query === void 0) { query = ''; } if (shareType === void 0) { shareType = 0; } //参数1---回调函数 参数2---是否判断分享成功,默认判断 参数3----附加的参数 4--分享类型 // 好友助力 if (CallbackMaster.hasChecked) { //如果审核通过了 var s = CallbackMaster.shareInfo[0]; if (shareType == 0) { //默认随机分享 s = CallbackMaster.shareInfo[Math.floor(Math.random() * 2)]; } else { s.imageUrl = CallbackMaster.shareInfo[2].imageUrl; s.title = (userDataMaster.myInfo.nickName || '') + CallbackMaster.shareInfo[2].title; } var obj = { title: s.title, imageUrl: s.imageUrl, query: 'uid=' + userDataMaster.getMyInfo.uid + query }; platform.shareAppMessage(obj); CallbackMaster.shareTime = judge ? new Date().getTime() : 0; CallbackMaster.shareSuc = Callback; } }; CallbackMaster.openHide = function (Callback) { if (Callback === void 0) { Callback = null; } CallbackMaster.onHideFun = Callback; }; CallbackMaster.recommandClick = function (type, item) { if (type === void 0) { type = 1; } //推荐位点击统计 var uid = userDataMaster.getMyInfo.uid; var params = { id: item.id, uid: uid, appid: item.appid, type: type, module_id: item.module_id, module_ext_id: item.module_ext_id }; ServiceMaster.post(ServiceMaster.gameClick, params, function (suc) { if (suc.code == 1 && suc.data) { } }); }; CallbackMaster.glowFilter = function (color, alpha, blurX, blurY) { if (color === void 0) { color = 0x6d3ec5; } if (alpha === void 0) { alpha = 0.8; } if (blurX === void 0) { blurX = 35; } if (blurY === void 0) { blurY = 35; } //发光滤镜 // var color: number = 0x33CCFF; /// 光晕的颜色,十六进制,不包含透明度 // var alpha: number = 0.8; /// 光晕的颜色透明度,是对 color 参数的透明度设定。有效值为 0.0 到 1.0。例如,0.8 设置透明度值为 80%。 // var blurX: number = 35; /// 水平模糊量。有效值为 0 到 255.0(浮点) // var blurY: number = 35; /// 垂直模糊量。有效值为 0 到 255.0(浮点) var strength = 2; /// 压印的强度,值越大,压印的颜色越深,而且发光与背景之间的对比度也越强。有效值为 0 到 255。暂未实现 var quality = 3 /* HIGH */; /// 应用滤镜的次数,建议用 BitmapFilterQuality 类的常量来体现 var inner = false; /// 指定发光是否为内侧发光,暂未实现 var knockout = false; /// 指定对象是否具有挖空效果,暂未实现 var glowFilter = new egret.GlowFilter(color, alpha, blurX, blurY, strength, quality, inner, knockout); return glowFilter; }; CallbackMaster.shareSuc = null; //分享成功回调 CallbackMaster.shareTime = 0; //分享的时间 CallbackMaster.onHideFun = null; //页面进入后台回调 //审核是否通过 CallbackMaster.hasChecked = false; CallbackMaster.saveShareSuc = null; //保存上次分享的回调 CallbackMaster.shareFailText = '分享到不同的群才能获得奖励哦~'; //分享失败的弹窗文案 CallbackMaster.shareInfo = [ { imageUrl: 'https://lixi.h5.app81.com/minigame/game_lixi/share_img/share_1.jpg', title: '球球精灵要饿坏了,快点来喂养吧~' }, { imageUrl: 'https://lixi.h5.app81.com/minigame/game_lixi/share_img/share_2.jpg', title: '快来测试一下你的手速是几阶吧?听说单身10年的人手速才达到5阶' }, { imageUrl: 'https://lixi.h5.app81.com/minigame/game_lixi/share_img/share_3.jpg?t=1', title: '给你采集了一大袋能量果,快来领一份吧~' }, ]; return CallbackMaster; }()); __reflect(CallbackMaster.prototype, "CallbackMaster"); <file_sep>/src/modal/levelUpModal.ts class levelUpModal extends eui.Component implements eui.UIComponent { public levelText: eui.Label; public scoreText: eui.Label; public goldText: eui.Label; public videoBtn: eui.Button; public getBtn: eui.Label; public info:any; public constructor(info:any) { super(); this.info = info; } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); if (this.videoBtn) { this.init() } else { this.addEventListener(egret.Event.COMPLETE, this.init, this) } } public init() { this.scoreText.text=this.info.score+''; this.levelText.text='第'+this.info.level+'关'; this.videoBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.videoFun, this); this.getBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.getFun, this); } public videoFun() { AdMaster.useVideo(() => { suc(); }, () => { CallbackMaster.openShare(() => { suc(); }) }); let that = this; function suc() { sceneMaster.changeScene(new startScene()); sceneMaster.openModal(new getSuccess(1, that.info.gold * 2)); } } public getFun() { sceneMaster.changeScene(new startScene()); sceneMaster.openModal(new getSuccess(1, this.info.gold)); } }<file_sep>/src/modal/getSuccess.ts class getSuccess extends eui.Component implements eui.UIComponent { public light: eui.Image; public img: eui.Image; public txt: eui.Label; public knowBtn: eui.Button; public ifShare: eui.Group; public shareImg: eui.Image; public type: number = 1;//类型 1--钻石 2--体力 public num: number = 0;//数量 public shareType = true;//是否分享 默认分享 public constructor(type = 1, num = 0) { super(); this.type = type; this.num = num; } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); if (this.knowBtn) { this.init() } else { this.addEventListener(egret.Event.COMPLETE, this.init, this) } } public init() { if (this.type == 2) { this.img.texture = RES.getRes('img_bullet_a2_png'); } this.txt.text='x'+this.num; egret.Tween.get(this.light, { loop: true }).to({ rotation: 360 }, 5000); this.knowBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.knowFun, this); this.ifShare.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ifShareFun, this); } public knowFun() { egret.Tween.removeTweens(this.light); if (this.shareType) { CallbackMaster.openShare(null, false); } sceneMaster.closeModal(); } public ifShareFun() { this.shareType = !this.shareType; } }<file_sep>/bin-debug/component/starCom.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var starCom = (function () { function starCom() { this.type = 4; //星星 this.isRemoved = false; //是否已经被移除 this.init(); } starCom.prototype.init = function () { this.img = this.createBitmapByName('star'); }; starCom.prototype.createBody = function (x, y, that) { var boxShape = new p2.Box({ width: 2, height: 2 }); boxShape.collisionGroup = 2; boxShape.collisionMask = 1; boxShape.sensor = true; //作为传感器,被穿透 this.boxBody = new p2.Body({ mass: 100, position: [x, y], type: p2.Body.STATIC }); this.boxBody.addShape(boxShape); this.boxBody.displays = [this.img]; that.addChild(this.img); return this.boxBody; }; starCom.prototype.updateText = function (that, callback) { if (callback === void 0) { callback = null; } //碰撞后做出反应 var self = this; self.isRemoved = true; egret.Tween.removeTweens(self.img); egret.Tween.get(self.img).to({ scaleX: 1.5, scaleY: 1.5 }, 100).to({ scaleX: 1, scaleY: 1 }, 100); callback && callback(); }; starCom.prototype.createBitmapByName = function (name) { var result = new egret.Bitmap(); var texture = RES.getRes(name + '_png'); result.texture = texture; result.anchorOffsetX = result.width / 2; result.anchorOffsetY = result.height / 2; return result; }; return starCom; }()); __reflect(starCom.prototype, "starCom"); window['starCom'] = starCom; <file_sep>/bin-debug/modal/moreScroller.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __extends = this && this.__extends || function __extends(t, e) { function r() { this.constructor = t; } for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); r.prototype = e.prototype, t.prototype = new r(); }; var moreScroller = (function (_super) { __extends(moreScroller, _super); function moreScroller() { var _this = _super.call(this) || this; _this.scrTerval = null; //左侧滚动定时器 _this.loadTimes = 0; return _this; } moreScroller.getInstance = function () { if (!moreScroller.shared) { moreScroller.shared = new moreScroller(); } return moreScroller.shared; }; moreScroller.prototype.partAdded = function (partName, instance) { _super.prototype.partAdded.call(this, partName, instance); }; moreScroller.prototype.childrenCreated = function () { _super.prototype.childrenCreated.call(this); this.init(); }; moreScroller.prototype.init = function () { var that = this; if (userDataMaster.recommand && userDataMaster.recommand['1'] && userDataMaster.recommand['1'].games) { var list = userDataMaster.recommand['1'].games; that.sourceArr = new eui.ArrayCollection(list); that.dataGroup = new eui.DataGroup(); that.dataGroup.dataProvider = that.sourceArr; that.dataGroup.useVirtualLayout = true; var layout = new eui.VerticalLayout(); layout.gap = 20; that.dataGroup.layout = layout; that.dataGroup.itemRenderer = moreItem; that.dataGroup2 = new eui.DataGroup(); that.dataGroup2.dataProvider = that.sourceArr; that.dataGroup2.useVirtualLayout = true; var layout2 = new eui.VerticalLayout(); layout2.gap = 20; that.dataGroup2.layout = layout2; that.dataGroup2.itemRenderer = moreItem; that.moreGroup.height = list.length * 150; that.moreGroup2.height = list.length * 150; that.moreGroup.addChild(that.dataGroup); that.moreGroup2.addChild(that.dataGroup2); that.moreGroup2.y = that.moreGroup.height; that.moreScroller.scrollPolicyV = 'off'; //禁止垂直滚动 that.scrTerval = setInterval(function () { egret.Tween.get(that.moreGroup).to({ y: that.moreGroup.y - 450 }, 1000).wait(100).call(function () { if (that.moreGroup.y <= -that.moreGroup.height) { that.moreGroup.y = that.moreGroup2.y + that.moreGroup2.height; } }); egret.Tween.get(that.moreGroup2).to({ y: that.moreGroup2.y - 450 }, 1000).wait(100).call(function () { if (that.moreGroup2.y <= -that.moreGroup.height) { that.moreGroup2.y = that.moreGroup.y + that.moreGroup.height; } }); }, 3000); } else if (that.loadTimes < 5) { setTimeout(function () { that.loadTimes++; that.init(); }, 300); } }; return moreScroller; }(eui.Component)); __reflect(moreScroller.prototype, "moreScroller", ["eui.UIComponent", "egret.DisplayObject"]); window['moreScroller'] = moreScroller; <file_sep>/src/component/beeCom.ts class beeCom { public img: egret.Bitmap;//图片 public boxBody: p2.Body; public adaptation = 0;//适配长度 public power:number=1;//每次的伤害值 public constructor() { this.init() } public init() { this.img = this.createBitmapByName('img_bullet_a2'); this.img.width = 58; this.img.height = 63; this.img.anchorOffsetX = this.img.width / 2; this.img.anchorOffsetY = this.img.height / 2; } public createBody(that,x=7.5) { var boxShape: p2.Shape = new p2.Box({ width: 1.16, height: 1.26 }); //不碰撞同类 boxShape.collisionGroup = 1; boxShape.collisionMask = 2; this.boxBody = new p2.Body({ mass: 100, position: [x, that.getPosition(900)] }); this.boxBody.gravityScale = 0; this.boxBody.addShape(boxShape); that.world.addBody(this.boxBody); this.boxBody.displays = [this.img]; that.addChild(this.img); return this.boxBody; } public powerUp(num=1){ //伤害值改变 this.power=num; if(num==2){ this.img.texture=RES.getRes('img_elf_32_png'); }else{ this.img.texture=RES.getRes('img_bullet_a2_png'); } } private createBitmapByName(name: string): egret.Bitmap { var result: egret.Bitmap = new egret.Bitmap(); var texture: egret.Texture = RES.getRes(name + '_png'); result.texture = texture; result.anchorOffsetX = result.width / 2; result.anchorOffsetY = result.height / 2; return result; } }<file_sep>/bin-debug/component/ballCom.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var ballCom = (function () { function ballCom() { this.type = 3; //精灵 this.isRemoved = false; //是否已经被移除 this.init(); } ballCom.prototype.init = function () { this.img = this.createBitmapByName('img_bullet_a1'); }; ballCom.prototype.createBody = function (x, y, that) { var boxShape = new p2.Box({ width: 2, height: 2 }); boxShape.collisionGroup = 2; boxShape.collisionMask = 1; boxShape.sensor = true; //作为传感器,被穿透 this.boxBody = new p2.Body({ mass: 100, position: [x, y], type: p2.Body.STATIC }); this.boxBody.addShape(boxShape); this.boxBody.displays = [this.img]; that.addChild(this.img); return this.boxBody; }; ballCom.prototype.updateText = function (that, callback) { if (callback === void 0) { callback = null; } //销毁 var self = this; self.boxBody.shapes[0].collisionMask = 0; self.isRemoved = true; setTimeout(function () { self.boxBody.type = p2.Body.DYNAMIC; self.boxBody.gravityScale = 0; self.boxBody.velocity = [0, -10]; self.boxBody.angularVelocity = 1; //计算掉落到地面销毁时间 var t = (self.boxBody.position[1] - that.getPosition(935)) / 10; console.log(t); setTimeout(function () { //销毁 that.world.removeBody(self.boxBody); self.img.parent && self.img.parent.removeChild(self.img); callback && callback(); }, t * 1000); }, 1000); //播放销毁的动画 }; ballCom.prototype.createBitmapByName = function (name) { var result = new egret.Bitmap(); var texture = RES.getRes(name + '_png'); result.texture = texture; result.anchorOffsetX = result.width / 2; result.anchorOffsetY = result.height / 2; return result; }; return ballCom; }()); __reflect(ballCom.prototype, "ballCom"); window['ballCom'] = ballCom; <file_sep>/src/master/movieMaster.ts class movieMaster { public static mcFactory: egret.MovieClipDataFactory; public constructor() { } public static init() { let data = RES.getRes("ball_travel_gif_json"); let txtr = RES.getRes("ball_travel_gif_png"); movieMaster.mcFactory = new egret.MovieClipDataFactory(data, txtr) } public static getGif(name) { let mc: egret.MovieClip = new egret.MovieClip(movieMaster.mcFactory.generateMovieClipData(name)); return mc; } } window['movieMaster'] = movieMaster<file_sep>/src/page/startScene.ts class startScene extends eui.Component implements eui.UIComponent { public bgImg: eui.Image; public lifeGroup: eui.Group; public liftText: eui.BitmapLabel; public goldGroup: eui.Group; public goldText: eui.BitmapLabel; public openStart: eui.Button; public openLife: eui.Button; public openShare: eui.Button; public openBullet: eui.Button; public openShop: eui.Button; public openRank: eui.Button; public targetArr = [ 'lifeGroup', 'goldGroup', 'openLife', 'openShare', 'openBullet', 'openShop', 'openRank', 'openGift', 'openStart' ]; public moreCom: moreScroller; public constructor() { super(); } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); if (this.bgImg) { this.init() } else { this.addEventListener(egret.Event.COMPLETE, this.init, this) } } public init() { let that = this; that.bgImg.height = that.stage.stageHeight; that.moreCom = new moreScroller(); that.moreCom.y = 300; that.addChild(that.moreCom); that.addEventListener(egret.TouchEvent.TOUCH_TAP, that.judgeFun, that) } public judgeFun(e: egret.TouchEvent) { let that = this; for (let item of that.targetArr) { let t = that[item]; let x = e.stageX - (t.x - t.anchorOffsetX); let y = e.stageY - (t.y - t.anchorOffsetY); if (x > 0 && x < t.width && y > 0 && y < t.height) { that[item + 'Fun'] && that[item + 'Fun'](); return; } } } public lifeGroupFun() { let that = this; } public goldGroupFun() { let that = this; } public openLifeFun() { let that = this; sceneMaster.openModal(new getLifeModal()) } public openShareFun() { let that = this; CallbackMaster.openShare(null, false); } public openBulletFun() { let that = this; } public openShopFun() { let that = this; } public openRankFun() { let that = this; sceneMaster.openModal(new rankModal(), false) } public openGiftFun() { let that = this; } public openStartFun() { let that = this; clearInterval(moreScroller.getInstance().scrTerval); sceneMaster.changeScene(new runningScene()); } }<file_sep>/src/component/gridCom.ts class gridCom { public img: egret.Bitmap;//图片 public txt: egret.BitmapText;//文字 public itemW: number = 94;//格子大小 public num: number = 1;//需要击打的数量 public boxBody: p2.Body; public type: number = 1;//类型 1--方形 2--三角型 5--炸弹 public hitText: egret.Bitmap;//被击中时显示的数字 public destroyGif;//被销毁时的动画 public isRemoved = false;//是否已经被移除 public constructor(num = 1) { this.num = num; let ran = Math.random(); if (ran < 0.4) { this.type = 2; } else if (ran < 0.6) { this.type = 5; } this.init(); } private onLoadComplete(font: egret.BitmapFont): void { } public init() { if (this.type == 1) { this.img = this.createBitmapByName('img_diamonds_a1'); } else if (this.type == 2) { this.img = this.createBitmapByName('img_diamonds_b1'); } else { this.img = this.createBitmapByName('img_diamonds_c1'); } this.txt = new egret.BitmapText(); let font: egret.BitmapFont = RES.getRes('stripe_text_fnt'); this.txt.font = font; this.txt.text = this.num + ''; this.txt.anchorOffsetX = this.img.width / 5; this.txt.anchorOffsetY = this.img.height / 1.8; } public createBody(x, y, that) { var boxShape: p2.Shape; if (this.type == 2) { var vertices = [[1, -1], [1, 1], [-1, 1]];//必须是逆时针方向的数组 boxShape = new p2.Convex({ vertices: vertices }); } else { boxShape = new p2.Box({ width: 2, height: 2 }); } boxShape.collisionGroup = 6; boxShape.collisionMask = 7; this.boxBody = new p2.Body({ mass: 100, position: [x, y], type: p2.Body.STATIC }); this.boxBody.addShape(boxShape); this.boxBody.fixedRotation = false; this.boxBody.displays = [this.img, this.txt]; that.addChild(this.img); that.addChild(this.txt); return this.boxBody; } public updateText(that, n = 1, callback: Function = null) { //n--击打次数 let hitText = new egret.BitmapText(); let font: egret.BitmapFont = RES.getRes('stripe_text_fnt'); hitText.font = font; let t = n > this.num ? this.num + '' : n + ''; hitText.text = n > this.num ? this.num + '' : n + ''; hitText.x = this.img.x + 20; hitText.y = this.img.y - 80; that.addChild(hitText); egret.Tween.get(hitText).to({ scaleX: 1.5, scaleY: 1.5, x: hitText.x + 30 * Math.random(), y: hitText.y - 100 }, 500).to({ alpha: 0.5 }, 200).call(() => { hitText.parent && hitText.parent.removeChild(hitText); }); if (this.num > n) { this.num -= n; this.txt.text = this.num + ''; } else { this.isRemoved = true; that.world.removeBody(this.boxBody); //销毁 this.img.parent && this.img.parent.removeChild(this.img); this.txt.parent && this.txt.parent.removeChild(this.txt); //播放销毁的动画 let res = {};//被销毁的对象,分数之类的信息 if (this.type == 5) { //是炸弹 判断被炸毁的区域 let d = that.adaptParams.itemWidth / that.factor; for (let i = 0, len = that.gridArr.length; i < len; i++) { let item = that.gridArr[i]; let dx = Math.floor(Math.abs(item.boxBody.position[0] - this.boxBody.position[0])*100)/100; let dy = Math.floor(Math.abs(item.boxBody.position[1] - this.boxBody.position[1])*100)/100; if (item.boxBody.id != this.boxBody.id && (dx <= d && dy <= d)) { console.log('boom',item.type) if (item.type == 3) { //精灵 if (!item.isRemoved){ that.shootPoint.beeNum++; let nx = item.boxBody.position[0]; item.updateText(that, () => { let b = new beeCom(); b.createBody(that, nx); that.beeArr.push(b); }); } } else if (item.type == 4) { //星星 } else if (!item.isRemoved) { console.log(55555) item.updateText(that, item.num, callback); } } } } else { } callback && callback(res); } } private createBitmapByName(name: string): egret.Bitmap { var result: egret.Bitmap = new egret.Bitmap(); var texture: egret.Texture = RES.getRes(name + '_png'); result.texture = texture; result.anchorOffsetX = result.width / 2; result.anchorOffsetY = result.height / 2; return result; } } window['gridCom'] = gridCom<file_sep>/src/modal/moreScroller.ts class moreScroller extends eui.Component implements eui.UIComponent { public moreScroller: eui.Scroller; public moreGroup: eui.Group; public moreGroup2: eui.Group; public dataGroup: eui.DataGroup; public sourceArr: eui.ArrayCollection; public scrTerval = null;//左侧滚动定时器 public dataGroup2: eui.DataGroup; public loadTimes = 0; public constructor() { super(); } public static shared: moreScroller; public static getInstance() { if (!moreScroller.shared) { moreScroller.shared = new moreScroller(); } return moreScroller.shared; } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); this.init(); } public init() { let that = this; if (userDataMaster.recommand && userDataMaster.recommand['1'] && userDataMaster.recommand['1'].games) { let list = userDataMaster.recommand['1'].games; that.sourceArr = new eui.ArrayCollection(list); that.dataGroup = new eui.DataGroup(); that.dataGroup.dataProvider = that.sourceArr; that.dataGroup.useVirtualLayout = true; let layout = new eui.VerticalLayout(); layout.gap = 20; that.dataGroup.layout = layout; that.dataGroup.itemRenderer = moreItem; that.dataGroup2 = new eui.DataGroup(); that.dataGroup2.dataProvider = that.sourceArr; that.dataGroup2.useVirtualLayout = true; let layout2 = new eui.VerticalLayout(); layout2.gap = 20; that.dataGroup2.layout = layout2; that.dataGroup2.itemRenderer = moreItem; that.moreGroup.height = list.length * 150; that.moreGroup2.height = list.length * 150; that.moreGroup.addChild(that.dataGroup); that.moreGroup2.addChild(that.dataGroup2); that.moreGroup2.y = that.moreGroup.height; that.moreScroller.scrollPolicyV = 'off';//禁止垂直滚动 that.scrTerval = setInterval(() => { egret.Tween.get(that.moreGroup).to({ y: that.moreGroup.y - 450 }, 1000).wait(100).call(() => { if (that.moreGroup.y <= -that.moreGroup.height) { that.moreGroup.y = that.moreGroup2.y + that.moreGroup2.height; } }); egret.Tween.get(that.moreGroup2).to({ y: that.moreGroup2.y - 450 }, 1000).wait(100).call(() => { if (that.moreGroup2.y <= -that.moreGroup.height) { that.moreGroup2.y = that.moreGroup.y + that.moreGroup.height; } }); }, 3000); } else if (that.loadTimes < 5) { setTimeout(function () { that.loadTimes++; that.init(); }, 300); } } } window['moreScroller'] = moreScroller<file_sep>/libs/exml.e.d.ts declare module skins{ class ButtonSkin extends eui.Skin{ } } declare module skins{ class CheckBoxSkin extends eui.Skin{ } } declare class getLifrSkin extends eui.Skin{ } declare module skins{ class HScrollBarSkin extends eui.Skin{ } } declare module skins{ class HSliderSkin extends eui.Skin{ } } declare module skins{ class ItemRendererSkin extends eui.Skin{ } } declare module skins{ class PanelSkin extends eui.Skin{ } } declare module skins{ class ProgressBarSkin extends eui.Skin{ } } declare module skins{ class RadioButtonSkin extends eui.Skin{ } } declare module skins{ class ScrollerSkin extends eui.Skin{ } } declare module skins{ class TextInputSkin extends eui.Skin{ } } declare module skins{ class ToggleSwitchSkin extends eui.Skin{ } } declare module skins{ class VScrollBarSkin extends eui.Skin{ } } declare module skins{ class VSliderSkin extends eui.Skin{ } } declare class getLifeModalSkin extends eui.Skin{ } declare class getSuccessSkin extends eui.Skin{ } declare class levelUpModalSkin extends eui.Skin{ } declare class moreItemSkin extends eui.Skin{ } declare class moreScrollerSkin extends eui.Skin{ } declare class rankItemSkin extends eui.Skin{ } declare class rankModalSkin extends eui.Skin{ } declare class rebornModalSkin extends eui.Skin{ } declare class gameOverSkin extends eui.Skin{ } declare class runningSceneSkin extends eui.Skin{ } declare class startSceneSkin extends eui.Skin{ } <file_sep>/src/modal/rebornModal.ts class rebornModal extends eui.Component implements eui.UIComponent { public rebornBtn: eui.Button; public ignoreBtn: eui.Label; public constructor() { super(); } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); if (this.ignoreBtn) { this.init() } else { this.addEventListener(egret.Event.COMPLETE, this.init, this) } } public init(){ let that=this; setTimeout(function () { that.ignoreBtn.visible = true; }, 5000); that.ignoreBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ignoreFun, this); } public ignoreFun() { // sceneMaster.closeModal(); sceneMaster.openModal(new gameOver()); } }<file_sep>/src/master/soundMaster.ts class soundMaster { public static bg_sound: egret.Sound;//背景音乐 public static guide_tap: egret.Sound;//新手引导时点击音乐 public static songArr = [ { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_0.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_1.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_2.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_3.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_4.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_5.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_6.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_7.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_8.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_9.mp3', sound: null }, { path: 'https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_10.mp3', sound: null } ];//歌曲列表 // 音轨 public static soundChannel: egret.SoundChannel; public static music: boolean = true; public static musicStart = 0;//音乐开始播放的时间 public static pauseTime = 0;//上次暂停时间点 public constructor() { } public static init() { // soundMaster.bg_sound = RES.getRes("bg_mp3"); RES.getResByUrl('https://lixi.h5.app81.com/minigame/game_lixi/new_music/music_guide.mp3', (res) => { soundMaster.guide_tap = res; }); for (let i = 0, len = soundMaster.songArr.length; i < len; i++) { RES.getResByUrl(soundMaster.songArr[i].path, (res) => { soundMaster.songArr[i].sound = res; }); } } public static playSongMusic(index = 0, reborn = 0) { if (soundMaster.songArr[index].sound && soundMaster.isMusic) { if (reborn == 0) { soundMaster.musicStart = egret.getTimer(); soundMaster.soundChannel = soundMaster.songArr[index].sound.play(0, -1); } else { //继续播放 soundMaster.soundChannel = soundMaster.songArr[index].sound.play(soundMaster.pauseTime, -1); } } } public static stopSongMusic(reborn = false) { if (soundMaster.soundChannel) { if (reborn) { soundMaster.pauseTime = (egret.getTimer() - soundMaster.musicStart) / 1000; } else { soundMaster.pauseTime = 0; } soundMaster.soundChannel.stop(); soundMaster.soundChannel = null; } } public static playSingleMusic(type) { if (soundMaster[type] && soundMaster.isMusic) { soundMaster[type].play(0, 1); } } public static set isMusic(val) { if (val) { // 播放 soundMaster.music = true; // soundMaster.playBgMusic(); } else { soundMaster.music = false; // soundMaster.stopBgMusic(); } } public static get isMusic() { return soundMaster.music; } }<file_sep>/src/master/sceneMaster.ts class sceneMaster { public static stage;//舞台 public static modal;//弹窗 public static littleModal;//二级弹窗 public static scene;//主页面 public static modalBg;//弹窗背景层 public static littleBg;//小弹窗背景层 public static stageHeight = 1334;//舞台高度 public constructor() { } public static init(stage) { sceneMaster.stage = stage; sceneMaster.stageHeight = stage.stageHeight; let rect = new eui.Rect(stage.stageWidth, stage.stageHeight, 0x000000); rect.alpha = 0.7; sceneMaster.modalBg = rect; let rect_2 = new eui.Rect(stage.stageWidth, stage.stageHeight, 0x000000); rect_2.alpha = 0.7; sceneMaster.littleBg = rect_2; } public static changeScene(scene) { sceneMaster.scene && sceneMaster.scene.parent && sceneMaster.stage.removeChild(sceneMaster.scene); sceneMaster.stage.addChild(scene); sceneMaster.scene = scene; sceneMaster.modal = null; sceneMaster.littleModal = null; } public static openModal(modal, modalBg = true) { //页面上加弹窗 if (sceneMaster.modal) { //已存在一个弹窗 sceneMaster.scene.removeChild(sceneMaster.modal); sceneMaster.modal = null; sceneMaster.littleModal = null; } sceneMaster.modal = modal; if (modalBg) { sceneMaster.scene.addChild(sceneMaster.modalBg); modal.scaleX = 0, modal.scaleY = 0; sceneMaster.scene.addChild(modal); setTimeout(function () { modal.x = 375, modal.y = 300; modal.anchorOffsetX = modal.width / 2, modal.anchorOffsetY = modal.height / 2; egret.Tween.get(modal).to({ scaleX: 1, scaleY: 1 }, 500, egret.Ease.backOut); }, 50); } else { sceneMaster.scene.addChild(modal); } } public static closeModal() { //关闭弹窗 if (sceneMaster.modal) { //存在一个弹窗 egret.Tween.get(sceneMaster.modal).to({ scaleX: 0, scaleY: 0 }, 500, egret.Ease.backOut).call(() => { sceneMaster.scene.removeChild(sceneMaster.modal); sceneMaster.modalBg.parent && sceneMaster.scene.removeChild(sceneMaster.modalBg); sceneMaster.modal = null; sceneMaster.littleModal = null; }) } } public static openLittleModal(littleModal, littleBg = true) { //在弹窗上打开小弹窗 if (sceneMaster.littleModal) { //已存在一个小弹窗 sceneMaster.modal.removeChild(sceneMaster.littleModal); } if (littleBg) { sceneMaster.modal.addChild(sceneMaster.littleBg); } sceneMaster.littleModal = littleModal; littleModal.scaleX = 0, littleModal.scaleY = 0; littleModal.x = 375, littleModal.y = 300; littleModal.anchorOffsetX = littleModal.width / 2, littleModal.anchorOffsetY = littleModal.height / 2; egret.Tween.get(littleModal).to({ scaleX: 1, scaleY: 1 }, 500, egret.Ease.backOut); sceneMaster.modal.addChild(littleModal); } public static closeLittleModal() { //关闭小弹窗 if (sceneMaster.littleModal) { //存在一个小弹窗 sceneMaster.modal.removeChild(sceneMaster.littleModal); sceneMaster.littleModal = null; sceneMaster.littleBg.parent && sceneMaster.modal.removeChild(sceneMaster.littleBg); } } }<file_sep>/src/page/gameOver.ts class gameOver extends eui.Component implements eui.UIComponent { public levelText: eui.Label; public levelProccess: eui.Label; public playBtn: eui.Button; public shareBtn: eui.Button; public homeBtn: eui.Button; public constructor() { super(); } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); if (this.homeBtn) { this.init() } else { this.addEventListener(egret.Event.COMPLETE, this.init, this) } } public init() { this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.shareFun, this); this.homeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.homeFun, this); this.playBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.playFun, this); } public shareFun() { CallbackMaster.openShare(null, false); } public homeFun() { sceneMaster.changeScene(new startScene()); } public playFun() { sceneMaster.changeScene(new runningScene()); } }<file_sep>/bin-debug/component/gridCom.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var gridCom = (function () { function gridCom(num) { if (num === void 0) { num = 1; } this.itemW = 94; //格子大小 this.num = 1; //需要击打的数量 this.type = 1; //类型 1--方形 2--三角型 5--炸弹 this.isRemoved = false; //是否已经被移除 this.num = num; var ran = Math.random(); if (ran < 0.4) { this.type = 2; } else if (ran < 0.6) { this.type = 5; } this.init(); } gridCom.prototype.onLoadComplete = function (font) { }; gridCom.prototype.init = function () { if (this.type == 1) { this.img = this.createBitmapByName('img_diamonds_a1'); } else if (this.type == 2) { this.img = this.createBitmapByName('img_diamonds_b1'); } else { this.img = this.createBitmapByName('img_diamonds_c1'); } this.txt = new egret.BitmapText(); var font = RES.getRes('stripe_text_fnt'); this.txt.font = font; this.txt.text = this.num + ''; this.txt.anchorOffsetX = this.img.width / 5; this.txt.anchorOffsetY = this.img.height / 1.8; }; gridCom.prototype.createBody = function (x, y, that) { var boxShape; if (this.type == 2) { var vertices = [[1, -1], [1, 1], [-1, 1]]; //必须是逆时针方向的数组 boxShape = new p2.Convex({ vertices: vertices }); } else { boxShape = new p2.Box({ width: 2, height: 2 }); } boxShape.collisionGroup = 6; boxShape.collisionMask = 7; this.boxBody = new p2.Body({ mass: 100, position: [x, y], type: p2.Body.STATIC }); this.boxBody.addShape(boxShape); this.boxBody.fixedRotation = false; this.boxBody.displays = [this.img, this.txt]; that.addChild(this.img); that.addChild(this.txt); return this.boxBody; }; gridCom.prototype.updateText = function (that, n, callback) { if (n === void 0) { n = 1; } if (callback === void 0) { callback = null; } //n--击打次数 var hitText = new egret.BitmapText(); var font = RES.getRes('stripe_text_fnt'); hitText.font = font; var t = n > this.num ? this.num + '' : n + ''; hitText.text = n > this.num ? this.num + '' : n + ''; hitText.x = this.img.x + 20; hitText.y = this.img.y - 80; that.addChild(hitText); egret.Tween.get(hitText).to({ scaleX: 1.5, scaleY: 1.5, x: hitText.x + 30 * Math.random(), y: hitText.y - 100 }, 500).to({ alpha: 0.5 }, 200).call(function () { hitText.parent && hitText.parent.removeChild(hitText); }); if (this.num > n) { this.num -= n; this.txt.text = this.num + ''; } else { this.isRemoved = true; that.world.removeBody(this.boxBody); //销毁 this.img.parent && this.img.parent.removeChild(this.img); this.txt.parent && this.txt.parent.removeChild(this.txt); //播放销毁的动画 var res = {}; //被销毁的对象,分数之类的信息 if (this.type == 5) { //是炸弹 判断被炸毁的区域 var d = that.adaptParams.itemWidth / that.factor; var _loop_1 = function (i, len) { var item = that.gridArr[i]; var dx = Math.floor(Math.abs(item.boxBody.position[0] - this_1.boxBody.position[0]) * 100) / 100; var dy = Math.floor(Math.abs(item.boxBody.position[1] - this_1.boxBody.position[1]) * 100) / 100; if (item.boxBody.id != this_1.boxBody.id && (dx <= d && dy <= d)) { console.log('boom', item.type); if (item.type == 3) { //精灵 if (!item.isRemoved) { that.shootPoint.beeNum++; var nx_1 = item.boxBody.position[0]; item.updateText(that, function () { var b = new beeCom(); b.createBody(that, nx_1); that.beeArr.push(b); }); } } else if (item.type == 4) { //星星 } else if (!item.isRemoved) { console.log(55555); item.updateText(that, item.num, callback); } } }; var this_1 = this; for (var i = 0, len = that.gridArr.length; i < len; i++) { _loop_1(i, len); } } else { } callback && callback(res); } }; gridCom.prototype.createBitmapByName = function (name) { var result = new egret.Bitmap(); var texture = RES.getRes(name + '_png'); result.texture = texture; result.anchorOffsetX = result.width / 2; result.anchorOffsetY = result.height / 2; return result; }; return gridCom; }()); __reflect(gridCom.prototype, "gridCom"); window['gridCom'] = gridCom; <file_sep>/bin-debug/modal/levelUpModal.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __extends = this && this.__extends || function __extends(t, e) { function r() { this.constructor = t; } for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); r.prototype = e.prototype, t.prototype = new r(); }; var levelUpModal = (function (_super) { __extends(levelUpModal, _super); function levelUpModal(info) { var _this = _super.call(this) || this; _this.info = info; return _this; } levelUpModal.prototype.partAdded = function (partName, instance) { _super.prototype.partAdded.call(this, partName, instance); }; levelUpModal.prototype.childrenCreated = function () { _super.prototype.childrenCreated.call(this); if (this.videoBtn) { this.init(); } else { this.addEventListener(egret.Event.COMPLETE, this.init, this); } }; levelUpModal.prototype.init = function () { this.scoreText.text = this.info.score + ''; this.levelText.text = '第' + this.info.level + '关'; this.videoBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.videoFun, this); this.getBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.getFun, this); }; levelUpModal.prototype.videoFun = function () { AdMaster.useVideo(function () { suc(); }, function () { CallbackMaster.openShare(function () { suc(); }); }); var that = this; function suc() { sceneMaster.changeScene(new startScene()); sceneMaster.openModal(new getSuccess(1, that.info.gold * 2)); } }; levelUpModal.prototype.getFun = function () { sceneMaster.changeScene(new startScene()); sceneMaster.openModal(new getSuccess(1, this.info.gold)); }; return levelUpModal; }(eui.Component)); __reflect(levelUpModal.prototype, "levelUpModal", ["eui.UIComponent", "egret.DisplayObject"]); <file_sep>/src/page/runningScene.ts class runningScene extends eui.Component implements eui.UIComponent { public bgImg: eui.Image; public scoreText: eui.BitmapLabel; public amountText: eui.BitmapLabel; public amountPro: eui.Image; public hero: eui.Image; public rayGroup: eui.Group; public arcPro: egret.Shape = new egret.Shape();//弧形进度条 public world: p2.World; public factor: number = 50; public bee: p2.Body; public currentTimer = egret.getTimer(); public ceilArr = []; public adaptParams = { gridAreaTop: 186 + 9,//格子区域距离屏幕顶部距离 gridAreaLeft: 30 + 9,//格子区域距离屏幕左侧距离 itemWidth: 96//格子尺寸 }; public worldSpeed = 1000;//世界运行速度 public ballSpeed = 1000;//物体的匀速 public gridArr: Array<any> = [];//障碍物存放数组 public beeArr: Array<beeCom> = [];//球球shuzu public shooting = false;//是否在射击进行中 public levelInfo = { level: 1, amount: 20, existAmount: 0 }; public amount: number = 0;//消灭的方块数量 public score: number = 0;//分数 public shootPoint = { bx: 375, by: 1034, ex: 0, ey: 0, floor: false, beeNum: 0, speedy: 3 }; //发射起点/目标点坐标/ 每次发射后是否有球落地/目前屁屁球数量(还没掉落到地的也算)//在地面上上时的速度 public constructor() { super(); } protected partAdded(partName: string, instance: any): void { super.partAdded(partName, instance); } protected childrenCreated(): void { super.childrenCreated(); // if (this.scoreText) { this.init() // } else { // this.addEventListener(egret.Event.COMPLETE, this.init, this) // } } public init() { let that = this; this.amountText.text = this.amount + '/' + this.levelInfo.amount; this.bgImg.height = this.stage.stageHeight; //创建world this.world = new p2.World(); this.world.sleepMode = p2.World.BODY_SLEEPING;//睡眠策略,提高性能 this.world.gravity = [0, -10]; this.world.defaultContactMaterial.restitution = 1;//全局弹性系数 for (let i = 0; i < 5; i++) { let bee = new beeCom(); bee.createBody(that); that.beeArr.push(bee); that.shootPoint.beeNum++; } that.updateBee() that.createCeil(); for (let i = 1; i <= 3; i++) { that.createGrids(i) } that.addChild(that.arcPro); that.world.on("beginContact", this.onBeginContact, this); this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this); that.addEventListener(egret.TouchEvent.TOUCH_BEGIN, that.touchBeginFun, this) that.addEventListener(egret.TouchEvent.TOUCH_MOVE, that.touchMoveFun, this) that.addEventListener(egret.TouchEvent.TOUCH_END, that.touchEndFun, this); } public createCeil() { let arr = [ { x: 676.5, y: 489, width: 0.18, height: 20 },//右边 { x: -4.5, y: 489, width: 0.18, height: 20 },//左边 { x: 345, y: -4.5, width: 13.8, height: 0.18 },//上面 { x: 345, y: 940, width: 13.8, height: 0.2 }//下面 地面位置 935-945 ]; for (let i = 0, len = arr.length; i < len; i++) { let item = arr[i]; var planeBody: p2.Body = new p2.Body({ mass: 1, position: [this.getPosition(item.x, 2), this.getPosition(item.y)], type: p2.Body.STATIC });//创建墙壁 var shape: p2.Shape = new p2.Box({ width: item.width, height: item.height }); shape.collisionGroup = 6; shape.collisionMask = 1; planeBody.addShape(shape);//给这个刚体添加形状 planeBody.displays = [];//与每个形状对应的显示对象 this.world.addBody(planeBody); this.ceilArr.push(planeBody) } } public getPosition(k, type = 1) { //px坐标转化为world坐标 // type=1时 k为相对格子区域的y坐标 //type=2时 k为相对格子区域的x坐标 let adaptParams = this.adaptParams; let p = 0; if (type == 1) { p = (this.stage.stageHeight - (adaptParams.gridAreaTop + k)) / this.factor; } else { p = (adaptParams.gridAreaLeft + k) / this.factor; } return p; } public updateProccess(num = 0) { //更新关卡进度 let that = this; if (num == 0) { //击掉方块 that.amount++; that.amountText.text = that.amount + '/' + that.levelInfo.amount; that.amountPro.width = that.amount / that.levelInfo.amount * 100; if (that.amount >= that.levelInfo.amount) { //通关成功 console.log('level up') } } else { //得分 that.score += num; that.scoreText.text = that.score + ''; let percent = that.score / 200; that.changeGraphics(percent) } } public createGrids(row = 1) { //每次生成一行 row--生成的位置为第几行(从上往下0行开始) 默认第一行 let that = this; if (that.amount >= that.levelInfo.amount) { //通关~~~~ let info = { gold: 0, score: that.score, level: 1 } that.removeEventListener(egret.Event.ENTER_FRAME, that.onEnterFrame, that); that.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, that.touchBeginFun, that) that.removeEventListener(egret.TouchEvent.TOUCH_MOVE, that.touchMoveFun, that) that.removeEventListener(egret.TouchEvent.TOUCH_END, that.touchEndFun, that); sceneMaster.openModal(new levelUpModal(info)) } if (that.levelInfo.existAmount >= that.levelInfo.amount) { //本关卡数量已足够 return; } for (let col = 0; col < 7; col++) { let g; let ran = Math.random(); if (ran > 0.4) { continue; } if (ran < 0.2 && (that.levelInfo.existAmount < that.levelInfo.amount)) { let num = Math.floor(1 + Math.random() * that.levelInfo.existAmount); g = new gridCom(num); that.levelInfo.existAmount++; } else if (ran < 0.3) { g = new ballCom(); } else if (ran < 0.4) { g = new starCom(); } let x = col * that.adaptParams.itemWidth + that.adaptParams.itemWidth / 2; let y = row * that.adaptParams.itemWidth + that.adaptParams.itemWidth / 2; that.world.addBody(g.createBody(that.getPosition(x, 2), that.getPosition(y), that)); that.gridArr.push(g); } } public touchBeginFun(e: egret.TouchEvent) { if (this.shooting) { return; } if (0) { //发射状态 this.touchMoveFun(e); } else { //使用道具 let adaptParams = this.adaptParams; let x = (e.stageX - adaptParams.gridAreaLeft) / adaptParams.itemWidth; let y = (e.stageY - adaptParams.gridAreaTop) / adaptParams.itemWidth; if (x > 0 && x < 7 && y > 0 && y < 8) { for (let i = 0, len = this.gridArr.length; i < len; i++) { let img = this.gridArr[i].img; if (Math.abs(e.stageX - img.x) <= img.width / 2 && Math.abs(e.stageY - img.y) <= img.height / 2) { console.log('target', i) break; } } this.useTool() } } } public useTool() { } public touchMoveFun(e: egret.TouchEvent) { if (this.shooting) { return; } this.shootPoint.ex = e.stageX; this.shootPoint.ey = e.stageY; this.shootPoint.speedy = 1; this.testRay() } public touchEndFun(e: egret.TouchEvent) { let that = this; if (this.shooting) { return; } this.shootPoint.speedy = 3; this.shootPoint.ex = e.stageX; this.shootPoint.ey = e.stageY; let dx = that.shootPoint.ex - that.shootPoint.bx; let dy = that.shootPoint.ey - that.shootPoint.by; let startX = that.shootPoint.bx / that.factor; let startY = (that.stage.stageHeight - that.shootPoint.by) / that.factor; this.rayGroup.removeChildren(); this.hero.rotation = 0; setTimeout(function () { that.shooting = true; console.log('shoot', that.shooting) }, 100); for (let i = 0; i < that.beeArr.length; i++) { let bee = that.beeArr[i].boxBody; setTimeout(function () { egret.Tween.removeTweens(bee.displays[0]); bee.position[0] = startX; bee.position[1] = startY; bee.velocity = [dx / that.factor, -dy / that.factor]; bee.gravityScale = 0; that.updateSpeed(bee); }, 100 * i); } } public testRay() { let that = this; let bx = that.shootPoint.bx / that.factor; let by = (that.stage.stageHeight - that.shootPoint.by) / that.factor; let ex = that.shootPoint.ex / that.factor; let ey = (that.stage.stageHeight - that.shootPoint.ey) / that.factor; let dx = ex - bx; let dy = ey - by;//ey<by的 var ray = new p2.Ray({ from: [bx, by], to: [ex + (25 / dy * dx), ey + 25], mode: p2.Ray.CLOSEST, checkCollisionResponse: true, collisionGroup: 1, collisionMask: 4 }); that.hero.rotation = 350; var result = new p2.RaycastResult(); that.world.raycast(result, ray); if (result && result.body) { that.createLine(result, ray) } } public createLine(result, ray) { let that = this; this.rayGroup.removeChildren(); let bx = that.shootPoint.bx / that.factor; let by = (that.stage.stageHeight - that.shootPoint.by) / that.factor; let distance = result.getHitDistance(ray); let dx = ray.to[0] - ray.from[0]; let dy = ray.to[1] - ray.from[1]; for (let i = 0; i < distance - 1; i++) { let point = that.createBitmapByName('point'); point.width = 10; point.height = 10; point.anchorOffsetX = point.width / 2; point.anchorOffsetY = point.height / 2; point.x = (ray.from[0] + dx / ray.length * i) * that.factor; point.y = that.stage.stageHeight - (ray.from[1] + dy / ray.length * i) * that.factor; this.rayGroup.addChild(point) } let point = that.createBitmapByName('arrow'); point.width = 10; point.height = 10; point.anchorOffsetX = point.width / 2; point.anchorOffsetY = point.height / 2; point.x = (ray.from[0] + dx / ray.length * (distance - 0.5)) * that.factor; point.y = that.stage.stageHeight - (ray.from[1] + dy / ray.length * (distance - 0.5)) * that.factor; this.rayGroup.addChild(point); } public onBeginContact(event): void { let that = this; var bodyA: p2.Body = event.bodyA; var bodyB: p2.Body = event.bodyB; for (let i = 0; i < that.beeArr.length; i++) { let bee = that.beeArr[i].boxBody; if (bodyA.id == bee.id || bodyB.id == bee.id) { // console.log("on target sensor BeginContact bodyA.id:" + bodyA.id + ",bodyB.id:" + bodyB.id); var hittedBody: p2.Body;//与playerBodyId碰撞的刚体 if (bodyA.id == bee.id) { hittedBody = bodyB; } else if (bodyB.id == bee.id) { hittedBody = bodyA; } if (hittedBody.id == that.ceilArr[0].id || hittedBody.id == that.ceilArr[1].id || hittedBody.id == that.ceilArr[2].id) { // 是墙壁 bee.angle = 0; return; } if (hittedBody.id == that.ceilArr[3].id) { // 是地面 bee.angle = 0; bee.fixedRotation = true;//防止旋转 bee.gravityScale = 1; bee.velocity = [0, -that.shootPoint.speedy]; return; } for (let k = 0; k < that.gridArr.length; k++) { if (that.gridArr[k].boxBody.id == hittedBody.id) { if (that.gridArr[k].type == 3) { //是球 if (!that.gridArr[k].isRemoved) { that.shootPoint.beeNum++; let nx = that.gridArr[k].boxBody.position[0]; that.gridArr[k].updateText(that, () => { let b = new beeCom(); b.createBody(that, nx); that.beeArr.push(b); console.log('hit') }); } } else { if (that.gridArr[k].type == 4) { //是星星 that.beeArr[i].powerUp(2); that.gridArr[k].updateText(that); } else if (!that.gridArr[k].isRemoved) { //是方块 let num = that.beeArr[i].power > that.gridArr[k].num ? that.gridArr[k].num : that.beeArr[i].power; that.updateProccess(num); that.gridArr[k].updateText(that, that.beeArr[i].power, (res) => { //已被击碎 如果是炸弹,分数怎么算??? res的形式未定 that.updateProccess(); }); } } break; } } // if (hittedBody.shapes[0].sensor == true) {//碰到了传感器,这里不需要计算爆炸位置,只作为传感器就好 // //碰撞到了传感器,不是普通dynamic刚体 // console.log("碰撞到了传感器,不是普通dynamic刚体,id:" + hittedBody.id); // } else { // this.getPlayerContactPos(); //这里是计算和其他Body.type=dynamic的刚体碰撞的位置 // } break; } } } // 获得player碰撞位置 private getPlayerContactPos(): void { // for(var i = 0;i < this.world.narrowphase.contactEquations.length;i++) { // var c: p2.ContactEquation = this.world.narrowphase.contactEquations; // if(c.bodyA.id == this.bee.id || c.bodyB.id == this.bee.id) { // var ptA: Array<number> = c.contactPointA;//pointA delta向量,上次使用contactPointB貌似没用对,用contactPointA就对了 // var contactPos: Array<number> = [c.bodyA.position[0] + ptA[0],c.bodyA.position[1] + ptA[1]];//在BodyA位置加上delta向量,这个就是碰撞发生的p2位置 // // var dispX: number = jbP2.P2Space.convertP2ValueToEgret(contactPos[0]);//转换到egret世界的位置 // // var dispY: number = jbP2.P2Space.convertP2Y_To_EgretY(contactPos[1]);//转换到egret世界的位置 // // //drawing the point to the graphics // // this.contactDrawing.graphics.lineStyle(1,0); // // this.contactDrawing.graphics.drawCircle(dispX,dispY,15); // // this.contactDrawing.graphics.endFill(); // } // } } private onEndContact(event): void { var bodyA: p2.Body = event.bodyA; var bodyB: p2.Body = event.bodyB; if (bodyA.id == 5 || bodyB.id == 5) { // console.log("on target sensor EndContact bodyA.id:" + bodyA.id + ",bodyB.id:" + bodyB.id); } } private onEnterFrame() { let that = this; let dt = egret.getTimer() - this.currentTimer; if (dt < 10) { return; } if (dt > 1000) { return; } this.world.step(dt / this.worldSpeed);//使物理系统向前经过一定时间,也就是使世界运行 this.currentTimer = egret.getTimer(); var stageHeight: number = egret.MainContext.instance.stage.stageHeight;//获取舞台高度???? var l = this.world.bodies.length;//所有body的长度 for (var i: number = 0; i < l; i++) { var boxBody: p2.Body = this.world.bodies[i]; var len = boxBody.displays.length; for (let j = 0; j < len; j++) { var box: egret.DisplayObject = boxBody.displays[j]; if (box) { if (j == 0) { box.anchorOffsetX = boxBody.displays[0].width / 2; } box.x = boxBody.position[0] * this.factor; box.y = stageHeight - boxBody.position[1] * this.factor;//坐标系不一样,所以要转换 // box.rotation = 360 - (boxBody.angle + boxBody.shapes[j].angle) * 180 / Math.PI;//旋转 box.rotation = 360 - boxBody.angle * 180 / Math.PI;//旋转 } } } let num = 0; for (let i = 0, len = this.beeArr.length; i < len; i++) { let bee = this.beeArr[i].boxBody; if (bee.position[1] <= that.getPosition(856)) { num++; if (bee.gravityScale == 0) { bee.velocity[0] = 0; bee.angle = 0; bee.displays[0].rotation = 0; bee.gravityScale = 1; this.beeArr[i].powerUp(); if (!that.shootPoint.floor) { //第一个球落地时更新下次发射点 that.shootPoint.floor = true; that.shootPoint.bx = bee.position[0] * that.factor; let nx = that.shootPoint.bx + that.hero.anchorOffsetX - that.hero.width / 2; let dt = Math.abs(that.hero.x - nx); egret.Tween.get(that.hero).to({ x: nx }, dt); } } //全部落地了 if ((i == len - 1) && num == len && that.shooting && that.shootPoint.beeNum == len) { console.log('enter', that.shooting) that.shooting = false; that.shootPoint.floor = false; setTimeout(function () { that.updateGrids(); that.updateBee() }, 100); } } else { if (bee.gravityScale == 0) { this.updateSpeed(bee); } else { bee.velocity[1] = -that.shootPoint.speedy; this.beeArr[i].powerUp(); } } } } public updateBee() { //更新球的水平坐标 let that = this; let bx = that.shootPoint.bx / that.factor; let direction = 0.8; let dx = that.hero.width / 2 / that.factor; if (bx > 7.5) { direction = -direction; dx = -dx; } for (let i = 0, len = that.beeArr.length; i < len; i++) { that.beeArr[i].boxBody.position[0] = i * direction + bx + dx; if ((that.beeArr[i].boxBody.position[0] > 14) || (that.beeArr[i].boxBody.position[0] < 1)) { that.beeArr[i].boxBody.position[0] = bx - dx - i * direction; } } } public updateGrids() { //更新方块的位置以及产生新方块 let that = this; for (let len = that.gridArr.length, i = len - 1; i >= 0; i--) { if (that.gridArr[i].isRemoved) { if (that.gridArr[i].img.parent && that.gridArr[i].type == 4) { that.world.removeBody(that.gridArr[i].boxBody); that.gridArr[i].img.parent.removeChild(that.gridArr[i].img); } that.gridArr.splice(i, 1); continue; } let y = that.gridArr[i].boxBody.position[1]; if (y <= that.getPosition(that.adaptParams.itemWidth * 6.5)) { //危险警告 console.log('danger'); } if (y <= that.getPosition(that.adaptParams.itemWidth * 7.5)) { //游戏结束 console.log('gameOver'); that.removeEventListener(egret.Event.ENTER_FRAME, that.onEnterFrame, that); that.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, that.touchBeginFun, that) that.removeEventListener(egret.TouchEvent.TOUCH_MOVE, that.touchMoveFun, that) that.removeEventListener(egret.TouchEvent.TOUCH_END, that.touchEndFun, that); sceneMaster.openModal(new rebornModal()); return; } that.gridArr[i].boxBody.position[1] = y - that.adaptParams.itemWidth / that.factor; } that.createGrids(); } public updateSpeed(bee) { //更新速度,保持匀速运动 let velocity = bee.velocity; if (Math.abs(velocity[1]) < 0.5) { console.log('垂直速度为', velocity[1]) velocity[1] = -0.5; } let k = Math.sqrt(this.ballSpeed / (velocity[0] * velocity[0] + velocity[1] * velocity[1])); bee.velocity = [k * velocity[0], k * velocity[1]]; bee.angle = 0; } private createBitmapByName(name: string): egret.Bitmap { var result: egret.Bitmap = new egret.Bitmap(); var texture: egret.Texture = RES.getRes(name + '_png'); result.texture = texture; return result; } public changeGraphics(percent) { //percent 进度百分比 let angle = percent * 2 * Math.PI * 3 / 4 + Math.PI / 2; this.arcPro.graphics.clear(); this.arcPro.graphics.lineStyle(20, 0xffdf5e, 1); this.arcPro.graphics.drawArc(100, 100, 50, Math.PI / 2, angle, false); this.arcPro.graphics.endFill(); } }<file_sep>/bin-debug/modal/getLifeModal.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __extends = this && this.__extends || function __extends(t, e) { function r() { this.constructor = t; } for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); r.prototype = e.prototype, t.prototype = new r(); }; var getLifeModal = (function (_super) { __extends(getLifeModal, _super); function getLifeModal() { return _super.call(this) || this; } getLifeModal.prototype.partAdded = function (partName, instance) { _super.prototype.partAdded.call(this, partName, instance); }; getLifeModal.prototype.childrenCreated = function () { _super.prototype.childrenCreated.call(this); if (this.videoBtn) { this.init(); } else { this.addEventListener(egret.Event.COMPLETE, this.init, this); } }; getLifeModal.prototype.init = function () { this.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.closeFun, this); this.videoBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.videoFun, this); this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.shareFun, this); }; getLifeModal.prototype.closeFun = function () { sceneMaster.closeModal(); }; getLifeModal.prototype.videoFun = function () { AdMaster.useVideo(function () { suc(); }, function () { CallbackMaster.openShare(function () { suc(); }); }); function suc() { } }; getLifeModal.prototype.shareFun = function () { CallbackMaster.openShare(function () { }); }; return getLifeModal; }(eui.Component)); __reflect(getLifeModal.prototype, "getLifeModal", ["eui.UIComponent", "egret.DisplayObject"]); <file_sep>/src/master/userDataMaster.ts class userDataMaster { public static myInfo: any = { uid: 0, openId: '', is_new_user: true, nickName: '', avatarUrl: '' };//用户信息 public static gold = 0;//能量果 public static cats = [ { id: 1, name: '白白球', state: true, process: 1000, target: 1000, belong: [0, 1, 2], des: '第一只拥有的精灵,洁白无一物', music: '《水晶》' }, { id: 2, name: '摇滚球', state: false, process: 0, target: 20000, belong: [3, 5, 6], des: '浑身散发魔性,带来的音乐也是酷酷风', music: '《幽默》' }, { id: 3, name: '水灵球', state: false, process: 0, target: 15000, belong: [7, 8, 10], des: '蜻蜓点水般的灵动,似风入海洋', music: '《沙滩》' }, { id: 4, name: '跑酷球', state: false, process: 0, target: 10000, belong: [11, 12, 13], des: '天生顽皮,似乎喂养了很多能量果', music: '《超越》' }, { id: 5, name: '火火球', state: false, process: 0, target: 0, belong: [15, 16, 17], des: '别看它小小的身体,却有大大的能量', music: '《希望》' }, { id: 6, name: '黑洞球', state: false, process: 0, target: 8000, belong: [18, 20, 21], des: '想法经常出乎意料,常常让你冒冷', music: '《迷宫》' }, { id: 7, name: '爆破球', state: false, process: 0, target: 6000, belong: [22, 23, 25], des: '拥有一秒燃爆森林的力量', music: '《时空》' }, { id: 8, name: '旋风球', state: false, process: 0, target: 5000, belong: [26, 27, 28], des: '可以带着风飞舞,跑遍世界角落', music: '《海洋》' }, { id: 9, name: '懒懒球', state: false, process: 0, target: 3000, belong: [30, 31, 32], des: '找不出第二只比懒懒球还懒的精灵了', music: '《星辰》' } ]; public static travels = [ { index: 0, id: 0, name: '月之桥', state: 0 }, { index: 1, id: 1, name: '白玉盘', state: 0 }, { index: 2, id: 2, name: '瑶台镜', state: 0 }, { index: 3, id: 3, name: '青云端', state: 0 }, { index: 4, id: -1, name: '', state: 0 }, { index: 5, id: 4, name: '仙人足', state: 0 }, { index: 6, id: 5, name: '树团团', state: 0 }, { index: 7, id: 6, name: '白兔岛', state: 0 }, { index: 8, id: 7, name: '蚀圆影', state: 0 }, { index: 9, id: -1, name: '', state: 0 }, { index: 10, id: 8, name: '明夜残', state: 0 }, { index: 11, id: 9, name: '落九乌', state: 0 }, { index: 12, id: 10, name: '升日月', state: 0 }, { index: 13, id: 11, name: '花落肩', state: 0 }, { index: 14, id: -1, name: '', state: 0 }, { index: 15, id: 12, name: '三生烟', state: 0 }, { index: 16, id: 13, name: '清晨迷', state: 0 }, { index: 17, id: 14, name: '尘滴落', state: 0 }, { index: 18, id: 15, name: '四木湖', state: 0 }, { index: 19, id: -1, name: '', state: 0 }, { index: 20, id: 16, name: '蔷薇轮', state: 0 }, { index: 21, id: 17, name: '嫩绿生', state: 0 }, { index: 22, id: 18, name: '清脆盘', state: 0 }, { index: 23, id: 19, name: '四季空', state: 0 }, { index: 24, id: -1, name: '', state: 0 }, { index: 25, id: 20, name: '木偶屋', state: 0 }, { index: 26, id: 21, name: '镜之藤', state: 0 }, { index: 27, id: 22, name: '缠上月', state: 0 }, { index: 28, id: 23, name: '莲渔舟', state: 0 }, { index: 29, id: -1, name: '', state: 0 }, { index: 30, id: 24, name: '光懒懒', state: 0 }, { index: 31, id: 25, name: '万颗紫', state: 0 }, { index: 32, id: 26, name: '七彩云', state: 0 }, { index: 33, id: -1, name: '', state: 0 } ];//state-当前状态 0--未获得 1--已获得 2--新获得尚未查看 public static travelList = [];//我拥有的印记 public static dayEnergy = { day: '', num: 0 };//上次领取每日能量的日期 public static myCollection: eui.ArrayCollection; public static shareUid = 0;//分享人id public static sourceEnergy = { uid: 0, day: '' };//能量分享的原始id,日期 public static bestScore = 0;//历史最高分 public static userInfoBtn; public static haveNickName = false;//是否有用户昵称头像 public static runCat = 0;//当前旅行的是哪个球 public static recommand: any;//推荐位列表 public static requestTimes = 0;//请求游戏数据的次数 public static dayTry = '';//上次试玩的日期 public static dayVideoEnergy = { day: '', num: 0 };//每日通过看视频/分享获得能量 public static loginCallback = null;//弹窗登录成功的回调 public static degree =0;//当前难度阶段默认0 public constructor() { } public static shared: userDataMaster; public static getInstance() { if (!userDataMaster.shared) { userDataMaster.shared = new userDataMaster(); } return userDataMaster.shared; } public static init() { let that = this; var sourceArr: any[] = [ userDataMaster.gold, userDataMaster.cats, userDataMaster.travels, userDataMaster.runCat ]; //用 ArrayCollection 包装 userDataMaster.myCollection = new eui.ArrayCollection(sourceArr); userDataMaster.login(); userDataMaster.getRecommand(); userDataMaster.getGameData(); } public static getGameData() { let that = this; let uid = userDataMaster.myInfo.uid; userDataMaster.requestTimes++; if (uid != 0) { ServiceMaster.post(ServiceMaster.getGameData, { uid }, (res) => { if (res.code == 1 && res.data) { let data = res.data; if (data.energy > 0) { userDataMaster.myGold = data.energy; } if (data.high_score) { userDataMaster.bestScore = data.high_score; } if (data.spirit_data.length > 0) { userDataMaster.MyCats = JSON.parse(data.spirit_data); } if (data.mark_data.length > 0) { userDataMaster.myTravels = JSON.parse(data.mark_data); } if (data.info.length > 0) { let info = JSON.parse(data.info); if (info.runCat >= 0) { userDataMaster.myRunCat = info.runCat; } if (info.dayEnergy) { userDataMaster.dayEnergy = info.dayEnergy; } if (info.dayTry) { userDataMaster.dayTry = info.dayTry; } if (info.travelList) { userDataMaster.travelList = info.travelList; } if (info.dayVideoEnergy) { userDataMaster.dayVideoEnergy = info.dayVideoEnergy; } if (info.degree) { userDataMaster.degree = info.degree; } } } }) } else { if (userDataMaster.requestTimes < 5) { setTimeout(function () { userDataMaster.getGameData(); }, 1000); } } } public static getRecommand() { //获取推荐位 ServiceMaster.post(ServiceMaster.getGameList, {}, (res) => { if (res.code == 1 && res.data) { userDataMaster.recommand = res.data; } }) } public static get myGold() { //获取能量果总数 return userDataMaster.gold; } public static set myGold(gold) { //更新能量果总数 userDataMaster.gold = gold; userDataMaster.myCollection.replaceItemAt(gold, 0); } public static get MyCats() { // 获取宠物列表数据 return userDataMaster.cats; } public static set myRunCat(index) { //更新当前出行球球 userDataMaster.runCat = index; userDataMaster.myCollection.replaceItemAt(index, 3); } public static setCat(index, cat) { //更新单个宠物数据 index--索引 cat--数据 userDataMaster.cats[index] = cat; userDataMaster.myCollection.replaceItemAt(userDataMaster.cats, 1); } public static set MyCats(cats) { // 更新宠物列表数据 userDataMaster.cats = cats; userDataMaster.myCollection.replaceItemAt(cats, 1); } public static get myTravels() { //旅行印记获取 return userDataMaster.travels; } public static set myTravels(travels) { //修改旅行印记 userDataMaster.travels = travels; userDataMaster.myCollection.replaceItemAt(travels, 2); } public static setTravel(index, travel) { //更新某项旅行印记数据 userDataMaster.travels[index] = travel; userDataMaster.myCollection.replaceItemAt(userDataMaster.travels, 2) } public static set getMyInfo(data) { userDataMaster.myInfo = data; } public static get getMyInfo() { return userDataMaster.myInfo; } public static getUserInfo(uid) { //获取用户道具信息 } public static get todayEnergy() { //获取今日可领取能量状态 if (userDataMaster.dayEnergy.day == userDataMaster.getToday()) { return userDataMaster.dayEnergy.num; } userDataMaster.dayEnergy = { day: userDataMaster.getToday(), num: 0 } return 0; } public static get todayTry() { //获取今日试玩状态 if (userDataMaster.dayTry == userDataMaster.getToday()) { //今日已试玩 return false; } return true; } public static updateTodayTry() { //更改今日试玩状态 userDataMaster.dayTry = userDataMaster.getToday(); } public static get todayVideoEnergy() { // 获取今天看视频或者分享获得能量状态 if (userDataMaster.dayVideoEnergy.day == userDataMaster.getToday()) { return userDataMaster.dayVideoEnergy.num; } userDataMaster.dayVideoEnergy = { day: userDataMaster.getToday(), num: 0 }; return 0; } public static async createLoginBtn(left, top, width, height) { let that = this; let scale = DeviceMaster.screenWidth / 750; left *= scale, top *= scale, width *= scale, height *= scale; userDataMaster.userInfoBtn = await platform.createUserInfoButton({ type: 'image', // type: 'text', // text: '获取用户信息', image: '../../resource/assets/imgData/img_yxbj.png', style: { left, top, width, height, lineHeight: 40, backgroundColor: '#ff0000', color: '#ffffff', textAlign: 'center', fontSize: 16, borderRadius: 4 } }) userDataMaster.userInfoBtn.onTap((res) => { userDataMaster.updateUser(res) }) } public static async updateUser(res: any = null) { let userInfo = res.userInfo; userDataMaster.myInfo.nickName = userInfo.nickName; userDataMaster.myInfo.avatarUrl = userInfo.avatarUrl; let params: any = { uid: userDataMaster.getMyInfo.uid, nickName: userInfo.nickName, gender: userInfo.gender, avatarUrl: userInfo.avatarUrl }; ServiceMaster.post( ServiceMaster.updateUser, params, function (suc) { if (parseInt(suc.code) === 1 && suc.data) { //修改用户信息成功 userDataMaster.userInfoBtn && userDataMaster.userInfoBtn.destroy(); userDataMaster.loginCallback && userDataMaster.loginCallback(); userDataMaster.loginCallback = null; } } ); } public static async login(res: any = null) { let login = await platform.login(); let params: any = { code: login.code }; // if (res != null) { // params.encryptedData = res.encryptedData; // params.iv = res.iv // } if (userDataMaster.shareUid > 0) { params.pid = userDataMaster.shareUid; } ServiceMaster.post( ServiceMaster.logins, params, function (suc) { if (parseInt(suc.code) === 1 && suc.data) { //登录成功 userDataMaster.getMyInfo = suc.data; //测试测试……………… // userDataMaster.myInfo.is_new_user = true; // userDataMaster.userInfoBtn && userDataMaster.userInfoBtn.destroy(); //初始化用户openid platform.openDataContext.postMessage({ type: "openid", openid: suc.data.openId }); userDataMaster.getUserInfo(suc.data.uid) } } ); } public static getToday() { //获取格式化的当前日期 let date = new Date(); let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) + '' : '0' + (date.getMonth() + 1); let day = date.getDate() > 9 ? (date.getDate()) + '' : '0' + date.getDate(); return date.getFullYear() + '-' + month + '-' + day; } } window['userDataMaster'] = userDataMaster<file_sep>/bin-debug/master/userDataMaster.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var userDataMaster = (function () { function userDataMaster() { } userDataMaster.getInstance = function () { if (!userDataMaster.shared) { userDataMaster.shared = new userDataMaster(); } return userDataMaster.shared; }; userDataMaster.init = function () { var that = this; var sourceArr = [ userDataMaster.gold, userDataMaster.cats, userDataMaster.travels, userDataMaster.runCat ]; //用 ArrayCollection 包装 userDataMaster.myCollection = new eui.ArrayCollection(sourceArr); userDataMaster.login(); userDataMaster.getRecommand(); userDataMaster.getGameData(); }; userDataMaster.getGameData = function () { var that = this; var uid = userDataMaster.myInfo.uid; userDataMaster.requestTimes++; if (uid != 0) { ServiceMaster.post(ServiceMaster.getGameData, { uid: uid }, function (res) { if (res.code == 1 && res.data) { var data = res.data; if (data.energy > 0) { userDataMaster.myGold = data.energy; } if (data.high_score) { userDataMaster.bestScore = data.high_score; } if (data.spirit_data.length > 0) { userDataMaster.MyCats = JSON.parse(data.spirit_data); } if (data.mark_data.length > 0) { userDataMaster.myTravels = JSON.parse(data.mark_data); } if (data.info.length > 0) { var info = JSON.parse(data.info); if (info.runCat >= 0) { userDataMaster.myRunCat = info.runCat; } if (info.dayEnergy) { userDataMaster.dayEnergy = info.dayEnergy; } if (info.dayTry) { userDataMaster.dayTry = info.dayTry; } if (info.travelList) { userDataMaster.travelList = info.travelList; } if (info.dayVideoEnergy) { userDataMaster.dayVideoEnergy = info.dayVideoEnergy; } if (info.degree) { userDataMaster.degree = info.degree; } } } }); } else { if (userDataMaster.requestTimes < 5) { setTimeout(function () { userDataMaster.getGameData(); }, 1000); } } }; userDataMaster.getRecommand = function () { //获取推荐位 ServiceMaster.post(ServiceMaster.getGameList, {}, function (res) { if (res.code == 1 && res.data) { userDataMaster.recommand = res.data; } }); }; Object.defineProperty(userDataMaster, "myGold", { get: function () { //获取能量果总数 return userDataMaster.gold; }, set: function (gold) { //更新能量果总数 userDataMaster.gold = gold; userDataMaster.myCollection.replaceItemAt(gold, 0); }, enumerable: true, configurable: true }); Object.defineProperty(userDataMaster, "MyCats", { get: function () { // 获取宠物列表数据 return userDataMaster.cats; }, set: function (cats) { // 更新宠物列表数据 userDataMaster.cats = cats; userDataMaster.myCollection.replaceItemAt(cats, 1); }, enumerable: true, configurable: true }); Object.defineProperty(userDataMaster, "myRunCat", { set: function (index) { //更新当前出行球球 userDataMaster.runCat = index; userDataMaster.myCollection.replaceItemAt(index, 3); }, enumerable: true, configurable: true }); userDataMaster.setCat = function (index, cat) { //更新单个宠物数据 index--索引 cat--数据 userDataMaster.cats[index] = cat; userDataMaster.myCollection.replaceItemAt(userDataMaster.cats, 1); }; Object.defineProperty(userDataMaster, "myTravels", { get: function () { //旅行印记获取 return userDataMaster.travels; }, set: function (travels) { //修改旅行印记 userDataMaster.travels = travels; userDataMaster.myCollection.replaceItemAt(travels, 2); }, enumerable: true, configurable: true }); userDataMaster.setTravel = function (index, travel) { //更新某项旅行印记数据 userDataMaster.travels[index] = travel; userDataMaster.myCollection.replaceItemAt(userDataMaster.travels, 2); }; Object.defineProperty(userDataMaster, "getMyInfo", { get: function () { return userDataMaster.myInfo; }, set: function (data) { userDataMaster.myInfo = data; }, enumerable: true, configurable: true }); userDataMaster.getUserInfo = function (uid) { //获取用户道具信息 }; Object.defineProperty(userDataMaster, "todayEnergy", { get: function () { //获取今日可领取能量状态 if (userDataMaster.dayEnergy.day == userDataMaster.getToday()) { return userDataMaster.dayEnergy.num; } userDataMaster.dayEnergy = { day: userDataMaster.getToday(), num: 0 }; return 0; }, enumerable: true, configurable: true }); Object.defineProperty(userDataMaster, "todayTry", { get: function () { //获取今日试玩状态 if (userDataMaster.dayTry == userDataMaster.getToday()) { //今日已试玩 return false; } return true; }, enumerable: true, configurable: true }); userDataMaster.updateTodayTry = function () { //更改今日试玩状态 userDataMaster.dayTry = userDataMaster.getToday(); }; Object.defineProperty(userDataMaster, "todayVideoEnergy", { get: function () { // 获取今天看视频或者分享获得能量状态 if (userDataMaster.dayVideoEnergy.day == userDataMaster.getToday()) { return userDataMaster.dayVideoEnergy.num; } userDataMaster.dayVideoEnergy = { day: userDataMaster.getToday(), num: 0 }; return 0; }, enumerable: true, configurable: true }); userDataMaster.createLoginBtn = function (left, top, width, height) { return __awaiter(this, void 0, void 0, function () { var that, scale, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: that = this; scale = DeviceMaster.screenWidth / 750; left *= scale, top *= scale, width *= scale, height *= scale; _a = userDataMaster; return [4 /*yield*/, platform.createUserInfoButton({ type: 'image', // type: 'text', // text: '获取用户信息', image: '../../resource/assets/imgData/img_yxbj.png', style: { left: left, top: top, width: width, height: height, lineHeight: 40, backgroundColor: '#ff0000', color: '#ffffff', textAlign: 'center', fontSize: 16, borderRadius: 4 } })]; case 1: _a.userInfoBtn = _b.sent(); userDataMaster.userInfoBtn.onTap(function (res) { userDataMaster.updateUser(res); }); return [2 /*return*/]; } }); }); }; userDataMaster.updateUser = function (res) { if (res === void 0) { res = null; } return __awaiter(this, void 0, void 0, function () { var userInfo, params; return __generator(this, function (_a) { userInfo = res.userInfo; userDataMaster.myInfo.nickName = userInfo.nickName; userDataMaster.myInfo.avatarUrl = userInfo.avatarUrl; params = { uid: userDataMaster.getMyInfo.uid, nickName: userInfo.nickName, gender: userInfo.gender, avatarUrl: userInfo.avatarUrl }; ServiceMaster.post(ServiceMaster.updateUser, params, function (suc) { if (parseInt(suc.code) === 1 && suc.data) { //修改用户信息成功 userDataMaster.userInfoBtn && userDataMaster.userInfoBtn.destroy(); userDataMaster.loginCallback && userDataMaster.loginCallback(); userDataMaster.loginCallback = null; } }); return [2 /*return*/]; }); }); }; userDataMaster.login = function (res) { if (res === void 0) { res = null; } return __awaiter(this, void 0, void 0, function () { var login, params; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, platform.login()]; case 1: login = _a.sent(); params = { code: login.code }; // if (res != null) { // params.encryptedData = res.encryptedData; // params.iv = res.iv // } if (userDataMaster.shareUid > 0) { params.pid = userDataMaster.shareUid; } ServiceMaster.post(ServiceMaster.logins, params, function (suc) { if (parseInt(suc.code) === 1 && suc.data) { //登录成功 userDataMaster.getMyInfo = suc.data; //测试测试……………… // userDataMaster.myInfo.is_new_user = true; // userDataMaster.userInfoBtn && userDataMaster.userInfoBtn.destroy(); //初始化用户openid platform.openDataContext.postMessage({ type: "openid", openid: suc.data.openId }); userDataMaster.getUserInfo(suc.data.uid); } }); return [2 /*return*/]; } }); }); }; userDataMaster.getToday = function () { //获取格式化的当前日期 var date = new Date(); var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) + '' : '0' + (date.getMonth() + 1); var day = date.getDate() > 9 ? (date.getDate()) + '' : '0' + date.getDate(); return date.getFullYear() + '-' + month + '-' + day; }; userDataMaster.myInfo = { uid: 0, openId: '', is_new_user: true, nickName: '', avatarUrl: '' }; //用户信息 userDataMaster.gold = 0; //能量果 userDataMaster.cats = [ { id: 1, name: '白白球', state: true, process: 1000, target: 1000, belong: [0, 1, 2], des: '第一只拥有的精灵,洁白无一物', music: '《水晶》' }, { id: 2, name: '摇滚球', state: false, process: 0, target: 20000, belong: [3, 5, 6], des: '浑身散发魔性,带来的音乐也是酷酷风', music: '《幽默》' }, { id: 3, name: '水灵球', state: false, process: 0, target: 15000, belong: [7, 8, 10], des: '蜻蜓点水般的灵动,似风入海洋', music: '《沙滩》' }, { id: 4, name: '跑酷球', state: false, process: 0, target: 10000, belong: [11, 12, 13], des: '天生顽皮,似乎喂养了很多能量果', music: '《超越》' }, { id: 5, name: '火火球', state: false, process: 0, target: 0, belong: [15, 16, 17], des: '别看它小小的身体,却有大大的能量', music: '《希望》' }, { id: 6, name: '黑洞球', state: false, process: 0, target: 8000, belong: [18, 20, 21], des: '想法经常出乎意料,常常让你冒冷', music: '《迷宫》' }, { id: 7, name: '爆破球', state: false, process: 0, target: 6000, belong: [22, 23, 25], des: '拥有一秒燃爆森林的力量', music: '《时空》' }, { id: 8, name: '旋风球', state: false, process: 0, target: 5000, belong: [26, 27, 28], des: '可以带着风飞舞,跑遍世界角落', music: '《海洋》' }, { id: 9, name: '懒懒球', state: false, process: 0, target: 3000, belong: [30, 31, 32], des: '找不出第二只比懒懒球还懒的精灵了', music: '《星辰》' } ]; userDataMaster.travels = [ { index: 0, id: 0, name: '月之桥', state: 0 }, { index: 1, id: 1, name: '白玉盘', state: 0 }, { index: 2, id: 2, name: '瑶台镜', state: 0 }, { index: 3, id: 3, name: '青云端', state: 0 }, { index: 4, id: -1, name: '', state: 0 }, { index: 5, id: 4, name: '仙人足', state: 0 }, { index: 6, id: 5, name: '树团团', state: 0 }, { index: 7, id: 6, name: '白兔岛', state: 0 }, { index: 8, id: 7, name: '蚀圆影', state: 0 }, { index: 9, id: -1, name: '', state: 0 }, { index: 10, id: 8, name: '明夜残', state: 0 }, { index: 11, id: 9, name: '落九乌', state: 0 }, { index: 12, id: 10, name: '升日月', state: 0 }, { index: 13, id: 11, name: '花落肩', state: 0 }, { index: 14, id: -1, name: '', state: 0 }, { index: 15, id: 12, name: '三生烟', state: 0 }, { index: 16, id: 13, name: '清晨迷', state: 0 }, { index: 17, id: 14, name: '尘滴落', state: 0 }, { index: 18, id: 15, name: '四木湖', state: 0 }, { index: 19, id: -1, name: '', state: 0 }, { index: 20, id: 16, name: '蔷薇轮', state: 0 }, { index: 21, id: 17, name: '嫩绿生', state: 0 }, { index: 22, id: 18, name: '清脆盘', state: 0 }, { index: 23, id: 19, name: '四季空', state: 0 }, { index: 24, id: -1, name: '', state: 0 }, { index: 25, id: 20, name: '木偶屋', state: 0 }, { index: 26, id: 21, name: '镜之藤', state: 0 }, { index: 27, id: 22, name: '缠上月', state: 0 }, { index: 28, id: 23, name: '莲渔舟', state: 0 }, { index: 29, id: -1, name: '', state: 0 }, { index: 30, id: 24, name: '光懒懒', state: 0 }, { index: 31, id: 25, name: '万颗紫', state: 0 }, { index: 32, id: 26, name: '七彩云', state: 0 }, { index: 33, id: -1, name: '', state: 0 } ]; //state-当前状态 0--未获得 1--已获得 2--新获得尚未查看 userDataMaster.travelList = []; //我拥有的印记 userDataMaster.dayEnergy = { day: '', num: 0 }; //上次领取每日能量的日期 userDataMaster.shareUid = 0; //分享人id userDataMaster.sourceEnergy = { uid: 0, day: '' }; //能量分享的原始id,日期 userDataMaster.bestScore = 0; //历史最高分 userDataMaster.haveNickName = false; //是否有用户昵称头像 userDataMaster.runCat = 0; //当前旅行的是哪个球 userDataMaster.requestTimes = 0; //请求游戏数据的次数 userDataMaster.dayTry = ''; //上次试玩的日期 userDataMaster.dayVideoEnergy = { day: '', num: 0 }; //每日通过看视频/分享获得能量 userDataMaster.loginCallback = null; //弹窗登录成功的回调 userDataMaster.degree = 0; //当前难度阶段默认0 return userDataMaster; }()); __reflect(userDataMaster.prototype, "userDataMaster"); window['userDataMaster'] = userDataMaster; <file_sep>/src/component/starCom.ts class starCom { public img: egret.Bitmap;//图片 public boxBody: p2.Body; public type = 4;//星星 public isRemoved = false;//是否已经被移除 public constructor() { this.init() } public init() { this.img = this.createBitmapByName('star'); } public createBody(x, y, that) { var boxShape: p2.Shape = new p2.Box({ width: 2, height: 2 }); boxShape.collisionGroup = 2; boxShape.collisionMask = 1; boxShape.sensor = true;//作为传感器,被穿透 this.boxBody = new p2.Body({ mass: 100, position: [x, y], type: p2.Body.STATIC }); this.boxBody.addShape(boxShape); this.boxBody.displays = [this.img]; that.addChild(this.img); return this.boxBody; } public updateText(that, callback: Function = null) { //碰撞后做出反应 let self = this; self.isRemoved = true; egret.Tween.removeTweens(self.img); egret.Tween.get(self.img).to({ scaleX: 1.5, scaleY: 1.5 }, 100).to({ scaleX: 1, scaleY: 1 }, 100); callback && callback(); } private createBitmapByName(name: string): egret.Bitmap { var result: egret.Bitmap = new egret.Bitmap(); var texture: egret.Texture = RES.getRes(name + '_png'); result.texture = texture; result.anchorOffsetX = result.width / 2; result.anchorOffsetY = result.height / 2; return result; } } window['starCom'] = starCom<file_sep>/bin-debug/master/movieMaster.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var movieMaster = (function () { function movieMaster() { } movieMaster.init = function () { var data = RES.getRes("ball_travel_gif_json"); var txtr = RES.getRes("ball_travel_gif_png"); movieMaster.mcFactory = new egret.MovieClipDataFactory(data, txtr); }; movieMaster.getGif = function (name) { var mc = new egret.MovieClip(movieMaster.mcFactory.generateMovieClipData(name)); return mc; }; return movieMaster; }()); __reflect(movieMaster.prototype, "movieMaster"); window['movieMaster'] = movieMaster; <file_sep>/bin-debug/modal/getSuccess.js var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __extends = this && this.__extends || function __extends(t, e) { function r() { this.constructor = t; } for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); r.prototype = e.prototype, t.prototype = new r(); }; var getSuccess = (function (_super) { __extends(getSuccess, _super); function getSuccess(type, num) { if (type === void 0) { type = 1; } if (num === void 0) { num = 0; } var _this = _super.call(this) || this; _this.type = 1; //类型 1--钻石 2--体力 _this.num = 0; //数量 _this.shareType = true; //是否分享 默认分享 _this.type = type; _this.num = num; return _this; } getSuccess.prototype.partAdded = function (partName, instance) { _super.prototype.partAdded.call(this, partName, instance); }; getSuccess.prototype.childrenCreated = function () { _super.prototype.childrenCreated.call(this); if (this.knowBtn) { this.init(); } else { this.addEventListener(egret.Event.COMPLETE, this.init, this); } }; getSuccess.prototype.init = function () { if (this.type == 2) { this.img.texture = RES.getRes('img_bullet_a2_png'); } this.txt.text = 'x' + this.num; egret.Tween.get(this.light, { loop: true }).to({ rotation: 360 }, 5000); this.knowBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.knowFun, this); this.ifShare.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ifShareFun, this); }; getSuccess.prototype.knowFun = function () { egret.Tween.removeTweens(this.light); if (this.shareType) { CallbackMaster.openShare(null, false); } sceneMaster.closeModal(); }; getSuccess.prototype.ifShareFun = function () { this.shareType = !this.shareType; }; return getSuccess; }(eui.Component)); __reflect(getSuccess.prototype, "getSuccess", ["eui.UIComponent", "egret.DisplayObject"]); <file_sep>/src/component/ballCom.ts class ballCom { public img: egret.Bitmap;//图片 public boxBody: p2.Body; public type = 3;//精灵 public isRemoved = false;//是否已经被移除 public constructor() { this.init() } public init() { this.img = this.createBitmapByName('img_bullet_a1'); } public createBody(x, y, that) { var boxShape: p2.Shape = new p2.Box({ width: 2, height: 2 }); boxShape.collisionGroup = 2; boxShape.collisionMask = 1; boxShape.sensor = true;//作为传感器,被穿透 this.boxBody = new p2.Body({ mass: 100, position: [x, y], type: p2.Body.STATIC }); this.boxBody.addShape(boxShape); this.boxBody.displays = [this.img]; that.addChild(this.img); return this.boxBody; } public updateText(that, callback: Function = null) { //销毁 let self = this; self.boxBody.shapes[0].collisionMask = 0; self.isRemoved = true; setTimeout(() => { self.boxBody.type = p2.Body.DYNAMIC; self.boxBody.gravityScale = 0; self.boxBody.velocity = [0, -10]; self.boxBody.angularVelocity = 1; //计算掉落到地面销毁时间 let t=(self.boxBody.position[1]-that.getPosition(935))/10; console.log(t) setTimeout(function () { //销毁 that.world.removeBody(self.boxBody); self.img.parent && self.img.parent.removeChild(self.img); callback && callback(); }, t*1000); }, 1000); //播放销毁的动画 } private createBitmapByName(name: string): egret.Bitmap { var result: egret.Bitmap = new egret.Bitmap(); var texture: egret.Texture = RES.getRes(name + '_png'); result.texture = texture; result.anchorOffsetX = result.width / 2; result.anchorOffsetY = result.height / 2; return result; } } window['ballCom'] = ballCom
10610dfccbb6c9edb6a085853567f4298382e0f9
[ "JavaScript", "TypeScript" ]
28
TypeScript
LuYueYan/shoot
8d05e40a9a2013bd2814dbaf211cdebb1be52ea6
1cd76d218bd9fe16d5bd04d4ca9d205c53f3fe43
refs/heads/master
<file_sep>import model.User; import java.util.HashMap; public class Main { private static String address="scripts.js"; public static void main(String[] args) throws Exception { User user = new User("temp_firstname", "temp_lastname", "temp_username", "1111", "<EMAIL>"); HashMap<String , Object> userHashMap = new HashMap<>(); userHashMap.put("user",user); JsCodeGenerator jsCodeGenerator=new JsCodeGenerator(userHashMap ,address); jsCodeGenerator.runJsCode(); } }
e3a62e363ad202270dc1a70fe3399b8f03f11c35
[ "Java" ]
1
Java
MahtabSarlak/graalvm-practice
ab56035b2dd75455cdcc15c4f4aa1226919abb07
a4f7e2d902d49ac054b0c0228e50f42fc831cb08
refs/heads/master
<repo_name>qhpeklh5959/ACM-Problems<file_sep>/Problems/2000/description.md Newton's method ----------- Given a initial $x_0$ and a recurrence $$ x__{n+1}=x_n - \frac{x_n^2-a}{2x_n} $$ tell me $x_n$. ------------- ##input There are 10 test cases. In each case there are three integer denoted to a, $x_0$ and n. $x_0 \geq a$ $0 < n < 1 \times 10^9$ ##output For each case, print the x_n in one line. Round to 1e-6. ------------- ##sample input 4 4 1 ##sample output 2.500000 <file_sep>/Problems/2000/2000.cpp /* * mail to <EMAIL> if any problem */ #include <stdio.h> const double eps = 1e-6; int main() { freopen("in.in", "r", stdin); freopen("out.out", "w", stdout); int a, n, x0; while(~scanf("%d%d%d", &a, &x0, &n)) { double xnPlus = x0, xn = (double)x0; double xnPlusTmp; for(int i = 0; i < n; i++) { xnPlus = xn - (xn * xn - a) / (2 * xn); if(xn - xnPlus < eps) break; xn = xnPlus; } printf("%.6f\n", xnPlus); } return 0; } <file_sep>/Problems/1001/Description.md #Build Twin Towers# **Time Limit: 1000ms** **Memory Limit: 32768 KiloBytes** --------- Severus is an architect. Today he wants to build a quartz-twin-tower. He has N blocks of quartz, the size of each block is known. He wants to use these blocks of quartz to build the towers. But he is a Virgo. He thinks the two towers must be of the same height. It's a big problem for him. But you are a programmer, it's a piece of cake for you. So it's the time to show your ability! --------- ##Input There are multiple test cases. In each case there are two lines. In the first line there is a integer N(1 \leq N \leq 100), and in the following line there are n integers, indicate the height of the blocks. ------------ ##Output For each case, print the maximum height Severus can build. If he can't build the tower, output "Impossible". ------------ ##Sample Input 5 1 3 4 5 2 ------------ ##Sample Output 7 ---------- ##Author Severus <file_sep>/Problems/1000/Description.md #Caculate A + B# **Time Limit: 1000ms** **Memory Limit: 32768 Kilobytes** -------------- Give you two integers a and b, work out a + b. ----------- ##Input There are multiple test cases, each case only have two integers in one line separated by a space. The input cases terminited by EOF. ---------- ##Output For each cases, there are only one integer in one line. ----------- ##Sample Input## 2 3 ----------- ##Sample Output## 5 <file_sep>/Problems/1001/Solution.md #解题报告# -------- 本题是动态规划题目。 首先,题目中已经给出,所有水晶块的高度和不会超过2000,那么显然可以用类背包方式来解决。 `dp[i][j]`表示的是用前i个水晶块建造高度差是j的两座塔,那个比较矮的塔的最高高度,看起来非常巧妙的一个状态。 那么显然,每一个状态与前面的状态是相关的,对于每一个水晶块,有三种可能: 1. 根本不用 2. 把它放在比较矮的塔上,这个时候应该比较这个水晶块的高度`h[i]`和`j`的大小,如果`h[i] < j`,那么总高度就增加`h[i]`,否则总高度就增加`j`,然后矮的塔变成了高的塔。 3. 把它放在比较高的塔上,这个时候最高高度不变,但是高度差变大了。 也就是说目前我们得到的转移方程就应该是 `dp[i][j]=max(dp[i-1][j], dp[i-1][j-h[i]]+h[i], dp[i-1][j+h[i]])` 那么最终我们只需要找到最大的那个`dp[i][0]`就好了。 <file_sep>/Problems/1001/1001.cc /************************************************************************* > File Name: 1001.cc > Author: > Mail: > Created Time: 2014年11月19日 星期三 11时27分35秒 ************************************************************************/ #include <cstdio> #include <climits> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int a[110], sum[110]; int dp[110][2010]; int n; void solve() { memset(sum, 0, sizeof(sum)); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); sum[i] = sum[i - 1] + a[i]; } for (int i = 0; i <= 100; i++) for (int j = 0; j <= 2000; j++) dp[i][j] = INT_MIN; dp[0][0] = 0; for (int i = 1; i <= n; i++) for (int j = sum[i]; j >= 0; j--) { if (a[i] >= j) dp[i][j] = max(dp[i - 1][j], max(dp[i - 1][a[i] - j] + j, dp[i - 1][j + a[i]])); else dp[i][j] = max(dp[i - 1][j], max(dp[i - 1][j - a[i]] + a[i], dp[i - 1][j + a[i]])); } int ans = -1; for (int i = 1; i <= n; i++) ans = max(ans, dp[i][0]); if (ans > 0) printf("%d\n", ans); else puts("Impossible"); } int main() { while (scanf("%d", &n) == 1) solve(); return 0; } <file_sep>/Problems/2000/solution.md Please google newton's method! <file_sep>/Problems/1000/data.cc #include <cstdio> #include <ctime> #include <climits> #include <cstdlib> #include <iostream> using namespace std; int main() { srand(time(NULL)); for (int i = 0; i < 100; i++) { int a = rand() % 10000 + 1; int b = rand() % 10000 + 1; cout << a << " " << b << endl; } return 0; } <file_sep>/Problems/1001/data.cc /************************************************************************* > File Name: data.cc > Author: > Mail: > Created Time: 2014年11月19日 星期三 11时32分03秒 ************************************************************************/ #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int main() { srand(time(NULL)); for (int i = 0; i < 20; i++) { int n = rand() % 100 + 1; cout << n << endl; for (int j = 0; j < n; j++) { int x = rand() % 20 + 1; cout << x << " "; } cout << endl; } }<file_sep>/README.md #DOTA ACM原创题题库# 组织一下学校的原创题库,以备出比赛之用 ---------- 出题人列表: 秦华鹏、杨智宇、廖统浪 ---------- 每月两道题,分别于15日,30日提交 提交格式如题目列表里面的1000,每道题提交5个文件,分别为`Description.md`,`data.cc/py/xxxx`,`题号.xxx`,`in.in`,`out.out/checker.xxx`,分别为题目描述、数据程序、标程、输入数据、输出数据或`special judge`所用的cheker 提交过后,需要在根目录中的`dic.md`中增加题目-tag(难度系数)的简要描述,以便组题。
5ee86198cd8182641dcbf1215adbfa616dd6047d
[ "Markdown", "C++" ]
10
Markdown
qhpeklh5959/ACM-Problems
33488fd1e218ceabd62a2ea871f317bcfd146749
94d5bac5404703081905877e1ec64092e0c3a303
refs/heads/master
<file_sep>package br.com.desafio.view; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import br.com.desafio.model.Funcionario; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.JTextField; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Color; import javax.swing.border.LineBorder; public class TelaCadastroFuncionario extends JFrame { private static final long serialVersionUID = 1L; public static TelaCadastroFuncionario telaCadastroFuncionarios = new TelaCadastroFuncionario(); private JPanel contentPane; private JTextField TextoNomeFunc; private JTextField TextoCPFFunc; public TelaCadastroFuncionario() { setTitle("Cadastro de Funcionários"); setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 355, 281); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.setBorder(new LineBorder(Color.WHITE, 4, true)); panel.setBounds(52, 28, 245, 210); contentPane.add(panel); panel.setLayout(null); JLabel lblNome = new JLabel("Nome:"); lblNome.setBounds(10, 51, 73, 14); panel.add(lblNome); lblNome.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblCompetncia = new JLabel("Compet\u00EAncia:"); lblCompetncia.setBounds(10, 101, 73, 14); panel.add(lblCompetncia); lblCompetncia.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblCpf = new JLabel("CPF:"); lblCpf.setBounds(10, 76, 73, 14); panel.add(lblCpf); lblCpf.setHorizontalAlignment(SwingConstants.RIGHT); TextoNomeFunc = new JTextField(); TextoNomeFunc.setBounds(93, 48, 125, 20); panel.add(TextoNomeFunc); TextoNomeFunc.setColumns(10); TextoCPFFunc = new JTextField(); TextoCPFFunc.setBounds(93, 73, 125, 20); panel.add(TextoCPFFunc); TextoCPFFunc.setColumns(10); JComboBox comboCompetencia = new JComboBox(); comboCompetencia.setBounds(93, 98, 125, 20); panel.add(comboCompetencia); comboCompetencia.setModel(new DefaultComboBoxModel(new String[] {"Fone", "Internet", "TV", "Fone/Internet", "Fone/TV", "Internet/TV", "FIT"})); JButton btnIncluir = new JButton("Incluir"); btnIncluir.setBounds(30, 126, 89, 23); panel.add(btnIncluir); JButton btnVoltar = new JButton("Cancelar"); btnVoltar.setBounds(129, 126, 89, 23); panel.add(btnVoltar); btnVoltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnIncluir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String Nome = TextoNomeFunc.getText().toString(); String CPF = TextoCPFFunc.getText().toString(); String Competencia = comboCompetencia.getSelectedItem().toString(); if (Nome.isEmpty() || CPF.isEmpty() || Competencia.isEmpty()){ JOptionPane.showMessageDialog(null,"Insira todos os campos ","eaeae",JOptionPane.INFORMATION_MESSAGE); } else if(Funcionario.addFuncionario(Nome, CPF, Competencia)){ JOptionPane.showMessageDialog(null,"Funcionario inserido com sucesso! ","eaeae",JOptionPane.INFORMATION_MESSAGE); } else{ JOptionPane.showMessageDialog(null,"Insira todos os campos ","eaeae",JOptionPane.INFORMATION_MESSAGE); } ; } }); } } <file_sep>package br.com.desafio.view; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import br.com.desafio.model.CadastroCliente; import br.com.desafio.model.Clientes; import java.awt.Color; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JOptionPane; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.SwingConstants; import javax.swing.border.TitledBorder; import javax.swing.border.LineBorder; public class TelaCadastroCliente extends JFrame { /** * */ private static final long serialVersionUID = 1L; public static TelaCadastroCliente telaCadastroCliente = new TelaCadastroCliente(); private JPanel contentPane; private JTextField nomeTexto; private JTextField CPF; private JTextField enderecoTexto; public TelaCadastroCliente() { setTitle("Cadastro de Clientes"); setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 316, 265); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.setBorder(new LineBorder(Color.WHITE, 4, true)); panel.setBounds(30, 45, 251, 165); contentPane.add(panel); panel.setLayout(null); JLabel lblNome = new JLabel("Nome:"); lblNome.setBounds(-18, 14, 81, 14); panel.add(lblNome); lblNome.setHorizontalAlignment(SwingConstants.RIGHT); nomeTexto = new JTextField(); nomeTexto.setBounds(71, 11, 150, 20); panel.add(nomeTexto); nomeTexto.setColumns(10); JLabel lblCPF = new JLabel("CPF:"); lblCPF.setBounds(-18, 43, 81, 14); panel.add(lblCPF); lblCPF.setHorizontalAlignment(SwingConstants.RIGHT); CPF = new JTextField(); CPF.setBounds(71, 40, 150, 20); panel.add(CPF); CPF.setColumns(10); JLabel lblEndereco = new JLabel("Endere\u00E7o:"); lblEndereco.setBounds(-18, 74, 81, 14); panel.add(lblEndereco); lblEndereco.setHorizontalAlignment(SwingConstants.RIGHT); enderecoTexto = new JTextField(); enderecoTexto.setBounds(71, 71, 150, 20); panel.add(enderecoTexto); enderecoTexto.setColumns(10); JComboBox comboBoxServico = new JComboBox(); comboBoxServico.setBounds(71, 99, 150, 20); panel.add(comboBoxServico); comboBoxServico.setModel(new DefaultComboBoxModel(new String[] {"TV", "FONE", "INTERNET", "TV/INTERNET", "TV/FONE", "INTERNET/FONE"})); JLabel lblServico = new JLabel("Servi\u00E7o:"); lblServico.setBounds(-34, 99, 97, 14); panel.add(lblServico); lblServico.setHorizontalAlignment(SwingConstants.RIGHT); JButton btnCadastrar = new JButton("Cadastrar"); btnCadastrar.setBounds(11, 130, 105, 23); panel.add(btnCadastrar); JButton btnVoltar = new JButton("Voltar"); btnVoltar.setBounds(136, 130, 105, 23); panel.add(btnVoltar); btnVoltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnCadastrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String cliente = nomeTexto.getText().toString(); String cpf = CPF.getText().toString(); String endereco = enderecoTexto.getText().toString(); String plano = comboBoxServico.getSelectedItem().toString(); if(cliente.isEmpty() || cpf.isEmpty() || endereco.isEmpty() || plano.isEmpty()){ JOptionPane.showMessageDialog(null,"Insira todos os dados corretamente","Erro",JOptionPane.WARNING_MESSAGE); } else{ Clientes.addCliente(cliente, cpf, endereco, plano); JOptionPane.showMessageDialog(null,"suecsso","Sucesso",JOptionPane.WARNING_MESSAGE); } } }); } } <file_sep>package br.com.desafio.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import br.com.desafio.model.ConexaoBanco; import javax.swing.border.TitledBorder; import javax.swing.UIManager; public class TelaChamados extends JFrame { private JPanel contentPane; public static JTable table; public static TelaChamados telaChamados = new TelaChamados(); public static String CodCliente = ""; public static String StatusChamado=""; static Object CelulaSelecionada; public TelaChamados() { setTitle("Chamados"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 950, 454); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton btnAddChamado = new JButton("Novo Chamado"); btnAddChamado.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new TelaNovoChamado().setVisible(true); }}); btnAddChamado.setBounds(6, 19, 130, 23); contentPane.add(btnAddChamado); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Chamados", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); panel.setBounds(4, 54, 926, 323); contentPane.add(panel); panel.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(6, 16, 914, 300); panel.add(scrollPane); table = new JTable(); table.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "N\u00FAmero ", "Cliente", "Tipo", "Respons\u00E1vel", "Data Abertura", "Data Encerramento","Prioridade", "Status", } ) { boolean[] columnEditables = new boolean[] { false, true, true, true }; public boolean isCellEditable(int row, int column) { return columnEditables[column]; } }); table.getColumnModel().getColumn(0).setResizable(false); table.setDefaultRenderer(Object.class, new CellRenderer()); table.setRowSelectionAllowed(true); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setBackground(Color.WHITE); scrollPane.setViewportView(table); JButton btnChamadosAbertos = new JButton("Mostrar Abertos"); btnChamadosAbertos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id " + "left join funcionarios f on ch.chamado_funcionario_id = f.funcionario_id where chamado_status = 'Aberto'"; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } }); btnChamadosAbertos.setBounds(191, 381, 141, 23); contentPane.add(btnChamadosAbertos); JButton btnChamadosFechados = new JButton("Mostrar Fechados"); btnChamadosFechados.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id " + "left join funcionarios f on ch.chamado_funcionario_id = f.funcionario_id where chamado_status = 'Fechado'"; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } }); btnChamadosFechados.setBounds(376, 381, 141, 23); contentPane.add(btnChamadosFechados); JButton btnTodosChamados = new JButton("Mostrar Todos"); btnTodosChamados.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id left join funcionarios f on" + " ch.chamado_funcionario_id = f.funcionario_id;"; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } }); btnTodosChamados.setBounds(10, 381, 141, 23); contentPane.add(btnTodosChamados); JButton btnVoltar = new JButton("Voltar"); btnVoltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); TelaLogado.frame2.setVisible(true); } }); btnVoltar.setBounds(556, 19, 89, 23); contentPane.add(btnVoltar); JButton btnEditarChamado = new JButton("Visualizar Chamado"); btnEditarChamado.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(table.getSelectedRow()<0){ JOptionPane.showMessageDialog(null,"Cliente não selecionado.","Selecione um cliente na tabela ao lado.",JOptionPane.WARNING_MESSAGE); } else{ TelaChamados.CelulaSelecionada = table.getValueAt(table.getSelectedRow(),0); TelaChamados.CodCliente = CelulaSelecionada.toString(); TelaChamados.StatusChamado=table.getValueAt(table.getSelectedRow(),7).toString(); JOptionPane.showMessageDialog(null,StatusChamado,"Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); new TelaEditarChamado().setVisible(true); } } }); btnEditarChamado.setBounds(163, 19, 162, 23); contentPane.add(btnEditarChamado); JButton btnRelatrioCompleto = new JButton("Relat\u00F3rio Din\u00E2mico"); btnRelatrioCompleto.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new RelatorioChamados().setVisible(true); } }); btnRelatrioCompleto.setBounds(712, 381, 183, 23); contentPane.add(btnRelatrioCompleto); JButton btnPesquisar = new JButton("Pesquisar Chamado"); btnPesquisar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new TelaPesquisaChamado().setVisible(true); } }); btnPesquisar.setBounds(348, 19, 169, 23); contentPane.add(btnPesquisar); } public static void mostraPesquisaCliente(String CodCliente){ Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id left join funcionarios f on" + " ch.chamado_funcionario_id = f.funcionario_id where chamado_cliente_id = "+CodCliente; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } public static void mostraPesquisaChamado(String NumChamado){ Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id left join funcionarios f on" + " ch.chamado_funcionario_id = f.funcionario_id where chamado_id = "+NumChamado; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } } <file_sep>package br.com.desafio.view; import java.awt.BorderLayout; import java.awt.EventQueue; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import com.mysql.jdbc.Connection; import br.com.desafio.model.Clientes; import br.com.desafio.model.ConexaoBanco; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Color; import javax.swing.border.TitledBorder; import javax.swing.border.LineBorder; public class TelaEditarCliente extends JFrame { private JPanel contentPane; private JTextField txtNome; private JTextField txtCpf; private JTextField txtEndereo; private JTextField txtPlano; public static TelaEditarCliente telaEditarCliente = new TelaEditarCliente(); public TelaEditarCliente() { setResizable(false); setTitle("Editar Cliente"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 323, 300); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.setBorder(new LineBorder(Color.WHITE, 4, true)); panel.setBounds(42, 47, 231, 174); contentPane.add(panel); panel.setLayout(null); txtNome = new JTextField(); txtNome.setBounds(100, 11, 86, 20); panel.add(txtNome); txtNome.setText("Nome"); txtNome.setColumns(10); txtCpf = new JTextField(); txtCpf.setBounds(100, 42, 86, 20); panel.add(txtCpf); txtCpf.setText("CPF"); txtCpf.setColumns(10); txtEndereo = new JTextField(); txtEndereo.setBounds(100, 73, 86, 20); panel.add(txtEndereo); txtEndereo.setText("Endere\u00E7o"); txtEndereo.setColumns(10); txtPlano = new JTextField(); txtPlano.setBounds(100, 104, 86, 20); panel.add(txtPlano); txtPlano.setText("Plano"); txtPlano.setColumns(10); JLabel lblNome = new JLabel("Nome:"); lblNome.setBounds(10, 14, 71, 14); panel.add(lblNome); lblNome.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblCpf = new JLabel("CPF:"); lblCpf.setBounds(10, 45, 71, 14); panel.add(lblCpf); lblCpf.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblEndereo = new JLabel("Endere\u00E7o:"); lblEndereo.setBounds(10, 76, 71, 14); panel.add(lblEndereo); lblEndereo.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblPlano = new JLabel("Plano:"); lblPlano.setBounds(10, 107, 71, 14); panel.add(lblPlano); lblPlano.setHorizontalAlignment(SwingConstants.RIGHT); JButton btnSalvar = new JButton("Salvar"); btnSalvar.setBounds(26, 139, 94, 23); panel.add(btnSalvar); JButton btnVoltar = new JButton("Voltar"); btnVoltar.setBounds(130, 139, 89, 23); panel.add(btnVoltar); mostraCliente(txtNome, txtCpf, txtEndereo, txtPlano); btnVoltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnSalvar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String Nome = txtNome.getText().toString(); String CPF = txtCpf.getText().toString(); String Endereco = txtEndereo.getText().toString(); String Plano = txtPlano.getText().toString(); Clientes.editaCliente(Nome, CPF, Endereco, Plano); } }); } public void mostraCliente(JTextField Nome, JTextField CPF, JTextField Endereco, JTextField Plano ){ Connection conn = (Connection) ConexaoBanco.getConnection(); PreparedStatement stmt; try { stmt = conn.prepareStatement(" select cliente_nome, cliente_CPF, cliente_endereco, cliente_plano from clientes where cliente_id = "+TelaClientes.CodCliente); ResultSet rs = stmt.executeQuery(); while (rs.next()) { String nome =rs.getString("cliente_nome"); String cpf = rs.getString("cliente_cpf"); String endereco = rs.getString("cliente_endereco"); String plano = rs.getString("cliente_plano"); Nome.setText(nome); CPF.setText(cpf); Endereco.setText(endereco); Plano.setText(plano); } conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package br.com.desafio.view; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.Color; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.border.TitledBorder; import javax.swing.UIManager; public class TelaLogado extends JFrame { public static TelaLogado frame2 = new TelaLogado(); private JPanel contentPane; public TelaLogado() { setTitle("Menu Principal"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Menu", TitledBorder.CENTER, TitledBorder.ABOVE_TOP, null, new Color(0, 0, 0))); panel.setBounds(124, 44, 196, 185); contentPane.add(panel); panel.setLayout(null); JButton btnClientes = new JButton("Clientes"); btnClientes.setBounds(45, 68, 108, 23); panel.add(btnClientes); JButton btnChamados = new JButton("Chamados"); btnChamados.setBounds(45, 36, 108, 23); panel.add(btnChamados); JButton btnColaboradores = new JButton("Funcion\u00E1rios"); btnColaboradores.setBounds(45, 100, 108, 23); panel.add(btnColaboradores); JButton btnLogoff = new JButton("Logoff"); btnLogoff.setBounds(45, 132, 108, 23); panel.add(btnLogoff); btnLogoff.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new TelaInicial().setVisible(true); } }); btnColaboradores.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new TelaFuncionarios().setVisible(true); } }); btnChamados.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new TelaChamados().setVisible(true); } }); btnClientes.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new TelaClientes().setVisible(true); } }); } } <file_sep>package br.com.desafio.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileOutputStream; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import org.oxbow.swingbits.table.filter.TableRowFilterSupport; import com.lowagie.text.Document; import com.lowagie.text.PageSize; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfWriter; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import br.com.desafio.model.ConexaoBanco; import javax.swing.JLabel; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Shape; import javax.swing.border.TitledBorder; import javax.swing.UIManager; public class RelatorioChamados extends JFrame { private JPanel contentPane; private JTable table; public RelatorioChamados() { setTitle("Relatório de Chamados"); setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 950, 454); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Chamados", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); panel.setBounds(4, 11, 926, 366); contentPane.add(panel); panel.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(6, 16, 914, 339); panel.add(scrollPane); JTable table_1 = new JTable(); table_1.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "N\u00FAmero ", "Cliente", "Tipo", "Respons\u00E1vel", "Data Abertura", "Data Encerramento", "Prioridade", "Status" } )); table = TableRowFilterSupport .forTable(table_1) .searchable(true) .apply(); scrollPane.setViewportView(table); table.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "N\u00FAmero ", "Cliente", "Tipo", "Respons\u00E1vel", "Data Abertura", "Data Encerramento","Prioridade", "Status", } ) { boolean[] columnEditables = new boolean[] { false, true, true, true }; public boolean isCellEditable(int row, int column) { return columnEditables[column]; } }); table.getColumnModel().getColumn(0).setResizable(false); table.setDefaultRenderer(Object.class, new CellRenderer()); table.setRowSelectionAllowed(true); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setBackground(Color.WHITE); JButton btnChamadosAbertos = new JButton("Mostrar Abertos"); btnChamadosAbertos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id " + "left join funcionarios f on ch.chamado_funcionario_id = f.funcionario_id where chamado_status = 'Aberto'"; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } }); btnChamadosAbertos.setBounds(191, 381, 141, 23); contentPane.add(btnChamadosAbertos); JButton btnChamadosFechados = new JButton("Mostrar Fechados"); btnChamadosFechados.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id " + "left join funcionarios f on ch.chamado_funcionario_id = f.funcionario_id where chamado_status = 'Fechado'"; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } }); btnChamadosFechados.setBounds(376, 381, 141, 23); contentPane.add(btnChamadosFechados); JButton btnTodosChamados = new JButton("Mostrar Todos"); btnTodosChamados.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Connection conn = (Connection) ConexaoBanco.getConnection(); String[] tableColumnsName = {"Número", "Cliente", "Tipo", "Responsável", "Data Abertura", "Data Encerramento","Prioridade", "Status"}; DefaultTableModel aModel = (DefaultTableModel) table.getModel(); aModel.setRowCount(0); aModel.setColumnIdentifiers(tableColumnsName); ResultSet rs; Statement st; try { st = (Statement) conn.createStatement(); String SQL = "Select chamado_id, cliente_nome, chamado_tipo, funcionario_nome, chamado_data_abertura, chamado_data_encerramento," + "chamado_prioridade, chamado_status from chamados ch join clientes cl on ch.chamado_cliente_id = cl.cliente_id left join funcionarios f on" + " ch.chamado_funcionario_id = f.funcionario_id;"; rs = st.executeQuery(SQL); java.sql.ResultSetMetaData rsmd = rs.getMetaData(); int colNo = rsmd.getColumnCount(); while(rs.next()){ Object[] objects = new Object[colNo]; for(int i = 0; i < colNo; i++) { objects[i] = rs.getObject(i+1); } aModel.addRow(objects); } table.setModel(aModel); conn.close(); }catch (SQLException ee) { // TODO Auto-generated catch block ee.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conexão, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } } }); btnTodosChamados.setBounds(10, 381, 141, 23); contentPane.add(btnTodosChamados); JButton btnFechar = new JButton("Fechar"); btnFechar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new TelaChamados().setVisible(true); } }); btnFechar.setBounds(705, 381, 141, 23); contentPane.add(btnFechar); } } <file_sep>package br.com.desafio.model; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import br.com.desafio.view.TelaClientes; public class Clientes { private String CodigoCliente; private String nome; private String CPF; private String endereco; private String plano; public String getCodigoCliente() { return CodigoCliente; } public void setCodigoCliente(String codigoCliente) { CodigoCliente = codigoCliente; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCPF() { return CPF; } public void setCPF(String cPF) { CPF = cPF; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getPlano() { return plano; } public void setPlano(String plano) { this.plano = plano; } public static boolean verificarExisteClienteID(String Id){ Connection conn = (Connection) ConexaoBanco.getConnection(); Statement st; if(Id.length()<1){ JOptionPane.showMessageDialog(null,"Campo de cliente vazio.","Erro!",JOptionPane.WARNING_MESSAGE); } else{ try { st = (Statement) conn.createStatement(); String SQL = "Select cliente_id from clientes where cliente_id = "+Id; ResultSet rs = st.executeQuery(SQL); while(rs.next()) { String Id2 = rs.getString("cliente_id"); if(Id2.equals(String.valueOf(Id))){ return true; }else { return false; } } }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conex„o, com o banco de dados!","Erro!",JOptionPane.WARNING_MESSAGE); } } return false; } public static boolean editaCliente(String Nome, String Cpf, String Endereco, String Plano){ Connection conn = (Connection) ConexaoBanco.getConnection(); try { // the mysql insert statement String query = "UPDATE clientes SET cliente_nome = ?, " + " cliente_cpf = ?," + " cliente_endereco = ?," + " cliente_plano = ?" + " WHERE cliente_id = "+TelaClientes.CodCliente; ; // create the mysql insert preparedstatement PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setString (1, Nome); preparedStmt.setString (2, Cpf); preparedStmt.setString (3, Endereco); preparedStmt.setString (4, Plano); // execute the preparedstatement preparedStmt.execute(); conn.close(); JOptionPane.showMessageDialog(null,"Sucesso ","",JOptionPane.INFORMATION_MESSAGE); return true; }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conex„o, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); return false; } } public static boolean deletarCliente(String Id){ Connection conn = (Connection) ConexaoBanco.getConnection(); try { String query = "delete from clientes where cliente_id = ?"; PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setString(1, Id); // execute the preparedstatement preparedStmt.execute(); conn.close(); }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conex„o, com o banco de dados!","Erro!",JOptionPane.WARNING_MESSAGE); } return false; } public static boolean addCliente(String nome, String cpf, String endereco, String plano){ Connection conn = (Connection) ConexaoBanco.getConnection(); try { String query = " insert into clientes (cliente_nome, cliente_cpf, cliente_endereco, cliente_plano)" + " values (?, ?, ?, ?)"; PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setString (1, nome); preparedStmt.setString (2, cpf); preparedStmt.setString (3, endereco); preparedStmt.setString (4, plano); preparedStmt.execute(); conn.close(); }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conex„o, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } return true; } } <file_sep>package br.com.desafio.controller; import br.com.desafio.view.TelaInicial; public class PrincipalController { public static void main(String[] args) { // TODO Auto-generated method stub new TelaInicial().setVisible(true); } } <file_sep>package br.com.desafio.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import com.mysql.jdbc.Connection; import br.com.desafio.model.ConexaoBanco; import br.com.desafio.model.Funcionario; public class TelaEditarFuncionario extends JFrame { private JPanel contentPane; private JTextField txtNomeFunc; private JTextField txtCPFFunc; private JComboBox comboCompetencia; public TelaEditarFuncionario() { setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 355, 281); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.setBorder(new LineBorder(Color.WHITE, 4, true)); panel.setBounds(52, 28, 245, 210); contentPane.add(panel); panel.setLayout(null); JLabel lblNome = new JLabel("Nome:"); lblNome.setBounds(10, 51, 73, 14); panel.add(lblNome); lblNome.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblCompetncia = new JLabel("Compet\u00EAncia:"); lblCompetncia.setBounds(10, 101, 73, 14); panel.add(lblCompetncia); lblCompetncia.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblCpf = new JLabel("CPF:"); lblCpf.setBounds(10, 76, 73, 14); panel.add(lblCpf); lblCpf.setHorizontalAlignment(SwingConstants.RIGHT); txtNomeFunc = new JTextField(); txtNomeFunc.setBounds(93, 48, 125, 20); panel.add(txtNomeFunc); txtNomeFunc.setColumns(10); txtCPFFunc = new JTextField(); txtCPFFunc.setBounds(93, 73, 125, 20); panel.add(txtCPFFunc); txtCPFFunc.setColumns(10); comboCompetencia = new JComboBox(); comboCompetencia.setBounds(93, 98, 125, 20); panel.add(comboCompetencia); comboCompetencia.setModel(new DefaultComboBoxModel(new String[] {"Fone", "Internet", "TV", "Fone/Internet", "Fone/TV", "Internet/TV", "FIT"})); JButton btnIncluir = new JButton("Salvar"); btnIncluir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String Nome = txtNomeFunc.getText().toString(); String CPF = txtCPFFunc.getText().toString(); String Competencia = comboCompetencia.getSelectedItem().toString(); Funcionario.editaFuncionario(Nome, CPF, Competencia); } }); btnIncluir.setBounds(30, 126, 89, 23); panel.add(btnIncluir); mostraFuncionario(txtNomeFunc, txtCPFFunc, comboCompetencia); JButton btnVoltar = new JButton("Cancelar"); btnVoltar.setBounds(129, 126, 89, 23); panel.add(btnVoltar); btnVoltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); } public void mostraFuncionario(JTextField Nome, JTextField CPF, JComboBox Competencia ){ Connection conn = (Connection) ConexaoBanco.getConnection(); PreparedStatement stmt; try { stmt = conn.prepareStatement(" select funcionario_nome, funcionario_CPF, funcionario_competencia from funcionarios where funcionario_id = "+TelaFuncionarios.CodFuncionario); ResultSet rs = stmt.executeQuery(); while (rs.next()) { String nome =rs.getString("funcionario_nome"); String cpf = rs.getString("funcionario_cpf"); String competencia = rs.getString("funcionario_competencia"); Nome.setText(nome); CPF.setText(cpf); Competencia.setSelectedItem(competencia); } conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package br.com.desafio.model; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import br.com.desafio.view.TelaChamados; import br.com.desafio.view.TelaClientes; public class Chamados { String Numero; int ClienteId; String DataAbertura; String Status; String Tipo; String Prioridade; String DataEncerramento; public int getClienteId() { return ClienteId; } public void setClienteId(int clienteId) { ClienteId = clienteId; } public int getFncionarioId() { return FncionarioId; } public void setFncionarioId(int fncionarioId) { FncionarioId = fncionarioId; } public String getDataEncerramento() { return DataEncerramento; } public void setDataEncerramento(String dataEncerramento) { DataEncerramento = dataEncerramento; } int FncionarioId; public String getNumero() { return Numero; } public void setNumero(String numero) { Numero = numero; } public String getDataAbertura() { return DataAbertura; } public void setDataAbertura(String dataAbertura) { DataAbertura = dataAbertura; } public String getStatus() { return Status; } public void setStatus(String status) { Status = status; } public String getTipo() { return Tipo; } public void setTipo(String tipo) { Tipo = tipo; } public String getPrioridade() { return Prioridade; } public void setPrioridade(String prioridade) { Prioridade = prioridade; } public static boolean addChamado(String Tipo, String ClienteId, String DataAbertura, String Prioridade, String Descricao){ Connection conn = (Connection) ConexaoBanco.getConnection(); Boolean result; try { // the mysql insert statement String query = " insert into chamados (chamado_tipo, chamado_cliente_id, chamado_data_abertura, chamado_prioridade, chamado_descricao, chamado_hora_abertura)" + " values (?, ?, ?, ?, ?, now())"; // create the mysql insert preparedstatement PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setString (1, Tipo); preparedStmt.setString (2, ClienteId); preparedStmt.setString (3, DataAbertura); preparedStmt.setString (4, Prioridade); preparedStmt.setString(5, Descricao); // execute the preparedstatement preparedStmt.execute(); conn.close(); result = true; }catch (SQLException e) { result = false; // TODO Auto-generated catch block e.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conex„o, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); } return result; } public static boolean editaChamado(int func_id, String Status){ Connection conn = (Connection) ConexaoBanco.getConnection(); Statement st = null; try { // the mysql insert statement String query = "UPDATE chamados SET chamado_funcionario_id = ?, " + " chamado_status = ?" + " WHERE chamado_id = "+TelaChamados.CodCliente; // create the mysql insert preparedstatement PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setInt (1, func_id); preparedStmt.setString (2, Status); // execute the preparedstatement preparedStmt.execute(); conn.close(); return true; }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conex„o, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); return false; } } public static boolean fecharChamado(int func_id, String Status, String DataEnc){ Connection conn = (Connection) ConexaoBanco.getConnection(); Statement st = null; try { // the mysql insert statement String query = "UPDATE chamados SET chamado_funcionario_id = ?, " + " chamado_status = ?," + " chamado_data_encerramento = ?" + " WHERE chamado_id = "+TelaChamados.CodCliente; // create the mysql insert preparedstatement PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setInt (1, func_id); preparedStmt.setString (2, Status); preparedStmt.setString (3, DataEnc); // execute the preparedstatement preparedStmt.execute(); conn.close(); return true; }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //vejamos que erro foi gerado e quem o gerou JOptionPane.showMessageDialog(null,"Erro na conex„o, com o banco de dados!","Oi. Simples assim!",JOptionPane.WARNING_MESSAGE); return false; } } }
85a47d873cc10d288233a97baeaa44939eb6ba39
[ "Java" ]
10
Java
erride/Desafio
f19f434edeaa952504f488302f53f19483de668a
8a2caf99e04594920eb08416ff6b60b873cd0efd
refs/heads/master
<file_sep>@file:Suppress("unused") package skycap.android.core.view import android.content.Context import android.support.design.widget.TabLayout import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.view.ViewGroup class CenterTabLayout : TabLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { super.onLayout(changed, l, t, r, b) val firstTab = (getChildAt(0) as ViewGroup).getChildAt(0) val lastTab = (getChildAt(0) as ViewGroup).getChildAt((getChildAt(0) as ViewGroup).childCount - 1) ViewCompat.setPaddingRelative( getChildAt(0), width / 2 - firstTab.width / 2, 0, width / 2 - lastTab.width / 2, 0 ) } }<file_sep>@file:JvmName("LiveDataExt") @file:Suppress("unused") package skycap.android.core.livedata import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.LiveData import android.arch.lifecycle.MediatorLiveData import android.arch.lifecycle.Observer import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit fun <T : Any, L : LiveData<T>> observeForever(liveData: L, body: (T?) -> Unit): Observer<T> { val observer = Observer<T>(body) liveData.observeForever(observer) return observer } fun <T : Any, L : LiveData<T>> observeForeverNonNull(liveData: L, body: (T) -> Unit): Observer<T> { val observer = Observer<T> { it?.apply(body) } liveData.observeForever(observer) return observer } fun <T : Any, L : LiveData<T>> LifecycleOwner.observe(liveData: L, body: (T?) -> Unit): Observer<T> { val observer = Observer<T>(body) liveData.observe(this, observer) return observer } fun <T : Any, L : LiveData<T>> LifecycleOwner.observeNonNull(liveData: L, body: (T) -> Unit): Observer<T> { val observer = Observer<T> { it?.apply(body) } liveData.observe(this, observer) return observer } /** * Observe [LiveData] in blocking mode, * Can be used in testing * */ fun <T> LiveData<T>.observeBlocking(count: Int = 1, waitInSeconds: Long = 2): T? { var value: T? = null val latch = CountDownLatch(count) val observer = Observer<T> { t -> value = t latch.countDown() } observeForever(observer) latch.await(waitInSeconds, TimeUnit.SECONDS) return value } fun <T> LiveData<T>.distinct(): LiveData<T> { val distinctLiveData = MediatorLiveData<T>() distinctLiveData.addSource(this, object : Observer<T> { private var lastObj: T? = null override fun onChanged(obj: T?) { if (obj != lastObj) { lastObj = obj distinctLiveData.postValue(lastObj) } } }) return distinctLiveData } <file_sep>@file:Suppress("unused") package skycap.android.core.sharedprefs import android.content.SharedPreferences class SharedPrefsHelper constructor(private val prefs: SharedPreferences) { fun save(key: String, value: Int) { prefs.edit().putInt(key, value).apply() } fun save(key: String, value: String) { prefs.edit().putString(key, value).apply() } fun save(key: String, value: Long) { prefs.edit().putLong(key, value).apply() } fun save(key: String, value: Boolean) { prefs.edit().putBoolean(key, value).apply() } fun saveStringSet(key: String, value: Set<String>) { prefs.edit().putStringSet(key, value).apply() } fun get(key: String, defaultValue: Int): Int { return prefs.getInt(key, defaultValue) } fun getInt(key: String, defaultValue: Int): Int? { return if (prefs.contains(key)) prefs.getInt(key, defaultValue) else null } fun get(key: String, defaultValue: String): String { return prefs.getString(key, defaultValue) ?: defaultValue } fun getString(key: String): String? { return prefs.getString(key, null) } fun get(key: String, defaultValue: Long): Long { return prefs.getLong(key, defaultValue) } fun getLong(key: String): Long? { return if (prefs.contains(key)) { prefs.getLong(key, 0L) } else { null } } fun get(key: String, defaultValue: Boolean): Boolean { return prefs.getBoolean(key, defaultValue) } fun getBoolean(key: String): Boolean? { return if (prefs.contains(key)) { prefs.getBoolean(key, false) } else { null } } fun getStringSet(key: String): Set<String>? { return prefs.getStringSet(key, null) } fun delete(key: String) { prefs.edit().remove(key).apply() } fun deleteAll() { prefs.edit().clear().apply() } fun containsKey(key: String): Boolean { return prefs.contains(key) } } <file_sep># Core Module ## How to add: ### Project's `build.gradle` ```gradle allprojects { repositories { ... maven { url 'https://dl.bintray.com/skycap/skycap-android' } } } ``` ### Module's `build.gradle` ```gradle implementation 'skycap.android:core:1.0.0-alpha11’ ``` ### Other Useful Refererences: Bintray : https://bintray.com/beta/#/skycap/skycap-android?tab=packages<file_sep>@file:JvmName("ViewModelExt") @file:Suppress("unused") package skycap.android.core.viewmodel import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity class BaseViewModelFactory<T>(val creator: () -> T) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>) = creator() as T } inline fun <reified T : ViewModel> Fragment.getViewModel(noinline creator: (() -> T)? = null): T { return if (creator == null) ViewModelProviders.of(this).get(T::class.java) else ViewModelProviders.of(this, BaseViewModelFactory(creator)).get(T::class.java) } inline fun <reified T : ViewModel> FragmentActivity.getViewModel(noinline creator: (() -> T)? = null): T { return if (creator == null) ViewModelProviders.of(this).get(T::class.java) else ViewModelProviders.of(this, BaseViewModelFactory(creator)).get(T::class.java) }<file_sep>@file:Suppress("unused") package skycap.android.core.view import android.animation.Animator import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.support.v4.view.GestureDetectorCompat import android.util.Log import android.view.GestureDetector import android.view.MotionEvent import android.view.View import skycap.android.core.LOG_TAG class PullToZoomListener( context: Context, maxZoomDp: Int, private val mOnZoomChangeListener: OnZoomChangeListener ) : View.OnTouchListener { private val maxZoomDp: Float = maxZoomDp.toFloat() / 100 private val myGestureListener = MyGestureListener() private val mDetector = GestureDetectorCompat(context, myGestureListener) @SuppressLint("ClickableViewAccessibility") override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { if (motionEvent.action == MotionEvent.ACTION_UP) { myGestureListener.upDetected() } return mDetector.onTouchEvent(motionEvent) } private inner class MyGestureListener : GestureDetector.SimpleOnGestureListener() { private var delta: Float = 0f private var valueAnimator: ValueAnimator? = null private var mFirstEvent = true override fun onDown(event: MotionEvent): Boolean = true override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { valueAnimator?.cancel() if (mFirstEvent) { mFirstEvent = false mOnZoomChangeListener.onZoomStart() return false } delta += distanceY val pct = getPct(delta) val pctInto100 = (pct * 100).toInt() Log.d(LOG_TAG, "pctInto100 = $pctInto100") mOnZoomChangeListener.onZoom(pctInto100) return false } fun upDetected() { mFirstEvent = true val pct = getPct(delta) valueAnimator = ValueAnimator().apply { setFloatValues(pct, 0.0f) addUpdateListener { animation -> (animation.animatedValue as? Float)?.also { Log.d(LOG_TAG, "animation.getAnimatedValue() = $animatedValue") val pctInto100 = (it * 100).toInt() Log.d(LOG_TAG, "pctInto100 = $pctInto100") mOnZoomChangeListener.onZoom(pctInto100) } } addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator) { mOnZoomChangeListener.onZoomStart() } override fun onAnimationEnd(animation: Animator) { delta = 0f mOnZoomChangeListener.onZoomEnd() } override fun onAnimationCancel(animation: Animator) {} override fun onAnimationRepeat(animation: Animator) {} }) } valueAnimator?.start() } private fun getPct(delta: Float): Float { var pct = -delta / PCT if (pct >= maxZoomDp) { pct = maxZoomDp } else if (pct <= 0) { pct = 0f } return pct } } interface OnZoomChangeListener { fun onZoomStart() fun onZoomEnd() fun onZoom(level: Int) } companion object { private const val PCT = 300f } }<file_sep>@file:JvmName("DisplayExt") @file:Suppress("unused") package skycap.android.core.device import android.content.Context import android.util.DisplayMetrics fun Context.getScreenHeightInPixels(): Float { return resources.displayMetrics.heightPixels.toFloat() } fun Context.getScreenWidthInPixels(): Float { return resources.displayMetrics.widthPixels.toFloat() } fun Context.getScreenHeightInDp(): Float { val displayMetrics = resources.displayMetrics return displayMetrics.heightPixels / displayMetrics.density } fun Context.getScreenWidthInDp(): Float { val displayMetrics = resources.displayMetrics return displayMetrics.widthPixels / displayMetrics.density } fun Context.getPixels(dp: Float): Float { val metrics = resources.displayMetrics return dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) } fun Context.getDp(px: Float): Float { val metrics = resources.displayMetrics return px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) } <file_sep>@file:JvmName("IntentExt") @file:Suppress("unused") package skycap.android.core import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Settings fun Context.intentToShowAppSettings() { val intent = Intent() intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS val uri = Uri.fromParts("package", packageName, null) intent.data = uri startActivity(intent) } fun Context.intentToWatchYoutubeVideo(videoId: String): Boolean { val appIntent = Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:$videoId")) val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=$videoId")) return try { startActivity(appIntent) true } catch (e: Exception) { e.printStackTrace() try { startActivity(webIntent) true } catch (e: Exception) { e.printStackTrace() false } } } fun Context.intentToOpenUrl(url: String): Boolean { return try { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) startActivity(intent) true } catch (e: Exception) { e.printStackTrace() false } } fun Context.intentToShareTextOnWhatsApp(message: String): Boolean { return try { val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(Intent.EXTRA_TEXT, message) sendIntent.type = "text/plain" sendIntent.`package` = "com.whatsapp" startActivity(sendIntent) true } catch (e: Exception) { e.printStackTrace() false } } fun Context.intentToShareText(text: String): Boolean { return try { val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(Intent.EXTRA_TEXT, text) sendIntent.type = "text/plain" startActivity(sendIntent) true } catch (e: Exception) { e.printStackTrace() false } } <file_sep>@file:Suppress("unused") package skycap.android.core.view import android.content.Context import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.MotionEvent import skycap.android.core.R class SwipeViewPager(context: Context, attrs: AttributeSet) : ViewPager(context, attrs) { var swipeEnabled: Boolean = false init { val a = context.obtainStyledAttributes(attrs, R.styleable.SwipeViewPager) try { swipeEnabled = a.getBoolean(R.styleable.SwipeViewPager_enableSwipe, true) } finally { a.recycle() } } override fun onInterceptTouchEvent(event: MotionEvent): Boolean = swipeEnabled && super.onInterceptTouchEvent(event) override fun onTouchEvent(event: MotionEvent): Boolean = swipeEnabled && super.onTouchEvent(event) } <file_sep>@file:Suppress("unused") package skycap.android.core.resource sealed class Resource<out T> { class Loading<T> : Resource<T>() data class Success<T>(val value: T) : Resource<T>() data class Error<T>(val code: Int) : Resource<T>() val isLoading: Boolean get() = this is Resource.Loading val isSuccess: Boolean get() = this is Resource.Success val isError: Boolean get() = this is Resource.Error companion object { fun <T> loading() = Resource.Loading<T>() fun <T> success(value: T) = Resource.Success(value) fun <T> error(code: Int) = Resource.Error<T>(code) } }<file_sep>@file:Suppress("unused") package skycap.android.core.encrypt import android.util.Base64 import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec class EncryptHelper(secret: String, iv: String, private val flags: Int = Base64.NO_PADDING) { private val secretKey = SecretKeySpec(secret.toByteArray(Charsets.UTF_8), "AES") private val cipher = Cipher.getInstance("AES/CBC/NoPadding") private val ivParameterSpec = IvParameterSpec(iv.toByteArray(Charsets.UTF_8)) fun encrypt(string: String): String? { try { cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec) // convert to bytes var bytes: ByteArray = string.toByteArray(Charsets.UTF_8) // encrypt bytes bytes = cipher.doFinal(bytes) // encode bytes bytes = Base64.encode(bytes, flags) return String(bytes, Charsets.UTF_8) } catch (throwable: Throwable) { throwable.printStackTrace() return null } } fun decrypt(string: String): String? { try { cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec) // convert to bytes var bytes: ByteArray = string.toByteArray(Charsets.UTF_8) // decode Base64 bytes bytes = Base64.decode(bytes, flags) // decrypt Base64 bytes bytes = cipher.doFinal(bytes) return String(bytes, Charsets.UTF_8) } catch (throwable: Throwable) { throwable.printStackTrace() return string } } }<file_sep>@file:JvmName("AnyExt") @file:Suppress("unused") package skycap.android.core val Any.LOG_TAG: String get() = this.javaClass.simpleName<file_sep>@file:Suppress("unused") package skycap.android.core.net object UrlHelper { fun getYouTubeVideoThumbnailUrl(videoId: String): String { return "http://img.youtube.com/vi/$videoId/0.jpg" } }<file_sep>@file:Suppress("unused") package skycap.android.core.device import android.annotation.SuppressLint import android.content.Context import android.provider.Settings class DeviceIdHelper(context: Context) { @SuppressLint("HardwareIds") private val uuid: String = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) fun getDeviceId(): String { return uuid } }<file_sep>@file:Suppress("unused") package skycap.android.core.gson import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.TypeAdapterFactory import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.io.IOException /** * Parse and return data using gson * Skip value if there is any error in parsing */ class LenientTypeAdapterFactory : TypeAdapterFactory { override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T> { val delegate = gson.getDelegateAdapter(this, type) return object : TypeAdapter<T>() { @Throws(IOException::class) override fun write(out: JsonWriter, value: T) { delegate.write(out, value) } @Throws(IOException::class) override fun read(reader: JsonReader): T? { return try { //Here is the magic //Try to read value using default TypeAdapter delegate.read(reader) } catch (e: Throwable) { //If we can't in case when we expecting to have an object but array is received // (or some other unexpected stuff), we just skip this value in reader and return null reader.skipValue() null } } } } } <file_sep>@file:JvmName("IntExt") @file:Suppress("unused") package skycap.android.core /** * Convert integer value to boolean * */ fun Int.boolValue(): Boolean = this > 0 <file_sep>@file:JvmName("ViewExt") @file:Suppress("unused") package skycap.android.core.view import android.view.View fun View.setVisibleOrGone(visibility: Boolean?) { val visible = if (visibility == true) View.VISIBLE else View.GONE this.visibility = visible } fun View.setVisibleOrInvisible(visibility: Boolean?) { val visible = if (visibility == true) View.VISIBLE else View.INVISIBLE this.visibility = visible } <file_sep>package skycap.android.sample import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Button import skycap.android.core.view.setVisibleOrGone class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<Button>(R.id.showHideButton).setVisibleOrGone(true) } } <file_sep>apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'com.jfrog.bintray' apply plugin: 'com.github.dcendents.android-maven' android { compileSdkVersion rootProject.compileSdkVersion defaultConfig { versionCode versionCode versionName versionName minSdkVersion rootProject.minSdkVersion targetSdkVersion rootProject.targetSdkVersion testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } publishNonDefault true } dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$rootProject.kotlinVersion" implementation "com.android.support:appcompat-v7:$rootProject.supportLibVersion" implementation "com.android.support:support-v4:$rootProject.supportLibVersion" implementation "com.android.support:design:$rootProject.supportLibVersion" implementation "android.arch.lifecycle:extensions:$rootProject.lifecycleVersion" implementation 'com.google.code.gson:gson:2.8.5' } apply from: 'jcenterConfig.gradle'<file_sep>@file:JvmName("BooleanExt") @file:Suppress("unused") package skycap.android.core /** * Convert boolean value to integer * */ fun Boolean.intValue(): Int = if (this) 1 else 0 <file_sep>@file:Suppress("unused") package skycap.android.core.view import android.content.Context import android.view.GestureDetector import android.view.MotionEvent import android.view.View class OnSwipeTouchListener(context: Context) : View.OnTouchListener { private val gestureDetector: GestureDetector private lateinit var view: View init { gestureDetector = GestureDetector(context, GestureListener()) } fun onSwipeLeft(view: View) {} fun onSwipeRight(view: View) {} override fun onTouch(v: View, event: MotionEvent): Boolean { view = v return gestureDetector.onTouchEvent(event) } private inner class GestureListener : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent): Boolean = true override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { val distanceX = e2.x - e1.x val distanceY = e2.y - e1.y if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (distanceX > 0) onSwipeRight(view) else onSwipeLeft(view) return true } return false } } companion object { private const val SWIPE_DISTANCE_THRESHOLD = 100 private const val SWIPE_VELOCITY_THRESHOLD = 100 } }<file_sep>@file:JvmName("SpannableExt") @file:Suppress("unused") package skycap.android.core.text import android.graphics.Typeface import android.text.Spannable import android.text.SpannableString import android.text.TextUtils import android.text.style.* /** * this way it possible to nest spans * spannable { * italic(underline(bold(size(2f, color(Color.RED, "Red Bold Color"))))) * } * */ fun spannable(func: () -> SpannableString) = func() private fun span(s: CharSequence, o: Any): SpannableString { val spannableString = if (s is String) { SpannableString(s) } else { s as? SpannableString ?: SpannableString("") } spannableString.setSpan(o, 0, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) return spannableString } operator fun SpannableString.plus(s: SpannableString) = SpannableString(TextUtils.concat(this, s)) operator fun SpannableString.plus(s: String) = SpannableString(TextUtils.concat(this, s)) fun bold(s: CharSequence) = span(s, StyleSpan(Typeface.BOLD)) fun bold(s: SpannableString) = span(s, StyleSpan(Typeface.BOLD)) fun italic(s: CharSequence) = span(s, StyleSpan(Typeface.ITALIC)) fun italic(s: SpannableString) = span(s, StyleSpan(Typeface.ITALIC)) fun underline(s: CharSequence) = span(s, UnderlineSpan()) fun underline(s: SpannableString) = span(s, UnderlineSpan()) fun strike(s: CharSequence) = span(s, StrikethroughSpan()) fun strike(s: SpannableString) = span(s, StrikethroughSpan()) fun sup(s: CharSequence) = span(s, SuperscriptSpan()) fun sup(s: SpannableString) = span(s, SuperscriptSpan()) fun sub(s: CharSequence) = span(s, SubscriptSpan()) fun sub(s: SpannableString) = span(s, SubscriptSpan()) fun size(size: Float, s: CharSequence) = span(s, RelativeSizeSpan(size)) fun size(size: Float, s: SpannableString) = span(s, RelativeSizeSpan(size)) fun color(color: Int, s: CharSequence) = span(s, ForegroundColorSpan(color)) fun color(color: Int, s: SpannableString) = span(s, ForegroundColorSpan(color)) fun background(color: Int, s: CharSequence) = span(s, BackgroundColorSpan(color)) fun background(color: Int, s: SpannableString) = span(s, BackgroundColorSpan(color)) fun url(url: String, s: CharSequence) = span(s, URLSpan(url)) fun url(url: String, s: SpannableString) = span(s, URLSpan(url)) fun normal(s: CharSequence) = span(s, SpannableString(s)) fun normal(s: SpannableString) = span(s, SpannableString(s))
5c9e2e1bd833b3c40540e0f20b949c9b18ce6bb3
[ "Markdown", "Kotlin", "Gradle" ]
22
Kotlin
hemantskycap/skycap-android
55e32830006cf446e70df31dfee56c076e59eff1
ad9e8db97a04334246cc66e0acc912f7bcf53c73
refs/heads/main
<repo_name>HyenSeoHWang/mysite<file_sep>/pybo/admin.py ''' * 장고 관리자 기능 URL * https://docs.djangoproject.com/en/3.0/ref/contrib/admin/ ''' from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): search_fields = ['subject', 'content'] admin.site.register(Question, QuestionAdmin) <file_sep>/pybo/__init__.py ''' * http 404 오류 * =>브라우저가 요청한 페이지를 찾을수 없을때 나타나는 오류이다 '''<file_sep>/pybo/urls.py from django.urls import path from . import views app_name = 'pybo' urlpatterns = [ path('',views.index , name = 'index'),#config.urls 에서 받은 호출 이후 veiws.index 호출한다 #path 함수의 인자가 ''인 이유는 이미 config.urls에서 매핑을 받았기때문이다. 그러니까 최종적으로 호출된 URL은 #pybo/ /이다.pybo.urls 에서는 ''을 매핑한것이기 때문이다. 만약 ''가 아닌 'create'을 코딩한다면 최종 URL은 /pybo/create/가 되는것이다 #3번째 인수 : http://localhost:8000/pybo/라는 URL에는 'index'라는 이름을 부여했다 path('<int:question_id>/', views.detail, name = 'detail'), path('answer/create/<int:question_id>/', views.answer_create, name='answer_create'), path('question/create/', views.question_create, name='question_create'), ]<file_sep>/pybo/views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Question, Answer from django.utils import timezone from .forms import QuestionForm, AnswerForm def index(request): ''' pybo 질문 목록 출력 ''' #Question(models에 존재하는 클래스)의 objects(객체)를 생성날짜의 역순(최신순)으로 정렬해라 question_list = Question.objects.order_by('-create_date')#order_by는 조회결과를 정렬하는 함수, -create_date 생성날짜를 역순으로 정렬 context = {'question_list' : question_list} return render(request, 'pybo/question_list.html', context)#즉,위에서 사용한 render 함수는 question_list 데이터를 pybo/question_list.html 파일에 적용하여 HTML을 리턴한다. #render함수의 context 인수는 템플릿에 표시 할 변수를 제공한다. 즉, 여기서는 question_list.html에서 사용할 question_list를 엑세스했음 def detail(request, question_id): ''' pybo 질문 내용 출력 ''' question = get_object_or_404(Question, pk =question_id) context = {'question' : question} return render(request, 'pybo/question_detail.html', context) def answer_create(request, question_id): """ pybo 답변등록 """ question = get_object_or_404(Question, pk=question_id) if request.method == "POST": form = AnswerForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.create_date = timezone.now() answer.question = question answer.save() return redirect('pybo:detail', question_id=question.id) else: form = AnswerForm() context = {'question': question, 'form': form} return render(request, 'pybo/question_detail.html', context) def question_create(request): ''' pybo 질문등록 ''' if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.create_date = timezone.now() question.save() return redirect('pybo:index') else: form = QuestionForm() context = {'form': form} return render(request, 'pybo/question_form.html', context)<file_sep>/config/urls.py """config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ #url.py는 브라우저가 페이지요청을 받았을때 가장 먼저 호출되는 파일이다. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('pybo/', include('pybo.urls')),#pybo/ 라는 url이 요청되면, include('pybo.urls')를 호출하라는 내용이다. #이곳은 최종url이기 때문에 pybo라는 앱의 urls을 불러오기 위해 include 기능을 사용한것이다. =>즉, pybo/를 요청 받으면 pybo.urls로 매핑! ]<file_sep>/pybo/models.py ''' *장고에서 사용하는 속성(Field)타입들 https://docs.djangoproject.com/en/3.0/ref/models/fields/#field-types * models.py는 데이터베이스를 처리하기 위한 파일이다. * SQL쿼리문을 이용해야하지만 장고를 통해 SQL문을 작성하지 않아도 가능하다. * 데이터베이스 모델을 작성할때에는 데이터베이스 모델의 속성을 잘 파악해야한다. * 데이터베이스에서 데이터를 저장하기 위한 데이터 집합의 모임을 '테이블'이라한다 * 테이블을 생성하기위해서는 pybo 라는 앱을 setting.py에 등록해야한다 * 파이썬 shell에서 데이터를 조회하는 방법이 담긴 URL : https://docs.djangoproject.com/en/3.0/topics/db/queries/ ''' from django.db import models class Question(models.Model):#Question 이라는 Database 공간을 만듦으로 이해 subject = models.CharField(max_length=200)#CharFiled =>글자수제한이 있는 텍스트를 받는 field content = models.TextField()#TextFeild =>글자수 제한이 없는 텍스트를 받는 field create_date = models.DateField()#DateFeild =>날짜와 시간에 관계된 속성을 받는 field def __str__(self): #파이썬 shell에서 등록된 질문을 조회할때 id(=pk)가 아닌 subject내용으로 나오게하는 함수 return self.subject class Answer(models.Model):#Anser 모델은 질문에 대한 답이기 때문에 Question모델의 속성을 가져와야한다 question = models.ForeignKey(Question, on_delete=models.CASCADE)#ForeignKey => 기존모델의 속성으로 연결을받는 field #on_delete=models.CASCADE의 의미는 이 답변과 연결된 질문(Question)이 삭제될 경우 답변(Answer)도 함께 삭제된다는 의미이다. content = models.TextField() create_date = models.DateTimeField()
c8e7c472e637ae781caa9d9e84955051f2e1d5c6
[ "Python" ]
6
Python
HyenSeoHWang/mysite
c809b19b3c72e54222876659dd15e71e5b217fbf
30ddd53b3e4f1cdc6ad2eb2fc0ff51eae40c8cf4
refs/heads/master
<file_sep># article-vue-app Простое приложение на vue, позволяющее "авторизироваться", "зарегистрироваться", и в зависимости от авторизации видеть некоторые изменения в приложении и оставлять комментарии ## Команды Прежде всего нужно сделать npm install npm run build - сборка приложения в папку dist npm run serve - запуск приложения в live-reload на webpack-dev-server <file_sep>import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const Store = new Vuex.Store({ state: { username: '', password: '', isAuth: false, comments: [], }, mutations: { signIn(state, user) { this.state.username = user.username this.state.password = <PASSWORD> this.state.isAuth = true }, setComments(state, comments) { this.state.comments = comments }, addComment(state, comment) { this.state.comments.push({ id: this.state.comments.length, user: comment.user, text: comment.text, date: comment.date, }) }, }, }) <file_sep>import Vue from 'vue' import VueRouter from 'vue-router' import Main from './components/Main.vue' import Article from './components/Article.vue' Vue.use(VueRouter) export const Router = new VueRouter({ routes: [ { path: '/', component: Main }, { path: '/article', component: Article }, ], })
3e63e6c21bfee2f7a794374844c9c22c6382ccdc
[ "Markdown", "JavaScript" ]
3
Markdown
megFree/article-vue-app
c65394e2c4f6877b07b82ea16fd787a33012f71b
aa4d464e4a2f571f4f2e703037682083a23a6208
refs/heads/master
<repo_name>reusee/fastcdc-go<file_sep>/go.mod module github.com/reusee/fastcdc-go go 1.14 <file_sep>/fastcdc_example_test.go package fastcdc_test import ( "bytes" "crypto/md5" "fmt" "io" "log" "math/rand" "github.com/reusee/fastcdc-go" ) func Example_basic() { data := make([]byte, 10*1024*1024) rand.Seed(4542) rand.Read(data) rd := bytes.NewReader(data) chunker, err := fastcdc.NewChunker(rd, fastcdc.Options{ AverageSize: 1024 * 1024, // target 1 MiB average chunk size }) if err != nil { log.Fatal(err) } fmt.Printf("%-32s %s\n", "CHECKSUM", "CHUNK SIZE") for { chunk, err := chunker.Next() if err == io.EOF { break } if err != nil { log.Fatal(err) } fmt.Printf("%x %d\n", md5.Sum(chunk.Data), chunk.Length) } // Output: // CHECKSUM CHUNK SIZE // dee6e6c5cff96b97879c8ccc3a0816c4 1073134 // febbb26d9293e4f7bbbd2690a2689bb0 1475338 // f749cff5958a66592ae9a5e1040da2e0 733274 // 1a111ef81439612d5ea511012fc53a99 1431958 // 7d37d2aec1ce28f52a09a74c3a6afb3c 1108001 // 045020dd21550af5c3494aab873b865e 901625 // ed746b6c49369f31db6fe01f783abbbc 1433591 // 666bdd16f26cc78fe682a124be777161 1230739 // 044df6a4f25c7817f420e12939db71cf 1098100 }
010ee93aef6a3e7e1dd8796fa03c1e722843371c
[ "Go", "Go Module" ]
2
Go Module
reusee/fastcdc-go
1756352c2ae739672d1c9e63258fd9e1dbc84814
8a653b8103a5c2f523102739942114b15a1d2632
refs/heads/master
<repo_name>amol-deshmukh/chatApp<file_sep>/app/src/main/java/com/example/hp/chatapplication/LoginActivity.java package com.example.hp.chatapplication; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; /** * Created by HP on 26-03-2018. */ public class LoginActivity extends AppCompatActivity implements View.OnClickListener { private EditText loginEmail; private EditText loginPass; private FirebaseAuth mAuth; private DatabaseReference mDatabase; private TextView txtRegisterHere; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); loginEmail =(EditText)findViewById(R.id.loginEmail); loginPass=(EditText)findViewById(R.id.loginPass); txtRegisterHere=findViewById(R.id.txtRegisterHere); mAuth=FirebaseAuth.getInstance(); mDatabase= FirebaseDatabase.getInstance().getReference().child("Users"); txtRegisterHere.setOnClickListener(this); } public void loginButtonClicked(View view){ String email =loginEmail.getText().toString().trim(); String password =loginPass.getText().toString().trim(); if (!TextUtils.isEmpty(email)&&!TextUtils.isEmpty(password)){ mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ CheckUserExists(); } } }); } } public void CheckUserExists(){ final String user_id=mAuth.getCurrentUser().getUid(); mDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(user_id)){ Intent loginIntent=new Intent(LoginActivity.this,MainActivity.class); startActivity(loginIntent); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.txtRegisterHere: Intent gotoRegisterIntent = new Intent(LoginActivity.this, RegistrationActivity.class); startActivity(gotoRegisterIntent); break; } } } <file_sep>/app/src/main/java/com/example/hp/chatapplication/HomeActivity.java package com.example.hp.chatapplication; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; /** * Created by <NAME> on 29/4/18. */ public class HomeActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_home); Log.v("@@@@","HomeActivity called"); // TODO check if user is already signed in if (!TextUtils.isEmpty(ChatPreferenceManager.instance(this).getUserName())){ //username is present // Do what ever you want Toast.makeText(getApplicationContext(),"User is laready signed in",Toast.LENGTH_LONG).show(); }else { //User is not signed in // navigate to signin page Intent loginIntent=new Intent(HomeActivity.this,LoginActivity.class); startActivity(loginIntent); } } }
0c880f9937e704b4cf38bcd54266907937cc3b14
[ "Java" ]
2
Java
amol-deshmukh/chatApp
3c99ba82b669478ce8ae5da5d82a402e40d1c98c
1a612899df93b27482050fa3a42da39f01b8687c
refs/heads/master
<repo_name>mattisss1/tillampadProg<file_sep>/GameObject.java package workspace; import java.awt.Graphics; import java.awt.Rectangle; public abstract class GameObject { protected static int x; protected static int y; protected ID id; public GameObject(int x, int y, ID id) { GameObject.x = x; GameObject.y = y; this.id = id; } public abstract void tick(); public abstract void render(Graphics g); public abstract Rectangle getBounds(); public void setX (int x) { GameObject.x = x; } public void setY (int y) { GameObject.y = y; } public void setId (ID id) { this.id = id; } public static int getX() { return x; } public static int getY() { return y; } public ID getId() { return id; } } <file_sep>/ListenMouse.java package workspace; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class ListenMouse implements MouseListener { public static int score; public static int miss; public ListenMouse(int score, int miss) { this.score = score; this.miss = miss; } public void mousePressed(MouseEvent e) { int x = GameObject.getX(); int y = GameObject.getY(); int mouseX = e.getX(); int mouseY = e.getY(); if((mouseX <= x+32 && mouseX >= x) && (mouseY <= y+32 && mouseY >= y )) { setScore(getScore()+1); System.out.println("HIT!"); }else { setMiss(getMiss()+1); System.out.println("MISS " + getMiss()); } } public void setScore(int score) { this.score = score; } public int getScore() { return score; } public void setMiss(int miss) { this.miss = miss; } public int getMiss() { return miss; } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } } <file_sep>/README.md # tillampadProg Jag ska göra ett spel i Java Spelet går ut på att en poisition i rutan kommer att lysa upp, användaren ska klicka på positionen med musen. Efter det kommer det det lysa upp på något annat ställe i rutan och spelaren ska fortsätta tills de missar eller tiden går ut Jag ska använda mig av Java.awt.Canvas och Graphics för att göra rutan och vad som visas i rutan. Jag gör detta för att lära mig mer om java och spel-utveckling. Tar hjälp av online sökningar och youtube tutorials för att bygga detta programmet.
c14cbe06a88f87762ca614a9719f8ff4483365d7
[ "Markdown", "Java" ]
3
Java
mattisss1/tillampadProg
78cf85f5f4359d32081ab3754b030258ef305c00
cfac98fb8bbc598216fec1a7bdc0af91740d2402
refs/heads/main
<repo_name>Ivan5Hernandez/iFuel<file_sep>/calculator.js $(document).ready(function(){ var button = $('#doCalculation'); var resetCalc = $('#resetResults'); var resetInput = $('#resetInputs'); // only allow input of minute OR laps, not both $('#raceDuration').on('change keyup', function() { if ($('#raceDuration').val() != '') { $('#raceLaps').val(''); } }); $('#raceLaps').on('change keyup', function() { if ($('#raceLaps').val() != '') { $('#raceDuration').val(''); } }); // remove error-class $('#minutes, #seconds, #milliseconds, #fuel').on('change keyup', function() { $(this).removeClass('fault'); }); $('#raceDuration, #raceLaps').on('change keyup', function() { $('#raceDuration, #raceLaps').removeClass('fault'); }); button.on("click", function(){ // set inputError false before validation inputError = false; // clear fields if there already was a Calculation $('#timeRace').val(''); $('#lapsRace').val(''); $('#neededFuel').val(''); // show error if missing inputs if ($('#seconds').val() == '') { $('#seconds').addClass('fault'); inputError = true; }; if ($('#fuel').val() == '') { $('#fuel').addClass('fault'); inputError = true; }; if ($('#raceDuration').val() == '' && $('#raceLaps').val() == '') { $('#raceDuration').addClass('fault'); $('#raceLaps').addClass('fault'); inputError = true; }; // Alert user if inputs are missing or wrong if(inputError) { alert('Missing or wrong inputs!'); return; }; // Set milliseconds to 000 if no value is entered if ($('#milliseconds').val() == '') { $('#milliseconds').val('000'); }; // fetch inputs var minutesInput = parseFloat($('#minutes').val()); var secondsInput = parseFloat($('#seconds').val()); var milsecInput = parseFloat($('#milliseconds').val()); var lengthInput = parseFloat($('#raceDuration').val()); var lapsInput = parseFloat($('#raceLaps').val()); var fuelInput = parseFloat($('#fuel').val()); // set 0 minutes if no value is entered, so value != null if ($('#minutes').val() == '') { var minutesInput = 0; }; // convert minutes and seconds to milliseconds var min = minutesInput * 60 * 1000; var sec = secondsInput * 1000; if ($('#raceLaps').val() != '') { // calculate total time in milliseconds for fixed laps race var totalTimeLaps = (min + sec + milsecInput) * lapsInput; // convert into est. duration var ms = totalTimeLaps % 1000; var s = ((totalTimeLaps - ms) / 1000) % 60; var m = (((totalTimeLaps - ms) / 1000) - s) / 60; // calculate needed fuel var fuel = fuelInput * lapsInput; // fill fields $('#timeRace').val(m + ':' + String("0" + s).slice(-2) + '.' + ms); $('#lapsRace').val(lapsInput + ' laps'); $('#neededFuel').val(fuel.toFixed(2) + ' litres/gallons/kg'); // alert('laps'); }else{ // convert single lap and total time to milliseconds var timeSingleLap = (min + sec + milsecInput); var timeCompleteRace = lengthInput * 60 * 1000; // count laps var totalLaps = timeCompleteRace / timeSingleLap; // calculate duration in milliseconds var totalDuration = (Math.ceil(totalLaps.toFixed(2))) * timeSingleLap var ms = totalDuration % 1000; var s = ((totalDuration - ms) / 1000) % 60; var m = (((totalDuration - ms) / 1000) - s) / 60; // calculate needed fuel var fuel = fuelInput * (Math.ceil(totalLaps.toFixed(2))); // fill fields $('#timeRace').val(m + ':' + String("0" + s).slice(-2) + '.' + ms); $('#lapsRace').val(Math.ceil(totalLaps.toFixed(2)) + ' laps'); $('#neededFuel').val(fuel.toFixed(2) + ' litres/gallons/kg'); // alert('time'); }; }); // reset results resetCalc.on("click", function(){ $('#timeRace').val(''); $('#lapsRace').val(''); $('#neededFuel').val(''); }); // reset inputs resetInput.on("click", function(){ $('#minutes').val(''); $('#seconds').val(''); $('#milliseconds').val(''); $('#raceDuration').val(''); $('#raceLaps').val(''); $('#fuel').val(''); }); }); <file_sep>/units.js $(document).ready(function(){ // PSI -> KPA $('#psiInput').on('change keyup', function() { var psi = parseFloat($('#psiInput').val()); if ($('#psiInput').val() == '') { $('#kpaOutput').val('') }else{ $('#kpaOutput').val((psi * 6.89475729).toFixed(1)); } }); // KPA -> PSI $('#kpaInput').on('change keyup', function() { var kpa = parseFloat($('#kpaInput').val()); if ($('#kpaInput').val() == '') { $('#psiOutput').val('') }else{ $('#psiOutput').val((kpa / 6.89475729).toFixed(1)); } }); // KPH -> MPH $('#kphInput').on('change keyup', function() { var kph = parseFloat($('#kphInput').val()); if ($('#kphInput').val() == '') { $('#mphOutput').val('') }else{ $('#mphOutput').val((kph * 0.625).toFixed(1)); } }); // MPH -> KPH $('#mphInput').on('change keyup', function() { var mph = parseFloat($('#mphInput').val()); if ($('#mphInput').val() == '') { $('#kphOutput').val('') }else{ $('#kphOutput').val((mph / 0.625).toFixed(1)); } }); // litres -> gals $('#litreInput').on('change keyup', function() { var litre = parseFloat($('#litreInput').val()); if ($('#litreInput').val() == '') { $('#galsOutput').val('') }else{ $('#galsOutput').val((litre / 3.78541).toFixed(1)); } }); // gals -> litres $('#galsInput').on('change keyup', function() { var gals = parseFloat($('#galsInput').val()); if ($('#galsInput').val() == '') { $('#litreOutput').val('') }else{ $('#litreOutput').val((gals * 3.78541).toFixed(1)); } }); });
7b2bc95a10f9e964807f542fdcbb7cdc10c78604
[ "JavaScript" ]
2
JavaScript
Ivan5Hernandez/iFuel
ea5e046b2787bf99ddb27d341fb624e4329b5d98
ee455c1e866ae8f79b2fe4ad28ba9bbcd92fd626
refs/heads/master
<repo_name>PC-Ascend-Team/MasterController<file_sep>/MasterController.ino #include <Wire.h> #include <Adafruit_GPS.h> #include <SoftwareSerial.h> SoftwareSerial sSerialGPS(11, 12); Adafruit_GPS GPS(&sSerialGPS); #define GPSECHO false boolean usingInterrupt = false; void useInterrupt(boolean); void altDetect(float oldAlt, float alt, int altBreakPoint[]); String message = ""; boolean sent = false; int altBreakPoint[5] = {0, 0, 0, 0, 0}; float gpsAlt[5] = {0.0, 0.0, 0.0, 0.0, 0.0}; int offset = 0; int abpOffset = 0; // for finding the altBreakPoint float oldAlt, alt; boolean falling = false; boolean forOldAlt = true; boolean checkAlt = false; char sampleCode = '\0'; boolean sampled = false; char rbStatus = false; int rbTransmissions, rbRecives; void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(115200); Wire.begin(); GPS.begin(9600); GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); GPS.sendCommand(PGCMD_ANTENNA); useInterrupt(true); delay(1000); sSerialGPS.println(PMTK_Q_RELEASE); } SIGNAL(TIMER0_COMPA_vect) { char c = GPS.read(); #ifdef UDR0 if (GPSECHO) if (c) UDR0 = c; #endif } void useInterrupt(boolean v) { if (v) { OCR0A = 0xAF; TIMSK0 |= _BV(OCIE0A); usingInterrupt = true; } else { TIMSK0 &= ~_BV(OCIE0A); usingInterrupt = false; } } void loop() { int t = millis(); if (GPS.newNMEAreceived()) { if (!GPS.parse(GPS.lastNMEA())) return; } if(GPS.fix) { Serial.println("Fix Found"); if((millis() / 1000) % 30 == 0) { Wire.beginTransmission(8); Wire.write("LAT: "); message.remove(0); // clear message message += GPS.latitudeDegrees; Wire.write(message.c_str()); Wire.write(", "); Wire.write("LON: "); message.remove(0); // clear message message += GPS.longitudeDegrees; Wire.write(message.c_str()); Wire.write(", "); Wire.write("FLIGHT STAGE: "); Wire.write((falling)? "DESC, " : "ASC, "); Wire.write("AS STAGE: "); Wire.write(sampleCode); Wire.write(", "); Wire.write("AS STATUS: "); Wire.write((sampled)? "COMPLETE" : "SAMPLING"); Wire.write('\0'); Wire.endTransmission(); } // for Altitude Average if((millis() / 1000) % 2) { if(offset < 5) { gpsAlt[offset] = GPS.altitude; offset++; } else { // i.e. offset is 5 float total = 0; for(int i = 0; i < 5; i++) { total += gpsAlt[i]; } float average = total / 5.0; if(!falling) { // get ready to call altDetect if(forOldAlt) { oldAlt = average; forOldAlt = false; } else { //i.e. for alt alt = average; forOldAlt = true; checkAlt = true; } // call altDetect if(checkAlt) { altDetect(oldAlt, alt, altBreakPoint); checkAlt = false; } } else { if(average < altBreakPoint[abpOffset]) { char sampleCode = '0' + abpOffset; Wire.beginTransmission(9); Wire.write(sampleCode); Wire.endTransmission(); abpOffset++; } } } } } else { } Wire.requestFrom(8, 3); while(Wire.available()) { rbStatus = Wire.read(); rbTransmissions = Wire.read(); rbRecives = Wire.read(); } Wire.requestFrom(9, 2); while(Wire.available()) { sampleCode = Wire.read(); sampled = Wire.read(); } Serial.print(rbStatus); Serial.print(sampleCode); Serial.println(sampled); t = millis() - t; Serial.print("Loop Time: "); Serial.print(t); Serial.println("ms"); delay(1000); digitalWrite(LED_BUILTIN, (digitalRead(LED_BUILTIN) == HIGH)? LOW : HIGH); } void altDetect (float oldAlt, float alt, int altBreakPoint[]){ int stepSize = 0; int deltaAlt = alt - oldAlt; if (deltaAlt < 0) { stepSize = alt/5; for(int y = 0; y < 5; y++){ altBreakPoint[5 - y] = {alt - ((y + 1) * stepSize)}; // stores break points in decsending order } falling = true; } }
f97ab3c6646a0ee5364fa0a7d0ae2c3ccc52c138
[ "C++" ]
1
C++
PC-Ascend-Team/MasterController
4826c6fac3c12f0b5ada80d3f53165034ad5ab6d
a9a024ebc938af54bed43586e3ac2f52750fe357
refs/heads/master
<file_sep>const { getLogger } = require('common-module/logger'); const { CustomerEntityTypeName, CustomerCreditReservationFailedEvent, CustomerValidationFailedEvent, CustomerCreditReservedEvent } = require('common-module/eventsConfig'); const orderService = require('./orderService.js'); const logger = getLogger({ title: 'customer-service' }); module.exports = { [CustomerEntityTypeName]: { [CustomerCreditReservedEvent]: (event) => { logger.debug('event:', event); const { payload: { orderId }} = event; return orderService.approveOrder(orderId); }, [CustomerCreditReservationFailedEvent]: (event) => { logger.debug('event:', event); const { payload: { orderId }} = event; return orderService.rejectOrder(orderId); }, [CustomerValidationFailedEvent]: (event) => { logger.debug('event:', event); const { payload: { orderId }} = event; return orderService.rejectOrder(orderId); } } }; <file_sep>const { OrderCreatedEvent } = require('common-module/eventsConfig'); class Order { constructor({ id, orderDetails, state }) { this.id = id; this.orderDetails = orderDetails; this.state = (typeof (state) === 'undefined') ? Order.orderState.PENDING : state; } static createOrder({ customerId, orderTotal }) { return [{ _type: OrderCreatedEvent, orderDetails: { customerId, orderTotal }}] } cancelOrder() { switch (this.state) { case Order.orderState.PENDING: throw new Error('PendingOrderCantBeCancelledException'); case Order.orderState.APPROVED: this.state = Order.orderState.CANCELLED; break; default: throw new Error(`Can't cancel in this state ${this.state}`); } } noteCreditReserved() { this.state = Order.orderState.APPROVED; } noteCreditReservationFailed() { this.state = Order.orderState.REJECTED; } static orderState = { PENDING: 0, APPROVED: 1, REJECTED: 2, CANCEL_PENDING: 3, CANCELLED: 4 }; static getOrderStateText(state) { return Object.keys(Order.orderState)[state]; } } module.exports = Order; <file_sep>const { eventMessageHeaders: { AGGREGATE_ID } } = require('eventuate-tram-core-nodejs'); const { getLogger } = require('common-module/logger'); const { CustomerEntityTypeName, CustomerCreatedEvent, OrderEntityTypeName, OrderCreatedEvent, OrderApprovedEvent, OrderRejectedEvent, OrderCancelledEvent } = require('common-module/eventsConfig'); const { createOrUpdateCustomer, createOrUpdateOrder, updateCustomerAndOrderViewState } = require('./orderHistoryService'); const logger = getLogger({ title: 'order-history-service' }); module.exports = { [CustomerEntityTypeName]: { [CustomerCreatedEvent]: (event) => { logger.debug('event:', event); const { [AGGREGATE_ID]: customerId, payload: { name, creditLimit }} = event; return createOrUpdateCustomer({ id: customerId, name, creditLimit }); } }, [OrderEntityTypeName]: { [OrderCreatedEvent]: async (event) => { logger.debug('event:', event); const { [AGGREGATE_ID]: orderId, payload: { orderDetails: { orderTotal, customerId }} } = event; return updateCustomerAndOrderViewState({ orderId, customerId, orderTotal, state: 'PENDING' }); }, [OrderApprovedEvent]: async (event) => { logger.debug('event:', event); const { [AGGREGATE_ID]: orderId, payload: { orderDetails: { orderTotal, customerId }} } = event; return updateCustomerAndOrderViewState({ orderId, customerId, orderTotal, state: 'APPROVED' }); }, [OrderRejectedEvent]: async (event) => { logger.debug('event:', event); const { [AGGREGATE_ID]: orderId, payload: { orderDetails: { orderTotal, customerId }} } = event; return updateCustomerAndOrderViewState({ orderId, customerId, orderTotal, state: 'REJECTED' }); }, [OrderCancelledEvent]: async (event) => { logger.debug('event:', event); const { [AGGREGATE_ID]: orderId, payload: { orderDetails: { orderTotal, customerId }} } = event; return updateCustomerAndOrderViewState({ orderId, customerId, orderTotal, state: 'CANCELLED' }); } } }; <file_sep>const mongoose = require('mongoose'); const { getLogger } = require('common-module/logger'); const logger = getLogger({ title: 'order-history-service' }); const mongoDbUri = process.env.MONGODB_URI; logger.debug(`mongoDbUri: ${mongoDbUri}`); module.exports.connectMongoDb = () => { return new Promise((resolve, reject) => { mongoose.connect(mongoDbUri, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, connectTimeoutMS: 10000 }); const db = mongoose.connection; db.on('error', reject); db.once('open', () => { logger.info(`Connected to MongoDB ${mongoDbUri}`); resolve(); }); db.on('disconnected', () => { logger.info(`Disconnected from MongoDB ${mongoDbUri}`); }); }); }; <file_sep>const knex = require('./knex'); const utils = require('./utils'); module.exports = { knex, utils };<file_sep>const express = require('express'); const customerCommandService = require('./customerService'); const router = express.Router(); router.post('/', async (req, res, next) => { const { name, creditLimit } = req.body; if (!name || typeof (creditLimit) === 'undefined') { return res.status(400).send('"name" and "creditLimit" should be provided'); } try { const customerId = await customerCommandService.create({ name, creditLimit }); res.status(200).send({ customerId }); } catch (e) { next(e); } }); module.exports = router;<file_sep>const knex = require('common-module/mysql-lib/knex'); const { getLogger } = require('common-module/logger'); const logger = getLogger({ title: 'order-service' }); const ORDER_TABLE = 'orders'; function insertIntoOrdersTable (customer_id, amount, state, context = {}) { const { trx } = context; const order = { customer_id, amount, state }; if (trx) { return knex(ORDER_TABLE).transacting(trx).insert(order); } return knex(ORDER_TABLE).insert(order).returning('*'); } async function getOrderById(id, context= {} ) { const { trx } = context; let order; if (trx) { ([ order ] = await knex(ORDER_TABLE).transacting(trx).where('id', id)); } else { ([ order ] = await knex(ORDER_TABLE).where('id', id)); } return order; } function createOrdersTable() { return knex.schema.createTable(ORDER_TABLE, (table) => { table.bigIncrements('id'); table.bigInteger('customer_id'); table.decimal('amount', 19, 2); table.integer('state'); }) } function updateOrderState(id, state, context = {}) { const { trx } = context; if (trx) { return knex(ORDER_TABLE) .transacting(trx) .where('id', id) .update({ state }); } return knex(ORDER_TABLE) .where('id', id) .update({ state }); } module.exports = { insertIntoOrdersTable, getOrderById, createOrdersTable, updateOrderState, };<file_sep>const knex = require('./knex'); async function withTransaction(callback) { const trx = await knex.transaction(); try { const result = await callback(trx); await trx.commit(); return result; } catch (e) { await trx.rollback(); throw e; } } module.exports = { withTransaction, };<file_sep>#!/usr/bin/env bash set -e . ./set-env.sh ./run-services.sh ./run-end-to-end-tests.sh docker-compose down <file_sep>const knex = require('common-module/mysql-lib/knex'); const { getLogger } = require('common-module/logger'); const logger = getLogger({ title: 'customer-service' }); const CUSTOMER_TABLE = 'customer'; function insertIntoCustomerTable (name, amount, creation_time, context = {}) { const { trx } = context; const customer = { name, amount, creation_time }; if (trx) { return knex(CUSTOMER_TABLE).transacting(trx).insert(customer); } return knex(CUSTOMER_TABLE).insert(customer).returning('*'); } async function getCustomerById(id, context = {}) { const { trx } = context; let customer; if (trx) { ([ customer ] = await knex(CUSTOMER_TABLE).transacting(trx).where('id', id)); } else { ([ customer ] = await knex(CUSTOMER_TABLE).where('id', id)); } return customer; } function createCustomerTable() { return knex.schema.createTable(CUSTOMER_TABLE, (table) => { table.bigIncrements('id'); table.string('name'); table.bigInteger('creation_time'); table.decimal('amount', 19, 2); }) } module.exports = { insertIntoCustomerTable, getCustomerById, createCustomerTable, }; <file_sep>#! /bin/bash host=$1 ports=$2 shift 2 done=false while [[ "$done" = false ]]; do for port in $ports; do curl --fail http://${host}:${port}/actuator/health >& /dev/null if [[ "$?" -eq "0" ]]; then done=true else done=false break fi done if [[ "$done" = true ]]; then echo services are started break; fi STOPPED_CONTAINERS=$(docker ps -a | egrep 'eventuate.*Exited') if [ ! -z "$STOPPED_CONTAINERS" ] ; then echo stopped exited containers echo $STOPPED_CONTAINERS exit 99 fi echo -n . sleep 1 done <file_sep>const { CustomerCreatedEvent } = require('common-module/eventsConfig'); class Customer { constructor({ id, name, creditLimit, creditReservations }) { this.id = id; this.name = name; this.creditLimit = creditLimit; this.creditReservations = creditReservations } static create({ name, creditLimit }) { return [{ _type: CustomerCreatedEvent, name, creditLimit }] } availableCredit() { const reservationsSum = Object.values(this.creditReservations).reduce((acc, amount) => acc + amount, 0); return this.creditLimit - reservationsSum; } reserveCredit(orderId, amount) { if (this.availableCredit() >= amount) { this.creditReservations[orderId] = amount; } else { throw new Error('CustomerCreditLimitExceededException'); } } unReserveCredit(orderId) { delete this.creditReservations[orderId]; } } module.exports = Customer;<file_sep>const express = require('express'); const router = express.Router(); const { getLogger } = require('common-module/logger'); const orderCommandService = require('./orderService'); const logger = getLogger({ title: 'order-service' }); const Order = require('./aggregates/Order'); router.post('/', async (req, res, next) => { logger.debug('Create order route', { body: req.body }); const { customerId, orderTotal } = req.body; if (!customerId || typeof (orderTotal) === 'undefined') { return res.status(400).send('"customer_id" and "orderTotal" should be provided'); } try { const orderId = await orderCommandService.create({ customerId, orderTotal }); res.status(200).send({ orderId }); } catch (e) { next(e); } }); router.get('/:orderId', async (req, res, next) => { const orderId = req.params.orderId; try { const order = await orderCommandService.getOrderById(orderId); if (!order) { return res.status(404).send('Order not found'); } res.status(200).send({ orderId: order.id, orderState: Order.getOrderStateText(order.state), }); } catch (e) { next(e); } }); router.post('/:orderId/cancel', async (req, res, next) => { const orderId = req.params.orderId; try { const order = await orderCommandService.cancelOrder(orderId); res.status(200).send({ orderId: order.id, orderState: Order.getOrderStateText(order.state) }); } catch (e) { if (e.message === 'OrderNotExistsException') { return res.status(404).send(); } next(e); } }); module.exports = router;<file_sep>#! /bin/bash -e docker run -i --rm -v $(pwd)/end-to-end-tests:/end-to-end-tests -e DOCKER_HOST_IP node:12.16.1 bash <<END cd /end-to-end-tests npm install npm run test:end-to-end END <file_sep>const knex = require('common-module/mysql-lib/knex'); const { getLogger } = require('common-module/logger'); const logger = getLogger({ title: 'customer-service' }); const CUSTOMER_CREDIT_RESERVATIONS_TABLE = 'customer_credit_reservations'; function createCustomerCreditReservationsTable() { return knex.schema.createTable(CUSTOMER_CREDIT_RESERVATIONS_TABLE, (table) => { table.bigInteger('customer_id'); table.bigInteger('credit_reservations_key'); table.decimal('amount', 19, 2); table.primary(['customer_id', 'credit_reservations_key']) }) } function getCustomerCreditReservations(customerId, context = {}) { const { trx } = context; if (trx) { return knex(CUSTOMER_CREDIT_RESERVATIONS_TABLE).transacting(trx).where('customer_id', customerId); } return knex(CUSTOMER_CREDIT_RESERVATIONS_TABLE).where('customer_id', customerId); } function insertCustomerReservation(customer_id, amount, credit_reservations_key, context = {}) { const { trx } = context; const customerReservation = { customer_id, amount, credit_reservations_key, }; if (trx) { return knex(CUSTOMER_CREDIT_RESERVATIONS_TABLE).transacting(trx).insert(customerReservation); } return knex(CUSTOMER_CREDIT_RESERVATIONS_TABLE).insert(customerReservation); } function deleteCustomerReservation(order_id, context = {}) { const { trx } = context; if (trx) { return knex(CUSTOMER_CREDIT_RESERVATIONS_TABLE) .transacting(trx) .where('credit_reservations_key', order_id) .del(); } return knex(CUSTOMER_CREDIT_RESERVATIONS_TABLE) .where('credit_reservations_key', order_id) .del(); } module.exports = { createCustomerCreditReservationsTable, insertCustomerReservation, deleteCustomerReservation, getCustomerCreditReservations, };<file_sep>function isDuplicateKeyError(err) { return err.code === 11000; } module.exports.updateDocument = (Model, data, conditions) => { const update = {}; if (data['$unset'] && typeof (data['$unset']) === 'object') { update['$unset'] = data['$unset']; delete data['$unset']; } update['$set'] = data; const options = { multi: false }; return Model.update(conditions, update, options); }; module.exports.createDocument = async (Model, data) => { const document = new Model(data); try { return await document.save(); } catch (err) { if (isDuplicateKeyError(err)) { try { return await module.exports.updateDocument(Model, data, { id: data.id }) } catch (e) { throw e; } } throw err; } }; module.exports.upsertDocument = (Model, data, condition) => { return Model.findOneAndUpdate(condition, data, { new: true, upsert: true }); }; module.exports.findDocument = (schema, condition = {}) => { return new Promise((resolve, reject) => { schema.find(condition, { _id: 0, __v: 0 }, { sort: { id: 1 }}, (err, res) => { if (err) { return reject(err); } resolve(res); }); }); }; module.exports.documentsCount = (schema, condition = {}) => { return new Promise((resolve, reject) => { schema.countDocuments(condition, (err, res) => { if (err) { return reject(err); } resolve(res); }); }); }; <file_sep>const mongoose = require('mongoose'); const { Schema } = mongoose; const CustomerSchema = new Schema({ id: { type: Number, required: true, unique: true }, creationTime: { type: Number, default: new Date().getTime() }, name: { type: String, required: true }, creditLimit: { type: Object, amount: { type: mongoose.Decimal128, required: true } }, orders: { type: Object } }); CustomerSchema.set('collection', 'customer'); module.exports = mongoose.model('customer', CustomerSchema); <file_sep>const express = require('express'); const { getOrderById } = require('./orderHistoryService'); const router = express.Router(); router.get('/:orderId', async (req, res, next) => { const { params: { orderId }} = req; try { const order = await getOrderById(orderId); if (!order) { return res.status(404).send(); } res.send(order); } catch (e) { next(e); } }); module.exports = router;<file_sep>#!/usr/bin/env bash set -e docker-compose up -d zookeeper kafka mysql mongodb cdcservice ./wait-for-services.sh ${DOCKER_HOST_IP?} "8099" docker-compose up -d --build customer-service order-history-service order-service ./wait-for-services.sh ${DOCKER_HOST_IP?} "8081 8082 8083"
07d11b7af6f7cd257bf76f3f68cbb53bbd0d933b
[ "JavaScript", "Shell" ]
19
JavaScript
tdias25/eventuate-tram-examples-nodejs-customers-and-orders
8c19f208439e2dfc9c5a9221efae6cd36a299993
a75253bbbe50d88bf7177a257ff7eb2204bd7754
refs/heads/master
<repo_name>SauravYadav12/Blog_project<file_sep>/project1/blog/migrations/0003_auto_20180622_1416.py # Generated by Django 2.0.2 on 2018-06-22 18:16 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0002_auto_20180622_0320'), ] operations = [ migrations.AddField( model_name='post', name='image', field=models.ImageField(blank=True, upload_to='pics'), ), migrations.AlterField( model_name='comment', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 18, 16, 19, 335933, tzinfo=utc)), ), migrations.AlterField( model_name='post', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 18, 16, 19, 334930, tzinfo=utc)), ), ] <file_sep>/project1/blog/migrations/0002_auto_20180622_0320.py # Generated by Django 2.0.2 on 2018-06-22 03:20 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AlterField( model_name='comment', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 3, 20, 53, 658412, tzinfo=utc)), ), migrations.AlterField( model_name='post', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 3, 20, 53, 657696, tzinfo=utc)), ), ] <file_sep>/project1/blog/migrations/0006_auto_20180628_0313.py # Generated by Django 2.0.2 on 2018-06-28 03:13 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0005_auto_20180622_1659'), ] operations = [ migrations.AlterField( model_name='comment', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 28, 3, 13, 51, 914756, tzinfo=utc)), ), migrations.AlterField( model_name='post', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 28, 3, 13, 51, 913986, tzinfo=utc)), ), migrations.AlterField( model_name='post', name='image', field=models.FileField(blank=True, null=True, upload_to=''), ), ] <file_sep>/project1/blog/migrations/0005_auto_20180622_1659.py # Generated by Django 2.0.2 on 2018-06-22 20:59 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0004_auto_20180622_1625'), ] operations = [ migrations.AlterField( model_name='comment', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 20, 59, 3, 695866, tzinfo=utc)), ), migrations.AlterField( model_name='post', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 20, 59, 3, 694362, tzinfo=utc)), ), ] <file_sep>/project1/blog/migrations/0004_auto_20180622_1625.py # Generated by Django 2.0.2 on 2018-06-22 20:25 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0003_auto_20180622_1416'), ] operations = [ migrations.AlterField( model_name='comment', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 20, 25, 53, 101518, tzinfo=utc)), ), migrations.AlterField( model_name='post', name='create_date', field=models.DateTimeField(default=datetime.datetime(2018, 6, 22, 20, 25, 53, 100015, tzinfo=utc)), ), migrations.AlterField( model_name='post', name='image', field=models.ImageField(blank=True, upload_to='photos'), ), ]
13a8352fd0da21e92889088c093f057b41832d86
[ "Python" ]
5
Python
SauravYadav12/Blog_project
670d4579400cb525a4817d7aa4596924a65e0051
3c1ef939cf4a6497865b71df4d7dee2f973b0fce
refs/heads/main
<repo_name>mdorante/Clase2-IntroTS<file_sep>/databinding/src/app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'databinding'; persona: any = { Nombre: 'Lionel', Apellido: 'Messi', Edad: 34, Documento: 1234567890, }; eventoBoton() { console.log( 'Presionaste el boton y disparaste una funcion del app.component.ts' ); console.dir(this.persona); } } <file_sep>/myfirstapp/src/app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'Soy la variable title de app.component.ts'; datos: Object = { Nombre: 'Manuel', Apellido: 'Dorante', Edad: 25, Documento: 95837491, }; } <file_sep>/myfirstapp/README.md # Myapp This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 12.2.6. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities. ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. ## NOTAS - Componentes - El archivo `app.<nombre del componente>.component.ts` define la logica del componente `app.mycomponent.component.ts` ```typescript import { Component, OnInit } from "@angular/core"; // decorador @Component({ // nombre del tag html de este componente (<app-mycomponent></app-mycomponent>) selector: "app-mycomponent", // vinculamos la vista con la logica templateUrl: "./mycomponent.component.html", // vinculamos el style con la logica styleUrls: ["./mycomponent.component.css"], }) export class MycomponentComponent implements OnInit { constructor() {} ngOnInit(): void {} } ``` - El archivo `src/app/app.module.ts` es el encargado de entender que componentes y dependencias tenemos en nuestra app. Si el componente es creado pero no esta declarado ahi, no podra ser utilizado. ```typescript @NgModule({ declarations: [ // vistas que pertenecen a tu modulo AppComponent, MycomponentComponent, ], imports: [ // modulos importados (otros ngModules cuyas clases exportadas son requeridas por templates de este modulo) BrowserModule, AppRoutingModule, ], // servicios que necesita este modulo y que estaran disponibles para toda la app providers: [], // componente principal (define la vista root) bootstrap: [AppComponent], // exports: serian los conjuntos de declaraciones que deben ser accesibles desde otros modulos }) export class AppModule {} ``` ``` ```
431fe20e14c9306c8e11dcbb5bbed00f5ddfb07e
[ "Markdown", "TypeScript" ]
3
TypeScript
mdorante/Clase2-IntroTS
7128231da5bcfd11f9cb38300446b978aff071c9
984a2d459747347f71c3f4c1a59971b95c701f89
refs/heads/main
<file_sep># Crude, no-error-checking, hey-it-works Epsilon Red encoded PS script decoder # Written under macOS via Python 3.8.2 -- may require fiddlin' # by @rj_chap, 2021.06.09 import sys import os import re # Ensure we have been provided an argument (which is hopefully a dir) try: dir_name=sys.argv[1] except: print('Please provide directory with scripts as argument') exit() script_done_pattern = '^\$a\=\$a\.Replace' # Pattern indicates the obfuscated script is done # Loop through files in the provided directory for file in os.listdir(dir_name): # Ignore hidden files and ensure we have an actual file if not file.startswith('.') and os.path.isfile(os.path.join(dir_name, file)): print('Decoding: ' + file) # Setup input & output files obf_file = open(os.path.join(dir_name, file), 'r') deobf_file = open(os.path.join(dir_name, file) + '-deobfuscated.ps1', 'w') obf_code = '' # ini string # Take each line of the obfuscated script until we hit the decoding portion for obf_line in obf_file: if not re.match(script_done_pattern, obf_line): obf_code += obf_line else: continue ''' $a=$a.Replace('[',''); $a=$a.Replace(']',''); $a=$a.Replace('{}{}-{}{}','"'); $a=$a.Replace('{}{}---{}{}',"'"); ''' deobf_code = obf_code.replace('[', '').replace(']', '').replace('{}{}-{}{}', '"').replace('{}{}---{}{}', "'").replace("$a=@'", '').replace("'@", '') deobf_file.write(deobf_code) # Write our output file obf_file.close() # Close the input file deobf_file.close() # Close the output file<file_sep># random_scripts Random stuff, just farting around really. I don't claim to be a dev proper, so feel free to roast my coding practices. Joking aside, I'm **always** open to feedback, especially about my coding :).
c208d3ea921ea965b520d0b3e42fb660f7b8b1e6
[ "Markdown", "Python" ]
2
Python
rj-chap/random_scripts
8bc2fd363fc7ece31bbd9e23f668faccb65d6e1f
b89bd4f1d7274cbfcfad6e377c1311fa9782d575
refs/heads/master
<file_sep>package application.servlets; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.ApplicationPath; import javax.ws.rs.Path; import java.io.IOException; /** * Created by Света on 06.07.2016. */ @javax.servlet.annotation.WebServlet(name = "WebServlet") public class WebServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } <file_sep>package application.model; /** * Created by Света on 01.07.2016. */ public interface Storable { public int getId(); public String getTable(); } <file_sep>package application; import application.model.staff.Department; import application.model.staff.Departments; import application.model.staff.Person; import application.model.staff.Persons; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.File; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Света on 08.07.2016. */ public class Marshall { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(5); list.clear(); list.add(1403897); list.add(1403837); list.add(1403827); Departments departments = new Departments(); Department depart = new Department(); departments.department.add(depart.createDep(1, "Департамент управления делами и контроля", "Департамент УДК", "<NAME>", list)); /* Person pers = new Person(); pers.setId(1); pers.setSurname("Захарова"); pers.setName("Светлана"); pers.setSecondName("Сергеевна"); pers.setPosition("практикант"); Person pers2 = new Person(); pers2.setId(1); pers2.setSurname("Захарова"); pers2.setName("Светлана"); pers2.setSecondName("Сергеевна"); pers2.setPosition("практикант"); Persons person = new Persons(); person.person.add(pers); person.person.add(pers2); */ try { File file = new File(System.getProperty("user.dir") + File.separator + "department.xml"); JAXBContext context = JAXBContext.newInstance(Departments.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(departments, file); marshaller.marshal(departments, System.out); } catch (JAXBException ex) { Logger.getLogger(Marshall.class.getName()) .log(Level.SEVERE, null, ex); } } } <file_sep>package application.servlets; import application.serveces.DerbyDBManager; import application.serveces.FileService; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Светлана on 20.07.2016. */ public class ServletContextListenerDB implements ServletContextListener { ServletContext context; @Override public void contextInitialized(ServletContextEvent contextEvent) { FileService fileService = null; try { fileService = new FileService(); } catch (URISyntaxException e) { e.printStackTrace(); } DerbyDBManager derbyDBManager=new DerbyDBManager("ApplicationDB"); context = contextEvent.getServletContext(); fileService.readFiles(); try { fileService = new FileService(); } catch (URISyntaxException e) { e.printStackTrace(); } try { try { // запись данных в таблицу derbyDBManager.executeUpdatePersons(fileService.getPersons()); } catch (SQLException e) { // если БД не существовала, то создаем таблицу и записываем данные derbyDBManager.createPersonTable(); derbyDBManager.executeUpdatePersons(fileService.getPersons()); } try { // запись данных в таблицу derbyDBManager.executeUpdateOrganizations(fileService.getOrganizations()); } catch (SQLException e) { // если БД не существовала или нет таблицы, то создаем таблицу // и после этого заполняем её значениями derbyDBManager.createOrganizationTables(); //запись данных из созданных таблиц derbyDBManager.executeUpdateOrganizations(fileService.getOrganizations()); } try { // запись данных в таблицу derbyDBManager.executeUpdateDepartments(fileService.getDepartments()); } catch (SQLException e) { // если БД не существовала, то создаем таблицу // и после этого заполняем её значениями derbyDBManager.createDepartmentTables(); //запись данных из созданных таблиц derbyDBManager.executeUpdateDepartments(fileService.getDepartments()); } } catch (SQLException e) { Logger.getLogger(FileService.class.getName()).log(Level.SEVERE, null, e); } } @Override public void contextDestroyed(ServletContextEvent contextEvent) { context = contextEvent.getServletContext(); } } <file_sep> package application.serveces; import application.model.staff.*; import java.sql.*; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Светлана on 18.07.2016. */ public class DerbyDBManager { private static Connection con = null ; private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver" ; private static final String url = "jdbc:derby:" ; ///имя БД private static String dbName = null; //Создаем соединение с бд public DerbyDBManager(String dbName) { this.dbName=dbName; // если искомой бд не существует, создаем ее if(!dbExists()) { try { //Загружаем драйвер Class.forName(driver) ; // Подключение к БД или её создание con = DriverManager.getConnection(url + dbName + ";create=true"); } catch (ClassNotFoundException e) { Logger.getLogger(FileService.class.getName()).log(Level.SEVERE, null, e); } catch (SQLException e) { Logger.getLogger(FileService.class.getName()).log(Level.SEVERE, null, e); } } } //проверяем, существует ли бд private Boolean dbExists() { Boolean exists = false ; try { Class.forName(driver) ; con = DriverManager.getConnection(url + dbName); exists = true ; } catch(Exception e) { Logger.getLogger(FileService.class.getName()).log(Level.SEVERE, null, e); // Если база не создана то ничего не делаем } return(exists) ; } // запрос на обновление базы данных (INSERT, UPDATE, CREATE TABLE и т.п.) public void executeUpdate(String sql) throws SQLException { PreparedStatement prstmt = con.prepareStatement(sql); int count = prstmt.executeUpdate(); prstmt.close(); } // запрос на выборку данных из базы public ResultSet executeQuery(String sql) throws SQLException { PreparedStatement prstmt = con.prepareStatement(sql); ResultSet result = prstmt.executeQuery() ; return result; } //добавление нескольких person(persons) public void executeUpdatePersons(Persons persons) throws SQLException { for (Person person: persons.person) { executeUpdatePerson(person); } } //добавление person public void executeUpdatePerson(Person person) throws SQLException { PreparedStatement prstmt = null; //если в результате запроса возвратилось id то переходим к след элементу if (!hasElementInTable(person.getId(), "person")){ //иначе добавляем элемент prstmt = con.prepareStatement( "INSERT INTO Person " + "(id, name, secondname, surname, position) " + "VALUES (?, ?, ?, ?, ?)"); prstmt.setInt(1, person.getId()); prstmt.setString(2, person.getName()); prstmt.setString(3, person.getSecondName()); prstmt.setString(4, person.getSurname()); prstmt.setString(5, person.getPosition()); prstmt.execute(); } } //добавление нескольких department(departments) public void executeUpdateDepartments(Departments departments) throws SQLException { for (Department department: departments.department) { executeUpdateDepartment(department); //если в результате запроса возвратилось id то переходим к след элементу } } //добавление department public void executeUpdateDepartment(Department department) throws SQLException { PreparedStatement prstmt = null; PreparedStatement prstmtTel = null; if (!hasElementInTable(department.getId(), "department")){ prstmt = con.prepareStatement( "INSERT INTO Department " + "(id, departname, shortname, boss) " + "VALUES (?, ?, ?, ?)"); prstmt.setInt(1, department.getId()); prstmt.setString(2, department.getDepartName()); prstmt.setString(3, department.getShortName()); prstmt.setString(4, department.getBoss()); prstmt.execute(); ArrayList<Integer> depTel = department.getTelNumbers(); //записываем номера телефонов в отдельную таблицу for (int i = 0; i < depTel.size(); i++) { prstmtTel = con.prepareStatement( "INSERT INTO DepartmentTel " + "(id, telNumber) " + "VALUES (?, ?)"); prstmtTel.setInt(1, department.getId()); prstmtTel.setInt(2, depTel.get(i)); prstmtTel.execute(); } } } //добавление нескольких organization(organizations) public void executeUpdateOrganizations(Organizations organizations) throws SQLException { for (Organization organization: organizations.organization) { executeUpdateOrganization(organization); } } //добавление organization public void executeUpdateOrganization(Organization organization) throws SQLException { PreparedStatement prstmt = null; PreparedStatement prstmtTel = null; if (!hasElementInTable(organization.getId(), "organization")){ prstmt = con.prepareStatement( "INSERT INTO Departments " + "(id, orgname, shortname, boss) " + "VALUES (?, ?, ?, ?)"); prstmt.setInt(1, organization.getId()); prstmt.setString(2, organization.getOrgName()); prstmt.setString(3, organization.getShortName()); prstmt.setString(4, organization.getOrgBoss()); prstmt.execute(); ArrayList<Integer> orgTel = organization.getOrgTelNumbers(); //записываем номера телефонов в отдельную таблицу for (int i = 0; i < orgTel.size(); i++) { prstmtTel = con.prepareStatement( "INSERT INTO OrganizationTel " + "(id, telNumber) " + "VALUES (?, ?)"); prstmtTel.setInt(1, organization.getId()); prstmtTel.setInt(2, orgTel.get(i)); prstmtTel.execute(); } } } //проверка элемента на наличие(принимает id элемента и название таблицы, в которой проверяем наличие) public boolean hasElementInTable (int id, String tableName) { boolean res = false; PreparedStatement prstmt = null; try { prstmt = con.prepareStatement("SELECT * FROM "+ tableName +" WHERE id = ?"); prstmt.setInt(1, id); ResultSet result = prstmt.executeQuery(); while (result.next()) { res = true; } } catch (SQLException e) { e.printStackTrace(); } return res; } //получаем persons(вся таблица) public Persons getPersonsFromDB(){ ResultSet rs = null; Persons persons = new Persons(); try { rs = this.executeQuery("SELECT * FROM Person"); while (rs.next()) { Person person = new Person(); person.setId(rs.getInt("id")); person.setName(rs.getString("name")); person.setSecondName(rs.getString("secondname")); person.setSurname(rs.getString("surname")); person.setPosition(rs.getString("position")); persons.person.add(person); } } catch (SQLException e) { e.printStackTrace(); } return persons; } //получаем person по id public Person getPersonFromDB(int id){ PreparedStatement prstmt = null; ResultSet rs = null; Person person = new Person(); try { prstmt = con.prepareStatement( "SELECT * FROM Person WHERE id = ?"); prstmt.setInt(1, id); rs = prstmt.executeQuery(); while (rs.next()) { person.setId(rs.getInt("id")); person.setName(rs.getString("name")); person.setSecondName(rs.getString("secondname")); person.setSurname(rs.getString("surname")); person.setSurname(rs.getString("position")); } } catch (SQLException e) { e.printStackTrace(); } return person; } //получаем departments(вся таблица) public Departments getDepartmentsFromDB(){ Departments departments = new Departments(); Department department = new Department(); ResultSet rs2 = null; ResultSet rs = null; try { rs = this.executeQuery("SELECT * FROM Department"); while (rs.next()) { department.setId(rs.getInt("id")); department.setDepartName(rs.getString("departname")); department.setShortName(rs.getString("shortname")); department.setBoss(rs.getString("boss")); rs2 = this.executeQuery("SELECT telNumber FROM DepartmentTel WHERE id="+rs.getInt("id")+""); ArrayList<Integer> depTel = new ArrayList<Integer>(); while (rs2.next()) { depTel.add(rs2.getInt("telNumber")); } department.setTelNumbers(depTel); departments.department.add(department); } } catch (SQLException e) { e.printStackTrace(); } return departments; } //получаем department по id public Department getDepartmentFromDB(int id){ PreparedStatement prstmt = null; Department department = new Department(); ResultSet rs2 = null; ResultSet rs = null; try { prstmt = con.prepareStatement( "SELECT * FROM Department WHERE id = ?"); prstmt.setInt(1, id); rs = prstmt.executeQuery(); while (rs.next()) { department.setId(rs.getInt("id")); department.setDepartName(rs.getString("departname")); department.setShortName(rs.getString("shortname")); department.setBoss(rs.getString("boss")); rs2 = this.executeQuery("SELECT telNumber FROM DepartmentTel WHERE id="+rs.getInt("id")+""); ArrayList<Integer> depTel = new ArrayList<Integer>(); while (rs2.next()) { depTel.add(rs2.getInt("telNumber")); } department.setTelNumbers(depTel); } } catch (SQLException e) { e.printStackTrace(); } return department; } //получаем organizations(вся таблица) public Organizations getOrganizationsFromDB(){ Organizations organizations = new Organizations(); Organization organization = new Organization(); ResultSet rs2 = null; ResultSet rs = null; try { rs = this.executeQuery("SELECT * FROM Organization"); while (rs.next()) { organization.setId(rs.getInt("id")); organization.setOrgName(rs.getString("orgname")); organization.setShortName(rs.getString("shortname")); organization.setOrgBoss(rs.getString("orgboss")); rs2 = this.executeQuery("SELECT telNumber FROM OrganizationTel WHERE id="+rs.getInt("id")+""); ArrayList<Integer> orgTel = new ArrayList<Integer>(); while (rs2.next()) { orgTel.add(rs2.getInt("telNumber")); } organization.setOrgTelNumbers(orgTel); organizations.organization.add(organization); } } catch (SQLException e) { e.printStackTrace(); } return organizations; } //получаем organization по id public Organization getOrganizationFromDB(int id){ PreparedStatement prstmt = null; Organization organization = new Organization(); ResultSet rs2 = null; ResultSet rs = null; try { prstmt = con.prepareStatement( "SELECT * FROM Department WHERE id = ?"); prstmt.setInt(1, id); rs = prstmt.executeQuery(); while (rs.next()) { organization.setId(rs.getInt("id")); organization.setOrgName(rs.getString("orgname")); organization.setShortName(rs.getString("shortname")); organization.setOrgBoss(rs.getString("orgboss")); rs2 = this.executeQuery("SELECT telNumber FROM OrganizationTel WHERE id="+rs.getInt("id")+""); ArrayList<Integer> orgTel = new ArrayList<Integer>(); while (rs2.next()) { orgTel.add(rs2.getInt("telNumber")); } organization.setOrgTelNumbers(orgTel); } } catch (SQLException e) { e.printStackTrace(); } return organization; } public void createOrganizationTables(){ try { this.executeUpdate("CREATE TABLE Organization(id int, orgname varchar(128)," + " shortname varchar(128), orgboss varchar(128))"); // таблица для номеров телефонов organizations this.executeUpdate("CREATE TABLE OrganizationTel(id int, telNumber int))"); } catch (SQLException e) { e.printStackTrace(); } } public void createDepartmentTables(){ try { this.executeUpdate("CREATE TABLE Department(id int, departname varchar(128)," + " shortname varchar(128), boss varchar(128))"); // таблица для номеров телефонов departments this.executeUpdate("CREATE TABLE DepatmentTel(id int, telNumber int))"); //запись данных из созданных таблиц } catch (SQLException e) { e.printStackTrace(); } }; public void createPersonTable(){ try { this.executeUpdate("CREATE TABLE Person(id int, name varchar(128)," + " secondname varchar(128), surname varchar(128), position varchar(128))"); } catch (SQLException e) { e.printStackTrace(); } } /* public boolean hasDepartment(int id) { boolean res = false; PreparedStatement prstmt = null; try { prstmt = con.prepareStatement("SELECT * FROM Department WHERE id = ?"); prstmt.setInt(1, id); ResultSet result = prstmt.executeQuery(); while (result.next()) { res = true; } } catch (SQLException e) { e.printStackTrace(); } return res; } public boolean hasOrganization(int id) { boolean res = false; PreparedStatement prstmt = null; try { prstmt = con.prepareStatement("SELECT * FROM Organization WHERE id = ?"); prstmt.setInt(1, id); ResultSet result = prstmt.executeQuery(); while (result.next()) { res = true; } } catch (SQLException e) { e.printStackTrace(); } return res; } */ } <file_sep>package application; /** * Created by Света on 01.07.2016. */ public class TestDoc { /* public static void main(String[] args) throws IOException { //1. сохраняем данные из файлов(пока только персонал ) //Перенести в точку входа map //Создаем hashmap для хранения классов и названий файлов Map<String,Class> staffMap = new HashMap<String,Class>(); staffMap.put("person.xml", Persons.class); staffMap.put("department.xml", Departments.class); staffMap.put("organization.xml", Organizations.class); FileService fileService = new FileService(); Persons person = fileService.readFiles(staffMap); //создаем экземпляр DocService DocService docService = new DocService(); //сохраняем person в docfieldStorage docService.savePersons(person); //доп масссив для случайной генерации одного из документов Class[] classDoc = new Class[3]; classDoc[0] = Task.class; classDoc[1] = Outgoing.class; classDoc[2] = Incoming.class; //создаем TreeSet для хранения документов TreeSet<Document> allDoc = new TreeSet<Document>(); int p;//переменная для хранения случайного значения //создаем документы for (int i = 0; i < 30; i++) { p = (int) (Math.random() * 3); Document doc = docService.createDoc(classDoc[p]); if (doc != null) { allDoc.add(doc); } } Map<Person, TreeSet<Document>> docsByPersonMap = new TreeMap<Person, TreeSet<Document>>(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); //сортируем документы по авторам for (Document d : allDoc) { if (!docsByPersonMap.containsKey(d.getAuthor())) { docsByPersonMap.put(d.getAuthor(), new TreeSet<Document>()); } docsByPersonMap.get(d.getAuthor()).add(d); } //генерируем отчеты по каждому автору в json файлы GsonBuilder builder = new GsonBuilder(); Gson gson = new Gson(); String authorStr; String stringInJSON; String dirName = "e:\\java\\workspace\\app3\\"; String extension = ".json"; // сортировка документов по автору for (Person author : docsByPersonMap.keySet()) { //очищаем строку stringInJSON=""; //сохраняем имя автора в переменную authorStr = author.getSurname() + " " + author.getName() + " " + author.getSecondName(); //добавляем документы в формате json в строку for (Document d : docsByPersonMap.get(author)) { stringInJSON = stringInJSON + gson.toJson(d); } try (FileWriter fileWriter = new FileWriter(dirName + authorStr + extension)) { fileWriter.write(stringInJSON); } catch (IOException ex) { Logger.getLogger(TestDoc.class.getName()) .log(Level.SEVERE, null, ex); } } //очищаем строку stringInJSON=""; for (Person person : docService.getDocFieldsStorage().getPersonDocStorage().values()) { //добавляем сотрудников в формате json в строку stringInJSON = stringInJSON + gson.toJson(person); } try (FileWriter fileWriter = new FileWriter(dirName+"Persons"+ extension)) { fileWriter.write(stringInJSON); } catch (IOException ex) { Logger.getLogger(TestDoc.class.getName()) .log(Level.SEVERE, null, ex); } } */ }
49c3cab214bee1a14177e68d50dec982add135a4
[ "Java" ]
6
Java
Saiongi/app3
3cfa8d2e8d6cf7029299d61a4ef3ddb9f515d8a9
7f887fd4cc7d268c64c7c7442983e914794a029d
refs/heads/master
<file_sep># RPI-CPU-Temp 树莓派cpu温控风扇 https://rehtt.com/index.php/archives/155/ <file_sep>package main import ( "bufio" "flag" "fmt" "github.com/rehtt/gogpio" "github.com/kardianos/service" "log" "os" "strconv" "time" ) var ( max, min int showTemp, h bool ) func main() { flag.BoolVar(&h, "h", false, "help") flag.IntVar(&max, "m", 55, "开启风扇温度") flag.IntVar(&min, "n", 50, "关闭风扇温度") flag.BoolVar(&showTemp, "s", false, "查看当前温度") flag.Usage = help flag.Parse() if h { flag.Usage() } else { if !showTemp { //服务 cfg := &service.Config{ Name: "temp", DisplayName: "RPI CPU Temp", Description: "RPI CPU Temp", } prg := &program{} s, err := service.New(prg, cfg) if err != nil { log.Fatal(err) } // logger 用于记录系统日志 logger, err := s.Logger(nil) if err != nil { log.Fatal(err) } if len(os.Args) == 2 { //如果有命令则执行 err = service.Control(s, os.Args[1]) if err != nil { log.Fatal(err) } } else { //否则说明是方法启动了 err = s.Run() if err != nil { logger.Error(err) } } if err != nil { logger.Error(err) } } else { fmt.Println("当前温度:", t(), "°") } } } func t() int { txt, _ := os.Open("/sys/class/thermal/thermal_zone0/temp") defer txt.Close() buf := bufio.NewReader(txt) t, _, _ := buf.ReadLine() temp, _ := strconv.Atoi(string(t)) temp = temp / 1000 return temp } func help() { fmt.Fprintln(os.Stderr, `使用:temp [选项] [服务操作] 选项:`) flag.PrintDefaults() fmt.Fprintln(os.Stderr,` 服务操作: install 安装服务(开启服务必做) start 运行服务 stop 停止服务 uninstall 卸载服务 示例: temp -s 显示温度 temp install && temp start 安装服务并启动 temp stop 停止服务 temp -m 50 start 带参数启动服务 启动服务需要root权限`) } //服务 type program struct{} func (p *program) Start(s service.Service) error { log.Println("开始服务") go p.run() return nil } func (p *program) Stop(s service.Service) error { log.Println("停止服务") return nil } func (p *program) run() { // 这里放置程序要执行的代码…… pin, _ := gogpio.Open(14, gogpio.OUT) for ; ; { if t() >= max { pin.High() } else if t() <= min { pin.Low() } time.Sleep(30 * time.Second) } }
b1e35cff6f0c6113594456b83cecf7b087542cb8
[ "Markdown", "Go" ]
2
Markdown
qusong520/RPI-CPU-Temp
2772003f042fd99da12374a8729d4a800f33dbb1
d2824b2660018d42b3384bdb38fdbc27020c1437
refs/heads/main
<file_sep>from django.contrib import admin from home.models import Article admin.site.register(Article) <file_sep><html lang="en"> <head> <meta charset="UTF-8"> <title>All article</title> </head> <body> {% for article in articles %} <div> <a href="{{ article.pk }}">Ссылка</a> <b>{{ article.title }}</b> <p>{{ article.content }}</p> </div> <hr> {% endfor %} </body> </html> <file_sep>from django.urls import path from home import views urlpatterns = [ path('', views.home, name='home'), path('cat/', views.markus, name='cat'), path('debug/', views.debug, name='debug'), path('articles/', views.all_articles, name='all-articles'), path('articles/<int:pk>/', views.get_article, name='get-articles'), path('<username>/', views.user, name='user-account'), ] <file_sep>from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from home.models import Article def home(request): return HttpResponse("<b>Hello</b> <i>world!</i>") def markus(request): return HttpResponse("Hello Markus!") def debug(request): page = request.GET.get('page') return HttpResponse(f"This is Debug URL. Page number {page}") def user(request, username): return HttpResponse(f"This is user {username}") def all_articles(request): articles = Article.objects.all() return render( request, "articles.html", {"articles": articles}, ) def get_article(request, pk: int): article = get_object_or_404(Article, pk=pk) return render( request, "article.html", {"article": article}, )
33000b548308dee3114bce10f5a4d12ce282287b
[ "Python", "HTML" ]
4
Python
michaelmedved/tms-django-autumn
0ba0290be83cc165afd2f07b19d94e56f92ee850
444ca44d9bc65bcf112bd2e08ea91da9da69263c
refs/heads/master
<repo_name>hostdime/hdcore-rb<file_sep>/lib/hdcore.rb require 'hdcore/version' require 'httparty' require 'logger' require 'yaml' require 'rubygems' require 'json' require 'digest/sha2' # to generate SHA256 hash require 'securerandom' # to generate v4 UUID Dir[File.dirname(__FILE__) + '/hdcore/*.rb'].each do |file| require file end <file_sep>/spec/lib/hdcore/request_spec.rb require 'spec_helper' describe Hdcore::Request do describe '.call' do it 'initializes and sends POST request to API endpoint' do test_action = 'some.action' Hdcore::Request.stub(:full_api_parameters).and_return(params = {:some => 'params'}) Hdcore::Request.should_receive(:init) Hdcore::Request.should_receive(:post).with("/#{test_action.gsub('.','/')}.json", :body => params) Hdcore::Request.call(test_action, {}) end end describe '.full_api_parameters' do it 'returns parameters merged with generated api parameters' do Hdcore::Request.stub(:generate_api_params).and_return(api_params = {:some => 'api_params'}) actual = Hdcore::Request.send(:full_api_parameters, 'some.action', params = {:some_other => 'params'}) actual.should == params.merge(api_params) end end describe '.generate_api_params' do it 'returns hash with four valid param keys' do actual = Hdcore::Request.send(:generate_api_params, "", {}) actual.keys.should == [:api_key, :api_unique, :api_timestamp, :api_hash] end it 'returns [:api_key] => public key' do Hdcore::Request.stub(:public_key).and_return(key = 'some_public_key') actual = Hdcore::Request.send(:generate_api_params, "", {}) actual[:api_key].should == key end it 'returns [:api_unique] => generated uuid' do Hdcore::Request.stub(:generate_uuid).and_return(uuid = 'some_uuid') actual = Hdcore::Request.send(:generate_api_params, "", {}) actual[:api_unique].should == uuid end it 'returns [:api_timestamp] => time of execution' do timestamp = Time.now.to_i actual = Hdcore::Request.send(:generate_api_params, "", {}) actual[:api_timestamp].should == timestamp end it 'returns [:api_hash] => generated hash' do Hdcore::Request.stub(:generate_hash).and_return(hash = 'some_hash') actual = Hdcore::Request.send(:generate_api_params, "", {}) actual[:api_hash].should == hash end it 'generated hash formed with the correct elements: [timestamp, uuid, pkey, action, json-ified params]' do Hdcore::Request.stub(:generate_uuid).and_return(uuid = 'some_uuid') Hdcore::Request.stub(:private_key).and_return(private_key = 'some_private_key') Hdcore::Request.should_receive(:generate_hash).with(Time.now.to_i, uuid, private_key, action = 'some.action', (params = {:some => 'optional_params'}).to_json.to_json ) Hdcore::Request.send(:generate_api_params, action, params) end end describe '.generate_hash' do it 'uses the SHA256 algorithm, and joins parameters with colons' do args = %w[one two three 4 five seven 8] hash = (Digest::SHA2.new << args.join(':')).to_s Hdcore::Request.send(:generate_hash, args).should == hash end end describe '.generate_uuid' do it 'uses Version 4 UUID' do SecureRandom.should_receive(:uuid).and_return(uuid = 'some_uuid') Hdcore::Request.send(:generate_uuid).should == uuid end end end <file_sep>/README.md # Hdcore ![image](https://travis-ci.org/hostdime/hdcore-rb.png) A basic wrapper for HostDime.com's customer portal 'Core' API. ## Installation Add this line to your application's Gemfile: gem 'hdcore' And then execute: $ bundle Or install it yourself as: $ gem install hdcore ## Usage Before use, the library must be configured with your client key: ```ruby Hdcore.configure(public_key: 'foobar', private_key: 'fazbaz') # or perhaps Hdcore.configure_with(path_to_some_yml_config_file) ``` API calls are then made statically, and return HTTParty response objects. ```ruby # An example of an action with parameters Hdcore::Request.call('server.get', {:cuid => 'S37'}) ``` For details on API specification, visit https://api.hostdime.com/ ## Contributing 1. Fork it 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/hdcore/hdcore.rb # module Hdcore @log = Logger.new(STDOUT) # Default configuration values @config = { :api_endpoint => 'https://api.hostdime.com/v1', :public_key => nil, :private_key => nil } @valid_config_keys = @config.keys class << self # Configure HDCore with an options hash. # @param [Hash] opts Configuration options hash # @option opts [String] :api_endpoint ('core.hostdime.com/api/v1') The HDCore API endpoint URI # @option opts [String] :public_key Your HDCore public key # @option opts [String] :private_key Your HDCore private key def configure opts = {} opts.each do |key, val| config[key.to_sym] = val if @valid_config_keys.include? key.to_sym end end # Configure HDCore with an external yaml config file. # @param [String] path_to_yaml_file Absolute path to yaml config file def configure_with path_to_yaml_file begin config = YAML::load(IO.read(path_to_yaml_file)) rescue Errno::ENOENT log.warn "YAML config file not found: using defaults instead"; return rescue Psych::SyntaxError log.warn "YAML config file has invalid syntax: using defaults instead"; return end configure(config) end # Current configuration hash def config @config end # For logging purposes def log @log end # @return [Bool] True if there are configuration keys that have no assigned value. def missing_config_values? config.values.include? nil end # @return [Array] Configuration keys that have no assigned value. def missing_config_values config.select{|k,v| v.nil?}.keys end end end<file_sep>/spec/lib/hdcore/hdcore_spec.rb require 'spec_helper' describe Hdcore do describe '.config' do it 'returns hash with expected keys [:api_endpoint, :public_key, :private_key]' do Hdcore.config.keys.should == [:api_endpoint, :public_key, :private_key] end it 'returns default [:api_endpoint] => "https://api.hostdime.com/v1"' do Hdcore.config[:api_endpoint].should == 'https://api.hostdime.com/v1' end it 'returns default [:public_key] => nil' do Hdcore.config[:public_key].should == nil end it 'returns default [:private_key] => nil' do Hdcore.config[:private_key].should == nil end end describe '.configure' do it 'assigns value if the key is valid' do # public_key is known to be a valid config key Hdcore.configure(:public_key => 'some_value') Hdcore.config[:public_key].should == 'some_value' end it 'does nothing for invalid keys' do Hdcore.configure(:bogus_key => 'some_value') Hdcore.config[:bogus_key].should be_nil end after do # reset to expected nil values Hdcore.configure({ :public_key => nil, :private_key => nil }) end end describe '.missing_config_values?' do it 'returns true by default, due to uninitialized config values' do Hdcore.missing_config_values?.should be_true end it 'returns true when a config value is nil' do Hdcore.stub(:config).and_return(:some => nil) Hdcore.missing_config_values?.should be_true end it 'returns false when config values are not nil' do Hdcore.stub(:config).and_return(:some => 'not_nil') Hdcore.missing_config_values?.should be_false end end describe '.missing_config_values' do it 'returns default [:public_key, :private_key]' do Hdcore.missing_config_values.should == [:public_key, :private_key] end it 'returns keys that have nil values' do Hdcore.stub(:config).and_return(:empty_config_key => nil, :not_empty => 'value') Hdcore.missing_config_values.should == [:empty_config_key] end end end <file_sep>/spec/spec_helper.rb require File.join(File.dirname(File.dirname(__FILE__)), '/lib/hdcore.rb')<file_sep>/lib/hdcore/request.rb # module Hdcore class Request include HTTParty class << self # @param [String] action The full API action # @param [Hash] params The given action parameters # @return [HTTParty::Response] def call(action, params = {}) init() post "/#{action.gsub('.','/')}.json", :body => full_api_parameters(action, params) end private # @private # Initializes the request: throws exception if there are configs missing (requires public and private keys) def init # Make sure required config values are set if Hdcore.missing_config_values? msg = "Hdcore is not yet properly configured: Missing #{Hdcore.missing_config_values}" Hdcore.log.error(msg) raise Exception, msg, caller end # set base uri for HTTParty request base_uri Hdcore.config[:api_endpoint] end # @private # @return [String] public key established in configuration def public_key Hdcore.config[:public_key] end # @private # @return [String] private key established in configuration def private_key Hdcore.config[:private_key] end # @private # @param [String] action The full API action # @param [Hash] params The given action parameters # @return [Hash] Full set of parameters, including generated api parameters def full_api_parameters(action, params = {}) params.merge generate_api_params(action, params) end # @private # @param [String] action The full API action # @param [Hash] action_params The given action parameters # @return [Hash] required api parameters: {:api_key, :api_unique, :api_timestamp, :api_hash} def generate_api_params(action, params = {}) { :api_key => public_key, :api_unique => uuid = generate_uuid, :api_timestamp => timestamp = Time.now.to_i, :api_hash => generate_hash( timestamp, uuid, private_key, action, params.to_json.to_json ) } end # @private # @return [String] SHA256 hash of all the arguments "joined:with:colons" def generate_hash(*args) (Digest::SHA2.new << args.join(':')).to_s end # @private # @return [String] Version 4 UUID # More: http://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 def generate_uuid SecureRandom.uuid end end end end
6e1a200d4b570957f2521e4e48d6120595200305
[ "Markdown", "Ruby" ]
7
Ruby
hostdime/hdcore-rb
ed13270eea0c34a89d63ef2c809963c2589dd7a4
532482605b78a519cb30dbea85542da4c8afa01d
refs/heads/master
<file_sep>package com.example.profiles.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.example.profiles.db.Db; import com.example.profiles.db.manager.Manager; @RestController public class MainController { @Autowired private Db db; @Autowired private Manager manager; @GetMapping("/profile") public String getProfile() { return db.getEnv(); } @GetMapping("/profile-manager") public String getProfileManager() { return manager.getName(); } } <file_sep>package com.example.profiles.db; public class Db { private String env; public Db() { } public Db(String env) { this.env = env; } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } } <file_sep>package com.example.profiles.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; import com.example.profiles.db.Db; @Configuration @Profile("dev") public class DevConfig { @Bean public Db getDb() { return new Db("DEV"); } @Bean @Primary public Db getDb2() { return new Db("DEV1"); } } <file_sep>package com.example.profiles.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import com.example.profiles.db.Db; @Configuration @Profile("int") public class IntConfig { @Bean public Db getDb() { return new Db("INT"); } } <file_sep>package com.example.profiles.db.manager; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("int") public class IntManager implements Manager { @Override public String getName() { return "IntManager"; } }
3389777a45aa5b44461ad4ae6caa2a2de29c8dda
[ "Java" ]
5
Java
NovikovEugeny/spring-profiles
866b3f4839be05128c5ece15c6c77675c1cf99d9
ee42fc3c164a46e395dd8ddc05eb1e3cb6c50535
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script src='script.js'></script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="">Check your Team Status</a> </div> <ul class="nav navbar-nav"> <li class="active"><a href="ourteamstatus.html">Our Team Players</a></li> <li><a href="gamedisplay.html">The games we play </a></li> <li><a href="summarydispaly.html">Summary display</a></li> </ul> </div> </nav> <div class="container"> <h3>The requirment of the projects</h3> <p>We want to create and extract information about your favorite sports team. Basketball, soccer, tennis, or water polo, you pick it. It’s your job to create data using the JavaScript data structures at your disposal: arrays, objects, etc. Once created, you can manipulate these data structures as well as gain insights from them. For example, you might want to get the total number of games your team has played, or the average score of all of their games..</p> </div> </body> </html><file_sep>const team = { _players: [ { firstName: 'Pablo', lastName: 'Sanchez', age: 11, } ], _games: [ { opponent: 'Broncos', teamPoints: 42, opponentPoints: 27, } ], get games() { return this._games }, get players() { return this._players }, addPlayer(firstName, lastName, age) { const player = { firstName, lastName, age, } this._players.push(player) }, addGame(opponent, teamPoints, opponentPoints) { const game = { opponent, teamPoints, opponentPoints } this._games.push(game) } } team.addPlayer('Steph', 'Curry', 28); team.addPlayer('Lisa', 'Leslie', 44); team.addPlayer('Bugs', 'Bunny', 76); team.addGame('Boston Celtics', 100, 110) team.addGame('Chicago Bulls', 90, 80) team.addGame('Brooklyn Nets', 80, 100) var point = 0; const myteamtotalScore = () => { for (var i = 0; i < team._games.length; i++) { point = point + team._games[i].teamPoints } return point } var opponentpoint = 0; const opponenttotalScore = () => { for (var i = 0; i < team._games.length; i++) { opponentpoint = opponentpoint + team._games[i].opponentPoints } return opponentpoint } const myteamAveragescore = () => { return myteamtotalScore() / team._games.length } const teamplayersDisplay = () => { const playersDisplay = `Totally we have ${team._players.length} players.` document.getElementById('demo2').innerHTML = '' team._players.forEach(player => { document.getElementById('demo2').innerHTML += ` One of them is ${player.firstName} ${player.lastName} and he is ${player.age} years old. <br/>` }) document.getElementById('demo1').innerHTML = playersDisplay } const gameDisplay = () => { document.getElementById('demo3').innerHTML = `Totally we have played ${team._games.length} games.` team._games.forEach(game => { document.getElementById('demo4').innerHTML += `We played against ${game.opponent},we got ${game.teamPoints} and the our opponent got ${game.opponentPoints} <br/>` }) } const summaryDisplay = () => { document.getElementById('demo5').innerHTML = `Our team total score is ${myteamtotalScore()}` document.getElementById('demo6').innerHTML = `Our opponent total score is ${opponenttotalScore()}` document.getElementById('demo7').innerHTML = `My team average score is ${myteamAveragescore()}` }
01198608f2c9480f96627dfbb512c6217bf3b6ff
[ "JavaScript", "HTML" ]
2
HTML
oskarcode/teamstatus
5d2ddc65c6d07da6a0478c3777f646da2a6b2f98
a6e4efb332b2a6ddd2eef60544f679d261e272f0
refs/heads/master
<repo_name>PatreekH/Bamazon<file_sep>/BamazonCustomer.js var prompt = require('prompt'); var mysql = require('mysql'); var inquirer = require('inquirer'); var connection = mysql.createConnection({ host: 'localhost', port: 3306, user: 'root', password: process.argv[2], database: 'Bamazon' }); //If connection is good then console logs the following connection.connect(function(err) { if (err) throw err; console.log(" "); console.log(" Welcome to: "); console.log(" ____ "); console.log(" | _ ] "); console.log(" | |_) | __ _ _ __ ____ __ _ ___________ ___ "); console.log(" | _ < / _` | '_ ` _ |/ _` |_ / _ } | '_ | "); console.log(" | |_) | (_| | | | | | | (_| |/ { (_) )| | | |"); console.log(" |____/|__,__|_| |_| |_|L__,_/___{___/ |_| |_|" ); console.log(" "); displayItems(); }); //Displays items after welcome console.log shows function displayItems() { connection.query('SELECT * FROM `Products`', function(err, rows, fields) { if (err) throw err; console.log(" "); console.log("==== Products Available: ===="); for (i = 0; i < rows.length; i++){ console.log(" "); console.log("========== ItemID: " + rows[i].ItemID + " =========="); console.log("| Name: " + rows[i].ProductName); console.log("| Department: " + rows[i].DepartmentName); console.log("| Price: $" + rows[i].Price); console.log("| Left in Stock: " + rows[i].StockQuantity); if (rows[i].ItemID >= 10){ console.log("================================") console.log(" "); } else { console.log("==============================="); } } buyProduct(); }); } //Prompts the user to enter the ID and quantity of the desired product function buyProduct(){ var item = { properties: { id: { description: "Please enter the ID of the product you would like to purchase" } } }; var quantity = { properties: { quantity: { description: "Please enter the quantity you would like to buy" } } }; prompt.start(); prompt.get([item, quantity], function(err, data){ makePurchase(data.id, data.quantity); }) }; //Makes sure the purchased item has enough quantity in stock, returns a receipt to the user function makePurchase(itemId, quantity){ connection.query('SELECT * FROM `Products` WHERE `ItemID` = "' + itemId + '"' , function(err, rows, fields) { if (err) throw err; //Your new total is: Does this look correct? //If yes run for loop, if no run buyProduct again for (i = 0; i < rows.length; i++){ var finalTotal = rows[i].Price * quantity; var newQuantity = rows[i].StockQuantity - quantity; if (quantity > rows[i].StockQuantity){ console.log(rows[i].StockQuantity); console.log(" "); console.log("Insufficient quantity! Please try again!"); console.log(" "); buyProduct(); } else { console.log(" "); console.log("Success! The sale has been finalized."); console.log("Here is your receipt: "); console.log("-----------------------------"); console.log("| "); console.log("| Name: " + rows[i].ProductName); console.log("| "); console.log("| Quantity Purchased: " + quantity); console.log("| "); console.log("| Price per item: $" + rows[i].Price); console.log("| "); console.log("| Total: $" + finalTotal); console.log("| "); console.log("-----------------------------"); console.log("Thank you for shopping with Bamazon!"); console.log(" "); continueShopping(itemId, newQuantity); updateTotalSales(finalTotal, rows[i].DepartmentName); } } }); } //asks the user if they would like to continue shopping function continueShopping(itemId, newQuantity){ connection.query('UPDATE `Products` SET `StockQuantity` = "' + newQuantity + '" WHERE `ItemID` = "' + itemId + '"', function(err, rows, fields) { if (err) throw err; inquirer.prompt([ { type: "list", message: "Would you like to keep shopping?", choices: ["Yes", "No"], name: "choice" } ]).then(function (answers) { if (answers.choice == "Yes"){ displayItems(); } else { console.log(" "); console.log("Thank you for using Bamazon, come back soon!"); console.log(" "); connection.end(); } }); }); } //updates the database function updateTotalSales(purchaseTotal, departmentName){ connection.query('UPDATE `Departments` SET `TotalSales` = "' + purchaseTotal + '" WHERE `DepartmentName` = "' + departmentName + '"', function(err, rows, fields) { if (err) throw err; //connection.end(); }); }<file_sep>/README.md # Bamazon A node based clone of Amazon.com
6278fcbb67b94e5d836fa8c21c4a32436afc0dcb
[ "JavaScript", "Markdown" ]
2
JavaScript
PatreekH/Bamazon
4a9cbc3574d924558f1e7102482b8fabeddc4b20
c21e7e70676c24abbf7004e34c31c943fbef9718
refs/heads/main
<file_sep>// // ViewController.swift // Milestone Project 3 // // Created by <NAME> on 12/8/20. // import UIKit class ViewController: UIViewController { var allWords = [String]() var cluesLabel: UILabel! var hangManLabel: UILabel! var currentAnswer: UITextField! var letterButtons = [UIButton]() var activatedButtons = [UIButton]() var letterArray = [String]() var correctLetters = [String]() var scoreLabel: UILabel! var hangManIndex = 0 var hangMan = [""" """, """ O """, """ O | """, """ O /| """, """ O /|\\ """, """ O /|\\ / """, """ O /|\\ / \\ """, """ +---+ | | O | /|\\ | / \\ | | ========= """] var score = 0 { didSet { scoreLabel.text = "Score: \(score)" } } override func loadView() { view = UIView() view.backgroundColor = .white scoreLabel = UILabel() scoreLabel.translatesAutoresizingMaskIntoConstraints = false scoreLabel.textAlignment = .right scoreLabel.text = "Score: 0" view.addSubview(scoreLabel) cluesLabel = UILabel() cluesLabel.translatesAutoresizingMaskIntoConstraints = false cluesLabel.font = UIFont.systemFont(ofSize: 100) cluesLabel.text = "" cluesLabel.textAlignment = .center cluesLabel.numberOfLines = 0 cluesLabel.setContentHuggingPriority(UILayoutPriority(1), for: .vertical) view.addSubview(cluesLabel) hangManLabel = UILabel() hangManLabel.translatesAutoresizingMaskIntoConstraints = false hangManLabel.font = UIFont.systemFont(ofSize: 50) hangManLabel.text = hangMan[0] hangManLabel.textAlignment = .center hangManLabel.numberOfLines = 0 hangManLabel.lineBreakMode = .byClipping hangManLabel.minimumScaleFactor = 0.5 hangManLabel.adjustsFontSizeToFitWidth = true hangManLabel.setContentHuggingPriority(UILayoutPriority(1), for: .vertical) view.addSubview( hangManLabel) currentAnswer = UITextField() currentAnswer.translatesAutoresizingMaskIntoConstraints = false currentAnswer.placeholder = "Choose a letter" currentAnswer.textAlignment = .center currentAnswer.font = UIFont.systemFont(ofSize: 60) currentAnswer.isUserInteractionEnabled = false view.addSubview(currentAnswer) let submit = UIButton(type: .system) submit.translatesAutoresizingMaskIntoConstraints = false submit.setTitle("SUBMIT", for: .normal) submit.addTarget(self, action: #selector(submitTapped), for: .touchUpInside) view.addSubview(submit) let clear = UIButton(type: .system) clear.translatesAutoresizingMaskIntoConstraints = false clear.setTitle("CLEAR", for: .normal) clear.addTarget(self, action: #selector(clearTapped), for: .touchUpInside) view.addSubview(clear) let buttonsView = UIView() buttonsView.layer.borderWidth = 1 buttonsView.layer.borderColor = UIColor.lightGray.cgColor buttonsView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(buttonsView) NSLayoutConstraint.activate([ scoreLabel.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor), scoreLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor), cluesLabel.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: -50), cluesLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), cluesLabel.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -800), hangManLabel.topAnchor.constraint(equalTo: cluesLabel.bottomAnchor, constant: -100), hangManLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), currentAnswer.centerXAnchor.constraint(equalTo: view.centerXAnchor), currentAnswer.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5), currentAnswer.topAnchor.constraint(equalTo: hangManLabel.bottomAnchor, constant: 20), submit.topAnchor.constraint(equalTo: currentAnswer.bottomAnchor), submit.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -100), submit.heightAnchor.constraint(equalToConstant: 44), clear.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 100), clear.centerYAnchor.constraint(equalTo: submit.centerYAnchor), clear.heightAnchor.constraint(equalToConstant: 44), buttonsView.widthAnchor.constraint(equalToConstant: 850), buttonsView.heightAnchor.constraint(equalToConstant: 320), buttonsView.centerXAnchor.constraint(equalTo: view.centerXAnchor), buttonsView.topAnchor.constraint(equalTo: submit.bottomAnchor, constant: 20), buttonsView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -20) ]) let width = 120 let height = 80 let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] for row in 0..<5 { for col in 0..<7 { let letterButton = UIButton(type: .system) letterButton.titleLabel?.font = UIFont.systemFont(ofSize: 36) letterButton.setTitle("", for: .normal) letterButton.addTarget(self, action: #selector(letterTapped), for: .touchUpInside) let frame = CGRect(x: col * width, y: row * height, width: width, height: height) letterButton.frame = frame buttonsView.addSubview(letterButton) letterButtons.append(letterButton) } } for i in 0 ..< 32 { if i >= alphabet.count { letterButtons[i].setTitle("", for: .normal) } else { letterButtons[i].setTitle(alphabet[i], for: .normal) } } } override func viewDidLoad() { super.viewDidLoad() if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") { if let startWords = try? String(contentsOf: startWordsURL) { allWords = startWords.components(separatedBy: "\n") } } startGame() } func startGame() { cluesLabel.text! = "" hangManLabel.text = hangMan[0] score = 0 hangManIndex = 0 for btn in letterButtons { btn.isHidden = false } if !letterArray.isEmpty { letterArray.removeAll(keepingCapacity: true) } if !correctLetters.isEmpty { correctLetters.removeAll(keepingCapacity: true) } let word = allWords.randomElement()!.map { String($0) } letterArray = Array(word) print(letterArray) for _ in letterArray { cluesLabel.text! += "?" } } @objc func clearTapped(_ sender: UIButton) { currentAnswer.text = "" for btn in activatedButtons { btn.isHidden = false } activatedButtons.removeAll() } @objc func submitTapped(_ sender: UIButton) { if currentAnswer.text == "" { let ac = UIAlertController(title: "Please select a letter!", message: nil, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Retry", style: .default, handler: nil)) present(ac, animated: true) return } guard let answerText = currentAnswer.text else { return } var letterArray2 = letterArray for i in 0..<letterArray.count { if letterArray[i] == answerText { letterArray2[i] = answerText correctLetters.append(answerText) activatedButtons.removeAll() score += 1 } else { if !correctLetters.contains(letterArray2[i]) { letterArray2[i] = "?" activatedButtons.removeAll() } if ((!letterArray.contains(answerText)) && (i == letterArray.count - 1)) { hangManIndex += 1 if hangManIndex == 7 { let ac = UIAlertController(title: "You lost!!!!", message: nil, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Retry", style: .default, handler: restartGame)) present(ac, animated: true) } hangManLabel.text = hangMan[hangManIndex] let ac = UIAlertController(title: "Incorrect!", message: "Please enter a different letter.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Retry", style: .default, handler: nil)) present(ac, animated: true) score -= 1 } } } cluesLabel.text = letterArray2.joined() currentAnswer.text = "" if letterArray.joined() == letterArray2.joined() { let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next word?", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Let's go!", style: .default, handler: restartGame)) present(ac, animated: true) } } @objc func letterTapped(_ sender: UIButton) { guard let buttonTitle = sender.titleLabel?.text else { return } if !currentAnswer.text!.isEmpty { return } currentAnswer.text = currentAnswer.text?.appending(buttonTitle) activatedButtons.append(sender) sender.alpha = 0.3 } func restartGame(action: UIAlertAction) { startGame() } } <file_sep># Milestone-Project-3 100 Days of Swift (Milestone Project 3) A hangman game using UIKit. Challenge: This is the first challenge that involves you creating a game. You’ll still be using UIKit, though, so it’s a good chance to practice your app skills too. The challenge is this: make a hangman game using UIKit. As a reminder, this means choosing a random word from a list of possibilities, but presenting it to the user as a series of underscores. So, if your word was “RHYTHM” the user would see “??????”. The user can then guess letters one at a time: if they guess a letter that it’s in the word, e.g. H, it gets revealed to make “?H??H?”; if they guess an incorrect letter, they inch closer to death. If they seven incorrect answers they lose, but if they manage to spell the full word before that they win. ![ezgif-3-e4cbe30647c2](https://user-images.githubusercontent.com/42749527/105552024-60fc4d80-5cd1-11eb-9642-1644aaae7e1b.gif)
f1b65d616877e019353830dbe9ddaa72374caca5
[ "Swift", "Markdown" ]
2
Swift
CarmenMorado/Milestone-Project-3
287c044e2fb77352f6448fef15be1efd3166089b
cb7d135cc68b267136491d0a8129c317ec76f177
refs/heads/master
<file_sep>package com.karthik.rest.webservices.restfulwebservices.user; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Component; @Component public class UserDaoService { private static List<User> users = new ArrayList<>(); static { users.add(new User(1,"Karthi", new Date())); users.add(new User(2,"Karthi", new Date())); users.add(new User(3,"Karthi", new Date())); } public List<User> findAll(){ return users; } public User findOne(int uid){ for(User user:users) { if(user.getUid()==uid) { return user; } } return null; } } <file_sep>package com.karthik.rest.webservices.restfulwebservices; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.karthik.rest.webservices.restfulwebservices.user.User; import com.karthik.rest.webservices.restfulwebservices.user.UserDaoService; @RestController public class HelloWorldController { @Autowired private UserDaoService service; @GetMapping("/HelloWorld") public String helloWorld() { return "HelloWorld"; } @GetMapping("/users") public List<User> allUsers() { return service.findAll(); } @GetMapping("/user/{uid}") public User oneUser(@PathVariable int uid) { return service.findOne(uid); } }
dbda1f6ca717169a47414119dcd15ddb65433ff9
[ "Java" ]
2
Java
ekarthikeyan/spring-web-services
173a54841a2cfeebc8d3c31d1ef1f750797b1291
d8863362800e3e97b90499a123a32dd677482d99
refs/heads/master
<file_sep>package com.example.helloworld; import android.content.Context; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.hardware.Sensor; import android.hardware.SensorManager; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements SensorEventListener { public boolean flag = false; private static final String FILENAME = "accData.txt"; private TextView xAccTxt, yAccTxt, zAccTxt, prompt; private Sensor accelerometerSensor, gyroscopeSensor; private SensorManager SM; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button sBtn = findViewById(R.id.startBtn); Button endBtn = findViewById(R.id.stopBtn); // Create out sensor maneger SM = (SensorManager) getSystemService(SENSOR_SERVICE); // Accelerometer sensor accelerometerSensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // Gyroscope sensor gyroscopeSensor = SM.getDefaultSensor(Sensor.TYPE_GYROSCOPE); // Register Accelerometer sensor listener SM.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL); // Register Gyroscope sensor listener SM.registerListener(this, gyroscopeSensor, SensorManager.SENSOR_DELAY_NORMAL); // Assign TextView xAccTxt = (TextView) findViewById(R.id.xAcc); yAccTxt = (TextView) findViewById(R.id.yAcc); zAccTxt = (TextView) findViewById(R.id.zAcc); prompt = (TextView) findViewById(R.id.prompt); } @Override public void onSensorChanged(SensorEvent sensorEvent) { Sensor sensor = sensorEvent.sensor; if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) { xAccTxt.setText("X : " + sensorEvent.values[0]); yAccTxt.setText("Z : " + sensorEvent.values[1]); zAccTxt.setText("Z : " + sensorEvent.values[2]); if (this.flag) { Point point; // assign values to db try{ point = new Point(-1,sensorEvent.values[0],sensorEvent.values[1] , sensorEvent.values[2],false); Log.d("Object is : " , String.valueOf(point)); }catch (Exception e){ Toast.makeText(this, "Error making the object", Toast.LENGTH_SHORT).show(); point = new Point(-1,0,0 , 0,false); } DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this); boolean success = dataBaseHelper.addRecord(point); } else { } } } @Override public void onAccuracyChanged(Sensor sensor, int i) { // not in use } public void startRecording(View view) { this.flag = true; prompt.setText("Capturing stream ..."); } public void stopRecording(View view) { this.flag = false; Point point; point = new Point(-1,0,0 , 0,true); DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this); boolean success = dataBaseHelper.addRecord(point); prompt.setText(""); Toast.makeText(this, "Stream Captured Successfully", Toast.LENGTH_SHORT).show(); } }
d1180564b14f7376a4e424ac1039189367e2f828
[ "Java" ]
1
Java
AbdelrahmanAbdullah451/GPTask2
3edad4cc332a9d7a8e424a6d006e39cb8b452269
96764b4d0512e596ec12e2181c9a8980da89e772
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; namespace Day6 { class Program { static string _FILE = "sample.csv"; static ArrayList read = new ArrayList(); static SortedDictionary<string, List<string>> suborbital = new SortedDictionary<string, List<string>>(); static SortedDictionary<string, int> subSuborbital = new SortedDictionary<string, int>(); static void Main(string[] args) { Stopwatch tmr = new Stopwatch(); tmr.Start(); Read_Input(); Parse_Input(); Collect_Obj_Orbit_Count(); Print_Direct_Orbits(); //Answer #1 - 103697 - too low //Answer #2 - 107946 - too high int direct = Calculate_Direct_Orbits(); int indirect = Calculate_Indirect_Orbits(); Console.WriteLine("Total Direct: {0} | Total Indirect orbits: {1} | Total overall: {2}", direct, indirect, direct + indirect); Console.WriteLine(); Display_Runtime(tmr); } private static void Print_Direct_Orbits() { int total = 0; foreach (KeyValuePair<string, int> item in subSuborbital) { total += item.Value; } Console.WriteLine(total); } private static int Calculate_Indirect_Orbits() { int total = 0; foreach (KeyValuePair<string, List<string>> item in suborbital) { List<string> te = item.Value; total += TraverseOrbits(te); } return total; } private static int TraverseOrbits(List<string> key) { int orb = 1; foreach (string item in key) { if (suborbital.ContainsKey(item)) { orb += TraverseOrbits(suborbital[item]); } else { orb++; } } return orb; } private static int Calculate_Direct_Orbits() { int total = 0; foreach (KeyValuePair<string, List<string>> item in suborbital) { List<string> te = item.Value; total += te.Count; } return total; } private static void Display_Runtime(Stopwatch tmr) { Console.WriteLine(string.Format("{0,-20}:{1,22}", "Days", tmr.Elapsed.Days)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Hours", tmr.Elapsed.Hours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Minutes", tmr.Elapsed.Minutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Seconds", tmr.Elapsed.Seconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Milliseconds", tmr.Elapsed.Milliseconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Ticks", tmr.Elapsed.Ticks)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalDays", tmr.Elapsed.TotalDays)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalHours", tmr.Elapsed.TotalHours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMinutes", tmr.Elapsed.TotalMinutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalSeconds", tmr.Elapsed.TotalSeconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMilliseconds", tmr.Elapsed.TotalMilliseconds)); } private static int[] GetIntArray(int num) { List<int> listOfInts = new List<int>(); while (num > 0) { listOfInts.Add(num % 10); num = num / 10; } //listOfInts.Reverse(); return listOfInts.ToArray(); } static void Read_Input() { using (StreamReader reader = new StreamReader(Path.GetFullPath(_FILE))) { while (!reader.EndOfStream) { read.Add(reader.ReadLine()); } } } static void Collect_Obj_Orbit_Count() { foreach (string item in read) { string[] obj = item.Split(')'); //split on the orbit delimiter foreach (string planet in obj) { if (!subSuborbital.ContainsKey(planet)) { subSuborbital.Add(planet, 1); } else { subSuborbital[planet]++; } } } } static void Parse_Input() { foreach (string item in read) { string[] obj = item.Split(')'); //split on the orbit delimiter if (!suborbital.ContainsKey(obj[0])) { suborbital.Add(obj[0], new List<string>() { obj[1] }); } else { List<string> temp = suborbital[obj[0]]; temp.Add(obj[1]); suborbital[obj[0]] = temp; } } } } } <file_sep>using System; using System.Collections; using System.IO; namespace Day2 { class Program { static string _FILE = "input.csv"; static int _EXPECTED = 19690720; static int[] INITIAL_OPCODE; static int[] WORKING_OPCODE; static ArrayList read = new ArrayList(); static void Main(string[] args) { Parse_Input(); Parse_Opcode_Int(); //Calculate_P1(); Calculate_P2(out int noun, out int verb); Console.WriteLine("Final value: {0}", (100 * noun) + verb); Console.ReadLine(); } private static void Calculate_P1() { WORKING_OPCODE = INITIAL_OPCODE; WORKING_OPCODE[1] = 12; WORKING_OPCODE[2] = 2; Calculate_Results(); Console.WriteLine(string.Format("Position 0 value: {0}", WORKING_OPCODE[0].ToString())); } private static void Calculate_P2(out int noun, out int verb) { bool quit = false; noun = 0; verb = 0; for (int i = 0; i <= 99; i++) { if (!quit) { for (int j = 0; j <= 99; j++) { if (!quit) { WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); WORKING_OPCODE[1] = i; WORKING_OPCODE[2] = j; Calculate_Results(); Console.WriteLine(string.Format("WORKING OPCODE | NOUN: {0} | VERB: {1} | Calc. value: {2}", WORKING_OPCODE[1], WORKING_OPCODE[2], WORKING_OPCODE[0])); if (WORKING_OPCODE[0].Equals(_EXPECTED)) { Console.WriteLine(string.Format("Found expected value!")); noun = WORKING_OPCODE[1]; verb = WORKING_OPCODE[2]; Console.WriteLine(string.Format("NOUN: {0} | VERB: {1}", noun, verb)); quit = true; } } else { break; } } } else { break; } } } private static void Calculate_Results() { bool quit = false; for (int i = 0; i < WORKING_OPCODE.Length; i += 4) { if (!quit) { int pos1_Loc = 0, pos1_Val = 0, pos2_Loc = 0, pos2_Val = 0, result_Loc = 0, result_Val = 0; switch (WORKING_OPCODE[i]) { case 1: //ADD pos1_Loc = WORKING_OPCODE[i + 1]; pos1_Val = WORKING_OPCODE[pos1_Loc]; pos2_Loc = WORKING_OPCODE[i + 2]; pos2_Val = WORKING_OPCODE[pos2_Loc]; result_Loc = WORKING_OPCODE[i + 3]; result_Val = pos1_Val + pos2_Val; WORKING_OPCODE[result_Loc] = result_Val; break; case 2: //MULTIPLY pos1_Loc = WORKING_OPCODE[i + 1]; pos1_Val = WORKING_OPCODE[pos1_Loc]; pos2_Loc = WORKING_OPCODE[i + 2]; pos2_Val = WORKING_OPCODE[pos2_Loc]; result_Loc = WORKING_OPCODE[i + 3]; result_Val = pos1_Val * pos2_Val; WORKING_OPCODE[result_Loc] = result_Val; break; case 99: //HALT //Console.WriteLine(string.Format("HALTING @ INDEX [{0}]", i)); quit = true; break; default: //UNKNOWN Console.WriteLine(string.Format("BAD CASE! | Index: [{0}] | Value: [{1}]", i, WORKING_OPCODE[i])); break; } } } } private static void Parse_Opcode_Int() { string[] str_opcode = read[0].ToString().Split(','); INITIAL_OPCODE = new int[str_opcode.Length]; for (int i = 0; i < str_opcode.Length; i++) { INITIAL_OPCODE[i] = int.Parse(str_opcode[i]); } } static void Parse_Input() { using (StreamReader reader = new StreamReader(Path.GetFullPath(_FILE))) { while (!reader.EndOfStream) { read.Add(reader.ReadLine()); } } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; namespace Day4 { class Program { static string _FILE = "input.csv"; static ArrayList read = new ArrayList(); static List<int> all_Num = new List<int>(); static List<int> regex_Num = new List<int>(); static List<int> less_Regex_Num = new List<int>(); static List<int> char_Num = new List<int>(); static List<int> final_Nums = new List<int>(); static Dictionary<int, Dictionary<int, int>> occs = new Dictionary<int, Dictionary<int, int>>(); static int _LOWER_BOUND = 136760; static int _UPPER_BOUND = 595730; static void Main(string[] args) { Stopwatch tmr = new Stopwatch(); tmr.Start(); //Read_Input(); //Parse_Input(); Store_Numbers(); Match_Regex_Incr_Digits(); Create_Dict(); Iterate_Dict(); Examine_Dict(); Console.WriteLine(final_Nums.Count); //Console.WriteLine(Match_Regex_Incr_Digits()); //Console.WriteLine(Match_Char_Incr_Digits()); Console.WriteLine(); Display_Runtime(tmr); } private static void Examine_Dict() { foreach (KeyValuePair<int, Dictionary<int, int>> entry in occs) { bool hasRepeat = false; Dictionary<int, int> val = entry.Value; for (int i = 0; i < 10; i++) { if (val[i] == 2) { hasRepeat = true; break; } } if (hasRepeat) final_Nums.Add(entry.Key); } } private static int[] GetIntArray(int num) { List<int> listOfInts = new List<int>(); while (num > 0) { listOfInts.Add(num % 10); num = num / 10; } listOfInts.Reverse(); return listOfInts.ToArray(); } private static void Iterate_Dict() { foreach (int item in regex_Num) { int[] digits = GetIntArray(item); //136760 foreach (int number in digits) { Dictionary<int, int> val = occs[item]; val[number]++; } } } private static void Create_Dict() { foreach (int item in regex_Num) { Dictionary<int, int> digits = new Dictionary<int, int> { { 0, 0 }, { 1, 0 }, { 2, 0 }, { 3, 0 }, { 4, 0 }, { 5, 0 }, { 6, 0 }, { 7, 0 }, { 8, 0 }, { 9, 0 }, }; occs.Add(item, digits); }; } private static int Match_Regex_Incr_Digits() { string pattern = @"^(?=\d{6}$)1*2*3*4*5*6*7*8*9*$"; Regex reg = new Regex(pattern); foreach (int item in all_Num) { if (reg.IsMatch(item.ToString())) { regex_Num.Add(item); } } return regex_Num.Count; } private static bool HasDouble(char[] chars, out int position) { bool check = false; position = -1; for (int i = 0; i < chars.Length - 1; i++) { if (chars[i] == chars[i + 1]) { check = true; position = i; break; } } return check; } private static int Match_Char_Incr_Digits() { foreach (int item in all_Num) { bool nope = false; char[] chars = item.ToString().ToCharArray(); //136778 if (chars[0] <= chars[1] && chars[1] <= chars[2] && chars[2] <= chars[3] && chars[3] <= chars[4] && chars[4] <= chars[5]) { char_Num.Add(item); } } return char_Num.Count; } private static void Store_Numbers() { for (int i = _LOWER_BOUND; i <= _UPPER_BOUND; i++) { all_Num.Add(i); } } private static void Display_Runtime(Stopwatch tmr) { Console.WriteLine(string.Format("{0,-20}:{1,22}", "Days", tmr.Elapsed.Days)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Hours", tmr.Elapsed.Hours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Minutes", tmr.Elapsed.Minutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Seconds", tmr.Elapsed.Seconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Milliseconds", tmr.Elapsed.Milliseconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Ticks", tmr.Elapsed.Ticks)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalDays", tmr.Elapsed.TotalDays)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalHours", tmr.Elapsed.TotalHours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMinutes", tmr.Elapsed.TotalMinutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalSeconds", tmr.Elapsed.TotalSeconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMilliseconds", tmr.Elapsed.TotalMilliseconds)); } static void Read_Input() { using (StreamReader reader = new StreamReader(Path.GetFullPath(_FILE))) { while (!reader.EndOfStream) { read.Add(reader.ReadLine()); } } } static void Parse_Input() { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; namespace Day5 { class Program { static string _FILE = "input.csv"; static ArrayList read = new ArrayList(); static int _EXPECTED = 19690720; static int _WORKING_VAR = 5; static int[] INITIAL_OPCODE; static int[] WORKING_OPCODE; static void Main(string[] args) { Stopwatch tmr = new Stopwatch(); tmr.Start(); Read_Input(); Parse_Input(); Calculate_P1(); Calculate_P2(); Console.WriteLine(); Display_Runtime(tmr); } private static void Calculate_P1() { WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _WORKING_VAR = 1; Calculate_Results(); } private static void Calculate_P2() { WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _WORKING_VAR = 5; Calculate_Results(); } private static void Calculate_Results() { int i = 0; while (i < WORKING_OPCODE.Length) { int[] opcode = GetIntArray(WORKING_OPCODE[i]); PARAMETER_MODES[] modesy = Get_Modes(opcode); int p1_Val = -1; int p2_Val = -1; int sw_Val = opcode.Length < 3 ? WORKING_OPCODE[i] : opcode[0]; switch (sw_Val) { case 1: //ADD - DEFAULT CASE IS POSITIONAL p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val + p2_Val; i += 4; break; case 2: //MULTIPLY - DEFAULT CASE IS POSITIONAL p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val * p2_Val; i += 4; break; case 3: //INPUT - TAKE INPUT & SAVE @ ADDRESS WORKING_OPCODE[WORKING_OPCODE[i + 1]] = _WORKING_VAR; i += 2; break; case 4: //OUTPUT - TAKE VALUE @ ADDRESS & PRINT TO SCREEN Console.WriteLine(string.Format("OUTPUTTING VALUE [{0}] @ INDEX [{1}]", WORKING_OPCODE[WORKING_OPCODE[i + 1]], i + 1)); i += 2; break; case 5: //JUMP-IF-TRUE p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; if (p1_Val != 0) { p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; i = p2_Val; } else { i += 3; } break; case 6: //JUMP-IF-FALSE p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; if (p1_Val == 0) { p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; i = p2_Val; } else { i += 3; } break; case 7: //LESS THAN p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val < p2_Val ? 1 : 0; i += 4; break; case 8: //EQUIVALENCE p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val == p2_Val ? 1 : 0; i += 4; break; case 99: //HALT Console.WriteLine(string.Format("HALTING @ INDEX [{0}]", i)); i = WORKING_OPCODE.Length; break; default: //UNKNOWN Console.WriteLine(string.Format("BAD CASE! | Index: [{0}] | Value: [{1}]", i, WORKING_OPCODE[i])); i = WORKING_OPCODE.Length; break; } } } private static PARAMETER_MODES[] Get_Modes(int[] opcode) { //just always declare it a size of 5 PARAMETER_MODES[] modes = new PARAMETER_MODES[5]; switch (opcode.Length) { case 1: case 2: //opcode only modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = PARAMETER_MODES.UNKNOWN; modes[3] = PARAMETER_MODES.UNKNOWN; modes[4] = PARAMETER_MODES.UNKNOWN; break; case 3: //Opcode + 1 parameter modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = opcode[2] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[3] = PARAMETER_MODES.UNKNOWN; modes[4] = PARAMETER_MODES.UNKNOWN; break; case 4: //Opcode + 2 parameters modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = opcode[2] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[3] = opcode[3] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[4] = PARAMETER_MODES.UNKNOWN; break; case 5: //Opcode + 3 parameters modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = opcode[2] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[3] = opcode[3] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[4] = opcode[4] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; break; } return modes; } private static void Display_Runtime(Stopwatch tmr) { Console.WriteLine(string.Format("{0,-20}:{1,22}", "Days", tmr.Elapsed.Days)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Hours", tmr.Elapsed.Hours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Minutes", tmr.Elapsed.Minutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Seconds", tmr.Elapsed.Seconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Milliseconds", tmr.Elapsed.Milliseconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Ticks", tmr.Elapsed.Ticks)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalDays", tmr.Elapsed.TotalDays)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalHours", tmr.Elapsed.TotalHours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMinutes", tmr.Elapsed.TotalMinutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalSeconds", tmr.Elapsed.TotalSeconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMilliseconds", tmr.Elapsed.TotalMilliseconds)); } private static int[] GetIntArray(int num) { List<int> listOfInts = new List<int>(); while (num > 0) { listOfInts.Add(num % 10); num = num / 10; } //listOfInts.Reverse(); return listOfInts.ToArray(); } static void Read_Input() { using (StreamReader reader = new StreamReader(Path.GetFullPath(_FILE))) { while (!reader.EndOfStream) { read.Add(reader.ReadLine()); } } } static void Parse_Input() { string[] str_opcode = read[0].ToString().Split(','); INITIAL_OPCODE = new int[str_opcode.Length]; for (int i = 0; i < str_opcode.Length; i++) { INITIAL_OPCODE[i] = int.Parse(str_opcode[i]); } } enum PARAMETER_MODES { OPCODE, POSITION, IMMEDIATE, UNKNOWN } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; namespace Day3 { class Program { static string _FILE = "input.csv"; static int _ORIGIN = 24000; static int _SMALLEST_MHD = 24000; static int _SMALLEST_STEPS = 500000; static ArrayList read = new ArrayList(); static HashSet<Point> ans; static HashSet<Point> wire1_grid = new HashSet<Point>(); static HashSet<Point> wire2_grid = new HashSet<Point>(); static List<int> wire1_Steps = new List<int>(); static List<int> wire2_Steps = new List<int>(); static string[] wire1; static string[] wire2; static int wire1_U_MAX = 0, wire1_R_MAX = 0, wire1_L_MAX = 0, wire1_D_MAX = 0, wire2_U_MAX = 0, wire2_R_MAX = 0, wire2_L_MAX = 0, wire2_D_MAX = 0; static void Main(string[] args) { Stopwatch tmr = new Stopwatch(); tmr.Start(); Read_Input(); Parse_Input(); //Determine_Largest_Value(wire1, out wire1_U_MAX, out wire1_R_MAX, out wire1_D_MAX, out wire1_L_MAX); //Console.WriteLine("Wire 1 | U max: {0} | R max: {1} | D max: {2} | L max: {3}", wire1_U_MAX, wire1_R_MAX, wire1_D_MAX, wire1_L_MAX); //Determine_Largest_Value(wire2, out wire2_U_MAX, out wire2_R_MAX, out wire2_D_MAX, out wire2_L_MAX); //Console.WriteLine("Wire 2 | U max: {0} | R max: {1} | D max: {2} | L max: {3}", wire2_U_MAX, wire2_R_MAX, wire2_D_MAX, wire2_L_MAX); Plot_Grid(wire1, wire1_grid); Plot_Grid(wire2, wire2_grid); Determine_Intersects(wire1_grid, wire2_grid); Determine_Manhattan_Distance(); Calculate_Shortest_Steps(wire1, wire1_Steps); Calculate_Shortest_Steps(wire2, wire2_Steps); Determine_Fewest_Steps(); tmr.Stop(); Console.WriteLine(_SMALLEST_MHD); Console.WriteLine(_SMALLEST_STEPS); Console.WriteLine(); Display_Runtime(tmr); Console.ReadLine(); } private static void Display_Runtime(Stopwatch tmr) { Console.WriteLine(string.Format("{0,-20}:{1,22}", "Days", tmr.Elapsed.Days)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Hours", tmr.Elapsed.Hours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Minutes", tmr.Elapsed.Minutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Seconds", tmr.Elapsed.Seconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Milliseconds", tmr.Elapsed.Milliseconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Ticks", tmr.Elapsed.Ticks)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalDays", tmr.Elapsed.TotalDays)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalHours", tmr.Elapsed.TotalHours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMinutes", tmr.Elapsed.TotalMinutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalSeconds", tmr.Elapsed.TotalSeconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMilliseconds", tmr.Elapsed.TotalMilliseconds)); } private static void Determine_Fewest_Steps() { for (int i = 0; i < wire1_Steps.Count; i++) { if (wire1_Steps[i] + wire2_Steps[i] < _SMALLEST_STEPS) { _SMALLEST_STEPS = wire1_Steps[i] + wire2_Steps[i]; } } } private static void Calculate_Shortest_Steps(string[] wire, List<int> stepper) { bool quit = false; int steps = 0, gridX = _ORIGIN, gridY = _ORIGIN; foreach (Point item in ans) { Point intersectionPt = new Point(item.X, item.Y); quit = false; steps = 0; gridX = _ORIGIN; gridY = _ORIGIN; foreach (string item2 in wire) { if (!quit) { string dir = item2.Substring(0, 1); int.TryParse(item2.Substring(1, item2.Length - 1), out int dist); switch (dir.ToUpper()) { case "U": for (int i = 0; i < dist; i++) { gridY++; steps++; if (intersectionPt.Equals(new Point(gridX, gridY))) { stepper.Add(steps); quit = true; break; } } break; case "D": for (int i = 0; i < dist; i++) { gridY--; steps++; if (intersectionPt.Equals(new Point(gridX, gridY))) { stepper.Add(steps); quit = true; break; } } break; case "L": for (int i = 0; i < dist; i++) { gridX--; steps++; if (intersectionPt.Equals(new Point(gridX, gridY))) { stepper.Add(steps); quit = true; break; } } break; case "R": for (int i = 0; i < dist; i++) { gridX++; steps++; if (intersectionPt.Equals(new Point(gridX, gridY))) { stepper.Add(steps); quit = true; break; } } break; } } else { break; } } } } private static void Determine_Manhattan_Distance() { foreach (Point item in ans) { int MD = Math.Abs(item.X - _ORIGIN) + Math.Abs(item.Y - _ORIGIN); if (MD < _SMALLEST_MHD) { _SMALLEST_MHD = MD; //Console.WriteLine(string.Format("Pt 1: {0} | Pt 2: {1} | MD: {2}", x, y, _SMALLEST_MHD)); } } } private static void Determine_Intersects(HashSet<Point> grid1, HashSet<Point> grid2) { ans = new HashSet<Point>(grid1); ans.IntersectWith(grid2); // THIS CODE IS SUUUUUPER SLOW (20 mins) //for (int i = 0; i < grid1.Count; i++) //{ // for (int j = 0; j < grid2.Count; j++) // { // if (grid1[i].Equals(grid2[j])) // intersectPts.Add(grid2[j]); // } //} } private static void Plot_Grid(string[] wire, HashSet<Point> grid) { int gridX = _ORIGIN, gridY = _ORIGIN; foreach (string item in wire) { string dir = item.Substring(0, 1); int.TryParse(item.Substring(1, item.Length - 1), out int dist); switch (dir.ToUpper()) { case "U": for (int i = 0; i < dist; i++) { gridY++; grid.Add(new Point(gridX, gridY)); } break; case "D": for (int i = 0; i < dist; i++) { gridY--; grid.Add(new Point(gridX, gridY)); } break; case "L": for (int i = 0; i < dist; i++) { gridX--; grid.Add(new Point(gridX, gridY)); } break; case "R": for (int i = 0; i < dist; i++) { gridX++; grid.Add(new Point(gridX, gridY)); } break; } } } private static void Determine_Largest_Value(string[] wire, out int uMax, out int rMax, out int dMax, out int lMax) { uMax = 0; rMax = 0; dMax = 0; lMax = 0; foreach (string item in wire) { string dir = item.Substring(0, 1); int.TryParse(item.Substring(1, item.Length - 1), out int dist); switch (dir.ToUpper()) { case "U": uMax += dist; break; case "D": dMax += dist; break; case "L": lMax += dist; break; case "R": rMax += dist; break; } } } static void Read_Input() { using (StreamReader reader = new StreamReader(Path.GetFullPath(_FILE))) { while (!reader.EndOfStream) { read.Add(reader.ReadLine()); } } } static void Parse_Input() { wire1 = read[0].ToString().Split(','); wire2 = read[1].ToString().Split(','); } } } <file_sep>using System; using System.Collections; using System.IO; namespace Day1 { class Program { static ArrayList lines = new ArrayList(); static ArrayList mass = new ArrayList(); static int _TOTAL_FUEL = 0; static string _FILE = "input.csv"; static void Main(string[] args) { Parse_Input(); Calculate_Mass(); Calculate_Total_Fuel(); Console.WriteLine(string.Format("Total Fuel: {0}", _TOTAL_FUEL)); Console.ReadLine(); } private static void Calculate_Mass() { int fuel = 0; foreach (string item in lines) { Double.TryParse(item, out double input); while (input > 0) { fuel = Calculate_Fuel(input); if (fuel > 0) mass.Add(fuel); input = fuel; } } } private static int Calculate_Fuel(double mass) { return (int)Math.Floor(mass / 3) - 2; } private static void Calculate_Total_Fuel() { foreach (int item in mass) { _TOTAL_FUEL += item; } } static void Parse_Input() { using (StreamReader reader = new StreamReader(Path.GetFullPath(_FILE))) { while (!reader.EndOfStream) { lines.Add(reader.ReadLine()); } } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; namespace Day7 { class Program { static string _FILE = "sample.csv"; static ArrayList read = new ArrayList(); static int _LARGEST = 0; static string _LARGEST_PHASE_1 = ""; static string _LARGEST_PHASE_2 = ""; static int _PHASE = 0; static int _INPUT = 0; static int[] INITIAL_OPCODE; static int[] WORKING_OPCODE; static int[] THRUSTER_INPUT = new int[] { 01234, 01243, 01324, 01342, 01423, 01432, 02134, 02143, 02314, 02341, 02413, 02431, 03124, 03142, 03214, 03241, 03412, 03421, 04123, 04132, 04213, 04231, 04312, 04321, 10234, 10243, 10324, 10342, 10423, 10432, 12034, 12043, 12304, 12340, 12403, 12430, 13024, 13042, 13204, 13240, 13402, 13420, 14023, 14032, 14203, 14230, 14302, 14320, 20134, 20143, 20314, 20341, 20413, 20431, 21034, 21043, 21304, 21340, 21403, 21430, 23014, 23041, 23104, 23140, 23401, 23410, 24013, 24031, 24103, 24130, 24301, 24310, 30124, 30142, 30214, 30241, 30412, 30421, 31024, 31042, 31204, 31240, 31402, 31420, 32014, 32041, 32104, 32140, 32401, 32410, 34012, 34021, 34102, 34120, 34201, 34210, 40123, 40132, 40213, 40231, 40312, 40321, 41023, 41032, 41203, 41230, 41302, 41320, 42013, 42031, 42103, 42130, 42301, 42310, 43012, 43021, 43102, 43120, 43201, 43210 }; static int[] THRUSTER_INPUT_2 = new int[] { 56789, 56798, 56879, 56897, 56978, 56987, 57689, 57698, 57869, 57896, 57968, 57986, 58679, 58697, 58769, 58796, 58967, 58976, 59678, 59687, 59768, 59786, 59867, 59876, 65789, 65798, 65879, 65897, 65978, 65987, 67589, 67598, 67859, 67895, 67958, 67985, 68579, 68597, 68759, 68795, 68957, 68975, 69578, 69587, 69758, 69785, 69857, 69875, 75689, 75698, 75869, 75896, 75968, 75986, 76589, 76598, 76859, 76895, 76958, 76985, 78569, 78596, 78659, 78695, 78956, 78965, 79568, 79586, 79658, 79685, 79856, 79865, 85679, 85697, 85769, 85796, 85967, 85976, 86579, 86597, 86759, 86795, 86957, 86975, 87569, 87596, 87659, 87695, 87956, 87965, 89567, 89576, 89657, 89675, 89756, 89765, 95678, 95687, 95768, 95786, 95867, 95876, 96578, 96587, 96758, 96785, 96857, 96875, 97568, 97586, 97658, 97685, 97856, 97865, 98567, 98576, 98657, 98675, 98756, 98765 }; static void Main(string[] args) { Stopwatch tmr = new Stopwatch(); tmr.Start(); Read_Input(); Parse_Input(); //Calculate_P1(); Calculate_P2(); Console.WriteLine(); Display_Runtime(tmr); } private static void Calculate_P1() { int A_AMP = 0, B_AMP = 0, C_AMP = 0, D_AMP = 0, E_AMP = 0; for (int i = 0; i < THRUSTER_INPUT.Length; i++) { int[] digits = GetDigits(THRUSTER_INPUT[i]); WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _PHASE = digits[0]; //PHASE SETTING _INPUT = 0; //INPUT (A = 0) A_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER A --> INPUT FOR AMPLIFIER B WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _PHASE = digits[1]; //PHASE SETTING _INPUT = A_AMP; //INPUT FROM A OUTPUT B_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER B --> INPUT FOR AMPLIFIER C WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _PHASE = digits[2]; //PHASE SETTING _INPUT = B_AMP; //INPUT FROM B OUTPUT C_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER C --> INPUT FOR AMPLIFIER D WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _PHASE = digits[3]; //PHASE SETTING _INPUT = C_AMP; //INPUT FROM C OUTPUT D_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER D --> INPUT FOR AMPLIFIER E WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _PHASE = digits[4]; //PHASE SETTING _INPUT = D_AMP; //INPUT FROM D OUTPUT E_AMP = Calculate_Results(); Console.WriteLine("FINAL OUTPUT SIGNAL FROM E AMPLIFIER: {0}", E_AMP); if (E_AMP > _LARGEST) { _LARGEST = E_AMP; _LARGEST_PHASE_1 = THRUSTER_INPUT[i].ToString().Length == 4 ? string.Concat("0", THRUSTER_INPUT[i].ToString()) : THRUSTER_INPUT[i].ToString(); } } Console.WriteLine("HIGHEST THRUST VALUE FOUND: {0} @ SETTING {1} ", _LARGEST, _LARGEST_PHASE_1); } private static void Calculate_P2() { int A_AMP = 0, B_AMP = 0, C_AMP = 0, D_AMP = 0, E_AMP = 0; bool FEEDBACK_ENABLED = false; for (int i = 0; i < THRUSTER_INPUT.Length; i++) { for (int j = 0; j < THRUSTER_INPUT_2.Length; j++) { int[] digits = GetDigits(THRUSTER_INPUT[i]); int[] digits2 = GetDigits(THRUSTER_INPUT_2[j]); WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _INPUT = FEEDBACK_ENABLED ? E_AMP : 0; //INPUT - FIRST INSTR = 0 | THEREAFTER: E_AMP _PHASE = FEEDBACK_ENABLED ? digits2[0] : digits[0]; //NORMAL OR FEEDBACK PHASE SETTING A_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER A --> INPUT FOR AMPLIFIER B WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _INPUT = A_AMP; //INPUT FROM A OUTPUT _PHASE = FEEDBACK_ENABLED ? digits2[1] : digits[1]; //NORMAL OR FEEDBACK PHASE SETTING B_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER B --> INPUT FOR AMPLIFIER C WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _INPUT = B_AMP; //INPUT FROM B OUTPUT _PHASE = FEEDBACK_ENABLED ? digits2[2] : digits[2]; //NORMAL OR FEEDBACK PHASE SETTING C_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER C --> INPUT FOR AMPLIFIER D WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _INPUT = C_AMP; //INPUT FROM C OUTPUT _PHASE = FEEDBACK_ENABLED ? digits2[3] : digits[3]; //NORMAL OR FEEDBACK PHASE SETTING D_AMP = Calculate_Results(); //OUTPUT FROM AMPLIFIER D --> INPUT FOR AMPLIFIER E WORKING_OPCODE = new int[INITIAL_OPCODE.Length]; Array.Copy(INITIAL_OPCODE, WORKING_OPCODE, INITIAL_OPCODE.Length); _INPUT = D_AMP; //INPUT FROM D OUTPUT _PHASE = FEEDBACK_ENABLED ? digits2[4] : digits[4]; //NORMAL OR FEEDBACK PHASE SETTING E_AMP = Calculate_Results(); FEEDBACK_ENABLED = true; Console.WriteLine("FINAL OUTPUT SIGNAL FROM E AMPLIFIER: {0}", E_AMP); if (E_AMP > _LARGEST) { _LARGEST = E_AMP; _LARGEST_PHASE_1 = THRUSTER_INPUT[i].ToString().Length == 4 ? string.Concat("0", THRUSTER_INPUT[i].ToString()) : THRUSTER_INPUT[i].ToString(); _LARGEST_PHASE_2 = THRUSTER_INPUT_2[j].ToString(); } } FEEDBACK_ENABLED = false; //once all the phase settings for the initial set have been iterated, reset the feedback boolean } Console.WriteLine("HIGHEST THRUST VALUE FOUND: {0} @ PH1: {1} PH2: {2}", _LARGEST, _LARGEST_PHASE_1, _LARGEST_PHASE_2); } private static int Calculate_Results() { bool PHASE_READ = false; int OUTPUT = -1; int i = 0; while (i < WORKING_OPCODE.Length) { int[] opcode = GetIntArray(WORKING_OPCODE[i]); PARAMETER_MODES[] modesy = Get_Modes(opcode); int p1_Val = -1; int p2_Val = -1; int sw_Val = opcode.Length < 3 ? WORKING_OPCODE[i] : opcode[0]; switch (sw_Val) { case 1: //ADD - DEFAULT CASE IS POSITIONAL p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val + p2_Val; i += 4; break; case 2: //MULTIPLY - DEFAULT CASE IS POSITIONAL p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val * p2_Val; i += 4; break; case 3: //INPUT - TAKE INPUT & SAVE @ ADDRESS if (!PHASE_READ) { WORKING_OPCODE[WORKING_OPCODE[i + 1]] = _PHASE; PHASE_READ = true; } else WORKING_OPCODE[WORKING_OPCODE[i + 1]] = _INPUT; i += 2; break; case 4: //OUTPUT - TAKE VALUE @ ADDRESS & PRINT TO SCREEN OUTPUT = WORKING_OPCODE[WORKING_OPCODE[i + 1]]; Console.WriteLine(string.Format("OUTPUTTING VALUE [{0}] @ INDEX [{1}]", OUTPUT, i + 1)); i += 2; break; case 5: //JUMP-IF-TRUE p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; if (p1_Val != 0) { p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; i = p2_Val; } else { i += 3; } break; case 6: //JUMP-IF-FALSE p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; if (p1_Val == 0) { p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; i = p2_Val; } else { i += 3; } break; case 7: //LESS THAN p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val < p2_Val ? 1 : 0; i += 4; break; case 8: //EQUIVALENCE p1_Val = modesy[2] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 1] : WORKING_OPCODE[WORKING_OPCODE[i + 1]]; p2_Val = modesy[3] == PARAMETER_MODES.IMMEDIATE ? WORKING_OPCODE[i + 2] : WORKING_OPCODE[WORKING_OPCODE[i + 2]]; WORKING_OPCODE[WORKING_OPCODE[i + 3]] = p1_Val == p2_Val ? 1 : 0; i += 4; break; case 99: //HALT Console.WriteLine(string.Format("HALTING @ INDEX [{0}]", i)); i = WORKING_OPCODE.Length; break; default: //UNKNOWN Console.WriteLine(string.Format("BAD CASE! | Index: [{0}] | Value: [{1}]", i, WORKING_OPCODE[i])); i = WORKING_OPCODE.Length; break; } } return OUTPUT; } private static PARAMETER_MODES[] Get_Modes(int[] opcode) { //just always declare it a size of 5 PARAMETER_MODES[] modes = new PARAMETER_MODES[5]; switch (opcode.Length) { case 1: case 2: //opcode only modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = PARAMETER_MODES.UNKNOWN; modes[3] = PARAMETER_MODES.UNKNOWN; modes[4] = PARAMETER_MODES.UNKNOWN; break; case 3: //Opcode + 1 parameter modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = opcode[2] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[3] = PARAMETER_MODES.UNKNOWN; modes[4] = PARAMETER_MODES.UNKNOWN; break; case 4: //Opcode + 2 parameters modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = opcode[2] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[3] = opcode[3] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[4] = PARAMETER_MODES.UNKNOWN; break; case 5: //Opcode + 3 parameters modes[0] = PARAMETER_MODES.OPCODE; modes[1] = PARAMETER_MODES.OPCODE; modes[2] = opcode[2] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[3] = opcode[3] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; modes[4] = opcode[4] == 1 ? PARAMETER_MODES.IMMEDIATE : PARAMETER_MODES.POSITION; break; } return modes; } private static void Display_Runtime(Stopwatch tmr) { Console.WriteLine(string.Format("{0,-20}:{1,22}", "Days", tmr.Elapsed.Days)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Hours", tmr.Elapsed.Hours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Minutes", tmr.Elapsed.Minutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Seconds", tmr.Elapsed.Seconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Milliseconds", tmr.Elapsed.Milliseconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "Ticks", tmr.Elapsed.Ticks)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalDays", tmr.Elapsed.TotalDays)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalHours", tmr.Elapsed.TotalHours)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMinutes", tmr.Elapsed.TotalMinutes)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalSeconds", tmr.Elapsed.TotalSeconds)); Console.WriteLine(string.Format("{0,-20}:{1,22}", "TotalMilliseconds", tmr.Elapsed.TotalMilliseconds)); } private static int[] GetDigits(int num) { List<int> listOfInts = new List<int>(); while (num > 0) { listOfInts.Add(num % 10); num = num / 10; } listOfInts.Reverse(); //add leading 0 if (listOfInts.Count.Equals(4)) { List<int> fiveDigits = new List<int>(5); fiveDigits.Add(0); fiveDigits.Add(listOfInts[0]); fiveDigits.Add(listOfInts[1]); fiveDigits.Add(listOfInts[2]); fiveDigits.Add(listOfInts[3]); listOfInts = fiveDigits; } return listOfInts.ToArray(); } private static int[] GetIntArray(int num) { List<int> listOfInts = new List<int>(); while (num > 0) { listOfInts.Add(num % 10); num = num / 10; } //listOfInts.Reverse(); return listOfInts.ToArray(); } static void Read_Input() { using (StreamReader reader = new StreamReader(Path.GetFullPath(_FILE))) { while (!reader.EndOfStream) { read.Add(reader.ReadLine()); } } } static void Parse_Input() { string[] str_opcode = read[0].ToString().Split(','); INITIAL_OPCODE = new int[str_opcode.Length]; for (int i = 0; i < str_opcode.Length; i++) { INITIAL_OPCODE[i] = int.Parse(str_opcode[i]); } } enum PARAMETER_MODES { OPCODE, POSITION, IMMEDIATE, UNKNOWN } } }
b8547a3aa7a6daeb74a2c9b34d34ea375542cb8f
[ "C#" ]
7
C#
duffym22/AOC_2019
8a74c3b57d9b8b331ab6235b7b55821c2ce511ac
468cdcfa64d9f30b37b7aa4a08800328f1fa0ccc
refs/heads/master
<repo_name>s628/report0809<file_sep>/report0809/src/sec01/ex01/OrderVO.java package sec01.ex01; import java.sql.Date; public class OrderVO { private String Order_num; private String Order_item; private String Prod_id; private String Prod_name; private String Quantity; private String Item_price; public String getOrder_num() { return Order_num; } public void setOrder_num(String order_num) { Order_num = order_num; } public String getOrder_item() { return Order_item; } public void setOrder_item(String order_item) { Order_item = order_item; } public String getProd_id() { return Prod_id; } public void setProd_id(String prod_id) { Prod_id = prod_id; } public String getProd_name() { return Prod_name; } public void setProd_name(String prod_name) { Prod_name = prod_name; } public String getQuantity() { return Quantity; } public void setQuantity(String quantity) { Quantity = quantity; } public String getItem_price() { return Item_price; } public void setItem_price(String item_price) { Item_price = item_price; } public OrderVO() { System.out.println("MemberVO 생성자 호출"); } }
e6e2bec055f8c8507654608f00d0a84fce202376
[ "Java" ]
1
Java
s628/report0809
3eae81a92772f6f8de44002b1e397b14b60f6d2e
38f96191c1c1077102c1c5a8a8a410b88abebdcf
refs/heads/master
<file_sep>from google.colab import auth from googleapiclient.http import MediaFileUpload from googleapiclient.discovery import build from google.colab import drive import os from IPython.display import HTML, display def restart_runtime(): os.kill(os.getpid(), 9) def save_to_drive(local_path, drive_path): auth.authenticate_user() drive_service = build('drive', 'v3') file_metadata = { 'name': drive_path, 'mimeType': 'application/octet-stream' } media = MediaFileUpload( local_path, mimetype='application/octet-stream', resumable=True ) created = drive_service.files().create( body=file_metadata, media_body=media, fields='id' ).execute() return created.get('id') def load_from_drive(drive_path, local_path): drive.mount('/content/drive') with open('/content/drive/My Drive/' + drive_path, 'rb') as f: with open(local_path, 'wb') as w: w.write(f.read()) drive.flush_and_unmount() def mount_drive(drive_path='/content/drive/'): drive.mount(drive_path) return drive_path + 'My Drive/' def colab_word_wrap(): def set_css(): display(HTML(''' <style> pre { white-space: pre-wrap; } </style> ''')) get_ipython().events.register('pre_run_cell', set_css) <file_sep>import gpt_2_simple as gpt2 import requests import os from shutil import make_archive, copyfile from zipfile import ZipFile from google_drive_downloader import GoogleDriveDownloader as gdd from google.colab import files from .utils import mount_drive class GPT2: def __init__(self, project_name, base_model): self.name = project_name self.base_model = base_model self.drive_path = '/content/drive/My Drive/' if not os.path.exists('checkpoint'): os.mkdir('checkpoint') self.check_model() def check_model(self): if not os.path.isdir(os.path.join("models", self.base_model)): gpt2.download_gpt2(model_name=self.base_model) def get_data(self, url): with open('data.txt', 'wb') as f: r = requests.get(url) f.write(r.content) def finetune(self, url, steps): self.get_data(url) sess = gpt2.start_tf_sess() gpt2.finetune( sess, 'data.txt', model_name=self.base_model, run_name=self.name, steps=steps, ) def save_to_drive(self, weights_name): self.drive_path = mount_drive() make_archive(weights_name, 'zip', 'checkpoint/' + self.name) copyfile(weights_name + '.zip', self.drive_path + weights_name + '.zip') os.remove(weights_name + '.zip') def load_from_drive(self, weights_name): self.drive_path = mount_drive() copyfile(self.drive_path + weights_name + '.zip', weights_name + '.zip') self.unpack_weights(weights_name + '.zip') def load(self, bot_name): urls = { 'shakespeare': 'https://drive.google.com/uc?export=download&id=1zvfzFcT2YsJXHNLuAmClnuMHoJuTNWyd', } bot_id = urls[bot_name].split('id=')[-1].split('&')[0] gdd.download_file_from_google_drive( file_id=bot_id, dest_path='checkpoint/' + self.name + '/temp.zip', unzip=True ) os.remove('checkpoint/' + self.name + '/temp.zip') def unpack_weights(self, filename): with ZipFile(filename, 'r') as z: z.extractall('checkpoint/' + self.name) os.remove(filename) def generate(self, prefix=None, num_samples=1, length=1023): self.check_model() args = dict( model_name=self.base_model, length=length, return_as_list=True, nsamples=num_samples, ) if prefix is not None: args['prefix'] = prefix sess = gpt2.start_tf_sess() if not os.path.exists('checkpoint/' + self.name): gpt2.load_gpt2(sess, model_name=self.base_model) else: args['run_name'] = self.name gpt2.load_gpt2(sess, run_name=self.name) output = [str(x) for x in gpt2.generate(sess, **args)] if num_samples == 1: return output[0] else: return output <file_sep>import pandas as pd import numpy as np import os import re import copy import string from toolz import sliding_window, take_nth class HierarchicalDoc(object): def __init__(self, text, patterns=None, strip_section_id=False): self.text = text self.strip_section_id = strip_section_id self.patterns = { 'Section 1.': re.compile('Section *[0-9]+\.'), '1.': re.compile('[0-9]+\. '), 'A.': re.compile('[A-Z]+\. '), '(1)': re.compile('\((\d+)\) '), '(a)': re.compile('\([a-h]+\) '), '(A)': re.compile('\([A-H]+\) '), '(i)': re.compile('\([ivx]+\) '), } if patterns is not None: self.patterns = patterns self.refresh() def get_hierarchy(self, text, patterns): h = [] for line in text.split('\n'): first_words = ' '.join(line.split()[:2]) for p in patterns: if p not in h: if patterns[p].match(first_words) is not None: h.append(p) return h def simple(self): data = self.levels data['text'] = data.apply(lambda x: x[str(x['level'])], axis=1) data = data[['level', 'section', 'text']] return data def get_levels(self, text, h, patterns, strip_section_id): data = [] current_index = [0] * len(h) index = [] row = {'level':0} for line in text.split('\n'): level = 0 for p in h: first_words = ' '.join(line.split()[:2]) m = patterns[p].match(first_words) if m is not None: if strip_section_id: clean_line = line.replace(m.group(), '').strip() else: clean_line = line level = h.index(p) + 1 data.append(copy.deepcopy(row)) index.append(copy.deepcopy(current_index)) if level <= row['level']: for k in list(row.keys()): if k not in ['level', 'section'] and int(k) > level: del row[k] row['section'] = ' / '.join(row['section'].split(' / ')[:level-1]) for i in range(level, len(current_index)): current_index[i] = 0 current_index[level - 1] += 1 if level == 1: row['section'] = m.group() else: row['section'] += ' / ' + m.group() row['level'] = level row[str(level)] = clean_line if level == 0 and row['level'] != 0: row[str(row['level'])] += '\n' + line data.append(copy.deepcopy(row)) index.append(copy.deepcopy(current_index)) index = pd.MultiIndex.from_tuples(index, names=[i+1 for i in range(len(current_index))]) data = pd.DataFrame(data, index=index) data = data[data['level'] != 0].fillna('') return data def get(self, level, ancestors=0, children=0): def apply_f(data, level, ancestors, children): cols = [x for x in data.columns if x in map(str, range(level - ancestors, level+1))] level_only = data[data['level'] == level] if len(level_only) == 0: return None text = ' '.join(level_only[cols].values[0]) data = data[data['level'].isin(range(level + 1, level + 1 + children))] for _, row in data.iterrows(): text += ' ' + row[str(row['level'])] return pd.Series({'section': level_only['section'].values[0], 'text':text}) lvl = self.levels lvl = lvl[lvl['level'] >= level] lvl = lvl.groupby(level=list(range(level))).apply(lambda x: apply_f(x, level, ancestors, children)) return lvl def get_context(self, level, min_context=0, max_context=None): if max_context is None: max_context = len(self.hierarchy) - (len(self.hierarchy) - (level - 1)) data = pd.DataFrame() for i in range(min_context, max_context+1): data = data.append(self.get(level, ancestors=i), ignore_index=True) return data def context(self, level=None, min_context=0, max_context=None): if level is None: data = pd.DataFrame() for i in range(len(self.hierarchy)): data = data.append(self.get_context(i+1), ignore_index=True) return data else: return self.get_context(level, min_context, max_context) def descriptions(self, max_length=256): data = self.context() data = data.dropna() descriptions = data[data['text'].apply(lambda x: len(x.split()) < max_length)] descriptions = descriptions.groupby('section').last().reset_index() simple = self.simple() for _, row in simple.iterrows(): if row['section'] not in descriptions['section'].values: descriptions = descriptions.append(pd.DataFrame([{ 'section': row['section'], 'text': ' '.join(row['text'].split()[:max_length]) + ' ...' }]), ignore_index=True) descriptions.columns = ['section', 'description'] return descriptions def refresh(self): self.hierarchy = self.get_hierarchy(self.text, self.patterns) self.levels = self.get_levels(self.text, self.hierarchy, self.patterns, self.strip_section_id) <file_sep>from models import FaceTranslationGANInferenceModel from face_toolbox_keras.models.verifier.face_verifier import FaceVerifier from face_toolbox_keras.models.parser import face_parser from face_toolbox_keras.models.detector import face_detector from face_toolbox_keras.models.detector.iris_detector import IrisDetector import face_recognition from matplotlib import pyplot as plt from IPython.display import clear_output import numpy as np import os import cv2 from utils import utils from google.colab import auth from google.colab import files import warnings from .utils import save_to_drive from .video import VideoEditor warnings.filterwarnings("ignore") class StyleGAN: def __init__(self): self.model = FaceTranslationGANInferenceModel() self.fv = FaceVerifier(classes=512) self.fp = face_parser.FaceParser() self.fd = face_detector.FaceAlignmentDetector() self.idet = IrisDetector() self.people = {} self.files = {} def add_person(self, name, paths=[], urls=[]): if len(paths) > 0: filenames = paths elif len(urls) > 0: filenames = [] for url in urls: os.system('wget ' + url) filenames.append(url.split('/')[-1]) else: filenames = [k for k,v in files.upload().items()] face, embedding = utils.get_tar_inputs(filenames, self.fd, self.fv) img = cv2.imread(filenames[0]) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) bounding_boxes = face_recognition.face_locations(img) encs = face_recognition.face_encodings(img, bounding_boxes) self.people[name] = { 'images': filenames, 'face': face, 'embedding': embedding, 'rec_enc': encs[0] } def add_file(self, name, url=None, path=None): if path is not None: filename = path else: if url is not None: os.system('wget ' + url) filename = url.split('/')[-1] else: filename = [k for k,v in files.upload().items()][0] self.files[name] = filename def image_swap(self, filename, person): src, mask, aligned_im, (x0, y0, x1, y1), landmarks = utils.get_src_inputs(filename, self.fd, self.fp, self.idet) tar, emb_tar = self.people[person]['face'], self.people[person]['embedding'] out = self.model.inference(src, mask, tar, emb_tar) face = np.squeeze(((out[0] + 1) * 255 / 2).astype(np.uint8)) img = utils.post_process_result(filename, self.fd, face, aligned_im, src, x0, y0, x1, y1, landmarks) return face, img def image_swap2(self, img, face_map={}): bounding_boxes = face_recognition.face_locations(img) fm = {k:v for k,v in face_map.items() if k != '*'} if len(bounding_boxes) > 0: try: try: src_encs = face_recognition.face_encodings(img, bounding_boxes) tar_encs = [self.people[x]['rec_enc'] for x in fm.keys()] for i in range(len(src_encs)): bb = bounding_boxes[i] scores = face_recognition.compare_faces(tar_encs, src_encs[i]) matches = [list(fm.keys())[i] for i in range(len(scores)) if scores[i] == 1] if len(matches) == 0: if '*' in list(face_map.keys()): matches = ['*'] for match in matches: adj = int(max(img.shape) * 0.1) x1, x2 = np.max([0, bb[0] - adj]), np.min([img.shape[0], bb[2] + adj]) y1, y2 = np.max([0, bb[3] - adj]), np.min([img.shape[1], bb[1] + adj]) face_img = img[x1:x2, y1:y2] original_shape = face_img.shape face_img = self.auto_resize(face_img) cv2.imwrite('temp.jpg', face_img) face, face_img = self.image_swap('temp.jpg', face_map[match]) face_img = cv2.resize(face_img, (original_shape[1], original_shape[0])) face_img[face_img[:,:] == (0,0,0)] = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)[x1:x2, y1:y2][face_img[:,:] == (0,0,0)] img[x1:x2, y1:y2] = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB) except AssertionError as e: print(e) except Exception as e: print(e) return img def get_frame(self, filename, frame_num): cap = cv2.VideoCapture(self.files[filename]) total_frames = cap.get(7) cap.set(1, frame_num) __, img = cap.read() cv2.destroyAllWindows() return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) def video_swap(self, filename, out_path, face_map={}, frame_range=None, autosave=False): def processor(img, frame_num): if frame_range is None or (frame_num >= frame_range[0] and frame_num < frame_range[1]): img = self.image_swap2(filename, face_img) if frame_num % 300 == 0: clear_output() if frame_num % 10 == 0: plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) print('Frame:', frame_num) plt.pause(0.000000001) return img if autosave: auth.authenticate_user() editor = VideoEditor(processor) editor.process(self.files[filename], out_path) if autosave: save_to_drive(out_path, out_path) def auto_resize(self, img, max_size=740): if np.max(img.shape) > max_size: ratio = max_size / np.max(img.shape) img = cv2.resize(img, (0,0), fx=ratio, fy=ratio) return img <file_sep>import librosa import argparse import numpy as np import moviepy.editor as mpy import random import torch from scipy.misc import toimage from tqdm import tqdm from pytorch_pretrained_biggan import ( BigGAN, one_hot_from_names, truncated_noise_sample, save_as_images, display_in_terminal, ) class DeepMusicVisualizer(object): def __init__(self, song, resolution = '512', duration=False, pitch_sensitivity=220, tempo_sensitivity=0.25, depth=1, classes=None, sort_classes_by_power=False, jitter=0.5, frame_length=512, truncation=1, smooth_factor=20, batch_size=30, ): self.song = song self.resolution = resolution self.duration=duration self.pitch_sensitivity=pitch_sensitivity self.tempo_sensitivity=tempo_sensitivity self.depth=depth self.classes=classes self.sort_classes_by_power=sort_classes_by_power self.jitter=jitter self.frame_length=frame_length self.truncation=truncation self.smooth_factor=smooth_factor self.batch_size=batch_size self.use_previous_classes=0 self.use_previous_vectors=0 if classes: self.num_classes=len(classes) else: self.num_classes=12 def generate(self, output_file): if self.song: song=self.song print('\nReading audio \n') y, sr = librosa.load(song) else: raise ValueError("you must enter an audio file name in the --song argument") #set model name based on resolution model_name='biggan-deep-' + self.resolution frame_length=self.frame_length #set pitch sensitivity pitch_sensitivity=(300-self.pitch_sensitivity) * 512 / frame_length #set tempo sensitivity tempo_sensitivity=self.tempo_sensitivity * frame_length / 512 #set depth depth=self.depth #set number of classes num_classes=self.num_classes #set sort_classes_by_power sort_classes_by_power=self.sort_classes_by_power #set jitter jitter=self.jitter #set truncation truncation=self.truncation #set batch size batch_size=self.batch_size #set use_previous_classes use_previous_vectors=self.use_previous_vectors #set use_previous_vectors use_previous_classes=self.use_previous_classes #set output name outname=output_file #set smooth factor if self.smooth_factor > 1: smooth_factor=int(self.smooth_factor * 512 / frame_length) else: smooth_factor=self.smooth_factor #set duration if self.duration: seconds=self.duration frame_lim=int(np.floor(seconds*22050/frame_length/batch_size)) else: frame_lim=int(np.floor(len(y)/sr*22050/frame_length/batch_size)) # Load pre-trained model model = BigGAN.from_pretrained(model_name) #set device device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') ######################################## ######################################## ######################################## ######################################## ######################################## #create spectrogram spec = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128,fmax=8000, hop_length=frame_length) #get mean power at each time point specm=np.mean(spec,axis=0) #compute power gradient across time points gradm=np.gradient(specm) #set max to 1 gradm=gradm/np.max(gradm) #set negative gradient time points to zero gradm = gradm.clip(min=0) #normalize mean power between 0-1 specm=(specm-np.min(specm))/np.ptp(specm) #create chromagram of pitches X time points chroma = librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=frame_length) #sort pitches by overall power chromasort=np.argsort(np.mean(chroma,axis=1))[::-1] ######################################## ######################################## ######################################## ######################################## ######################################## if self.classes: classes=self.classes if len(classes) not in [12,num_classes]: raise ValueError("The number of classes entered in the --class argument must equal 12 or [num_classes] if specified") elif self.use_previous_classes==1: cvs=np.load('class_vectors.npy') classes=list(np.where(cvs[0]>0)[0]) else: #select 12 random classes cls1000=list(range(1000)) random.shuffle(cls1000) classes=cls1000[:12] if sort_classes_by_power==1: classes=[classes[s] for s in np.argsort(chromasort[:num_classes])] #initialize first class vector cv1=np.zeros(1000) for pi,p in enumerate(chromasort[:num_classes]): if num_classes < 12: cv1[classes[pi]] = chroma[p][np.min([np.where(chrow>0)[0][0] for chrow in chroma])] else: cv1[classes[p]] = chroma[p][np.min([np.where(chrow>0)[0][0] for chrow in chroma])] #initialize first noise vector nv1 = truncated_noise_sample(truncation=truncation)[0] #initialize list of class and noise vectors class_vectors=[cv1] noise_vectors=[nv1] #initialize previous vectors (will be used to track the previous frame) cvlast=cv1 nvlast=nv1 #initialize the direction of noise vector unit updates update_dir=np.zeros(128) for ni,n in enumerate(nv1): if n<0: update_dir[ni] = 1 else: update_dir[ni] = -1 #initialize noise unit update update_last=np.zeros(128) ######################################## ######################################## ######################################## ######################################## ######################################## #get new jitters def new_jitters(jitter): jitters=np.zeros(128) for j in range(128): if random.uniform(0,1)<0.5: jitters[j]=1 else: jitters[j]=1-jitter return jitters #get new update directions def new_update_dir(nv2,update_dir): for ni,n in enumerate(nv2): if n >= 2*truncation - tempo_sensitivity: update_dir[ni] = -1 elif n < -2*truncation + tempo_sensitivity: update_dir[ni] = 1 return update_dir #smooth class vectors def smooth(class_vectors,smooth_factor): if smooth_factor==1: return class_vectors class_vectors_terp=[] for c in range(int(np.floor(len(class_vectors)/smooth_factor)-1)): ci=c*smooth_factor cva=np.mean(class_vectors[int(ci):int(ci)+smooth_factor],axis=0) cvb=np.mean(class_vectors[int(ci)+smooth_factor:int(ci)+smooth_factor*2],axis=0) for j in range(smooth_factor): cvc = cva*(1-j/(smooth_factor-1)) + cvb*(j/(smooth_factor-1)) class_vectors_terp.append(cvc) return np.array(class_vectors_terp) #normalize class vector between 0-1 def normalize_cv(cv2): min_class_val = min(i for i in cv2 if i != 0) for ci,c in enumerate(cv2): if c==0: cv2[ci]=min_class_val cv2=(cv2-min_class_val)/np.ptp(cv2) return cv2 print('\nGenerating input vectors \n') for i in tqdm(range(len(gradm))): #print progress pass #update jitter vector every 100 frames by setting ~half of noise vector units to lower sensitivity if i%200==0: jitters=new_jitters(jitter) #get last noise vector nv1=nvlast #set noise vector update based on direction, sensitivity, jitter, and combination of overall power and gradient of power update = np.array([tempo_sensitivity for k in range(128)]) * (gradm[i]+specm[i]) * update_dir * jitters #smooth the update with the previous update (to avoid overly sharp frame transitions) update=(update+update_last*3)/4 #set last update update_last=update #update noise vector nv2=nv1+update #append to noise vectors noise_vectors.append(nv2) #set last noise vector nvlast=nv2 #update the direction of noise units update_dir=new_update_dir(nv2,update_dir) #get last class vector cv1=cvlast #generate new class vector cv2=np.zeros(1000) for j in range(num_classes): cv2[classes[j]] = (cvlast[classes[j]] + ((chroma[chromasort[j]][i])/(pitch_sensitivity)))/(1+(1/((pitch_sensitivity)))) #if more than 6 classes, normalize new class vector between 0 and 1, else simply set max class val to 1 if num_classes > 6: cv2=normalize_cv(cv2) else: cv2=cv2/np.max(cv2) #adjust depth cv2=cv2*depth #this prevents rare bugs where all classes are the same value if np.std(cv2[np.where(cv2!=0)]) < 0.0000001: cv2[classes[0]]=cv2[classes[0]]+0.01 #append new class vector class_vectors.append(cv2) #set last class vector cvlast=cv2 #interpolate between class vectors of bin size [smooth_factor] to smooth frames class_vectors=smooth(class_vectors,smooth_factor) #check whether to use vectors from last run if use_previous_vectors==1: #load vectors from previous run class_vectors=np.load('class_vectors.npy') noise_vectors=np.load('noise_vectors.npy') else: #save record of vectors for current video np.save('class_vectors.npy',class_vectors) np.save('noise_vectors.npy',noise_vectors) ######################################## ######################################## ######################################## ######################################## ######################################## #convert to Tensor noise_vectors = torch.Tensor(np.array(noise_vectors)) class_vectors = torch.Tensor(np.array(class_vectors)) #Generate frames in batches of batch_size print('\n\nGenerating frames \n') #send to CUDA if running on GPU model=model.to(device) noise_vectors=noise_vectors.to(device) class_vectors=class_vectors.to(device) frames = [] for i in tqdm(range(frame_lim)): #print progress pass if (i+1)*batch_size > len(class_vectors): torch.cuda.empty_cache() break #get batch noise_vector=noise_vectors[i*batch_size:(i+1)*batch_size] class_vector=class_vectors[i*batch_size:(i+1)*batch_size] # Generate images with torch.no_grad(): output = model(noise_vector, class_vector, truncation) output_cpu=output.cpu().data.numpy() #convert to image array and add to frames for out in output_cpu: im=np.array(toimage(out)) frames.append(im) #empty cuda cache torch.cuda.empty_cache() #Save video aud = mpy.AudioFileClip(song, fps = 44100) if self.duration: aud.duration=self.duration clip = mpy.ImageSequenceClip(frames, fps=22050/frame_length) clip = clip.set_audio(aud) clip.write_videofile(outname,audio_codec='aac') <file_sep>import numpy as np import cv2 class VideoEditor: def __init__(self, f): self.f = f def process(self, in_path, out_path): stream = cv2.VideoCapture(in_path) fps = stream.get(cv2.CAP_PROP_FPS) img = None while img is None: ret, img = stream.read() img = self.f(img, 0) fourcc = cv2.VideoWriter_fourcc(*'MP4V') out = cv2.VideoWriter(out_path, fourcc, fps, (img.shape[1], img.shape[0])) frame_num = 0 while 1: ret, img = stream.read() frame_num += 1 if not ret or cv2.waitKey(25) & 0XFF == ord('q'): cv2.destroyAllWindows() break else: img = self.f(img, frame_num) out.write(img) <file_sep># Junk Drawer
fd1b9c82e105115d1f0f7d3ffa4300765f16be6e
[ "Markdown", "Python" ]
7
Python
naughtynates/playgrounds
f961bd8434e8d7aceae14a5a14d7afc6484fc350
b4c18e328a802c4858b0cac9fcd5993bdc4043ca
refs/heads/master
<file_sep># 자료구조 선언 a = list() b = [1, 2, 3, 4, 5] # 데이터의 추가 a.append('hi') b.append(6) b.append('seven') # 파이썬의 리스트는 데이터의 자료형에 통일성이 없어도 된다. # 데이터 검색 print(a[0]) print(b[1]) print(b[-1]) # 파이썬의 리스트에서 음수 인덱스는, 맨 뒤에서부터 검색한다는 것을 의미한다. # 데이터의 삭제 a.remove('hi') b.remove(6)<file_sep># 단순 연결 리스트 클래스 class SimpleLinkedList(): # 노드 클래스 class Node(): def __init__(self, item, next_node): self.item = item self.next_node = next_node # 리스트 초기화 def __init__(self): self.head = None # data type : Node self.size_num = 0 # 리스트 크기 확인 def size(self): print(self.size_num) # 리스트 empty 여부 확인 def is_empty(self): return True if self.size_num == 0 else False # 리스트 요소 맨 앞에 추가 # 단순 연결 리스트는 요소 추가를 맨 앞에 하는 것이 효율적이다. def add_first(self, item): if self.is_empty(): self.head = self.Node(item, None) else: # 맨 앞 추가이므로, 다음 노드는 현재의 head가 됨 self.head = self.Node(item, self.head) print('what is next', self.head.item) self.size_num += 1 # 리스트 요소 중간 삽입 def insert_next(self, item, node): node.next_node = SimpleLinkedList.Node(item, node.next_node) self.size_num += 1 # 리스트 맨 앞 요소 삭제 def remove_first(self): if self.is_empty(): return 'isEmpty' else: self.head = self.head.next_node self.size_num -= 1 # 리스트 중간 요소 삭제 def remove_next(self, node): if self.is_empty(): return 'isEmpty' else: temp = node.next_node node.next_node = temp.next_node self.size_num -= 1 # 리스트 요소 인덱스 검색 def get_index(self, item): temp = self.head for i in range(self.size_num): if item == temp.item: print(i) break temp = temp.next_node else: print('There is no element you want to get') # 리스트 전체 출력 def all_list(self): temp = self.head while temp: print(temp.item, end=' ') temp = temp.next_node print() # 리스트 생성 sll = SimpleLinkedList() # 데이터 추가 sll.add_first('hi') sll.add_first('my') sll.add_first('friend') sll.insert_next('my1', sll.head.next_node) # 데이터 삭제 sll.remove_first() sll.all_list() sll.remove_next(sll.head.next_node) # 데이터 검색 sll.get_index('my1') sll.get_index('your') sll.all_list() sll.size()
ef7602e56dca579ec9e0fd4576f0282b38ba66ea
[ "Python" ]
2
Python
liza0525/data-structure-study
cce0ac7b8be99728a90e75742259758f2a483f22
50fa1141591cf5e69dc23d6473f1e2c95934f38b
refs/heads/master
<repo_name>vta92/AutoEncoder<file_sep>/autoencoder.py import torch from torch.autograd import Variable import torch.optim as optim import torch.nn as nn import torch.nn.parallel import torch.utils.data import numpy as np import pandas as pd import matplotlib.pyplot as plt #these files have no headers movies=pd.read_csv('ml-1m/movies.dat', sep='::', header=None, encoding='latin-1', engine='python') ratings=pd.read_csv('ml-1m/ratings.dat',sep='::', header=None, encoding='latin-1', engine='python') users=pd.read_csv('ml-1m/users.dat', sep='::', header=None, encoding='latin-1', engine='python') movies.columns=['Movie_ID','Name','Tags'] ratings.columns=['User_ID','Movie_ID','Rating','Timestamp'] users.columns=['User_ID','Gender','Age','Job_ID','Zip_Code'] train_set1 = pd.read_csv('ml-100k/u1.base',delimiter='\t') test_set1 = pd.read_csv('ml-100k/u1.test', delimiter='\t') train_set1.columns=['User_ID','Movie_ID','Rating','Timestamp'] test_set1.columns=['User_ID','Movie_ID','Rating','Timestamp'] #have to convert from pd to np array for processing later train_set1 = np.array(train_set1,dtype='int') test_set1 = np.array(test_set1,dtype='int') #dropping the timestamps train_set1= train_set1[:,:-1] test_set1 = test_set1[:,:-1] #assuming the max user id = total number of user in a given dataset, we have: total_users = max(train_set1[:,0].max(), test_set1[:,0].max()) total_movies = max(train_set1[:,1].max(), test_set1[:,1].max()) #we have a 943x1682 matrix from the 2 variables above, with each cell contains a rating #pytorch expects a list of list def matrix_rep(data, total_users, total_movies): matrix=[[0 for i in range(total_movies)] for i in range(total_users)] for row in range(len(data)): #get the number of rows in the whole test set user_id, movie_id, rating = data[row][0], data[row][1], data[row][2] matrix[user_id-1][movie_id-1] = float(rating) return matrix train_set1 = matrix_rep(train_set1, total_users, total_movies) train_set1 = torch.FloatTensor(train_set1) test_set1 = matrix_rep(test_set1, total_users, total_movies) test_set1 = torch.FloatTensor(test_set1) #end of processing ######################################################################################################### class auto_encoder(nn.Module): def __init__(self, total_movies, hid1_size, hid2_size): super(auto_encoder, self).__init__() #first 2 layers vis->hid1, with the number of features or movies specified, 30 nodes in hid1 layer #we have in total of 3 hidden layers with in features and out features, with linear transformation + bias = true #goal: vis == decoding/outlayer self.vh1 = nn.Linear(total_movies,hid1_size) self.h1h2 = nn.Linear(hid1_size, hid2_size) self.h2h3 = nn.Linear(hid2_size, hid1_size) #stacked AE, needs to mirror the prev layer self.h3o = nn.Linear(hid1_size, total_movies) #activation function self.activation_func = nn.Tanh() #need to experiment to see the best act. func def prop_forward (self,vector): vector = self.activation_func(self.vh1(vector)) vector = self.activation_func(self.h1h2(vector)) vector = self.activation_func(self.h2h3(vector)) vector = self.h3o(vector) #hope that the output matches the input return vector def training(epochs, metrics, optimizer): global auto_encoder accuracy = list() #store the accuracy for graph for epoch in range (epochs): training_loss = 0 num_users_who_rated = 0.0 for i in range(total_users): in_feature = train_set1[i] #create a fake dim of batchsize = 1 vector. Pytorch expects this in_feature = Variable(in_feature).unsqueeze(0) target = in_feature.clone() #the original input, unchanged. For loss calculation if torch.sum(target.data > 0) > 0: #make sure the input is not empty, ppl rate at least 1 movie out_feature = auto_encoder.prop_forward(in_feature) out_feature[target == 0] = 0 #unrated = can't count in loss function #don't want to compute grad w/r target target.require_grad = False loss = metrics(out_feature, target) mean_correction = total_movies/float(torch.sum(target.data > 0)+1e-20) #only select movies with ratings, make sure denom != 0 loss.backward() #gradient training_loss += np.sqrt(loss.data[0]*mean_correction) num_users_who_rated += 1.0 optimizer.step() #difference between backward() and step/opt: backward decides the direction of change, opt will determine the magnitude print('epoch ' + str(epoch) +': ' + str(training_loss/num_users_who_rated)) accuracy.append(training_loss/num_users_who_rated) return accuracy #test set has the solution to the unwatched movies in the training set. Therefore we still predict the training set. #no need to worry about gradient/backprop as usual def predict(metrics): global auto_encoder test_loss = 0 counter = 0 for i in range(total_users): in_feature = train_set1[i] in_feature = Variable(in_feature).unsqueeze(0) target = Variable(test_set1[i]) if torch.sum(target.data > 0) > 0: result = auto_encoder.prop_forward(in_feature) target.require_grad = False result[target == 0] = 0 loss = metrics(result, target) mean_correction = total_movies/float(torch.sum(target.data > 0)+1e-20) test_loss += np.sqrt(loss.data[0]*mean_correction) counter += 1 print('test mean loss' +': ' + str(test_loss/counter)) def graph(accuracy): x = [i for i in range(len(accuracy))] y = accuracy plt.plot(x,y) plt.ylabel("mean corrected training loss") plt.xlabel("epochs") plt.show() #we want the loss to be less than 1, so our error is less than 1 star rating '''architecture of AE defined here''' hid1_size = 30 hid2_size = 15 epochs = 30 #testing out with 300 conditions = [total_movies, hid1_size, hid2_size] auto_encoder = auto_encoder(int(conditions[0]), conditions[1], conditions[2]) metrics = nn.MSELoss(size_average=True) optimizer = optim.Adam(auto_encoder.parameters(), lr=0.003, weight_decay = 0.2) #inherited the parameters() method from nn train_accuracy = training(epochs, metrics, optimizer) graph = graph(train_accuracy) predict(metrics)
b50fd47ebec276e436303b40769fa861bc9cc8c6
[ "Python" ]
1
Python
vta92/AutoEncoder
ec44b34b1d8f2cc320bfc6b2c1ce1715124f0e49
4c7276c4127e5f19d8b548a03f3ee5bf128b39a4
refs/heads/master
<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Windows.Forms; namespace hexd { class Program { class Arguments { private Arguments() { } public static Arguments ParseCmdline(string[] cargs) { Arguments parsedArguments = new Arguments(); for(int i = 0; i < cargs.Length; ++i) { if (cargs[i] == "-ToSystemClipboard") parsedArguments.ToSystemClipboard = true; else if (cargs[i] == "-NoBloatedOutput") parsedArguments.NoBloatedOutput = true; else if (cargs[i] == "-NoOffset") parsedArguments.NoOffset = true; else if (cargs[i] == "-NoSpaces") parsedArguments.NoSpaces = true; else if (cargs[i] == "-Lowercase") parsedArguments.Lowercase = true; else if (cargs[i] == "-MaxBytes") { try { parsedArguments.MaxBytes = Convert.ToInt32(cargs[++i]); } catch(IndexOutOfRangeException) { Console.WriteLine("-MaxBytes requires a value"); Environment.Exit(1); } catch(FormatException) { Console.WriteLine("{0} is not a number", cargs[i]); Environment.Exit(1); } } else parsedArguments.Filenames.Add(cargs[i]); } return parsedArguments; } public bool ToSystemClipboard = false; public bool NoBloatedOutput = false; public bool NoOffset = false; public bool NoSpaces = false; public bool Lowercase = false; public int MaxBytes = 16; public List<string> Filenames = new List<string>(); } private static Arguments programArgs; private static int GetPrintableBytesNumber() { if (programArgs.ToSystemClipboard) return programArgs.MaxBytes; int oneLineBytes = Console.WindowWidth; if (!programArgs.NoOffset) oneLineBytes -= 10; oneLineBytes /= 3; if (programArgs.MaxBytes > oneLineBytes) return --oneLineBytes; return programArgs.MaxBytes; } private static string GetHexDump(string file) { int b; int counter = GetPrintableBytesNumber(); int loc = 0; string formatter; if (programArgs.Lowercase) formatter = "{0:x2}"; else formatter = "{0:X2}"; if (!programArgs.NoSpaces) formatter += " "; using (StringWriter writer = new StringWriter()) { try { using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { while ((b = stream.ReadByte()) != -1) { if (counter - GetPrintableBytesNumber() == 0) { writer.WriteLine(); if (!programArgs.NoOffset) writer.Write("{0:X8}: ", loc); counter = 0; } writer.Write(formatter, b); counter++; loc++; } } } catch (IOException) { if (!programArgs.NoBloatedOutput) writer.WriteLine("\nignoring {0}: does not exist", file); return writer.ToString(); } writer.WriteLine(); return writer.ToString(); } } private static string GetFullHexDump() { using (StringWriter fullDump = new StringWriter()) { foreach (var filename in programArgs.Filenames) { if (!programArgs.NoBloatedOutput) fullDump.WriteLine("\n{0}", filename); fullDump.Write(GetHexDump(filename)); } return fullDump.ToString(); } } [STAThread] static void Main(string[] args) { programArgs = Arguments.ParseCmdline(args); string dump = GetFullHexDump(); if (dump.Length > 0 && dump[dump.Length - 1] == '\n') dump = dump.Remove(dump.Length - 1, 1); if (programArgs.ToSystemClipboard) Clipboard.SetText(dump); else Console.WriteLine(dump); } } }
37306e0eac88a5e03c53f08a16a141bf71d363bf
[ "C#" ]
1
C#
StefanoBelli/hexd
cebd494bfb2a816c1fd8f989623c1de25d1eabcb
b0db15e9a4640fcaeb07b99bcd8cddb482fd1c15
refs/heads/master
<file_sep>import cv2 import math import numpy as np from fixer import fixer class ImageFixer(fixer._Fixer): def __init__(self): super(ImageFixer, self).__init__() def __cut_image(self, image, size, cut_edge): h_max, w_max, _ = image.shape h_size, w_size = size if cut_edge: h_size_k, w_size_k = h_size-20, w_size-20 nh, nw = math.ceil(h_max/(h_size_k)), math.ceil(w_max/(w_size_k)) batch = [image[max(0,h*h_size_k-10):min((h+1)*h_size_k+10,h_max),max(0,w*w_size_k-10):min((w+1)*w_size_k+10,w_max)] for h in range(nh) for w in range(nw)] else: nh, nw = math.ceil(h_max/h_size), math.ceil(w_max/w_size) batch = [image[h*h_size:min((h+1)*h_size,h_max),w*w_size:min((w+1)*w_size,w_max)] for h in range(nh) for w in range(nw)] return batch, nh, nw def __cut_edge(self, batch, nh, nw): blen = len(batch) block_pos = lambda x: (x//nw,x%nw) for i in range(blen): xy = block_pos(i) if not xy[0] == 0: batch[i] = batch[i][10:,:] if not xy[0] == nh-1: batch[i] = batch[i][:-10,:] if not xy[1] == 0: batch[i] = batch[i][:,10:] if not xy[1] == nw-1: batch[i] = batch[i][:,:-10] return batch def __merge_image(self, batch, nh, nw, cut_edge): if nh == nw == 1: return batch[0] if cut_edge: self.__cut_edge(batch, nh, nw) image = np.vstack([np.hstack(batch[h*nw:(h+1)*nw]) for h in range(nh)]) return image def _fix(self, image, size, cut_edge, gpu): batch, nh, nw = self.__cut_image(image, size, cut_edge) batch_fix = [] for img in batch: out_img = self._run(img[np.newaxis], gpu).squeeze() batch_fix.append(out_img) outp = self.__merge_image(batch_fix, nh, nw, cut_edge) return outp def fix(self, inp_path, outp_path, size, gpu): image = cv2.imread(inp_path) image = image/255. if size < 0: size = image.shape[:2] cut_edge = False elif size <= 20: raise ValueError("block size must be larger than 20 in order to get a better quality") else: size = (size,size) cut_edge = True outp = self._fix(image, size, cut_edge, gpu) if outp_path.endswith('.jpg') or outp_path.endswith('.jpeg'): cv2.imwrite(outp_path, outp, [int(cv2.IMWRITE_JPEG_QUALITY), 100]) else: cv2.imwrite(outp_path, outp) return outp<file_sep>import torch import numpy as np from models import fsrcnn class _Fixer: def __init__(self): self.model = fsrcnn.FSRCNN(3,3,scale=1) model_state_dict = torch.load('../model_param/FSRCNN1x.pt') self.model.load_state_dict(model_state_dict) self.model.eval() def _run(self, batch, gpu): batch = batch.transpose((0,3,1,2)) batch = torch.from_numpy(batch).type(torch.FloatTensor) if gpu: batch = batch.cuda() self.model.cuda() else: self.model.cpu() outp = self.model(batch) outp = torch.clamp(outp, 0., 1.) outp_img = outp.detach().cpu().numpy() outp_img = outp_img.transpose((0,2,3,1)) outp_img = (outp_img * 255.).astype(np.uint8) return outp_img<file_sep># AnimEx A deep neural network used to reduce **JPEG compression**, and it bases on [**F**ast **S**uper **R**esolution **CNN**](https://arxiv.org/abs/1608.00367)<file_sep>import os import cv2 import argparse import skimage.metrics import fixer.fix_image as f_img def parse_arg(): parser = argparse.ArgumentParser() parser.add_argument('-i', dest='inp_path', required=True) parser.add_argument('-o', dest='outp_path', default=None) parser.add_argument('-g', dest='gpu', action='store_true', default=False) parser.add_argument('-s', dest='block_size', type=int, default=-1) parser.add_argument('-m', dest='measure', default=None) return parser.parse_args() def main(): argv = parse_arg() file_name = os.path.basename(argv.inp_path) outp_path = argv.outp_path if outp_path is None: outp_path = os.path.dirname(argv.inp_path) outp_path = os.path.join(outp_path, f'{file_name}-output.jpg') elif os.path.isdir(outp_path): outp_path = os.path.join(outp_path, file_name) solver = f_img.ImageFixer() outp = solver.fix(argv.inp_path, outp_path, size=argv.block_size, gpu=argv.gpu) if argv.measure is not None: gt = cv2.imread(argv.measure) if not gt.shape == outp.shape: print('UserWarning: the ground truth has different dimensions, and to fit the scale of output the ground truth will be resized') if gt.shape[0] < outp.shape[0]: inter_method = cv2.INTER_CUBIC else: inter_method = cv2.INTER_LANCZOS4 gt = cv2.resize(gt, (outp.shape[1],outp.shape[0]), interpolation=inter_method) psnr = skimage.metrics.peak_signal_noise_ratio(gt, outp) print(f'PSNR: {psnr}') if __name__ == '__main__': main()<file_sep>import torch import torch.nn as nn class FSRCNN(nn.Module): def __init__(self, in_channels, out_channels, scale=1): super(FSRCNN, self).__init__() self.first_part = self.__first(in_channels) self.mid_part = self.__mid() self.last_part = self.__last(out_channels, scale) def __first(self, in_channels): first = nn.Sequential( nn.Conv2d(in_channels, 32, kernel_size=3, padding=1), nn.PReLU(), nn.Conv2d(32, 32, kernel_size=3, padding=1), nn.PReLU(), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.PReLU(), nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.PReLU() ) for m in first.modules(): if type(m) is nn.Conv2d: nn.init.kaiming_normal_(m.weight) return first def __mid(self): mid = nn.Sequential( nn.Conv2d(64, 16, kernel_size=1), nn.PReLU(), nn.Conv2d(16, 16, kernel_size=3, padding=1), nn.PReLU(), nn.Conv2d(16, 16, kernel_size=3, padding=1), nn.PReLU(), nn.Conv2d(16, 16, kernel_size=3, padding=1), nn.PReLU(), nn.Conv2d(16, 16, kernel_size=3, padding=1), nn.PReLU(), nn.Conv2d(16, 64, kernel_size=1), nn.PReLU() ) for m in mid.modules(): if type(m) is nn.Conv2d: nn.init.kaiming_normal_(m.weight) return mid def __last(self, out_channels, scale): last = nn.ConvTranspose2d(128, out_channels, kernel_size=5, padding=2, stride=scale, output_padding=scale-1) nn.init.kaiming_normal_(last.weight) return last def forward(self, x): x1 = self.first_part(x) x2 = self.mid_part(x1) y = self.last_part(torch.cat((x2,x1), dim=1)) return y
1823e8c14744fba582788eadbecdc35986ef9338
[ "Markdown", "Python" ]
5
Python
New2World/AnimEx
c97ee379a40c857facbc17b876407a01d69bdba4
41454904756b679812468ed1267d82aef53d4882
refs/heads/master
<file_sep><?php namespace RKW\RkwNewsletter\Manager; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Domain\Model\FileReference; use Madj2k\CoreExtended\Domain\Repository\FileReferenceRepository; use RKW\RkwNewsletter\Domain\Model\Content; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Newsletter; use RKW\RkwNewsletter\Domain\Model\Pages; use RKW\RkwNewsletter\Domain\Model\Topic; use RKW\RkwNewsletter\Domain\Repository\ContentRepository; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\NewsletterRepository; use RKW\RkwNewsletter\Domain\Repository\PagesRepository; use RKW\RkwNewsletter\Exception; use RKW\RkwNewsletter\Status\ApprovalStatus; use RKW\RkwNewsletter\Status\IssueStatus; use TYPO3\CMS\Core\Authentication\BackendUserAuthentication; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; use TYPO3\CMS\Extbase\SignalSlot\Dispatcher; /** * IssueManager * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class IssueManager implements \TYPO3\CMS\Core\SingletonInterface { /** * @var \RKW\RkwNewsletter\Domain\Repository\NewsletterRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected NewsletterRepository $newsletterRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected IssueRepository $issueRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\PagesRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PagesRepository $pagesRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\ContentRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected ContentRepository $contentRepository; /** * @var \Madj2k\CoreExtended\Domain\Repository\FileReferenceRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected FileReferenceRepository $fileReferenceRepository; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager * @TYPO3\CMS\Extbase\Annotation\Inject */ private ObjectManager $objectManager; /** * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PersistenceManager $persistenceManager; /** * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher * @TYPO3\CMS\Extbase\Annotation\Inject */ protected Dispatcher $signalSlotDispatcher; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * @const string */ const SIGNAL_FOR_SENDING_MAIL_RELEASE = 'sendMailRelease'; /** * replaceTitlePlaceholder * * @param string $title * @return string */ public function replaceTitlePlaceholders (string $title): string { $title = str_replace("{D}", date("d", time()), $title); $title = str_replace("{M}", date("m", time()), $title); $title = str_replace("{F}", date("F", time()), $title); $title = str_replace("{Y}", date("Y", time()), $title); return $title; } /** * Creates an issue * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @param bool $isSpecial * @return \RKW\RkwNewsletter\Domain\Model\Issue * @throws Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function createIssue(Newsletter $newsletter, bool $isSpecial = false): Issue { // check if persisted if ($newsletter->_isNew()) { throw new Exception('Newsletter is not persisted.', 1639058270); } // create issue and set title /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = GeneralUtility::makeInstance(Issue::class); $issue->setTitle(($isSpecial ? 'SPECIAL: ': '') . $this->replaceTitlePlaceholders($newsletter->getIssueTitle())); $issue->setStatus(0); $issue->setIsSpecial($isSpecial); // persist in order to get uid $this->issueRepository->add($issue); $newsletter->addIssue($issue); $this->newsletterRepository->update($newsletter); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Created issue with id=%s of newsletter with id=%s.', $issue->getUid(), $newsletter->getUid() ) ); return $issue; } /** * Creates a page for the topic * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return \RKW\RkwNewsletter\Domain\Model\Pages * @throws Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @todo add translation functionality when upgraded to TYPO3 9.5 and above */ public function createPage(Newsletter $newsletter, Topic $topic, Issue $issue): Pages { // check if container-page exists if (! $topic->getContainerPage()) { throw new Exception('Container-page does not exist.', 1641967659); } /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = GeneralUtility::makeInstance(Pages::class); $page->setTxRkwnewsletterNewsletter($newsletter); $page->setTxRkwnewsletterTopic($topic); $page->setTitle($issue->getTitle()); $page->setDokType(1); $page->setPid($topic->getContainerPage()->getUid()); $page->setNoSearch(true); $page->setTxRkwnewsletterExclude(true); // $page->setSysLanguageUid($newsletter->getSysLanguageUid()); $this->pagesRepository->add($page); $this->persistenceManager->persistAll(); $issue->addPages($page); $this->issueRepository->update($issue); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Created page with id=%s and sysLanguageUid=%s for topic id=%s in parent page with id=%s of newsletter with id=%s.', $page->getUid(), 'null', $topic->getUid(), $topic->getContainerPage()->getUid(), $newsletter->getUid() ) ); return $page; } /** * Creates a content element based on page-properties * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @param \RKW\RkwNewsletter\Domain\Model\Pages $sourcePage * @return \RKW\RkwNewsletter\Domain\Model\Content * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function createContent (Newsletter $newsletter, Pages $page, Pages $sourcePage): Content { /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = GeneralUtility::makeInstance(Content::class); $content->setPid($page->getUid()); $content->setSysLanguageUid($newsletter->getSysLanguageUid()); $content->setContentType('textpic'); $content->setImageCols(1); $content->setHeader($sourcePage->getTxRkwnewsletterTeaserHeading() ?: $sourcePage->getTitle()); $content->setBodytext($sourcePage->getTxRkwnewsletterTeaserText() ?: $sourcePage->getAbstract()); $content->setHeaderLink($sourcePage->getTxRkwnewsletterTeaserLink() ?: 't3://page?uid=' . $sourcePage->getUid()); // we need a loop here to work with persistence - what ever... foreach ($sourcePage->getTxRkwauthorsAuthorship() as $author) { $content->addTxRkwnewsletterAuthors($author); $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Added author with id=%s to content of page with uid=%s of newsletter with id=%s.', $author->getUid(), $sourcePage->getUid(), $newsletter->getUid() ) ); } // add object $this->contentRepository->add($content); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Added content-element with id=%s and sysLanguageUid=%s to page with uid=%s of newsletter with id=%s.', $content->getUid(), $content->getSysLanguageUid(), $page->getUid(), $newsletter->getUid() ) ); return $content; } /** * Creates a file reference for a content based on page-properties * * @param \Madj2k\CoreExtended\Domain\Model\FileReference $fileReferenceSource * @param \RKW\RkwNewsletter\Domain\Model\Content $content * @return \Madj2k\CoreExtended\Domain\Model\FileReference * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function createFileReference(FileReference $fileReferenceSource, Content $content): FileReference { // we switch to admin for BE-user for full file access - !!! BE CAREFUL WITH THIS !!! /** @var \TYPO3\CMS\Core\Authentication\BackendUserAuthentication $backendUserAuthentication */ $backendUserAuthentication = GeneralUtility::makeInstance(BackendUserAuthentication::class); $backendUserAuthentication->setWorkspace(0); $beUserTemp = $GLOBALS['BE_USER']; $GLOBALS['BE_USER'] = $backendUserAuthentication; /** @var \Madj2k\CoreExtended\Domain\Model\FileReference $fileReference */ $fileReference = GeneralUtility::makeInstance(FileReference::class); $fileReference->setOriginalResource($fileReferenceSource->getOriginalResource()); $fileReference->setFile($fileReferenceSource->getFile()); $fileReference->setTableLocal($fileReferenceSource->getTableLocal()); $fileReference->setTablenames('tt_content'); $fileReference->setFieldName('image'); $fileReference->setUidForeign($content->getUid()); $fileReference->setPid($content->getPid()); $this->fileReferenceRepository->add($fileReference); $this->persistenceManager->persistAll(); // switch BE-user back to normal !!! $GLOBALS['BE_USER'] = $beUserTemp; $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Added fileReference with id=%s to content with uid=%s.', $fileReference->getUid(), $content->getUid() ) ); return $fileReference; } /** * Builds all contents for a topic * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @return bool * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function buildContents (Newsletter $newsletter, Topic $topic, Pages $page): bool { /** @var \TYPO3\CMS\Extbase\Persistence\QueryResultInterface $sourcePagesList */ $sourcePagesList = $this->pagesRepository->findByTopicNotIncluded($topic); if (count($sourcePagesList) > 0) { /** @var \RKW\RkwNewsletter\Domain\Model\Pages $sourcePage */ foreach ($sourcePagesList as $sourcePage) { // create content $content = $this->createContent($newsletter, $page, $sourcePage); // optional: add image try { /** @var \Madj2k\CoreExtended\Domain\Model\FileReference $fileReference */ $fileReference = $sourcePage->getTxRkwnewsletterTeaserImage() ?: ($sourcePage->getTxCoreextendedPreviewImage() ?: null); if ($fileReference) { $this->createFileReference($fileReference, $content); } } catch (\Exception $e) { $this->getLogger()->log( LogLevel::ERROR, sprintf( 'Can not add fileReference to content with id=%s of newsletter with id=%s. Error: %s', $content->getUid(), $newsletter->getUid(), $e->getMessage() ) ); } // update timestamp $sourcePage->setTxRkwnewsletterIncludeTstamp(time()); $this->pagesRepository->update($sourcePage); } $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Built contents of topic with id=%s of newsletter with id=%s.', $topic->getUid(), $newsletter->getUid() ) ); return true; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'No contents built for topic with id=%s of newsletter with id=%s.', $topic->getUid(), $newsletter->getUid() ) ); return false; } /** * Builds all pages for a topic and adds contents * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param array<\RKW\RkwNewsletter\Domain\Model\Topic> $topics * @return bool * @throws Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function buildPages (Newsletter $newsletter, Issue $issue, array $topics = []): bool { /** @var \RKW\RkwNewsletter\Manager\ApprovalManager $approvalManager */ $approvalManager = $this->objectManager->get(ApprovalManager::class); if ( (! $topics) && ($newsletter->getTopic()) ){ $topics = $newsletter->getTopic()->toArray(); } if (count($topics)) { foreach ($topics as $topic) { // Create page $page = $this->createPage($newsletter, $topic, $issue); // Build contents on that page $this->buildContents ($newsletter, $topic, $page); // Create approval for page $approvalManager->createApproval($topic, $issue, $page); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Built page for topic with id=%s for issue with id=%s of newsletter with id=%s.', $topic->getUid(), $issue->getUid(), $newsletter->getUid() ) ); } return true; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'No pages built for issue with id=%s of newsletter with id=%s. No topics defined for newsletter.', $issue->getUid(), $newsletter->getUid() ) ); return false; } /** * Builds an issue with all contents for the given newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @param array<\RKW\RkwNewsletter\Domain\Model\Topic> $topics * @return bool * @throws Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function buildIssue (Newsletter $newsletter, array $topics = []): bool { // check for topics if (count($newsletter->getTopic())) { // create issue and set approval-status $issue = $this->createIssue($newsletter, intval($topics)); try { $this->buildPages ($newsletter, $issue, $topics); $issue->setStatus(1); } catch (\Exception $e) { $issue->setStatus(99); $this->getLogger()->log( LogLevel::ERROR, sprintf( 'Error while trying to create an issue for newsletter with id=%s: %s', $newsletter->getUid(), $e->getMessage() ) ); } // if topics are set, we have a manually created special-issue if (! count($topics)) { $newsletter->setLastIssueTstamp(time()); $this->newsletterRepository->update($newsletter); } $this->issueRepository->update($issue); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Built %s created issue for newsletter with id=%s.', ($topics ? 'manually' : 'automatically'), $newsletter->getUid() ) ); return true; } $this->getLogger()->log( LogLevel::WARNING, sprintf( 'No topics defined for newsletter with id=%s. No issue created.', $newsletter->getUid() ) ); return false; } /** * Builds issues for all due newsletters * * @param int $tolerance * @param int $timestampNow * @return bool * @throws Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Core\Type\Exception\InvalidEnumerationValueException * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException */ public function buildAllIssues (int $tolerance = 0, int $timestampNow = 0): bool { $newsletterList = $this->newsletterRepository->findAllToBuildIssue($tolerance, $timestampNow); if (count($newsletterList)) { /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ foreach ($newsletterList as $newsletter) { $this->buildIssue($newsletter); } $this->getLogger()->log( LogLevel::INFO, sprintf( 'Built issues for %s newsletters.', count($newsletterList) ) ); return true; } $this->getLogger()->log( LogLevel::DEBUG, 'No issues built. No newsletter is due for a new issue.' ); return false; } /** * Increases the level of the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Approval Issue $issue * @return bool * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function increaseLevel (Issue $issue): bool { $stage = IssueStatus::getStage($issue); if (IssueStatus::increaseLevel($issue)) { $this->issueRepository->update($issue); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Increased level for issue id=%s in issue-stage %s.', $issue->getUid(), $stage ) ); return true; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Did not increase level for issue id=%s.', $issue->getUid() ) ); return false; } /** * Increases the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return bool * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function increaseStage (Issue $issue): bool { $stage = IssueStatus::getStage($issue); if (IssueStatus::increaseStage($issue)) { $this->issueRepository->update($issue); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Increased stage for issue id=%s in issue-stage %s.', $issue->getUid(), $stage ) ); return true; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Did not increase stage for issue id=%s.', $issue->getUid() ) ); return false; } /** * Get the email-recipients for the approval based in the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return array */ public function getMailRecipients(Issue $issue): array { $mailRecipients = []; $stage = IssueStatus::getStage($issue); if ($stage == IssueStatus::STAGE_RELEASE) { if (count($issue->getNewsletter()->getApproval()) > 0) { /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $beUser */ foreach ($issue->getNewsletter()->getApproval()->toArray() as $beUser) { if (GeneralUtility::validEmail($beUser->getEmail())) { $mailRecipients[] = $beUser; } } } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Found %s recipients for issue id=%s in issue-stage %s.', count($mailRecipients), $issue->getUid(), $stage ) ); } return $mailRecipients; } /** * Send info-mails or reminder-mails for outstanding confirmations * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return int * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException */ public function sendMails(Issue $issue): int { $stage = IssueStatus::getStage($issue); $level = IssueStatus::getLevel($issue); $isReminder = ($level == IssueStatus::LEVEL2); // get recipients - but only if stage and level match AND if valid recipients are found if ( ($stage == IssueStatus::STAGE_RELEASE) && (count($recipients = $this->getMailRecipients($issue))) ) { if ($level != IssueStatus::LEVEL_DONE) { // Signal for e.g. E-Mails $this->signalSlotDispatcher->dispatch( __CLASS__, self::SIGNAL_FOR_SENDING_MAIL_RELEASE, [$recipients, $issue, $isReminder] ); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Sending email for issue with id=%s in issue-stage %s and level %s.', $issue->getUid(), $stage, $level ) ); return 1; } else { // here we could implement an automatic approval // but we don't want this on here! $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Automatic confirmation for issue with id=%s in issue-stage %s and level %s triggered, but nothing done!', $issue->getUid(), $stage, $level ) ); return 2; } } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Issue with id=%s in issue-stage %s has no mail-recipients.', $issue->getUid(), $stage ) ); return 0; } /** * Check if all approvals are done and set status of the issue to "release" then * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return bool * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException */ public function processConfirmation (Issue $issue): bool { // only if status is "approval" if ( ($issue->getStatus() != IssueStatus::STAGE_APPROVAL) && ($issue->getStatus() != IssueStatus::STAGE_RELEASE) ){ return false; } // check if all approvals are done /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ foreach ($issue->getApprovals() as $approval) { if (ApprovalStatus::getStage($approval) != ApprovalStatus::STAGE_DONE) { return false; } } // update if status is approval if ($issue->getStatus() == IssueStatus::STAGE_APPROVAL) { // update status to release $issue->setStatus(IssueStatus::STAGE_RELEASE); $this->issueRepository->update($issue); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Set stage to %s for issue with id=%s.', IssueStatus::STAGE_RELEASE, $issue->getUid() ) ); } // send mails and increase level for the next time if ($this->sendMails($issue) == 1) { $this->increaseLevel($issue); return true; } return false; } /** * Check all issues if there is a release stage to check * * @param int $toleranceLevel2 * @return int * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException */ public function processAllConfirmations (int $toleranceLevel2): int { $issueList = $this->issueRepository->findAllForConfirmationByTolerance($toleranceLevel2); if (count($issueList)) { /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ foreach ($issueList as $issue) { $this->processConfirmation($issue); } } $this->getLogger()->log( LogLevel::INFO, sprintf( 'Processed release status for %s issues.', count($issueList) ) ); return count($issueList); } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger(): Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers\Backend; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Topic; use TYPO3\CMS\Core\Authentication\BackendUserAuthentication; use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper; /** * AbstractHasBackendUserPermissionViewHelper * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ abstract class AbstractHasBackendUserPermissionViewHelper extends AbstractViewHelper { /** * Checks permissions * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param \RKW\RkwNewsletter\Domain\Model\Topic|null $topic * @param int $approvalStage * @param bool $allApprovals * @return bool */ protected static function checkPermissions( Issue $issue, bool $allApprovals = false, Topic $topic = null, int $approvalStage = 1 ): bool { /** @var \TYPO3\CMS\Core\Authentication\BackendUserAuthentication $beUserAuthentication */ $beUserAuthentication = ($GLOBALS['BE_USER'] ?: null); $backendUserId = intval($GLOBALS['BE_USER']->user['uid']); if ($backendUserId) { if ( ($beUserAuthentication instanceof BackendUserAuthentication) && ($beUserAuthentication->isAdmin()) ){ return true; } // first check if user is allowed by issue /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ foreach ($issue->getNewsletter()->getApproval() as $backendUser) { if ($backendUser->getUid() == $backendUserId) { return true; } } // then check if he is allowed by approval for a specific topic and stage if ($topic) { $getter = 'getApprovalStage' . $approvalStage; /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ foreach ($topic->$getter() as $backendUser) { if ($backendUser->getUid() == $backendUserId) { return true; } } // check if any approval-permissions match! } else if ($allApprovals) { foreach([1,2] as $stage) { $getter = 'getApprovalStage' . $stage; /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ foreach($issue->getNewsletter()->getTopic() as $topic) { /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ foreach ($topic->$getter() as $backendUser) { if ($backendUser->getUid() == $backendUserId) { return true; } } } } } } return false; } } <file_sep><?php defined('TYPO3_MODE') || die('Access denied.'); call_user_func( function (string $extKey) { //================================================================= // Register Plugins //================================================================= \TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerPlugin( $extKey, 'Subscription', 'RKW Newsletter: Anmeldung' ); //================================================================= // Add Flexforms //================================================================= // plugin signature: <extension key without underscores> '_' <plugin name in lowercase> $pluginSignature = str_replace('_','', $extKey) . '_subscription'; $GLOBALS['TCA']['tt_content']['types']['list']['subtypes_addlist'][$pluginSignature] = 'pi_flexform'; $fileName = 'FILE:EXT:rkw_newsletter/Configuration/FlexForms/Subscription.xml'; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPiFlexFormValue( $pluginSignature, $fileName ); //================================================================= // TCA Extension //================================================================= $tmpCols = [ 'tx_rkwnewsletter_is_editorial' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tt_content.tx_rkwnewsletter_is_editorial', 'config' => [ 'type' => 'check', 'default' => 0, ], ], ]; // Extend TCA when rkw_authors is available if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('rkw_authors')) { $tmpCols['tx_rkwnewsletter_authors'] = [ 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tt_content.tx_rkwnewsletter_authors', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'foreign_table' => 'tx_rkwauthors_domain_model_authors', 'foreign_table_where' => 'AND tx_rkwauthors_domain_model_authors.internal = 1 AND ((\'###PAGE_TSCONFIG_IDLIST###\' <> \'0\' AND FIND_IN_SET(tx_rkwauthors_domain_model_authors.pid,\'###PAGE_TSCONFIG_IDLIST###\')) OR (\'###PAGE_TSCONFIG_IDLIST###\' = \'0\')) AND tx_rkwauthors_domain_model_authors.sys_language_uid = ###REC_FIELD_sys_language_uid### ORDER BY tx_rkwauthors_domain_model_authors.last_name ASC', 'maxitems' => 1, 'minitems' => 0, 'size' => 5, ], ]; } \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('tt_content', $tmpCols); \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes( 'tt_content', '--div--;LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tt_content.tx_rkwnewsletter;,tx_rkwnewsletter_is_editorial, tx_rkwnewsletter_authors' ); }, 'rkw_newsletter' ); <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\ViewHelpers\Mailing; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Fluid\View\StandaloneView; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; /** * GetCacheIdentifierViewHelperTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class GetCacheIdentifierViewHelperTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/GetCacheIdentifierViewHelperTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \TYPO3\CMS\Fluid\View\StandaloneView|null */ private ?StandaloneView $standAloneViewHelper = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository issueRepository */ $this->issueRepository = $this->objectManager->get(IssueRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository topicRepository */ $this->topicRepository = $this->objectManager->get(TopicRepository::class); /** @var \TYPO3\CMS\Fluid\View\StandaloneView standAloneViewHelper */ $this->standAloneViewHelper = $this->objectManager->get(StandaloneView::class); $this->standAloneViewHelper->setTemplateRootPaths( [ 0 => self::FIXTURE_PATH . '/Frontend/Templates' ] ); } //============================================= /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsIdentifierWithTopicAFirst() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * When the ViewHelper is rendered with topic-parameter in the order A-B * Then a string is returned * Then this string starts with the issue-uid * Then this string contains the topic-ids in the order A-B as second part * Then this string contains the limit of zero as third part */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $objectStorage->attach($topic2); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage ] ); self::assertEquals( '10_10-11_0', trim($this->standAloneViewHelper->render()) ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsIdentifierWithTopicBFirst() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * When the ViewHelper is rendered with topic-parameter in the order B-A * Then a string is returned * Then this string starts with the issue-uid * Then this string contains the topic-ids in the order B-A as second part * Then this string contains the limit of zero as third part */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage ] ); self::assertEquals( '10_11-10_0', trim($this->standAloneViewHelper->render()) ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsIdentifierAndRespectsLimit() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * When the ViewHelper is rendered with topic-parameter in the order B-A and with limit = 1 * Then a string is returned * Then this string starts with the issue-uid * Then this string contains the topic-ids in the order B-A as second part * Then this string contains the limit of one as third part */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage, 'limit' => 1 ] ); self::assertEquals( '10_11-10_1', trim($this->standAloneViewHelper->render()) ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsIdentifierOfAllAvailableTopics() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * When the ViewHelper is rendered without topic parameter * Then a string is returned * Then this string starts with the issue-uid * Then this string contains the topic-ids of all available topics as second part * Then this string contains the limit of zero as third part */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue ] ); self::assertEquals( '10_10-11-12_0', trim($this->standAloneViewHelper->render()) ); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Permissions; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Utility\GeneralUtility; use RKW\RkwNewsletter\Domain\Model\Pages; use RKW\RkwNewsletter\Domain\Repository\PagesRepository; use RKW\RkwNewsletter\Status\PageStatus; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Type\Bitmask\Permission; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; /** * PagePermissions * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class PagePermissions { /** * @var \RKW\RkwNewsletter\Domain\Repository\PagesRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PagesRepository $pagesRepository; /** * PersistenceManager * * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PersistenceManager $persistenceManager; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * setPermissions for page defined by given issue and topic * * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @param array $settings * @return bool * @throws \RKW\RkwNewsletter\Exception * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function setPermissions (Pages $page, array $settings = []): bool { if (! $settings) { $settings = $this->getPermissionSettings(); } $userGroupIdNames = [ 'userId', 'groupId', ]; $permissionNames = [ 'user', 'group', 'everybody', ]; $update = false; $stage = PageStatus::getStage($page); $properties = array_merge( $userGroupIdNames, $permissionNames); foreach ($properties as $propertyName) { if ( (isset($settings[$stage])) && (isset($settings[$stage][$propertyName])) && ($permission = $settings[$stage][$propertyName]) ) { // check for valid permission-values - but not the user- and group-id! if ( (! in_array($propertyName, $userGroupIdNames)) && (! self::validatePermission($permission)) ) { continue; } $setter = 'setPerms' . ucfirst($propertyName); $page->$setter($permission); $update = true; } } if ($update) { $this->pagesRepository->update($page); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Updated page permissions for page id=%s to values for "%s".', $page->getUid(), $stage ) ); } return $update; } /** * Validate the given permission value * * @param int $permission * @return bool */ public function validatePermission (int $permission): bool { if ( ($permission < Permission::NOTHING) || ($permission > Permission::ALL) ) { return false; } return true; } /** * Returns permission-settings * * @return array * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function getPermissionSettings(): array { $settings = GeneralUtility::getTypoScriptConfiguration( 'Rkwnewsletter', ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS ); return $settings['pages']['permissions'] ?: []; } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger(): Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } } <file_sep><?php namespace RKW\RkwNewsletter\Controller; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Utility\SiteUtility; use Madj2k\Postmaster\Domain\Model\QueueRecipient; use Madj2k\CoreExtended\Utility\GeneralUtility; use Madj2k\Postmaster\Domain\Repository\QueueMailRepository; use Madj2k\Postmaster\Domain\Repository\QueueRecipientRepository; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use TYPO3\CMS\Core\Context\Context; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * WebViewController * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class WebViewController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController { /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected TopicRepository $topicRepository; /** * @var \Madj2k\Postmaster\Domain\Repository\QueueMailRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected QueueMailRepository $queueMailRepository; /** * @var \Madj2k\Postmaster\Domain\Repository\QueueRecipientRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected QueueRecipientRepository $queueRecipientRepository; /** * action show * * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("issue") * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param array $topicsRaw * @param string $hash * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Core\Exception\SiteNotFoundException */ public function showAction(Issue $issue, array $topicsRaw = [], string $hash = ''): void { $queueMailId = 0; $queueRecipientId = 0; // check for queueMailId and queueRecipientId as params from redirection $rkwMailerParams = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('tx_postmaster'); if (isset($rkwMailerParams['mid'])) { $queueMailId = intval($rkwMailerParams['mid']); } if (isset($rkwMailerParams['uid'])) { $queueRecipientId = intval($rkwMailerParams['uid']); } // set default recipient based on FE-language settings – just in case /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = GeneralUtility::makeInstance(QueueRecipient::class); $queueRecipient->setLanguageCode($GLOBALS['TSFE']->config['config']['language']); $this->view->assign('queueRecipient', $queueRecipient); // check if there is a recipient given if ( /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ ($queueMail = $this->queueMailRepository->findByUid($queueMailId)) /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ && ($queueRecipient = $this->queueRecipientRepository->findByUid($queueRecipientId)) ) { // assign objects to view $this->view->assignMultiple( array( 'queueRecipient' => $queueRecipient, 'queueMail' => $queueMail, ) ); } // convert topic-ids to objects $topics = new ObjectStorage(); if ($topicsRaw) { foreach ($topicsRaw as $topicId) { if ($topic = $this->topicRepository->findByIdentifier($topicId)) { $topics->attach($topic); } } } else { foreach($issue->getPages() as $page) { /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ if ($topic = $page->getTxRkwnewsletterTopic()) { $topics->attach($topic); } } } // add paths depending on template of newsletter - including the default one! $settings = GeneralUtility::getTypoScriptConfiguration( 'Rkwnewsletter', ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK ); $layoutPaths = $settings['view']['newsletter']['layoutRootPaths']; $layoutPathsNew = []; if (is_array($layoutPaths)) { foreach ($layoutPaths as $path) { $path = trim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $layoutPathsNew[] = $path . 'Default'; if ($issue->getNewsletter()->getTemplate() != 'Default') { $layoutPathsNew[] = $path . $issue->getNewsletter()->getTemplate(); } } } $partialPaths = $settings['view']['newsletter']['partialRootPaths']; $partialPathsNew = []; if (is_array($partialPaths)) { foreach ($partialPaths as $path) { $path = trim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $partialPathsNew[] = $path . 'Default'; if ($issue->getNewsletter()->getTemplate() != 'Default') { $partialPathsNew[] = $path . $issue->getNewsletter()->getTemplate(); } } } $this->view->setLayoutRootPaths($layoutPathsNew); $this->view->setPartialRootPaths($partialPathsNew); // override maxContentItems $settings['settings']['maxContentItems'] = 9999; $this->view->assignMultiple( array( 'issue' => $issue, 'topics' => $topics, 'hash' => $hash, 'settings' => $settings['settings'], 'isWebView' => true ) ); } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Mailing; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use RKW\RkwNewsletter\Domain\Model\Content; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Pages; use RKW\RkwNewsletter\Domain\Model\Topic; use RKW\RkwNewsletter\Domain\Repository\ContentRepository; use RKW\RkwNewsletter\Mailing\ContentLoader; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * ContentLoaderTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ContentLoaderTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/ContentLoaderTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Mailing\ContentLoader|null */ private ?ContentLoader $subject = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\ContentRepository|null */ private ?ContentRepository $contentRepository = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository issueRepository */ $this->issueRepository = $this->objectManager->get(IssueRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository topicRepository */ $this->topicRepository = $this->objectManager->get(TopicRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\ContentRepository contentRepository */ $this->contentRepository = $this->objectManager->get(ContentRepository::class); /** @var \RKW\RkwNewsletter\Mailing\ContentLoader $subject */ $this->subject = $this->objectManager->get(ContentLoader::class); } //============================================= /** * @test * @throws \Exception */ public function setIssueSetsIssueAndTopics() { /** * Scenario: * * Given two persisted newsletter-objects X and Y * Given a persisted issue-object M that belongs to the newsletter-object X * Given a persisted issue-object N that belongs to the newsletter-object Y * Given three persisted topic-objects A, B, C that belong to the newsletter-object X * Given a persisted topic-object D that belongs to the newsletter-object Y * Given for topic-object A there is a page-object W that belongs to the issue-object M * Given for topic-object B there is a page-object X that belongs to the issue-object M * Given for topic-object C there is a page-object Y that belongs to the issue-object M * Given for topic-object D there is a page-object Z that belongs to the issue-object N * Given the issue-object N is set via setIssue before * When method is called * Then getIssue returns the issue M that has been set * Then getTopics returns three topics * Then these topics are the topics A, B and C of the given issue M */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check110.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueOne */ $issueOne = $this->issueRepository->findByUid(110); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueTwo */ $issueTwo = $this->issueRepository->findByUid(111); $expectedTopics = []; /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ foreach($issueOne->getPages() as $page) { $expectedTopics[] = $page->getTxRkwnewsletterTopic(); } $this->subject->setIssue($issueTwo); $this->subject->setIssue($issueOne); self::assertEquals($issueOne, $this->subject->getIssue()); self::assertCount(3, $this->subject->getTopics()); self::assertEquals($expectedTopics, $this->subject->getTopics()->toArray()); } //============================================= /** * @test * @throws \Exception */ public function getOrderingReturnsAllTopicIdsOfIssue() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B, C and D * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the issue-object is set via setIssue before * When method is called * Then it returns an array * Then the array contains three key-value-pairs * Then the key of topic A contains the value 0 * Then the key of topic B contains the value 1 * Then the key of topic C contains the value 2 * Then topic D is not part of the array */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $this->subject->setIssue($issue); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(3, $result); self::assertEquals(0, $result[10]); self::assertEquals(1, $result[11]); self::assertEquals(2, $result[12]); } //============================================= /** * @test * @throws \Exception */ public function getTopicsReturnsAllTopicsOfIssue() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B, C and D * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the issue-object is set via setIssue before * When method is called * Then it returns an ObjectStorage * Then the ObjectStorage contains three topic-objects * Then topic D is not part of the ObjectStorage */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $this->subject->setIssue($issue); $result = $this->subject->getTopics(); self::assertInstanceOf(ObjectStorage::class, $result); self::assertCount(3, $result); $result = $result->toArray(); self::assertInstanceOf(Topic::class, $result[0]); self::assertInstanceOf(Topic::class, $result[1]); self::assertInstanceOf(Topic::class, $result[2]); } //============================================= /** * @comment: not needed anymore! * @throws \Exception */ public function setTopicsThrowsException() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B, C and D * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the issue-object is set via setIssue before * When the method is called with sorting-parameter with one topic-object and one issue-object * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1649840507 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1649840507); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); $this->subject->setIssue($issue); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $objectStorage->attach(GeneralUtility::makeInstance(Issue::class)); $this->subject->setTopics($objectStorage); } /** * @test * @throws \Exception */ public function setTopicsUpdatesOrderingToTopicAFirst() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B, C and D * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the issue-object is set via setIssue before * When the method is called with two topic-objects in the order topic A/topic B * Then getSorting returns an array * Then the array contains two key-value-pairs * Then the key of topic A contains the value 0 * Then the key of topic B contains the value 1 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $objectStorage->attach($topic2); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(0, $result[10]); self::assertEquals(1, $result[11]); } /** * @test * @throws \Exception */ public function setTopicsUpdatesOrderingToTopicBFirst() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B, C and D * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the issue-object is set via setIssue before * When method is called with two topic-objects in the order topic B/topic A * Then getSorting returns an array * Then the array contains two key-value-pairs * Then the key of topic A contains the value 1 * Then the key of topic B contains the value 0 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(1, $result[10]); self::assertEquals(0, $result[11]); } /** * @test * @throws \Exception */ public function setTopicsUpdatesOrderingToSpecialTopicFirst() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given topic-object C is marked as special topic * Given the issue-object is set via setIssue before * When method is called with two topic-objects in the order topic B/topic A * Then getSorting returns an array * Then the array contains three key-value-pairs * Then the key of topic C contains the value 0 * Then the key of topic B contains the value 1 * Then the key of topic A contains the value 2 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(81); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(3, $result); self::assertEquals(0, $result[82]); self::assertEquals(1, $result[81]); self::assertEquals(2, $result[80]); } /** * @test * @throws \Exception */ public function setTopicsUpdatesOrderingToTopicBFirstWithSpecialTopic() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given topic-object C is marked as special topic * Given the issue-object is set via setIssue before * When the method is called with two topic-objects in the order topic B/topic A/topic C * Then getSorting returns an array * Then the array contains three key-value-pairs * Then the key of topic B contains the value 0 * Then the key of topic A contains the value 1 * Then the key of topic C contains the value 2 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(81); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic3 = $this->topicRepository->findByUid(82); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $objectStorage->attach($topic3); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(3, $result); self::assertEquals(0, $result[81]); self::assertEquals(1, $result[80]); self::assertEquals(2, $result[82]); } /** * @test * @throws \Exception */ public function setTopicsIgnoresTopicsOfOtherNewsletters() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted newsletter-object Y * Given a persisted issue-object K that belongs to the newsletter-object X * Given a persisted issue-object L that belongs to the newsletter-object Y * Given two persisted topic-objects A and B that belong to the the newsletter-object X * Given one persisted topic-object C that belongs to the the newsletter-object Y * Given for topic-object A there is a page-object X that belongs to the current issue-object K * Given for topic-object B there is a page-object Y that belongs to the current issue-object K * Given for topic-object C there is a page-object Z that belongs to the current issue-object L * Given the issue-object is set via setIssue before * When the method is called with three topic-objects in the order topic B/topic A/topic C * Then getSorting returns an array * Then the array contains two key-value-pairs * Then the key of topic B contains the value 0 * Then the key of topic A contains the value 1 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(161); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic3 */ $topic3 = $this->topicRepository->findByUid(162); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $objectStorage->attach($topic3); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(0, $result[161]); self::assertEquals(1, $result[160]); } //============================================= /** * @test * @throws \Exception */ public function addTopicUpdatesOrdering() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B, C and D * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given setTopics is called with topic-object B only * Then this method is called with topic-object A * Then getSorting returns an array * Then the array contains two key-value-pairs * Then the key of topic A contains the value 1 * Then the key of topic B contains the value 0 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $this->subject->addTopic($topic1); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(1, $result[10]); self::assertEquals(0, $result[11]); } /** * @test * @throws \Exception */ public function addTopicUpdatesOrderingWithSpecialTopicFirst() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given topic-object C is marked as special topic * Given setTopics is called with topic-object B only * Then this method is called with topic-object A * Then getSorting returns an array * Then the array contains three key-value-pairs * Then the key of topic C contains the value 0 * Then the key of topic B contains the value 1 * Then the key of topic A contains the value 2 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(81); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $this->subject->addTopic($topic1); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(3, $result); self::assertEquals(0, $result[82]); self::assertEquals(1, $result[81]); self::assertEquals(2, $result[80]); } /** * @test * @throws \Exception */ public function addTopicIgnoresTopicOfOtherNewsletters() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted newsletter-object Y * Given a persisted issue-object K that belongs to the newsletter-object X * Given a persisted issue-object L that belongs to the newsletter-object Y * Given two persisted topic-objects A and B that belong to the the newsletter-object X * Given one persisted topic-object C that belongs to the the newsletter-object Y * Given for topic-object A there is a page-object X that belongs to the current issue-object K * Given for topic-object B there is a page-object Y that belongs to the current issue-object K * Given for topic-object C there is a page-object Z that belongs to the current issue-object L * Given the issue-object is set via setIssue before * Given setTopics is called with topic-objects B and A * When the method is called with topic-object C * Then getSorting returns an array * Then the array contains two key-value-pairs * Then the key of topic B contains the value 0 * Then the key of topic A contains the value 1 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(161); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic3 */ $topic3 = $this->topicRepository->findByUid(162); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $this->subject->addTopic($topic3); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(0, $result[161]); self::assertEquals(1, $result[160]); } //============================================= /** * @test * @throws \Exception */ public function removeTopicUpdatesOrdering() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B, C and D * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given setTopics is called with two topic-objects in the order topic B/topic A * Then this method is called with topic-object B * Then getSorting returns an array * Then the array contains one key-value-pair * Then the key of topic A contains the value 1 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $this->subject->removeTopic($topic2); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(1, $result); self::assertEquals(0, $result[10]); } /** * @test * @throws \Exception */ public function removeTopicUpdatesOrderingWithSpecialTopicFirst() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given topic-object C is marked as special topic * Given setTopics is called with two topic-objects in the order topic B/topic A * Then this method is called with topic-object B * Then getSorting returns an array * Then the array contains two key-value-pair * Then the key of topic C contains the value 0 * Then the key of topic A contains the value 1 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(81); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $this->subject->removeTopic($topic2); $result = $this->subject->getOrdering(); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(0, $result[82]); self::assertEquals(1, $result[80]); } //============================================= /** * @test * @throws \Exception */ public function getContentsReturnsSortedContents() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * Given setTopics is called with two topic-objects in the order topic B/topic A * Given the issue-object is set via setIssue before * When the method is called * Then an array of the size of five is returned * Then the items are instances of \RKW\RkwNewsletter\Domain\Model\Content * Then the array starts with contents of topic B * Then the array is ordered in zipper-method respecting the defined order of contents (database) * Then the contents marked as editorial are ignored * Then no contents of topic C are included */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(21); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getContents(); self::assertIsArray( $result); self::assertCount(5, $result); $content = $result[0]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 21.2', $content->getHeader()); $content = $result[1]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 20.2', $content->getHeader()); $content = $result[2]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 21.3', $content->getHeader()); $content = $result[3]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 20.3', $content->getHeader()); $content = $result[4]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 20.4', $content->getHeader()); } /** * @test * @throws \Exception */ public function getContentsReturnsSortedContentsAndRespectsLimit() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with two topic-objects in the order topic B/topic A * When the method is called with limit = 1 * Then an array of the size of two is returned * Then the items are instances of \RKW\RkwNewsletter\Domain\Model\Content * Then the array starts with contents of topic B * Then the array is ordered in zipper-method respecting the defined order of contents (database) * Then only one content of each topic A and B is included * Then the contents marked as editorial are ignored * Then no contents of topic C are included */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(21); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getContents(1); self::assertIsArray( $result); self::assertCount(2, $result); $content = $result[0]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 21.2', $content->getHeader()); $content = $result[1]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 20.2', $content->getHeader()); } /** * @test * @throws \Exception */ public function getContentsReturnsSortedContentsAndIgnoresEmptyTopics() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains no content-objects * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with two topic-objects in the order topic A/topic B * When the method is called * Then an array of the size of three is returned * Then the items are instances of \RKW\RkwNewsletter\Domain\Model\Content * Then the array contains only contents of topic B respecting the defined order of contents (database) * Then the contents marked as editorial are ignored * Then no contents of topic C are included */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(40); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(40); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(41); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getContents(); self::assertIsArray( $result); self::assertCount(3, $result); $content = $result[0]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 40.2', $content->getHeader()); $content = $result[1]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 40.3', $content->getHeader()); $content = $result[2]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 40.4', $content->getHeader()); } /** * @test * @throws \Exception */ public function getContentsReturnsSortedContentsOfAllTopicsOfIssue() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given four persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that does NOT belong to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given addTopic is called with topic C before * When the method is called * Then an array of the size of five is returned * Then the items are instances of \RKW\RkwNewsletter\Domain\Model\Content * Then the array starts with contents of topic A * Then the array is ordered in zipper-method respecting the defined order of contents (database) * Then the contents marked as editorial are ignored * Then the contents of topic C are ignored */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(92); $this->subject->setIssue($issue); $this->subject->addTopic($topic); $result = $this->subject->getContents(); self::assertIsArray( $result); self::assertCount(5, $result); $content = $result[0]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 90.2', $content->getHeader()); $content = $result[1]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 91.2', $content->getHeader()); $content = $result[2]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 90.3', $content->getHeader()); $content = $result[3]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 91.3', $content->getHeader()); $content = $result[4]; self::assertInstanceOf(Content::class, $content); self::assertEquals('Content 90.4', $content->getHeader()); } //============================================= /** * @test * @throws \Exception */ public function getFirstHeadlineReturnsFirstHeadline() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with two topic-objects in the order topic B/topic A * When the method is called * Then a string is returned * Then the string is the headline of the first content of topic B * Then the contents marked as editorial are ignored */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(21); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getFirstHeadline(); self::assertIsString( $result); self::assertEquals('Content 21.2', $result); } /** * @test * @throws \Exception */ public function getFirstHeadlineReturnsEmptyIfFirstIsEmpty() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with two topic-objects in the order topic B/topic A * When the method is called * Then a string is returned * Then the string is empty */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(31); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getFirstHeadline(); self::assertIsString( $result); self::assertEmpty($result); } /** * @test * @throws \Exception */ public function getFirstHeadlineIgnoresEditorials() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with topic-object B only * When the method is called * Then a string is returned * Then the string is the headline of the first content of topic B * Then the contents marked as editorial are ignored even if there is only one topic given */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(21); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getFirstHeadline(); self::assertIsString( $result); self::assertEquals('Content 21.2', $result); } //============================================= /** * @test * @throws \Exception */ public function getTopicOfContentReturnsTopicOfContent() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted page-object B * Given that page-object B belongs to the newsletter-object X * Given that page-object B belongs to the issue-object Y * Given that page-object B belongs to the topic-object A * Given a persisted content-object C * Given that content-object C belongs to the page-object B * Given the issue-object is set via setIssue before * When the method is called with content-object C as parameter * Then the topic-object A is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(50); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->contentRepository->findByUid(50); $this->subject->setIssue($issue); $result = $this->subject->getTopicOfContent($content); self::assertInstanceOf(Topic::class, $result); self::assertEquals(50, $result->getUid()); } /** * @test * @throws \Exception */ public function getTopicOfContentReturnsNull() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted page-object B * Given that page-object B belongs to the newsletter-object X * Given that page-object B belongs to the issue-object Y * Given that page-object does not belong to the topic-object A * Given a persisted content-object C * Given that content-object C belongs to the page-object B * Given the issue-object is set via setIssue before * When the method is called with content-object C as parameter * Then null is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(60); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->contentRepository->findByUid(60); $this->subject->setIssue($issue); $result = $this->subject->getTopicOfContent($content); self::assertNull($result); } //============================================= /** * @test * @throws \Exception */ public function getEditorialReturnsNullForAllTopics() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * When the method is called * Then null is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(70); $this->subject->setIssue($issue); $result = $this->subject->getEditorial(); self::assertNull($result); } /** * @test * @throws \Exception */ public function getEditorialReturnsNullIfOneTopicUsedButNoEditorial() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called before with topic A only * When the method is called * Then null is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(70); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(70); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getEditorial(); self::assertNull($result); } /** * @test * @throws \Exception */ public function getEditorialReturnsContentIfOneTopicUsedWithEditorial() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called before with topic B only * When the method is called * Then an object of instance \RKW\RkwNewsletter\Domain\Model\Content is returned * Then this object is the editorial of the given topic B */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(70); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(71); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); /** @var \RKW\RkwNewsletter\Domain\Model\Content $result */ $result = $this->subject->getEditorial(); self::assertInstanceOf(Content::class, $result); self::assertEquals(1, $result->getTxRkwnewsletterIsEditorial()); self::assertEquals('Content 71.1', $result->getHeader()); } /** * @test * @throws \Exception */ public function getEditorialReturnsContentIfSpecialTopicOnlyWithEditorial() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given topic-object B is marked as special * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with an empty ObjectStorage before (= no topics set) * When the method is called * Then an object of instance \RKW\RkwNewsletter\Domain\Model\Content is returned * Then this object is the editorial of the given topic B */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check100.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(100); $this->subject->setIssue($issue); $this->subject->setTopics(new ObjectStorage()); /** @var \RKW\RkwNewsletter\Domain\Model\Content $result */ $result = $this->subject->getEditorial(); self::assertInstanceOf(Content::class, $result); self::assertEquals(1, $result->getTxRkwnewsletterIsEditorial()); self::assertEquals('Content 71.1', $result->getHeader()); } /** * @test * @throws \Exception */ public function getEditorialReturnsContentIfEmptyTopicAndSpecialTopicWithEditorial() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given topic-object B is marked as special * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with topic A only * When the method is called * Then an object of instance \RKW\RkwNewsletter\Domain\Model\Content is returned * Then this object is the editorial of the given topic B */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(150); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(150); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); /** @var \RKW\RkwNewsletter\Domain\Model\Content $result */ $result = $this->subject->getEditorial(); self::assertInstanceOf(Content::class, $result); self::assertEquals(1, $result->getTxRkwnewsletterIsEditorial()); self::assertEquals('Content 151.1', $result->getHeader()); } //============================================= /** * @test * @throws \Exception */ public function getPagesReturnsRelevantPagesInTopicOrder() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted topic-object C that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given that page-object S belongs to the newsletter-object X * Given that page-object S belongs to the issue-object Y * Given that page-object S belongs to the topic-object C * Given the issue-object is set via setIssue before * Given setTopics is called with topic B/topic A * When the method is called * Then an array is returned * Then this array contains two items of \RKW\RkwNewsletter\Domain\Model\Pages * Then the first item is page R * Then the second item is page Q */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check120.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(120); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(120); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(121); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); /** @var array $result */ $result = $this->subject->getPages(); self::assertIsArray( $result); self::assertCount(2, $result); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $result[0]; self::assertInstanceOf(Pages::class, $page); self::assertEquals(121 , $page->getUid()); $page = $result[1]; self::assertInstanceOf(Pages::class, $page); self::assertEquals(120, $page->getUid()); } /** * @test * @throws \Exception */ public function getPagesReturnsEmptyArray() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted topic-object C that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given that page-object S belongs to the newsletter-object X * Given that page-object S belongs to the issue-object Y * Given that page-object S belongs to the topic-object C * Given the issue-object is set via setIssue before * Given setTopics is called with an empty ObjectStorage (=no topics set) * When the method is called * Then an array is returned * Then this array is empty */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check120.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(120); $this->subject->setIssue($issue); $this->subject->setTopics(new ObjectStorage()); /** @var array $result */ $result = $this->subject->getPages(); self::assertIsArray( $result); self::assertCount(0, $result); } /** * @test * @throws \Exception */ public function getPagesReturnsIgnoresPagesWithoutTopic() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted topic-object C that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to no topic-object * Given that page-object S belongs to the newsletter-object X * Given that page-object S belongs to the issue-object Y * Given that page-object S belongs to the topic-object C * Given the issue-object is set via setIssue before * Given setTopics is called with topic B/topic A * When the method is called * Then an array is returned * Then this array contains one item of \RKW\RkwNewsletter\Domain\Model\Pages * Then this item is page Q */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check130.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(130); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(130); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(131); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); /** @var array $result */ $result = $this->subject->getPages(); self::assertIsArray( $result); self::assertCount(1, $result); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $result[0]; self::assertInstanceOf(Pages::class, $page); self::assertEquals(131 , $page->getUid()); } //============================================= /** * @test * @throws \Exception */ public function hasContentReturnsTrue() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains one content-object * Given this content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with topic B/topic A * When the method is called * Then true returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(140); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(140); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(141); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertTrue($this->subject->hasContents()); } /** * @test * @throws \Exception */ public function hasContentReturnsTrueOnEditorialOnly() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains one content-object * Given this content-object is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with topic B only * When the method is called * Then true returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(140); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(141); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertTrue($this->subject->hasContents()); } //============================================= /** * @test * @throws \Exception */ public function countTopicsWithContentsReturnsOneForNormalContent () { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains one content-object * Given this content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with topic B/topic A * When the method is called * Then one returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(140); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(140); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(141); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertEquals(1, $this->subject->countTopicsWithContents()); } /** * @test * @throws \Exception */ public function countTopicsWithContentsReturnsZeroForTopicWithEditorialOnly() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains one content-object * Given this content-object is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with topic B only * When the method is called * Then true returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(140); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(141); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertEquals(0, $this->subject->countTopicsWithContents()); } /** * @test * @throws \Exception */ public function countTopicsWithContentsReturnsOneForNonSetSpecialTopic() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given topic-object B is marked as special * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given the issue-object is set via setIssue before * Given setTopics is called with topic A only * When the method is called * Then one is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(150); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(150); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertEquals(1, $this->subject->countTopicsWithContents()); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers\Mailing\Content; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Content; use RKW\RkwNewsletter\Mailing\ContentLoader; use RKW\RkwNewsletter\ViewHelpers\Mailing\AbstractViewHelper; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * GetTopicNameViewHelper * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class GetTopicNameViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('content', Content::class, 'Content to get topic for.', true); } /** * Gets the contents of the given issue and respects given topics * * @return string */ public function render(): string { /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->arguments['issue']; /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->arguments['content']; /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Mailing\ContentLoader $contentLoader */ $contentLoader = $objectManager->get(ContentLoader::class, $issue); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ if ($topic = $contentLoader->getTopicOfContent($content)) { return $topic->getName(); } return ''; } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Utility\GeneralUtility; use \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper; /** * IsMandatoryFieldViewHelper * * returns true, if given field is mandatory * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later * @todo rework and write tests */ class IsMandatoryFieldViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('fieldName', 'string', 'FieldName to check for', true); } /** * @return boolean * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function render(): bool { $fieldName = $this->arguments['fieldName']; $settings = GeneralUtility::getTypoScriptConfiguration('Rkwnewsletter'); $requiredFields = array('email'); if ($settings['requiredFieldsSubscription']) { $requiredFields = array_merge( $requiredFields, GeneralUtility::trimExplode( ',', $settings['requiredFieldsSubscription'], true ) ); } return in_array($fieldName, $requiredFields); } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Repository; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings; use TYPO3\CMS\Extbase\Persistence\QueryResultInterface; /** * ApprovalRepository * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ApprovalRepository extends AbstractRepository { /** * @return void * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function initializeObject(): void { parent::initializeObject(); $this->defaultQuerySettings = $this->objectManager->get(Typo3QuerySettings::class); $this->defaultQuerySettings->setRespectStoragePage(false); } /** * findAllOpenApprovals * * @param int $toleranceLevel2 * @param int $toleranceLevel1 * @param int $toleranceStage1 * @param int $toleranceStage2 * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * comment: implicitly tested */ public function findAllForConfirmationByTolerance( int $toleranceLevel1, int $toleranceLevel2, int $toleranceStage1 = 0, int $toleranceStage2 = 0 ): QueryResultInterface { $query = $this->createQuery(); $constraints = []; // Check for info/reminder settings on stage 1 $constraints[] = $query->logicalAnd( $query->equals('allowedTstampStage1', 0), $query->logicalOr( $query->equals('sentInfoTstampStage1', 0), $query->logicalAnd( $query->lessThan('sentInfoTstampStage1', time() - $toleranceLevel1), $query->equals('sentReminderTstampStage1', 0) ) ) ); // Check for info/reminder on stage 2 $constraints[] = $query->logicalAnd( $query->greaterThan('allowedTstampStage1', 0), $query->equals('allowedTstampStage2', 0), $query->logicalOr( $query->equals('sentInfoTstampStage2', 0), $query->logicalAnd( $query->lessThan('sentInfoTstampStage2', time() - $toleranceLevel2), $query->equals('sentReminderTstampStage2', 0) ) ) ); // Check for automatic approval on stage 1 if ($toleranceStage1) { $constraints[] = $query->logicalAnd( $query->lessThan('sentInfoTstampStage1', time() - $toleranceStage1), $query->greaterThan('sentInfoTstampStage1', 0), $query->greaterThan('sentReminderTstampStage1', 0), $query->equals('allowedTstampStage1', 0) ); } // Check for automatic approval on stage 2 if ($toleranceStage2) { $constraints[] = $query->logicalAnd( $query->lessThan('sentInfoTstampStage2', time() - $toleranceStage2), $query->greaterThan('sentInfoTstampStage2', 0), $query->greaterThan('sentReminderTstampStage2', 0), $query->greaterThan('allowedTstampStage1', 0), $query->equals('allowedTstampStage2', 0) ); } // Build query $query->matching( $query->logicalAnd( $query->logicalOr( $constraints ), $query->equals('issue.status', 1), $query->equals('issue.sentTstamp', 0), $query->equals('issue.releaseTstamp', 0) ) ); return $query->execute(); } } <file_sep><?php namespace RKW\RkwNewsletter\Command; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Manager\IssueManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * class CreateIssuesCommand * * Execute on CLI with: 'vendor/bin/typo3 rkw_newsletter:createIssues' * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class CreateIssuesCommand extends Command { /** * @var \RKW\RkwNewsletter\Manager\IssueManager|null */ protected ?IssueManager $issueManager = null; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * Configure the command by defining the name, options and arguments */ protected function configure(): void { $this->setDescription('Creates issues for all newsletters.') ->addOption( 'tolerance', 't', InputOption::VALUE_REQUIRED, 'Tolerance for creating next issue according to last time an issue was built (in seconds, default: 604800)', 604800 ); } /** * Initializes the command after the input has been bound and before the input * is validated. * * This is mainly useful when a lot of commands extends one main command * where some things need to be initialized based on the input arguments and options. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @see \Symfony\Component\Console\Input\InputInterface::bind() * @see \Symfony\Component\Console\Input\InputInterface::validate() */ protected function initialize(InputInterface $input, OutputInterface $output): void { /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->issueManager = $objectManager->get(IssueManager::class); } /** * Executes the command for showing sys_log entries * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return int * @see \Symfony\Component\Console\Input\InputInterface::bind() * @see \Symfony\Component\Console\Input\InputInterface::validate() */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title($this->getDescription()); $tolerance = $input->getOption('tolerance'); $result = 0; try { /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Manager\IssueManager $issueManager */ $issueManager = $objectManager->get(IssueManager::class); if ($issueManager->buildAllIssues($tolerance)) { $io->note('Successfully created new issues.'); } else { $io->note('No new issues created.'); } } catch (\Exception $e) { $message = sprintf('An unexpected error occurred while trying to update the statistics of e-mails: %s', str_replace(array("\n", "\r"), '', $e->getMessage()) ); $io->error($message); $this->getLogger()->log(LogLevel::ERROR, $message); $result = 1; } $io->writeln('Done'); return $result; } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger(): Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Repository; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Pages; use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Extbase\Persistence\QueryInterface; use TYPO3\CMS\Extbase\Persistence\QueryResultInterface; /** * ContentRepository * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ContentRepository extends AbstractRepository { /* * initializeObject */ public function initializeObject(): void { parent::initializeObject(); $this->defaultQuerySettings = $this->objectManager->get(Typo3QuerySettings::class); $this->defaultQuerySettings->setRespectStoragePage(false); $this->defaultQuerySettings->setRespectSysLanguage(false); } /** * findByPageAndLanguageUid * * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @param int $languageUid * @param int $limit * @param bool $includeEditorials * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * comment: implicitly tested */ public function findByPageAndLanguage( Pages $page, int $languageUid = 0, int $limit = 0, bool $includeEditorials = false ): QueryResultInterface { $query = $this->createQuery(); $constraints = [ $query->equals('pid', $page), $query->equals('sysLanguageUid', $languageUid) ]; if (! $includeEditorials) { $constraints[] = $query->equals('txRkwnewsletterIsEditorial', 0); } $query->matching( $query->logicalAnd($constraints) ); $query->setOrderings( array( 'sorting' => QueryInterface::ORDER_ASCENDING, ) ); if ($limit > 0) { $query->setLimit($limit); } return $query->execute(); } /** * countByPageAndLanguageUid * * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @param int $languageUid * @param bool $includeEditorials * @return int * comment: implicitly tested */ public function countByPageAndLanguage( Pages $page, int $languageUid = 0, bool $includeEditorials = false ): int { $query = $this->createQuery(); $constraints = [ $query->equals('pid', $page), $query->equals('sysLanguageUid', $languageUid) ]; if (! $includeEditorials) { $constraints[] = $query->equals('txRkwnewsletterIsEditorial', 0); } $query->matching( $query->logicalAnd($constraints) ); return $query->execute()->count(); } /** * countByPagesAndLanguageUid * * @param array<\RKW\RkwNewsletter\Domain\Model\Pages> $pages * @param int $languageUid * @param bool $includeEditorials * @return int * comment: implicitly tested * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function countByPagesAndLanguage( array $pages, int $languageUid = 0, bool $includeEditorials = false ): int { $query = $this->createQuery(); $constraints = [ $query->in('pid', $pages), $query->equals('sysLanguageUid', $languageUid) ]; if (! $includeEditorials) { $constraints[] = $query->equals('txRkwnewsletterIsEditorial', 0); } $query->matching( $query->logicalAnd($constraints) ); $query->setOrderings( array( 'sorting' => QueryInterface::ORDER_ASCENDING, ) ); return $query->execute()->count(); } /** * findOneEditorialsByPagesAndLanguage * * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @param int $languageUid * @return \RKW\RkwNewsletter\Domain\Model\Content|null * comment: implicitly tested */ public function findOneEditorialByPageAndLanguage( Pages $page, int $languageUid = 0 ) { $query = $this->createQuery(); $query->matching( $query->logicalAnd( $query->equals('pid', $page), $query->equals('sysLanguageUid', $languageUid), $query->equals('txRkwnewsletterIsEditorial', 1) ) ); return $query->execute()->getFirst(); } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Status; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\PagesRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use RKW\RkwNewsletter\Status\PageStatus; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * PageStatusTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class PageStatusTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/PageStatusTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Status\PageStatus|null */ private ?PageStatus $subject = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\PagesRepository|null */ private ?PagesRepository $pagesRepository = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(static::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', static::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $this->objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->issueRepository = $this->objectManager->get(IssueRepository::class); $this->topicRepository = $this->objectManager->get(TopicRepository::class); $this->pagesRepository = $this->objectManager->get(PagesRepository::class); $this->subject = $this->objectManager->get(PageStatus::class); } //============================================= /** * @test * @throws \Exception */ public function getStageReturnsDraft() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 0 * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * Given that approval-object has no value for the allowedTstampStage1-property set * Given that approval-object has no value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::DRAFT is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(10); self::assertEquals($this->subject::DRAFT, $this->subject::getStage($page)); } /** * @test * @throws \Exception */ public function getStageReturnsStage1() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 1 * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * Given that approval-object has no value for the allowedTstampStage1-property set * Given that approval-object has no value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::APPROVAL_1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(20); self::assertEquals($this->subject::APPROVAL_1, $this->subject::getStage($page)); } /** * @test * @throws \Exception */ public function getStageReturnsStage2() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 1 * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * Given that approval-object has a value for the allowedTstampStage1-property set * Given that approval-object has no value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::APPROVAL_2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(30); self::assertEquals($this->subject::APPROVAL_2, $this->subject::getStage($page)); } /** * @test * @throws \Exception */ public function getStageReturnsReleaseWhenStage2Done() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 1 * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * Given that approval-object has a value for the allowedTstampStage1-property set * Given that approval-object has a value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::RELEASE is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(40); self::assertEquals($this->subject::RELEASE, $this->subject::getStage($page)); } /** * @test * @throws \Exception */ public function getStageReturnsRelease() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 2 * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * Given that approval-object has no value for the allowedTstampStage1-property set * Given that approval-object has no value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::RELEASE is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(50); self::assertEquals($this->subject::RELEASE, $this->subject::getStage($page)); } /** * @test * @throws \Exception */ public function getStageReturnsSending() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 3 * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * Given that approval-object has no value for the allowedTstampStage1-property set * Given that approval-object has no value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::SENDING is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(60); self::assertEquals($this->subject::SENDING, $this->subject::getStage($page)); } /** * @test * @throws \Exception */ public function getStageReturnsDone() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 4 * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * Given that approval-object has no value for the allowedTstampStage1-property set * Given that approval-object has no value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::DONE is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(70); self::assertEquals($this->subject::DONE, $this->subject::getStage($page)); } //============================================= /** * @test * @throws \Exception */ public function getApprovalThrowsExceptionOnNonMatchingTopic() { /** * Scenario: * * Given a persisted issue-object * Given a persisted topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object does not belong to the topic-object * When the method is called * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1644845316 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1644845316); $this->importDataSet(self::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(80); $this->subject::getApproval($issue, $topic); } /** * @test * @throws \Exception */ public function getApprovalThrowsExceptionOnNonExistingApproval() { /** * Scenario: * * Given a persisted issue-object * Given a persisted topic-object * Given no persisted approval-object * When the method is called * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1644845316 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1644845316); $this->importDataSet(self::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(90); $this->subject::getApproval($issue, $topic); } /** * @test * @throws \Exception */ public function getApprovalReturnsApprovalObject() { /** * Scenario: * * Given a persisted issue-object * Given a persisted topic-object * Given a persisted approval-object * Given that approval-object belongs to the issue-object * Given that approval-object belongs to the topic-object * When the method is called * Then an instance of \RKW\RkwNewsletter\Domain\Model\Approval is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check100.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(100); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(100); self::assertInstanceOf( \RKW\RkwNewsletter\Domain\Model\Approval::class, $this->subject::getApproval($issue, $topic) ); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php defined('TYPO3_MODE') || die('Access denied.'); call_user_func( function () { // extend "fe_users" TCA $tmpColsUser = [ 'tx_rkwnewsletter_subscription' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:fe_user.tx_rkwnewsletter_domain_model_subscription', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'size' => 8, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 9999, 'foreign_table' => 'tx_rkwnewsletter_domain_model_topic', 'foreign_table_where' => 'AND tx_rkwnewsletter_domain_model_topic.deleted = 0 AND tx_rkwnewsletter_domain_model_topic.hidden = 0', 'itemsProcFunc' => 'RKW\RkwNewsletter\TCA\OptionLabels->getNewsletterTopicTitlesWithRootByUid', ], ], 'tx_rkwnewsletter_hash' => [ 'config' => [ 'type' => 'passthrough', ], ], 'tx_rkwnewsletter_priority' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:fe_user.tx_rkwnewsletter_priority', 'config' => [ 'type' => 'check', 'default' => 0, ], ], ]; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns( 'fe_users', $tmpColsUser ); \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes( 'fe_users', '--div--;LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter;,tx_rkwnewsletter_subscription, tx_rkwnewsletter_priority', '0' ); } ); <file_sep><?php namespace RKW\RkwNewsletter\Status; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Issue; /** * IssueStatus * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class IssueStatus { /** * @var int */ const STAGE_DRAFT = 0; /** * @var int */ const STAGE_APPROVAL = 1; /** * @var int */ const STAGE_RELEASE = 2; /** * @var int */ const STAGE_SENDING = 3; /** * @var int */ const STAGE_DONE = 4; /** * @var int */ const LEVEL_NONE = 0; /** * @var int */ const LEVEL1 = 1; /** * @var int */ const LEVEL2 = 2; /** * @var int */ const LEVEL_DONE = 3; /** * Returns current stage of the issue based on timestamps and status * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return int */ public static function getStage (Issue $issue): int { if ($issue->getStatus() == 1) { return self::STAGE_APPROVAL; } if ($issue->getStatus() == 2) { return self::STAGE_RELEASE; } if ($issue->getStatus() == 3) { return self::STAGE_SENDING; } if ($issue->getStatus() == 4) { return self::STAGE_DONE; } return self::STAGE_DRAFT; } /** * Returns current mail-status of the issue based on timestamps * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return string */ public static function getLevel (Issue $issue): string { // Only relevant for stage "release" if (self::getStage($issue) != self::STAGE_RELEASE) { return self::LEVEL_NONE; } if ( ($issue->getInfoTstamp() < 1) && ($issue->getReminderTstamp() < 1) ) { return self::LEVEL1; } if ($issue->getReminderTstamp() < 1) { return self::LEVEL2; } return self::LEVEL_DONE; } /** * Increases the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return bool */ public static function increaseStage (Issue $issue): bool { $stage = self::getStage($issue); $update = false; if ($stage == self::STAGE_DRAFT) { $issue->setStatus(self::STAGE_APPROVAL); $update = true; } if ($stage == self::STAGE_APPROVAL) { $issue->setStatus(self::STAGE_RELEASE); $update = true; } if ($stage == self::STAGE_RELEASE) { $issue->setStatus(self::STAGE_SENDING); $issue->setReleaseTstamp(time()); $update = true; } if ($stage == self::STAGE_SENDING) { $issue->setStatus(self::STAGE_DONE); $issue->setSentTstamp(time()); $update = true; } return $update; } /** * Increases the level of the release stage - only available here!!!! * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return bool */ public static function increaseLevel (Issue $issue): bool { // Only relevant for stage "release" if (self::getStage($issue) != self::STAGE_RELEASE) { return false; } $level = self::getLevel($issue); $update = false; if ($level == self::LEVEL1) { $issue->setInfoTstamp(time()); $update = true; } else if ($level == self::LEVEL2) { $issue->setReminderTstamp(time()); $update = true; } return $update; } } <file_sep><?php namespace RKW\RkwNewsletter\Service; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\Postmaster\Mail\MailMassage; use Madj2k\Postmaster\Mail\MailMessage; use RKW\RkwNewsletter\Domain\Model\Approval; use RKW\RkwNewsletter\Domain\Model\BackendUser; use RKW\RkwNewsletter\Domain\Model\Issue; use Madj2k\FeRegister\Domain\Model\FrontendUser; use Madj2k\FeRegister\Domain\Model\OptIn; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; use Madj2k\Postmaster\Utility\FrontendLocalizationUtility; /** * RkwMailService * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class RkwMailService implements \TYPO3\CMS\Core\SingletonInterface { /** * Send mail to admin for proofing a release (respectively the topics of it) * * @param array $admins * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @param int $stage * @param bool $isReminder * @return void * @throws \Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3Fluid\Fluid\View\Exception\InvalidTemplateResourceException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function sendMailAdminApproval( array $admins, Approval $approval, int $stage = 1, bool$isReminder = false ): void { // get settings $settings = $this->getSettings(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK); if ($settings['view']['templateRootPaths']) { /** @var \Madj2k\Postmaster\Mail\MailMessage $mailService */ $mailService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(MailMessage::class); /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $admin */ foreach ($admins as $admin) { if ( ($admin instanceof BackendUser) && ($admin->getEmail()) ) { // send new user an email with token $mailService->setTo($admin, array( 'marker' => array( 'approval' => $approval, 'backendUser' => $admin, 'stage' => $stage, 'isReminder' => $isReminder, ), 'subject' => FrontendLocalizationUtility::translate( ($isReminder ? 'rkwMailService.subject.adminApprovalReminder' : 'rkwMailService.subject.adminApproval'), 'rkw_newsletter', null, $admin->getLang() ), )); } } $mailService->getQueueMail()->setSubject( FrontendLocalizationUtility::translate( ($isReminder ? 'rkwMailService.subject.adminApprovalReminder' : 'rkwMailService.subject.adminApproval'), 'rkw_newsletter', null, 'de' ) ); $mailService->getQueueMail()->addTemplatePaths($settings['view']['templateRootPaths']); $mailService->getQueueMail()->addPartialPaths($settings['view']['partialRootPaths']); $mailService->getQueueMail()->setPlaintextTemplate('Email/AdminApproval'); $mailService->getQueueMail()->setHtmlTemplate('Email/AdminApproval'); $mailService->send(); } } /** * Send mail to admin for proofing a release (respectively the topics of it) * * @param array $admins * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @param int $stage * @return void * @throws \Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3Fluid\Fluid\View\Exception\InvalidTemplateResourceException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function sendMailAdminApprovalAutomatic( array $admins, Approval $approval, int $stage = 1 ): void { // get settings $settings = $this->getSettings(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK); if ($settings['view']['templateRootPaths']) { /** @var \Madj2k\Postmaster\Mail\MailMessage $mailService */ $mailService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(MailMessage::class); /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $admin */ foreach ($admins as $admin) { if ( ($admin instanceof BackendUser) && ($admin->getEmail()) ) { // send new user an email with token $mailService->setTo($admin, array( 'marker' => array( 'approval' => $approval, 'backendUser' => $admin, 'stage' => $stage, ), 'subject' => FrontendLocalizationUtility::translate( 'rkwMailService.subject.adminApprovalAutomatic', 'rkw_newsletter', null, $admin->getLang() ), )); } } $mailService->getQueueMail()->setSubject( FrontendLocalizationUtility::translate( 'rkwMailService.subject.adminApprovalAutomatic', 'rkw_newsletter', null, 'de' ) ); $mailService->getQueueMail()->addTemplatePaths($settings['view']['templateRootPaths']); $mailService->getQueueMail()->addPartialPaths($settings['view']['partialRootPaths']); $mailService->getQueueMail()->setPlaintextTemplate('Email/AdminApprovalAutomatic'); $mailService->getQueueMail()->setHtmlTemplate('Email/AdminApprovalAutomatic'); $mailService->send(); } } /** * Send mail to admin for final permission of checked issue * * @param array $admins * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param bool $isReminder * @return void * @throws \Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3Fluid\Fluid\View\Exception\InvalidTemplateResourceException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function sendMailAdminRelease( array $admins, Issue $issue, bool $isReminder = false ): void { // get settings $settings = $this->getSettings(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK); if ($settings['view']['templateRootPaths']) { /** @var \Madj2k\Postmaster\Mail\MailMessage $mailService */ $mailService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(MailMessage::class); /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $admin */ foreach ($admins as $admin) { if ( ($admin instanceof BackendUser) && ($admin->getEmail()) ) { // send new user an email with token $mailService->setTo($admin, array( 'marker' => array( 'issue' => $issue, 'backendUser' => $admin, 'isReminder' => $isReminder, ), 'subject' => FrontendLocalizationUtility::translate( ($isReminder ? 'rkwMailService.subject.adminReleaseReminder' : 'rkwMailService.subject.adminRelease'), 'rkw_newsletter', null, $admin->getLang() ), )); } } $mailService->getQueueMail()->setSubject( FrontendLocalizationUtility::translate( ($isReminder ? 'rkwMailService.subject.adminReleaseReminder' : 'rkwMailService.subject.adminRelease'), 'rkw_newsletter', null, 'de' ) ); $mailService->getQueueMail()->addTemplatePaths($settings['view']['templateRootPaths']); $mailService->getQueueMail()->addPartialPaths($settings['view']['partialRootPaths']); $mailService->getQueueMail()->setPlaintextTemplate('Email/AdminRelease'); $mailService->getQueueMail()->setHtmlTemplate('Email/AdminRelease'); $mailService->send(); } } /** * send opt-in * * @param \Madj2k\FeRegister\Domain\Model\FrontendUser $frontendUser * @param \Madj2k\FeRegister\Domain\Model\OptIn|null $optIn * @return void * @throws \Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3Fluid\Fluid\View\Exception\InvalidTemplateResourceException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function sendOptInRequest( FrontendUser $frontendUser, OptIn $optIn = null ): void { // get settings $settings = $this->getSettings(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK); $settingsDefault = $this->getSettings(); if ($settings['view']['templateRootPaths']) { /** @var \Madj2k\Postmaster\Mail\MailMessage $mailService */ $mailService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(MailMessage::class); // send new user an email with token $mailService->setTo($frontendUser, array( 'marker' => array( 'frontendUser' => $frontendUser, 'optIn' => $optIn, 'pageUid' => intval($GLOBALS['TSFE']->id), 'loginPid' => intval($settingsDefault['loginPid']), ), )); $mailService->getQueueMail()->setSubject( FrontendLocalizationUtility::translate( 'rkwMailService.subject.optInRequest', 'rkw_newsletter', array(), $frontendUser->getTxFeregisterLanguageKey() ) ); $mailService->getQueueMail()->addTemplatePaths($settings['view']['templateRootPaths']); $mailService->getQueueMail()->addPartialPaths($settings['view']['partialRootPaths']); $mailService->getQueueMail()->setPlaintextTemplate('Email/OptInRequest'); $mailService->getQueueMail()->setHtmlTemplate('Email/OptInRequest'); $mailService->send(); } } /** * Returns TYPO3 settings * * @param string $which Which type of settings will be loaded * @return array * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ protected function getSettings(string $which = ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS): array { return \Madj2k\CoreExtended\Utility\GeneralUtility::getTypoScriptConfiguration('Rkwnewsletter', $which); } } <file_sep><?php namespace RKW\RkwNewsletter\Validation\TCA; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Utility\GeneralUtility; use TYPO3\CMS\Core\Messaging\FlashMessage; use TYPO3\CMS\Core\Messaging\FlashMessageService; use \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Utility\LocalizationUtility; /** * Class FormValidator * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class NewsletterTeaserLengthEvaluation { /** * JavaScript code for client side validation/evaluation * * @return string JavaScript code for client side validation/evaluation */ public function returnFieldJS(): string { return 'return value;'; } /** * Server-side validation/evaluation on saving the record * * @param string $value The field value to be evaluated * @param string $isIn The "is_in" value of the field configuration from TCA * @param bool $set Boolean defining if the value is written to the database or not. Must be passed by reference and changed if needed. * @return string Evaluated field value * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function evaluateFieldValue(string $value, string $isIn = null, bool &$set = false): string { $settings = $this->getSettings(); if ( ($settings['minTeaserLength']) || ($settings['maxTeaserLength']) ) { /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); $flashMessageService = $objectManager->get(FlashMessageService::class); $messageQueue = $flashMessageService->getMessageQueueByIdentifier(); $strLength = strlen(strip_tags($value)); if ( ($settings['minTeaserLength']) && ($strLength > 5) && ($strLength < intval($settings['minTeaserLength'])) ) { $message = GeneralUtility::makeInstance(FlashMessage::class, LocalizationUtility::translate( 'newsletterTeaserLengthEvaluation.message.tooShort', 'rkw_newsletter', [$settings['minTeaserLength'], $strLength] ), LocalizationUtility::translate( 'newsletterTeaserLengthEvaluation.header.tooShort', 'rkw_newsletter', [$settings['minTeaserLength'], $strLength] ), FlashMessage::INFO ); $messageQueue->addMessage($message); } if ( ($settings['maxTeaserLength']) && ($strLength > intval($settings['maxTeaserLength'])) ) { $message = GeneralUtility::makeInstance(FlashMessage::class, LocalizationUtility::translate( 'newsletterTeaserLengthEvaluation.message.tooLong', 'rkw_newsletter', [$settings['maxTeaserLength'], $strLength] ), LocalizationUtility::translate( 'newsletterTeaserLengthEvaluation.header.tooLong', 'rkw_newsletter', [$settings['maxTeaserLength'], $strLength] ), FlashMessage::INFO ); $messageQueue->addMessage($message); } } return $value; } /** * Server-side validation/evaluation on opening the record * * @param array $parameters Array with key 'value' containing the field value from the database * @return string Evaluated field value */ public function deevaluateFieldValue(array $parameters): string { return $parameters['value']; } /** * Returns TYPO3 settings * * @param string $which Which type of settings will be loaded * @return array * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ protected function getSettings(string $which = ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS): array { return GeneralUtility::getTypoScriptConfiguration('Rkwnewsletter', $which); } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers\Backend; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository; /** * CountSubscriptionsViewHelper * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class CountSubscriptionsViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('newsletter', \RKW\RkwNewsletter\Domain\Model\Newsletter::class, 'Count the subscribers of this newsletter.', true); $this->registerArgument('topic', \RKW\RkwNewsletter\Domain\Model\Topic::class, 'Count the subscribers of this topic (optional).', false, null); } /** * Gets the number of subscribers for the newsletter * * @return int * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function render(): int { $newsletter = $this->arguments['newsletter']; $topic = is_object($this->arguments['topic']) ? $this->arguments['topic'] : null; /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository $frontendUserRepository */ $frontendUserRepository = $objectManager->get(FrontendUserRepository::class); if ($topic) { return $frontendUserRepository->findSubscriptionsByTopic($topic)->count(); } return $frontendUserRepository->findSubscriptionsByNewsletter($newsletter)->count(); } } <file_sep><?php namespace RKW\RkwNewsletter\Controller; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\FeRegister\Utility\FrontendUserSessionUtility; use RKW\RkwNewsletter\Domain\Model\FrontendUser; use RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository; use RKW\RkwNewsletter\Domain\Repository\NewsletterRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use Madj2k\FeRegister\Registration\FrontendUserRegistration; use Madj2k\FeRegister\Utility\FrontendUserUtility; use TYPO3\CMS\Core\Messaging\AbstractMessage; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Extbase\Utility\LocalizationUtility; /** * SubscriptionController * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class SubscriptionController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController { /** * @var \RKW\RkwNewsletter\Domain\Repository\NewsletterRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected NewsletterRepository $newsletterRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected TopicRepository $topicRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected FrontendUserRepository $frontendUserRepository; /** * FrontendUser * * @var \RKW\RkwNewsletter\Domain\Model\FrontendUser|null */ protected ?FrontendUser $frontendUser = null; /** * FrontendUser via hash, not logged in * * @var \RKW\RkwNewsletter\Domain\Model\FrontendUser|null */ protected ?FrontendUser $frontendUserByHash = null; /** * initializeAction * * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException */ public function initializeAction(): void { parent::initializeAction(); // identify user by given hash value if ( ($this->request->hasArgument('hash')) && ($this->request->getArgument('hash')) ) { $this->frontendUserByHash = $this->frontendUserRepository->findOneByTxRkwnewsletterHash( $this->request->getArgument('hash') ); // check if user could be identified if (!$this->getFrontendUserByHash()) { $this->controllerContext = $this->buildControllerContext(); $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.notIdentified', 'rkw_newsletter' ), '', AbstractMessage::ERROR ); $this->redirect('new'); } // check if user is already logged in with another id! if ( ($this->getFrontendUserByHash()) && ($this->getFrontendUserId()) && ($this->getFrontendUserId() != $this->getFrontendUserByHash()->getUid()) ) { $this->frontendUserByHash = null; $this->controllerContext = $this->buildControllerContext(); $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.alreadyLoggedIn', 'rkw_newsletter' ), '', AbstractMessage::ERROR ); $this->redirect('message'); } } } /** * Id of logged User * * @return int * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException */ protected function getFrontendUserId(): int { if ( ($frontendUser = FrontendUserSessionUtility::getLoggedInUser()) && (! FrontendUserUtility::isGuestUser($frontendUser)) ){ return $frontendUser->getUid(); } return 0; } /** * Returns current loggedin user object * * @return \RKW\RkwNewsletter\Domain\Model\FrontendUser|null * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException */ protected function getFrontendUser():? FrontendUser { if (!$this->frontendUser) { $this->frontendUser = $this->frontendUserRepository->findByIdentifier($this->getFrontendUserId()); } if ($this->frontendUser instanceof \RKW\RkwNewsletter\Domain\Model\FrontendUser) { return $this->frontendUser; } return null; } /** * Returns user object identified by hash * * @return \RKW\RkwNewsletter\Domain\Model\FrontendUser|null */ protected function getFrontendUserByHash():? FrontendUser { return $this->frontendUserByHash; } /** * action new * * @param \RKW\RkwNewsletter\Domain\Model\FrontendUser|null $frontendUser * @param array $topics * @return void * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException */ public function newAction(FrontendUser $frontendUser = null, array $topics = []): void { // FE-User may be logged in /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ if (!$frontendUser) { $frontendUser = ($this->getFrontendUser() ? $this->getFrontendUser() : $this->getFrontendUserByHash()); } // check if frontendUser has an existing subscription and redirect to edit if ($frontendUser) { if (count($frontendUser->getTxRkwnewsletterSubscription())) { $this->forward('edit'); } } $this->view->assignMultiple( array( 'newsletterList' => $this->newsletterRepository->findAllForSubscription($this->settings['newsletterList']?: ''), 'topicList' => $this->buildCleanedTopicList($topics), 'frontendUser' => $frontendUser ) ); } /** * action create * * @param \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser * @param array $topics * @return void * @throws \Madj2k\FeRegister\Exception * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException * @throws \TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\TooDirtyException * @TYPO3\CMS\Extbase\Annotation\Validate("RKW\RkwNewsletter\Validation\FormValidator", param="frontendUser") * @TYPO3\CMS\Extbase\Annotation\Validate("Madj2k\FeRegister\Validation\Consent\TermsValidator", param="frontendUser") * @TYPO3\CMS\Extbase\Annotation\Validate("Madj2k\FeRegister\Validation\Consent\PrivacyValidator", param="frontendUser") * @TYPO3\CMS\Extbase\Annotation\Validate("Madj2k\FeRegister\Validation\Consent\MarketingValidator", param="frontendUser") * @TYPO3\CMS\Extbase\Annotation\Validate("Madj2k\CoreExtended\Validation\CaptchaValidator", param="frontendUser") */ public function createAction(FrontendUser $frontendUser, array $topics = []): void { /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $subscriptions */ $subscriptions = $this->buildCleanedTopicList($topics); // If no topics are selected this can't be the indention :) if (count($subscriptions) < 1) { $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.noTopicSelected', 'rkw_newsletter' ), '', AbstractMessage::ERROR ); $this->forward('new', null, null, $this->request->getArguments()); } // Case 1: FE-User is not logged in and is not identified via hash-tag // Case 2: FE-User is not logged in, but has been identified by hash-tag if ( ($frontendUser->_isNew()) || (!$this->getFrontendUser()) ) { // get all changed properties and save them in the opt-in $frontendUserArray = FrontendUserUtility::convertObjectToArray($frontendUser, true); // take array to reduce size in the database /** @var \Madj2k\FeRegister\Registration\FrontendUserRegistration $registration */ $registration = $this->objectManager->get(FrontendUserRegistration::class); $registration->setFrontendUserOptInUpdate($frontendUser) ->setFrontendUser($frontendUser) ->setData($subscriptions) ->setCategory('rkwNewsletter') ->setRequest($this->request) ->startRegistration(); $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.message.optInCreated', 'rkw_newsletter' ) ); $this->redirect('message'); // Case 3: Fe-User is logged in } else { if ( ($this->getFrontendUser()) && ($frontendUser->getUid() == $this->getFrontendUser()->getUid()) ) { // set FeUser and save $frontendUser->setTxRkwnewsletterSubscription($subscriptions); if (! $frontendUser->getTxRkwnewsletterHash()) { $hash = sha1($frontendUser->getUid() . $frontendUser->getEmail() . rand()); $frontendUser->setTxRkwnewsletterHash($hash); } $this->frontendUserRepository->update($frontendUser); \Madj2k\FeRegister\DataProtection\ConsentHandler::add( $this->request, $this->getFrontendUser(), $subscriptions, 'new newsletter subscription' ); $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.message.subscriptionSaved', 'rkw_newsletter' ) ); $this->redirect('edit'); // Case 3: something is strange } else { $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.unexpectedError', 'rkw_newsletter' ) ); $this->forward('new'); } } $this->redirect('new'); } /** * action edit * * @param array $topics * @return void * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function editAction(array $topics = array()): void { // FE-User has to be logged in or identified by hash /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = ($this->getFrontendUser() ? $this->getFrontendUser() : $this->getFrontendUserByHash()); if (!$frontendUser) { $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.notIdentified', 'rkw_newsletter' ), '', AbstractMessage::ERROR ); $this->forward('new'); } $this->view->assignMultiple( array( 'newsletterList' => $this->newsletterRepository->findAllForSubscription($this->settings['newsletterList']?: ''), 'topicList' => $this->buildCleanedTopicList($topics), 'frontendUser' => $frontendUser, 'hash' => ($this->getFrontendUserByHash() ? $this->getFrontendUserByHash()->getTxRkwnewsletterHash() : ''), ) ); } /** * action update * * @param array $topics * @return void * @throws \Madj2k\FeRegister\Exception * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException * @throws \TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException * @TYPO3\CMS\Extbase\Annotation\Validate("Madj2k\FeRegister\Validation\Consent\PrivacyValidator", param="topics") * @TYPO3\CMS\Extbase\Annotation\Validate("Madj2k\FeRegister\Validation\Consent\MarketingValidator", param="topics") */ public function updateAction(array $topics = array()) { // FE-User has to be logged in or identified by hash /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = ($this->getFrontendUser() ? $this->getFrontendUser() : $this->getFrontendUserByHash()); if (!$frontendUser) { $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.notIdentified', 'rkw_newsletter' ), '', AbstractMessage::ERROR ); $this->redirect('new'); } /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $subscriptions */ $subscriptions = $this->buildCleanedTopicList($topics); // opt out should be possible without opt-in for existing users ;-) // and without having to accept the privacy conditions if (count($subscriptions) < 1) { $frontendUser->setTxRkwnewsletterSubscription($subscriptions); $frontendUser->setTxRkwnewsletterHash(''); $this->frontendUserRepository->update($frontendUser); $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.message.allSubscriptionsDeleted', 'rkw_newsletter' ) ); $this->redirect('new'); } // check if there have been any changes! $existingSubscriptionIds = array(); $newSubscriptionIds = array(); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ foreach ($subscriptions as $topic) { $newSubscriptionIds[] = $topic->getUid(); } /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ foreach ($frontendUser->getTxRkwnewsletterSubscription() as $topic) { $existingSubscriptionIds[] = $topic->getUid(); } if ( ( (count($newSubscriptionIds) > count($existingSubscriptionIds)) && (count(array_diff($newSubscriptionIds, $existingSubscriptionIds)) < 1) ) || ( (count($existingSubscriptionIds) >= count($newSubscriptionIds)) && (count(array_diff($existingSubscriptionIds, $newSubscriptionIds)) < 1) ) ) { $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.nothingChanged', 'rkw_newsletter' ), '', AbstractMessage::ERROR ); $this->forward('edit', null, null, $this->request->getArguments()); } // Case 1: FE-User is not logged in, but has been identified by hash-tag if ( ($this->getFrontendUserByHash()) && (!$this->getFrontendUser()) ) { // register new user or simply send opt-in to existing user /** @var \Madj2k\FeRegister\Registration\FrontendUserRegistration $registration */ $registration = $this->objectManager->get(FrontendUserRegistration::class); $registration->setFrontendUser($frontendUser) ->setData($subscriptions) ->setCategory('rkwNewsletter') ->setRequest($this->request) ->startRegistration(); $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.message.optInCreated', 'rkw_newsletter' ) ); $this->redirect('message'); // Case 2: Fe-User is logged in } else { if ($this->getFrontendUser()) { // set FeUser and save $frontendUser->setTxRkwnewsletterSubscription($subscriptions); $this->frontendUserRepository->update($frontendUser); \Madj2k\FeRegister\DataProtection\ConsentHandler::add( $this->request, $this->getFrontendUser(), $subscriptions, 'edited newsletter subscription' ); $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.message.subscriptionSaved', 'rkw_newsletter' ) ); // Case 3: something is strange } else { $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.unexpectedError', 'rkw_newsletter' ) ); $this->forward('new'); } } $this->redirect('edit'); } /** * action message * * @return void * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException */ public function messageAction(): void { // nothing to do here – just look good $this->view->assignMultiple( array( 'frontendUser' => ($this->getFrontendUser() ? $this->getFrontendUser() : $this->getFrontendUserByHash()), ) ); } /** * action optIn * takes optIn parameter counter that were previously sent to the user via e-mail * * @param string $tokenUser * @param string $token * @return void * @throws \Madj2k\FeRegister\Exception * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException * @throws \TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException */ public function optInAction(string $tokenUser, string $token): void { /** @var \Madj2k\FeRegister\Registration\FrontendUserRegistration $registration */ $registration = $this->objectManager->get(FrontendUserRegistration::class); $result = $registration->setFrontendUserToken($tokenUser) ->setCategory('rkwNewsletter') ->setRequest($this->request) ->validateOptIn($token); $hash = ''; if ( ($result >= 200 && $result < 300) && ($frontendUser = $registration->getFrontendUserPersisted()) && ($frontendUser instanceof \Madj2k\FeRegister\Domain\Model\FrontendUser) && ($frontendUser = $this->frontendUserRepository->findByIdentifier($frontendUser->getUid())) ){ $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.message.subscriptionSaved', 'rkw_newsletter' ) ); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ if (!$frontendUser->getTxRkwnewsletterHash()) { $hash = sha1($frontendUser->getUid() . $frontendUser->getEmail() . rand()); $frontendUser->setTxRkwnewsletterHash($hash); $this->frontendUserRepository->update($frontendUser); } else { $hash = $frontendUser->getTxRkwnewsletterHash(); } } elseif ( ($result >= 300 && $result < 400) && ($frontendUser = $registration->getFrontendUserPersisted()) && ($frontendUser instanceof \Madj2k\FeRegister\Domain\Model\FrontendUser) && ($frontendUser = $this->frontendUserRepository->findByIdentifier($frontendUser->getUid())) ){ $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.message.subscriptionCanceled', 'rkw_newsletter' ) ); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $hash = $frontendUser->getTxRkwnewsletterHash(); } else { $this->addFlashMessage( LocalizationUtility::translate( 'subscriptionController.error.subscriptionError', 'rkw_newsletter' ), '', AbstractMessage::ERROR ); } $this->redirect('message', null, null, array('hash' => $hash)); } /** * createSubscription - used by SignalSlot * Called via SignalSlot after successfully completed optIn * * @param \Madj2k\FeRegister\Domain\Model\FrontendUser $frontendUser * @param \Madj2k\FeRegister\Domain\Model\OptIn $optIn * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function saveSubscription( \Madj2k\FeRegister\Domain\Model\FrontendUser $frontendUser, \Madj2k\FeRegister\Domain\Model\OptIn $optIn ){ if ( ($subscriptions =$optIn->getData()) && ($subscriptions instanceof \TYPO3\CMS\Extbase\Persistence\ObjectStorage) ) { // override with newsletter based model! /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUserDatabase */ if ($frontendUserDatabase = $this->frontendUserRepository->findByIdentifier($frontendUser->getUid())) { // set subscription $frontendUserDatabase->setTxRkwnewsletterSubscription($subscriptions); $this->frontendUserRepository->update($frontendUserDatabase); } } } /** * buildCleanedTopicList * Build cleaned up topic list * * @param array $topics * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage */ protected function buildCleanedTopicList(array $topics = []): ObjectStorage { /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $topicList */ $topicList = $this->objectManager->get(ObjectStorage::class); // check if given topics exists and set them to subscription foreach ($topics as $topicId) { /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ if ($topic = $this->topicRepository->findByUid($topicId)) { $topicList->attach($topic); } } return $topicList; } /** * Remove ErrorFlashMessage * * @see \TYPO3\CMS\Extbase\Mvc\Controller\ActionController::getErrorFlashMessage() */ protected function getErrorFlashMessage(): bool { return false; } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers\Backend; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Topic; use TYPO3\CMS\Extbase\Persistence\QueryResultInterface; /** * HasBackendUserPermissionViewHelper * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class HasBackendUserPermissionMultipleViewHelper extends AbstractHasBackendUserPermissionViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('issues', QueryResultInterface::class, 'Check permissions for this list of issues.', true); $this->registerArgument('topic', Topic::class, 'Check permissions for this topic (optional).', false, null); $this->registerArgument('approvalStage', 'int', 'Approval level to check. (optional, default:1)', false, null); $this->registerArgument('allApprovals', 'bool', 'Check for all approval, regardless on which topic or stage. (optional, default: false)', false, false); } /** * Checks if backendUser can approve/release at any given level of the issue-list * * @return int */ public function render(): int { $issues = $this->arguments['issues']; $topic = is_object($this->arguments['topic']) ? $this->arguments['topic'] : null; $approvalStage = intval($this->arguments['approvalStage']) ?: 1; $allApprovals = boolval($this->arguments['allApprovals']); foreach ($issues as $issue) { if (self::checkPermissions($issue, $allApprovals, $topic, $approvalStage)) { return 1; } } return 0; } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Model; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Domain\Model\FileReference; /** * Pages * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class Pages extends \RKW\RkwAuthors\Domain\Model\Pages { /** * @var int */ protected int $permsUserId = 0; /** * @var int */ protected int $permsGroupId = 0; /** * @var int */ protected int $permsUser = 0; /** * @var int */ protected int $permsGroup = 0; /** * @var int */ protected int $permsEverybody = 0; /** * @var \RKW\RkwNewsletter\Domain\Model\Newsletter|null */ protected ?Newsletter $txRkwnewsletterNewsletter = null; /** * @var \RKW\RkwNewsletter\Domain\Model\Topic|null */ protected ?Topic $txRkwnewsletterTopic = null; /** * @var \RKW\RkwNewsletter\Domain\Model\Issue|null */ protected ?Issue $txRkwnewsletterIssue = null; /** * @var bool */ protected bool $txRkwnewsletterExclude = false; /** * @var string */ protected string $txRkwnewsletterTeaserHeading = ''; /** * @var string */ protected string $txRkwnewsletterTeaserText = ''; /** * @var \Madj2k\CoreExtended\Domain\Model\FileReference|null */ protected ?FileReference $txRkwnewsletterTeaserImage = null; /** * @var string */ protected string $txRkwnewsletterTeaserLink = ''; /** * @var int */ protected int $txRkwnewsletterIncludeTstamp = 0; /** * @return int $permsUserId */ public function getPermsUserId(): int { return $this->permsUserId; } /** * Sets the permsUserId * * @param int $permsUserId * @return void */ public function setPermsUserId(int $permsUserId): void { $this->permsUserId = $permsUserId; } /** * Returns the permsGroupId * * @return int $permsGroupId */ public function getPermsGroupId(): int { return $this->permsGroupId; } /** * Sets the permsGroupId * * @param int $permsGroupId * @return void */ public function setPermsGroupId(int $permsGroupId) :void { $this->permsGroupId = $permsGroupId; } /** * Returns the permsUser * * @return int $permsUser */ public function getPermsUser(): int { return $this->permsUser; } /** * Sets the permsUser * * @param int $permsUser * @return void */ public function setPermsUser(int $permsUser): void { $this->permsUser = $permsUser; } /** * Returns the permsGroup * * @return int $permsGroup */ public function getPermsGroup(): int { return $this->permsGroup; } /** * Sets the permsGroup * * @param int $permsGroup * @return void */ public function setPermsGroup(int $permsGroup): void { $this->permsGroup = $permsGroup; } /** * Returns the permsEverybody * * @return int $permsEverybody */ public function getPermsEverybody(): int { return $this->permsEverybody; } /** * Sets the permsEverybody * * @param int $permsEverybody * @return void */ public function setPermsEverybody(int $permsEverybody): void { $this->permsEverybody = $permsEverybody; } /** * Returns the newsletter * * @return \RKW\RkwNewsletter\Domain\Model\Newsletter|null */ public function getTxRkwnewsletterNewsletter():? Newsletter { return $this->txRkwnewsletterNewsletter; } /** * Sets the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $txRkwnewsletterNewsletter * @return void */ public function setTxRkwnewsletterNewsletter(Newsletter $txRkwnewsletterNewsletter): void { $this->txRkwnewsletterNewsletter = $txRkwnewsletterNewsletter; } /** * Returns the topic * * @return \RKW\RkwNewsletter\Domain\Model\Topic|null */ public function getTxRkwnewsletterTopic():? Topic { return $this->txRkwnewsletterTopic; } /** * Sets the topic * * @param \RKW\RkwNewsletter\Domain\Model\Topic $txRkwnewsletterTopic * @return void */ public function setTxRkwnewsletterTopic(Topic $txRkwnewsletterTopic): void { $this->txRkwnewsletterTopic = $txRkwnewsletterTopic; } /** * Returns the txRkwnewsletterIssue * * @return \RKW\RkwNewsletter\Domain\Model\Issue|null $txRkwnewsletterIssue */ public function getTxRkwnewsletterIssue():? Issue { return $this->txRkwnewsletterIssue; } /** * Returns the txRkwnewsletterExclude * * @return bool $txRkwnewsletterExclude */ public function getTxRkwnewsletterExclude(): bool { return $this->txRkwnewsletterExclude; } /** * Sets the txRkwnewsletterExclude * * @param bool $txRkwnewsletterExclude * @return void */ public function setTxRkwnewsletterExclude(bool $txRkwnewsletterExclude): void { $this->txRkwnewsletterExclude = $txRkwnewsletterExclude; } /** * Returns the txRkwnewsletterTeaserHeading * * @return string $txRkwnewsletterTeaserHeading */ public function getTxRkwnewsletterTeaserHeading(): string { return $this->txRkwnewsletterTeaserHeading; } /** * Sets the txRkwnewsletterTeaserHeading * * @param string $txRkwnewsletterTeaserHeading * @return void */ public function setTxRkwnewsletterTeaserHeading(string $txRkwnewsletterTeaserHeading): void { $this->txRkwnewsletterTeaserHeading = $txRkwnewsletterTeaserHeading; } /** * Returns the txRkwnewsletterTeaserText * * @return string $txRkwnewsletterTeaserText */ public function getTxRkwnewsletterTeaserText(): string { return $this->txRkwnewsletterTeaserText; } /** * Sets the txRkwnewsletterTeaserText * * @param string $txRkwnewsletterTeaserText * @return void */ public function setTxRkwnewsletterTeaserText(string $txRkwnewsletterTeaserText): void { $this->txRkwnewsletterTeaserText = $txRkwnewsletterTeaserText; } /** * Returns the txRkwnewsletterTeaserImage * * @return \Madj2k\CoreExtended\Domain\Model\FileReference|null */ public function getTxRkwnewsletterTeaserImage():? FileReference { return $this->txRkwnewsletterTeaserImage; } /** * Sets the txRkwnewsletterTeaserImage * * @param \Madj2k\CoreExtended\Domain\Model\FileReference $txRkwnewsletterTeaserImage * @return void */ public function setTxRkwnewsletterTeaserImage(FileReference $txRkwnewsletterTeaserImage): void { $this->txRkwnewsletterTeaserImage = $txRkwnewsletterTeaserImage; } /** * Returns the txRkwnewsletterTeaserLink * * @return string $txRkwnewsletterTeaserLink */ public function getTxRkwnewsletterTeaserLink(): string { return $this->txRkwnewsletterTeaserLink; } /** * Sets the txRkwnewsletterTeaserLink * * @param string $txRkwnewsletterTeaserLink * @return void */ public function setTxRkwnewsletterTeaserLink(string $txRkwnewsletterTeaserLink): void { $this->txRkwnewsletterTeaserLink = $txRkwnewsletterTeaserLink; } /** * Returns the txRkwnewsletterIncludeTstamp * * @return int $txRkwnewsletterIncludeTstamp */ public function getTxRkwnewsletterIncludeTstamp(): int { return $this->txRkwnewsletterIncludeTstamp; } /** * Sets the txRkwnewsletterIncludeTstamp * * @param int $txRkwnewsletterIncludeTstamp * @return void */ public function setTxRkwnewsletterIncludeTstamp(int $txRkwnewsletterIncludeTstamp): void { $this->txRkwnewsletterIncludeTstamp = $txRkwnewsletterIncludeTstamp; } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Model; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Approval * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class Approval extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * @var \RKW\RkwNewsletter\Domain\Model\Topic|null */ protected ?Topic $topic = null; /** * @var \RKW\RkwNewsletter\Domain\Model\Issue|null */ protected ?Issue $issue = null; /** * @var \RKW\RkwNewsletter\Domain\Model\Pages|null */ protected ?Pages $page = null; /** * @var \RKW\RkwNewsletter\Domain\Model\BackendUser|null */ protected ?BackendUser $allowedByUserStage1 = null; /** * @var \RKW\RkwNewsletter\Domain\Model\BackendUser|null */ protected ?BackendUser $allowedByUserStage2 = null; /** * @var int */ protected int $allowedTstampStage1 = 0; /** * @var int */ protected int $allowedTstampStage2 = 0; /** * @var int */ protected int $sentInfoTstampStage1 = 0; /** * @var int */ protected int $sentInfoTstampStage2 = 0; /** * @var int */ protected int $sentReminderTstampStage1 = 0; /** * @var int */ protected int $sentReminderTstampStage2 = 0; /** * Returns the topic * * @return \RKW\RkwNewsletter\Domain\Model\Topic|null */ public function getTopic():? Topic { return $this->topic; } /** * Sets the topic * * @param \RKW\RkwNewsletter\Domain\Model\Topic * @return void */ public function setTopic(Topic $topic): void { $this->topic = $topic; } /** * Returns the issue * * @return \RKW\RkwNewsletter\Domain\Model\Issue|null $issue */ public function getIssue():? Issue { return $this->issue; } /** * Sets the issue * * @param \RKW\RkwNewsletter\Domain\Model\Issue issue * @return void */ public function setIssue(Issue $issue): void { $this->issue = $issue; } /** * Returns the pages * * @return \RKW\RkwNewsletter\Domain\Model\Pages|null */ public function getPage():? Pages { return $this->page; } /** * Sets the pages * * @param \RKW\RkwNewsletter\Domain\Model\Pages * @return void */ public function setPage(Pages $pages): void { $this->page = $pages; } /** * Returns the user. * * @return \RKW\RkwNewsletter\Domain\Model\BackendUser|null */ public function getAllowedByUserStage1():? BackendUser { return $this->allowedByUserStage1; } /** * Sets a user * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void */ public function setAllowedByUserStage1(BackendUser $backendUser): void { $this->allowedByUserStage1 = $backendUser; } /** * Returns the user. * * @return \RKW\RkwNewsletter\Domain\Model\BackendUser|null */ public function getAllowedByUserStage2():? BackendUser { return $this->allowedByUserStage2; } /** * Sets a user * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void */ public function setAllowedByUserStage2(BackendUser $backendUser): void { $this->allowedByUserStage2 = $backendUser; } /** * Returns the allowedTstampStage1 * * @return int */ public function getAllowedTstampStage1(): int { return $this->allowedTstampStage1; } /** * Sets the allowedTstampStage1 * * @param int $timestamp * @return void */ public function setAllowedTstampStage1(int $timestamp): void { $this->allowedTstampStage1 = $timestamp; } /** * Returns the allowedTstampStage2 * * @return int */ public function getAllowedTstampStage2(): int { return $this->allowedTstampStage2; } /** * Sets the allowedTstampStage2 * * @param int $timestamp * @return void */ public function setAllowedTstampStage2(int $timestamp): void { $this->allowedTstampStage2 = $timestamp; } /** * Returns the sentInfoTstampStage1 * * @return int */ public function getSentInfoTstampStage1(): int { return $this->sentInfoTstampStage1; } /** * Sets the sentInfoTstampStage1 * * @param int $timestamp * @return void */ public function setSentInfoTstampStage1(int $timestamp): void { $this->sentInfoTstampStage1 = $timestamp; } /** * Returns the sentInfoTstampStage2 * * @return int */ public function getSentInfoTstampStage2(): int { return $this->sentInfoTstampStage2; } /** * Sets the sentInfoTstampStage2 * * @param int $timestamp * @return void */ public function setSentInfoTstampStage2(int $timestamp): void { $this->sentInfoTstampStage2 = $timestamp; } /** * Returns the sentReminderTstampStage1 * * @return int */ public function getSentReminderTstampStage1(): int { return $this->sentReminderTstampStage1; } /** * Sets the sentReminderTstampStage1 * * @param int $timestamp * @return void */ public function setSentReminderTstampStage1(int $timestamp): void { $this->sentReminderTstampStage1 = $timestamp; } /** * Returns the sendReminderomailStage2 * * @return int */ public function getSentReminderTstampStage2(): int { return $this->sentReminderTstampStage2; } /** * Sets the sentReminderTstampStage2 * * @param int $timestamp * @return void */ public function setSentReminderTstampStage2(int $timestamp): void { $this->sentReminderTstampStage2 = $timestamp; } } <file_sep><?php defined('TYPO3_MODE') || die('Access denied.'); call_user_func( function($extKey) { //================================================================= // Register BackendModule //================================================================= if (TYPO3_MODE === 'BE') { \TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule( 'RKW.' . $extKey, 'tools', // Make module a submodule of 'tools' 'management', // Submodule key '', // Position array( 'Release' => 'confirmationList, approve, defer, testList, testSend, createIssueList, createIssue, sendList, sendConfirm, send', ), array( 'access' => 'user,group', 'icon' => 'EXT:' . $extKey . '/ext_icon.gif', 'labels' => 'LLL:EXT:' . $extKey . '/Resources/Private/Language/locallang_management.xlf', ) ); } //================================================================= // Add tables //================================================================= \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages( 'tx_rkwnewsletter_domain_model_approval' ); \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages( 'tx_rkwnewsletter_domain_model_issue' ); \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages( 'tx_rkwnewsletter_domain_model_newsletter' ); \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages( 'tx_rkwnewsletter_domain_model_topic' ); }, $_EXTKEY ); <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers\Mailing\Content; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Mailing\ContentLoader; use RKW\RkwNewsletter\ViewHelpers\Mailing\AbstractViewHelper; use RKW\RkwNewsletter\Domain\Model\Content; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * GetEditorialViewHelper * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class GetEditorialViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('topics', ObjectStorage::class, 'ObjectStorage of topics to load contents for. (optional, default: all).', false, null); } /** * Returns editorial of content * * @return \RKW\RkwNewsletter\Domain\Model\Content|null * @throws \RKW\RkwNewsletter\Exception */ public function render(): ?Content { /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->arguments['issue']; $topics = $this->arguments['topics']; /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Mailing\ContentLoader $contentLoader */ $contentLoader = $objectManager->get(ContentLoader::class, $issue); // set topics if ($topics) { $contentLoader->setTopics($topics); } return $contentLoader->getEditorial(); } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Topic; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper; /** * IsTopicInListViewHelper * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later * @todo rework and write tests */ class IsTopicInListViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('topicList', ObjectStorage::class, 'ObjectStorage with topics.', true); $this->registerArgument('topic', Topic::class, 'Topic to check for', true); } /** * checks is user has subscribed to a topic * * @return boolean */ public function render(): bool { $topicList = $this->arguments['topicList']; $topic = $this->arguments['topic']; /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topicFromList */ foreach ($topicList as $topicFromList) { if ($topicFromList->getUid() == $topic->getUid()) { return true; //=== } } return false; } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Manager; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use Madj2k\CoreExtended\Domain\Model\FileReference; use Madj2k\CoreExtended\Domain\Repository\FileReferenceRepository; use RKW\RkwNewsletter\Domain\Model\Content; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Newsletter; use RKW\RkwNewsletter\Domain\Model\Pages; use RKW\RkwNewsletter\Domain\Repository\ApprovalRepository; use RKW\RkwNewsletter\Domain\Repository\ContentRepository; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\NewsletterRepository; use RKW\RkwNewsletter\Domain\Repository\PagesRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use RKW\RkwNewsletter\Manager\IssueManager; use RKW\RkwNewsletter\Status\IssueStatus; use TYPO3\CMS\Core\Database\ConnectionPool; use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction; use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction; use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction; use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; /** * IssueManagerTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class IssueManagerTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/IssueManagerTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_authors', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Manager\IssueManager|null */ private ?IssueManager $subject = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\NewsletterRepository|null */ private ?NewsletterRepository $newsletterRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\PagesRepository|null */ private ?PagesRepository $pagesRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\ContentRepository|null */ private ?ContentRepository $contentRepository = null; /** * @var \Madj2k\CoreExtended\Domain\Repository\FileReferenceRepository|null */ private ?FileReferenceRepository $fileReferenceRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\ApprovalRepository|null */ private ?ApprovalRepository $approvalRepository = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(static::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', static::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $this->objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->newsletterRepository = $this->objectManager->get(NewsletterRepository::class); $this->topicRepository = $this->objectManager->get(TopicRepository::class); $this->issueRepository = $this->objectManager->get(IssueRepository::class); $this->pagesRepository = $this->objectManager->get(PagesRepository::class); $this->contentRepository = $this->objectManager->get(ContentRepository::class); $this->fileReferenceRepository = $this->objectManager->get(FileReferenceRepository::class); $this->approvalRepository = $this->objectManager->get(ApprovalRepository::class); $this->subject = $this->objectManager->get(IssueManager::class); // For Mail-Interface $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName'] = 'RKW'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'] = '<EMAIL>'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailReplyName'] = 'RKW'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailReplyToAddress'] = '<EMAIL>'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailReturnAddress'] = '<EMAIL>'; } //============================================= /** * @test * @throws \Exception */ public function replaceTitlePlaceholdersReplacesYear() { /** * Scenario: * * Given a string with {Y} placeholder * When the method is called * Then the placeholder is replaced with the current year */ $result = $this->subject->replaceTitlePlaceholders('this year is {Y}'); self::assertEquals('this year is '. date('Y'), $result); } /** * @test * @throws \Exception */ public function replaceTitlePlaceholdersReplacesMonth() { /** * Scenario: * * Given a string with {M} placeholder * When the method is called * Then the placeholder is replaced with the current month */ $result = $this->subject->replaceTitlePlaceholders('this month is {M}'); self::assertEquals('this month is '. date('m'), $result); } /** * @test * @throws \Exception */ public function replaceTitlePlaceholdersReplacesTextualMonth() { /** * Scenario: * * Given a string with {F} placeholder * When the method is called * Then the placeholder is replaced with the textual representation of the current month */ $result = $this->subject->replaceTitlePlaceholders('this month is {F}'); self::assertEquals('this month is '. date('F'), $result); } /** * @test * @throws \Exception */ public function replaceTitlePlaceholdersReplacesDay() { /** * Scenario: * * Given a string with {D} placeholder * When the method is called * Then the placeholder is replaced with the current day */ $result = $this->subject->replaceTitlePlaceholders('this day is {D}'); self::assertEquals('this day is '. date('d'), $result); } //============================================= /** * @test * @throws \Exception */ public function createIssueThrowsExceptionIfNewsletterNotPersisted() { /** * Scenario: * * Given a newsletter-object that is not persisted * When the method is called * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1639058270 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1639058270); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = GeneralUtility::makeInstance(Newsletter::class); $this->subject->createIssue($newsletter); } /** * @test * @throws \Exception */ public function createIssueSetsTitleAndStatusToIssue() { /** * Scenario: * * Given a newsletter-object that is persisted * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Issue is returned * Then this instance is persisted * Then the title of this instance is set to the title set in the newsletter-object * Then the stage of the instance is set to zero * Then the isSpecial-attribute is set to false */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->subject->createIssue($newsletter); self::assertInstanceOf(Issue::class, $issue); self::assertEquals('Newsletter ' . date('m') . '/' . date('Y'), $issue->getTitle()); self::assertEquals(0, $issue->getStatus()); self::assertEquals(false, $issue->getIsSpecial()); } /** * @test * @throws \Exception */ public function createIssueSetsIsSpecial() { /** * Scenario: * * Given a newsletter-object that is persisted * When the method is called with isSpecial-Parameter * Then an instance of \RKW\RkwNewsletter\Model\Issue is returned * Then the title of this instance is set to the title set in the newsletter-object plus special marks * Then the stage of the instance is set to zero * Then the isSpecial-Attribute is set to true */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->subject->createIssue($newsletter, true); self::assertInstanceOf(Issue::class, $issue); self::assertEquals('SPECIAL: Newsletter ' . date('m') . '/' . date('Y'), $issue->getTitle()); self::assertEquals(0, $issue->getStatus()); self::assertEquals(true, $issue->getIsSpecial()); } /** * @test * @throws \Exception */ public function createIssuePersistsIssueAndAddsItToNewsletter() { /** * Scenario: * * Given a newsletter-object that is persisted * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Issue is returned * Then the issue-instance is persisted * Then the instance is added as issue to the newsletter-object * Then this newsletter-object is also persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->subject->createIssue($newsletter); self::assertInstanceOf(Issue::class, $issue); /** @var \TYPO3\CMS\Extbase\Persistence\QueryResultInterface $issuesDb */ $issuesDb = $this->issueRepository->findAll(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueDb */ $issueDb = $issuesDb->getFirst(); self::assertCount(1, $issuesDb); self::assertEquals($issueDb, $issue); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletterDb */ $newsletterDb = $this->newsletterRepository->findByUid(10); self::assertCount(1, $newsletterDb->getIssue()); $newsletterDb->getIssue()->rewind(); self::assertEquals($issueDb, $newsletterDb->getIssue()->current()); } //============================================= /** * @test * @throws \Exception */ public function createPageThrowsExceptionIfNoContainerPage() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given the topic-object has no container-page defined * When the method is called * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1641967659 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1641967659); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); $this->subject->createPage($newsletter, $topic, $issue); } /** * @test * @throws \Exception */ public function createPagesSetsProperties() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given the topic-object has a container-page defined * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Pages is returned * Then the txRkwnewsletterNewsletter-property of this instance is set to the newsletter-object * Then the txRkwnewsletterTopic-property of this instance is set to the topic-object * Then the title-property of this instance is set to the title of the issue * Then the dokType-property of this instance is set to the value 1 * Then the pid-property of this instance is set to the container-page of the topic-object * Then the no-search-property of this instance is set to true * Then the txRkwnewsletterExclude-property of this instance is set to true */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->subject->createPage($newsletter, $topic, $issue); self::assertInstanceOf(Pages::class, $page); self::assertEquals($newsletter, $page->getTxRkwnewsletterNewsletter()); self::assertEquals($topic, $page->getTxRkwnewsletterTopic()); self::assertEquals($issue->getTitle(), $page->getTitle()); self::assertEquals(1, $page->getDokType()); self::assertEquals($topic->getContainerPage()->getUid(), $page->getPid()); self::assertEquals(true, $page->getNoSearch()); self::assertEquals(true, $page->getTxRkwnewsletterExclude()); } /** * @test * @throws \Exception */ public function createPagePersistsPageAndAddsItToIssue() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given the topic-object has a container-page defined * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Pages is returned * Then the instance is persisted * Then the txRkwnewsletterNewsletter-property of this persisted instance is set to the newsletter-object * Then the txRkwnewsletterTopic-property of this persisted instance is set to the topic-object * Then the title-property of this persisted instance is set to the title of the issue * Then the dokType-property of this persisted instance is set to the value 1 * Then the pid-property of this persisted instance is set to the container-page of the topic-object * Then the no-search-property of this persisted instance is set to true * Then the txRkwnewsletterExclude-property of this persisted instance is set to true * Then the instance is added as page to the issue-object * Then this issue-object is also updated */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(40); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(40); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(40); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->subject->createPage($newsletter, $topic, $issue); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); self::assertInstanceOf(Pages::class, $page); /** @var \TYPO3\CMS\Extbase\Persistence\QueryResultInterface $pagesDb */ $pagesDb = $this->pagesRepository->findAll()->toArray(); self::assertCount(1, $pagesDb); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $pageDb */ $pageDb = $pagesDb[0]; self::assertEquals($newsletter->getUid(), $pageDb->getTxRkwnewsletterNewsletter()->getUid()); self::assertEquals($topic->getUid(), $pageDb->getTxRkwnewsletterTopic()->getUid()); self::assertEquals($issue->getTitle(), $pageDb->getTitle()); self::assertEquals(1, $pageDb->getDokType()); self::assertEquals($topic->getContainerpage()->getUid(), $pageDb->getPid()); self::assertEquals(true, $pageDb->getNoSearch()); self::assertEquals(true, $pageDb->getTxRkwnewsletterExclude()); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueDb */ $issueDb = $this->issueRepository->findByUid(40); self::assertCount(1, $issueDb->getPages()); $issueDb->getPages()->rewind(); self::assertEquals($page->getUid(), $issueDb->getPages()->current()->getUid()); } //============================================= /** * @test * @throws \Exception */ public function createContentSetsPropertiesWithFallback() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted page-object that belongs to the issue-object * Given a persisted page-object with contents * Given the persisted page-object has no txRkwnewsletterTeaserHeading-property set * Given the persisted page-object has no txRkwnewsletterTeaserText-property set * Given the persisted page-object has no txRkwnewsletterTeaserLink-property set * Given the persisted page-object has no txRkwauthorsAuthorship-property set * Given the topic-object has a container-page defined * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Content is returned * Then the pid-property of this instance is set to the page-object that belongs to the issue-object * Then the sysLanguageUid-property of this instance is set to the sysLanguageUid-property of the newsletter-object * Then the contentType-property of this instance is set to the value 'textpic' * Then the header-property of this instance is set to the title of the page * Then the bodytext-property of this instance is set to the abstract of the page * Then the headerLink-property of this instance is set to the id of the page * Then no txRkwNewsletterAuthors-property is set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(50); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $targetPage */ $targetPage = $this->pagesRepository->findByUid(50); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(51); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->subject->createContent($newsletter, $targetPage, $page); self::assertInstanceOf(Content::class, $content); self::assertEquals($targetPage->getUid(), $content->getPid()); self::assertEquals('textpic', $content->getContentType()); self::assertEquals(1, $content->getImageCols()); self::assertEquals($page->getTitle(), $content->getHeader()); self::assertEquals($page->getAbstract(), $content->getBodytext()); self::assertEquals('t3://page?uid=' . $page->getUid(), $content->getHeaderLink()); self::assertCount(0, $content->getTxRkwnewsletterAuthors()); } /** * @test * @throws \Exception */ public function createContentSetsProperties() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted page-object that belongs to the issue-object * Given the persisted page-object has a txRkwnewsletterTeaserHeading-property set * Given the persisted page-object has a txRkwnewsletterTeaserText-property set * Given the persisted page-object has a txRkwnewsletterTeaserLink-property set * Given the persisted page-object has a txRkwauthorsAuthorship-property set * Given the topic-object has a container-page defined * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Content is returned * Then the pid-property of this instance is set to the page-object * Then the sysLanguageUid-property of this instance is set to the sysLanguageUid-property of the newsletter-object * Then the contentType-property of this instance is set to the value 'textpic' * Then the header-property of this instance is set to the txRkwnewsletterTeaserHeading-property of the page * Then the bodytext-property of this instance is set to the txRkwnewsletterTeaserText-property of the page * Then the headerLink-property of this instance is set to the txRkwnewsletterTeaserLink-property of the page * Then the txRkwNewsletterAuthors-property of this instance is set to the txRkwNewsletterAuthors-property of the page */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(60); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $targetPage */ $targetPage = $this->pagesRepository->findByUid(60); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(61); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->subject->createContent($newsletter, $targetPage, $page); self::assertInstanceOf(Content::class, $content); self::assertEquals($targetPage->getUid(), $content->getPid()); self::assertEquals('textpic', $content->getContentType()); self::assertEquals(1, $content->getImageCols()); self::assertEquals('Header', $content->getHeader()); self::assertEquals('Text', $content->getBodytext()); self::assertEquals('http://www.google.de', $content->getHeaderLink()); self::assertCount(1, $content->getTxRkwnewsletterAuthors()); $content->getTxRkwnewsletterAuthors()->rewind(); self::assertEquals(60, $content->getTxRkwnewsletterAuthors()->current()->getUid()); } /** * @test * @throws \Exception */ public function createContentPersistsContent() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted page-object that belongs to the issue-object * Given the topic-object has a container-page defined * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Content is returned * Then the instance is persisted * Then the pid-property of this persisted instance is set to the page-object * Then the sysLanguageUid-property of this persisted instance is set to the sysLanguageUid-property of the newsletter-object * Then the contentType-property of this persisted instance is set to the value 'textpic' * Then the header-property of this persisted instance is set to the txRkwnewsletterTeaserHeading-property of the page * Then the bodytext-property of this persisted instance is set to the txRkwnewsletterTeaserText-property of the page * Then the headerLink-property of this persisted instance is set to the txRkwnewsletterTeaserLink-property of the page * Then the txRkwNewsletterAuthors-property of this persisted instance is set to the txRkwNewsletterAuthors-property of the page */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(70); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $targetPage */ $targetPage = $this->pagesRepository->findByUid(70); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(71); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->subject->createContent($newsletter, $targetPage, $page); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); self::assertInstanceOf(Content::class, $content); /** @var \TYPO3\CMS\Extbase\Persistence\QueryResultInterface $contentsDb */ $contentsDb = $this->contentRepository->findAll(); self::assertCount(1, $contentsDb); /** @var \RKW\RkwNewsletter\Domain\Model\Content $contentDb*/ $contentDb = $contentsDb->getFirst(); self::assertEquals($content->getUid(), $contentDb->getUid()); self::assertEquals($targetPage->getUid(), $contentDb->getPid()); self::assertEquals('textpic', $contentDb->getContentType()); self::assertEquals(1, $contentDb->getImageCols()); self::assertEquals('Header', $contentDb->getHeader()); self::assertEquals('Text', $contentDb->getBodytext()); self::assertEquals('http://www.google.de', $contentDb->getHeaderLink()); self::assertCount(1, $contentDb->getTxRkwnewsletterAuthors()); $contentDb->getTxRkwnewsletterAuthors()->rewind(); self::assertEquals(70, $contentDb->getTxRkwnewsletterAuthors()->current()->getUid()); } //============================================= /** * @test * @throws \Exception */ public function createImageSetsReference() { /** * Scenario: * * Given a persisted file-object * Given a persisted content-object * Given a persisted fileReference-object between the page- and file-object * When the method is called * Then an instance of \Madj2k\CoreExtended\Model\FileReference is returned * Then the file-property is identical to the file-property of the fileReference-object * Then the tableLocal-property is identical to the tableLocale-property of the fileReference-object * Then the fieldname-property of this instance is set to 'image' * Then the tablenames-property of this instance is set to 'tt_content' * Then the uidForeign-property of this instance is set to the uid of the content-object * Then the pid-property of this instance is set to the pid of the content-object * Then the image-property of the content-object is updated to the amount of images referenced (1) * Then the image-property returns the file-reference */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \Madj2k\CoreExtended\Domain\Model\FileReference $fileReferenceSource */ $fileReferenceSource = $this->fileReferenceRepository->findByUid(80); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->contentRepository->findByUid(80); /** @var \Madj2k\CoreExtended\Domain\Model\FileReference $fileReference */ $fileReference = $this->subject->createFileReference($fileReferenceSource, $content); self::assertInstanceOf(FileReference::class, $fileReference); self::assertEquals($fileReferenceSource->getFile(), $fileReference->getFile()); self::assertEquals($fileReferenceSource->getTableLocal(), $fileReference->getTableLocal()); self::assertEquals('image', $fileReference->getFieldname()); self::assertEquals('tt_content', $fileReference->getTablenames()); self::assertEquals($content->getUid(), $fileReference->getUidForeign()); self::assertEquals($content->getPid(), $fileReference->getPid()); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class) ->getConnectionForTable('tt_content'); /** @var \TYPO3\CMS\Core\Database\Query\QueryBuilder $queryBuilder */ $queryBuilder = $connection->createQueryBuilder(); $queryBuilder->getRestrictions() ->removeByType(StartTimeRestriction::class) ->removeByType(EndTimeRestriction::class) ->removeByType(HiddenRestriction::class) ->removeByType(DeletedRestriction::class); $contentDbCount = $queryBuilder->count('uid') ->from('tt_content') ->where( $queryBuilder->expr()->eq( 'uid', $queryBuilder->createNamedParameter(80, \PDO::PARAM_INT) ) ) ->execute() ->fetchColumn(0); self::assertEquals(1, $contentDbCount); // force TYPO3 to load object new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->contentRepository->findByUid(80); self::assertCount(1, $content->getImage()); } //============================================= /** * @test * @throws \Exception */ public function buildContentsBuildsContentsSelectively() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted page-object as container-page * Given for the topic-object six persisted page-objects exist that belong to it * Given page-object one is hidden * Given page-object two is marked to be excluded * Given page-object three is marked as already used for a newsletter-issue * Given page-object four has the wrong doktype * Given page-object five and six have no properties that exclude them from being used * Given there is a seventh page-object that does not belong to the topic-object * When the method is called * Then true is returned * Then the contents of the page-objects one to four and seven are ignored * Then the contents of the page-objects four and five are created in the container-page * Then the txRkwnewsletterIncludeTstamp for the included page-objects five and six are set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(90); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(90); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $targetPage */ $targetPage = $this->pagesRepository->findByUid(90); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $result = $this->subject->buildContents($newsletter, $topic, $targetPage); self::assertTrue($result); $contents = $this->contentRepository->findByPid(90)->toArray(); self::assertCount(2, $contents); self::assertEquals('t3://page?uid=95', $contents[0]->getHeaderLink()); self::assertEquals('Use One', $contents[0]->getHeader()); self::assertEquals('t3://page?uid=96', $contents[1]->getHeaderLink()); self::assertEquals('Use Two', $contents[1]->getHeader()); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(95); self::assertGreaterThan(0, $page->getTxRkwnewsletterIncludeTstamp()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(96); self::assertGreaterThan(0, $page->getTxRkwnewsletterIncludeTstamp()); } /** * @test * @throws \Exception */ public function buildContentsUsesCoreExtendedPreviewImage() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted page-object as container-page * Given for the topic-object there exists a persisted page-object that belongs to it * Given page-object has a file-reference to a file for the txCoreextendedPreviewImage-property set * Given page-object has no file-reference to a file for the txCoreextendedPreviewImage-property set * When the method is called * Then true is returned * Then the content of the page-object is created in the container-page * Then the new content has one file-reference in the image-property * Then this file-references refers to the image of the txCoreextendedTeaserImage-property of the page-object */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check100.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(100); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(100); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $targetPage */ $targetPage = $this->pagesRepository->findByUid(100); $result = $this->subject->buildContents($newsletter, $topic, $targetPage); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $contents = $this->contentRepository->findByPid(100)->toArray(); self::assertCount(1, $contents); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $contents[0]; /** @var \Madj2k\CoreExtended\Domain\Model\File $file */ $file = $content->getImage()->current()->getFile(); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(101); self::assertEquals($page->getTxCoreextendedPreviewImage()->getFile(), $file); } /** * @test * @throws \Exception */ public function buildContentsUsesRkwNewsletterTeaserImage() { /** * Scenario: * * Given a persisted newsletter-object * Given a persisted topic-object that belongs to the newsletter-object * Given a persisted page-object as container-page * Given for the topic-object there exists a persisted page-object that belongs to it * Given page-object has a file-reference to a file for the txCoreextendedPreviewImage-property set * Given page-object has a file-reference to a file for the txCoreextendedPreviewImage-property set * When the method is called * Then true is returned * Then the content of the page-object is created in the container-page * Then the new content has one file-reference in the image-property * Then this file-references refers to the image of the txRkwNewsletterTeaserImage-property of the page-object */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check110.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(110); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(110); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $targetPage */ $targetPage = $this->pagesRepository->findByUid(110); $result = $this->subject->buildContents($newsletter, $topic, $targetPage); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $contents = $this->contentRepository->findByPid(110)->toArray(); self::assertCount(1, $contents); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $contents[0]; /** @var \Madj2k\CoreExtended\Domain\Model\File $file */ $file = $content->getImage()->current()->getFile(); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(111); self::assertEquals($page->getTxRkwnewsletterTeaserImage()->getFile(), $file); } //============================================= /** * @test * @throws \Exception */ public function buildPagesReturnsFalseWhenNoTopicsDefined() { /** * Scenario: * * Given a persisted newsletter-object * Given no persisted topic-objects belong to the newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check130.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(130); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(130); $result = $this->subject->buildPages($newsletter, $issue); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildPagesCreatesPageForEachTopic() { /** * Scenario: * * Given a persisted newsletter-object * Given two persisted topic-objects that belong to the newsletter-object * Given each topic-object has a container-page set * Given these container-pages are persisted * Given a persisted issue-object that belongs to the newsletter-object * When the method is called * Then true is returned * Then two content-pages are created * Then each content-page is a subpages of the container-page of the corresponding topic * Then each content-page has the newsletter and the corresponding topic as reference * Then for each content-page an approval-object is created * Then each approval-object has the content-page and the corresponding topic as reference */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check120.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(120); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topicOne */ $topicOne = $this->topicRepository->findByUid(120); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topicTwo */ $topicTwo = $this->topicRepository->findByUid(121); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(120); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages'); /** @var \TYPO3\CMS\Core\Database\Query\QueryBuilder $queryBuilder */ $queryBuilder = $connection->createQueryBuilder(); $queryBuilder->getRestrictions() ->removeByType(StartTimeRestriction::class) ->removeByType(EndTimeRestriction::class) ->removeByType(HiddenRestriction::class) ->removeByType(DeletedRestriction::class); $countBefore = $queryBuilder->count('uid') ->from('pages') ->execute() ->fetchColumn(0); $result = $this->subject->buildPages($newsletter, $issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $countAfter = $queryBuilder->count('uid') ->from('pages') ->execute() ->fetchColumn(0); self::assertEquals(2, $countAfter - $countBefore); $pageOne = $this->pagesRepository->findByUid(122); self::assertEquals(120, $pageOne->getPid()); self::assertEquals($newsletter->getUid(), $pageOne->getTxRkwnewsletterNewsletter()->getUid()); self::assertEquals($topicOne->getUid(), $pageOne->getTxRkwnewsletterTopic()->getUid()); $pageTwo = $this->pagesRepository->findByUid(123); self::assertEquals(121, $pageTwo->getPid()); self::assertEquals($newsletter->getUid(), $pageTwo->getTxRkwnewsletterNewsletter()->getUid()); self::assertEquals($topicTwo->getUid(), $pageTwo->getTxRkwnewsletterTopic()->getUid()); $approvals = $this->approvalRepository->findAll()->toArray(); self::assertCount(2, $approvals); self::assertEquals($pageOne, $approvals[0]->getPage()); self::assertEquals($pageOne->getTxRkwnewsletterTopic(), $approvals[0]->getTopic()); self::assertEquals($pageTwo, $approvals[1]->getPage()); self::assertEquals($pageTwo->getTxRkwnewsletterTopic(), $approvals[1]->getTopic()); } /** * @test * @throws \Exception */ public function buildPagesCreatesPageForGivenTopic() { /** * Scenario: * * Given a persisted newsletter-object * Given two persisted topic-objects A and B that belong to the newsletter-object * Given each topic-object has a container-page set * Given these container-pages are persisted * Given a persisted issue-object that belongs to the newsletter-object * When the method is called with topic A as parameter * Then true is returned * Then one content-page is created * Then the content-page is a subpages of the container-page of topic A * Then the content-page has the newsletter and topic A as reference * Then for the content-page an approval-object is created * Then the approval-object has the content-page and the topic A as reference */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check120.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(120); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topicOne */ $topicOne = $this->topicRepository->findByUid(120); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(120); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages'); /** @var \TYPO3\CMS\Core\Database\Query\QueryBuilder $queryBuilder */ $queryBuilder = $connection->createQueryBuilder(); $queryBuilder->getRestrictions() ->removeByType(StartTimeRestriction::class) ->removeByType(EndTimeRestriction::class) ->removeByType(HiddenRestriction::class) ->removeByType(DeletedRestriction::class); $countBefore = $queryBuilder->count('uid') ->from('pages') ->execute() ->fetchColumn(0); $result = $this->subject->buildPages($newsletter, $issue, [$topicOne]); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $countAfter = $queryBuilder->count('uid') ->from('pages') ->execute() ->fetchColumn(0); self::assertEquals(1, $countAfter - $countBefore); $pageOne = $this->pagesRepository->findByUid(122); self::assertEquals(120, $pageOne->getPid()); self::assertEquals($newsletter->getUid(), $pageOne->getTxRkwnewsletterNewsletter()->getUid()); self::assertEquals($topicOne->getUid(), $pageOne->getTxRkwnewsletterTopic()->getUid()); $approvals = $this->approvalRepository->findAll()->toArray(); self::assertCount(1, $approvals); self::assertEquals($pageOne, $approvals[0]->getPage()); self::assertEquals($pageOne->getTxRkwnewsletterTopic(), $approvals[0]->getTopic()); } //============================================= /** * @test * @throws \Exception */ public function buildIssueReturnsFalseWhenNoTopicsDefined() { /** * Scenario: * * Given a persisted newsletter-object * Given no topic-objects belong to the newsletter-object * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(140); $result = $this->subject->buildIssue($newsletter); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildIssueCreatesIssueAndSetsStatus () { /** * Scenario: * * Given a persisted newsletter-object * Given two persisted topic-objects belong to the newsletter-object * Given each persisted topic-object has a persisted container-page defined * When the method is called * Then true is returned * Then an issue is created and persisted * Then the stage of the issue is set to the value 1 * Then the isSpecial-value of the issue is not set * Then the lastIssueTimestamp of the newsletter-object is set to the current time * Then this change of the newsletter-object is persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(150); $result = $this->subject->buildIssue($newsletter); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(1, $issues); self::assertEquals(1, $issues[0]->getStatus()); self::assertEquals(false, $issues[0]->getIsSpecial()); self::assertLessThanOrEqual(time(), $newsletter->getLastIssueTstamp()); self::assertGreaterThan(time()-10, $newsletter->getLastIssueTstamp()); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletterDb */ $newsletterDb = $this->newsletterRepository->findByUid(150); self::assertEquals($newsletter->getLastIssueTstamp(), $newsletterDb->getLastIssueTstamp()); } /** * @test * @throws \Exception */ public function buildIssueCreatesManualIssueWithGivenTopicsAndSetsStatus () { /** * Scenario: * * Given a persisted newsletter-object * Given two persisted topic-objects A and B belong to the newsletter-object * Given each persisted topic-object has a persisted container-page defined * When the method is called with topic A as parameter * Then true is returned * Then an issue is created and persisted * Then the stage of the issue is set to the value 1 * Then no lastIssueTimestamp for the newsletter-object is set * Then the isSpecial-value of the issue is set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(150); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topicOne */ $topic = $this->topicRepository->findByUid(150); $result = $this->subject->buildIssue($newsletter, [$topic]); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(1, $issues); self::assertEquals(1, $issues[0]->getStatus()); self::assertEquals(true, $issues[0]->getIsSpecial()); self::assertEquals(0, $newsletter->getLastIssueTstamp()); } //============================================= /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueMonthly () { /** * Scenario: * * Given two persisted newsletter-objects with monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of February * Given today is the 25th of February * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 2 , 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 2 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueMonthlyBetweenMonths () { /** * Scenario: * * Given two persisted newsletter-objects with monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of February * Given today is the 25th of February * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 1st * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 2 , 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 2 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 1); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueMonthly () { /** * Scenario: * * Given two persisted newsletter-objects with monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of January * Given today is the 14th of February * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then true is returned * Then two issues are created */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 2 , 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueMonthlyBetweenYears () { /** * Scenario: * * Given two persisted newsletter-objects with monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of December last year * Given today is the 14th of January * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then true is returned * Then two issues are created */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 1 , 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 12 , 15, date("Y") -1); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueBiMonthly () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of February * Given today is the 25th of March * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check390.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 3, 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 2 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueBiMonthlyBetweenMonths () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of February * Given today is the 25th of March * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 1st * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check390.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 3, 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 2 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 1); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueBiMonthly () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of January * Given today is the 14th of March * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then true is returned * Then two issues are created */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check390.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 3 , 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNewsletterDueBiMonthlyBetweenYears () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of December last year * Given today is the 14th of January * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check390.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 1 , 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 12 , 15, date("Y") -1); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueBiMonthlyBetweenYears () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of December last year * Given today is the 14th of February * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then true is returned * Then two issues are created */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check390.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 2 , 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 12 , 15, date("Y") -1); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueQuarterly () { /** * Scenario: * * Given two persisted newsletter-objects with quarterly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of January * Given today is the 25th of March * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check170.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 3 , 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueQuarterlyBetweenMonths () { /** * Scenario: * * Given two persisted newsletter-objects with quarterly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of January * Given today is the 25th of March * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check170.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 3 , 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 1); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueQuarterly () { /** * Scenario: * * Given two persisted newsletter-objects with quarterly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of January * Given today is the 2nd of April * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check170.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 4 , 2, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueQuarterlyBetweenYears () { /** * Scenario: * * Given two persisted newsletter-objects with quarterly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of October * Given today is the 2nd of January the next year * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check170.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 1 , 2, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 10 , 15, date("Y") - 1); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueBiAnnually () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of February * Given today is the 25th of June * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check400.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 6, 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1, 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNoNewsletterDueBiAnnuallyBetweenMonths () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of February * Given today is the 25th of June * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 1st * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check400.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 6, 25, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1, 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 1); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueBiAnnually () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of January * Given today is the 14th of July * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then true is returned * Then two issues are created */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check400.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 7, 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 1 , 15, date("Y")); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsFalseWhenNewsletterDueBiAnnuallyBetweenYears () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of August last year * Given today is the 14th of January * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check400.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 1 , 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 8 , 15, date("Y") -1); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertFalse($result); } /** * @test * @throws \Exception */ public function buildAllIssuesReturnsTrueWhenNewsletterDueBiAnnuallyBetweenYears () { /** * Scenario: * * Given two persisted newsletter-objects with bi-monthly rhythm * Given to each newsletter-object belong two persisted topic-objects * Given each persisted topic-object has a persisted container-page defined * Given both of the newsletter-objects were sent on the 15th of August last year * Given today is the 14th of February * Given the tolerance is set to fifteen days * Given dayOfMonth is set to the 15th * When the method is called * Then true is returned * Then two issues are created */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check400.xml'); // prepare timestamps for test $timestampNow = mktime(0, 0, 0, 2 , 14, date("Y")); $timestampNewsletter = mktime(0, 0, 0, 8, 15, date("Y") -1); /** @var \TYPO3\CMS\Core\Database\Connection $connectionPages */ $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_rkwnewsletter_domain_model_newsletter'); $updateQueryBuilder = $connection->createQueryBuilder(); $updateQueryBuilder->update('tx_rkwnewsletter_domain_model_newsletter') ->set('last_issue_tstamp', $timestampNewsletter) ->set('day_for_sending', 15); $updateQueryBuilder->execute(); // tolerance is 15 days (1209600) for testing $result = $this->subject->buildAllIssues(1209600, $timestampNow); self::assertTrue($result); $issues = $this->issueRepository->findAll()->toArray(); self::assertCount(2, $issues); } //============================================= /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseForWrongStage() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "approval" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $issue->setStatus(IssueStatus::STAGE_APPROVAL); $result = $this->subject->increaseLevel($issue); self::assertFalse($result); } /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueAndSetsFirstLevel() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * When the method is called * Then true is returned * Then the infoTstamp-property is set * Then the changes to the issue-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $result = $this->subject->increaseLevel($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issueDb = $this->issueRepository->findByUid(260); self::assertGreaterThan(0, $issueDb->getInfoTstamp()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueAndSetSecondLevel() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property is set * Given the issue-object has no value for the reminderTstamp-property set * When the method is called * Then true is returned * Then the reminderTstamp-property is set * Then the changes to the issue-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check270.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(270); $result = $this->subject->increaseLevel($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issueDb = $this->issueRepository->findByUid(270); self::assertGreaterThan(0, $issueDb->getReminderTstamp()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseForLevel2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property is set * Given the issue-object has a value for the reminderTstamp-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check280.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(280); $result = $this->subject->increaseLevel($issue); self::assertFalse($result); } //============================================= /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStageDraft() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "draft" * When the method is called * Then true is returned * Then the stage is set to "approval" * Then the changes to the issue-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check290.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(290); $issue->setStatus(IssueStatus::STAGE_DRAFT); $result = $this->subject->increaseStage($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueDb */ $issueDb = $this->issueRepository->findByUid(290); self::assertEquals(IssueStatus::STAGE_APPROVAL, $issueDb->getStatus()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStageApproval() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "approval" * When the method is called * Then true is returned * Then the stage is set to "release" * Then the changes to the issue-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check290.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(290); $issue->setStatus(IssueStatus::STAGE_APPROVAL); $result = $this->subject->increaseStage($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueDb */ $issueDb = $this->issueRepository->findByUid(290); self::assertEquals(IssueStatus::STAGE_RELEASE, $issueDb->getStatus()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStageRelease() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * When the method is called * Then true is returned * Then the stage is set to "sending" * Then the releaseTstamp-property is set * Then the changes to the issue-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check290.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(290); $issue->setStatus(IssueStatus::STAGE_RELEASE); $result = $this->subject->increaseStage($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueDb */ $issueDb = $this->issueRepository->findByUid(290); self::assertEquals(IssueStatus::STAGE_SENDING, $issueDb->getStatus()); self::assertGreaterThan(0, $issueDb->getReleaseTstamp()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStageSending() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "sending" * When the method is called * Then true is returned * Then the stage is set to "done" * Then the sentTstamp-property is set * Then the changes to the issue-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check290.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(290); $issue->setStatus(IssueStatus::STAGE_SENDING); $result = $this->subject->increaseStage($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueDb */ $issueDb = $this->issueRepository->findByUid(290); self::assertEquals(IssueStatus::STAGE_DONE, $issueDb->getStatus()); self::assertGreaterThan(0, $issueDb->getSentTstamp()); } /** * @test * @throws \Exception */ public function increaseStageReturnsFalseForStageDone() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "done" * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check290.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(290); $issue->setStatus(IssueStatus::STAGE_DONE); $result = $this->subject->increaseStage($issue); self::assertFalse($result); } //============================================= /** * @test * @throws \Exception */ public function getMailRecipientReturnsEmptyArray() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has no approval-admins set * Given a persisted issue-object that belongs to the newsletter-object * Given that issue-object has the stage "release" * When the method is called * Then an empty array is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check230.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(230); self::assertEmpty($this->subject->getMailRecipients($issue)); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsRecipients() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given that issue-object has the stage "release" * When the method is called * Then an array is returned * Then this array contains the two be-users */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check240.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(240); $result = $this->subject->getMailRecipients($issue); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(240, $result[0]->getUid()); self::assertEquals(241, $result[1]->getUid()); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsEmptyArrayOnWrongStage() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given that issue-object has the stage "approval" * When the method is called * Then an empty array is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check240.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(240); $issue->setStatus(IssueStatus::STAGE_APPROVAL); self::assertEmpty($this->subject->getMailRecipients($issue)); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsRecipientsAndChecksForEmail() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given one of the approval-admins has an invalid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given that issue-object has the stage "release" * When the method is called * Then an array is returned * Then this array contains the be-user with the valid email-address */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check250.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(250); $result = $this->subject->getMailRecipients($issue); self::assertIsArray( $result); self::assertCount(1, $result); self::assertEquals(251, $result[0]->getUid()); } //============================================= /** * @test * @throws \Exception */ public function sendMailsReturnsZeroForStageApproval() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "approval" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * When the method is called * Then the value 1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check300.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(300); $issue->setStatus(IssueStatus::STAGE_APPROVAL); $result = $this->subject->sendMails($issue); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsOneForStageReleaseLevel1() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * When the method is called * Then the value 1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check300.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(300); $result = $this->subject->sendMails($issue); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsOneForStageReleaseLevel2() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * When the method is called * Then the value 1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check310.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(310); $result = $this->subject->sendMails($issue); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsTwoForStageReleaseLevelDone() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has a value for the reminderTstamp-property set * When the method is called * Then the value 2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check320.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(320); $result = $this->subject->sendMails($issue); self::assertEquals(2, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsZeroIfNoRecipients() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has no approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * When the method is called * Then the value 1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check330.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(330); $result = $this->subject->sendMails($issue); self::assertEquals(0, $result); } //============================================= /** * @test * @throws \Exception */ public function processConfirmationReturnsFalseIfOneApprovalNotReady () { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "approval" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given one of the approval-objects have the allowedTstampStage2-property set * Given one of the approval-objects have the allowedTstampStage2-property not set * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check180.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(180); $result = $this->subject->processConfirmation($issue); self::assertFalse($result); } /** * @test * @throws \Exception */ public function processConfirmationReturnsTrueIfAllApprovalsReady () { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "approval" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * When the method is called * Then true is returned * Then the stage of the issue is set to "release" * Then the new status of the issue is persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check190.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(190); $issue->setStatus(IssueStatus::STAGE_APPROVAL); $result = $this->subject->processConfirmation($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(190); self::assertEquals(IssueStatus::STAGE_RELEASE, $issue->getStatus()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsTrueAndIncreasesLevelForStageReleaseLevel1 () { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * When the method is called * Then true is returned * Then the infoTstamp-property is set * Then the reminderTstamp-property is not set * Then the changes to the issue-object are persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check190.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(190); $result = $this->subject->processConfirmation($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(190); self::assertGreaterThan(0, $issue->getInfoTstamp()); self::assertEquals(0, $issue->getReminderTstamp()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsTrueAndIncreasesLevelForStageReleaseLevel2 () { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * When the method is called * Then true is returned * Then the infoTstamp-property is set * Then the reminderTstamp-property is set * Then the changes to the issue-object are persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check200.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(200); $result = $this->subject->processConfirmation($issue); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(200); self::assertGreaterThan(0, $issue->getInfoTstamp()); self::assertGreaterThan(0, $issue->getReminderTstamp()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsFalseForStageReleaseLevelDone () { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has a value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check210.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(210); $result = $this->subject->processConfirmation($issue); self::assertFalse($result); } /** * @test * @throws \Exception */ public function processConfirmationReturnsFalseForWrongStage () { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "sending" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * When the method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check220.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(220); $result = $this->subject->processConfirmation($issue); self::assertFalse($result); } //============================================= /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfNotInRightStage() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "sending" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * Given the tolerance-parameter for the level has been set to 600 seconds * When the method is called * Then zero is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check340.xml'); $result = $this->subject->processAllConfirmations(600); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfInStageApprovalAndDueForInfoMail() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "approval" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * Given the tolerance-parameter for the level has been set to 600 seconds * When the method is called * Then one is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check350.xml'); $result = $this->subject->processAllConfirmations(600); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfInStageReleaseAndDueForInfoMail() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has no value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * Given the tolerance-parameter for the level has been set to 600 seconds * When the method is called * Then one is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check360.xml'); $result = $this->subject->processAllConfirmations(600); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfInStageReleaseAndDueForReminderMail() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * Given the tolerance-parameter for the level has been set to 600 seconds * When the method is called * Then one is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check370.xml'); $result = $this->subject->processAllConfirmations(600); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfInStageReleaseAndNotDueForReminderMail() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has no value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * Given the tolerance-parameter for the level has been set to 600 seconds * Given the infoTstamp-property is set to a value not older than 600 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check370.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue*/ $issue = $this->issueRepository->findByUid(370); $issue->setInfoTstamp(time() - 5); $this->issueRepository->update($issue); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $persistenceManager->clearState(); $result = $this->subject->processAllConfirmations(600); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfInStageReleaseAndDueForAutomaticConfirmation() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has a value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * Given the tolerance-parameter for the level has been set to 600 seconds * When the method is called * Then one is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check380.xml'); $result = $this->subject->processAllConfirmations(600); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfInStageReleaseAndNotDueForAutomaticConfirmation() { /** * Scenario: * * Given a persisted newsletter-object * Given that newsletter-object has two approval-admins set * Given all of the approval-admins have a valid email-address set * Given a persisted issue-object that belongs to the newsletter-object * Given the issue-object has the stage "release" * Given the issue-object has a value for the infoTstamp-property set * Given the issue-object has a value for the reminderTstamp-property set * Given two persisted approval-objects * Given the two approval-objects belong to the issue-object * Given both of the approval-objects have the allowedTstampStage2-property set * Given the tolerance-parameter for the level has been set to 600 seconds * Given the reminerTstamp-property is set to a value not older than 600 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check380.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue*/ $issue = $this->issueRepository->findByUid(380); $issue->setReminderTstamp(time() - 5); $this->issueRepository->update($issue); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $persistenceManager->clearState(); $result = $this->subject->processAllConfirmations(600); self::assertEquals(0, $result); } /** * * @throws \Exception */ public function processAllConfirmationsReturnsTrue () { /** * Scenario: * * Given a two persisted issue-objects * Given one of the issue-objects has the stage "release" * Given one of the issue-objects has the stage "approval" * When the method is called * Then true is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check220.xml'); $result = $this->subject->processAllConfirmations(); self::assertTrue($result); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Model; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwAuthors\Domain\Model\Authors; use TYPO3\CMS\Extbase\Domain\Model\FrontendUserGroup; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * Newsletter * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class Newsletter extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * @var int */ protected int $sysLanguageUid = -1; /** * @var string */ protected string $name = ''; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwAuthors\Domain\Model\Authors>|null */ protected ?ObjectStorage $authors = null; /** * @var string */ protected string $issueTitle = ''; /** * @var string */ protected string $senderName = ''; /** * @var string */ protected string $senderMail = ''; /** * @var string */ protected string $replyName = ''; /** * @var string */ protected string $replyMail = ''; /** * @var string */ protected string $returnPath = ''; /** * @var int */ protected int $priority = 0; /** * @var string */ protected string $template = ''; /** * @var \RKW\RkwNewsletter\Domain\Model\Pages|null */ protected ?Pages $settingsPage = null; /** * @var int */ protected int $format = 0; /** * @var int */ protected int $rythm = 0; /** * @var int */ protected int $dayForSending = 0; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser>|null */ protected ?ObjectStorage $approval = null; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FrontendUserGroup>|null */ protected ?ObjectStorage $usergroup = null; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Topic>|null */ protected ?ObjectStorage $topic = null; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Issue>|null */ protected ?ObjectStorage $issue = null; /** * @var int */ protected int $lastSentTstamp = 0; /** * @var int */ protected int $lastIssueTstamp = 0; /** * __construct */ public function __construct() { //Do not remove the next line: It would break the functionality $this->initStorageObjects(); } /** * Initializes all ObjectStorage properties * Do not modify this method! * It will be rewritten on each save in the extension builder * You may modify the constructor of this class instead * * @return void */ protected function initStorageObjects(): void { $this->usergroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); $this->approval = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); $this->topic = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); $this->issue = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); } /** * Returns the sysLanguageUid * * @return int $sysLanguageUid */ public function getSysLanguageUid(): int { return $this->sysLanguageUid; } /** * Sets the sysLanguageUid * * @param int $sysLanguageUid * @return void */ public function setSysLanguageUid(int $sysLanguageUid): void { $this->sysLanguageUid = $sysLanguageUid; } /** * Returns the name * * @return string $name */ public function getName(): string { return $this->name; } /** * Sets the name * * @param string $name * @return void */ public function setName(string $name): void { $this->name = $name; } /** * Returns the issueTitle * * @return string */ public function getIssueTitle(): string { return $this->issueTitle; } /** * Sets the issueTitle * * @param string $issueTitle * @return void */ public function setIssueTitle(string $issueTitle): void { $this->issueTitle = $issueTitle; } /** * Returns the senderName * * @return string */ public function getSenderName(): string { return $this->senderName; } /** * Sets the senderName * * @param string $senderName * @return void */ public function setSenderName(string $senderName): void { $this->senderName = $senderName; } /** * Returns the senderMail * * @return string */ public function getSenderMail(): string { return $this->senderMail; } /** * Sets the senderMail * * @param string $senderMail * @return void */ public function setSenderMail(string $senderMail): void { $this->senderMail = $senderMail; } /** * Returns the replyName * * @return string */ public function getReplyName(): string { return $this->replyName; } /** * Sets the replyName * * @param string $replyName * @return void */ public function setReplyName(string $replyName): void { $this->replyName = $replyName; } /** * Returns the replyMail * * @return string */ public function getReplyMail(): string { return $this->replyMail; } /** * Sets the replyMail * * @param string $replyMail * @return void */ public function setReplyMail(string $replyMail): void { $this->replyMail = $replyMail; } /** * Returns the returnPath * * @return string */ public function getReturnPath(): string { return $this->returnPath; } /** * Sets the returnPath * * @param string $returnPath * @return void */ public function setReturnPath(string $returnPath): void { $this->returnPath = $returnPath; } /** * Returns the priority * * @return int */ public function getPriority(): int { return $this->priority; } /** * Sets the priority * * @param int $priority * @return void */ public function setPriority(int $priority): void { $this->priority = $priority; } /** * Returns the template * * @return string */ public function getTemplate(): string { return $this->template; } /** * Sets the template * * @param string $template * @return void */ public function setTemplate(string $template): void { $this->template = $template; } /** * Returns the settingsPage * * @return \RKW\RkwNewsletter\Domain\Model\Pages|null */ public function getSettingsPage():? Pages { return $this->settingsPage; } /** * Sets the settingsPage * * @param \RKW\RkwNewsletter\Domain\Model\Pages $settingsPage * @return void */ public function setSettingsPage(Pages $settingsPage): void { $this->settingsPage = $settingsPage; } /** * Returns the format * * @return int */ public function getFormat(): int { return $this->format; } /** * Sets the format * * @param int $format * @return void */ public function setFormat(int $format): void { $this->format = $format; } /** * Returns the rythm * * @return int $rythm */ public function getRythm(): int { return $this->rythm; } /** * Sets the rythm * * @param int $rythm * @return void */ public function setRythm(int $rythm): void { $this->rythm = $rythm; } /** * Returns the dayForSending * * @return int $dayForSending */ public function getDayForSending(): int { return $this->dayForSending; } /** * Sets the dayForSending * * @param int $dayForSending * @return void */ public function setDayForSending(int $dayForSending): void { $this->dayForSending = $dayForSending; } /** * Adds a backend user to the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void * @api */ public function addApproval(BackendUser $backendUser): void { $this->approval->attach($backendUser); } /** * Removes a backend user from the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void * @api */ public function removeApproval(BackendUser $backendUser): void { $this->approval->detach($backendUser); } /** * Returns the backend user. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser> * @api */ public function getApproval(): ObjectStorage { return $this->approval; } /** * Sets the backend user. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser> $backendUser * @return void * @api */ public function setApproval(ObjectStorage $backendUser) { $this->approval = $backendUser; } /** * Adds a usergroup to the newsletter * * @param \TYPO3\CMS\Extbase\Domain\Model\FrontendUserGroup $usergroup * @return void * @api */ public function addUsergroup(FrontendUserGroup $usergroup): void { $this->usergroup->attach($usergroup); } /** * Removes a usergroup from the newsletter * * @param \TYPO3\CMS\Extbase\Domain\Model\FrontendUserGroup $usergroup * @return void * @api */ public function removeUsergroup(FrontendUserGroup $usergroup): void { $this->usergroup->detach($usergroup); } /** * Returns the usergroups. Keep in mind that the property is called "usergroup" * although it can hold several usergroups. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage An object storage containing the usergroup * @api */ public function getUsergroup(): ObjectStorage { return $this->usergroup; } /** * Sets the usergroups. Keep in mind that the property is called "usergroup" * although it can hold several usergroups. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $usergroup * @return void * @api */ public function setUsergroup(ObjectStorage $usergroup): void { $this->usergroup = $usergroup; } /** * Adds a topic to the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @return void * @api */ public function addTopic(Topic $topic): void { $this->topic->attach($topic); } /** * Removes a usergroup from the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @return void * @api */ public function removeTopic(Topic $topic): void { $this->topic->detach($topic); } /** * Returns the topic. Keep in mind that the property is called "topic" * although it can hold several topic. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage An object storage containing the topic * @api */ public function getTopic(): ObjectStorage { return $this->topic; } /** * Sets the topic. Keep in mind that the property is called "topic" * although it can hold several topic. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $topic * @return void * @api */ public function setTopic(ObjectStorage $topic): void { $this->topic = $topic; } /** * Adds a issue to the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return void * @api */ public function addIssue(Issue $issue): void { $this->issue->attach($issue); } /** * Removes a usergroup from the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return void * @api */ public function removeIssue(Issue $issue): void { $this->issue->detach($issue); } /** * Returns the issue. Keep in mind that the property is called "issue" * although it can hold several issue. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage An object storage containing the issue * @api */ public function getIssue(): ObjectStorage { return $this->issue; } /** * Sets the issue. Keep in mind that the property is called "issue" * although it can hold several issue. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $issue * @return void * @api */ public function setIssue(ObjectStorage $issue): void { $this->issue = $issue; } /** * Returns the lastSentTstamp * * @return int */ public function getLastSentTstamp(): int { return $this->lastSentTstamp; } /** * Sets the lastSentTstamp * * @param int $lastSentTstamp * @return void */ public function setLastSentTstamp(int $lastSentTstamp): void { $this->lastSentTstamp = $lastSentTstamp; } /** * Returns the lastIssueTstamp * * @return int */ public function getLastIssueTstamp(): int { return $this->lastIssueTstamp; } /** * Sets the lastIssueTstamp * * @param int $lastIssueTstamp * @return void */ public function setLastIssueTstamp(int $lastIssueTstamp): void { $this->lastIssueTstamp = $lastIssueTstamp; } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers\Backend; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Issue; use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper; /** * GetNonSpecialTopicsViewHelper * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class GetNonSpecialTopicsViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('issue', Issue::class, 'Get non-special topics from this issue.', true); } /** * Gets all topics of the issue without special topics * * @return array */ public function render(): array { /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->arguments['issue']; $finalTopics = array(); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ if ($issue->getPages()) { foreach ($issue->getPages() as $page) { /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ if ($topic = $page->getTxRkwnewsletterTopic()) { if (!$topic->getIsSpecial()) { $finalTopics[] = $topic; } } } } return $finalTopics; } } <file_sep><?php namespace RKW\RkwNewsletter\Validation; use Madj2k\CoreExtended\Utility\GeneralUtility; use RKW\RkwNewsletter\Domain\Model\FrontendUser; use Madj2k\FeRegister\Utility\FrontendUserUtility; use TYPO3\CMS\Extbase\Error\Error; use TYPO3\CMS\Extbase\Utility\LocalizationUtility; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Class FormValidator * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class FormValidator extends \TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator { /** * validation * * @param \Madj2k\FeRegister\Domain\Model\FrontendUser $frontendUser * @return boolean * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function isValid($frontendUser) { $isValid = true; // get required fields of user $settings = GeneralUtility::getTypoScriptConfiguration('Rkwnewsletter'); $requiredFields = array('email'); if ($settings['requiredFieldsSubscription']) { $requiredFields = array_merge($requiredFields, \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $settings['requiredFieldsSubscription'], true)); } // check valid email if (in_array('email', $requiredFields)) { if (! FrontendUserUtility::isEmailValid($frontendUser->getEmail())) { $this->result->forProperty('email')->addError( new Error( LocalizationUtility::translate( 'validator.email_invalid', 'rkw_newsletter' ), 1537173349 ) ); $isValid = false; } } // check all properties on required foreach ($requiredFields as $requiredField) { $getter = 'get' . ucFirst($requiredField); if (method_exists($frontendUser, $getter)) { // has already been checked! if ($requiredField == 'email') { continue; } if ( ( ($requiredField != 'txFeregisterGender') && (empty($frontendUser->$getter())) ) || ( ($requiredField == 'txFeregisterGender') && ($frontendUser->$getter() == 99) ) ) { $this->result->forProperty($requiredField)->addError( new Error( LocalizationUtility::translate( 'validator.field_required', 'rkw_newsletter', array('field' => LocalizationUtility::translate( 'tx_rkwnewsletter_domain_model_frontenduser.' . \TYPO3\CMS\Core\Utility\GeneralUtility::camelCaseToLowerCaseUnderscored($requiredField), 'rkw_newsletter' ), ) ), 1537173350 ) ); $isValid = false; } } } return $isValid; } } <file_sep><?php return [ 'rkw_newsletter:createIssues' => [ 'class' => \RKW\RkwNewsletter\Command\CreateIssuesCommand::class, 'schedulable' => true, ], 'rkw_newsletter:processConfirmations' => [ 'class' => \RKW\RkwNewsletter\Command\ProcessConfirmationsCommand::class, 'schedulable' => true, ], 'rkw_newsletter:buildNewsletters' => [ 'class' => \RKW\RkwNewsletter\Command\BuildNewslettersCommand::class, 'schedulable' => true, ], ]; <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\ViewHelpers\Backend; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use TYPO3\CMS\Fluid\View\StandaloneView; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\NewsletterRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; /** * CountSubscriptionsViewHelperTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class CountSubscriptionsViewHelperTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/CountSubscriptionsViewHelperTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Domain\Repository\NewsletterRepository|null */ private ?NewsletterRepository $newletterRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \TYPO3\CMS\Fluid\View\StandaloneView|null */ private ?StandaloneView $standAloneViewHelper = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\NewsletterRepository newsletterRepository */ $this->newsletterRepository = $this->objectManager->get(NewsletterRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository topicRepository */ $this->topicRepository = $this->objectManager->get(TopicRepository::class); /** @var \TYPO3\CMS\Fluid\View\StandaloneView standAloneViewHelper */ $this->standAloneViewHelper = $this->objectManager->get(StandaloneView::class); $this->standAloneViewHelper->setTemplateRootPaths( [ 0 => self::FIXTURE_PATH . '/Frontend/Templates' ] ); } //============================================= /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsAllSubscriptions() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given two topics, A and B, that belong to the newsletter-object * Given topic A has two subscriptions, user X and Y * Given topic B has one subscription, user Z * When the ViewHelper is rendered without topic-parameter * Then the value 3 is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(10); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'newsletter' => $newsletter, 'topic' => null ] ); self::assertEquals('3', trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsAllSubscriptionsDistinct() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given two topics, A and B, that belong to the newsletter-object * Given topic A has two subscriptions, user X and Y * Given topic B has two subscriptions, user X and Z * When the ViewHelper is rendered without topic-parameter * Then the value 3 is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(20); $this->standAloneViewHelper->setTemplate('Check20.html'); $this->standAloneViewHelper->assignMultiple( [ 'newsletter' => $newsletter, 'topic' => null ] ); self::assertEquals('3', trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsSubscriptionsOfTopic() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given two topics, A and B, that belong to the newsletter-object * Given topic A has two subscriptions, user X and Y * Given topic B has one subscription, user Z * When the ViewHelper is rendered with topic-parameter topic A * Then the value 2 is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = $this->newsletterRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(30); $this->standAloneViewHelper->setTemplate('Check30.html'); $this->standAloneViewHelper->assignMultiple( [ 'newsletter' => $newsletter, 'topic' => $topic ] ); self::assertEquals('2', trim($this->standAloneViewHelper->render())); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php defined('TYPO3_MODE') || die('Access denied.'); call_user_func( function () { $tmpColsPages = [ 'tx_rkwnewsletter_newsletter' => [ 'exclude' => 0, 'onChange' => 'reload', 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_newsletter', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'size' => 1, 'eval' => 'int', 'items' => [ ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_newsletter.please_choose', 0], ], 'minitems' => 0, 'maxitems' => 1, 'default' => '', 'foreign_table' => 'tx_rkwnewsletter_domain_model_newsletter', 'foreign_table_where' => 'AND tx_rkwnewsletter_domain_model_newsletter.deleted = 0 AND tx_rkwnewsletter_domain_model_newsletter.hidden = 0', ], ], 'tx_rkwnewsletter_topic' => [ 'displayCond' => 'FIELD:tx_rkwnewsletter_newsletter:REQ:TRUE', 'onChange' => 'reload', 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_topic', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'size' => 1, 'eval' => 'int', 'foreign_table' => 'tx_rkwnewsletter_domain_model_topic', 'foreign_table_where' => 'AND newsletter=###REC_FIELD_tx_rkwnewsletter_newsletter### AND tx_rkwnewsletter_domain_model_topic.deleted = 0 AND tx_rkwnewsletter_domain_model_topic.hidden = 0', 'minitems' => 1, 'maxitems' => 1, 'items' => [ ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_topic.please_choose', 0], ], ], ], 'tx_rkwnewsletter_issue' => [ 'config' => [ 'type' => 'passthrough', 'foreign_table' => 'tx_rkwnewsletter_domain_model_issue', ], ], 'tx_rkwnewsletter_exclude' => [ 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_exclude', 'config' => [ 'type' => 'passthrough', ], ], 'tx_rkwnewsletter_teaser_heading' => [ 'displayCond' => [ 'AND' => [ 'FIELD:tx_rkwnewsletter_newsletter:REQ:TRUE', 'FIELD:tx_rkwnewsletter_topic:REQ:TRUE', ], ], 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_teaser_heading', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim,required' ], ], 'tx_rkwnewsletter_teaser_text' => [ 'displayCond' => [ 'AND' => [ 'FIELD:tx_rkwnewsletter_newsletter:REQ:TRUE', 'FIELD:tx_rkwnewsletter_topic:REQ:TRUE', ], ], 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_teaser_text', 'config' => [ 'type' => 'text', 'cols' => '40', 'rows' => '15', 'wrap' => 'off', 'eval' => 'RKW\\RkwNewsletter\\Validation\\TCA\\NewsletterTeaserLengthEvaluation,required', 'enableRichtext' => true, ], ], 'tx_rkwnewsletter_teaser_image' => [ 'displayCond' => [ 'AND' => [ 'FIELD:tx_rkwnewsletter_newsletter:REQ:TRUE', 'FIELD:tx_rkwnewsletter_topic:REQ:TRUE', ], ], 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_teaser_image', 'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig( 'txRkwnewsletterTeaserImage', [ 'maxitems' => 1 ], $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] ), ], 'tx_rkwnewsletter_teaser_link' => [ 'displayCond' => [ 'AND' => [ 'FIELD:tx_rkwnewsletter_newsletter:REQ:TRUE', 'FIELD:tx_rkwnewsletter_topic:REQ:TRUE', ], ], 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_teaser_link', 'config' => [ 'type' => 'input', 'renderType' => 'inputLink', 'size' => 30, 'eval' => 'trim', 'softref' => 'typolink' ], ], 'tx_rkwnewsletter_include_tstamp' => [ 'displayCond' => [ 'AND' => [ 'FIELD:tx_rkwnewsletter_newsletter:REQ:TRUE', 'FIELD:tx_rkwnewsletter_topic:REQ:TRUE', ], ], 'exclude' => 0, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter_include_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'eval' => 'datetime,int', 'default' => 0, ], ], ]; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns( 'pages', $tmpColsPages ); \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes( 'pages', '--div--;LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:pages.tx_rkwnewsletter;,tx_rkwnewsletter_newsletter,tx_rkwnewsletter_topic,tx_rkwnewsletter_teaser_heading,tx_rkwnewsletter_teaser_text,tx_rkwnewsletter_teaser_link,tx_rkwnewsletter_teaser_image,tx_rkwnewsletter_include_tstamp' ); } ); <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Status; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use RKW\RkwNewsletter\Domain\Repository\ApprovalRepository; use RKW\RkwNewsletter\Domain\Repository\BackendUserRepository; use RKW\RkwNewsletter\Status\ApprovalStatus; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; /** * ApprovalStatusTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ApprovalStatusTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/ApprovalStatusTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_authors', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Status\ApprovalStatus|null */ private ?ApprovalStatus $subject = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\ApprovalRepository|null */ private ?ApprovalRepository $approvalRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\BackendUserRepository|null */ private ?BackendUserRepository $backendUserRepository = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $this->objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->approvalRepository = $this->objectManager->get(ApprovalRepository::class); $this->backendUserRepository = $this->objectManager->get(BackendUserRepository::class); $this->subject = $this->objectManager->get(ApprovalStatus::class); } //============================================= /** * @test * @throws \Exception */ public function getStageReturnsDone() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has a value for the allowedTstampStage2-property set * When the method is called * Then $this->subject::STAGE3 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(10); self::assertEquals($this->subject::STAGE_DONE, $this->subject::getStage($approval)); } /** * @test * @throws \Exception */ public function getStageReturnsStage2() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has a value for the allowedTstampStage1-property set * When the method is called * Then $this->subject::STAGE2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(20); self::assertEquals($this->subject::STAGE2, $this->subject::getStage($approval)); } /** * @test * @throws \Exception */ public function getStageReturnsStage1() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has none of the allowedTstampStage-properties set * When the method is called * Then $this->subject::STAGE1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(30); self::assertEquals($this->subject::STAGE1, $this->subject::getStage($approval)); } //============================================= /** * @test * @throws \Exception */ public function getLevelReturnsLevel1ForStage1() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has none of the allowedTstampStage-properties set * Given that approval-object has no sentInfoTstampStage1-property set * When the method is called * Then $this->subject::LEVEL1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(40); self::assertEquals($this->subject::LEVEL1, $this->subject::getLevel($approval)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevel2ForStage1() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has none of the allowedTstampStage-properties set * Given that approval-object has a value for the sentInfoTstampStage1-property set * When the method is called * Then $this->subject::LEVEL2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(50); self::assertEquals($this->subject::LEVEL2, $this->subject::getLevel($approval)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevelDoneForStage1() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has none of the allowedTstampStage-properties set * Given that approval-object has a value for the sentReminderTstampStage1-property set * When the method is called * Then $this->subject::LEVEL_DONE is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(60); self::assertEquals($this->subject::LEVEL_DONE, $this->subject::getLevel($approval)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevel1ForStage2() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has a value for of the allowedTstampStage1-property set * Given that approval-object has no sentInfoTstampStage2-property set * When the method is called * Then $this->subject::LEVEL1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(70); self::assertEquals($this->subject::LEVEL1, $this->subject::getLevel($approval)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevel2ForStage2() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has a value for of the allowedTstampStage1-property set * Given that approval-object has a value for the sentInfoTstampStage2-property set * When the method is called * Then $this->subject::LEVEL2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(80); self::assertEquals($this->subject::LEVEL2, $this->subject::getLevel($approval)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevelDoneForStage2() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has a value for of the allowedTstampStage1-property set * Given that approval-object has a value for the sentReminderTstampStage1-property set * When the method is called * Then $this->subject::LEVEL2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(90); self::assertEquals($this->subject::LEVEL_DONE, $this->subject::getLevel($approval)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevelDoneForStagesAboveStage2() { /** * Scenario: * * Given a persisted approval-object * Given that approval-object has a value for of the allowedTstampStage2-property set * Given that approval-object has none of the sentInfoTstampStage-properties set * Given that approval-object has none of the sentReminderTstampStage-properties set * When the method is called * Then $this->subject::LEVEL0 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check100.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(100); self::assertEquals($this->subject::LEVEL_DONE, $this->subject::getLevel($approval)); } /** * @test * @throws \Exception */ public function increaseLevelSetsFirstLevelForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * When the method is called * Then true is returned * Then the sentInfoTstampStage1-property is set * Then the reminderTstamp-property is not set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check110.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(110); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); self::assertGreaterThan(0, $approval->getSentInfoTstampStage1()); self::assertEquals(0, $approval->getSentReminderTstampStage1()); } /** * @test * @throws \Exception */ public function increaseLevelSetSecondLevelForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * When the method is called * Then true is returned * Then the sentReminderTstampStage1-property is set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check120.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(120); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); self::assertGreaterThan(0, $approval->getSentReminderTstampStage1()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has a value for the sentReminderTstampStage1-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check130.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(130); $result = $this->subject->increaseLevel($approval); self::assertFalse($result); } /** * @test * @throws \Exception */ public function increaseLevelSetsFirstLevelForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * When the method is called * Then true is returned * Then the sentInfoTstampStage2-property is set * Then the sentReminderTstampStage2-property is not set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(140); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); self::assertGreaterThan(0, $approval->getSentInfoTstampStage2()); self::assertEquals(0, $approval->getSentReminderTstampStage2()); } /** * @test * @throws \Exception */ public function increaseLevelSetSecondLevelForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * When the method is called * Then true is returned * Then the sentReminderTstampStage2-property is set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(150); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); self::assertGreaterThan(0, $approval->getSentReminderTstampStage2()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has a value for the sentReminderTstampStage2-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(160); $result = $this->subject->increaseLevel($approval); self::assertFalse($result); } //============================================= /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given no backendUser * When the method is called * Then true is returned * Then the allowedTstampStage1-property is set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check170.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(170); $result = $this->subject->increaseStage($approval); self::assertTrue($result); self::assertGreaterThan(0, $approval->getAllowedTstampStage1()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage1AndSetsBeUser() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given a persisted backendUser * When the method is called * Then true is returned * Then the allowedTstampStage1-property is set * Then the allowedByUserStage1-property is set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check200.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(200); /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ $backendUser = $this->backendUserRepository->findByUid(200); $result = $this->subject->increaseStage($approval, $backendUser); self::assertTrue($result); self::assertGreaterThan(0, $approval->getAllowedTstampStage1()); self::assertEquals($backendUser, $approval->getAllowedByUserStage1()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * When the method is called * Then true is returned * Then the allowedTstampStage2-property is set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check180.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(180); $result = $this->subject->increaseStage($approval); self::assertTrue($result); self::assertGreaterThan(0, $approval->getAllowedTstampStage2()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage2AndSetsBeUser() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given a persisted backendUser * When the method is called * Then true is returned * Then the allowedTstampStage2-property is set * Then the allowedByUserStage2-property is set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check210.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(210); /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ $backendUser = $this->backendUserRepository->findByUid(210); $result = $this->subject->increaseStage($approval, $backendUser); self::assertTrue($result); self::assertGreaterThan(0, $approval->getAllowedTstampStage2()); self::assertEquals($backendUser, $approval->getAllowedByUserStage2()); } /** * @test * @throws \Exception */ public function increaseStageReturnsFalseForStagesAboveStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has a value for the allowedTstampStage2-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check190.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(190); $result = $this->subject->increaseStage($approval); self::assertFalse($result); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php defined('TYPO3_MODE') || die('Access denied.'); call_user_func( function (string $extKey) { //================================================================= // Add TypoScript //================================================================= \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile( $extKey, 'Configuration/TypoScript', 'RKW Newsletter' ); //================================================================= // Add TsConfig //================================================================= \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::registerPageTSConfigFile( $extKey, 'Configuration/TsConfig/setup.typoscript', 'RKW Newsletter' ); }, 'rkw_newsletter' ); <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Newsletter; use TYPO3\CMS\Extbase\Domain\Model\FrontendUser; use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper; /** * IsNewsletterSubscriptionAllowedViewHelper * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later * @todo rework and write tests */ class IsNewsletterSubscriptionAllowedViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('newsletter', Newsletter::class, 'Newsletter-object.', true); $this->registerArgument('frontendUser', FrontendUser::class, 'Frontend-user', false, null); } /** * Checks whether a user must be logged in to see a newsletter (group restriction / logged in) * * @return boolean */ public function render(): bool { $newsletter = $this->arguments['newsletter']; $frontendUser = $this->arguments['frontendUser']; // if newsletter has no restrictions if (!$newsletter->getUsergroup()->toArray()) { return true; } // check access for logged-in users if ($frontendUser) { /** @var \TYPO3\CMS\Extbase\Domain\Model\FrontendUserGroup $usergroup */ foreach ($frontendUser->getUsergroup()->toArray() as $userGroup) { /** @var \TYPO3\CMS\Extbase\Domain\Model\FrontendUserGroup $newsletterGroup */ foreach ($newsletter->getUsergroup()->toArray() as $newsletterGroup) { if ($userGroup->getUid() === $newsletterGroup->getUid()) { return true; } } } } return false; } } <file_sep><?php namespace RKW\RkwNewsletter\TCA; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Topic; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * Class OptionLabels * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class OptionLabels { /** * Fetches labels for newsletter topics * * @params array &$params * @params object $pObj * @param array $params * @param $pObj * @return void */ public static function getNewsletterTopicTitlesWithRootByUid(array &$params, $pObj): void { /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository $topic */ $topicRepository = $objectManager->get(TopicRepository::class); $result = $topicRepository->findAll(); // build extended names $extendedNames = []; /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ foreach ($result as $topic) { $extendedNames[$topic->getUid()] = self::getExtendedTopicName($topic); } // override given values foreach ($params['items'] as &$item) { if (isset($extendedNames[$item[1]])) { $item[0] = $extendedNames[$item[1]]; } } } /** * Return extended name for a newsletter topic * * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @return string */ public static function getExtendedTopicName(Topic $topic): string { if ($topic->getNewsletter()) { return $topic->getName() . ' (' . $topic->getNewsletter()->getName() . ')'; } return $topic->getName(); } } <file_sep><?php namespace RKW\RkwNewsletter\ViewHelpers; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper; /** * GetGroupedSubscribedTopics * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later * @todo rework and write tests */ class GetGroupedSubscribedTopicsViewHelper extends AbstractViewHelper { /** * Initialize arguments. * * @throws \TYPO3Fluid\Fluid\Core\ViewHelper\Exception */ public function initializeArguments(): void { parent::initializeArguments(); $this->registerArgument('subscriptions', ObjectStorage::class, 'ObjectStorage with subscriptions.', true); } /** * returns a grouped list of topics * * @return array */ public function render(): array { $subscriptions = $this->arguments['subscriptions']; $groupedTopics = array(); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ foreach ($subscriptions as $topic) { if ($topic->getNewsletter()) { if (!$groupedTopics[$topic->getNewsletter()->getName()]) { $groupedTopics[$topic->getNewsletter()->getName()] = array(); } $groupedTopics[$topic->getNewsletter()->getName()][$topic->getName()] = $topic; } } // now sort by topic-name foreach ($groupedTopics as $newsletter => &$topics) { ksort($topics); } return $groupedTopics; } } <file_sep><?php namespace RKW\RkwNewsletter\Controller; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Approval; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Newsletter; use RKW\RkwNewsletter\Domain\Model\Topic; use RKW\RkwNewsletter\Domain\Repository\BackendUserRepository; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\NewsletterRepository; use RKW\RkwNewsletter\Mailing\MailProcessor; use RKW\RkwNewsletter\Manager\ApprovalManager; use RKW\RkwNewsletter\Manager\IssueManager; use RKW\RkwNewsletter\Status\IssueStatus; use RKW\RkwNewsletter\Validation\EmailValidator; use TYPO3\CMS\Core\Messaging\FlashMessage; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Extbase\Utility\LocalizationUtility; /** * ReleaseController * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ReleaseController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController { /** * @var \RKW\RkwNewsletter\Domain\Repository\NewsletterRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected NewsletterRepository $newsletterRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected IssueRepository $issueRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\BackendUserRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected BackendUserRepository $backendUserRepository; /** * @var \RKW\RkwNewsletter\Manager\IssueManager * @TYPO3\CMS\Extbase\Annotation\Inject */ protected IssueManager $issueManager; /** * @var \RKW\RkwNewsletter\Manager\ApprovalManager * @TYPO3\CMS\Extbase\Annotation\Inject */ protected ApprovalManager $approvalManager; /** * @var \RKW\RkwNewsletter\Mailing\MailProcessor * @TYPO3\CMS\Extbase\Annotation\Inject */ protected MailProcessor $mailProcessor; /** * @var \RKW\RkwNewsletter\Validation\EmailValidator * @TYPO3\CMS\Extbase\Annotation\Inject */ protected EmailValidator $emailValidator; /** * Show a list of all outstanding confirmations * * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function confirmationListAction(): void { $issuesOpenApprovalStage1List = $this->issueRepository->findAllToApproveOnStage1(); $issuesOpenApprovalStage2List = $this->issueRepository->findAllToApproveOnStage2(); $issuesReadyToStart = $this->issueRepository->findAllToStartSending(); $this->view->assignMultiple( [ 'issuesOpenApprovalStage1List' => $issuesOpenApprovalStage1List, 'issuesOpenApprovalStage2List' => $issuesOpenApprovalStage2List, 'issuesReadyToStart' => $issuesReadyToStart ] ); } /** * action approve * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("approval") */ public function approveAction(Approval $approval): void { if ($this->approvalManager->increaseStage($approval)) { $this->addFlashMessage(LocalizationUtility::translate( 'releaseController.message.approvalSuccessful', 'rkw_newsletter' ), '', FlashMessage::OK); } else { $this->addFlashMessage(LocalizationUtility::translate( 'releaseController.error.unexpected', 'rkw_newsletter' ), '', FlashMessage::ERROR); } $this->redirect('confirmationList'); } /** * action defer * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException */ public function deferAction(Issue $issue): void { $issue->setStatus(98); $this->issueRepository->update($issue); $this->addFlashMessage(LocalizationUtility::translate( 'releaseController.message.issueDeferredSuccessfully', 'rkw_newsletter' ), '', FlashMessage::OK); $this->redirect('confirmationList'); } /** * action createIssueList * * @return void */ public function createIssueListAction(): void { /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ $backendUser = $this->backendUserRepository->findByUid(intval($GLOBALS['BE_USER']->user['uid'])); /** @var \TYPO3\CMS\Extbase\Persistence\QueryResultInterface $newsletters */ $newsletters = $this->newsletterRepository->findAll(); $this->view->assignMultiple( [ 'newsletters' => $newsletters, 'backendUser' => $backendUser, ] ); } /** * action createIssue * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @param \RKW\RkwNewsletter\Domain\Model\Topic|null $topic * @return void * @throws \RKW\RkwNewsletter\Exception * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function createIssueAction(Newsletter $newsletter, Topic $topic = null): void { // take all topics - or the one given $topicArray = $newsletter->getTopic()->toArray(); if ($topic) { $topicArray = [$topic]; } $this->issueManager->buildIssue($newsletter,$topicArray); $this->addFlashMessage( LocalizationUtility::translate( 'releaseController.message.issueCreated', 'rkw_newsletter' ) ); $this->redirect('createIssueList'); } /** * action testList * * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function testListAction(): void { /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ $backendUser = $this->backendUserRepository->findByUid(intval($GLOBALS['BE_USER']->user['uid'])); $issues = $this->issueRepository->findAllForTestSending(); $this->view->assignMultiple( [ 'issues' => $issues, 'backendUser' => $backendUser, ] ); } /** * action test * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param string $emails * @param \RKW\RkwNewsletter\Domain\Model\Topic|null $topic * @param string $title * @return void * @throws \Madj2k\Postmaster\Exception * @throws \RKW\RkwNewsletter\Exception * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("issue") */ public function testSendAction(Issue $issue, string $emails, Topic $topic = null, string $title = ''): void { $emailArray = GeneralUtility::trimExplode(',', $emails); foreach ($emailArray as $email) { /** @var \TYPO3\CMS\Extbase\Error\Result $validateEmail */ $validateEmail = $this->emailValidator->email($email); if ($validateEmail->hasErrors()) { $this->addFlashMessage( LocalizationUtility::translate( 'releaseController.error.emailIncorrect', 'rkw_newsletter', [$email] ), '', FlashMessage::ERROR ); $this->forward("testList"); } } // update title, and persist it $issue->setTitle($title); $this->issueRepository->update($issue); // set issue and topics $this->mailProcessor->setIssue($issue); $this->mailProcessor->setTopics(); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); if ($topic) { $objectStorage->attach($topic); $this->mailProcessor->setTopics($objectStorage); } // send mail if ($this->mailProcessor->sendTestMails($emails)) { $this->addFlashMessage( LocalizationUtility::translate( 'releaseController.message.testMailSent', 'rkw_newsletter' ) ); } else { $this->addFlashMessage( LocalizationUtility::translate( 'releaseController.error.testMail', 'rkw_newsletter' ), '', FlashMessage::ERROR ); } $this->redirect('testList'); } /** * action sendList * * @param \RKW\RkwNewsletter\Domain\Model\Issue|null $confirmIssue * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function sendListAction(Issue $confirmIssue = null): void { $issues = $this->issueRepository->findAllToStartSending(); $this->view->assignMultiple( [ 'issues' => $issues, 'confirmIssue' => $confirmIssue, 'backendUserId' => intval($GLOBALS['BE_USER']->user['uid']), 'backendUserName' => $GLOBALS['BE_USER']->user['realName'], ] ); } /** * action sendConfirm * * @param \RKW\RkwNewsletter\Domain\Model\Issue|null $issue * @param string $title * @return void * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("issue") */ public function sendConfirmAction(Issue $issue = null, string $title = ''): void { // check for issue if (! $issue) { $this->addFlashMessage( LocalizationUtility::translate( 'releaseController.error.selectIssue', 'rkw_newsletter' ), '', FlashMessage::ERROR ); $this->redirect('sendList'); } // set title $issue->setTitle($title); $this->issueRepository->update($issue); $this->view->assignMultiple( [ 'issue' => $issue, ] ); } /** * action send * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param string $title * @return void * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("issue") * @throws \Exception */ public function sendAction(Issue $issue, string $title = ''): void { if ($issue->getStatus() == IssueStatus::STAGE_RELEASE) { if ($title) { $issue->setTitle($title); $this->issueRepository->update($issue); } $this->issueManager->increaseStage($issue); $this->addFlashMessage( \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate( 'releaseController.message.sendingStarted', 'rkw_newsletter' ) ); } $this->redirect('sendList'); } } <file_sep><?php namespace RKW\RkwNewsletter\Validation; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Error\Result; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Validation\ValidatorResolver; /** * EmailValidator * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class EmailValidator implements \TYPO3\CMS\Core\SingletonInterface { /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager * @TYPO3\CMS\Extbase\Annotation\Inject */ protected ObjectManager $objectManager; /** * mail * * @param string $emailAddress * @return \TYPO3\CMS\Extbase\Error\Result */ public function email(string $emailAddress): Result { /** @var \TYPO3\CMS\Extbase\Validation\ValidatorResolver $validatorResolver */ $validatorResolver = $this->objectManager->get(ValidatorResolver::class); $conjunctionValidator = $validatorResolver->createValidator('Conjunction'); $conjunctionValidator->addValidator($validatorResolver->createValidator('EmailAddress')); return $conjunctionValidator->validate($emailAddress); } } <file_sep><?php return [ 'ctrl' => [ 'hideTable' => 1, 'title' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_topic', 'label' => 'name', 'tstamp' => 'tstamp', 'crdate' => 'crdate', 'cruser_id' => 'cruser_id', 'dividers2tabs' => true, 'delete' => 'deleted', 'enablecolumns' => [ 'disabled' => 'hidden', 'starttime' => 'starttime', 'endtime' => 'endtime', ], 'searchFields' => 'name,short_description,approval_stage1,approval_stage2,topic_pid,', 'iconfile' => 'EXT:rkw_newsletter/Resources/Public/Icons/tx_rkwnewsletter_domain_model_topic.gif' ], 'interface' => [ 'showRecordFieldList' => 'hidden, name, approval_stage1, approval_stage2, container_page, is_special', ], 'types' => [ '1' => ['showitem' => 'name, approval_stage1, approval_stage2, container_page, is_special, --div--;LLL:EXT:cms/locallang_ttc.xlf:tabs.access, hidden,--palette--;;1, starttime, endtime'], ], 'palettes' => [ '1' => ['showitem' => ''], ], 'columns' => [ 'hidden' => [ 'exclude' => false, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.hidden', 'config' => [ 'type' => 'check', ], ], 'starttime' => [ 'exclude' => false, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.starttime', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 13, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'range' => [ 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')), ], 'behaviour' => [ 'allowLanguageSynchronization' => true ] ], ], 'endtime' => [ 'exclude' => false, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.endtime', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 13, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'range' => [ 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')), ], 'behaviour' => [ 'allowLanguageSynchronization' => true ] ], ], 'name' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_topic.name', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim,required' ], ], 'short_description' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_topic.short_description', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'approval_stage1' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_topic.approval_stage1', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'size' => 8, 'eval' => 'int', 'minitems' => 1, 'maxitems' => 10, 'foreign_table' => 'be_users', 'foreign_table_where' => 'AND be_users.deleted = 0 AND be_users.disable = 0 ORDER BY be_users.username', ], ], 'approval_stage2' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_topic.approval_stage2', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'size' => 8, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 10, 'foreign_table' => 'be_users', 'foreign_table_where' => 'AND be_users.deleted = 0 AND be_users.disable = 0 ORDER BY be_users.username', ], ], 'container_page' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xl:tx_rkwnewsletter_domain_model_topic.container_page', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'int, required', ], ], 'is_special' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_topic.is_special', 'config' => [ 'type' => 'check' ], ], 'newsletter' => [ 'config' => [ 'type' => 'passthrough', 'foreign_table' => 'tx_rkwnewsletter_domain_model_newsletter', ], ], 'sorting' => [ 'config' => [ 'type' => 'passthrough', ], ], ], ]; <file_sep><?php namespace RKW\RkwNewsletter\Mailing; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Content; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Topic; use RKW\RkwNewsletter\Domain\Repository\ContentRepository; use RKW\RkwNewsletter\Domain\Repository\PagesRepository; use RKW\RkwNewsletter\Exception; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * ContentLoader * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ContentLoader { /** * @var \RKW\RkwNewsletter\Domain\Model\Issue|null */ protected ?Issue $issue = null; /** * @var array */ protected array $ordering = []; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage|null */ protected ?ObjectStorage $topics = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\ContentRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected ContentRepository $contentRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\PagesRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PagesRepository $pagesRepository; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * Constructor * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue $issue * @return void * @throws \RKW\RkwNewsletter\Exception */ public function __construct(Issue $issue) { $this->topics = new ObjectStorage(); $this->setIssue($issue); } /** * Gets the issue * * @return \RKW\RkwNewsletter\Domain\Model\Issue|null */ public function getIssue():? Issue { return $this->issue; } /** * Sets the issue and sets topics accordingly based on pages * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue $issue * @return void * @throws \RKW\RkwNewsletter\Exception */ public function setIssue(Issue $issue): void { $this->issue = $issue; /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $topics = new ObjectStorage(); foreach($this->issue->getPages() as $page) { /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ if ($topic = $page->getTxRkwnewsletterTopic()) { $topics->attach($topic); } } $this->setTopics($topics); } /** * Returns the current ordering * * @return array */ public function getOrdering(): array { return $this->ordering; } /** * Gets the topics * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Topic> $topics */ public function getTopics (): ObjectStorage { return $this->topics; } /** * Sets the topics * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Topic> $topics * @return void * @throws \RKW\RkwNewsletter\Exception */ public function setTopics (ObjectStorage $topics): void { // reset topics $this->topics = GeneralUtility::makeInstance(ObjectStorage::class); // add the given ones /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ foreach($topics as $topic) { // check if topic belongs to current newsletter-configuration before we add it if ($this->issue->getNewsletter()->getTopic()->contains($topic)) { $this->topics->attach($topic); } else { $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Topic with id=%s does not belong to issue with id=%s and is ignored.', $topic->getUid(), $this->issue->getUid() ) ); } } $this->updateOrdering(); } /** * Adds a topic * * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @return void * @throws \RKW\RkwNewsletter\Exception */ public function addTopic (Topic $topic): void { // check if topic belongs to current newsletter-configuration before we add it if ($this->issue->getNewsletter()->getTopic()->contains($topic)) { $this->topics->attach($topic); $this->updateOrdering(); } else { $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Topic with id=%s does not belong to issue with id=%s and is ignored.', $topic->getUid(), $this->issue->getUid() ) ); } } /** * Removes a topic * * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @return void * @throws \RKW\RkwNewsletter\Exception */ public function removeTopic (Topic $topic): void { $this->topics->detach($topic); $this->updateOrdering(); } /** * Checks if contents are available for the given topics * * @return bool * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function hasContents (): bool { if ($pages = $this->getPages()) { return (bool) $this->contentRepository->countByPagesAndLanguage( $pages, ($this->issue->getNewsletter()? $this->issue->getNewsletter()->getSysLanguageUid(): 0), true ); } return false; } /** * Counts the topics with contents * * @return int */ public function countTopicsWithContents (): int { $cnt = 0; if ($pages = $this->getPages()) { foreach ($pages as $page) { // get contents for topic $contentCount = $this->contentRepository->countByPageAndLanguage( $page, ($this->issue->getNewsletter() ? $this->issue->getNewsletter()->getSysLanguageUid() : 0), false ); if ($contentCount) { $cnt++; } } } return $cnt; } /** * Get all contents as a zip-merged array by topics * * @param int limit * @return array */ public function getContents (int $limit = 0): array { // load all contents of relevant pages /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $contents = []; foreach ($this->getPages() as $page) { // get contents for topic $contentsOfTopic = $this->contentRepository->findByPageAndLanguage( $page, ($this->issue->getNewsletter()? $this->issue->getNewsletter()->getSysLanguageUid(): 0), $limit, false )->toArray(); // set contents to key according to desired order - this is already given via getPages() if ($contentsOfTopic) { $contents[] = $contentsOfTopic; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Loaded %s contents for topic with id=%s of issue with id=%s.', count($contentsOfTopic), $page->getTxRkwnewsletterTopic()->getUid(), $this->issue->getUid() ) ); } // now mix topics together - pass array-items as separate parameters to arrayZipMerge $result = call_user_func_array( '\Madj2k\CoreExtended\Utility\GeneralUtility::arrayZipMerge', $contents ); if (is_array($result)) { return $result; } return []; } /** * Get first headline * * @return string */ public function getFirstHeadline (): string { // get first page in order /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ if ( ($pages = $this->getPages()) && ($page = $pages[0]) ){ /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->contentRepository->findByPageAndLanguage( $page, ($this->issue->getNewsletter()? $this->issue->getNewsletter()->getSysLanguageUid() : 0), 1, false )->getFirst(); if ($content) { $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Loaded first headline for topic with id=%s of issue with id=%s.', $page->getTxRkwnewsletterTopic()->getUid(), $this->issue->getUid() ) ); return $content->getHeader(); } return ''; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'No first headline found for issue with id=%s.', $this->issue->getUid() ) ); return ''; } /** * Get topic of content * * @param \RKW\RkwNewsletter\Domain\Model\Content $content * @return \RKW\RkwNewsletter\Domain\Model\Topic|null */ public function getTopicOfContent (Content $content):? Topic { /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid($content->getPid()); if ($topic = $page->getTxRkwnewsletterTopic()) { return $topic; } return null; } /** * Get editorial if content contains an editorial * * @return \RKW\RkwNewsletter\Domain\Model\Content|null */ public function getEditorial():? Content { // always empty if we have more than one topic with contents if ($this->countTopicsWithContents() > 1) { return null; } // get first page in order /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ if ( ($pages = $this->getPages()) && ($page = $pages[0]) ){ return $this->contentRepository->findOneEditorialByPageAndLanguage( $page, ($this->issue->getNewsletter()? $this->issue->getNewsletter()->getSysLanguageUid(): 0) ); } return null; } /** * Get the relevant pages based on set topics * * @return array */ public function getPages(): array { $pages = []; foreach ($this->issue->getPages() as $page) { // get topic of page if ($topic = $page->getTxRkwnewsletterTopic()) { // check if topic is allowed if (!isset($this->ordering[$topic->getUid()])) { continue; } // add page in order of given topics $pages[$this->ordering[$topic->getUid()]] = $page; } } ksort($pages); return $pages; } /** * Updates the ordering * * @return void * @throws \RKW\RkwNewsletter\Exception */ protected function updateOrdering (): void { // reset $this->ordering = []; $newTopics = new ObjectStorage(); // Always include special topics and set them at the beginning of the array if ($this->issue->getNewsletter()) { /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ foreach ($this->issue->getNewsletter()->getTopic() as $topic) { if ( ($topic->getIsSpecial()) && (!$this->topics->contains($topic)) ) { $newTopics->attach($topic); $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Added special topic with id=%s to ordering of issue with id=%s.', $topic->getUid(), $this->issue->getUid() ) ); } } } // combine old with new, because we can't do an array_unshift to add topic at position 0 if (count($newTopics->toArray())) { foreach ($this->topics as $topic) { if (! $topic instanceof Topic) { throw new Exception( 'Only instances of \RKW\RkwNewsletter\Domain\Model\Topic are allowed here.', 1649840507 ); } $newTopics->attach($topic); } $this->topics = $newTopics; } // get ordering in separate array based on topic-order /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $cnt = 0; foreach ($this->topics as $topic) { if (! $topic instanceof Topic) { throw new Exception( 'Only instances of \RKW\RkwNewsletter\Domain\Model\Topic are allowed here.', 1649840507 ); } $this->ordering[$topic->getUid()] = $cnt; $cnt++; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Updated ordering of issue with id=%s to: %s.', $this->issue->getUid(), str_replace("\n", '', print_r($this->ordering, true)) ) ); } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger():? Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\ViewHelpers\Backend; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use TYPO3\CMS\Core\Authentication\BackendUserAuthentication; use TYPO3\CMS\Fluid\View\StandaloneView; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; /** * HasBackendUserPermissionViewHelperTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class HasBackendUserPermissionViewHelperTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/HasBackendUserPermissionViewHelperTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \TYPO3\CMS\Fluid\View\StandaloneView|null */ private ?StandaloneView $standAloneViewHelper = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository issueRepository */ $this->issueRepository = $this->objectManager->get(IssueRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository topicRepository */ $this->topicRepository = $this->objectManager->get(TopicRepository::class); /** @var \TYPO3\CMS\Fluid\View\StandaloneView standAloneViewHelper */ $this->standAloneViewHelper = $this->objectManager->get(StandaloneView::class); $this->standAloneViewHelper->setTemplateRootPaths( [ 0 => self::FIXTURE_PATH . '/Frontend/Templates' ] ); } //============================================= /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsZeroIfHasReleasePermissionButIsNotLoggedIn() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted backend-user * Given that backend-user has the permission to release the issue * Given this backend-user is logged in * When the ViewHelper is rendered * Then the value 0 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( ['issue' => $issue] ); self::assertEquals(0, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsOneIfUserHasReleasePermission() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted backend-user * Given that backend-user has the permission to release the issue * Given this backend-user is logged in * When the ViewHelper is rendered * Then the value 1 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $GLOBALS['BE_USER']->user['uid'] = 10; $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( ['issue' => $issue] ); self::assertEquals(1, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsZeroIfUserHasReleasePermissionForOtherNewsletter() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object A * Given a persisted issue-object A that belongs to the newsletter-object A * Given a persisted newsletter-object B * Given a persisted issue-object B that belongs to the newsletter-object B * Given a persisted backend-user * Given that backend-user has the permission to release newsletter B * Given this backend-user is logged in * When the ViewHelper is rendered with issue A as parameter * Then the value 0 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); $GLOBALS['BE_USER']->user['uid'] = 20; $this->standAloneViewHelper->setTemplate('Check20.html'); $this->standAloneViewHelper->assignMultiple( ['issue' => $issue] ); self::assertEquals(0, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsZeroIfUserHasApprovalPermissionForAnyTopicOnReleaseOnly() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted topic-object A that belongs to the newsletter-object * Given a persisted backend-user * Given that backend-user has not the permission to release the issue * Given that backend-user has the permission to approve the topic A on approvalsStage 1 * Given this backend-user is logged in * When the ViewHelper is rendered without any topic- or stage-parameter * Then the value 0 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(70); $GLOBALS['BE_USER']->user['uid'] = 70; $this->standAloneViewHelper->setTemplate('Check70.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, ] ); self::assertEquals(0, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsOneIfUserHasApprovalPermissionForSpecificTopic() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted topic-object A that belongs to the newsletter-object * Given a persisted backend-user * Given that backend-user has not the permission to release the issue * Given that backend-user has the permission to approve the topic A on approvalsStage 1 * Given this backend-user is logged in * When the ViewHelper is rendered with approvalStage-parameter = 1 and topic-parameter = topic A * Then the value 1 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(30); $GLOBALS['BE_USER']->user['uid'] = 30; $this->standAloneViewHelper->setTemplate('Check30.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topic' => $topic, 'approvalStage' => 1 ] ); self::assertEquals(1, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsOneIfUserHasApprovalPermissionForAnyTopic() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted topic-object A that belongs to the newsletter-object * Given a persisted backend-user * Given that backend-user has not the permission to release the issue * Given that backend-user has the permission to approve the topic A on approvalsStage 1 * Given this backend-user is logged in * When the ViewHelper is rendered without any topic- or stage-parameter, but with allApprovals-parameter = true * Then the value 1 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(60); $GLOBALS['BE_USER']->user['uid'] = 60; $this->standAloneViewHelper->setTemplate('Check60.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, ] ); self::assertEquals(1, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsZeroIfUserHasApprovalPermissionOnAnotherStage() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted topic-object A that belongs to the newsletter-object * Given a persisted backend-user * Given that backend-user has not the permission to release the issue * Given that backend-user has the permission to approve the topic A on approvalsStage 1 * Given this backend-user is logged in * When the ViewHelper is rendered with approvalStage-parameter = 2 and topic-parameter = topic A * Then the value 0 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(30); $GLOBALS['BE_USER']->user['uid'] = 30; $this->standAloneViewHelper->setTemplate('Check30.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topic' => $topic, 'approvalStage' => 2 ] ); self::assertEquals(0, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsZeroIfUserHasApprovalPermissionForOtherNewsletter() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object A * Given a persisted issue-object A that belongs to the newsletter-object A * Given a persisted topic-object A that belongs to the newsletter-object A * Given a persisted newsletter-object A * Given a persisted issue-object B that belongs to the newsletter-object B * Given a persisted topic-object B that belongs to the newsletter-object B * Given a persisted backend-user * Given that backend-user has not the permission to release the issue of newsletter A * Given that backend-user has not the permission to release the issue of newsletter B * Given that backend-user has the permission to approve the topic B on approvalsStage 1 for newsletter B * Given this backend-user is logged in * When the ViewHelper is rendered with issue A as parameter and approvalStage = 1 as parameter and topic-parameter = topic B * Then the value 0 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(40); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(40); $GLOBALS['BE_USER']->user['uid'] = 40; $this->standAloneViewHelper->setTemplate('Check40.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topic' => $topic, 'approvalStage' => 1 ] ); self::assertEquals(0, trim($this->standAloneViewHelper->render())); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsTrueIfUserIsAdmin() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given a persisted backend-user * Given that backend-user has no permissions for the issue or the approvals * Given this backend-user is admin * Given this backend-user is logged in * When the ViewHelper is rendered * Then the value 1 is rendered */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(50); $GLOBALS['BE_USER'] = GeneralUtility::makeInstance(BackendUserAuthentication::class); $GLOBALS['BE_USER']->user['uid'] = 50; $GLOBALS['BE_USER']->user['admin'] = 1; $this->standAloneViewHelper->setTemplate('Check50.html'); $this->standAloneViewHelper->assignMultiple( ['issue' => $issue] ); self::assertEquals(1, trim($this->standAloneViewHelper->render())); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Repository; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Utility\QueryUtility; use TYPO3\CMS\Core\Utility\DebugUtility; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings; use TYPO3\CMS\Extbase\Persistence\QueryResultInterface; /** * NewsletterRepository * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class NewsletterRepository extends AbstractRepository { /** * @return void * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function initializeObject(): void { parent::initializeObject(); $this->defaultQuerySettings = $this->objectManager->get(Typo3QuerySettings::class); $this->defaultQuerySettings->setRespectStoragePage(false); } /** * findAllToBuildIssue * * @param int $tolerance in seconds * @param int $dayOfMonth * @param int $currentTime * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Core\Type\Exception\InvalidEnumerationValueException * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException * comment: only used by command controller */ public function findAllToBuildIssue(int $tolerance = 0, int $currentTime = 0): QueryResultInterface { if (! $currentTime) { $currentTime = time(); } $statement = 'SELECT * FROM tx_rkwnewsletter_domain_model_newsletter WHERE ( ( rythm = 1 AND WEEKOFYEAR(FROM_UNIXTIME(last_issue_tstamp)) < WEEKOFYEAR(FROM_UNIXTIME(' . ($currentTime + $tolerance) . ')) ) OR ( rythm = 2 AND DATEDIFF(FROM_UNIXTIME(' . ($currentTime + $tolerance) . '), FROM_UNIXTIME(last_issue_tstamp)) >= 30 AND (DAY(FROM_UNIXTIME(' . ($currentTime + $tolerance) . ')) >= day_for_sending) ) OR ( rythm = 3 AND DATEDIFF(FROM_UNIXTIME(' . ($currentTime + $tolerance) . '), FROM_UNIXTIME(last_issue_tstamp)) >= (30*2) AND (DAY(FROM_UNIXTIME(' . ($currentTime + $tolerance) . ')) >= day_for_sending) ) OR ( rythm = 5 AND DATEDIFF(FROM_UNIXTIME(' . ($currentTime + $tolerance) . '), FROM_UNIXTIME(last_issue_tstamp)) >= (30*6) AND (DAY(FROM_UNIXTIME(' . ($currentTime + $tolerance) . ')) >= day_for_sending) ) OR ( rythm = 4 AND ( ( QUARTER(FROM_UNIXTIME(last_issue_tstamp)) < QUARTER(FROM_UNIXTIME(' . ($currentTime + $tolerance). ')) AND QUARTER(FROM_UNIXTIME(last_issue_tstamp)) != QUARTER(FROM_UNIXTIME(' . ($currentTime) . ')) ) OR ( QUARTER(FROM_UNIXTIME(last_issue_tstamp)) > QUARTER(FROM_UNIXTIME(' . ($currentTime + $tolerance). ')) AND YEAR(FROM_UNIXTIME(last_issue_tstamp)) < YEAR(FROM_UNIXTIME(' . $currentTime . ')) ) ) AND (DAY(FROM_UNIXTIME(' . ($currentTime + $tolerance) . ')) >= day_for_sending) ) )' . QueryUtility::getWhereClauseEnabled('tx_rkwnewsletter_domain_model_newsletter') . QueryUtility::getWhereClauseVersioning('tx_rkwnewsletter_domain_model_newsletter'); $query = $this->createQuery(); $query->statement($statement); return $query->execute(); } /** * Returns all newsletters and filter by given id-list * * @param string $idList * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * comment: used for subscription * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function findAllForSubscription(string $idList = ''): QueryResultInterface { $query = $this->createQuery(); if ($idList) { $query->matching( $query->in('uid', GeneralUtility::trimExplode(',', $idList, true)) ); } return $query->execute(); } } <file_sep># rkw_newsletter ## Features Extension for sending newsletters. Each newsletter can contain several topics, which can be freely selected by the subscribers. In the dispatch process, each subscriber then receives only the topics that he or she has chosen. Special issues can be created. ## Structure and process Editors can mark content in the backend as relevant for the newsletter. It is then automatically collected and copied into the editorial template a few days before the send date, reducing the editor's workload for the newsletter. A folder ("issue-folder") must be created for each newsletter topic. Here the extention creates a new page a few days before the dispatch date and collects the marked contents there. Using appropriate roles and approval processes, each topic can be prepared accordingly. Each newsletter can have a general editorial that is sent to those who have subscribed to more than one topic. In addition, each topic can have an editorial that is used only when a person subscribes to that topic only. The extension includes a multi-step approval process. A timed release can be set on the lower release levels. In the dispatch process, each subscribing person then receives only the topics that he or she has selected. In the process, the topics are zipped together while maintaining the order selected by the editor. ## Setup * Create a newsletter record with corresponding topics. * A folder has to be created in the backend for each topic. The issues per topic will be generated into this. * There is a backend layout for editing the newsletter articles, which can be set via page configuration of the issue-folders. * A cronjob must be created for the time-controlled creation of the issues, the approval process and the dispatch process. Status of editing: 2022-05-10<file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\ViewHelpers\Mailing; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Fluid\View\StandaloneView; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; /** * GetContentsViewHelperTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class GetContentsViewHelperTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/GetContentsViewHelperTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \TYPO3\CMS\Fluid\View\StandaloneView|null */ private ?StandaloneView $standAloneViewHelper = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository issueRepository */ $this->issueRepository = $this->objectManager->get(IssueRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository topicRepository */ $this->topicRepository = $this->objectManager->get(TopicRepository::class); /** @var \TYPO3\CMS\Fluid\View\StandaloneView standAloneViewHelper */ $this->standAloneViewHelper = $this->objectManager->get(StandaloneView::class); $this->standAloneViewHelper->setTemplateRootPaths( [ 0 => self::FIXTURE_PATH . '/Frontend/Templates' ] ); } //============================================= /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsContentsWithTopicAFirst() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered with topic-parameter in the order A-B * Then a list of five contents is rendered * Then the list contains only the given topics of the issue * Then the list starts with contents of topic A * Then the list is ordered in zipper-method respecting the defined order of contents * Then the contents marked as editorial are ignored * Then no contents of topic C are included */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $objectStorage->attach($topic2); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage ] ); self::assertEquals( 'Content 10.2,Content 11.2,Content 10.3,Content 11.3,Content 10.4', trim($this->standAloneViewHelper->render()) ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsContentsWithTopicBFirst() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered with topic-parameter in the order B-A * Then a list of five contents is rendered * Then the list contains only the given topics of the issue * Then the list starts with contents of topic B * Then the list is ordered in zipper-method respecting the defined order of contents * Then the contents marked as editorial are ignored * Then no contents of topic C are included */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage ] ); self::assertEquals( 'Content 11.2,Content 10.2,Content 11.3,Content 10.3,Content 10.4', trim($this->standAloneViewHelper->render()) ); } /** * @test * @throws \Exception */ public function itReturnsSortedContentsWithSpecialTopicFirst() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the topic-object C is marked as a special topic * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered with topic-parameter topic A/topic B * Then a list of seven contents is rendered * Then the list contains only the given topics of the issue * Then the list starts with contents of topic c * Then the list is ordered in zipper-method respecting the defined order of contents * Then the contents marked as editorial are ignored */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(21); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $objectStorage->attach($topic2); $this->standAloneViewHelper->setTemplate('Check20.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage ] ); self::assertEquals( 'Content 92.2,Content 90.2,Content 91.2,Content 92.3,Content 90.3,Content 91.3,Content 90.4', trim($this->standAloneViewHelper->render()) ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsContentsAndRespectsLimit() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered with topic-parameter in the order B-A and with limit = 1 * Then a list of two contents is rendered * Then the list contains only the given topics of the issue * Then the list starts with contents of topic B * Then the list is ordered in zipper-method respecting the defined order of contents * Then the contents marked as editorial are ignored */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic2); $objectStorage->attach($topic1); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage, 'limit' => 1 ] ); self::assertEquals( 'Content 11.2,Content 10.2', trim($this->standAloneViewHelper->render()) ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsContentsOfAllAvailableTopics() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object * Given a persisted issue-object that belongs to the newsletter-object * Given three persisted topic-objects A, B and C * Given this topic-objects belong to the newsletter-object * Given for topic-object A there is a page-object X that belongs to the current issue-object * Given for topic-object B there is a page-object Y that belongs to the current issue-object * Given for topic-object C there is a page-object Z that belongs to the current issue-object * Given the page-object X contains four content-objects * Given one of the content-objects is an editorial * Given the page-object Y contains three content-objects * Given one of the content-objects is an editorial * Given the page-object Z contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered without topic parameter * Then a list of seven contents is rendered * Then the list contains all available topics of the issue * Then the list starts with contents of topic A * Then the list is ordered in zipper-method respecting the defined order of contents * Then the contents marked as editorial are ignored */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue ] ); self::assertEquals( 'Content 10.2,Content 11.2,Content 12.2,Content 10.3,Content 11.3,Content 12.3,Content 10.4', trim($this->standAloneViewHelper->render()) ); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Manager; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use RKW\RkwNewsletter\Domain\Model\Approval; use RKW\RkwNewsletter\Domain\Model\BackendUser; use RKW\RkwNewsletter\Domain\Repository\ApprovalRepository; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\PagesRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use RKW\RkwNewsletter\Manager\ApprovalManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; /** * ApprovalManagerTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ApprovalManagerTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/ApprovalManagerTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_authors', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Manager\ApprovalManager|null */ private ?ApprovalManager $subject = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\PagesRepository|null */ private ?PagesRepository $pagesRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\ApprovalRepository|null */ private ?ApprovalRepository $approvalRepository; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $this->objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->topicRepository = $this->objectManager->get(TopicRepository::class); $this->issueRepository = $this->objectManager->get(IssueRepository::class); $this->pagesRepository = $this->objectManager->get(PagesRepository::class); $this->approvalRepository = $this->objectManager->get(ApprovalRepository::class); $this->subject = $this->objectManager->get(ApprovalManager::class); // For Mail-Interface $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName'] = 'RKW'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'] = '<EMAIL>'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailReplyName'] = 'RKW'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailReplyToAddress'] = '<EMAIL>'; $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailReturnAddress'] = '<EMAIL>'; } //============================================= /** * @test * @throws \Exception */ public function createApprovalCreatesApprovalAndAddsItToIssue() { /** * Scenario: * * Given a topic-object that is persisted * Given an issue-object that is persisted and belongs to that topic * Given a page-object that is persisted and belongs to the issue * When the method is called * Then an instance of \RKW\RkwNewsletter\Model\Approval is returned * Then the topic-property of this instance is set to the topic-object * Then the page-property of this instance is set to the page-object * Then the approval-object is persisted * Then the approval-object is added to the approvals-property of the issue-object * Then the changes on the issue-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $approval = $this->subject->createApproval($topic, $issue, $page); self::assertInstanceOf(Approval::class, $approval); self::assertEquals($topic, $approval->getTopic()); self::assertEquals($page, $approval->getPage()); /** @var \TYPO3\CMS\Extbase\Persistence\QueryResultInterface $approvals */ $approvalsDb = $this->approvalRepository->findAll(); self::assertCount(1, $approvalsDb); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approvalDb = $approvalsDb->getFirst(); self::assertEquals($approval, $approvalDb); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issueDb */ $issueDb = $this->issueRepository->findByUid(10); self::assertCount(1, $issueDb->getApprovals()); $issueDb->getApprovals()->rewind(); self::assertEquals($approval, $issueDb->getApprovals()->current()); } //============================================= /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueAndSetsFirstLevelForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * When the method is called * Then true is returned * Then the sentInfoTstampStage1-property is set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(80); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(80); self::assertGreaterThan(0, $approvalDb->getSentInfoTstampStage1()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueAndSetSecondLevelForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * When the method is called * Then true is returned * Then the sentTeminderTstampStage1-property is set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(90); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(90); self::assertGreaterThan(0, $approvalDb->getSentReminderTstampStage1()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has a value for the sentReminderTstampStage1-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check100.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(100); $result = $this->subject->increaseLevel($approval); self::assertFalse($result); } /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueAndSetsFirstLevelForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * When the method is called * Then true is returned * Then the sentInfoTstampStage2-property is set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check110.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(110); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(110); self::assertGreaterThan(0, $approvalDb->getSentInfoTstampStage2()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueAndSetSecondLevelForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * When the method is called * Then true is returned * Then the sentReminderTstampStage2-property is set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check120.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(120); $result = $this->subject->increaseLevel($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(120); self::assertGreaterThan(0, $approvalDb->getSentReminderTstampStage2()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has a value for the sentReminderTstampStage2-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check130.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(130); $result = $this->subject->increaseLevel($approval); self::assertFalse($result); } //============================================= /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given no backendUser is logged in * When the method is called * Then true is returned * Then the allowedTstampStage1-property is set * Then the allowedByUserStage1-property is not set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(140); $GLOBALS['BE_USER'] = new \TYPO3\CMS\Core\Authentication\BackendUserAuthentication(); $GLOBALS['BE_USER']->user = []; $result = $this->subject->increaseStage($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(140); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage1()); self::assertNull($approvalDb->getAllowedByUserStage1()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage1AndSetsBackendUser() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the allowedTstampStage-properties set * Given the method is called via backend and thus a backendUser is logged in * When the method is called * Then true is returned * Then the allowedTstampStage1-property is set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(140); $GLOBALS['BE_USER'] = new \TYPO3\CMS\Core\Authentication\BackendUserAuthentication(); $GLOBALS['BE_USER']->user= []; $GLOBALS['BE_USER']->user['uid'] = 140; $result = $this->subject->increaseStage($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(140); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage1()); self::assertInstanceOf(BackendUser::class, $approvalDb->getAllowedByUserStage1()); self::assertEquals(140, $approvalDb->getAllowedByUserStage1()->getUid()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given no backendUser is logged in * When the method is called * Then true is returned * Then the allowedTstampStage2-property is set * Then the allowedByUserStage2-property is not set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(150); $GLOBALS['BE_USER'] = new \TYPO3\CMS\Core\Authentication\BackendUserAuthentication(); $GLOBALS['BE_USER']->user = []; $result = $this->subject->increaseStage($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(150); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage2()); self::assertNull($approvalDb->getAllowedByUserStage2()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForStage2AndSetsBackendUser() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given no backendUser is logged in * When the method is called * Then true is returned * Then the allowedTstampStage2-property is set * Then the allowedByUserStage2-property is set * Then the changes to the approval-object are persisted */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(150); $GLOBALS['BE_USER'] = new \TYPO3\CMS\Core\Authentication\BackendUserAuthentication(); $GLOBALS['BE_USER']->user= []; $GLOBALS['BE_USER']->user['uid'] = 150; $result = $this->subject->increaseStage($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(150); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage2()); self::assertInstanceOf(BackendUser::class, $approvalDb->getAllowedByUserStage2()); self::assertEquals(150, $approvalDb->getAllowedByUserStage2()->getUid()); } /** * @test * @throws \Exception */ public function increaseStageReturnsFalseForStagesAboveStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has a value for the allowedTstampStage2-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(160); $result = $this->subject->increaseStage($approval); self::assertFalse($result); } //============================================= /** * @test * @throws \Exception */ public function getMailRecipientsReturnsEmptyArray() { /** * Scenario: * * Given a persisted approval-object * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has no approval-admins set * When the method is called * Then an empty array is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(20); self::assertEmpty($this->subject->getMailRecipients($approval)); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsRecipientsForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the two allowedTstampStage-properties set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has two approval-be-users for stage 1 set * Given that topic-object has two approval-be-users for stage 2 set * When the method is called * Then an array is returned * Then this array contains the two be-users for stage 1 */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(30); $result = $this->subject->getMailRecipients($approval); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(30, $result[0]->getUid()); self::assertEquals(31, $result[1]->getUid()); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsRecipientsForStage1AndChecksForEmail() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has none of the two allowedTstampStage-properties set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has two approval-be-users for stage 1 set * Given one of the approval-be-users for stage 1 has an invalid email-address set * Given that topic-object has two approval-be-users for stage 2 set * When the method is called * Then an array is returned * Then this array contains the one be-user for stage 1 * Then the be-user with the wrong email-address is not included in the array */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(40); $result = $this->subject->getMailRecipients($approval); self::assertIsArray( $result); self::assertCount(1, $result); self::assertEquals(40, $result[0]->getUid()); self::assertEquals('<EMAIL>', $result[0]->getEmail()); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsRecipientsForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has the allowedTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has two approval-be-users for stage 1 set * Given that topic-object has two approval-be-users for stage 2 set * When the method is called * Then an array is returned * Then this array contains the two be-users for stage 2 */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(50); $result = $this->subject->getMailRecipients($approval); self::assertIsArray( $result); self::assertCount(2, $result); self::assertEquals(52, $result[0]->getUid()); self::assertEquals(53, $result[1]->getUid()); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsRecipientsForStage2AndChecksForEmail() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has the allowedTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has two approval-be-users for stage 1 set * Given that topic-object has two approval-be-users for stage 2 set * Given one of the approval-be-users for stage 2 has an invalid email-address set * When the method is called * Then an array is returned * Then this array contains the one be-user for stage 2 * Then the be-user with the wrong email-address is not included in the array */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(60); $result = $this->subject->getMailRecipients($approval); self::assertIsArray( $result); self::assertCount(1, $result); self::assertEquals(62, $result[0]->getUid()); self::assertEquals('<EMAIL>', $result[0]->getEmail()); } /** * @test * @throws \Exception */ public function getMailRecipientsReturnsEmptyArrayOnHigherStages() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has the allowedTstampStage1-property set * Given the approval-object has the allowedTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has two approval-be-users for stage 1 set * Given that topic-object has two approval-be-users for stage 2 set * When the method is called * Then an empty array is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(70); $result = $this->subject->getMailRecipients($approval); self::assertEmpty($result); } //============================================= /** * @test * @throws \Exception */ public function sendMailsReturnsOneForStage1Level1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * When the method is called * Then the value 1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check170.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(170); $result = $this->subject->sendMails($approval); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsOneForStage1Level2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * When the method is called * Then the value 1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check180.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(180); $result = $this->subject->sendMails($approval); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsTwoForStage1LevelDone() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has a value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * When the method is called * Then the value 2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check190.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(190); $result = $this->subject->sendMails($approval); self::assertEquals(2, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsZeroIfNoRecipientsForStage1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has no approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * When the method is called * Then the value 0 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check200.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(200); $result = $this->subject->sendMails($approval); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsOneForStage2Level1() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * When the method is called * Then the value 1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check210.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(210); $result = $this->subject->sendMails($approval); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsOneForStage2Level2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * When the method is called * Then the value 1 is returned * */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check220.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(220); $result = $this->subject->sendMails($approval); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsTwoForStage2LevelDone() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has a value for the sentReminderTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * When the method is called * Then the value 2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check230.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(230); $result = $this->subject->sendMails($approval); self::assertEquals(2, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsZeroIfNoRecipientsForStage2() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has no approval-be-user for stage 2 set * When the method is called * Then the value 0 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check240.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(240); $result = $this->subject->sendMails($approval); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function sendMailsReturnsZeroForStageDone() { /** * Scenario: * * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has a value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has no approval-be-user for stage 2 set * When the method is called * Then the value 0 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check270.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(270); $result = $this->subject->sendMails($approval); self::assertEquals(0, $result); } //============================================= /** * @test * @throws \Exception */ public function processConfirmationReturnsTrueAndIncreasesLevelForStage1Level0() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given the approval-object has a page defined in the page-property * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then true is returned * Then the sentInfoTstampStage1-property is set * Then the sentReminderTstampStage1-property is not set * Then the allowTstampStage1-property is not set * Then the allowTstampStage2-property is not set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check170.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(170); $result = $this->subject->processConfirmation($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(170); self::assertGreaterThan(0, $approvalDb->getSentInfoTstampStage1()); self::assertEquals(0, $approvalDb->getSentReminderTstampStage1()); self::assertEquals(0, $approvalDb->getAllowedTstampStage1()); self::assertEquals(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(170); self::assertEquals(1, $page->getPermsUserId()); self::assertEquals(1, $page->getPermsGroupId()); self::assertEquals(1, $page->getPermsUser()); self::assertEquals(1, $page->getPermsGroup()); self::assertEquals(1, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsTrueAndIncreasesLevelForStage1Level1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then true is returned * Then the sentReminderTstampStage1-property is set * Then the allowTstampStage1-property is not set * Then the allowTstampStage2-property is not set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check180.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(180); $result = $this->subject->processConfirmation($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(180); self::assertGreaterThan(0, $approvalDb->getSentReminderTstampStage1()); self::assertEquals(0, $approvalDb->getAllowedTstampStage1()); self::assertEquals(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(180); self::assertEquals(1, $page->getPermsUserId()); self::assertEquals(1, $page->getPermsGroupId()); self::assertEquals(1, $page->getPermsUser()); self::assertEquals(1, $page->getPermsGroup()); self::assertEquals(1, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsFalseAndIncreasesStageForStage1Level2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has a value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then false is returned * Then the allowTstampStage1-property is set * Then the allowTstampStage2-property is not set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check190.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(190); $result = $this->subject->processConfirmation($approval); self::assertFalse($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(190); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage1()); self::assertEquals(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(190); self::assertEquals(2, $page->getPermsUserId()); self::assertEquals(2, $page->getPermsGroupId()); self::assertEquals(2, $page->getPermsUser()); self::assertEquals(2, $page->getPermsGroup()); self::assertEquals(2, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsFalseAndIncreasesStageIfNoRecipientsForStage1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has no approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then false is returned * Then the allowTstampStage1-property is set * Then the allowTstampStage2-property is not set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check200.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(200); $result = $this->subject->processConfirmation($approval); self::assertFalse($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(200); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage1()); self::assertEquals(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(200); self::assertEquals(2, $page->getPermsUserId()); self::assertEquals(2, $page->getPermsGroupId()); self::assertEquals(2, $page->getPermsUser()); self::assertEquals(2, $page->getPermsGroup()); self::assertEquals(2, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsTrueAndIncreasesLevelForStage2Level0() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then true is returned * Then the sentInfoTstampStage2-property is set * Then the sentReminderTstampStage2-property is not set * Then the allowTstampStage2-property is not set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check210.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(210); $result = $this->subject->processConfirmation($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(210); self::assertGreaterThan(0, $approvalDb->getSentInfoTstampStage2()); self::assertEquals(0, $approvalDb->getSentReminderTstampStage2()); self::assertEquals(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(210); self::assertEquals(2, $page->getPermsUserId()); self::assertEquals(2, $page->getPermsGroupId()); self::assertEquals(2, $page->getPermsUser()); self::assertEquals(2, $page->getPermsGroup()); self::assertEquals(2, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsTrueAndIncreasesLevelForStage2Level1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then true is returned * Then the sentReminderTstampStage2-property is set * Then the allowTstampStage2-property is not set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check220.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(220); $result = $this->subject->processConfirmation($approval); self::assertTrue($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(220); self::assertGreaterThan(0, $approvalDb->getSentReminderTstampStage2()); self::assertEquals(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(220); self::assertEquals(2, $page->getPermsUserId()); self::assertEquals(2, $page->getPermsGroupId()); self::assertEquals(2, $page->getPermsUser()); self::assertEquals(2, $page->getPermsGroup()); self::assertEquals(2, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsFalseAndIncreasesStageForStage2Level2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has a value for the sentReminderTstampStage2-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has one approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then false is returned * Then the allowTstampStage2-property is set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check230.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(230); $result = $this->subject->processConfirmation($approval); self::assertFalse($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(230); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(230); self::assertEquals(3, $page->getPermsUserId()); self::assertEquals(3, $page->getPermsGroupId()); self::assertEquals(4, $page->getPermsUser()); self::assertEquals(4, $page->getPermsGroup()); self::assertEquals(4, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function processConfirmationReturnsFalseAndIncreasesStageIfNoRecipientsForStage2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object belongs to this issue-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted topic-object that belongs to the approval-object * Given that topic-object has one approval-be-user for stage 1 set * Given that topic-object has no approval-be-user for stage 2 set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * When the method is called * Then false is returned * Then the allowTstampStage2-property is set * Then the changes to the approval-object are persisted * Then the permissions of the page are set according to the configuration of the new status */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check240.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(240); $result = $this->subject->processConfirmation($approval); self::assertFalse($result); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approvalDb */ $approvalDb = $this->approvalRepository->findByUid(240); self::assertGreaterThan(0, $approvalDb->getAllowedTstampStage2()); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(240); self::assertEquals(3, $page->getPermsUserId()); self::assertEquals(3, $page->getPermsGroupId()); self::assertEquals(4, $page->getPermsUser()); self::assertEquals(4, $page->getPermsGroup()); self::assertEquals(4, $page->getPermsEverybody()); } //============================================= /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfDueForInfoMailForStage1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has no value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * When the method is called * Then one is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check250.xml'); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfDueForReminderMailForStage1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage1-property is set to a value older than 600 seconds from now * When the method is called * Then one is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check250.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(250); $approval->setSentInfoTstampStage1(time() - 601); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfNotDueForReminderMailForStage1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has no value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage1-property is set to a value not older than 600 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check250.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(250); $approval->setSentInfoTstampStage1(time() - 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $persistenceManager->clearState(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfNotDueForAutomaticConfirmationForStage1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has a value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage1-property is set to a value not older than 1200 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check250.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(250); $approval->setSentInfoTstampStage1(time()); $approval->setSentReminderTstampStage1($approval->getSentInfoTstampStage1() + 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfDueForAutomaticConfirmationForStage1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has a value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage1-property is set to a value older than 1200 seconds from now * When the method is called * Then one is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check250.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(250); $approval->setSentInfoTstampStage1(time() - 1201); $approval->setSentReminderTstampStage1($approval->getSentInfoTstampStage1() + 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfDueForAutomaticConfirmationButNoToleranceSetForStage1() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object has no value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage1-property set * Given the approval-object has a value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given the tolerance-parameter for the stage1 has been set to 0 seconds * Given the tolerance-parameter for the stage2 has been set to 1200 seconds * Given the sentInfoTstampStage1-property is set to a value older than 1200 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check250.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(250); $approval->setSentInfoTstampStage1(time() - 1201); $approval->setSentReminderTstampStage1($approval->getSentInfoTstampStage1() + 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 0, 1200); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfDueForInfoMailForStage2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object a value for the allowedTstampStage1-property set * Given the approval-object no value for the allowedTstampStage2-property set * Given the approval-object as no value for the sentInfoTstampStage2-property set * Given the approval-object as no value for the sentReminderTstampStage2-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * When the method is called * Then one is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); $result = $this->subject->processAllConfirmations(1200,1200, 600, 600); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfDueForReminderMailForStage2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object a value for the allowedTstampStage1-property set * Given the approval-object no value for the allowedTstampStage2-property set * Given the approval-object a value for the sentInfoTstampStage2-property set * Given the approval-object as no value for the sentReminderTstampStage2-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage2-property is set to a value older than 600 seconds from now * When the method is called * Then one is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(260); $approval->setSentInfoTstampStage2(time() - 601); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfNotDueForReminderMailForStage2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object a value for the allowedTstampStage1-property set * Given the approval-object no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has no value for the sentReminderTstampStage2-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage1-property is set to a value not older than 600 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(260); $approval->setSentInfoTstampStage2(time() - 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $persistenceManager->clearState(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfNotDueForAutomaticConfirmationForStage2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object has a value for the allowedTstampStage1-property set * Given the approval-object has no value for the allowedTstampStage2-property set * Given the approval-object has a value for the sentInfoTstampStage2-property set * Given the approval-object has a value for the sentReminderTstampStage2-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage2-property is set to a value not older than 1200 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(260); $approval->setSentInfoTstampStage2(time() - 5); $approval->setSentReminderTstampStage2($approval->getSentInfoTstampStage2() + 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(0, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsOneIfDueForAutomaticConfirmationForStage2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object a value for the allowedTstampStage1-property set * Given the approval-object no value for the allowedTstampStage2-property set * Given the approval-object a value for the sentInfoTstampStage2-property set * Given the approval-object a value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given both tolerance-parameters for the stage have been set to 1200 seconds * Given the sentInfoTstampStage2-property is set to a value older than 1200 seconds from now * When the method is called * Then one is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(260); $approval->setSentInfoTstampStage2(time() - 1201); $approval->setSentReminderTstampStage2($approval->getSentInfoTstampStage2() + 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 1200); self::assertEquals(1, $result); } /** * @test * @throws \Exception */ public function processAllConfirmationsReturnsZeroIfDueForAutomaticConfirmationButNoToleranceSetForStage2() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the status "approval" * Given a persisted approval-object * Given the approval-object a value for the allowedTstampStage1-property set * Given the approval-object no value for the allowedTstampStage2-property set * Given the approval-object a value for the sentInfoTstampStage2-property set * Given the approval-object a value for the sentReminderTstampStage1-property set * Given a persisted page-object * Given the page-object refers the issue-object * Given the page-object refers the topic-object * Given the page-object belongs to the approval-object * Given both tolerance-parameters for the level have been set to 600 seconds * Given the tolerance-parameter for the stage1 has been set to 1200 seconds * Given the tolerance-parameter for the stage2 has been set to 0 seconds * Given the sentInfoTstampStage2-property is set to a value older than 1200 seconds from now * When the method is called * Then zero is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = $this->approvalRepository->findByUid(260); $approval->setSentInfoTstampStage2(time() - 1201); $approval->setSentReminderTstampStage2($approval->getSentInfoTstampStage2() + 5); $this->approvalRepository->update($approval); $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->persistAll(); $result = $this->subject->processAllConfirmations(600, 600, 1200, 0); self::assertEquals(0, $result); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Command; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Manager\ApprovalManager; use RKW\RkwNewsletter\Manager\IssueManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * class ProcessConfirmationsCommand * * Execute on CLI with: 'vendor/bin/typo3 rkw_newsletter:processConfirmations' * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ProcessConfirmationsCommand extends Command { /** * @var \RKW\RkwNewsletter\Manager\ApprovalManager|null */ protected ?ApprovalManager $approvalManager = null; /** * @var \RKW\RkwNewsletter\Manager\IssueManager|null */ protected ?IssueManager $issueManager = null; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * Configure the command by defining the name, options and arguments */ protected function configure(): void { $this->setDescription('Processes confirmations of approvals and issues.'); } /** * Initializes the command after the input has been bound and before the input * is validated. * * This is mainly useful when a lot of commands extends one main command * where some things need to be initialized based on the input arguments and options. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @see \Symfony\Component\Console\Input\InputInterface::bind() * @see \Symfony\Component\Console\Input\InputInterface::validate() */ protected function initialize(InputInterface $input, OutputInterface $output): void { /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->approvalManager = $objectManager->get(ApprovalManager::class); $this->issueManager = $objectManager->get(IssueManager::class); } /** * Executes the command for showing sys_log entries * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return int * @see \Symfony\Component\Console\Input\InputInterface::bind() * @see \Symfony\Component\Console\Input\InputInterface::validate() */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title($this->getDescription()); $result = 0; try { $settings = $this->getSettings(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK); $this->approvalManager->processAllConfirmations( intval($settings['settings']['reminderApprovalStage1']), intval($settings['settings']['reminderApprovalStage2']), intval($settings['settings']['automaticApprovalStage1']), intval($settings['settings']['automaticApprovalStage2']) ); $count = $this->issueManager->processAllConfirmations(intval($settings['settings']['reminderApprovalStage3'])); $io->note('Processed ' . $count . ' confirmation(s).'); } catch (\Exception $e) { $message = sprintf('An unexpected error occurred while trying to update the statistics of e-mails: %s', str_replace(array("\n", "\r"), '', $e->getMessage()) ); $io->error($message); $this->getLogger()->log(LogLevel::ERROR, $message); $result = 1; } $io->writeln('Done'); return $result; } /** * Returns TYPO3 settings * * @param string $which Which type of settings will be loaded * @return array * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ protected function getSettings(string $which = ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS): array { return \Madj2k\CoreExtended\Utility\GeneralUtility::getTypoScriptConfiguration('Rkwnewsletter', $which); } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger(): Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } } <file_sep><?php namespace RKW\RkwNewsletter\Status; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Approval; use RKW\RkwNewsletter\Domain\Model\BackendUser; /** * ApprovalStatus * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ApprovalStatus { /** * @var int */ const STAGE1 = 1; /** * @var int */ const STAGE2 = 2; /** * @var int */ const STAGE_DONE = 3; /** * @var int */ const LEVEL1 = 1; /** * @var int */ const LEVEL2 = 2; /** * @var int */ const LEVEL_DONE = 3; /** * Returns current stage of the approval based on timestamps * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return int */ public static function getStage (Approval $approval): int { if ($approval->getAllowedTstampStage2()) { return self::STAGE_DONE; } else if ($approval->getAllowedTstampStage1()) { return self::STAGE2; } return self::STAGE1; } /** * Returns current mail-status of the approval based on timestamps * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return string */ public static function getLevel (Approval $approval): string { if (self::getStage($approval) == self::STAGE1) { if ( ($approval->getSentInfoTstampStage1() < 1) && ($approval->getSentReminderTstampStage1() < 1) ) { return self::LEVEL1; } if ($approval->getSentReminderTstampStage1() < 1) { return self::LEVEL2; } } if (self::getStage($approval) == self::STAGE2) { if ( ($approval->getSentInfoTstampStage2() < 1) && ($approval->getSentReminderTstampStage2() < 1) ) { return self::LEVEL1; } if ($approval->getSentReminderTstampStage2() < 1) { return self::LEVEL2; } } return self::LEVEL_DONE; } /** * Increases the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @param \RKW\RkwNewsletter\Domain\Model\BackendUser|null $backendUser * @return bool */ public static function increaseStage (Approval $approval, BackendUser $backendUser = null): bool { $stage = self::getStage($approval); $update = false; if ($stage == self::STAGE1) { if ($backendUser) { $approval->setAllowedByUserStage1($backendUser); } $approval->setAllowedTstampStage1(time()); $update = true; } if ($stage == self::STAGE2) { if ($backendUser) { $approval->setAllowedByUserStage2($backendUser); } $approval->setAllowedTstampStage2(time()); $update = true; } return $update; } /** * Increases the level of the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Approval Approval $approval * @return bool */ public static function increaseLevel (Approval $approval): bool { $stage = self::getStage($approval); $level = self::getLevel($approval); $update = false; if ($stage == self::STAGE1) { if ($level == self::LEVEL1) { $approval->setSentInfoTstampStage1(time()); $update = true; } else { if ($level == self::LEVEL2) { $approval->setSentReminderTstampStage1(time()); $update = true; } } } if ($stage == self::STAGE2) { if ($level == self::LEVEL1) { $approval->setSentInfoTstampStage2(time()); $update = true; } else { if ($level == self::LEVEL2) { $approval->setSentReminderTstampStage2(time()); $update = true; } } } return $update; } } <file_sep><?php defined('TYPO3_MODE') || die('Access denied.'); call_user_func( function($extKey) { //================================================================= // Configure Plugins //================================================================= \TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin( 'RKW.' . $extKey, 'Subscription', array( 'Subscription' => 'new, create, edit, update, message, optIn, createSubscription, finalSaveSubscription, unsubscribe', ), // non-cacheable actions array( 'Subscription' => 'new, create, edit, update, message, optIn, createSubscription, finalSaveSubscription, unsubscribe', ) ); \TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin( 'RKW.' . $extKey, 'Webview', array( 'WebView' => 'show', ), // non-cacheable actions array( 'WebView' => 'show', ) ); //================================================================= // Register TCA evaluation to be available in 'eval' of TCA //================================================================= $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals']['RKW\\RkwNewsletter\\Validation\\TCA\\NewsletterTeaserLengthEvaluation'] = ''; //================================================================= // Register Hooks //================================================================= $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][$extKey] = 'RKW\\RkwNewsletter\\Hooks\\ResetNewsletterConfigOnPageCopyHook'; //================================================================= // Register SignalSlots //================================================================= /** * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher $signalSlotDispatcher */ $signalSlotDispatcher = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class); $signalSlotDispatcher->connect( Madj2k\FeRegister\Registration\AbstractRegistration::class, \Madj2k\FeRegister\Registration\AbstractRegistration::SIGNAL_AFTER_CREATING_OPTIN . 'RkwNewsletter', \RKW\RkwNewsletter\Service\RkwMailService::class, 'sendOptInRequest' ); $signalSlotDispatcher->connect( Madj2k\FeRegister\Registration\AbstractRegistration::class, \Madj2k\FeRegister\Registration\AbstractRegistration::SIGNAL_AFTER_REGISTRATION_COMPLETED . 'RkwNewsletter', \RKW\RkwNewsletter\Controller\SubscriptionController::class, 'saveSubscription' ); // Slots for backend module release approval, test send and final send $signalSlotDispatcher->connect( \RKW\RkwNewsletter\Manager\ApprovalManager::class, \RKW\RkwNewsletter\Manager\ApprovalManager::SIGNAL_FOR_SENDING_MAIL_APPROVAL, \RKW\RkwNewsletter\Service\RkwMailService::class, 'sendMailAdminApproval' ); $signalSlotDispatcher->connect( \RKW\RkwNewsletter\Manager\ApprovalManager::class, \RKW\RkwNewsletter\Manager\ApprovalManager::SIGNAL_FOR_SENDING_MAIL_APPROVAL_AUTOMATIC, \RKW\RkwNewsletter\Service\RkwMailService::class, 'sendMailAdminApprovalAutomatic' ); $signalSlotDispatcher->connect( \RKW\RkwNewsletter\Manager\IssueManager::class, \RKW\RkwNewsletter\Manager\IssueManager::SIGNAL_FOR_SENDING_MAIL_RELEASE, \RKW\RkwNewsletter\Service\RkwMailService::class, 'sendMailAdminRelease' ); //================================================================= // Register Logger //================================================================= $GLOBALS['TYPO3_CONF_VARS']['LOG']['RKW']['RkwNewsletter']['writerConfiguration'] = array( // configuration for WARNING severity, including all // levels with higher severity (ERROR, CRITICAL, EMERGENCY) \TYPO3\CMS\Core\Log\LogLevel::WARNING => array( // add a FileWriter 'TYPO3\\CMS\\Core\\Log\\Writer\\FileWriter' => array( // configuration for the writer 'logFile' => \TYPO3\CMS\Core\Core\Environment::getVarPath() . '/log/tx_rkwnewsletter.log' ) ), ); }, $_EXTKEY ); <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Permissions; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use RKW\RkwNewsletter\Domain\Repository\PagesRepository; use RKW\RkwNewsletter\Permissions\PagePermissions; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; /** * PagePermissionsTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class PagePermissionsTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/PagePermissionsTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Permissions\PagePermissions|null */ private ?PagePermissions $subject = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\PagesRepository|null */ private ?PagesRepository $pagesRepository; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(static::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', static::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $this->objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->pagesRepository = $this->objectManager->get(PagesRepository::class); $this->subject = $this->objectManager->get(PagePermissions::class); } //============================================= /** * @test * @throws \Exception */ public function setPermissionsReturnsFalseOnMissingStageConfiguration() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given no valid configuration for the stage "release" but for another stage defined via parameter * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(10); $settings = [ 'stage2' => [ 'userId' => 1, 'groupId' => 1, 'user' => 1, 'group' => 1, 'everybody' => 1, ] ]; self::assertFalse($this->subject->setPermissions($page, $settings)); } /** * @test * @throws \Exception */ public function setPermissionsReturnsFalseOnWrongConfigurationValues() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a valid configuration for the stage "release" defined via parameter * Given this configuration does not contain settings for userId and groupId * Given all configuration-values for page-permissions are beyond the allowed range * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(10); $settings = [ 'release' => [ 'user' => 32, 'group' => 32, 'everybody' => 32, ] ]; self::assertFalse($this->subject->setPermissions($page, $settings)); } /** * @test * @throws \Exception */ public function setPermissionsReturnsTrue() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a valid configuration for the stage "release" defined via parameter * Given this configuration does not contain settings for userId and groupId * Given all configuration-values for page-permissions are in the allowed range * When the method is called * Then true is returned * Then the page-permissions are persisted as configured */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(10); $settings = [ 'release' => [ 'user' => 31, 'group' => 16, 'everybody' => 1, ] ]; self::assertTrue($this->subject->setPermissions($page, $settings)); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $page = $this->pagesRepository->findByUid(10); self::assertEquals(31, $page->getPermsUser()); self::assertEquals(16, $page->getPermsGroup()); self::assertEquals(1, $page->getPermsEverybody()); } /** * @test * @throws \Exception */ public function setPermissionsReturnsTrueWithoutCheckingUserIdGroupId() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a valid configuration for the stage "release" defined via parameter * Given this configuration contain a settings for userId and groupId * Given this settings have values higher than the allowed range for page-rights * When the method is called * Then true is returned * Then the user-id and group-id-property are persisted as configured */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(10); $settings = [ 'release' => [ 'userId' => 35, 'groupId' => 38 ] ]; self::assertTrue($this->subject->setPermissions($page, $settings)); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $page = $this->pagesRepository->findByUid(10); self::assertEquals(35, $page->getPermsUserId()); self::assertEquals(38, $page->getPermsGroupId()); } /** * @test * @throws \Exception */ public function setPermissionsReturnsTrueUsingTyposcriptConfiguration() { /** * Scenario: * * Given a persisted issue-object * Given the issue-object has the stage "release" * Given a persisted topic-object * Given a persisted page-object * Given that page-object belongs to the issue-object * Given that page-object belongs to the topic-object * Given a valid configuration defined via typoscript * Given this configuration contain a settings for userId and groupId * Given this settings have values higher than the allowed range for page-rights * When the method is called * Then true is returned * Then the page-permissions are persisted as configured */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Pages $page */ $page = $this->pagesRepository->findByUid(10); self::assertTrue($this->subject->setPermissions($page)); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $page = $this->pagesRepository->findByUid(10); self::assertEquals(3, $page->getPermsUserId()); self::assertEquals(3, $page->getPermsGroupId()); self::assertEquals(4, $page->getPermsUser()); self::assertEquals(4, $page->getPermsGroup()); self::assertEquals(4, $page->getPermsEverybody()); } //============================================= /** * @test * @throws \Exception */ public function validatePermissionReturnsFalseOnValueBelowZero() { /** * Scenario: * * Given a value below zero * When the method is called * Then false is returned */ self::assertFalse($this->subject->validatePermission(-1)); } /** * @test * @throws \Exception */ public function validatePermissionReturnsFalseOnValueAboveThirtyOne() { /** * Scenario: * * Given a value above 31 * When the method is called * Then false is returned */ self::assertFalse($this->subject->validatePermission(32)); } /** * @test * @throws \Exception */ public function validatePermissionReturnsTrueOnValueInValidRange() { /** * Scenario: * * Given a value in valid range * When the method is called * Then true is returned */ self::assertTrue($this->subject->validatePermission(17)); } //============================================= /** * @test * @throws \Exception */ public function getPermissionSettingsReturnsConfiguration() { /** * Scenario: * * Given valid configuration * When the method is called * Then a configuration-array is returned */ $expected = [ 'stage1' => [ 'userId' => '1', 'groupId' => '1', 'user' => '1', 'group' => '1', 'everybody' => '1', ], 'stage2' => [ 'userId' => '2', 'groupId' => '2', 'user' => '2', 'group' => '2', 'everybody' => '2', ], 'release' => [ 'userId' => '3', 'groupId' => '3', 'user' => '4', 'group' => '4', 'everybody' => '4', ], 'sent' => [ 'userId' => '4', 'groupId' => '4', 'user' => '8', 'group' => '8', 'everybody' => '8', ] ]; self::assertEquals($expected, $this->subject->getPermissionSettings()); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Status; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Approval; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Pages; use RKW\RkwNewsletter\Domain\Model\Topic; use RKW\RkwNewsletter\Exception; /** * PageStatus * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class PageStatus { /** * @var string */ const DRAFT = 'draft'; /** * @var string */ const APPROVAL_1 = 'stage1'; /** * @var string */ const APPROVAL_2 = 'stage2'; /** * @var string */ const RELEASE = 'release'; /** * @var string */ const SENDING = 'sent'; // no mistake! /** * @var int */ const DONE = 'sent'; /** * Returns current stage of the page based on the status of the issue and its approvals * * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @return string * @throws \RKW\RkwNewsletter\Exception */ public static function getStage (Pages $page): string { $issueStage = IssueStatus::getStage($page->getTxRkwnewsletterIssue()); if ($issueStage == IssueStatus::STAGE_APPROVAL) { /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = self::getApproval($page->getTxRkwnewsletterIssue(), $page->getTxRkwnewsletterTopic()); $approvalStage = ApprovalStatus::getStage($approval); if ($approvalStage == ApprovalStatus::STAGE2) { return self::APPROVAL_2; } if ($approvalStage == ApprovalStatus::STAGE_DONE) { return self::RELEASE; } return self::APPROVAL_1; } if ($issueStage == IssueStatus::STAGE_RELEASE) { return self::RELEASE; } if ($issueStage == IssueStatus::STAGE_SENDING) { return self::SENDING; } if ($issueStage == IssueStatus::STAGE_DONE) { return self::DONE; } return self::DRAFT; } /** * Returns approval-object by given issue and topic * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @return \RKW\RkwNewsletter\Domain\Model\Approval * @throws \RKW\RkwNewsletter\Exception */ public static function getApproval (Issue $issue, Topic $topic): Approval { /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ foreach ($issue->getApprovals() as $approval) { if ( ($approval->getTopic()) && ($approval->getTopic()->getUid() == $topic->getUid()) ) { return $approval; } } throw new Exception( 'No approval found for given issue and topic', 1644845316 ); } } <file_sep><?php namespace RKW\RkwNewsletter\Mailing; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Madj2k\CoreExtended\Utility\FrontendSimulatorUtility; use Madj2k\Postmaster\Validation\QueueMailValidator; use Madj2k\Postmaster\Mail\MailMessage; use RKW\RkwNewsletter\Domain\Model\FrontendUser; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\NewsletterRepository; use RKW\RkwNewsletter\Exception; use RKW\RkwNewsletter\Status\IssueStatus; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use Madj2k\CoreExtended\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * MailProcessor * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class MailProcessor { /** * @var \RKW\RkwNewsletter\Domain\Model\Issue|null */ protected ?Issue $issue = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected FrontendUserRepository $frontendUserRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\NewsletterRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected NewsletterRepository $newsletterRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected IssueRepository $issueRepository; /** * @var \RKW\RkwNewsletter\Mailing\ContentLoader * @TYPO3\CMS\Extbase\Annotation\Inject */ protected ContentLoader $contentLoader; /** * @var \Madj2k\Postmaster\Mail\MailMessage * @TYPO3\CMS\Extbase\Annotation\Inject */ protected MailMessage $mailMessage; /** * @var \Madj2k\Postmaster\Validation\QueueMailValidator * @TYPO3\CMS\Extbase\Annotation\Inject */ protected QueueMailValidator $queueMailValidator; /** * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PersistenceManager $persistenceManager; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * @var array */ protected array $settings = []; /** * Gets the mailMessage * * @return \Madj2k\Postmaster\Mail\MailMessage */ public function getMailMessage(): MailMessage { return $this->mailMessage; } /** * Gets the contentLoader * * @return \RKW\RkwNewsletter\Mailing\ContentLoader */ public function getContentLoader(): ContentLoader { return $this->contentLoader; } /** * Gets the issue * * @return \RKW\RkwNewsletter\Domain\Model\Issue|null */ public function getIssue():? Issue { return $this->issue; } /** * Sets the issue and inits mailMessage * * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue $issue * @return void * @throws Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function setIssue(Issue $issue): void { self::debugTime(__LINE__, __METHOD__); if ($issue->_isNew()) { throw new Exception('Issue-object has to be persisted.', 1650541236); } if (! $issue->getNewsletter()) { throw new Exception('No newsletter-object for this issue set.', 1650541234); } $this->issue = $issue; $this->contentLoader->setIssue($issue); $this->init(); self::debugTime(__LINE__, __METHOD__); } /** * Gets the recipients and adds them to issue * * @return bool * @throws Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function setRecipients(): bool { self::debugTime(__LINE__, __METHOD__); if (! $this->issue) { throw new Exception('No issue is set.', 1650541235); } // Check if not yet started! if (! $this->issue->getStartTstamp()) { // reset $this->issue->setRecipients([]); /** @var \TYPO3\CMS\Extbase\Persistence\QueryResultInterface $recipients */ $subscribers = $this->frontendUserRepository->findSubscriptionsByNewsletter($this->issue->getNewsletter()); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ foreach ($subscribers as $frontendUser) { $this->issue->addRecipient($frontendUser); } $this->issueRepository->update($this->issue); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf('Added recipients to issue with id=%s.', $this->issue->getUid() ) ); self::debugTime(__LINE__, __METHOD__); return true; } $this->getLogger()->log( LogLevel::DEBUG, sprintf('No recipients added to issue with id=%s.', $this->issue->getUid() ) ); self::debugTime(__LINE__, __METHOD__); return false; } /** * Gets the subscription has for a frontendUser * * @param \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser * @return string * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function getSubscriptionHash(FrontendUser $frontendUser): string { self::debugTime(__LINE__, __METHOD__); // generate hash-value if none exists if (! $frontendUser->getTxRkwnewsletterHash()) { $hash = sha1($frontendUser->getUid() . $frontendUser->getEmail() . rand()); $frontendUser->setTxRkwnewsletterHash($hash); $this->frontendUserRepository->update($frontendUser); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::DEBUG, sprintf('Generated subscription-hash for frontendUser with uid=%s.', $frontendUser->getUid() ) ); } self::debugTime(__LINE__, __METHOD__); return $frontendUser->getTxRkwnewsletterHash(); } /** * Sets the subscribed topics and shuffles them * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Topic>|null $topics * @return void * @throws Exception */ public function setTopics(ObjectStorage $topics = null): void { self::debugTime(__LINE__, __METHOD__); if (! $this->issue) { throw new Exception('No issue is set.', 1650549470); } // if no topic-parameter given, we take the existing and shuffle them! if (!$topics) { $topics = $this->contentLoader->getTopics(); } // shuffle order and set it as reference for contentLoader $topicsArray = $topics->toArray(); shuffle($topicsArray); $topicsShuffled = new ObjectStorage(); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topics */ foreach ($topicsArray as $topic) { $topicsShuffled->attach($topic); } $this->contentLoader->setTopics($topicsShuffled); $this->getLogger()->log( LogLevel::DEBUG, sprintf('Set shuffled topics for issue with id=%s.', $this->issue->getUid() ) ); self::debugTime(__LINE__, __METHOD__); } /** * Gets the current subject for the mail * * @return string * @throws Exception */ public function getSubject(): string { self::debugTime(__LINE__, __METHOD__); if (! $this->issue) { throw new Exception('No issue is set.', 1650549470); } $firstHeadline = $this->contentLoader->getFirstHeadline(); self::debugTime(__LINE__, __METHOD__); return ($firstHeadline ? ($this->issue->getTitle() . ' – ' . $firstHeadline) : $this->issue->getTitle()); } /** * Sends an email to the given frontendUser with his subscriptions * * @param \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser * @return bool * @throws Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function sendMail(FrontendUser $frontendUser): bool { self::debugTime(__LINE__, __METHOD__); if (! $this->issue) { throw new Exception('No issue is set.', 1650608449); } // load settings $settings = $this->getSettings(); // set topics according to subscription $this->setTopics($frontendUser->getTxRkwnewsletterSubscription()); // check for contents! if ($this->contentLoader->hasContents()) { // send email via mailMessage $result = $this->mailMessage->setTo( $frontendUser, array( 'marker' => array( 'issue' => $this->issue, 'topics' => $this->contentLoader->getTopics(), 'hash' => $this->getSubscriptionHash($frontendUser), 'settings' => $settings['settings'], ), 'subject' => $this->getSubject(), ), true ); if ($result) { self::debugTime(__LINE__, __METHOD__); $this->getLogger()->log( LogLevel::DEBUG, sprintf('Added frontendUser with id=%s to recipients of issue with id=%s.', $frontendUser->getUid(), $this->issue->getUid() ) ); return true; } } $this->getLogger()->log( LogLevel::INFO, sprintf('Did not add frontendUser with id=%s to recipients of issue with id=%s.', $frontendUser->getUid(), $this->issue->getUid() ) ); return false; } /** * Sends an email to the given email * * @param string $email * @return bool * @throws Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function sendTestMail(string $email): bool { self::debugTime(__LINE__, __METHOD__); if (! $this->issue) { throw new Exception('No issue is set.', 1650629464); } // load settings $settings = $this->getSettings(); // check for contents! if ($this->contentLoader->hasContents()) { // send email via mailMessage $result = $this->mailMessage->setTo( [ 'fistName' => 'Maxima', 'lastName' => 'Musterfrau', 'txFeregisterGender' => 1, 'title' => 'Prof. Dr. Dr.', 'email' => $email, ], array( 'marker' => array( 'issue' => $this->issue, 'topics' => $this->contentLoader->getTopics(), 'settings' => $settings['settings'], ), 'subject' => 'TEST: ' . $this->getSubject(), ), false ); if ($result) { self::debugTime(__LINE__, __METHOD__); $this->getLogger()->log( LogLevel::DEBUG, sprintf('Added email "%s" to test-recipients of issue with id=%s.', $email, $this->issue->getUid() ) ); return true; } } $this->getLogger()->log( LogLevel::INFO, sprintf('Did not add email "%s" to test-recipients of issue with id=%s.', $email, $this->issue->getUid() ) ); return false; } /** * Sends emails to all subscribers * * @param int $limit * @return bool * @throws Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \Exception */ public function sendMails(int $limit = 0): bool { self::debugTime(__LINE__, __METHOD__); if (!$this->issue) { throw new Exception('No issue is set.', 1650636949); } // set startTstamp - no matter what! // persist queueMail on start to be able to start pipelining! if (! $this->issue->getStartTstamp()) { $this->issue->setStartTstamp(time()); $this->issue->setQueueMail($this->mailMessage->getQueueMail()); $this->issueRepository->update($this->issue); $this->persistenceManager->persistAll(); $this->mailMessage->getQueueMail()->setType(1); $this->mailMessage->startPipelining(); $this->getLogger()->log( LogLevel::INFO, sprintf('Started sending of issue with id=%s.', $this->issue->getUid() ) ); } // work through recipients if ($this->issue->getRecipients()) { $cnt = 0; /** @var int $frontendUserUid */ foreach ($this->issue->getRecipients() as $frontendUserUid) { /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ if ($frontendUser = $this->frontendUserRepository->findByUid($frontendUserUid)) { try { $this->sendMail($frontendUser); } catch (\Exception $e) { $this->getLogger()->log( LogLevel::ERROR, sprintf('Could not send issue with id=%s to recipient with id=%s. Reason: %s.', $this->issue->getUid(), $frontendUser->getUid(), $e->getMessage() ) ); } } // remove userId from list - if it exists or not! $this->issue->removeRecipientById($frontendUserUid); $cnt++; if ($cnt >= $limit) { break; } } $this->issueRepository->update($this->issue); $this->persistenceManager->persistAll(); // send mail $this->mailMessage->send(); return true; } // no subscribers left? Then end current sending! // remove pipeline flag $this->mailMessage->stopPipelining(); // set status and timestamp $this->issue->setSentTstamp(time()); $this->issue->setStatus(IssueStatus::STAGE_DONE); // set timestamp to newsletter $this->issue->getNewsletter()->setLastSentTstamp($this->issue->getSentTstamp()); $this->newsletterRepository->update($this->issue->getNewsletter()); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf('Finished sending of issue with id=%s.', $this->issue->getUid() ) ); self::debugTime(__LINE__, __METHOD__); return false; } /** * Sends emails to all given emails * * @param string $emails * @return bool * @throws Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ public function sendTestMails(string $emails): bool { self::debugTime(__LINE__, __METHOD__); if (! $this->issue) { throw new Exception('No issue is set.', 1650636949); } if ( ($recipients = GeneralUtility::trimExplode(',', $emails, true)) && (count($recipients)) ){ foreach($recipients as $recipient) { try { $this->sendTestMail($recipient); } catch (\Exception $e) { $this->getLogger()->log( LogLevel::ERROR, sprintf('Could not send test-mail for issue with id=%s to recipient with email "%s". Reason: %s.', $this->issue->getUid(), $recipient, $e->getMessage() ) ); } } return $this->mailMessage->send(); } $this->getLogger()->log( LogLevel::INFO, sprintf('Finished test-sending of issue with id=%s.', $this->issue->getUid() ) ); self::debugTime(__LINE__, __METHOD__); return false; } /** * inits mailMessage * * @return void * @throws \RKW\RkwNewsletter\Exception * @throws \Madj2k\Postmaster\Exception * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException */ protected function init() { self::debugTime(__LINE__, __METHOD__); if ( ($this->issue) && ($this->issue->getNewsletter()) ) { if ($queueMail = $this->issue->getQueueMail()) { $this->mailMessage->setQueueMail($queueMail); $this->getLogger()->log( LogLevel::DEBUG, sprintf('Initialized mailMessage for issue with id=%s of newsletter-configuration with id=%s with existing queueMail-object with id=%s.', $this->issue->getUid(), $this->issue->getNewsletter()->getUid(), $this->mailMessage->getQueueMail()->getUid() ) ); } else { // set settingsPid and load settings from there $settings = $this->getSettings(); if ($this->issue->getNewsletter()->getSettingsPage()) { $this->mailMessage->getQueueMail()->setSettingsPid($this->issue->getNewsletter()->getSettingsPage()->getUid()); } // set properties for queueMail /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $this->mailMessage->getQueueMail()->setSubject($this->issue->getTitle()); $this->mailMessage->getQueueMail()->setCategory('rkwNewsletter'); // set mail params if ($this->issue->getNewsletter()->getReturnPath()) { $this->mailMessage->getQueueMail()->setReturnPath($this->issue->getNewsletter()->getReturnPath()); } if ($this->issue->getNewsletter()->getReplyMail()) { $this->mailMessage->getQueueMail()->setReplyToAddress($this->issue->getNewsletter()->getReplyMail()); } if ($this->issue->getNewsletter()->getSenderMail()) { $this->mailMessage->getQueueMail()->setFromAddress($this->issue->getNewsletter()->getSenderMail()); } if ($this->issue->getNewsletter()->getSenderName()) { $this->mailMessage->getQueueMail()->setReplyToName($this->issue->getNewsletter()->getSenderName()); $this->mailMessage->getQueueMail()->setFromName($this->issue->getNewsletter()->getSenderName()); } $this->mailMessage->getQueueMail()->setPlaintextTemplate( ($this->issue->getNewsletter()->getTemplate() ?: 'Default') ); $this->mailMessage->getQueueMail()->setHtmlTemplate( ($this->issue->getNewsletter()->getTemplate() ?: 'Default') ); $this->mailMessage->getQueueMail()->addLayoutPaths($settings['view']['newsletter']['layoutRootPaths']); $this->mailMessage->getQueueMail()->addTemplatePaths($settings['view']['newsletter']['templateRootPaths']); $this->mailMessage->getQueueMail()->addPartialPaths($settings['view']['newsletter']['partialRootPaths']); // add paths depending on template - including the default one! $layoutPaths = $settings['view']['newsletter']['layoutRootPaths']; if (is_array($layoutPaths)) { foreach ($layoutPaths as $path) { $path = trim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $this->mailMessage->getQueueMail()->addLayoutPath($path . 'Default'); if ($this->issue->getNewsletter()->getTemplate() != 'Default') { $this->mailMessage->getQueueMail()->addLayoutPath( $path . $this->issue->getNewsletter()->getTemplate() ); } } } $partialPaths = $settings['view']['newsletter']['partialRootPaths']; if (is_array($partialPaths)) { foreach ($partialPaths as $path) { $path = trim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $this->mailMessage->getQueueMail()->addPartialPath($path . 'Default'); if ($this->issue->getNewsletter()->getTemplate() != 'Default') { $this->mailMessage->getQueueMail()->addPartialPath( $path . $this->issue->getNewsletter()->getTemplate() ); } } } /** * @todo Add further template paths based on settingsPid */ // last but not least: check if queueMail has all configuration needed for sending if (! $this->queueMailValidator->validate($this->mailMessage->getQueueMail())) { throw new Exception('Newsletter is missing essential configuration. Sending will not be possible.', 1651215173); } $this->getLogger()->log( LogLevel::DEBUG, sprintf('Initialized mailMessage for issue with id=%s of newsletter-configuration with id=%s with new queueMail-object with id=%s.', $this->issue->getUid(), $this->issue->getNewsletter()->getUid(), $this->mailMessage->getQueueMail()->getUid() ) ); } } self::debugTime(__LINE__, __METHOD__); } /** * Returns TYPO3 settings * * @param string $which Which type of settings will be loaded * @return array * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ protected function getSettings(string $which = ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK): array { $pid = 1; if ($this->issue->getNewsletter()->getSettingsPage()) { $pid = $this->issue->getNewsletter()->getSettingsPage()->getUid(); } if (isset($this->settings[$pid])) { return $this->settings[$pid]; } FrontendSimulatorUtility::simulateFrontendEnvironment($pid); $this->settings[$pid] = GeneralUtility::getTypoScriptConfiguration('Rkwnewsletter', $which); FrontendSimulatorUtility::resetFrontendEnvironment(); return $this->settings[$pid]; } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger(): Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } /** * Does debugging of runtime * * @param int $line * @param string $function * @return void */ private static function debugTime(int $line, string $function): void { if (GeneralUtility::getApplicationContext()->isDevelopment()) { $path = \TYPO3\CMS\Core\Core\Environment::getVarPath() . '/log/tx_rkwnewsletter_runtime.txt'; file_put_contents($path, microtime() . ' ' . $line . ' ' . $function . "\n", FILE_APPEND); } } } <file_sep><?php return [ 'ctrl' => [ 'hideTable' => true, 'title' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval', 'label' => 'name', 'tstamp' => 'tstamp', 'crdate' => 'crdate', 'cruser_id' => 'cruser_id', 'dividers2tabs' => true, 'searchFields' => 'topic, pages, allowed_by_user_stage1, allowed_by_user_stage2, allowed_tstamp_stage1, allowed_tstamp_stage2, sent_info_tstamp_stage1, sent_info_tstamp_stage2, sent_reminder_tstamp_stage1, sent_reminder_tstamp_stage2,', 'iconfile' => 'EXT:rkw_newsletter/Resources/Public/Icons/tx_rkwnewsletter_domain_model_approval.gif' ], 'interface' => [ 'showRecordFieldList' => 'topic, page, allowed_by_user_stage1, allowed_by_user_stage2, allowed_tstamp_stage1, allowed_tstamp_stage2, sent_info_tstamp_stage1, sent_info_tstamp_stage2, sent_reminder_tstamp_stage1, sent_reminder_tstamp_stage2', ], 'types' => [ '1' => ['showitem' => 'topic, page, allowed_by_user_stage1, allowed_by_user_stage2, allowed_tstamp_stage1, allowed_tstamp_stage2, sent_info_tstamp_stage1, sent_info_tstamp_stage2, sent_reminder_tstamp_stage1, sent_reminder_tstamp_stage2'], ], 'palettes' => [ '1' => ['showitem' => ''], ], 'columns' => [ 'topic' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.topic', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'size' => 1, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 1, 'foreign_table' => 'tx_rkwnewsletter_domain_model_topic', 'foreign_table_where' => 'AND tx_rkwnewsletter_domain_model_topic.deleted = 0 AND tx_rkwnewsletter_domain_model_topic.hidden = 0', ], ], 'page' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.page', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'size' => 1, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 1, 'foreign_table' => 'pages', 'foreign_table_where' => 'AND pages.deleted = 0 AND pages.hidden = 0', ], ], 'allowed_by_user_stage1' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.allowed_by_user_stage1', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'size' => 7, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 99, 'foreign_table' => 'be_users', 'foreign_table_where' => 'AND be_users.deleted = 0 AND be_users.disable = 0', ], ], 'allowed_by_user_stage2' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.allowed_by_user_stage2', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'size' => 7, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 99, 'foreign_table' => 'be_users', 'foreign_table_where' => 'AND be_users.deleted = 0 AND be_users.disable = 0', ], ], 'allowed_tstamp_stage1' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.allowed_tstamp_stage1', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, ], ], 'allowed_tstamp_stage2' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.allowed_tstamp_stage2', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, ], ], 'sent_info_tstamp_stage1' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.sent_info_tstamp_stage1', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, ], ], 'sent_info_tstamp_stage2' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.sent_info_tstamp_stage2', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, ], ], 'sent_reminder_tstamp_stage1' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.sent_reminder_tstamp_stage1', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, ], ], 'sent_reminder_tstamp_stage2' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_approval.sent_reminder_tstamp_stage2', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, ], ], 'issue' => [ 'config' => [ 'type' => 'passthrough', 'foreign_table' => 'tx_rkwnewsletter_domain_model_issue', ], ], ], ]; <file_sep><?php namespace RKW\RkwNewsletter\Domain\Repository; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings; use TYPO3\CMS\Extbase\Persistence\QueryResultInterface; /** * IssueRepository * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class IssueRepository extends AbstractRepository { /** * @return void * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function initializeObject(): void { parent::initializeObject(); $this->defaultQuerySettings = $this->objectManager->get(Typo3QuerySettings::class); $this->defaultQuerySettings->setRespectStoragePage(false); } /** * findAllForConfirmationByTolerance * * @param int $toleranceLevel2 * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * comment: implicitly tested */ public function findAllForConfirmationByTolerance(int $toleranceLevel2): QueryResultInterface { $query = $this->createQuery(); $query->matching( $query->logicalAnd( // status is approval or release $query->logicalOr( $query->equals('status', 2), $query->equals('status', 1) ), // nor released nor sent $query->equals('sentTstamp', 0), $query->equals('releaseTstamp', 0), // Check level 1 and level 2 $query->logicalOr( $query->equals('infoTstamp', 0), $query->logicalOr( $query->logicalAnd( $query->greaterThan('infoTstamp', 0), $query->equals('reminderTstamp', 0), $query->lessThan('infoTstamp', time() - $toleranceLevel2) ), $query->logicalAnd( $query->greaterThan('infoTstamp', 0), $query->greaterThan('reminderTstamp', 0), $query->lessThan('reminderTstamp', time() - $toleranceLevel2) ) ) ) ) ); return $query->execute(); } /** * findAllToApproveOnStage1 * * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * comment: only used in backend module */ public function findAllToApproveOnStage1(): QueryResultInterface { $query = $this->createQuery(); $query->matching( $query->logicalAnd( $query->equals('status', 1), $query->equals('approvals.allowedTstampStage1', 0) ) ); return $query->execute(); } /** * findAllToApproveOnStage2 * * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * comment: only used in backend module */ public function findAllToApproveOnStage2(): QueryResultInterface { $query = $this->createQuery(); $query->matching( $query->logicalAnd( $query->equals('status', 1), $query->logicalAnd( $query->greaterThan('approvals.allowedTstampStage1', 0), $query->equals('approvals.allowedTstampStage2', 0) ) ) ); return $query->execute(); } /** * findAllForTestSending * * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * comment: only used in backend module */ public function findAllForTestSending(): QueryResultInterface { $query = $this->createQuery(); $query->matching( $query->logicalAnd( $query->in('status', array(1, 2)), $query->equals('releaseTstamp', 0) ) ); return $query->execute(); } /** * findAllToStartSending * * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * comment: only used in backend module */ public function findAllToStartSending(): QueryResultInterface { $query = $this->createQuery(); $query->matching( $query->logicalAnd( $query->equals('status',2), $query->logicalAnd( $query->greaterThan('approvals.allowedTstampStage1', 0), $query->greaterThan('approvals.allowedTstampStage2', 0) ) ) ); return $query->execute(); } /** * findAllToSend * * @param int $limit * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * comment: only used in command controller */ public function findAllToSend(int $limit = 5): QueryResultInterface { $query = $this->createQuery(); $query->matching( $query->logicalAnd( $query->equals('status', 3), $query->greaterThan('releaseTstamp', 0), $query->equals('sentTstamp', 0) ) ); $query->setLimit($limit); return $query->execute(); } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Status; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Status\IssueStatus; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * IssueStatusTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class IssueStatusTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/IssueStatusTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_authors', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Status\IssueStatus|null */ private ?IssueStatus $subject = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_authors/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $this->objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->issueRepository = $this->objectManager->get(IssueRepository::class); $this->subject = $this->objectManager->get(IssueStatus::class); } //============================================= /** * @test * @throws \Exception */ public function getStageReturnsDraft() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 0 * When the method is called * Then $this->subject::STAGE_DRAFT is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); self::assertEquals($this->subject::STAGE_DRAFT, $this->subject::getStage($issue)); } /** * @test * @throws \Exception */ public function getStageReturnsApproval() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 1 * When the method is called * Then $this->subject::STAGE_APPROVAL is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); self::assertEquals($this->subject::STAGE_APPROVAL, $this->subject::getStage($issue)); } /** * @test * @throws \Exception */ public function getStageReturnsRelease() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 2 * When the method is called * Then $this->subject::STAGE_RELEASE is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); self::assertEquals($this->subject::STAGE_RELEASE, $this->subject::getStage($issue)); } /** * @test * @throws \Exception */ public function getStageReturnsSending() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 3 * When the method is called * Then $this->subject::STAGE_SENDING is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(40); self::assertEquals($this->subject::STAGE_SENDING, $this->subject::getStage($issue)); } /** * @test * @throws \Exception */ public function getStageReturnsDone() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 4 * When the method is called * Then $this->subject::STAGE_DONE is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(50); self::assertEquals($this->subject::STAGE_DONE, $this->subject::getStage($issue)); } //============================================= /** * @test * @throws \Exception */ public function getLevelReturnsNoneOnWrongStage() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "draft" * When the method is called * Then $this->subject::LEVEL_NONE is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(60); self::assertEquals($this->subject::LEVEL_NONE, $this->subject::getLevel($issue)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevel1() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "release" * Given that issue-object has no value for the infoTimestamp-property set * Given that issue-object has no value for the reminderTimestamp-property set * When the method is called * Then $this->subject::LEVEL1 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(70); self::assertEquals($this->subject::LEVEL1, $this->subject::getLevel($issue)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevel2() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "release" * Given that issue-object has a value for the infoTimestamp-property set * Given that issue-object has no value for the reminderTimestamp-property set * When the method is called * Then $this->subject::LEVEL2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(80); self::assertEquals($this->subject::LEVEL2, $this->subject::getLevel($issue)); } /** * @test * @throws \Exception */ public function getLevelReturnsLevelDone() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "release" * Given that issue-object has a value for the infoTimestamp-property set * Given that issue-object has a value for the reminderTimestamp-property set * When the method is called * Then $this->subject::LEVEL2 is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); self::assertEquals($this->subject::LEVEL_DONE, $this->subject::getLevel($issue)); } //============================================= /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForDraft() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 0 * When the method is called * Then true is returned * Then the status of the issue-object is set to $this->subject::STAGE_APPROVAL * Then the releaseTstamp-property is not set * Then the sentTstamp-property is not set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $result = $this->subject->increaseStage($issue); self::assertTrue($result); self::assertEquals($this->subject::STAGE_APPROVAL, $issue->getStatus()); self::assertEquals(0, $issue->getReleaseTstamp()); self::assertEquals(0, $issue->getSentTstamp()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForApproval() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 1 * When the method is called * Then true is returned * Then the status of the issue-object is set to $this->subject::STAGE_RELEASE * Then the releaseTstamp-property is not set * Then the sentTstamp-property is not set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); $result = $this->subject->increaseStage($issue); self::assertTrue($result); self::assertEquals($this->subject::STAGE_RELEASE, $issue->getStatus()); self::assertEquals(0, $issue->getReleaseTstamp()); self::assertEquals(0, $issue->getSentTstamp()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForRelease() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 2 * When the method is called * Then true is returned * Then the status of the issue-object is set to $this->subject::STAGE_SENDING * Then the releaseTstamp-property is set to the current time * Then the sentTstamp-property is not set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); $result = $this->subject->increaseStage($issue); self::assertTrue($result); self::assertEquals($this->subject::STAGE_SENDING, $issue->getStatus()); self::assertGreaterThan(0, $issue->getReleaseTstamp()); self::assertEquals(0, $issue->getSentTstamp()); } /** * @test * @throws \Exception */ public function increaseStageReturnsTrueForSending() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 3 * When the method is called * Then true is returned * Then the status of the issue-object is set to $this->subject::STAGE_DONE * Then the releaseTstamp-property is not set * Then the sentTstamp-property is set to the current time */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(40); $result = $this->subject->increaseStage($issue); self::assertTrue($result); self::assertEquals($this->subject::STAGE_DONE, $issue->getStatus()); self::assertEquals(0, $issue->getReleaseTstamp()); self::assertGreaterThan(0, $issue->getSentTstamp()); } /** * @test * @throws \Exception */ public function increaseStageReturnsFalseForDone() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the status-property set to 4 * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(50); $result = $this->subject->increaseStage($issue); self::assertFalse($result); } //============================================= /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseOnWrongStage() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "draft" * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(60); self::assertFalse($this->subject::increaseLevel($issue)); } /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueForLevel0() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "release" * Given that issue-object has no value for the infoTimestamp-property set * Given that issue-object has no value for the reminderTimestamp-property set * When the method is called * Then true is returned * Then the infoTstamp-property is set * Then the reminderTstamp-property is not set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(70); self::assertTrue($this->subject::increaseLevel($issue)); self::assertGreaterThan(0, $issue->getInfoTstamp()); self::assertEquals(0, $issue->getReminderTstamp()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsTrueForLevel1() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "release" * Given that issue-object has a value for the infoTimestamp-property set * Given that issue-object has no value for the reminderTimestamp-property set * When the method is called * Then true is returned * Then the infoTstamp-property is set * Then the reminderTstamp-property is set */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(80); self::assertTrue($this->subject::increaseLevel($issue)); self::assertGreaterThan(0, $issue->getInfoTstamp()); self::assertGreaterThan(0, $issue->getReminderTstamp()); } /** * @test * @throws \Exception */ public function increaseLevelReturnsFalseForLevel2() { /** * Scenario: * * Given a persisted issue-object * Given that issue-object has the stage "release" * Given that issue-object has a value for the infoTimestamp-property set * Given that issue-object has a value for the reminderTimestamp-property set * When the method is called * Then false is returned */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); self::assertFalse($this->subject::increaseLevel($issue)); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Model; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * FrontendUser * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class FrontendUser extends \Madj2k\FeRegister\Domain\Model\FrontendUser { /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Topic>|null */ protected ?ObjectStorage $txRkwnewsletterSubscription = null; /** * @var string */ protected string $txRkwnewsletterHash = ''; /** * @var bool */ protected bool $txRkwnewsletterPriority = false; /** * __construct */ public function __construct() { parent::__construct(); //Do not remove the next line: It would break the functionality $this->initStorageObjects(); } /** * Initializes all ObjectStorage properties * Do not modify this method! * It will be rewritten on each save in the extension builder * You may modify the constructor of this class instead * * @return void */ protected function initStorageObjects(): void { $this->txRkwnewsletterSubscription = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); } /** * Sets the Subscriptions. Keep in mind that the property is called "Subscription" * although it can hold several topics. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $subscription * @return void * @api */ public function setTxRkwnewsletterSubscription(ObjectStorage $subscription): void { $this->txRkwnewsletterSubscription = $subscription; } /** * Adds a $subscription to the frontend user * * @param \RKW\RkwNewsletter\Domain\Model\Topic $subscription * @return void * @api */ public function addTxRkwnewsletterSubscription(Topic $subscription): void { $this->txRkwnewsletterSubscription->attach($subscription); } /** * Removes a Subscription from the frontend user * * @param \RKW\RkwNewsletter\Domain\Model\Topic $subscription * @return void * @api */ public function removeTxRkwnewsletterSubscription(Topic $subscription): void { $this->txRkwnewsletterSubscription->detach($subscription); } /** * Returns the topics. Keep in mind that the property is called "$newsletter" * although it can hold several $newsletter. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage An object storage containing the $newsletter * @api */ public function getTxRkwnewsletterSubscription(): ObjectStorage { return $this->txRkwnewsletterSubscription; } /** * set the TxRkwnewsletterHash * * @param string $hash * @return void */ public function setTxRkwnewsletterHash(string $hash): void { $this->txRkwnewsletterHash = $hash; } /** * get the TxRkwnewsletterHash * * @return string */ public function getTxRkwnewsletterHash(): string { return $this->txRkwnewsletterHash; } /** * set the TxRkwnewsletterPriority * * @param bool $priority * @return void */ public function setTxRkwnewsletterPriority(bool $priority): void { $this->txRkwnewsletterPriority = $priority; } /** * get the TxRkwnewsletterPriority * * @return bool */ public function getTxRkwnewsletterPriority(): bool { return $this->txRkwnewsletterPriority; } } <file_sep><?php namespace RKW\RkwNewsletter\Hooks; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * ResetNewsletterConfigOnPageCopyHook * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ResetNewsletterConfigOnPageCopyHook { /** * Hook to modify newsletter config on page duplication * * @param string $action The action to perform, e.g. 'update'. * @param string $table The table affected by action, e.g. 'fe_users'. * @param string $uid The uid of the record affected by action. * @param array $modifiedFields The modified fields of the record. * @return void */ public function processDatamap_postProcessFieldArray( string $action, string $table, string $uid, array &$modifiedFields ): void { if ( $table === 'pages' && isset($modifiedFields['t3_origuid']) ) { $modifiedFields['tx_rkwnewsletter_include_tstamp'] = 0; } } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Model; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwAuthors\Domain\Model\Authors; use Madj2k\CoreExtended\Domain\Model\FileReference; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * Content * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class Content extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * @var int */ protected int $crdate = 0; /** * @var int */ protected int $sysLanguageUid = -1; /** * @var string */ protected string $header = ''; /** * @var string */ protected string $headerLink = ''; /** * @var string */ protected string $bodytext = ''; /** * @var string */ protected string $contentType = 'textpic'; /** * @var int */ protected int $imageCols = 0; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Madj2k\CoreExtended\Domain\Model\FileReference>|null */ protected ?ObjectStorage $image = null; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwAuthors\Domain\Model\Authors>|null */ protected ?ObjectStorage $txRkwnewsletterAuthors = null; /** * @var bool */ protected bool $txRkwnewsletterIsEditorial = false; /** * __construct */ public function __construct() { //Do not remove the next line: It would break the functionality $this->initStorageObjects(); } /** * Initializes all ObjectStorage properties * Do not modify this method! * It will be rewritten on each save in the extension builder * You may modify the constructor of this class instead * * @return void */ protected function initStorageObjects(): void { $this->image = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); $this->txRkwnewsletterAuthors = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); } /** * Returns the uid * * @return int $uid */ public function getUid(): int { return $this->uid; } /** * Sets the uid * * @param int $uid * @return void */ public function setUid(int $uid): void { $this->uid = $uid; } /** * Returns the crdate * * @return int $crdate */ public function getCrdate(): int { return $this->crdate; } /** * Sets the crdate * * @param int $crdate * @return void */ public function setCrdate(int $crdate): void { $this->crdate = $crdate; } /** * Returns the sysLanguageUid * * @return int $sysLanguageUid */ public function getSysLanguageUid(): int { return $this->sysLanguageUid; } /** * Sets the sysLanguageUid * * @param int $sysLanguageUid * @return void */ public function setSysLanguageUid(int $sysLanguageUid): void { $this->sysLanguageUid = $sysLanguageUid; } /** * Returns the header * * @return string $header */ public function getHeader(): string { return $this->header; } /** * Sets the header * * @param string $header * @return void */ public function setHeader(string $header): void { $this->header = $header; } /** * Returns the headerLink * * @return string $headerLink */ public function getHeaderLink(): string { return $this->headerLink; } /** * Sets the headerLink * * @param string $headerLink * @return void */ public function setHeaderLink(string $headerLink): void { $this->headerLink = $headerLink; } /** * Returns the bodytext * * @return string $bodytext */ public function getBodytext(): string { return $this->bodytext; } /** * Sets the bodytext * * @param string $bodytext * @return void */ public function setBodytext(string $bodytext): void { $this->bodytext = $bodytext; } /** * Returns the contentType * * @return string $contentType */ public function getContentType(): string { return $this->contentType; } /** * Sets the contentType * * @param string $contentType * @return void */ public function setContentType(string $contentType): void { $this->contentType = $contentType; } /** * Returns the imageCols * * @return int $imageCols */ public function getImageCols(): int { return $this->imageCols; } /** * Sets the imageCols * * @param int $imageCols * @return void */ public function setImageCols(int $imageCols): void { $this->imageCols = $imageCols; } /** * Adds an image * * @param \Madj2k\CoreExtended\Domain\Model\FileReference $image * @return void * @api */ public function addImage(FileReference $image): void { $this->image->attach($image); } /** * Removes an image * * @param \Madj2k\CoreExtended\Domain\Model\FileReference $image * @return void * @api */ public function removeImage(FileReference $image): void { $this->image->detach($image); } /** * Returns the images * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Madj2k\CoreExtended\Domain\Model\FileReference> * @api */ public function getImage(): ObjectStorage { return $this->image; } /** * Sets the images * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Madj2k\CoreExtended\Domain\Model\FileReference> $image * @return void * @api */ public function setImage(ObjectStorage $image): void { $this->image = $image; } /** * Adds a txRkwnewsletterAuthors * * @param \RKW\RkwAuthors\Domain\Model\Authors $txRkwnewsletterAuthors * @return void * @api */ public function addTxRkwnewsletterAuthors(Authors $txRkwnewsletterAuthors): void { $this->txRkwnewsletterAuthors->attach($txRkwnewsletterAuthors); } /** * Removes a txRkwnewsletterAuthors * * @param \RKW\RkwAuthors\Domain\Model\Authors $txRkwnewsletterAuthors The Authors to be removed * @return void * @api */ public function removeTxRkwnewsletterAuthors(Authors $txRkwnewsletterAuthors): void { $this->txRkwnewsletterAuthors->detach($txRkwnewsletterAuthors); } /** * Returns the txRkwnewsletterAuthors * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwAuthors\Domain\Model\Authors> $txRkwnewsletterAuthors * @api */ public function getTxRkwnewsletterAuthors(): ObjectStorage { return $this->txRkwnewsletterAuthors; } /** * Sets the txRkwnewsletterAuthors * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwAuthors\Domain\Model\Authors> $txRkwnewsletterAuthors * @return void * @api */ public function setTxRkwnewsletterAuthors(ObjectStorage $txRkwnewsletterAuthors): void { $this->txRkwnewsletterAuthors = $txRkwnewsletterAuthors; } /** * Returns the txRkwnewsletterIsEditorial * * @return bool */ public function getTxRkwnewsletterIsEditorial(): bool { return $this->txRkwnewsletterIsEditorial; } /** * Sets the txRkwnewsletterIsEditorial * * @param bool $txRkwnewsletterIsEditorial * @return void */ public function setTxRkwnewsletterIsEditorial(bool $txRkwnewsletterIsEditorial): void { $this->txRkwnewsletterIsEditorial = $txRkwnewsletterIsEditorial; } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Functional\Controller; use Nimut\TestingFramework\TestCase\FunctionalTestCase; use Madj2k\Postmaster\Mail\MailMassage; use RKW\RkwNewsletter\Controller\SubscriptionController; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * SubscriptionControllerTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class SubscriptionControllerTest extends FunctionalTestCase { /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/fe_register', 'typo3conf/ext/rkw_authors', 'typo3conf/ext/rkw_newsletter', ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'css_styled_content', 'filemetadata', 'seo' ]; /** * @var \RKW\RkwNewsletter\Controller\SubscriptionController|null */ private ?SubscriptionController $subject = null; /** * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager|null */ private ?PersistenceManager $persistenceManager = null; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->persistenceManager = GeneralUtility::makeInstance(PersistenceManager::class); $this->importDataSet(__DIR__ . '/Fixtures/Database/Pages.xml'); $this->importDataSet(__DIR__ . '/Fixtures/Database/TtContent.xml'); $this->importDataSet(__DIR__ . '/Fixtures/Database/FeUsers.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:css_styled_content/static/constants.typoscript', 'EXT:css_styled_content/static/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:fe_register/Configuration/TypoScript/constants.typoscript', 'EXT:fe_register/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Tests/Functional/Controller/Fixtures/Frontend/Basics.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->subject = $objectManager->get(SubscriptionController::class); } /** * @test */ public function newActionRedirectsToEditIfFrontendUserHasSubscription () { // dummy so far! self::assertSame(1,1); } /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\ViewHelpers\Mailing\Content; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use RKW\RkwNewsletter\Domain\Repository\ContentRepository; use TYPO3\CMS\Fluid\View\StandaloneView; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; /** * GetTopicNameViewHelperTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class GetTopicNameViewHelperTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/GetTopicNameViewHelperTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository */ private $issueRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\ContentRepository */ private $contentRepository; /** * @var \TYPO3\CMS\Fluid\View\StandaloneView */ private $standAloneViewHelper; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager */ private $objectManager; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository issueRepository */ $this->issueRepository = $this->objectManager->get(IssueRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\ContentRepository contentRepository */ $this->contentRepository = $this->objectManager->get(ContentRepository::class); /** @var \TYPO3\CMS\Fluid\View\StandaloneView standAloneViewHelper */ $this->standAloneViewHelper = $this->objectManager->get(StandaloneView::class); $this->standAloneViewHelper->setTemplateRootPaths( [ 0 => self::FIXTURE_PATH . '/Frontend/Templates' ] ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsNameOfTopic() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted page-object B * Given that page-object B belongs to the newsletter-object X * Given that page-object B belongs to the issue-object Y * Given that page-object B belongs to the topic-object A * Given a persisted content-object C * Given that content-object C belongs to the page-object B * When the ViewHelper is rendered with content-object C as parameter * Then a string is returned * Then the name of topic-object A is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->contentRepository->findByUid(10); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'content' => $content ] ); $result = trim($this->standAloneViewHelper->render()); self::assertIsString( $result); self::assertEquals('Topic 10', $result); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsEmpty() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted page-object B * Given that page-object B belongs to the newsletter-object X * Given that page-object B belongs to the issue-object Y * Given that page-object B does not belong to the topic-object A * Given a persisted content-object C * Given that content-object C belongs to the page-object B * When the ViewHelper is rendered with content-object C as parameter * Then the topic-object A is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); /** @var \RKW\RkwNewsletter\Domain\Model\Content $content */ $content = $this->contentRepository->findByUid(20); $this->standAloneViewHelper->setTemplate('Check20.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'content' => $content ] ); self::assertEmpty(trim($this->standAloneViewHelper->render())); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Model; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwAuthors\Domain\Model\Authors; use Madj2k\Postmaster\Domain\Model\QueueMail; use RKW\RkwNewsletter\Exception; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * Issue * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class Issue extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * @var string */ protected string $title = ''; /** * @var int */ protected int $status = 0; /** * * @var string */ protected string $introduction = ''; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwAuthors\Domain\Model\Authors>|null */ protected ?ObjectStorage $authors = null; /** * @var \RKW\RkwNewsletter\Domain\Model\Newsletter|null */ protected ?Newsletter $newsletter = null; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Pages>|null */ protected ?ObjectStorage $pages = null; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Approval>|null */ protected ?ObjectStorage $approvals = null; /** * @var \Madj2k\Postmaster\Domain\Model\QueueMail|null */ protected ?QueueMail $queueMail = null; /** * @var int */ protected int $infoTstamp = 0; /** * @var int */ protected int $reminderTstamp = 0; /** * @var int */ protected int $releaseTstamp = 0; /** * @var int */ protected int $startTstamp = 0; /** * @var int */ protected int $sentTstamp = 0; /** * @var string */ protected string $recipients = ''; /** * @var bool */ protected bool $isSpecial = false; /** * __construct */ public function __construct() { //Do not remove the next line: It would break the functionality $this->initStorageObjects(); } /** * Initializes all ObjectStorage properties * Do not modify this method! * It will be rewritten on each save in the extension builder * You may modify the constructor of this class instead * * @return void */ protected function initStorageObjects(): void { $this->pages = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); $this->approvals = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); $this->authors = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); } /** * Returns the title * * @return string $title */ public function getTitle(): string { return $this->title; } /** * Sets the title * * @param string $title * @return void */ public function setTitle(string $title): void { $this->title = $title; } /** * Returns the status * * @return int $status */ public function getStatus(): int { return $this->status; } /** * Sets the status * * @param int $status * @return void */ public function setStatus(int $status): void { $this->status = $status; } /** * Returns the introduction * * @return string $introduction */ public function getIntroduction(): string { return $this->introduction; } /** * Sets the introduction * * @param string $introduction * @return void */ public function setIntroduction(string $introduction): void { $this->introduction = $introduction; } /** * Adds an Authors * * @param \RKW\RkwAuthors\Domain\Model\Authors $authors * @return void */ public function addAuthors(Authors $authors): void { $this->authors->attach($authors); } /** * Removes an Authors * * @param \RKW\RkwAuthors\Domain\Model\Authors $authorsToRemove The Authors to be removed * @return void */ public function removeAuthors(Authors $authorsToRemove): void { $this->authors->detach($authorsToRemove); } /** * Returns the authors * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwAuthors\Domain\Model\Authors> $authors * @api */ public function getAuthors(): ObjectStorage { return $this->authors; } /** * Sets the authors * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwAuthors\Domain\Model\Authors> $authors * @return void * @api */ public function setAuthors(ObjectStorage $authors): void { $this->authors = $authors; } /** * Returns the newsletter * * @return \RKW\RkwNewsletter\Domain\Model\Newsletter|null $newsletter */ public function getNewsletter():? Newsletter { return $this->newsletter; } /** * Sets the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @return void */ public function setNewsletter(Newsletter $newsletter): void { $this->newsletter = $newsletter; } /** * Adds a page to the issue * * @param \RKW\RkwNewsletter\Domain\Model\Pages $pages * @return void * @api */ public function addPages(Pages $pages): void { $this->pages->attach($pages); } /** * Removes a page from the issue * * @param \RKW\RkwNewsletter\Domain\Model\Pages $pages * @return void * @api */ public function removePages(Pages $pages): void { $this->pages->detach($pages); } /** * Returns the pages. Keep in mind that the property is called "pages" * although it can hold several pages. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Pages> * @api */ public function getPages(): ObjectStorage { return $this->pages; } /** * Sets the pages. Keep in mind that the property is called "pages" * although it can hold several pages. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Pages> $pages * @return void * @api */ public function setPages(ObjectStorage $pages):void { $this->pages = $pages; } /** * Adds a approval to the release * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return void * @api */ public function addApprovals(Approval $approval) { $this->approvals->attach($approval); } /** * Removes a approval from the release * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return void * @api */ public function removeApprovals(Approval $approval): void { $this->approvals->detach($approval); } /** * Returns the approval. Keep in mind that the property is called "approvals" * although it can hold several approvals. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Approval> * @api */ public function getApprovals(): ObjectStorage { return $this->approvals; } /** * Sets the approval. Keep in mind that the property is called "approvals" * although it can hold several approvals. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\Approval> $approval * @return void * @api */ public function setApprovals(ObjectStorage $approvals) { $this->approvals = $approvals; } /** * Returns the queueMail * * @return \Madj2k\Postmaster\Domain\Model\QueueMail|null $queueMail */ public function getQueueMail():? QueueMail { return $this->queueMail; } /** * Sets the queueMail * * @param \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail * @return void */ public function setQueueMail(QueueMail $queueMail): void { $this->queueMail = $queueMail; } /** * Returns the infoTstamp * * @return int */ public function getInfoTstamp(): int { return $this->infoTstamp; } /** * Sets the infoTstamp * * @param int $infoTstamp * @return void */ public function setInfoTstamp(int $infoTstamp): void { $this->infoTstamp = $infoTstamp; } /** * Returns the reminderTstamp * * @return int */ public function getReminderTstamp(): int { return $this->reminderTstamp; } /** * Sets the reminderTstamp * * @param int $reminderTstamp * @return void */ public function setReminderTstamp(int $reminderTstamp): void { $this->reminderTstamp = $reminderTstamp; } /** * Returns the releaseTstamp * * @return int */ public function getReleaseTstamp(): int { return $this->releaseTstamp; } /** * Sets the releaseTstamp * * @param int releaseTstamp * @return void */ public function setReleaseTstamp(int $releaseTstamp): void { $this->releaseTstamp = $releaseTstamp; } /** * Returns the startTstamp * * @return int */ public function getStartTstamp(): int { return $this->startTstamp; } /** * Sets the start * * @param int $startTstamp * @return void */ public function setStartTstamp(int $startTstamp): void { $this->startTstamp = $startTstamp; } /** * Returns the sentTstamp * * @return int */ public function getSentTstamp(): int { return $this->sentTstamp; } /** * Sets the sent * * @param int $sentTstamp * @return void */ public function setSentTstamp(int $sentTstamp): void { $this->sentTstamp = $sentTstamp; } /** * Adds a recipient to the release * * @param \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser * @return void * @api */ public function addRecipient(FrontendUser $frontendUser): void { $recipients = $this->getRecipients(); $recipients[] = $frontendUser->getUid(); $this->setRecipients($recipients); } /** * Removes a recipient from the issue * * @param \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser * @return void * @api */ public function removeRecipient(FrontendUser $frontendUser): void { $recipients = $this->getRecipients(); if (false !== $key = array_search($frontendUser->getUid(), $recipients)) { array_splice($recipients, $key, 1); $this->setRecipients($recipients); } } /** * Removes a recipient by id from the issue * * @param int $frontendUserId * @return void * @api */ public function removeRecipientById(int $frontendUserId): void { $recipients = $this->getRecipients(); if (false !== $key = array_search($frontendUserId, $recipients)) { array_splice($recipients, $key, 1); $this->setRecipients($recipients); } } /** * Returns the recipient. Keep in mind that the property is called "recipients" * although it can hold several pages. * * @return array * @api */ public function getRecipients(): array { return GeneralUtility::trimExplode(',', $this->recipients, true); } /** * Sets the recipient. Keep in mind that the property is called "pages" * although it can hold several pages. * * @param array $recipients * @return void * @api */ public function setRecipients(array $recipients = []): void { $this->recipients = implode(',', $recipients); } /** * Returns the isSpecial * * @return bool */ public function getIsSpecial(): bool { return $this->isSpecial; } /** * Sets the isSpecial * * @param bool $isSpecial * @return void */ public function setIsSpecial(bool $isSpecial): void { $this->isSpecial = $isSpecial; } } <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\Mailing; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use Madj2k\Postmaster\Cache\MailCache; use Madj2k\Postmaster\Domain\Model\QueueRecipient; use Madj2k\Postmaster\Domain\Repository\QueueMailRepository; use Madj2k\Postmaster\Domain\Repository\QueueRecipientRepository; use Madj2k\Postmaster\Utility\QueueMailUtility; use RKW\RkwNewsletter\Domain\Model\FrontendUser; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Newsletter; use RKW\RkwNewsletter\Domain\Repository\BackendUserRepository; use RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository; use RKW\RkwNewsletter\Mailing\MailProcessor; use RKW\RkwNewsletter\Status\IssueStatus; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Extbase\Persistence\QueryResultInterface; /** * MailProcessorTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class MailProcessorTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/MailProcessorTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_authors', 'typo3conf/ext/rkw_newsletter', 'typo3conf/ext/fe_register', ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Mailing\MailProcessor|null */ private ?MailProcessor $subject; /** * @var \Madj2k\Postmaster\Domain\Repository\QueueMailRepository|null */ private ?QueueMailRepository $queueMailRepository = null; /** * @var \Madj2k\Postmaster\Domain\Repository\QueueRecipientRepository|null */ private ?QueueRecipientRepository $queueRecipientRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ private ?IssueRepository $issueRepository = null; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository|null */ private ?TopicRepository $topicRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository|null */ private ?FrontendUserRepository $frontendUserRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\BackendUserRepository|null */ private ?BackendUserRepository $backendUserRepository; /** * @var \Madj2k\Postmaster\Cache\MailCache|null */ private ?MailCache $mailCache; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager|null */ private ?ObjectManager $objectManager; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ], ['rkw-kompetenzzentrum.local' => self::FIXTURE_PATH . '/Frontend/Configuration/config.yaml'] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \Madj2k\Postmaster\Domain\Repository\QueueMailRepository queueMailRepository */ $this->queueMailRepository = $this->objectManager->get(QueueMailRepository::class); /** @var \Madj2k\Postmaster\Domain\Repository\QueueRecipientRepository queueRecipientRepository */ $this->queueRecipientRepository = $this->objectManager->get(QueueRecipientRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository issueRepository */ $this->issueRepository = $this->objectManager->get(IssueRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository topicRepository */ $this->topicRepository = $this->objectManager->get(TopicRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\FrontendUserRepository frontendUserRepository */ $this->frontendUserRepository = $this->objectManager->get(FrontendUserRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\BackendUserRepository backendUserRepository */ $this->backendUserRepository = $this->objectManager->get(BackendUserRepository::class); /** @var \RKW\RkwNewsletter\Mailing\MailProcessor $subject */ $this->subject = $this->objectManager->get(MailProcessor::class); $this->mailCache = $this->objectManager->get(MailCache::class); } //============================================= /** * @test * @throws \Exception */ public function setIssueThrowsExceptionIfMissingNewsletterObject() { /** * Scenario: * * Given a persisted issue-object Y that has no newsletter-object set * When method is called with the issue-object Y as parameter * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1650541234 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1650541234); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(40); $this->subject->setIssue($issue); } /** * @test * @throws \Exception */ public function setIssueThrowsExceptionIfNonPersistedObject() { /** * Scenario: * * Given a new newsletter-object X * Given a new issue-object Y that belongs to newsletter-object X * When method is called with the issue-object Y as parameter * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1650541236 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1650541236); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check40.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = GeneralUtility::makeInstance(Issue::class); /** @var \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter */ $newsletter = GeneralUtility::makeInstance(Newsletter::class); $issue->setNewsletter($newsletter); $this->subject->setIssue($issue); } /** * @test * @throws \Exception */ public function setIssueThrowsExceptionIfConfigurationMissing() { /** * Scenario: * * Given a new newsletter-object X * Given that newsletter-object has no basic configuration-parameters set * Given a new issue-object Y that belongs to newsletter-object X * When method is called with the issue-object Y as parameter * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1651215173 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1651215173); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check270.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(270); $this->subject->setIssue($issue); } /** * @test * @throws \Exception */ public function setIssueSetsBasicConfigurationOfMailService() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has no queueMail-object set * When method is called with the issue-object Y as parameter * Then a new queueMail-object is created * Then this new queueMail-object is added to the mailService * Then the setSettingsPid-property of the queueMail-object is set to the value set in the newsletter-object X * Then the issue-property of the queueMail-object is set to the title-property of the issue-object Y * Then the category-property of the queueMail-object is set the value "rkwNewsletter" * Then the returnPath-property of the queueMail-object is set to the returnPath-value set in the newsletter-object X * Then the replyToAddress-property of the queueMail-object is set to the replayMail-value set in the newsletter-object X * Then the replyToName-property of the queueMail-object is set to the senderName-value set in the newsletter-object X * Then the fromAddress-property of the queueMail-object is set to the senderMail-value set in the newsletter-object X * Then the fromName-property of the queueMail-object is set to the senderName-value set in the newsletter-object X */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $this->subject->setIssue($issue); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMail = $this->queueMailRepository->findByUid(1); self::assertEquals(1, $this->subject->getMailMessage()->getQueueMail()->getUid()); self::assertEquals(2, $queueMail->getSettingsPid()); self::assertEquals('rkwNewsletter', $queueMail->getCategory()); self::assertEquals('<EMAIL>', $queueMail->getReturnPath()); self::assertEquals('<EMAIL>', $queueMail->getReplyToAddress()); self::assertEquals('Test', $queueMail->getReplyToName()); self::assertEquals('<EMAIL>', $queueMail->getFromAddress()); self::assertEquals('Test', $queueMail->getFromName()); } /** * @test * @throws \Exception */ public function setIssueSetsDefaultTemplatePathsOfMailService() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given that newsletter-object has no settingsPid set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has no queueMail-object set * When method is called with the issue-object Y as parameter * Then a new queueMail-object is created * Then this new queueMail-object is added to the mailService * Then the layoutPaths-property of the queueMail-object contains the basic layout-paths * Then the layoutPaths-property of the queueMail-object contains the layout-path of the default-template * Then the layoutPaths-property of the queueMail-object contains the layout-paths of the set template of mewsletter-object X * Then the partialPaths-property of the queueMail-object contains the basic partial-paths * Then the partialPaths-property of the queueMail-object contains the partial-path of the default-template * Then the partialPaths-property of the queueMail-object contains the partial-paths of the set template of mewsletter-object X */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); $expectedLayoutPaths = [ 'EXT:rkw_newsletter/Resources/Private/Layouts/Newsletter', '{$plugin.tx_rkwnewsletter.view.newsletter.layoutRootPath}', 'EXT:rkw_newsletter/Resources/Private/Layouts/Newsletter/Default', 'EXT:rkw_newsletter/Resources/Private/Layouts/Newsletter/Managementletter', '{$plugin.tx_rkwnewsletter.view.newsletter.layoutRootPath}/Default', '{$plugin.tx_rkwnewsletter.view.newsletter.layoutRootPath}/Managementletter' ]; $expectedPartialPaths = [ 'EXT:rkw_newsletter/Resources/Private/Partials/Newsletter', '{$plugin.tx_rkwnewsletter.view.newsletter.partialRootPath}', 'EXT:rkw_newsletter/Resources/Private/Partials/Newsletter/Default', 'EXT:rkw_newsletter/Resources/Private/Partials/Newsletter/Managementletter', '{$plugin.tx_rkwnewsletter.view.newsletter.partialRootPath}/Default', '{$plugin.tx_rkwnewsletter.view.newsletter.partialRootPath}/Managementletter' ]; $this->subject->setIssue($issue); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMail = $this->queueMailRepository->findByUid(1); self::assertEquals(1, $this->subject->getMailMessage()->getQueueMail()->getUid()); self::assertEquals($expectedLayoutPaths, $queueMail->getLayoutPaths()); self::assertEquals($expectedPartialPaths, $queueMail->getPartialPaths()); } /** * @test * @throws \Exception */ public function setIssueSetsTemplatePathsOfMailServiceBasedOnSettingsPid() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has no queueMail-object set * When method is called with the issue-object Y as parameter * Then a new queueMail-object is created * Then this new queueMail-object is added to the mailService * Then the layoutPaths-property of the queueMail-object contains the basic layout-paths * Then the layoutPaths-property of the queueMail-object contains the layout-path of the default-template * Then the layoutPaths-property of the queueMail-object contains the layout-paths of the set template of mewsletter-object X * Then the partialPaths-property of the queueMail-object contains the basic partial-paths * Then the partialPaths-property of the queueMail-object contains the partial-path of the default-template * Then the partialPaths-property of the queueMail-object contains the partial-paths of the set template of mewsletter-object X */ $this->importDataSet(self::FIXTURE_PATH . '/Database/Check21.xml'); $this->setUpFrontendRootPage( 21, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Page21.typoscript', ] ); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(21); $expectedLayoutPaths = [ 'test/Resources/Private/Layouts/Newsletter', '{$plugin.tx_rkwnewsletter.view.newsletter.layoutRootPath}', 'test/Resources/Private/Layouts/Newsletter/Default', 'test/Resources/Private/Layouts/Newsletter/Managementletter', '{$plugin.tx_rkwnewsletter.view.newsletter.layoutRootPath}/Default', '{$plugin.tx_rkwnewsletter.view.newsletter.layoutRootPath}/Managementletter' ]; $expectedPartialPaths = [ 'test/Resources/Private/Partials/Newsletter', '{$plugin.tx_rkwnewsletter.view.newsletter.partialRootPath}', 'test/Resources/Private/Partials/Newsletter/Default', 'test/Resources/Private/Partials/Newsletter/Managementletter', '{$plugin.tx_rkwnewsletter.view.newsletter.partialRootPath}/Default', '{$plugin.tx_rkwnewsletter.view.newsletter.partialRootPath}/Managementletter' ]; $this->subject->setIssue($issue); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMail = $this->queueMailRepository->findByUid(1); self::assertEquals(1, $this->subject->getMailMessage()->getQueueMail()->getUid()); self::assertEquals($expectedLayoutPaths, $queueMail->getLayoutPaths()); self::assertEquals($expectedPartialPaths, $queueMail->getPartialPaths()); self::assertEquals('Managementletter', $queueMail->getHtmlTemplate()); self::assertEquals('Managementletter', $queueMail->getPlaintextTemplate()); } /** * @test * @throws \Exception */ public function setIssueSetsDefaultTemplate() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given that newsletter-object has no template set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has no queueMail-object set * When method is called with the issue-object Y as parameter * Then a new queueMail-object is created * Then this new queueMail-object is added to the mailService * Then the plaintextTemplate-property of the queueMail-object is set to the default template * Then the htmlTemplate-property of the queueMail-object is set to the default template */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); $issue->getNewsletter()->setTemplate(''); $this->subject->setIssue($issue); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMail = $this->queueMailRepository->findByUid(1); self::assertEquals('Default', $queueMail->getHtmlTemplate()); self::assertEquals('Default', $queueMail->getPlaintextTemplate()); } /** * @test * @throws \Exception */ public function setIssueSetsDefinedTemplate() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given that newsletter-object a template set that is not the default-template * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has no queueMail-object set * When method is called with the issue-object Y as parameter * Then a new queueMail-object is created * Then this new queueMail-object is added to the mailService * Then the plaintextTemplate-property of the queueMail-object is set to the default template * Then the htmlTemplate-property of the queueMail-object is set to the default template */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check20.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(20); $this->subject->setIssue($issue); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMail = $this->queueMailRepository->findByUid(1); self::assertEquals('Managementletter', $queueMail->getHtmlTemplate()); self::assertEquals('Managementletter', $queueMail->getPlaintextTemplate()); } /** * @test * @throws \Exception */ public function setIssueDoesNotStartPipeliningOfMailService() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has no queueMail-object set * When method is called with the issue-object Y as parameter * Then a new queueMail-object is created * Then this new queueMail-object is added to the mailService * Then the pipeline-property of the queueMail-object is not set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); $this->subject->setIssue($issue); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMail = $this->queueMailRepository->findByUid(1); self::assertEquals(1, $this->subject->getMailMessage()->getQueueMail()->getUid()); self::assertEquals(0, $queueMail->getPipeline()); } /** * @test * @throws \Exception */ public function setIssueDoesNotSetQueueMailProperty() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has no queueMail-object set * When method is called with the issue-object Y as parameter * Then a new queueMail-object is created * Then this new queueMail-object is added to the mailService * Then this queueMail-Object is not added to the issue-object Y */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check30.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(30); $this->subject->setIssue($issue); self::assertEquals(1, $this->subject->getMailMessage()->getQueueMail()->getUid()); self::assertNull($issue->getQueueMail()); } /** * @test * @throws \Exception */ public function setIssueUsesExistingQueueMailForMailService() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue-object Y has a queueMail-object Z set * When method is called with the issue-object Y as parameter * Then no new queueMail-object is created * Then the existing queueMail-object Z is passed to the mailService */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check50.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(50); $this->subject->setIssue($issue); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMails = $this->queueMailRepository->findAll(); self::assertCount(1, $queueMails); self::assertEquals(50, $this->subject->getMailMessage()->getQueueMail()->getUid()); } /** * @test * @throws \Exception */ public function setIssueSetsIssueAndTopicsForContentLoader() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given three persisted topic-objects A, B, C that belong to the newsletter-object X * Given for topic-object A there is a page-object W that belongs to the issue-object Y * Given for topic-object B there is a page-object X that belongs to the issue-object Y * Given for topic-object C there is a page-object Y that belongs to the issue-object Y * When method is called with the issue-object Y as parameter * Then the issue Y is set to the contentLoader * Then the contentLoader has three topics set * Then the contentLoader has the topics A, B and C set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); $this->subject->setIssue($issue); self::assertEquals($issue, $this->subject->getContentLoader()->getIssue()); $topics = $this->subject->getContentLoader()->getTopics(); $topicsArray = $topics->toArray(); self::assertCount(3, $topicsArray); self::assertEquals(90, $topicsArray[0]->getUid()); self::assertEquals(91, $topicsArray[1]->getUid()); self::assertEquals(92, $topicsArray[2]->getUid()); } //============================================= /** * @test * @throws \Exception */ public function setRecipientsThrowsExceptionIfNoIssueSet() { /** * Scenario: * * Given setIssue is not called before * When method is called * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1650541235 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1650541235); $this->subject->setRecipients(); } /** * @test * @throws \Exception */ public function setRecipientsReturnsTrueAndAddsRecipients() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted newsletter-object Y * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given this issue-object Y has no startTstamp-property set * Given two topic-objects A and B that belong to the newsletter-object X * Given two topic-objects C and D that belong to the newsletter-object Y * Given two frontendUser-objects K and L that have subscribed to the topic C at first * Given two frontendUser-objects K and L that have subscribed to the topic A in the second step * Given three frontendUser-objects K, M and N that have subscribed to the topic B * Given the frontendUser-object N has the priority-property set to true * Given one frontendUser-objects P that has not subscribed to a topic * Given one frontendUser-objects Q that has subscribed to a topic C * Given setIssue with the issue Y is called before * Given the status of the queueMail-object of the mailService is DRAFT (default) * When method is called * Then true is returned * Then the recipients-property of the issue Y returns an array * Then this array contains four items * Then this array contains the ids of the frontendUsers K, L, M and N * Then the frontendUser N is returned first * Then this recipient-list is persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(60); $this->subject->setIssue($issue); self::assertTrue($this->subject->setRecipients()); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $result = $this->subject->getIssue()->getRecipients(); self::assertIsArray( $result); self::assertCount(4, $result); self::assertEquals(63, $result[0]); self::assertEquals(60, $result[1]); self::assertEquals(61, $result[2]); self::assertEquals(62, $result[3]); } /** * @test * @throws \Exception */ public function setRecipientsReturnsTrueAndResetsRecipientList() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted newsletter-object Y * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given this issue-object Y has no startTstamp-property set * Given two topic-objects A and B that belong to the newsletter-object X * Given two topic-objects C and D that belong to the newsletter-object Y * Given two frontendUser-objects K and L that have subscribed to the topic C at first * Given two frontendUser-objects K and L that have subscribed to the topic A in the second step * Given three frontendUser-objects K, M and N that have subscribed to the topic B * Given the frontendUser-object N has the priority-property set to true * Given one frontendUser-objects P that has not subscribed to a topic * Given one frontendUser-objects Q that has subscribed to a topic C * Given setIssue with the issue Y is called before * Given the status of the queueMail-object of the mailService is DRAFT (default) * Given the method has been called before * When method is called * Then true is returned * Then the recipients-property of the issue Y returns an array * Then this array contains four items * Then this array contains the ids of the frontendUsers K, L, M and N * Then the frontendUser N is returned first * Then this recipient-list is persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(60); $this->subject->setIssue($issue); $this->subject->setRecipients(); self::assertTrue($this->subject->setRecipients()); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); $result = $this->subject->getIssue()->getRecipients(); self::assertIsArray( $result); self::assertCount(4, $result); self::assertEquals(63, $result[0]); self::assertEquals(60, $result[1]); self::assertEquals(61, $result[2]); self::assertEquals(62, $result[3]); } /** * @test * @throws \Exception */ public function setRecipientsReturnsFalseIfIssueAlreadyStartedWithSending() { /** * Scenario: * * Given a persisted newsletter-object X * Given a persisted newsletter-object Y * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given this issue-object Y has no startTstamp-property set * Given two topic-objects A and B that belong to the newsletter-object X * Given two topic-objects C and D that belong to the newsletter-object Y * Given two frontendUser-objects K and L that have subscribed to the topic C at first * Given two frontendUser-objects K and L that have subscribed to the topic A in the second step * Given three frontendUser-objects K, M and N that have subscribed to the topic B * Given the frontendUser-object N has the priority-property set to true * Given one frontendUser-objects P that has not subscribed to a topic * Given one frontendUser-objects Q that has subscribed to a topic C * Given setIssue with the issue Y is called before * Given the status of the queueMail-object is SENDING * When method is called * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check60.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(60); $issue->setStartTstamp(time()); $this->subject->setIssue($issue); self::assertFalse($this->subject->setRecipients()); } //============================================= /** * @test * @throws \Exception */ public function getSubscriptionHashReturnsExistingHash() { /** * Scenario: * * Given a persisted frontendUser-object * Given this frontendUser-object has a subscription hash set * When method is called with the frontendUser-object as parameter * Then a string is returned * Then this string is the stored hash from the database */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check70.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(70); $result = $this->subject->getSubscriptionHash($frontendUser); self::assertIsString( $result); self::assertEquals('testhash', $result); } /** * @test * @throws \Exception */ public function getSubscriptionHashReturnsNewHash() { /** * Scenario: * * Given a persisted frontendUser-object * Given this frontendUser-object has no subscription hash set * When method is called with the frontendUser-object as parameter * Then a string is returned * Then a new hash is generated * Then this hash is persisted in the database */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check80.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(80); $result = $this->subject->getSubscriptionHash($frontendUser); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(80); self::assertEquals($result, $frontendUser->getTxRkwnewsletterHash()); } //============================================= /** * @test * @throws \Exception */ public function setTopicsThrowsExceptionIfNoIssueSet() { /** * Scenario: * * Given setIssue is not called before * When method is called * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1650549470 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1650549470); $this->subject->setTopics(new ObjectStorage()); } /** * @test * @throws \Exception */ public function setTopicsSetsGivenTopicsToContentLoader() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given three persisted topic-objects A, B, C that belong to the newsletter-object X * Given for topic-object A there is a page-object W that belongs to the issue-object Y * Given for topic-object B there is a page-object X that belongs to the issue-object Y * Given for topic-object C there is a page-object Y that belongs to the issue-object Y * When method is called with the topics A and C as objectStorage * Then the contentLoader has two topics set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic1 */ $topic1 = $this->topicRepository->findByUid(90); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic2 */ $topic2 = $this->topicRepository->findByUid(92); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic1); $objectStorage->attach($topic2); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $topics = $this->subject->getContentLoader()->getTopics(); self::assertCount(2, $topics); } /** * @test * @throws \Exception */ public function setTopicsSetsAllTopicsOfIssueToContentLoader() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given three persisted topic-objects A, B, C that belong to the newsletter-object X * Given for topic-object A there is a page-object W that belongs to the issue-object Y * Given for topic-object B there is a page-object X that belongs to the issue-object Y * Given for topic-object C there is a page-object Y that belongs to the issue-object Y * When method is called without parameter * Then the contentLoader has three topics set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); $this->subject->setIssue($issue); $this->subject->setTopics(); $topics = $this->subject->getContentLoader()->getTopics(); self::assertCount(3, $topics); } /** * @test * @throws \Exception */ public function setTopicsSetsNoTopicsToContentLoader() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given three persisted topic-objects A, B, C that belong to the newsletter-object X * Given for topic-object A there is a page-object W that belongs to the issue-object Y * Given for topic-object B there is a page-object X that belongs to the issue-object Y * Given for topic-object C there is a page-object Y that belongs to the issue-object Y * When method is called without an empty objectStorage as parameter * Then the contentLoader has no topics set */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check90.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(90); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $topics = $this->subject->getContentLoader()->getTopics(); self::assertCount(0, $topics); } //============================================= /** * @test * @throws \Exception */ public function getSubjectThrowsExceptionIfNoIssueSet() { /** * Scenario: * * Given a persisted frontendUser * Given setIssue is not set before * When method is called with the frontendUser as parameter * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1650549470 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1650549470); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check100.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(110); $this->subject->getSubject($frontendUser); } /** * @test * @throws \Exception */ public function getSubjectReturnsCombinedSubject() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all basic configuration-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given setIssue with the issue Y is called before * Given setTopics is called with topic B before * When method is called * Then a string is returned * Then this string begins with the issue-title * Then this string ends with the headline of the first content of topic B which is no editorial */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check100.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(100); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topicOne */ $topic = $this->topicRepository->findByUid(101); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); $result = $this->subject->getSubject(); self::assertEquals('Test – Content 71.2', $result); } //============================================= /** * @test * @throws \Exception */ public function sendMailThrowsExceptionIfNoIssueSet() { /** * Scenario: * * Given setIssue is not called before * When method is called * Then an exception is thrown * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1650608449 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1650608449); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check110.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(110); $this->subject->sendMail($frontendUser); } /** * @test * @throws \Exception */ public function sendMailReturnsFalseIfNoContentsAvailable() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check120.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(120); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(120); $this->subject->setIssue($issue); self::assertFalse($this->subject->sendMail($frontendUser)); } /** * @test * @throws \Exception */ public function sendMailReturnsTrueIfContentsAvailable() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic B * Given that frontendUser has a valid email set * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then true is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check130.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(130); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(130); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); } /** * @test * @throws \Exception */ public function sendMailReturnsFalseIfEmailMissing() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic B * Given that frontendUser has no valid email set * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check140.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(140); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(140); $this->subject->setIssue($issue); self::assertFalse($this->subject->sendMail($frontendUser)); } /** * @test * @throws \Exception */ public function sendMailAddsMarkerToQueueRecipient() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic B * Given that frontendUser has a valid email set * Given that frontendUser has a subscription-hash set * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then true is returned * Then a queueRecipient-object is created * Then this queueRecipient-object has a marker-array with four items set * Then this queueRecipient-object has the issue-object Y set as reduced marker * Then this queueRecipient-object has the topic-object B set as reduced marker-array * Then this queueRecipient-object has the subscription-hash of the frontendUser set as string-marker * Then this queueRecipient-object has the settings of rkwNewsletter set as normal marker-array */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check150.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(150); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(150); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); $marker = $queueRecipient->getMarker(); self::assertIsArray( $marker); self::assertCount(4, $marker); self::assertEquals('TX_ACCELERATOR_NAMESPACES RKW\RkwNewsletter\Domain\Model\Issue:150', $marker['issue']); self::assertEquals('TX_ACCELERATOR_NAMESPACES_ARRAY RKW\RkwNewsletter\Domain\Model\Topic:151', $marker['topics']); self::assertEquals('HashMeIfYouCanButWeHaveToHaveFourtySigns', $marker['hash']); self::assertIsArray($marker['settings']); self::assertEquals('302400', $marker['settings']['reminderApprovalStage1']); } /** * @test * @throws \Exception */ public function sendMailRendersDefaultEditorial() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A and B * Given that frontendUser has a valid email set * Given the frontendUser has no names set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains the default editorial * Then the mailCache for html contains the default editorial * Then the mailCache for plaintext does not contain the editorial of topic A * Then the mailCache for html does not contain the editorial of topic A * Then the mailCache for plaintext does not contain the editorial of topic B * Then the mailCache for html does not contain the editorial of topic B */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(160); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( 'untenstehend finden Sie Neuigkeiten zu Projekten, Veröffentlichungen und Veranstaltungen des RKW Kompetenzzentrums', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'untenstehend finden Sie Neuigkeiten zu Projekten, Veröffentlichungen und Veranstaltungen des RKW Kompetenzzentrums', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 160', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 160', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 161', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 161', $this->mailCache->getHtmlBody($queueRecipient) ); } /** * @test * @throws \Exception */ public function sendMailRendersTopicEditorial() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A only * Given that frontendUser has a valid email set * Given the frontendUser has no names set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext does not contain the default editorial * Then the mailCache for html does not contain the default editorial * Then the mailCache for plaintext contains the editorial of topic A * Then the mailCache for html contains the editorial of topic A */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check170.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(170); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(170); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringNotContainsString( 'untenstehend finden Sie Neuigkeiten zu Projekten, Veröffentlichungen und Veranstaltungen des RKW Kompetenzzentrums', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'untenstehend finden Sie Neuigkeiten zu Projekten, Veröffentlichungen und Veranstaltungen des RKW Kompetenzzentrums', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Test the editorial 170', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Test the editorial 170', $this->mailCache->getHtmlBody($queueRecipient) ); } /** * @test * @throws \Exception */ public function sendMailRendersContents() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A and B * Given that frontendUser has a valid email set * Given the frontendUser has no names set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains all contents of topic A * Then the mailCache for html contains all contents of topic A * Then the mailCache for plaintext does not contain the editorial of topic A * Then the mailCache for html does not contain the editorial of topic A * Then the mailCache for plaintext contains all contents of topic B * Then the mailCache for html contains all contents of topic B * Then the mailCache for plaintext does not contain the editorial of topic B * Then the mailCache for html does not contain the editorial of topic B */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(160); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( '', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 160', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 160', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 160.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 160.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 160.3', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 160.3', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 160.4', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 160.4', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 161', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Test the editorial 161', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 161.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 161.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 161.3', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 161.3', $this->mailCache->getHtmlBody($queueRecipient) ); } /** * @test * @throws \Exception */ public function sendMailRendersContentsOfSpecialTopicForAllRecipients() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted topic-object C that belongs to the newsletter-object X * Given topic B is marked as special * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A and C * Given that frontendUser has a valid email set * Given the frontendUser has no names set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains all contents of topic B * Then the mailCache for html contains all contents of topic B * Then the mailCache for plaintext contains the editorial of topic B * Then the mailCache for html contains the editorial of topic B */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check240.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(240); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(240); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( 'Test the editorial 241', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Test the editorial 241', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 241.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 241.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 241.3', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 241.3', $this->mailCache->getHtmlBody($queueRecipient) ); } /** * @test * @throws \Exception */ public function sendMailRendersSubscriptionList() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A and B * Given that frontendUser has a valid email set * Given the frontendUser has no names set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains the text for the subscription-list * Then the mailCache for html contains the text for the subscription-list * Then the mailCache for plaintext contains the label of topic A * Then the mailCache for html contains the label of topic A * Then the mailCache for plaintext contains the label of topic B * Then the mailCache for html contains the label of topic B */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(160); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( 'Sie haben folgende Themen abonniert', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Sie haben folgende Themen abonniert', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Topic 160', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Topic 160', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Topic 161', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Topic 161', $this->mailCache->getHtmlBody($queueRecipient) ); } /** * @test * @throws \Exception */ public function sendMailRendersSubscriptionLink() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A and B * Given that frontendUser has a valid email set * Given the frontendUser has no names set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains the subscription-pid * Then the mailCache for html contains the subscription-pid * Then the mailCache for plaintext contains the subscription-hash * Then the mailCache for html contains the subscription-hash */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(160); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( 'http%3A%2F%2Fwww.rkw-kompetenzzentrum.rkw.local%2Fabonnements%2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'http%3A%2F%2Fwww.rkw-kompetenzzentrum.rkw.local%2Fabonnements%2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( '%2FHashMeIfYouCanButWeHaveToHaveFourtySigns%2F', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( '%2FHashMeIfYouCanButWeHaveToHaveFourtySigns%2F', $this->mailCache->getHtmlBody($queueRecipient) ); } /** * @test * @throws \Exception */ public function sendMailRendersDefaultSalutation() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A and B * Given that frontendUser has a valid email set * Given the frontendUser has no names set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains default salutation * Then the mailCache for html contains efault salutation */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check160.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(160); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(160); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( 'Hallo,', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Hallo,', $this->mailCache->getHtmlBody($queueRecipient) ); } /** * @test * @throws \Exception */ public function sendMailRendersCustomSalutation() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser * Given that frontendUser has subscribed to topic A and B * Given that frontendUser has a valid email set * Given the frontendUser has a first-name set * Given the frontendUser has a last-name set * Given the frontendUser has a gender set * Given that frontendUser has a subscription-hash set * Given that frontendUser has "de" set as language-key * Given setIssue with the issue Y is called before * When method is called with the frontendUser as parameter * Then false is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains default salutation * Then the mailCache for html contains efault salutation */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check180.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(180); /** @var \RKW\RkwNewsletter\Domain\Model\FrontendUser $frontendUser */ $frontendUser = $this->frontendUserRepository->findByUid(180); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMail($frontendUser)); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( '<NAME>,', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( '<NAME>,', $this->mailCache->getHtmlBody($queueRecipient) ); } //============================================= /** * @test * @throws \Exception */ public function sendTestMailThrowsExceptionIfNoIssueSet() { /** * Scenario: * * Given setIssue is not called before * When method is called * Then an exception is thrown * Then an exception is thrown * Then the exception is an instance of \RKW\RkwNewsletter\Exception * Then the exception has the code 1650629464 */ static::expectException(\RKW\RkwNewsletter\Exception::class); static::expectExceptionCode(1650629464); $this->importDataSet(static::FIXTURE_PATH . '/Database/Check190.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ $backendUser = $this->backendUserRepository->findByUid(190); $this->subject->sendTestMail($backendUser); } /** * @test * @throws \Exception */ public function sendTestMailReturnsFalseIfNoContentsAvailable() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given setTopic with topic A is called before * Given setIssue with the issue Y is called before * When method is called with a valid email-address as parameter * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check200.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(200); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(200); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertFalse($this->subject->sendTestMail('<EMAIL>')); } /** * @test * @throws \Exception */ public function sendTestMailReturnsTrueIfContentsAvailable() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given setTopic with topic B is called before * Given that backendUser has a valid email set * Given setIssue with the issue Y is called before * When method is called with a valid email-address as parameter * Then true is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check210.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(210); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(211); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertTrue($this->subject->sendTestMail('<EMAIL>')); } /** * @test * @throws \Exception */ public function sendTestMailReturnsFalseIfEmailInvalid() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted backendUser * Given setTopic with topic B is called before * Given setIssue with the issue Y is called before * When method is called with an invalid email-address as parameter * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check220.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(220); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(221); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertFalse($this->subject->sendTestMail('test')); } /** * @test * @throws \Exception */ public function sendTestMailAddsMarkerToQueueRecipient() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given setTopic with topic B is called before * Given setIssue with the issue Y is called before * When method is called with a valid email-address as parameter * Then true is returned * Then a queueRecipient-object is created * Then this queueRecipient-object has a marker-array with three items set * Then this queueRecipient-object has the issue-object Y set as reduced marker * Then this queueRecipient-object has the topic-object B set as reduced marker-array * Then this queueRecipient-object has no subscription-hash as marker set * Then this queueRecipient-object has the settings of rkwNewsletter set as normal marker-array */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check210.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(210); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(211); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertTrue($this->subject->sendTestMail('<EMAIL>')); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); $marker = $queueRecipient->getMarker(); self::assertIsArray( $marker); self::assertCount(3, $marker); self::assertEquals('TX_ACCELERATOR_NAMESPACES RKW\RkwNewsletter\Domain\Model\Issue:210', $marker['issue']); self::assertEquals('TX_ACCELERATOR_NAMESPACES_ARRAY RKW\RkwNewsletter\Domain\Model\Topic:211', $marker['topics']); self::assertNull($marker['hash']); self::assertIsArray( $marker['settings']); self::assertEquals('302400', $marker['settings']['reminderApprovalStage1']); } /** * @test * @throws \Exception */ public function sendTestMailRendersDummySalutation() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains no content-objects * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given setTopic with topic B is called before * Given setIssue with the issue Y is called before * When method is called with a valid email-address as parameter * Then true is returned * Then a queueRecipient-object is created * Then the mailCache for plaintext contains default salutation * Then the mailCache for html contains efault salutation */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check210.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(210); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(211); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertTrue($this->subject->sendTestMail('<EMAIL>')); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); // we have to trigger the rendering manually here - for testing only! $this->subject->getMailMessage()->getMailer()->renderTemplates( $this->subject->getMailMessage()->getQueueMail(), $queueRecipient ); self::assertStringContainsString( 'Hallo Prof. Dr. Dr. Musterfrau,', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Hallo Prof. Dr. Dr. Musterfrau,', $this->mailCache->getHtmlBody($queueRecipient) ); } //============================================= /** * @test * @throws \Exception */ public function sendMailsSetsStartTsstamp() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue has four fictive recipients in the recipient-property set * Given setIssue with the issue Y is called before * When the method is called with limit-parameter 2 * Then true is returned * Then the startTstamp-property of the issue-object Y is set to the current time * Then the sentTstamp-property of the issue-object Y is not set * Then this changes to issue-object are persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMails(2)); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); self::assertGreaterThanOrEqual(time() - 5, $issue->getStartTstamp()); self::assertEquals(0, $issue->getSentTstamp()); } /** * @test * @throws \Exception */ public function sendMailsSetsSentTsstampAndStatusDone() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue has four fictive recipients in the recipient-property set * Given setIssue with the issue Y is called before * When the method is called with limit-parameter 4 * Then true is returned * When the method is called with limit-parameter 4 * Then false is returned * Then the pipeline-property of the queueMail-object is set to false * Then the startTstamp-property of the issue-object Y is set to the current time * Then the sentTstamp-property of the issue-object Y is set to the current time * Then the status-property of the issue-object Y is set to IssueStatus::STAGE_DONE * Then the lastSentTstamp-property of the newsletter-object X is set to the current time * Then this changes to issue-object are persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $this->subject->setIssue($issue); // -------------------------------- // First call // -------------------------------- self::assertTrue($this->subject->sendMails(4)); // -------------------------------- // Second call // -------------------------------- self::assertFalse($this->subject->sendMails(4)); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); self::assertGreaterThanOrEqual(time() - 5, $issue->getStartTstamp()); self::assertGreaterThanOrEqual(time() - 5, $issue->getSentTstamp()); self::assertEquals(IssueStatus::STAGE_DONE, $issue->getStatus()); self::assertGreaterThanOrEqual(time() - 5, $issue->getNewsletter()->getLastSentTstamp()); } /** * @test * @throws \Exception */ public function sendMailsSetsTypeOfMailService() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue has four fictive recipients in the recipient-property set * Given setIssue with the issue Y is called before * When the method is called with limit-parameter 2 * Then true is returned * Then the type-property of the queueMail-object is set to 1 */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMails(2)); self::assertEquals(1, $this->subject->getMailMessage()->getQueueMail()->getType()); } /** * @test * @throws \Exception */ public function sendMailsStartsPipeliningOfMailService() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue has four fictive recipients in the recipient-property set * Given setIssue with the issue Y is called before * When the method is called with limit-parameter 2 * Then true is returned * Then the pipeline-property of the queueMail-object is set to true */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $this->subject->setIssue($issue); self::assertTrue($this->subject->sendMails(2)); self::assertTrue($this->subject->getMailMessage()->getQueueMail()->getPipeline()); } /** * @test * @throws \Exception */ public function sendMailsStopsPipeliningOfMailService() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue has four fictive recipients in the recipient-property set * Given setIssue with the issue Y is called before * When the method is called with limit-parameter 4 * Then true is returned * Then the pipeline-property of the queueMail-object is set to true * When the method is called with limit-parameter 2 * Then false is returned * Then the pipeline-property of the queueMail-object is set to false */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $this->subject->setIssue($issue); // -------------------------------- // First call // -------------------------------- self::assertTrue($this->subject->sendMails(4)); self::assertTrue($this->subject->getMailMessage()->getQueueMail()->getPipeline()); // -------------------------------- // Second call // -------------------------------- self::assertFalse($this->subject->sendMails(4)); self::assertFalse($this->subject->getMailMessage()->getQueueMail()->getPipeline()); } /** * @test * @throws \Exception */ public function sendMailsRemovesRecipientsEvenIfNonExistent() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue has four fictive recipients in the recipient-property set * Given setIssue with the issue Y is called before * When the method is called with limit-parameter 2 * Then true is returned * Then the recipient-property of the issue-object is an array * Then this array has two items * When the method is called with limit-parameter 2 * Then true is returned * Then the recipient-property of the issue-object is an array * Then this array is empty * Then this changes to issue-object are persisted */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $this->subject->setIssue($issue); // -------------------------------- // First call // -------------------------------- self::assertTrue($this->subject->sendMails(2)); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); self::assertIsArray( $issue->getRecipients()); self::assertCount(2, $issue->getRecipients()); // -------------------------------- // Second call // -------------------------------- self::assertTrue($this->subject->sendMails(2)); // force TYPO3 to load objects new from database $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->clearState(); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); self::assertIsArray( $issue->getRecipients()); self::assertCount(0, $issue->getRecipients()); } /** * @test * @throws \Exception */ public function sendMailsReusesQueueMail() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given that issue has four fictive recipients in the recipient-property set * Given setIssue with the issue Y is called before * When the method is called with limit-parameter 2 * Then true is returned * Then no new queueMail-object is created * Then the queueMail-object of the mailService is set to the corresponding issue * Then this changes to issue-object are persisted * When the method is called with limit-parameter 2 * Then true is returned * Then no new queueMail-object is created * Then the same queueMail-object of the mailService is used again */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check260.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); $this->subject->setIssue($issue); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ $queueMail = $this->subject->getMailMessage()->getQueueMail(); $count = $this->queueMailRepository->findAll()->count(); // -------------------------------- // First call // -------------------------------- self::assertTrue($this->subject->sendMails(2)); self::assertCount($count, $this->queueMailRepository->findAll()->toArray()); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); self::assertEquals($queueMail->getUid(), $issue->getQueueMail()->getUid()); self::assertEquals($queueMail->getUid(), $this->subject->getMailMessage()->getQueueMail()->getUid()); // -------------------------------- // Second call // -------------------------------- self::assertTrue($this->subject->sendMails(2)); self::assertCount($count, $this->queueMailRepository->findAll()); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(260); self::assertEquals($queueMail->getUid(), $issue->getQueueMail()->getUid()); self::assertEquals($queueMail->getUid(), $this->subject->getMailMessage()->getQueueMail()->getUid()); } /** * @test * @throws \Exception */ public function sendMailsRendersContentsAccordingToSubscriptions() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given a persisted frontendUser 1 * Given that frontendUser 1 has subscribed to topic A and B * Given that frontendUser 1 has a subscription-hash set * Given that frontendUser 1 has "de" set as language-key * Given a persisted frontendUser 2 * Given that frontendUser 2 has subscribed to topic A * Given that frontendUser 2 has a subscription-hash set * Given that frontendUser 2 has "de" set as language-key * Given a persisted frontendUser 3 * Given that frontendUser 3 has subscribed to topic B * Given that frontendUser 3 has a subscription-hash set * Given that frontendUser 3 has "de" set as language-key * Given a persisted frontendUser 4 * Given that frontendUser 4 has subscribed to topic B * Given that frontendUser 4 has a subscription-hash set * Given that frontendUser 4 has "de" set as language-key * Given setIssue with the issue Y is called before * Given setRecipients is called before * When method is called with limit 2 * Then true is returned * Then two queueRecipient-object One and Two are created for the frontendUsers 1 and 2 * Then the contents of topic A and B are rendered for the queueRecipient-object One * Then the contents of topic A only are rendered for the queueRecipient-object Two * When method is called with limit 1 a second time * Then true is returned * Then one queueRecipient-object is created for the frontendUser 3 * Then the contents of topic B are rendered for the queueRecipient-object * When method is called with limit 2 a third time * Then true is returned * Then one queueRecipient-object is created created for the frontendUser 4 * Then the contents of topic B are rendered for the queueRecipient-object * When method is called with limit 2 a fourth time * Then false is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check230.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(230); /** @var \Madj2k\Postmaster\Domain\Model\QueueMail $queueMail */ self::assertCount(0, $this->queueMailRepository->findAll()); $this->subject->setIssue($issue); $this->subject->setRecipients(); // -------------------------------- // First call // -------------------------------- self::assertTrue($this->subject->sendMails(2)); self::assertCount(2, $this->queueRecipientRepository->findAll()); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( 'Content 230.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 230.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getHtmlBody($queueRecipient) ); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(2); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringContainsString( 'Content 230.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 230.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringNotContainsString( 'Content 231.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Content 231.2', $this->mailCache->getHtmlBody($queueRecipient) ); // -------------------------------- // Second call // -------------------------------- self::assertTrue($this->subject->sendMails(1)); self::assertCount(3, $this->queueRecipientRepository->findAll()); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(3); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getHtmlBody($queueRecipient) ); // -------------------------------- // third call // -------------------------------- self::assertTrue($this->subject->sendMails(2)); self::assertCount(4, $this->queueRecipientRepository->findAll()); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(4); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getHtmlBody($queueRecipient) ); // -------------------------------- // Fourth call // -------------------------------- self::assertFalse($this->subject->sendMails(2)); } //============================================= /** * @test * @throws \Exception */ public function sendTestMailsWorksThroughRecipients() { /** * Scenario: * * Given a persisted newsletter-object X * Given that newsletter-object has all relevant mail-parameters set * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given one of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * Given setIssue with the issue Y is called before * Given setTopic with topic B is called before * Given three email-addresses * Given one of the three email-addresses is invalid * When method is called with this email-addresses as comma-separated string * Then true is returned * Then two queueRecipient-objects * Then the contents of topic B only are rendered for the two queueRecipient-objects * Then the pipeline-property of the mailService is set to false * Then the status-property of the issue Y is not set to STAGE_DONE * Then the sentTstamp-property of the issue Y is zero * Then the lastSendTimestamp-property of the newsletter X is zero */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check250.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(250); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(251); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->subject->setIssue($issue); $this->subject->setTopics($objectStorage); self::assertTrue($this->subject->sendTestMails('test,<EMAIL>,<EMAIL>')); self::assertCount(2, $this->queueRecipientRepository->findAll()); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(1); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); // we have to trigger the rendering manually here - for testing only! $this->subject->getMailMessage()->getMailer()->renderTemplates( $this->subject->getMailMessage()->getQueueMail(), $queueRecipient ); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getHtmlBody($queueRecipient) ); /** @var \Madj2k\Postmaster\Domain\Model\QueueRecipient $queueRecipient */ $queueRecipient = $this->queueRecipientRepository->findByUid(2); self::assertInstanceOf(QueueRecipient::class, $queueRecipient); // we have to trigger the rendering manually here - for testing only! $this->subject->getMailMessage()->getMailer()->renderTemplates( $this->subject->getMailMessage()->getQueueMail(), $queueRecipient ); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringNotContainsString( 'Content 230.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getPlaintextBody($queueRecipient) ); self::assertStringContainsString( 'Content 231.2', $this->mailCache->getHtmlBody($queueRecipient) ); self::assertEquals(false, $this->subject->getMailMessage()->getQueueMail()->getPipeline()); self::assertNotEquals(IssueStatus::STAGE_DONE, $issue->getStatus()); self::assertEquals(0, $issue->getSentTstamp()); self::assertEquals(0, $issue->getNewsletter()->getLastSentTstamp()); } //============================================= /** * TearDown */ protected function tearDown(): void { $this->mailCache->clearCache(); parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Repository; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings; use TYPO3\CMS\Extbase\Persistence\QueryResultInterface; /** * PagesRepository * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class PagesRepository extends AbstractRepository { /** * @return void * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function initializeObject(): void { parent::initializeObject(); $querySettings = $this->objectManager->get(Typo3QuerySettings::class); $querySettings->setRespectStoragePage(false); } /** * findByTopicNotIncluded * * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface * comment: implicitly tested */ public function findByTopicNotIncluded(\RKW\RkwNewsletter\Domain\Model\Topic $topic): QueryResultInterface { $query = $this->createQuery(); $query->getQuerySettings()->setRespectStoragePage(false); $query->matching( $query->logicalAnd( $query->equals('doktype', 1), $query->equals('txRkwnewsletterNewsletter', $topic->getNewsletter()), $query->equals('txRkwnewsletterTopic', $topic->getUid()), $query->equals('txRkwnewsletterIncludeTstamp', 0), $query->equals('txRkwnewsletterExclude', false) ) ); return $query->execute(); } } <file_sep><?php return [ 'ctrl' => [ 'title' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter', 'label' => 'name', 'tstamp' => 'tstamp', 'crdate' => 'crdate', 'cruser_id' => 'cruser_id', 'dividers2tabs' => true, 'languageField' => 'sys_language_uid', 'transOrigPointerField' => 'l10n_parent', 'transOrigDiffSourceField' => 'l10n_diffsource', 'delete' => 'deleted', 'enablecolumns' => [ 'disabled' => 'hidden', 'starttime' => 'starttime', 'endtime' => 'endtime', ], 'searchFields' => 'name, issue_title, sender_name, sender_mail, reply_mail, return_path, priority, template, settings_page, format, rythm, day_for_sending, approval, usergroup, topic, recently_sent,', 'iconfile' => 'EXT:rkw_newsletter/Resources/Public/Icons/tx_rkwnewsletter_domain_model_newsletter.gif' ], 'interface' => [ 'showRecordFieldList' => 'sys_language_uid, l10n_parent, l10n_diffsource, hidden, name, issue_title, sender_name, sender_mail, reply_mail, return_path, template, type, settings_page, rythm, day_for_sending, approval, usergroup, topic, last_sent_tstamp, last_issue_tstamp, issue', ], 'types' => [ '1' => ['showitem' => 'sys_language_uid, l10n_parent, l10n_diffsource, name, issue_title, sender_name, sender_mail, reply_mail, return_path, template, type, settings_page, encoding, charset, rythm, day_for_sending, approval, usergroup, topic, last_sent_tstamp, last_issue_tstamp, issue, --div--;LLL:EXT:cms/locallang_ttc.xlf:tabs.access, hidden,--palette--;;1, starttime, endtime'], ], 'palettes' => [ '1' => ['showitem' => ''], ], 'columns' => [ 'sys_language_uid' => [ 'exclude' => true, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.language', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'foreign_table' => 'sys_language', 'foreign_table_where' => 'ORDER BY sys_language.title', 'default' => 0, 'items' => [ ['LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.allLanguages', -1], ['LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.default_value', 0], ], ], ], 'l10n_parent' => [ 'displayCond' => 'FIELD:sys_language_uid:>:0', 'exclude' => false, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.l18n_parent', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'items' => [ ['', 0], ], 'foreign_table' => 'tx_rkwnewsletter_domain_model_newsletter', 'foreign_table_where' => 'AND tx_rkwnewsletter_domain_model_newsletter.pid=###CURRENT_PID### AND tx_rkwnewsletter_domain_model_newsletter.sys_language_uid IN (-1,0)', ], ], 'l10n_diffsource' => [ 'config' => [ 'type' => 'passthrough', ], ], 'hidden' => [ 'exclude' => true, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.hidden', 'config' => [ 'type' => 'check', ], ], 'starttime' => [ 'exclude' => true, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.starttime', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 13, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'range' => [ 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')), ], 'behaviour' => [ 'allowLanguageSynchronization' => true ] ], ], 'endtime' => [ 'exclude' => true, 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.endtime', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 13, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'range' => [ 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')), ], 'behaviour' => [ 'allowLanguageSynchronization' => true ] ], ], 'name' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.name', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim, required', ], ], 'issue_title' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.issue_title', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim, required' ], ], 'sender_name' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.sender_name', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'sender_mail' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.sender_mail', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'reply_name' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.reply_name', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'reply_mail' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.reply_mail', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'return_path' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.return_path', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'priority' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.priority', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'items' => [ ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.priority.normal', '2'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.priority.high', '3'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.priority.low', '1'], ], 'size' => 1, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 1, ], ], 'template' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.template', 'config' => [ 'type' => 'input', 'size' => 30, 'default' => 'Default', 'eval' => 'trim, required' ], ], 'settings_page' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xl:tx_rkwnewsletter_domain_model_newsletter.settings_page', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'int, required', ], ], 'format' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.format', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'items' => [ ['Plaintext', '1'], ['HTML', '2'], ['Plaintext / HTML', '3'], ], 'size' => 1, 'eval' => 'int, required', 'minitems' => 0, 'maxitems' => 1, ], ], 'rythm' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.rythm', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'items' => [ ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.rythm.weekly', 1], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.rythm.monthly', 2], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.rythm.bimonthly', 3], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.rythm.quarterly', 4], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.rythm.semiannually', 5], ], 'size' => 1, 'eval' => 'int, required', 'minitems' => 1, 'maxitems' => 1, ], ], 'day_for_sending' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.day_for_sending', 'config' => [ 'type' => 'input', 'size' => 30, 'range' => array( 'lower' => 1, 'upper' => 31 ), 'default' => 15, 'eval' => 'num, trim, required', ], ], 'approval' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.approval', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'size' => 8, 'eval' => 'int', 'default' => '', 'minitems' => 1, 'maxitems' => 10, 'foreign_table' => 'be_users', 'foreign_table_where' => 'AND be_users.deleted = 0 AND be_users.disable = 0 ORDER BY be_users.username', ], ], 'usergroup' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.usergroup', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'size' => 8, 'eval' => 'int', 'minitems' => 0, 'maxitems' => 10, 'foreign_table' => 'fe_groups', 'foreign_table_where' => 'AND fe_groups.deleted = 0 AND fe_groups.hidden = 0', ], ], 'topic' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.topic', 'config' => [ 'type' => 'inline', 'internal_type' => 'db', 'foreign_table' => 'tx_rkwnewsletter_domain_model_topic', 'foreign_table_where' => 'AND tx_rkwnewsletter_domain_model_topic.deleted = 0 AND tx_rkwnewsletter_domain_model_topic.hidden = 0', 'foreign_field' => 'newsletter', 'foreign_sortby' => 'sorting', 'show_thumbs' => true, 'minitems' => 1, 'maxitems' => 9999, 'size' => 5, 'appearance' => [ 'elementBrowserType' => 'db' ], ], ], 'issue' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.issue', 'config' => [ 'type' => 'inline', 'internal_type' => 'db', 'foreign_table' => 'tx_rkwnewsletter_domain_model_issue', 'foreign_field' => 'newsletter', 'foreign_default_sortby' => 'status', 'show_thumbs' => true, 'minitems' => 0, 'maxitems' => 9999, 'size' => 5, 'appearance' => [ 'elementBrowserType' => 'db', 'useSortable' => false, 'showPossibleLocalizationRecords' => false, 'showRemovedLocalizationRecords' => false, 'showSynchronizationLink' => false, 'showAllLocalizationLink' => false, 'enabledControls' => [ 'info' => true, 'new' => false, 'dragdrop' => false, 'sort' => false, 'hide' => false, 'delete' => false, 'localize' => false, ], ], ], ], 'last_sent_tstamp' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.last_sent_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 13, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'readOnly' => 1, 'range' => [ 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')), ], ], ], 'last_issue_tstamp' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_newsletter.last_issue_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 13, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'readOnly' => 1, 'range' => [ 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')), ], ], ], ], ]; <file_sep># # Table structure for table 'tx_rkwnewsletter_domain_model_newsletter' # CREATE TABLE tx_rkwnewsletter_domain_model_newsletter ( uid int(11) NOT NULL auto_increment, pid int(11) DEFAULT '0' NOT NULL, name varchar(255) DEFAULT '' NOT NULL, issue_title varchar(255) DEFAULT '' NOT NULL, sender_name varchar(255) DEFAULT '' NOT NULL, sender_mail varchar(255) DEFAULT '' NOT NULL, reply_name varchar(255) DEFAULT '' NOT NULL, reply_mail varchar(255) DEFAULT '' NOT NULL, return_path varchar(255) DEFAULT '' NOT NULL, priority int(11) DEFAULT '0' NOT NULL, template varchar(255) DEFAULT '' NOT NULL, format tinyint(4) DEFAULT '0' NOT NULL, settings_page int(11) DEFAULT '0' NOT NULL, rythm tinyint(4) DEFAULT '0' NOT NULL, day_for_sending tinyint(4) DEFAULT '15' NOT NULL, approval varchar(255) DEFAULT '' NOT NULL, usergroup varchar(255) DEFAULT '' NOT NULL, topic varchar(255) DEFAULT '' NOT NULL, issue varchar(255) DEFAULT '' NOT NULL, last_sent_tstamp int(11) DEFAULT '0' NOT NULL, last_issue_tstamp int(11) DEFAULT '0' NOT NULL, tstamp int(11) unsigned DEFAULT '0' NOT NULL, crdate int(11) unsigned DEFAULT '0' NOT NULL, cruser_id int(11) unsigned DEFAULT '0' NOT NULL, deleted tinyint(4) unsigned DEFAULT '0' NOT NULL, hidden tinyint(4) unsigned DEFAULT '0' NOT NULL, starttime int(11) unsigned DEFAULT '0' NOT NULL, endtime int(11) unsigned DEFAULT '0' NOT NULL, sys_language_uid int(11) DEFAULT '0' NOT NULL, l10n_parent int(11) DEFAULT '0' NOT NULL, l10n_diffsource mediumblob, PRIMARY KEY (uid), KEY parent (pid), KEY language (l10n_parent,sys_language_uid) ); # # Table structure for table 'tx_rkwnewsletter_domain_model_topic' # CREATE TABLE tx_rkwnewsletter_domain_model_topic ( uid int(11) NOT NULL auto_increment, pid int(11) DEFAULT '0' NOT NULL, name varchar(255) DEFAULT '' NOT NULL, short_description varchar(255) DEFAULT '' NOT NULL, approval_stage1 varchar(255) DEFAULT '' NOT NULL, approval_stage2 varchar(255) DEFAULT '' NOT NULL, container_page int(11) unsigned DEFAULT '0' NOT NULL, is_special int(1) unsigned DEFAULT '0' NOT NULL, newsletter int(11) unsigned DEFAULT '0' NOT NULL, tstamp int(11) unsigned DEFAULT '0' NOT NULL, crdate int(11) unsigned DEFAULT '0' NOT NULL, cruser_id int(11) unsigned DEFAULT '0' NOT NULL, deleted tinyint(4) unsigned DEFAULT '0' NOT NULL, hidden tinyint(4) unsigned DEFAULT '0' NOT NULL, starttime int(11) unsigned DEFAULT '0' NOT NULL, endtime int(11) unsigned DEFAULT '0' NOT NULL, sorting int(11) unsigned DEFAULT '0' NOT NULL, PRIMARY KEY (uid), KEY parent (pid), ); # # Table structure for table 'tx_rkwnewsletter_domain_model_approval' # CREATE TABLE tx_rkwnewsletter_domain_model_approval ( uid int(11) NOT NULL auto_increment, pid int(11) DEFAULT '0' NOT NULL, topic int(11) unsigned DEFAULT '0', issue int(11) unsigned DEFAULT '0', page int(11) unsigned DEFAULT '0', allowed_by_user_stage1 varchar(255) DEFAULT '' NOT NULL, allowed_by_user_stage2 varchar(255) DEFAULT '' NOT NULL, allowed_tstamp_stage1 int(11) unsigned DEFAULT '0', allowed_tstamp_stage2 int(11) unsigned DEFAULT '0', sent_info_tstamp_stage1 int(11) unsigned DEFAULT '0', sent_info_tstamp_stage2 int(11) unsigned DEFAULT '0', sent_reminder_tstamp_stage1 int(11) unsigned DEFAULT '0', sent_reminder_tstamp_stage2 int(11) unsigned DEFAULT '0', tstamp int(11) unsigned DEFAULT '0' NOT NULL, crdate int(11) unsigned DEFAULT '0' NOT NULL, cruser_id int(11) unsigned DEFAULT '0' NOT NULL, PRIMARY KEY (uid), KEY parent (pid), ); # # Table structure for table 'tx_rkwnewsletter_domain_model_issue' # CREATE TABLE tx_rkwnewsletter_domain_model_issue ( uid int(11) NOT NULL auto_increment, pid int(11) DEFAULT '0' NOT NULL, title varchar(255) DEFAULT '' NOT NULL, introduction text NOT NULL, authors varchar(255) DEFAULT '' NOT NULL, status tinyint(4) DEFAULT '0' NOT NULL, newsletter int(11) unsigned DEFAULT '0', pages int(11) unsigned DEFAULT '0', approvals int(11) unsigned DEFAULT '0', queue_mail int(11) unsigned DEFAULT '0', info_tstamp int(11) unsigned DEFAULT '0', reminder_tstamp int(11) unsigned DEFAULT '0', release_tstamp int(11) unsigned DEFAULT '0', start_tstamp int(11) unsigned DEFAULT '0', sent_tstamp int(11) unsigned DEFAULT '0', recipients text NOT NULL, is_special int(1) unsigned DEFAULT '0' NOT NULL, tstamp int(11) unsigned DEFAULT '0' NOT NULL, crdate int(11) unsigned DEFAULT '0' NOT NULL, cruser_id int(11) unsigned DEFAULT '0' NOT NULL, PRIMARY KEY (uid), KEY parent (pid) ); # # Table structure for table 'fe_users' # CREATE TABLE fe_users ( tx_rkwnewsletter_subscription varchar(255) DEFAULT '' NOT NULL, tx_rkwnewsletter_hash varchar(255) DEFAULT '' NOT NULL, tx_rkwnewsletter_priority int(1) unsigned DEFAULT '0' NOT NULL, KEY tx_rkwnewsletter_hash (tx_rkwnewsletter_hash), KEY tx_rkwnewsletter_subscription (tx_rkwnewsletter_subscription) ); # # Table structure for table 'pages' # CREATE TABLE pages ( tx_rkwnewsletter_newsletter int(11) DEFAULT '0' NOT NULL, tx_rkwnewsletter_topic int(11) DEFAULT '0' NOT NULL, tx_rkwnewsletter_issue int(11) DEFAULT '0' NOT NULL, tx_rkwnewsletter_exclude tinyint(4) unsigned DEFAULT '0' NOT NULL, tx_rkwnewsletter_teaser_heading varchar(255) DEFAULT '' NOT NULL, tx_rkwnewsletter_teaser_text text NOT NULL, tx_rkwnewsletter_teaser_image varchar(255) DEFAULT '' NOT NULL, tx_rkwnewsletter_teaser_link varchar(255) DEFAULT '' NOT NULL, tx_rkwnewsletter_include_tstamp int(11) DEFAULT '0' NOT NULL, KEY tx_rkwnewsletter_newsletter (tx_rkwnewsletter_newsletter), KEY tx_rkwnewsletter_topic (tx_rkwnewsletter_topic), KEY tx_rkwnewsletter_issue (tx_rkwnewsletter_issue) ); # # Table structure for table 'tt_content' # CREATE TABLE tt_content ( tx_rkwnewsletter_authors varchar(255) DEFAULT '' NOT NULL, tx_rkwnewsletter_is_editorial tinyint(4) DEFAULT '0' NOT NULL, ); <file_sep><?php namespace RKW\RkwNewsletter\Tests\Integration\ViewHelpers\Mailing\Content; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Nimut\TestingFramework\TestCase\FunctionalTestCase; use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Fluid\View\StandaloneView; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Domain\Repository\TopicRepository; /** * GetEditorialViewHelperTest * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwMailer * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class GetEditorialViewHelperTest extends FunctionalTestCase { /** * @const */ const FIXTURE_PATH = __DIR__ . '/GetEditorialViewHelperTest/Fixtures'; /** * @var string[] */ protected $testExtensionsToLoad = [ 'typo3conf/ext/core_extended', 'typo3conf/ext/ajax_api', 'typo3conf/ext/accelerator', 'typo3conf/ext/persisted_sanitized_routing', 'typo3conf/ext/postmaster', 'typo3conf/ext/rkw_newsletter' ]; /** * @var string[] */ protected $coreExtensionsToLoad = [ 'seo' ]; /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository */ private $issueRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository */ private $topicRepository; /** * @var \TYPO3\CMS\Fluid\View\StandaloneView */ private $standAloneViewHelper; /** * @var \TYPO3\CMS\Extbase\Object\ObjectManager */ private $objectManager; /** * Setup * @throws \Exception */ protected function setUp(): void { parent::setUp(); $this->importDataSet(self::FIXTURE_PATH . '/Database/Global.xml'); $this->setUpFrontendRootPage( 1, [ 'EXT:core_extended/Configuration/TypoScript/setup.typoscript', 'EXT:postmaster/Configuration/TypoScript/setup.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/setup.typoscript', 'EXT:core_extended/Configuration/TypoScript/constants.typoscript', 'EXT:postmaster/Configuration/TypoScript/constants.typoscript', 'EXT:rkw_newsletter/Configuration/TypoScript/constants.typoscript', self::FIXTURE_PATH . '/Frontend/Configuration/Rootpage.typoscript', ] ); /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class); /** @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository issueRepository */ $this->issueRepository = $this->objectManager->get(IssueRepository::class); /** @var \RKW\RkwNewsletter\Domain\Repository\TopicRepository topicRepository */ $this->topicRepository = $this->objectManager->get(TopicRepository::class); /** @var \TYPO3\CMS\Fluid\View\StandaloneView standAloneViewHelper */ $this->standAloneViewHelper = $this->objectManager->get(StandaloneView::class); $this->standAloneViewHelper->setTemplateRootPaths( [ 0 => self::FIXTURE_PATH . '/Frontend/Templates' ] ); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsEmptyForAllTopics() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered with issue-parameter only * Then an empty value is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, ] ); $result = trim($this->standAloneViewHelper->render()); self::assertEmpty($result); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsEmptyIfOneTopicUsedButNoEditorial() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered with issue-parameter and topic-parameter with topic A * Then an empty value is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(10); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage ] ); $result = trim($this->standAloneViewHelper->render()); self::assertEmpty($result); } /** * @test * @throws \Exception * @throws \TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException */ public function itReturnsContentIfOneTopicUsedAndEditorial() { /** * Scenario: * * Given the ViewHelper is used in a template * Given a persisted newsletter-object X * Given a persisted issue-object Y that belongs to the newsletter-object X * Given a persisted topic-object A that belongs to the newsletter-object X * Given a persisted topic-object B that belongs to the newsletter-object X * Given a persisted page-object Q * Given that page-object Q belongs to the newsletter-object X * Given that page-object Q belongs to the issue-object Y * Given that page-object Q belongs to the topic-object A * Given the page-object Q contains four content-objects * Given none of the content-objects is an editorial * Given that page-object R belongs to the newsletter-object X * Given that page-object R belongs to the issue-object Y * Given that page-object R belongs to the topic-object B * Given the page-object R contains three content-objects * Given one of the content-objects is an editorial * When the ViewHelper is rendered with issue-parameter and topic-parameter with topic B * Then the editorial of topic B is returned */ $this->importDataSet(static::FIXTURE_PATH . '/Database/Check10.xml'); /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ $issue = $this->issueRepository->findByUid(10); /** @var \RKW\RkwNewsletter\Domain\Model\Topic $topic */ $topic = $this->topicRepository->findByUid(11); /** @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage */ $objectStorage = new ObjectStorage(); $objectStorage->attach($topic); $this->standAloneViewHelper->setTemplate('Check10.html'); $this->standAloneViewHelper->assignMultiple( [ 'issue' => $issue, 'topics' => $objectStorage ] ); $result = trim($this->standAloneViewHelper->render()); self::assertEquals('Content 11.1', $result); } //============================================= /** * TearDown */ protected function tearDown(): void { parent::tearDown(); } } <file_sep><?php namespace RKW\RkwNewsletter\Manager; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Model\Approval; use RKW\RkwNewsletter\Domain\Model\Issue; use RKW\RkwNewsletter\Domain\Model\Pages; use RKW\RkwNewsletter\Domain\Model\Topic; use RKW\RkwNewsletter\Domain\Repository\ApprovalRepository; use RKW\RkwNewsletter\Domain\Repository\BackendUserRepository; use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Permissions\PagePermissions; use RKW\RkwNewsletter\Status\ApprovalStatus; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Core\Authentication\BackendUserAuthentication; use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager; use TYPO3\CMS\Extbase\SignalSlot\Dispatcher; /** * ApprovalManager * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class ApprovalManager implements \TYPO3\CMS\Core\SingletonInterface { /** * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected IssueRepository $issueRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\ApprovalRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected ApprovalRepository $approvalRepository; /** * @var \RKW\RkwNewsletter\Domain\Repository\BackendUserRepository * @TYPO3\CMS\Extbase\Annotation\Inject */ protected BackendUserRepository $backendUserRepository; /** * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PersistenceManager $persistenceManager; /** * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher * @TYPO3\CMS\Extbase\Annotation\Inject */ protected Dispatcher $signalSlotDispatcher; /** * @var \RKW\RkwNewsletter\Permissions\PagePermissions * @TYPO3\CMS\Extbase\Annotation\Inject */ protected PagePermissions $pagePermissions; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * @const string */ const SIGNAL_FOR_SENDING_MAIL_APPROVAL = 'sendMailApproval'; /** * @const string */ const SIGNAL_FOR_SENDING_MAIL_APPROVAL_AUTOMATIC = 'sendMailApprovalAutomatic'; /** * Creates an approval for the given topic * * @param \RKW\RkwNewsletter\Domain\Model\Topic $topic * @param \RKW\RkwNewsletter\Domain\Model\Issue $issue * @param \RKW\RkwNewsletter\Domain\Model\Pages $page * @return \RKW\RkwNewsletter\Domain\Model\Approval * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function createApproval (Topic $topic, Issue $issue, Pages $page): Approval { /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ $approval = GeneralUtility::makeInstance(Approval::class); $approval->setTopic($topic); $approval->setPage($page); $this->approvalRepository->add($approval); $issue->addApprovals($approval); $this->issueRepository->update($issue); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Created approval for topic with id=%s of issue with id=%s.', $topic->getUid(), $issue->getUid() ) ); return $approval; } /** * Increases the level of the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Approval Approval $approval * @return bool * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function increaseLevel (Approval $approval): bool { $stage = ApprovalStatus::getStage($approval); if (ApprovalStatus::increaseLevel($approval)) { $this->approvalRepository->update($approval); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Increased level for approval id=%s in approval-stage %s.', $approval->getUid(), $stage ) ); return true; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Did not increase level for approval id=%s.', $approval->getUid() ) ); return false; } /** * Increases the current stage * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return bool * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException */ public function increaseStage (Approval $approval): bool { $stage = ApprovalStatus::getStage($approval); $backendUser = null; // check if triggered via backend if ( ($GLOBALS['BE_USER'] instanceof BackendUserAuthentication) && ($backendUserId = intval($GLOBALS['BE_USER']->user['uid'])) ) { /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser */ $backendUser = $this->backendUserRepository->findByUid($backendUserId); } if (ApprovalStatus::increaseStage($approval, $backendUser)) { $this->approvalRepository->update($approval); $this->persistenceManager->persistAll(); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Increased stage for approval id=%s in approval-stage %s.', $approval->getUid(), $stage ) ); return true; } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Did not increase stage for approval id=%s.', $approval->getUid() ) ); return false; } /** * Get the email-recipients for the approval based in the current stage * * @param Approval $approval * @return array */ public function getMailRecipients (Approval $approval): array { $mailRecipients = []; $stage = ApprovalStatus::getStage($approval); if ($stage == ApprovalStatus::STAGE1) { if (count($approval->getTopic()->getApprovalStage1()) > 0) { /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $beUser */ foreach ($approval->getTopic()->getApprovalStage1()->toArray() as $beUser) { if (GeneralUtility::validEmail($beUser->getEmail())) { $mailRecipients[] = $beUser; } } } } if ($stage == ApprovalStatus::STAGE2) { if (count($approval->getTopic()->getApprovalStage2()) > 0) { /** @var \RKW\RkwNewsletter\Domain\Model\BackendUser $beUser */ foreach ($approval->getTopic()->getApprovalStage2()->toArray() as $beUser) { if (GeneralUtility::validEmail($beUser->getEmail())) { $mailRecipients[] = $beUser; } } } } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Found %s recipients for approval id=%s in approval-stage %s.', count($mailRecipients), $approval->getUid(), $stage ) ); return $mailRecipients; } /** * Send info-mails or reminder-mails for outstanding confirmations * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return int * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException */ public function sendMails(Approval $approval): int { $stage = ApprovalStatus::getStage($approval); $level = ApprovalStatus::getLevel($approval); $isReminder = ($level == ApprovalStatus::LEVEL2); // get recipients - but only if stage and level match AND if valid recipients are found if ( (count($recipients = $this->getMailRecipients($approval))) && ($stage != ApprovalStatus::STAGE_DONE) ){ if ($level != ApprovalStatus::LEVEL_DONE) { // Signal for e.g. E-Mails $this->signalSlotDispatcher->dispatch( __CLASS__, self::SIGNAL_FOR_SENDING_MAIL_APPROVAL, [$recipients, $approval, $stage, $isReminder] ); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Sending email for approval with id=%s in approval-stage %s and level %s.', $approval->getUid(), $stage, $level ) ); return 1; } else { // Signal for e.g. E-Mails $this->signalSlotDispatcher->dispatch( __CLASS__, self::SIGNAL_FOR_SENDING_MAIL_APPROVAL_AUTOMATIC, [$recipients, $approval, $stage, $isReminder] ); $this->getLogger()->log( LogLevel::INFO, sprintf( 'Sending email for automatic confirmation for approval with id=%s in approval-stage %s and level %s.', $approval->getUid(), $stage, $level ) ); return 2; } } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Approval with id=%s in approval-stage %s has no mail-recipients.', $approval->getUid(), $stage ) ); return 0; } /** * Send email for given approval or directly increase its stage * * @param \RKW\RkwNewsletter\Domain\Model\Approval $approval * @return bool * @throws \RKW\RkwNewsletter\Exception * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException */ public function processConfirmation(Approval $approval): bool { // if the value 1 is returned, we simply increase the level if ($this->sendMails($approval) == 1) { $this->increaseLevel($approval); $this->pagePermissions->setPermissions($approval->getPage()); return true; } // if we reach this point, the approval has timed-out ($this->sendMails returns 2) // OR the approval has no recipients ($this->sendMails returns 0) // in that case we increase the stage $this->increaseStage($approval); $this->pagePermissions->setPermissions($approval->getPage()); return false; } /** * Processes all approvals * * @param int $toleranceLevel2 * @param int $toleranceLevel1 * @param int $toleranceStage1 * @param int $toleranceStage2 * @return int * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException * @throws \RKW\RkwNewsletter\Exception */ public function processAllConfirmations ( int $toleranceLevel1, int $toleranceLevel2, int $toleranceStage1 = 0, int $toleranceStage2 = 0 ): int { $approvalList = $this->approvalRepository->findAllForConfirmationByTolerance( $toleranceLevel1, $toleranceLevel2, $toleranceStage1, $toleranceStage2 ); if (count($approvalList)) { /** @var \RKW\RkwNewsletter\Domain\Model\Approval $approval */ foreach ($approvalList as $approval) { $this->processConfirmation($approval); } } $this->getLogger()->log( LogLevel::DEBUG, sprintf( 'Processed %s approvals.', count($approvalList) ) ); return count($approvalList); } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger(): Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } } <file_sep><?php namespace RKW\RkwNewsletter\Command; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use RKW\RkwNewsletter\Domain\Repository\IssueRepository; use RKW\RkwNewsletter\Mailing\MailProcessor; use RKW\RkwNewsletter\Manager\IssueManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use TYPO3\CMS\Core\Log\Logger; use TYPO3\CMS\Core\Log\LogLevel; use TYPO3\CMS\Core\Log\LogManager; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * class BuildNewslettersCommand * * Execute on CLI with: 'vendor/bin/typo3 rkw_newsletter:buildNewsletters' * * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class BuildNewslettersCommand extends Command { /** * issueRepository * * @var \RKW\RkwNewsletter\Domain\Repository\IssueRepository|null */ protected ?IssueRepository $issueRepository = null; /** * MailProcessor * * @var \RKW\RkwNewsletter\Mailing\MailProcessor|null */ protected ?MailProcessor $mailProcessor = null; /** * @var \TYPO3\CMS\Core\Log\Logger|null */ protected ?Logger $logger = null; /** * Configure the command by defining the name, options and arguments */ protected function configure(): void { $this->setDescription('Creates mails for all released newsletters.') ->addOption( 'newsletterLimit', 'l', InputOption::VALUE_REQUIRED, 'Maximum number of newsletters to process on each call (default: 5)', 5 ) ->addOption( 'recipientsPerNewsletterLimit', 'r', InputOption::VALUE_REQUIRED, 'Maximum number of recipients per newsletters to process on each call (default: 50)', 50 ) ->addOption( 'sleep', 's', InputOption::VALUE_REQUIRED, 'How many seconds the script should sleep after each run (default: 10)', 10 ); } /** * Initializes the command after the input has been bound and before the input * is validated. * * This is mainly useful when a lot of commands extends one main command * where some things need to be initialized based on the input arguments and options. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @see \Symfony\Component\Console\Input\InputInterface::bind() * @see \Symfony\Component\Console\Input\InputInterface::validate() */ protected function initialize(InputInterface $input, OutputInterface $output): void { /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */ $objectManager = GeneralUtility::makeInstance(ObjectManager::class); $this->issueRepository = $objectManager->get(IssueRepository::class); $this->mailProcessor = $objectManager->get(MailProcessor::class); } /** * Executes the command for showing sys_log entries * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return int * @see \Symfony\Component\Console\Input\InputInterface::bind() * @see \Symfony\Component\Console\Input\InputInterface::validate() */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title($this->getDescription()); $newsletterLimit = $input->getOption('newsletterLimit'); $recipientsPerNewsletterLimit = $input->getOption('recipientsPerNewsletterLimit'); $sleep = $input->getOption('sleep'); $result = 0; try { $issues = $this->issueRepository->findAllToSend($newsletterLimit); if (count($issues)) { /** @var \RKW\RkwNewsletter\Domain\Model\Issue $issue */ foreach ($issues as $issue) { $this->mailProcessor->setIssue($issue); $this->mailProcessor->setRecipients(); $this->mailProcessor->sendMails($recipientsPerNewsletterLimit); usleep(intval($sleep * 1000000)); } } else { $message = 'No issues to build.'; $io->note($message); $this->getLogger()->log(LogLevel::INFO, $message); } } catch (\Exception $e) { $message = sprintf('An unexpected error occurred while trying to update the statistics of e-mails: %s', str_replace(array("\n", "\r"), '', $e->getMessage()) ); $io->error($message); $this->getLogger()->log(LogLevel::ERROR, $message); $result = 1; } $io->writeln('Done'); return $result; } /** * Returns logger instance * * @return \TYPO3\CMS\Core\Log\Logger */ protected function getLogger(): Logger { if (!$this->logger instanceof Logger) { $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); } return $this->logger; } } <file_sep><?php namespace RKW\RkwNewsletter\Domain\Model; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * Topic * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @copyright RKW Kompetenzzentrum * @package RKW_RkwNewsletter * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later */ class Topic extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * @var string */ protected string $name = ''; /** * @var string */ protected string $shortDescription = ''; /** * @var \RKW\RkwNewsletter\Domain\Model\Pages|null */ protected ?Pages $containerPage = null; /** * @var \RKW\RkwNewsletter\Domain\Model\Newsletter|null */ protected ?Newsletter $newsletter = null; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser>|null */ protected ?ObjectStorage $approvalStage1 = null; /** * approvalStage2 * * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser>|null */ protected ?ObjectStorage $approvalStage2 = null; /** * @var bool */ protected bool $isSpecial = false; /** * @var int */ protected int $sorting = 0; /** * __construct */ public function __construct() { //Do not remove the next line: It would break the functionality $this->initStorageObjects(); } /** * Initializes all ObjectStorage properties * Do not modify this method! * It will be rewritten on each save in the extension builder * You may modify the constructor of this class instead * * @return void */ protected function initStorageObjects(): void { $this->approvalStage1 = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); $this->approvalStage2 = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); } /** * Returns the name * * @return string $name */ public function getName(): string { return $this->name; } /** * Sets the name * * @param string $name * @return void */ public function setName(string $name): void { $this->name = $name; } /** * Returns the shortDescription * * @return string */ public function getShortDescription(): string { return $this->shortDescription; } /** * Sets the shortDescription * * @param string $shortDescription * @return void */ public function setShortDescription(string $shortDescription): void { $this->shortDescription = $shortDescription; } /** * Returns the containerPage * * @return \RKW\RkwNewsletter\Domain\Model\Pages|null $containerPage */ public function getContainerPage():? Pages { return $this->containerPage; } /** * Sets the containerPage * * @param \RKW\RkwNewsletter\Domain\Model\Pages $containerPage * @return void */ public function setContainerPage(Pages $containerPage): void { $this->containerPage = $containerPage; } /** * Returns the newsletter * * @return \RKW\RkwNewsletter\Domain\Model\Newsletter|null $newsletter */ public function getNewsletter():? Newsletter { return $this->newsletter; } /** * Sets the newsletter * * @param \RKW\RkwNewsletter\Domain\Model\Newsletter $newsletter * @return void */ public function setNewsletter(Newsletter $newsletter): void { $this->newsletter = $newsletter; } /** * Adds a backend user to the topic * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void * @api */ public function addApprovalStage1(BackendUser $backendUser): void { $this->approvalStage1->attach($backendUser); } /** * Removes a backend user from the topic * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void * @api */ public function removeApprovalStage1(BackendUser $backendUser): void { $this->approvalStage1->detach($backendUser); } /** * Returns the backend user. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser> * @api */ public function getApprovalStage1(): ObjectStorage { return $this->approvalStage1; } /** * Sets the backend user. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser> $backendUser * @return void * @api */ public function setApprovalStage1(ObjectStorage $backendUser): void { $this->approvalStage1 = $backendUser; } /** * Adds a backend user to the topic * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void * @api */ public function addApprovalStage2(BackendUser $backendUser): void { $this->approvalStage2->attach($backendUser); } /** * Removes a backend user from the topic * * @param \RKW\RkwNewsletter\Domain\Model\BackendUser $backendUser * @return void * @api */ public function removeApprovalStage2(BackendUser $backendUser): void { $this->approvalStage2->detach($backendUser); } /** * Returns the backend user. * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser> * @api */ public function getApprovalStage2(): ObjectStorage { return $this->approvalStage2; } /** * Sets the backend user. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\RKW\RkwNewsletter\Domain\Model\BackendUser> $backendUser * @return void * @api */ public function setApprovalStage2(ObjectStorage $backendUser): void { $this->approvalStage2 = $backendUser; } /** * Returns the isSpecial * * @return bool $isSpecial */ public function getIsSpecial(): bool { return $this->isSpecial; } /** * Sets the isSpecial * * @param bool $isSpecial * @return void */ public function setIsSpecial(bool $isSpecial): void { $this->isSpecial = $isSpecial; } /** * Returns the sorting * * @return int $sorting */ public function getSorting(): int { return $this->sorting; } /** * Sets the sorting * * @param int $sorting * @return void */ public function setSorting(int $sorting): void { $this->sorting = $sorting; } } <file_sep><?php return [ 'ctrl' => [ 'hideTable' => true, 'title' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue', 'label' => 'title', 'tstamp' => 'tstamp', 'crdate' => 'crdate', 'cruser_id' => 'cruser_id', 'dividers2tabs' => true, 'searchFields' => 'name, introduction, authors, status, pages, newsletter, pages_approval, allowed_by_user, info_tstamp, reminder_tstamp, allowed_tstamp, start_tstamp, sent_tstamp', 'iconfile' => 'EXT:rkw_newsletter/Resources/Public/Icons/tx_rkwnewsletter_domain_model_issue.gif', // @todo only needed for TYPO3 8.7 'security' => [ 'ignoreRootLevelRestriction' => true, ], ], 'interface' => [ 'showRecordFieldList' => 'title, introduction, authors, status, release_tstamp, start_tstamp, sent_tstamp', ], 'types' => [ '1' => ['showitem' => 'title, introduction, authors, status, release_tstamp, start_tstamp, sent_tstamp'], ], 'palettes' => [ '1' => ['showitem' => ''], ], 'columns' => [ 'title' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.title', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'introduction' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.introduction', 'config' => [ 'type' => 'text', 'cols' => '40', 'rows' => '15', 'eval' => 'trim', 'enableRichtext' => true ], ], 'authors' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.authors', 'config' => [ 'type' => 'select', 'renderType' => 'selectMultipleSideBySide', 'foreign_table' => 'tx_rkwauthors_domain_model_authors', 'foreign_table_where' => 'AND tx_rkwauthors_domain_model_authors.internal = 1 AND ((\'###PAGE_TSCONFIG_IDLIST###\' <> \'0\' AND FIND_IN_SET(tx_rkwauthors_domain_model_authors.pid,\'###PAGE_TSCONFIG_IDLIST###\')) OR (\'###PAGE_TSCONFIG_IDLIST###\' = \'0\')) AND tx_rkwauthors_domain_model_authors.sys_language_uid = ###REC_FIELD_sys_language_uid### ORDER BY tx_rkwauthors_domain_model_authors.last_name ASC', 'maxitems' => 1, 'minitems' => 0, 'size' => 5, ] ], 'status' => [ 'exclude' => true, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.status', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'items' => [ ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_issue.status.issue', '0'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_issue.status.approval', '1'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_issue.status.ready', '2'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_issue.status.sending', '3'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_issue.status.sent', '4'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_issue.status.deferred', '98'], ['LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_issue.status.error', '99'], ], 'size' => 1, 'eval' => 'int, required', 'minitems' => 0, 'maxitems' => 1, ], ], 'info_tstamp' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.info_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, 'readOnly' => true ], ], 'reminder_tstamp' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.reminder_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, 'readOnly' => true ], ], 'release_tstamp' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.release_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => 1, 'readOnly' => true ], ], 'start_tstamp' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.start_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => true, 'readOnly' => true ], ], 'sent_tstamp' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.sent_tstamp', 'config' => [ 'type' => 'input', 'renderType' => 'inputDateTime', 'size' => 10, 'eval' => 'datetime', 'checkbox' => true, 'readOnly' => true ], ], 'pages' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.pages', 'config' => [ 'type' => 'inline', 'internal_type' => 'db', 'foreign_table' => 'pages', 'foreign_field' => 'tx_rkwnewsletter_issue', 'foreign_sortby' => 'sorting', 'show_thumbs' => true, 'minitems' => 0, 'maxitems' => 9999, 'size' => 5, 'readOnly' => true, 'appearance' => [ 'elementBrowserType' => 'db', 'useSortable' => false, 'showPossibleLocalizationRecords' => false, 'showRemovedLocalizationRecords' => false, 'showSynchronizationLink' => false, 'showAllLocalizationLink' => false, 'enabledControls' => [ 'info' => true, 'new' => false, 'dragdrop' => false, 'sort' => false, 'hide' => false, 'delete' => false, 'localize' => false, ], ], ], ], 'approvals' => [ 'exclude' => false, 'label' => 'LLL:EXT:rkw_newsletter/Resources/Private/Language/locallang_db.xlf:tx_rkwnewsletter_domain_model_issue.approvals', 'config' => [ 'type' => 'inline', 'internal_type' => 'db', 'foreign_table' => 'tx_rkwnewsletter_domain_model_approval', 'foreign_field' => 'issue', //'foreign_sortby' => 'sorting', 'show_thumbs' => true, 'minitems' => 0, 'maxitems' => 9999, 'size' => 5, 'readOnly' => true, 'appearance' => [ 'elementBrowserType' => 'db', 'useSortable' => false, 'showPossibleLocalizationRecords' => false, 'showRemovedLocalizationRecords' => false, 'showSynchronizationLink' => false, 'showAllLocalizationLink' => false, 'enabledControls' => [ 'info' => true, 'new' => false, 'dragdrop' => false, 'sort' => false, 'hide' => false, 'delete' => false, 'localize' => false, ], ], ], ], 'recipients' => [ 'config' => [ 'type' => 'passthrough', ], ], 'is_special' => [ 'config' => [ 'type' => 'passthrough', ], ], 'newsletter' => [ 'config' => [ 'type' => 'passthrough', 'foreign_table' => 'tx_rkwnewsletter_domain_model_newsletter', ], ], 'queue_mail' => [ 'config' => [ 'type' => 'passthrough', 'foreign_table' => 'tx_postmaster_domain_model_queuemail', ], ], ], ];
35c28881c5384d9846df14e32d3332920da73f69
[ "Markdown", "SQL", "PHP" ]
70
PHP
RKWKomZe/RkwNewsletter
ec97c8046ee9004d72158c44ef4aa6bc7d816690
a942183d7527f18486378b346be7db5ad868a27b
refs/heads/master
<file_sep><?php class ChangePasswordYandexDriver implements \RainLoop\Providers\ChangePassword\ChangePasswordInterface { private $pdd_token; private $host; private $url; private $domain; private $sAllowedEmails = ''; public function SetToken($token) { $this->pdd_token = $token; } public function SetHost($host) { $this->host = $host; } public function SetUrl($url) { $this->url = $url; } public function SetDomain($domain) { $this->domain = $domain; } public function SetAllowedEmails($sAllowedEmails) { $this->sAllowedEmails = $sAllowedEmails; return $this; } /** * @param \RainLoop\Account $oAccount * * @return bool */ public function PasswordChangePossibility($oAccount) { return $oAccount && $oAccount->Email() && \RainLoop\Plugins\Helper::ValidateWildcardValues($oAccount->Email(), $this->sAllowedEmails); } /** * @param \RainLoop\Account $oAccount * @param string $sPrevPassword * @param string $sNewPassword * * @return bool */ public function ChangePassword(\RainLoop\Account $oAccount, $sPrevPassword, $sNewPassword) { $bResult = false; $data = array( 'domain' => $this->domain, 'login' => $oAccount->Email(), 'password' => $<PASSWORD> ); try { $url = 'https://'.$this->host . $this->url; $header = array( 'PddToken: ' . $this->pdd_token, 'Host: ' . $this->host ); $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_ENCODING, "gzip"); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response,true); if ($result['success'] == 'ok') { $bResult = true; } else { $bResult = false; } } catch (\Exception $oException) { $bResult = false; } return $bResult; } }<file_sep>#Плагин для Rainloop Для смены пароля почты на pdd.yandex.ru <file_sep><?php class YandexChangePasswordPlugin extends \RainLoop\Plugins\AbstractPlugin { public function Init() { $this->addHook('main.fabrica', 'MainFabrica'); } /** * @param string $sName * @param mixed $oProvider */ public function MainFabrica($sName, &$oProvider) { switch ($sName) { case 'change-password': include_once __DIR__ . '/ChangePasswordYandexDriver.php'; $oProvider = new ChangePasswordYandexDriver(); $oProvider->SetToken($this->Config()->Get('plugin', 'pdd_token', '')); $oProvider->SetHost($this->Config()->Get('plugin', 'host', '')); $oProvider->SetUrl($this->Config()->Get('plugin', 'url', '')); $oProvider->SetDomain($this->Config()->Get('plugin', 'domain', '')); $oProvider->SetAllowedEmails(\strtolower(\trim($this->Config()->Get('plugin', 'allowed_emails', '')))); break; } } /** * @return array */ public function configMapping() { return array( \RainLoop\Plugins\Property::NewInstance('host')->SetLabel('yandex domain host') ->SetDefaultValue('pddimp.yandex.ru'), \RainLoop\Plugins\Property::NewInstance('pdd_token')->SetLabel('PddToken') ->SetDefaultValue(''), \RainLoop\Plugins\Property::NewInstance('url')->SetLabel('Url') ->SetDefaultValue('/api2/admin/email/edit'), \RainLoop\Plugins\Property::NewInstance('domain')->SetLabel('Domain') ->SetDefaultValue(''), \RainLoop\Plugins\Property::NewInstance('allowed_emails')->SetLabel('Allowed emails') ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) ->SetDescription('Allowed emails, space as delimiter, wildcard supported. Example: <EMAIL> <EMAIL> *@domain2.net') ->SetDefaultValue('*') ); } }
ab37d603b670bf98b168adb205d766dca4960d8c
[ "Markdown", "PHP" ]
3
PHP
uitlaber/yandex-change-password
7f44469afad9ed1e03bf7be9ae088887d178092f
741d9966c9c0e0c9af6fe0bfa724d2891edacf06
refs/heads/main
<file_sep>import { IProduct } from "./product.interface"; export interface IResponseAPI<T> { data: T; total: number; } export interface IFilterFindAll { limit?: number; skip?: number; startId?: string; } export interface IProductsApi { findAll(filters: IFilterFindAll): Promise<IResponseAPI<IProduct[]> | null>; findOne(code: number): Promise<IProduct | null>; } <file_sep><h1 align="center">Welcome to fullstack-challenge-2021-coodesh-frontend 👋</h1> <p> <img alt="Version" src="https://img.shields.io/badge/version-0.1.0-blue.svg?cacheSeconds=2592000" /> <a href="https://mit-license.org" target="_blank"> <img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" /> </a> </p> <div align="center"> <h3 align="center">Coodesh Challenge</h3> <p align="center"> an incredible project that extracts products from a web page and serves in a REST API </p> <br/> <a href="https://lab.coodesh.com/wja1/fullstack-challenge-2021?utm_source=mail&utm_medium=sendgrid&utm_campaign=website"><strong>For more information see the challenge repository</strong></a> </div> # DEMO ![Listagem de produtos](docs/images/listing.png) ![Detalhe do produto](docs/images/detail.png) --- ### Built With This section should list any major frameworks/libraries used to bootstrap your project. Leave any add-ons/plugins for the acknowledgements section. Here are a few examples. - [react.Js](https://reactjs.org/) - [chakra-ui](https://chakra-ui.com/) - [emotion](https://emotion.sh/docs/@emotion/react) - [typescript](https://www.typescriptlang.org/) - [react-router-dom](https://www.npmjs.com/package/react-router-dom) - [jest](https://jestjs.io/docs/getting-started/) - [docker](https://www.docker.com/) - [docker compose](https://docs.docker.com/compose/) ## Getting Started Instructions on setting up your project locally. To get a local copy up and running follow these simple example steps. ### Prerequisites List things you need to use the software and how to install them. #### Roadmap - [x] docker - [x] docker compose ### Installation 1. Clone and configure the repo [coodesh-fullstack-challenge-2021-api](https://github.com/wdev007/coodesh-fullstack-challenge-2021-api) 2. Change the settings files ```sh cp .env.example .env ``` ## Usage ```sh docker-compose up ``` ## Run tests ```sh yarn run test ``` ## Author 👤 **<NAME>** - Github: [@wdev007](https://github.com/wdev007) ## Show your support Give a ⭐️ if this project helped you! ## 📝 License Copyright © 2021 [<NAME>](https://github.com/wdev007).<br /> This project is [MIT](https://mit-license.org) licensed. --- _[Challenge by coodesh](https://coodesh.com/)_ <file_sep>export interface IAppContext { loading: boolean; logged: boolean; } <file_sep>import axios from "axios"; import { IProduct } from "../interfaces/product.interface"; import { SERVER_BASE_URL } from "../../../shared/utils/constants"; import { IFilterFindAll, IResponseAPI, IProductsApi, } from "../interfaces/product.service.interface"; const PRODUCTS_BASE_URL = `${SERVER_BASE_URL}/products`; const productsApi: IProductsApi = { findAll: async ({ limit, skip, }: IFilterFindAll): Promise<IResponseAPI<IProduct[]> | null> => { try { const skipUrl = skip ? `&skip=${skip}` : ""; let url = `${PRODUCTS_BASE_URL}?limit=${limit}${skipUrl}`; const { data } = await axios.get<IResponseAPI<IProduct[]>>(url); return data; } catch (error) { return null; } }, findOne: async (code: number): Promise<IProduct | null> => { try { const { data } = await axios.get<IProduct>( `${PRODUCTS_BASE_URL}/${code}` ); return data; } catch (error) { return null; } }, }; export default productsApi; <file_sep>import { ButtonProps } from "@chakra-ui/button"; const baseStyles: ButtonProps = { w: 7, fontSize: "sm", color: "white", }; export const normalStyles: ButtonProps = { ...baseStyles, _hover: { bg: "gray.300", }, bg: "gray.500", }; export const activeStyles: ButtonProps = { ...baseStyles, _hover: { bg: "gray.600", }, bg: "gray.700", }; export const separatorStyles: ButtonProps = { w: 7, bg: "gray.400", }; <file_sep>export const SERVER_BASE_URL = process.env.SERVER_BASE_URL || "http://localhost:3333"; export const APP_NAME = "ProdList"; <file_sep>import { IProduct } from "./product.interface"; import { IFilterFindAll } from "./product.service.interface"; export interface IProductsContext { products: IProduct[]; product: IProduct | undefined; total: number; findProducts(filters: IFilterFindAll): void; findOne(code: number): void; } <file_sep>export interface IProduct { code: number; barcode: string; status: string; imported_t: string; url: string; product_name: string; quantity: string; categories: string; packaging: string; brands: string; image_url: string; }
a81324bb7c5097c313b2e16a4b48ae350720ad1c
[ "Markdown", "TypeScript" ]
8
TypeScript
wdev007/coodesh-fullstack-challenge-2021-frontend
282aff9d78964100551e0acba03b21dc0be53a13
4f83abd98d207eecc2ac27231a39306197f49540
refs/heads/master
<repo_name>Compassion/SmsScheduler<file_sep>/SmsScheduler/SmsActionerTests/SmsActionerWorkflowTestFixture.cs using System; using NServiceBus.Testing; using NUnit.Framework; using Rhino.Mocks; using SmsActioner; using SmsMessages.CommonData; using SmsMessages.MessageSending.Commands; using SmsMessages.MessageSending.Events; namespace SmsActionerTests { [TestFixture] public class SmsActionerWorkflowTestFixture { // TODO: Add tests for data in messages being set [Test] public void SendSingleSmsNow_SuccessReturnedIsInvalid_HasNoDeliveryStatus() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var smsSent = new SmsSent("r", DateTime.Now); smsService.Expect(s => s.Send(sendOneMessageNow)).Return(smsSent); Test.Initialize(); Assert.That(() => Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => a.SmsService = smsService) .ExpectPublish<MessageSent>() .When(a => a.Handle(sendOneMessageNow)), Throws.Exception.With.Message.Contains("SmsSent type is invalid - followup is required to get delivery status") ); } [Test] public void SendSingleSmsNow_QueuedReturnedIsInvalid_HasNoPrice() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var smsQueued = new SmsQueued("sid"); smsService.Expect(s => s.Send(sendOneMessageNow)).Return(smsQueued); Test.Initialize(); Assert.That(() => Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => a.SmsService = smsService) .ExpectPublish<MessageSent>() .When(a => a.Handle(sendOneMessageNow)), Throws.Exception.With.Message.Contains("SmsQueued type is invalid - followup is required to get delivery status") ); } [Test] public void SendSingleSmsNow_Failure() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var smsSent = new SmsFailed("sid", "code", "message"); smsService.Expect(s => s.Send(sendOneMessageNow)).Return(smsSent); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => a.SmsService = smsService) .ExpectPublish<MessageFailedSending>() .When(a => a.Handle(sendOneMessageNow)) .AssertSagaCompletionIs(true); } [Test] public void SendSingleSmsNow_SendingThenSuccess() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var timeoutCalculator = MockRepository.GenerateMock<ITimeoutCalculator>(); var smsSending = new SmsSending("12", 0.06m); var smsSent = new SmsSent("r", DateTime.Now); smsService.Expect(s => s.Send(sendOneMessageNow)).Return(smsSending); smsService.Expect(s => s.CheckStatus(smsSending.Sid)).Return(smsSent); var timeoutTimespan = new TimeSpan(); timeoutCalculator.Expect(t => t.RequiredTimeout(Arg<int>.Is.Anything)).Return(timeoutTimespan); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.TimeoutCalculator = timeoutCalculator; }) .ExpectTimeoutToBeSetIn<SmsPendingTimeout>((timeoutMessage, timespan) => timespan == timeoutTimespan) .When(a => a.Handle(sendOneMessageNow)) .ExpectPublish<MessageSent>() .WhenSagaTimesOut() .AssertSagaCompletionIs(true); } [Test] public void SendSingleSmsNow_SendingThenFail() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var timeoutCalculator = MockRepository.GenerateMock<ITimeoutCalculator>(); const string sid = "12"; var smsSending = new SmsSending(sid, 0.06m); var smsFailed = new SmsFailed(sid, "c", "m"); smsService.Expect(s => s.Send(sendOneMessageNow)).Return(smsSending); smsService.Expect(s => s.CheckStatus(smsSending.Sid)).Return(smsFailed); var timeoutTimespan = new TimeSpan(); timeoutCalculator.Expect(t => t.RequiredTimeout(Arg<int>.Is.Anything)).Return(timeoutTimespan); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.TimeoutCalculator = timeoutCalculator; }) .ExpectTimeoutToBeSetIn<SmsPendingTimeout>((timeoutMessage, timespan) => timespan == timeoutTimespan) .When(a => a.Handle(sendOneMessageNow)) .ExpectNotPublish<MessageSent>() .WhenSagaTimesOut() .AssertSagaCompletionIs(true); } [Test] public void SendSingleSmsNow_SendingThenQueuedThenSuccess() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var timeoutCalculator = MockRepository.GenerateMock<ITimeoutCalculator>(); const string sid = "12"; var smsSending = new SmsSending(sid, 0.06m); var smsQueued = new SmsQueued(sid); var smsSuccess = new SmsSent("r", DateTime.Now); smsService.Expect(s => s.Send(sendOneMessageNow)).Return(smsSending); smsService.Expect(s => s.CheckStatus(smsQueued.Sid)).Repeat.Once().Return(smsQueued); smsService.Expect(s => s.CheckStatus(smsQueued.Sid)).Return(smsSuccess); var timeoutTimespan = new TimeSpan(); timeoutCalculator.Expect(t => t.RequiredTimeout(Arg<int>.Is.Anything)).Return(timeoutTimespan); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.TimeoutCalculator = timeoutCalculator; }) .ExpectTimeoutToBeSetIn<SmsPendingTimeout>((timeoutMessage, timespan) => timespan == timeoutTimespan) .When(a => a.Handle(sendOneMessageNow)) .ExpectNotPublish<MessageSent>() .ExpectTimeoutToBeSetIn<SmsPendingTimeout>((timeoutMessage, timespan) => timespan == timeoutTimespan) .WhenSagaTimesOut() .ExpectPublish<MessageSent>() .WhenSagaTimesOut(); } [Test] public void SmsSentUsesUtc() { var now = DateTime.Now; var smsConfirmationData = new SmsConfirmationData("receipt", now, 2m); Assert.That(smsConfirmationData.SentAtUtc.Hour, Is.EqualTo(now.Hour)); Assert.That(smsConfirmationData.SentAtUtc.Minute, Is.EqualTo(now.Minute)); Assert.That(smsConfirmationData.SentAtUtc.Second, Is.EqualTo(now.Second)); Assert.That(smsConfirmationData.SentAtUtc.Kind, Is.Not.EqualTo(now.Kind)); Assert.That(smsConfirmationData.SentAtUtc.Kind, Is.EqualTo(DateTimeKind.Utc)); } } } <file_sep>/SmsScheduler/SmsScheduler/EndpointConfig.cs using NServiceBus; namespace SmsScheduler { public class EndpointConfig : IConfigureThisEndpoint, IWantCustomInitialization, AsA_Publisher { public void Init() { var configure = Configure.With() .DefaultBuilder() .DefiningCommandsAs(t => t.Namespace != null && t.Namespace.EndsWith("Commands")) .DefiningEventsAs(t => t.Namespace != null && t.Namespace.EndsWith("Events")) .DefiningMessagesAs(t => t.Namespace != null && t.Namespace.EndsWith("Messages")) .DefiningMessagesAs(t => t.Namespace == "SmsMessages") .DefiningMessagesAs(t => t.Namespace == "SmsTrackingMessages.Messages") .RunTimeoutManager() .Log4Net() .XmlSerializer() .MsmqTransport() .IsTransactional(true) .PurgeOnStartup(false) .RavenPersistence() .Sagas() .RavenSagaPersister() .UnicastBus() .ImpersonateSender(false) .LoadMessageHandlers(); // .RavenSubscriptionStorage(); Configure.Instance.Configurer.ConfigureComponent<RavenDocStore>(DependencyLifecycle.SingleInstance); configure.CreateBus().Start(); //.Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install()); } } } <file_sep>/SmsScheduler/SchedulerTests/SentLaterTestFixture.cs using System; using System.Collections.Generic; using NServiceBus; using NServiceBus.Testing; using NUnit.Framework; using Raven.Client; using Raven.Client.Embedded; using Rhino.Mocks; using SmsMessages.CommonData; using SmsMessages.MessageSending.Commands; using SmsMessages.MessageSending.Events; using SmsMessages.Scheduling.Commands; using SmsMessages.Scheduling.Events; using SmsScheduler; using SmsTrackingModels; namespace SmsSchedulerTests { [TestFixture] public class SentLaterTestFixture { public IDocumentStore DocumentStore { get; set; } public SentLaterTestFixture() { DocumentStore = new EmbeddableDocumentStore { RunInMemory = true }; DocumentStore.Initialize(); } [Test] public void ScheduleSmsForSendingLater() { var scheduleSmsForSendingLater = new ScheduleSmsForSendingLater { SendMessageAtUtc = DateTime.Now.AddDays(1), ScheduleMessageId = Guid.NewGuid() }; var sagaId = Guid.NewGuid(); var messageSent = new MessageSent { ConfirmationData = new SmsConfirmationData("a", DateTime.Now, 3), SmsData = new SmsData("1", "2") }; var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, MessageStatus = MessageStatus.WaitingForScheduling }, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, Originator = "place", OriginalMessageId = Guid.NewGuid().ToString(), OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData() } }; Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => timeout == scheduleSmsForSendingLater.SendMessageAtUtc) .When(s => s.Handle(scheduleSmsForSendingLater)) .ExpectSend<SendOneMessageNow>() .WhenSagaTimesOut() .ExpectPublish<ScheduledSmsSent>() .When(s => s.Handle(messageSent)) .AssertSagaCompletionIs(true); var scheduleTrackingData = GetSchedule(scheduleSmsForSendingLater.ScheduleMessageId.ToString()); Assert.That(scheduleTrackingData.MessageStatus, Is.EqualTo(MessageStatus.Sent)); } [Test] public void ScheduleSmsForSendingLaterButFails() { var scheduleSmsForSendingLater = new ScheduleSmsForSendingLater { SendMessageAtUtc = DateTime.Now.AddDays(1), ScheduleMessageId = Guid.NewGuid()}; var sagaId = Guid.NewGuid(); var messageFailed = new MessageFailedSending { SmsData = new SmsData("1", "2"), SmsFailed = new SmsFailed(string.Empty, string.Empty, string.Empty) }; var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, MessageStatus = MessageStatus.WaitingForScheduling }, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, Originator = "place", OriginalMessageId = Guid.NewGuid().ToString(), OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData() } }; Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => timeout == scheduleSmsForSendingLater.SendMessageAtUtc) .When(s => s.Handle(scheduleSmsForSendingLater)) .ExpectSend<SendOneMessageNow>() .WhenSagaTimesOut() .ExpectPublish<ScheduledSmsFailed>() .When(s => s.Handle(messageFailed)) .AssertSagaCompletionIs(true); var scheduleTrackingData = GetSchedule(scheduleSmsForSendingLater.ScheduleMessageId.ToString()); Assert.That(scheduleTrackingData.MessageStatus, Is.EqualTo(MessageStatus.Failed)); } [Test] public void ScheduleSmsForSendingLaterButIsPaused() { var scheduleSmsForSendingLater = new ScheduleSmsForSendingLater { SendMessageAtUtc = DateTime.Now.AddDays(1), SmsData = new SmsData("1", "2"), ScheduleMessageId = Guid.NewGuid()}; var sagaId = Guid.NewGuid(); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, MessageStatus = MessageStatus.WaitingForScheduling }, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, Originator = "place", OriginalMessageId = "one", OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData() } }; Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => timeout == scheduleSmsForSendingLater.SendMessageAtUtc) .When(s => s.Handle(scheduleSmsForSendingLater)) .ExpectPublish<MessageSchedulePaused>() .When(s => s.Handle(new PauseScheduledMessageIndefinitely(Guid.Empty))) .ExpectNotSend<SendOneMessageNow>(now => false) .WhenSagaTimesOut(); var scheduleTrackingData = GetSchedule(scheduleSmsForSendingLater.ScheduleMessageId.ToString()); Assert.That(scheduleTrackingData.MessageStatus, Is.EqualTo(MessageStatus.Paused)); } [Test] public void ScheduleSmsForSendingLaterButIsPausedThenResumedAndSent() { var scheduleSmsForSendingLater = new ScheduleSmsForSendingLater { SendMessageAtUtc = DateTime.Now.AddDays(1), SmsData = new SmsData("1", "2") }; var sagaId = Guid.NewGuid(); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, MessageStatus = MessageStatus.WaitingForScheduling }, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, Originator = "place", OriginalMessageId = Guid.NewGuid().ToString(), OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData() } }; Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => timeout == scheduleSmsForSendingLater.SendMessageAtUtc && state.TimeoutCounter == 0) .When(s => s.Handle(scheduleSmsForSendingLater)) .ExpectPublish<MessageSchedulePaused>() .When(s => s.Handle(new PauseScheduledMessageIndefinitely(Guid.Empty))) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => state.TimeoutCounter == 1) .ExpectPublish<MessageRescheduled>() .When(s => s.Handle(new ResumeScheduledMessageWithOffset(Guid.Empty, new TimeSpan()))) .ExpectNotSend<SendOneMessageNow>(now => false) .When(s => s.Timeout(new ScheduleSmsTimeout { TimeoutCounter = 0 })) .ExpectSend<SendOneMessageNow>() .When(s => s.Timeout(new ScheduleSmsTimeout { TimeoutCounter = 1 })) .ExpectPublish<ScheduledSmsSent>() .When(s => s.Handle(new MessageSent { ConfirmationData = new SmsConfirmationData("a", DateTime.Now, 3), SmsData = new SmsData("1", "2")})) .AssertSagaCompletionIs(true); var scheduleTrackingData = GetSchedule(scheduleSmsForSendingLater.ScheduleMessageId.ToString()); Assert.That(scheduleTrackingData.MessageStatus, Is.EqualTo(MessageStatus.Sent)); } [Test] public void ScheduleSmsForSendingLaterButIsPausedThenRescheduledAndSent() { var scheduleSmsForSendingLater = new ScheduleSmsForSendingLater { SendMessageAtUtc = DateTime.Now.AddDays(1), SmsData = new SmsData("1", "2"), ScheduleMessageId = Guid.NewGuid()}; var sagaId = Guid.NewGuid(); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, MessageStatus = MessageStatus.WaitingForScheduling }, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, Originator = "place", OriginalMessageId = Guid.NewGuid().ToString(), OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData() } }; Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => timeout == scheduleSmsForSendingLater.SendMessageAtUtc && state.TimeoutCounter == 0) .When(s => s.Handle(scheduleSmsForSendingLater)) .ExpectPublish<MessageSchedulePaused>() .When(s => s.Handle(new PauseScheduledMessageIndefinitely(Guid.Empty))) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => state.TimeoutCounter == 1) .ExpectPublish<MessageRescheduled>() .When(s => s.Handle(new RescheduleScheduledMessageWithNewTime(Guid.Empty, new DateTime(2040,4,4,4,4,4, DateTimeKind.Utc)))) .ExpectNotSend<SendOneMessageNow>(now => false) .When(s => s.Timeout(new ScheduleSmsTimeout { TimeoutCounter = 0 })) .ExpectSend<SendOneMessageNow>() .When(s => s.Timeout(new ScheduleSmsTimeout { TimeoutCounter = 1 })) .ExpectPublish<ScheduledSmsSent>() .When(s => s.Handle(new MessageSent { ConfirmationData = new SmsConfirmationData("a", DateTime.Now, 3), SmsData = new SmsData("1", "2")})) .AssertSagaCompletionIs(true); var scheduleTrackingData = GetSchedule(scheduleSmsForSendingLater.ScheduleMessageId.ToString()); Assert.That(scheduleTrackingData.MessageStatus, Is.EqualTo(MessageStatus.Sent)); } [Test] public void ScheduleSmsForSendingLaterButIsPausedThenResumedOutOfOrderAndSent() { var scheduleSmsForSendingLater = new ScheduleSmsForSendingLater { SendMessageAtUtc = DateTime.Now.AddDays(1), SmsData = new SmsData("1", "2"), ScheduleMessageId = Guid.NewGuid()}; var sagaId = Guid.NewGuid(); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, MessageStatus = MessageStatus.WaitingForScheduling }, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, Originator = "place", OriginalMessageId = Guid.NewGuid().ToString(), OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData() } }; Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => timeout == scheduleSmsForSendingLater.SendMessageAtUtc && state.TimeoutCounter == 0) .When(s => s.Handle(scheduleSmsForSendingLater)) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, timeout) => state.TimeoutCounter == 1) .ExpectPublish<MessageRescheduled>() .When(s => s.Handle(new ResumeScheduledMessageWithOffset(Guid.Empty, new TimeSpan()) { MessageRequestTimeUtc = DateTime.Now })) .When(s => s.Handle(new PauseScheduledMessageIndefinitely(Guid.Empty) { MessageRequestTimeUtc = DateTime.Now.AddMinutes(-10)})) .ExpectSend<SendOneMessageNow>() .When(s => s.Timeout(new ScheduleSmsTimeout { TimeoutCounter = 1})) .ExpectPublish<ScheduledSmsSent>() .When(s => s.Handle(new MessageSent { ConfirmationData = new SmsConfirmationData("a", DateTime.Now, 3), SmsData = new SmsData("1", "2") })) .AssertSagaCompletionIs(true); var scheduleTrackingData = GetSchedule(scheduleSmsForSendingLater.ScheduleMessageId.ToString()); Assert.That(scheduleTrackingData.MessageStatus, Is.EqualTo(MessageStatus.Sent)); } [Test] public void ResumePausedSchedule_Data() { var sagaId = Guid.NewGuid(); var scheduleMessageId = Guid.NewGuid(); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleMessageId, MessageStatus = MessageStatus.Paused }, scheduleMessageId.ToString()); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, ScheduleMessageId = scheduleMessageId, Originator = "place", OriginalMessageId = Guid.NewGuid().ToString(), OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData(),SendMessageAtUtc = DateTime.Now } }; Test.Initialize(); var rescheduleMessage = new ResumeScheduledMessageWithOffset(scheduleMessageId, new TimeSpan(0, 1, 0, 0)); var rescheduledTime = scheduledSmsData.OriginalMessage.SendMessageAtUtc.Add(rescheduleMessage.Offset); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, span) => span == rescheduledTime) .ExpectPublish<MessageRescheduled>() .When(s => s.Handle(rescheduleMessage)); var schedule = GetSchedule(scheduleMessageId.ToString()); Assert.That(schedule.MessageStatus, Is.EqualTo(MessageStatus.Scheduled)); Assert.That(schedule.ScheduleTimeUtc, Is.EqualTo(rescheduledTime)); } [Test] public void ReschedulePausedSchedule_Data() { var sagaId = Guid.NewGuid(); var scheduleMessageId = Guid.NewGuid(); StoreDocument(new ScheduleTrackingData { ScheduleId = scheduleMessageId, MessageStatus = MessageStatus.Paused }, scheduleMessageId.ToString()); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); var scheduledSmsData = new ScheduledSmsData { Id = sagaId, ScheduleMessageId = scheduleMessageId, Originator = "place", OriginalMessageId = Guid.NewGuid().ToString(), OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "msg"), SmsMetaData = new SmsMetaData(),SendMessageAtUtc = DateTime.Now } }; Test.Initialize(); var rescheduleMessage = new RescheduleScheduledMessageWithNewTime(scheduleMessageId, new DateTime(2040, 4, 4, 4,4,4, DateTimeKind.Utc)); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = scheduledSmsData; a.RavenDocStore = ravenDocStore; }) .ExpectTimeoutToBeSetAt<ScheduleSmsTimeout>((state, span) => span == rescheduleMessage.NewScheduleTimeUtc) .ExpectPublish<MessageRescheduled>() .When(s => s.Handle(rescheduleMessage)); var schedule = GetSchedule(scheduleMessageId.ToString()); Assert.That(schedule.MessageStatus, Is.EqualTo(MessageStatus.Scheduled)); Assert.That(schedule.ScheduleTimeUtc, Is.EqualTo(rescheduleMessage.NewScheduleTimeUtc)); } [Test] public void TimeoutPromptsMessageSending_Data() { var bus = MockRepository.GenerateMock<IBus>(); var sendOneMessageNow = new SendOneMessageNow(); bus.Expect(b => b.Send(Arg<SendOneMessageNow>.Is.NotNull)) .WhenCalled(i => sendOneMessageNow = (SendOneMessageNow)((object[])(i.Arguments[0]))[0]); var dataId = Guid.NewGuid(); var originalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("3443", "message"), SmsMetaData = new SmsMetaData { Tags = new List<string> { "a", "b" }, Topic = "topic" } }; var data = new ScheduledSmsData { Id = dataId, OriginalMessage = originalMessage}; var scheduleSms = new ScheduleSms { Bus = bus, Data = data }; var timeoutMessage = new ScheduleSmsTimeout(); scheduleSms.Timeout(timeoutMessage); Assert.That(sendOneMessageNow.SmsData, Is.EqualTo(data.OriginalMessage.SmsData)); Assert.That(sendOneMessageNow.SmsMetaData, Is.EqualTo(data.OriginalMessage.SmsMetaData)); Assert.That(sendOneMessageNow.CorrelationId, Is.EqualTo(data.Id)); bus.VerifyAllExpectations(); } [Test] public void TimeoutSendingPausedNoAction_Data() { var bus = MockRepository.GenerateStrictMock<IBus>(); var dataId = Guid.NewGuid(); var originalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("3443", "message"), SmsMetaData = new SmsMetaData { Tags = new List<string> { "a", "b" }, Topic = "topic" } }; var data = new ScheduledSmsData { Id = dataId, OriginalMessage = originalMessage, SchedulingPaused = true }; var scheduleSms = new ScheduleSms { Bus = bus, Data = data }; var timeoutMessage = new ScheduleSmsTimeout(); scheduleSms.Timeout(timeoutMessage); bus.VerifyAllExpectations(); } [Test] public void OriginalMessageGetsSavedToSaga_Data() { var data = new ScheduledSmsData(); var originalMessage = new ScheduleSmsForSendingLater { SendMessageAtUtc = DateTime.Now }; StoreDocument(new ScheduleTrackingData { ScheduleId = originalMessage.ScheduleMessageId, MessageStatus = MessageStatus.WaitingForScheduling}, originalMessage.ScheduleMessageId.ToString()); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = data; a.RavenDocStore = ravenDocStore; }) .WhenReceivesMessageFrom("address") .ExpectPublish<SmsScheduled>(m => m.CoordinatorId == data.Id && m.ScheduleMessageId == originalMessage.ScheduleMessageId) .When(s => s.Handle(originalMessage)); Assert.That(data.OriginalMessage, Is.EqualTo(originalMessage)); var schedule = GetSchedule(originalMessage.ScheduleMessageId.ToString()); Assert.That(schedule.MessageStatus, Is.EqualTo(MessageStatus.Scheduled)); } [Test] public void PauseMessageSetsSchedulePauseFlag_Data() { var data = new ScheduledSmsData { OriginalMessage = new ScheduleSmsForSendingLater { SmsData = new SmsData("1", "2")}}; var scheduleId = Guid.NewGuid(); var pauseScheduledMessageIndefinitely = new PauseScheduledMessageIndefinitely(scheduleId); StoreDocument(new ScheduleTrackingData { ScheduleId = data.OriginalMessage.ScheduleMessageId, MessageStatus = MessageStatus.Scheduled}, data.OriginalMessage.ScheduleMessageId.ToString()); var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore().OpenSession("SmsTracking")).Return(DocumentStore.OpenSession()); Test.Initialize(); Test.Saga<ScheduleSms>() .WithExternalDependencies(a => { a.Data = data; a.RavenDocStore = ravenDocStore; }) .WhenReceivesMessageFrom("place") .When(s => s.Handle(pauseScheduledMessageIndefinitely)); Assert.IsTrue(data.SchedulingPaused); var schedule = GetSchedule(data.OriginalMessage.ScheduleMessageId.ToString()); Assert.That(schedule.MessageStatus, Is.EqualTo(MessageStatus.Paused)); } private void StoreDocument(object obj, string id) { using (var session = DocumentStore.OpenSession()) { session.Store(obj, id); session.SaveChanges(); } } private ScheduleTrackingData GetSchedule(string id) { using (var session = DocumentStore.OpenSession()) { return session.Load<ScheduleTrackingData>(id); } } } }<file_sep>/SmsScheduler/ConfigurationModels/MailGunConfiguration.cs using System.ComponentModel.DataAnnotations; namespace ConfigurationModels { public class MailgunConfiguration { [Required] public string ApiKey { get; set; } [Required] public string DomainName { get; set; } [Required] public string DefaultFrom { get; set; } } }<file_sep>/SmsScheduler/SmsWeb/Controllers/CoordinatorModelToMessageMapping.cs using System; using System.Collections.Generic; using System.Linq; using ConfigurationModels; using SmsMessages.CommonData; using SmsMessages.Coordinator.Commands; using SmsWeb.Models; namespace SmsWeb.Controllers { public interface ICoordinatorModelToMessageMapping { TrickleSmsOverCalculatedIntervalsBetweenSetDates MapToTrickleOverPeriod(CoordinatedSharedMessageModel model, CountryCodeReplacement countryCodeReplacement, List<string> excludedNumbers); TrickleSmsWithDefinedTimeBetweenEachMessage MapToTrickleSpacedByPeriod(CoordinatedSharedMessageModel model, CountryCodeReplacement countryCodeReplacement, List<string> excludedNumbers); SendAllMessagesAtOnce MapToSendAllAtOnce(CoordinatedSharedMessageModel coordinatedSharedMessageModel, CountryCodeReplacement countryCodeReplacement, List<string> excludedNumbers); } public class CoordinatorModelToMessageMapping : ICoordinatorModelToMessageMapping { public CoordinatorModelToMessageMapping(IDateTimeUtcFromOlsenMapping dateTimeUtcFromOlsenMapping) { DateTimeOlsenMapping = dateTimeUtcFromOlsenMapping; } private IDateTimeUtcFromOlsenMapping DateTimeOlsenMapping { get; set; } public TrickleSmsOverCalculatedIntervalsBetweenSetDates MapToTrickleOverPeriod(CoordinatedSharedMessageModel model, CountryCodeReplacement countryCodeReplacement, List<string> excludedNumbers) { return new TrickleSmsOverCalculatedIntervalsBetweenSetDates { Duration = model.SendAllBy.Value.Subtract(model.StartTime), Messages = model .GetCleanInternationalisedNumbers(countryCodeReplacement) .Where(n => !excludedNumbers.Contains(n)) .Select(n => new SmsData(n, model.Message)) .ToList(), StartTimeUtc = DateTimeOlsenMapping.DateTimeWithOlsenZoneToUtc(model.StartTime, model.UserTimeZone), // startTimeUtc,// model.StartTime.ToUniversalTime(), MetaData = new SmsMetaData { Tags = model.GetTagList(), Topic = model.Topic }, ConfirmationEmail = model.ConfirmationEmail, ConfirmationEmails = model.GetEmailList(), UserOlsenTimeZone = model.UserTimeZone }; } public TrickleSmsWithDefinedTimeBetweenEachMessage MapToTrickleSpacedByPeriod(CoordinatedSharedMessageModel model, CountryCodeReplacement countryCodeReplacement, List<string> excludedNumbers) { return new TrickleSmsWithDefinedTimeBetweenEachMessage { Messages = model .GetCleanInternationalisedNumbers(countryCodeReplacement) .Where(n => !excludedNumbers.Contains(n)) .Select(n => new SmsData(n, model.Message)) .ToList(), StartTimeUtc = DateTimeOlsenMapping.DateTimeWithOlsenZoneToUtc(model.StartTime, model.UserTimeZone), TimeSpacing = TimeSpan.FromSeconds(model.TimeSeparatorSeconds.Value), MetaData = new SmsMetaData { Tags = model.GetTagList(), Topic = model.Topic }, ConfirmationEmail = model.ConfirmationEmail, ConfirmationEmails = model.GetEmailList(), UserOlsenTimeZone = model.UserTimeZone }; } public SendAllMessagesAtOnce MapToSendAllAtOnce(CoordinatedSharedMessageModel model, CountryCodeReplacement countryCodeReplacement, List<string> excludedNumbers) { return new SendAllMessagesAtOnce { Messages = model .GetCleanInternationalisedNumbers(countryCodeReplacement) .Where(n => !excludedNumbers.Contains(n)) .Select(n => new SmsData(n, model.Message)) .ToList(), SendTimeUtc = DateTimeOlsenMapping.DateTimeWithOlsenZoneToUtc(model.StartTime, model.UserTimeZone), MetaData = new SmsMetaData { Tags = model.GetTagList(), Topic = model.Topic }, ConfirmationEmail = model.ConfirmationEmail, ConfirmationEmails = model.GetEmailList(), UserOlsenTimeZone = model.UserTimeZone }; } } }<file_sep>/SmsScheduler/SmsWeb/Models/CoordinatedSharedMessageModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using ConfigurationModels; using SmsMessages.Coordinator.Commands; namespace SmsWeb.Models { public class CoordinatedSharedMessageModel { public CoordinatedSharedMessageModel() { CoordinatorsToExclude = new List<Guid>(); } [Required] public string Numbers { get; set; } [Required] public string Message { get; set; } [Required] public DateTime StartTime { get; set; } [Required] public string UserTimeZone { get; set; } public int? TimeSeparatorSeconds { get; set; } public DateTime? SendAllBy { get; set; } public bool? SendAllAtOnce { get; set; } public string Tags { get; set; } public string Topic { get; set; } public string ConfirmationEmail { get; set; } public List<Guid> CoordinatorsToExclude { get; set; } public List<string> GetTagList() { return string.IsNullOrWhiteSpace(Tags) ? null : Tags.Split(new[] { ',', ';', ':' }).ToList().Select(t => t.Trim()).ToList(); } public List<string> GetEmailList() { return string.IsNullOrWhiteSpace(ConfirmationEmail) ? null : ConfirmationEmail.Split(new[] {',', ';', ':'}).ToList().Select(t => t.Trim()).ToList(); } public List<string> GetCleanInternationalisedNumbers(CountryCodeReplacement countryCodeReplacement) { return Numbers.Split(new[] { ',', ';', ':' }).Select(number => countryCodeReplacement != null ? countryCodeReplacement.CleanAndInternationaliseNumber(number) : number.Trim()).ToList(); } public bool IsMessageTypeValid() { try { GetMessageTypeFromModel(); return true; } catch { return false; } } // TODO : Add tests for this method public Type GetMessageTypeFromModel() { Type requestType = typeof(object); var trueCount = 0; if (SendAllBy.HasValue) { requestType = typeof(TrickleSmsOverCalculatedIntervalsBetweenSetDates); trueCount++; } if (TimeSeparatorSeconds.HasValue) { requestType = typeof(TrickleSmsWithDefinedTimeBetweenEachMessage); trueCount++; } if (SendAllAtOnce.GetValueOrDefault() || Numbers.Split(',').Count() == 1) { requestType = typeof(SendAllMessagesAtOnce); trueCount++; } if (trueCount != 1) throw new ArgumentException("Cannot determine which message type to send"); return requestType; } } }<file_sep>/SmsScheduler/SmsMessages/CommonData/MessageStatus.cs namespace SmsMessages.CommonData { public enum MessageStatus { WaitingForScheduling, Scheduled, Sent, Paused, Cancelled, Failed } }<file_sep>/SmsScheduler/SmsActioner/EndpointConfig.cs using NServiceBus; namespace SmsActioner { public class EndpointConfig : IConfigureThisEndpoint, IWantCustomInitialization, AsA_Publisher { public void Init() { var configure = Configure.With() .DefaultBuilder() .DefiningCommandsAs(t => t.Namespace != null && t.Namespace.EndsWith("Commands")) .DefiningEventsAs(t => t.Namespace != null && t.Namespace.EndsWith("Events")) .RunTimeoutManager() .Log4Net() .XmlSerializer() .MsmqTransport() .IsTransactional(true) .PurgeOnStartup(false) .RavenPersistence() .Sagas() .RavenSagaPersister() .UnicastBus() .ImpersonateSender(false) .LoadMessageHandlers(); const string listeningOn = "http://*:8888/"; var appHost = new AppHost(); appHost.Init(); appHost.Start(listeningOn); Configure.Instance.Configurer.ConfigureComponent<RavenDocStore>(DependencyLifecycle.SingleInstance); Configure.Instance.Configurer.ConfigureComponent<TimeoutCalculator>(DependencyLifecycle.InstancePerUnitOfWork); Configure.Instance.Configurer.ConfigureComponent<SmsService>(DependencyLifecycle.InstancePerUnitOfWork); Configure.Instance.Configurer.ConfigureComponent<SmsTechWrapper>(DependencyLifecycle.InstancePerUnitOfWork); var bus = configure.CreateBus().Start(); //.Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install()); appHost.Container.Register(bus); appHost.Container.RegisterAutoWiredAs<RavenDocStore, IRavenDocStore>();//.RegisterAs<IRavenDocStore>(new RavenDocStore()); } } }<file_sep>/SmsScheduler/SmsActioner/ITimeoutCalculator.cs using System; using System.Collections.Generic; namespace SmsActioner { public interface ITimeoutCalculator { TimeSpan RequiredTimeout(int numberOfTimeoutsComplete); } public class TimeoutCalculator : ITimeoutCalculator { private readonly List<TimeSpan> _timespans = new List<TimeSpan> { new TimeSpan(0, 0, 10), new TimeSpan(0, 0, 30), new TimeSpan(0, 1, 0), new TimeSpan(0, 5, 0), new TimeSpan(0, 30, 0), new TimeSpan(0, 60, 0) }; public TimeSpan RequiredTimeout(int numberOfTimeoutsComplete) { if (numberOfTimeoutsComplete < 0) numberOfTimeoutsComplete = 0; if (numberOfTimeoutsComplete >= _timespans.Count) numberOfTimeoutsComplete = _timespans.Count - 1; return _timespans[numberOfTimeoutsComplete]; } } }<file_sep>/SmsScheduler/SmsActioner/ISmsTechWrapper.cs using System; using System.Collections.Generic; using System.Configuration; using System.Runtime.Serialization; using System.Text; using ConfigurationModels; using Newtonsoft.Json; using RestSharp; using TransmitSms.Helpers; using TransmitSms.Models; using TransmitSms.Models.Recipients; using TransmitSms.Models.Sms; namespace SmsActioner { public interface ISmsTechWrapper { SendSmsResponse SendSmsMessage(string to, string message); SmsSentResponse CheckMessage(string sid); } public class SmsTechWrapper : ISmsTechWrapper { private IRavenDocStore DocumentStore { get; set; } private RestClient RestClient { get; set; } private TransmitSms.TransmitSmsWrapper TransmitSmsClient { get; set; } public SmsTechWrapper(IRavenDocStore documentStore) { var smsTechUrl = ConfigurationManager.AppSettings["SMSTechUrl"]; DocumentStore = documentStore; using (var session = DocumentStore.GetStore().OpenSession("Configuration")) { var smsTechConfiguration = session.Load<SmsTechConfiguration>("SmsTechConfig"); if (smsTechConfiguration == null) throw new ArgumentException("Could not find sms tech configuration"); TransmitSmsClient = new TransmitSms.TransmitSmsWrapper(smsTechConfiguration.ApiKey, smsTechConfiguration.ApiSecret, smsTechUrl); /* - ALL FOR CHECKING TRANSMIT SMS NUGET PACKAGE */ var baseUrl = smsTechUrl; var authHeader = string.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", smsTechConfiguration.ApiKey, smsTechConfiguration.ApiSecret)))); RestClient = new RestClient(baseUrl); RestClient.AddDefaultHeader("Authorization", authHeader); RestClient.AddDefaultHeader("Accept", "application/json"); } } public SendSmsResponse SendSmsMessage(string to, string message) { using (var session = DocumentStore.GetStore().OpenSession("Configuration")) { var smsTechConfiguration = session.Load<SmsTechConfiguration>("SmsTechConfig"); if (smsTechConfiguration == null) throw new NotImplementedException(); return TransmitSmsClient.SendSms(message, new[]{to}, smsTechConfiguration.From, null, null, null, null, 0); } } public SmsSentResponse CheckMessage(string sid) { RestRequest request = new RestRequest("get-sms-sent.json", Method.POST); request.AddParameter("message_id", (object)sid, ParameterType.GetOrPost); request.AddParameter("optout", (object)EnumUtility.GetEnumDescription((Enum)OptoutsIncludeOptions.Include), ParameterType.GetOrPost); request.AddParameter("page", (object)1, ParameterType.GetOrPost); request.AddParameter("max", (object)1, ParameterType.GetOrPost); var restResponse = RestClient.Execute(request); if (restResponse.ErrorException != null) throw new Exception(restResponse.ErrorException.Message, restResponse.ErrorException); else { var j = JsonConvert.DeserializeObject<SmsSentResponse>(restResponse.Content); return j; } //return this._serviceUtility.Execute<SmsSentResponse>(request); /* - ALL FOR CHECKING TRANSMIT SMS NUGET PACKAGE */ //var request = new RestRequest("send-sms.json", Method.POST); //request.AddParameter("message", message, ParameterType.GetOrPost); //request.AddParameter("to", to, ParameterType.GetOrPost); //request.AddParameter("from", smsTechConfiguration.From, ParameterType.GetOrPost); ////request.AddParameter("dlr_callback", (object)dlrCallback, ParameterType.GetOrPost); ////request.AddParameter("reply_callback", (object)replyCallback, ParameterType.GetOrPost); //request.AddParameter("validity", 0, ParameterType.GetOrPost); ////var response = RestClient.Execute(request); //return TransmitSmsClient.GetSmsSent(Convert.ToInt32(sid), OptoutsIncludeOptions.Include, 1, 1); } } [DataContract] public class SmsSentResponse : ResponseBase { [DataMember(Name = "page")] public PageModel Page { get; set; } [DataMember(Name = "total")] public int Total { get; set; } [DataMember(Name = "message")] public SmsResponseBase Message { get; set; } [DataMember(Name = "recipients")] public IEnumerable<RecipientForSms> Recipients { get; set; } } }<file_sep>/SmsScheduler/SmsCoordinator/Email/IMailActioner.cs using System; using System.Net.Mail; using ConfigurationModels; using Typesafe.Mailgun; namespace SmsCoordinator.Email { public interface IMailActioner { void Send(MailgunConfiguration configuration, MailMessage message); } public class MailActioner : IMailActioner { public void Send(MailgunConfiguration configuration, MailMessage message) { var mailgunClient = new MailgunClient(configuration.DomainName, configuration.ApiKey); var commandResult = mailgunClient.SendMail(message); var s = commandResult.Message; Console.Write(s); } } }<file_sep>/SmsScheduler/SmsActioner/SmsSentTracker.cs using NServiceBus; using SmsMessages.MessageSending.Events; using SmsTrackingModels; namespace SmsActioner { public class SmsSentTracker : IHandleMessages<MessageSent>, IHandleMessages<MessageFailedSending> { public IRavenDocStore RavenStore { get; set; } public void Handle(MessageSent message) { using (var session = RavenStore.GetStore().OpenSession()) { session.Advanced.UseOptimisticConcurrency = true; var messageSent = session.Load<SmsTrackingData>(message.CorrelationId); if (messageSent != null) return; session.Store(new SmsTrackingData(message), message.CorrelationId.ToString()); session.SaveChanges(); } } public void Handle(MessageFailedSending message) { using (var session = RavenStore.GetStore().OpenSession()) { session.Advanced.UseOptimisticConcurrency = true; var messageSent = session.Load<SmsTrackingData>(message.CorrelationId); if (messageSent != null) return; session.Store(new SmsTrackingData(message), message.CorrelationId.ToString()); session.SaveChanges(); } } } }<file_sep>/SmsScheduler/SmsWeb/Controllers/SmsTechConfigController.cs using System.Web.Mvc; using ConfigurationModels; namespace SmsWeb.Controllers { public class SmsTechConfigController : Controller { public IRavenDocStore DocumentStore { get; set; } public PartialViewResult DetailsAjax() { using (var session = DocumentStore.GetStore().OpenSession("Configuration")) { var smsTechConfiguration = session.Load<SmsTechConfiguration>("SmsTechConfig"); if (smsTechConfiguration == null) return PartialView("_SmsTechConfigEdit"); return PartialView("_SmsTechConfigDetails", smsTechConfiguration); } } public PartialViewResult EditAjax() { using (var session = DocumentStore.GetStore().OpenSession("Configuration")) { var smsTechConfiguration = session.Load<SmsTechConfiguration>("SmsTechConfig"); if (smsTechConfiguration == null) return PartialView("_SmsTechConfigEdit"); return PartialView("_SmsTechConfigEdit", smsTechConfiguration); } } [HttpPost] public PartialViewResult EditAjax(SmsTechConfiguration configuration) { var isValid = TryUpdateModel(configuration); if (!isValid) return PartialView("_SmsTechConfigEdit", configuration); using (var session = DocumentStore.GetStore().OpenSession("Configuration")) { var smsTechConfiguration = session.Load<SmsTechConfiguration>("SmsTechConfig"); if (smsTechConfiguration == null) { session.Store(configuration, "SmsTechConfig"); } else { smsTechConfiguration.ApiKey = configuration.ApiKey; smsTechConfiguration.ApiSecret = configuration.ApiSecret; smsTechConfiguration.From = configuration.From; } session.SaveChanges(); return PartialView("_SmsTechConfigDetails", configuration); } } } } <file_sep>/SmsScheduler/SmsTrackingModels/ScheduleMessagesInCoordinatorIndex.cs using System; using System.Linq; using Raven.Abstractions.Indexing; using Raven.Client.Indexes; namespace SmsTrackingModels { public class ScheduleMessagesInCoordinatorIndex : AbstractIndexCreationTask<ScheduleTrackingData> { public ScheduleMessagesInCoordinatorIndex() { Map = schedules => from schedule in schedules select new { CoordinatorId = schedule.CoordinatorId.ToString(), MessageStatus = schedule.MessageStatus.ToString(), ScheduleId = schedule.ScheduleId.ToString(), ScheduleTimeUtc = schedule.ScheduleTimeUtc }; Indexes.Add(s => s.CoordinatorId, FieldIndexing.Analyzed); Indexes.Add(s => s.MessageStatus, FieldIndexing.Analyzed); Indexes.Add(s => s.ScheduleId, FieldIndexing.Analyzed); Indexes.Add(s => s.ScheduleTimeUtc, FieldIndexing.Default); } } public class CoordinatorTrackingDataByDate : AbstractIndexCreationTask<CoordinatorTrackingData> { public CoordinatorTrackingDataByDate() { Map = coordinators => from coordinator in coordinators select new { CreationDate = coordinator.CreationDateUtc, Status = coordinator.CurrentStatus }; Indexes.Add(c => c.CreationDateUtc, FieldIndexing.Default); } } }<file_sep>/SmsScheduler/ConfigurationModels/SmsTechConfiguration.cs using System.ComponentModel.DataAnnotations; namespace ConfigurationModels { public class SmsTechConfiguration { [Required] public string ApiSecret { get; set; } [Required] public string ApiKey { get; set; } [Required] public string From { get; set; } } }<file_sep>/SmsScheduler/SmsMessages/Email/Commands/CoordinatorCompleteEmailWithSummary.cs using System; using System.Collections.Generic; using SmsMessages.Coordinator.Events; namespace SmsMessages.Email.Commands { public class CoordinatorCompleteEmailWithSummary { public CoordinatorCompleteEmailWithSummary() { EmailAddresses = new List<string>(); } public Guid CoordinatorId { get; set; } public DateTime StartTimeUtc { get; set; } public DateTime FinishTimeUtc { get; set; } public string UserOlsenTimeZone { get; set; } public string Topic { get; set; } public List<string> EmailAddresses { get; set; } public int FailedCount { get; set; } public int SuccessCount { get; set; } public decimal Cost { get; set; } } public class CoordinatorCreatedEmail { public CoordinatorCreated CoordinatorCreated { get; set; } public CoordinatorCreatedEmail() { CoordinatorCreated = new CoordinatorCreated(); } public CoordinatorCreatedEmail(CoordinatorCreated coordinatorCreated) { CoordinatorCreated = coordinatorCreated; } } }<file_sep>/SmsScheduler/SmsActionerTests/SmsServiceTestFixture.cs using NUnit.Framework; using Rhino.Mocks; using SmsActioner; using SmsMessages.CommonData; using SmsMessages.MessageSending.Commands; using TransmitSms.Models; using TransmitSms.Models.Sms; namespace SmsActionerTests { [TestFixture] public class SmsServiceTestFixture { [Test] public void SmsServiceSending_WithoutERRORCode_ThrowsException() { var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") }; var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsMessageSending = new SendSmsResponse {Cost = (float) 0.06, MessageId = 123456, Error = new Error { Code = string.Empty } }; smsTechWrapper .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message)) .Return(smsMessageSending); Assert.That(() => smsService.Send(messageToSend), Throws.ArgumentException.With.Message.Contains("Error code expected")); smsTechWrapper.VerifyAllExpectations(); } [Test] public void SmsServiceSending() { var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") }; var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsMessageSending = new SendSmsResponse {Cost = (float) 0.06, MessageId = 123456, Error = new Error { Code = "SUCCESS"} }; smsTechWrapper .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message)) .Return(smsMessageSending); var response = smsService.Send(messageToSend); Assert.That(response, Is.TypeOf(typeof (SmsSending))); Assert.That(response.Sid, Is.EqualTo(smsMessageSending.MessageId.ToString())); var smsSending = response as SmsSending; Assert.That(smsSending.Price, Is.EqualTo(smsMessageSending.Cost)); smsTechWrapper.VerifyAllExpectations(); } [Test] public void SmsServiceInvalidNumber() { var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") }; var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsMessageSending = new SendSmsResponse { Cost = (float)0.06, MessageId = 123456, Error = new Error { Code = "RECIPIENTS_ERROR", Description = "can't send a message to those dudes!"} }; smsTechWrapper .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message)) .Return(smsMessageSending); var response = smsService.Send(messageToSend); Assert.That(response, Is.TypeOf(typeof(SmsFailed))); Assert.That(response.Sid, Is.EqualTo(smsMessageSending.MessageId.ToString())); var smsFailed = response as SmsFailed; Assert.That(smsFailed.Code, Is.EqualTo(smsMessageSending.Error.Code)); Assert.That(smsFailed.Message, Is.EqualTo(smsMessageSending.Error.Description)); smsTechWrapper.VerifyAllExpectations(); } [Test] public void SmsServiceOutOfMoney() { var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") }; var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsMessageSending = new SendSmsResponse { Cost = (float)0.06, MessageId = 123456, Error = new Error { Code = "LEDGER_ERROR", Description = "can't send a message to those dudes!" } }; const string accountIsCurrentlyOutOfMoney = "Could not send message - account is currently out of money"; smsTechWrapper .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message)) .Return(smsMessageSending); Assert.That(() => smsService.Send(messageToSend), Throws.Exception.TypeOf<AccountOutOfMoneyException>().With.Message.EqualTo(accountIsCurrentlyOutOfMoney)); } [Test] public void SmsServiceAuthenticationFailed() { var messageToSend = new SendOneMessageNow { SmsData = new SmsData("mobile", "message") }; var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsMessageSending = new SendSmsResponse { Cost = (float)0.06, MessageId = 123456, Error = new Error { Code = "AUTH_FAILED", Description = "we don't know who you are!" } }; smsTechWrapper .Expect(t => t.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message)) .Return(smsMessageSending); Assert.That(() => smsService.Send(messageToSend), Throws.Exception.TypeOf<SmsTechAuthenticationFailed>().With.Message.EqualTo(smsMessageSending.Error.Description)); } } }<file_sep>/SmsScheduler/SmsCoordinator/IRavenScheduleDocuments.cs using System; using System.Collections.Generic; using System.Linq; using Raven.Client; using SmsMessages.CommonData; using SmsMessages.Coordinator.Events; using SmsMessages.Scheduling.Commands; using SmsTrackingModels; namespace SmsCoordinator { public interface IRavenScheduleDocuments { List<ScheduleTrackingData> GetActiveScheduleTrackingData(Guid coordinatorId); void SaveSchedules(List<ScheduleSmsForSendingLater> messageList, Guid coordinatorId); DateTime GetMaxScheduleDateTime(Guid coordinatorId); bool AreCoordinatedSchedulesComplete(Guid coordinatorId); void SaveCoordinator(CoordinatorCreated message); void MarkCoordinatorAsComplete(Guid coordinatorId, DateTime utcCompleteDate); List<ScheduledMessagesStatusCountInCoordinatorIndex.ReduceResult> GetScheduleSummary(Guid coordinatorId); } public class RavenScheduleDocuments : IRavenScheduleDocuments { public IRavenDocStore RavenDocStore { get; set; } public List<ScheduleTrackingData> GetActiveScheduleTrackingData(Guid coordinatorId) { var trackingData = new List<ScheduleTrackingData>(); int page = 0; int pageSize = 100; RavenQueryStatistics ravenStats; using (var session = RavenDocStore.GetStore().OpenSession()) { session.Query<ScheduleTrackingData>("ScheduleMessagesInCoordinatorIndex") .Statistics(out ravenStats) .FirstOrDefault(s => s.CoordinatorId == coordinatorId && (s.MessageStatus == MessageStatus.Scheduled || s.MessageStatus == MessageStatus.WaitingForScheduling || s.MessageStatus == MessageStatus.Paused)); } while (ravenStats.TotalResults > (page) * pageSize) { using (var session = RavenDocStore.GetStore().OpenSession()) { var tracking = session.Query<ScheduleTrackingData>("ScheduleMessagesInCoordinatorIndex") .Where(s => s.CoordinatorId == coordinatorId) .Where( s => s.MessageStatus == MessageStatus.Scheduled || s.MessageStatus == MessageStatus.WaitingForScheduling || s.MessageStatus == MessageStatus.Paused) .OrderBy(s => s.ScheduleId) .Skip(pageSize * page) .Take(pageSize).ToList(); trackingData.AddRange(tracking); } page++; } return trackingData; } public void SaveSchedules(List<ScheduleSmsForSendingLater> messageList, Guid coordinatorId) { using (var session = RavenDocStore.GetStore().OpenSession()) { foreach (var scheduleSmsForSendingLater in messageList) { var scheduleTracker = new ScheduleTrackingData { MessageStatus = MessageStatus.WaitingForScheduling, ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, SmsData = scheduleSmsForSendingLater.SmsData, SmsMetaData = scheduleSmsForSendingLater.SmsMetaData, ScheduleTimeUtc = scheduleSmsForSendingLater.SendMessageAtUtc, CoordinatorId = coordinatorId }; session.Store(scheduleTracker, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); } session.SaveChanges(); } } public DateTime GetMaxScheduleDateTime(Guid coordinatorId) { using (var session = RavenDocStore.GetStore().OpenSession()) { return session.Query<ScheduleTrackingData>() .Customize(s => s.WaitForNonStaleResultsAsOfNow()) .Where(x => x.CoordinatorId == coordinatorId) .OrderByDescending(x => x.ScheduleTimeUtc) .Select(s => s.ScheduleTimeUtc) .FirstOrDefault(); } } public bool AreCoordinatedSchedulesComplete(Guid coordinatorId) { using (var session = RavenDocStore.GetStore().OpenSession()) { var reduceResult = session .Query<ScheduledMessages_ByCoordinatorIdAndStatus.ReduceResult, ScheduledMessages_ByCoordinatorIdAndStatus>() .Customize(s => s.WaitForNonStaleResultsAsOfNow()) .Where(s => s.CoordinatorId == coordinatorId.ToString() && ( s.Status == MessageStatus.WaitingForScheduling.ToString() || s.Status == MessageStatus.Scheduled.ToString() || s.Status == MessageStatus.Paused.ToString())) .FirstOrDefault(); return reduceResult == null || reduceResult.Count == 0; } } public void SaveCoordinator(CoordinatorCreated message) { using (var session = RavenDocStore.GetStore().OpenSession()) { var coordinatorTrackingData = new CoordinatorTrackingData { CoordinatorId = message.CoordinatorId, CreationDateUtc = message.CreationDateUtc, MetaData = message.MetaData, ConfirmationEmailAddress = String.Join(", ", message.ConfirmationEmailAddresses), UserOlsenTimeZone = message.UserOlsenTimeZone, CurrentStatus = CoordinatorStatusTracking.Started, MessageBody = message.MessageBody, MessageCount = message.MessageCount }; session.Store(coordinatorTrackingData, message.CoordinatorId.ToString()); session.SaveChanges(); } } public void MarkCoordinatorAsComplete(Guid coordinatorId, DateTime utcCompleteDate) { using (var session = RavenDocStore.GetStore().OpenSession()) { var coordinatorTrackingData = session.Load<CoordinatorTrackingData>(coordinatorId.ToString()); coordinatorTrackingData.CompletionDateUtc = utcCompleteDate; coordinatorTrackingData.CurrentStatus = CoordinatorStatusTracking.Completed; session.SaveChanges(); } } public List<ScheduledMessagesStatusCountInCoordinatorIndex.ReduceResult> GetScheduleSummary(Guid coordinatorId) { using (var session = RavenDocStore.GetStore().OpenSession()) { var coordinatorSummary = session.Query<ScheduledMessagesStatusCountInCoordinatorIndex.ReduceResult, ScheduledMessagesStatusCountInCoordinatorIndex>() .Customize(x => x.WaitForNonStaleResultsAsOfNow(new TimeSpan(0,0,30))) .Where(s => s.CoordinatorId == coordinatorId.ToString()) .ToList(); return coordinatorSummary; } } } }<file_sep>/SmsScheduler/SmsActioner/AccountOutOfMoneyException.cs using System; namespace SmsActioner { public class AccountOutOfMoneyException : Exception { public AccountOutOfMoneyException(string message) :base(message){} } public class SmsTechAuthenticationFailed : Exception { public SmsTechAuthenticationFailed(string message) : base(message){} } }<file_sep>/SmsScheduler/SmsActionerTests/SmsActionerHandlerTestFixture.cs using System; using System.Collections.Generic; using NServiceBus.Testing; using NUnit.Framework; using Rhino.Mocks; using SmsActioner; using SmsMessages.CommonData; using SmsMessages.MessageSending.Commands; using SmsMessages.MessageSending.Events; namespace SmsActionerTests { [TestFixture] public class SmsActionerHandlerTestFixture { [Test] public void SendOneMessageNow_SmsSent_InvalidThrowsException() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var smsSent = new SmsSent("r", DateTime.Now); smsService .Expect(s => s.Send(sendOneMessageNow)) .Return(smsSent); var smsActioner = new SmsActioner.SmsActioner { SmsService = smsService }; Assert.That(() => smsActioner.Handle(sendOneMessageNow), Throws.Exception.With.Message.Contains("SmsSent type is invalid - followup is required to get delivery status")); } [Test] public void SendOneMessageNow_SmsQueued_InvalidThrowsException() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var smsQueued = new SmsQueued("sid"); smsService .Expect(s => s.Send(sendOneMessageNow)) .Return(smsQueued); var smsActioner = new SmsActioner.SmsActioner { SmsService = smsService }; Assert.That(() => smsActioner.Handle(sendOneMessageNow), Throws.Exception.With.Message.Contains("SmsQueued type is invalid - followup is required to get delivery status")); } [Test] public void SendOneMessageNow_SmsSendingSetsPriceAndId() { var sendOneMessageNow = new SendOneMessageNow(); var smsService = MockRepository.GenerateMock<ISmsService>(); var timeoutCalculator = MockRepository.GenerateMock<ITimeoutCalculator>(); var smsSending = new SmsSending("id", 0.06m); var data = new SmsActionerData(); smsService .Expect(s => s.Send(sendOneMessageNow)) .Return(smsSending); var timeoutRequested = new TimeSpan(); timeoutCalculator.Expect(t => t.RequiredTimeout(data.NumberOfTimeoutRequests)).Return(timeoutRequested); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.Data = data; a.TimeoutCalculator = timeoutCalculator; }) .WhenReceivesMessageFrom("somewhere") .ExpectTimeoutToBeSetIn<SmsPendingTimeout>((timeoutMessage, timespan) => timespan == timeoutRequested) .When(a => a.Handle(sendOneMessageNow)); Assert.That(data.SmsRequestId, Is.EqualTo(smsSending.Sid)); Assert.That(data.Price, Is.EqualTo(smsSending.Price)); Assert.That(data.OriginalMessage, Is.EqualTo(sendOneMessageNow)); Assert.That(data.NumberOfTimeoutRequests, Is.EqualTo(1)); smsService.VerifyAllExpectations(); timeoutCalculator.VerifyAllExpectations(); } [Test] public void SendOneMessageNow_SmsFailed() { var sendOneMessageNow = new SendOneMessageNow { ConfirmationEmailAddress = "<EMAIL>", CorrelationId = Guid.NewGuid(), SmsData = new SmsData("mobile", "message"), SmsMetaData = new SmsMetaData { Tags = new List<string> { "tag1", "tag2" }, Topic = "topic" } }; var smsService = MockRepository.GenerateMock<ISmsService>(); var smsFailed = new SmsFailed("sid", "faile", "why why why"); smsService .Expect(s => s.Send(sendOneMessageNow)) .Return(smsFailed); var data = new SmsActionerData(); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.Data = data; }) .WhenReceivesMessageFrom("somewhere") .ExpectPublish<MessageFailedSending>(message => message.ConfirmationEmailAddress == sendOneMessageNow.ConfirmationEmailAddress && message.CorrelationId == sendOneMessageNow.CorrelationId && message.SmsData == sendOneMessageNow.SmsData && message.SmsMetaData == sendOneMessageNow.SmsMetaData && message.SmsFailed == smsFailed ) .When(a => a.Handle(sendOneMessageNow)) .AssertSagaCompletionIs(true); smsService.VerifyAllExpectations(); } [Test] public void TimeoutHandle_CheckStatus_SmsFailed() { var timeout = new SmsPendingTimeout(); var sendOneMessageNow = new SendOneMessageNow { ConfirmationEmailAddress = "<EMAIL>", CorrelationId = Guid.NewGuid(), SmsData = new SmsData("mobile", "message"), SmsMetaData = new SmsMetaData { Tags = new List<string> { "tag1", "tag2" }, Topic = "topic" } }; var data = new SmsActionerData { Id = Guid.NewGuid(), OriginalMessage = sendOneMessageNow, Price = 0.06m, SmsRequestId = "123" }; var smsService = MockRepository.GenerateMock<ISmsService>(); var smsFailed = new SmsFailed("sid", "faile", "why why why"); smsService .Expect(s => s.CheckStatus(data.SmsRequestId)) .Return(smsFailed); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.Data = data; }) .WhenReceivesMessageFrom("somewhere") .ExpectPublish<MessageFailedSending>(message => message.ConfirmationEmailAddress == sendOneMessageNow.ConfirmationEmailAddress && message.CorrelationId == sendOneMessageNow.CorrelationId && message.SmsData == sendOneMessageNow.SmsData && message.SmsMetaData == sendOneMessageNow.SmsMetaData && message.SmsFailed == smsFailed ) .When(a => a.Timeout(timeout)) .AssertSagaCompletionIs(true); smsService.VerifyAllExpectations(); } [Test] public void TimeoutHandle_CheckStatus_SmsSent() { var timeout = new SmsPendingTimeout(); var sendOneMessageNow = new SendOneMessageNow { ConfirmationEmailAddress = "<EMAIL>", CorrelationId = Guid.NewGuid(), SmsData = new SmsData("mobile", "message"), SmsMetaData = new SmsMetaData { Tags = new List<string> { "tag1", "tag2" }, Topic = "topic" } }; var data = new SmsActionerData { Id = Guid.NewGuid(), OriginalMessage = sendOneMessageNow, Price = 0.06m, SmsRequestId = "123" }; var smsService = MockRepository.GenerateMock<ISmsService>(); var smsSent = new SmsSent("doesn't matter", DateTime.Now); smsService .Expect(s => s.CheckStatus(data.SmsRequestId)) .Return(smsSent); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.Data = data; }) .WhenReceivesMessageFrom("somewhere") .ExpectPublish<MessageSent>(message => message.ConfirmationEmailAddress == sendOneMessageNow.ConfirmationEmailAddress && message.CorrelationId == sendOneMessageNow.CorrelationId && message.SmsData == sendOneMessageNow.SmsData && message.SmsMetaData == sendOneMessageNow.SmsMetaData && message.ConfirmationData.Price == data.Price && message.ConfirmationData.Receipt == data.SmsRequestId && message.ConfirmationData.SentAtUtc == smsSent.SentAtUtc ) .When(a => a.Timeout(timeout)) .AssertSagaCompletionIs(true); smsService.VerifyAllExpectations(); } [Test] public void TimeoutHandle_CheckStatus_SmsQueued_RequestsTimeout() { var timeout = new SmsPendingTimeout(); var sendOneMessageNow = new SendOneMessageNow(); var data = new SmsActionerData { Id = Guid.NewGuid(), OriginalMessage = sendOneMessageNow, Price = 0.06m, SmsRequestId = "123", NumberOfTimeoutRequests = 1 }; var smsService = MockRepository.GenerateMock<ISmsService>(); var timeoutCalculator = MockRepository.GenerateMock<ITimeoutCalculator>(); var smsQueued = new SmsQueued(data.SmsRequestId); smsService .Expect(s => s.CheckStatus(data.SmsRequestId)) .Return(smsQueued); var timeoutTimespan = new TimeSpan(); timeoutCalculator.Expect(t => t.RequiredTimeout(data.NumberOfTimeoutRequests)).Return(timeoutTimespan); Test.Initialize(); Test.Saga<SmsActioner.SmsActioner>() .WithExternalDependencies(a => { a.SmsService = smsService; a.Data = data; a.TimeoutCalculator = timeoutCalculator; }) .WhenReceivesMessageFrom("somewhere") .ExpectTimeoutToBeSetIn<SmsPendingTimeout>((timeoutMessage, timespan) => timespan == timeoutTimespan) .When(a => a.Timeout(timeout)) .AssertSagaCompletionIs(false); Assert.That(data.NumberOfTimeoutRequests, Is.EqualTo(2)); smsService.VerifyAllExpectations(); timeoutCalculator.VerifyAllExpectations(); } } }<file_sep>/SmsScheduler/SmsActioner/ISmsService.cs using System; using System.Linq; using SmsMessages.CommonData; using SmsMessages.MessageSending.Commands; namespace SmsActioner { public interface ISmsService { /// <summary> /// Send the SMS message through a provider /// </summary> /// <param name="messageToSend">Phone number and message to send to contact</param> /// <returns>Status of the SMS message, including SId from the provider</returns> SmsStatus Send(SendOneMessageNow messageToSend); SmsStatus CheckStatus(string sid); } public class SmsService : ISmsService { public ISmsTechWrapper SmsTechWrapper { get; set; } /// <summary> /// This method will never get success / fail of message delivery - just that it is valid, and how much it will cost /// </summary> /// <param name="messageToSend"></param> /// <returns></returns> public SmsStatus Send(SendOneMessageNow messageToSend) { var createdSmsMessage = SmsTechWrapper.SendSmsMessage(messageToSend.SmsData.Mobile, messageToSend.SmsData.Message); if (createdSmsMessage.Error.Code.Equals("AUTH_FAILED")) throw new SmsTechAuthenticationFailed(createdSmsMessage.Error.Description); if (createdSmsMessage.Error.Code.Equals("LEDGER_ERROR")) throw new AccountOutOfMoneyException("Could not send message - account is currently out of money"); if (createdSmsMessage.Error.Code.Equals("RECIPIENTS_ERROR")) return new SmsFailed(createdSmsMessage.MessageId.ToString(), createdSmsMessage.Error.Code, createdSmsMessage.Error.Description); if (createdSmsMessage.Error.Code.Equals("SUCCESS")) return new SmsSending(createdSmsMessage.MessageId.ToString(), Convert.ToDecimal(createdSmsMessage.Cost)); throw new ArgumentException("Error code expected"); } public SmsStatus CheckStatus(string sid) { var smsSentResponse = SmsTechWrapper.CheckMessage(sid); var recipientForSms = smsSentResponse.Recipients.First(); if (recipientForSms.DeliveryStatus.Equals("hard-bounce", StringComparison.CurrentCultureIgnoreCase)) return new SmsFailed(sid, recipientForSms.DeliveryStatus, "The number is invalid or disconnected."); if (recipientForSms.DeliveryStatus.Equals("soft-bounce", StringComparison.CurrentCultureIgnoreCase)) return new SmsFailed(sid, recipientForSms.DeliveryStatus, "The message timed out after 72 hrs, either the recipient was out of range, their phone was off for longer than 72 hrs or the message was unable to be delivered due to a network outage or other connectivity issue."); if (recipientForSms.DeliveryStatus.Equals("pending", StringComparison.CurrentCultureIgnoreCase)) return new SmsQueued(sid); if (recipientForSms.DeliveryStatus.Equals("delivered", StringComparison.CurrentCultureIgnoreCase)) return new SmsSent(sid, smsSentResponse.Message.SendAt); throw new ArgumentException("Unexpected delivery status " + recipientForSms.DeliveryStatus); } } } <file_sep>/SmsScheduler/SmsScheduler/ScheduleSms.cs using System; using NServiceBus; using NServiceBus.Saga; using SmsMessages.CommonData; using SmsMessages.MessageSending.Commands; using SmsMessages.MessageSending.Events; using SmsMessages.Scheduling.Commands; using SmsMessages.Scheduling.Events; using SmsTrackingModels; namespace SmsScheduler { public class ScheduleSms : Saga<ScheduledSmsData>, IAmStartedByMessages<ScheduleSmsForSendingLater>, IHandleTimeouts<ScheduleSmsTimeout>, IHandleMessages<PauseScheduledMessageIndefinitely>, IHandleMessages<ResumeScheduledMessageWithOffset>, IHandleMessages<RescheduleScheduledMessageWithNewTime>, IHandleMessages<MessageSent>, IHandleMessages<MessageFailedSending> { public IRavenDocStore RavenDocStore { get; set; } public override void ConfigureHowToFindSaga() { ConfigureMapping<MessageSent>(data => data.Id, message => message.CorrelationId); ConfigureMapping<MessageFailedSending>(data => data.Id, message => message.CorrelationId); ConfigureMapping<PauseScheduledMessageIndefinitely>(data => data.ScheduleMessageId, message => message.ScheduleMessageId); ConfigureMapping<ResumeScheduledMessageWithOffset>(data => data.ScheduleMessageId, message => message.ScheduleMessageId); ConfigureMapping<RescheduleScheduledMessageWithNewTime>(data => data.ScheduleMessageId, message => message.ScheduleMessageId); base.ConfigureHowToFindSaga(); } public void Handle(ScheduleSmsForSendingLater scheduleSmsForSendingLater) { Data.OriginalMessage = scheduleSmsForSendingLater; Data.ScheduleMessageId = scheduleSmsForSendingLater.ScheduleMessageId == Guid.NewGuid() ? Data.Id : scheduleSmsForSendingLater.ScheduleMessageId; Data.RequestingCoordinatorId = scheduleSmsForSendingLater.CorrelationId; Data.TimeoutCounter = 0; var timeout = new DateTime(scheduleSmsForSendingLater.SendMessageAtUtc.Ticks, DateTimeKind.Utc); RequestUtcTimeout(timeout, new ScheduleSmsTimeout { TimeoutCounter = 0}); using (var session = RavenDocStore.GetStore().OpenSession("SmsTracking")) { var scheduleTrackingData = session.Load<ScheduleTrackingData>(scheduleSmsForSendingLater.ScheduleMessageId.ToString()); if (scheduleTrackingData == null) { var scheduleTracker = new ScheduleTrackingData { MessageStatus = MessageStatus.Scheduled, ScheduleId = scheduleSmsForSendingLater.ScheduleMessageId, SmsData = scheduleSmsForSendingLater.SmsData, SmsMetaData = scheduleSmsForSendingLater.SmsMetaData, ScheduleTimeUtc = scheduleSmsForSendingLater.SendMessageAtUtc, CoordinatorId = scheduleSmsForSendingLater.CorrelationId }; session.Store(scheduleTracker, scheduleSmsForSendingLater.ScheduleMessageId.ToString()); } else { scheduleTrackingData.MessageStatus = MessageStatus.Scheduled; } session.SaveChanges(); } Bus.Publish(new SmsScheduled { ScheduleMessageId = Data.ScheduleMessageId, CoordinatorId = scheduleSmsForSendingLater.CorrelationId, SmsData = scheduleSmsForSendingLater.SmsData, SmsMetaData = scheduleSmsForSendingLater.SmsMetaData, ScheduleSendingTimeUtc = scheduleSmsForSendingLater.SendMessageAtUtc }); } public void Timeout(ScheduleSmsTimeout state) { if (!Data.SchedulingPaused && state.TimeoutCounter == Data.TimeoutCounter) { var sendOneMessageNow = new SendOneMessageNow { CorrelationId = Data.Id, SmsData = Data.OriginalMessage.SmsData, SmsMetaData = Data.OriginalMessage.SmsMetaData, ConfirmationEmailAddress = Data.OriginalMessage.ConfirmationEmail }; Bus.Send(sendOneMessageNow); } } public void Handle(MessageSent message) { Bus.Publish(new ScheduledSmsSent { CoordinatorId = Data.RequestingCoordinatorId, ScheduledSmsId = Data.ScheduleMessageId, ConfirmationData = message.ConfirmationData, Number = message.SmsData.Mobile}); using (var session = RavenDocStore.GetStore().OpenSession("SmsTracking")) { var scheduleTrackingData = session.Load<ScheduleTrackingData>(Data.ScheduleMessageId.ToString()); scheduleTrackingData.ConfirmationData = message.ConfirmationData; scheduleTrackingData.MessageStatus = MessageStatus.Sent; session.SaveChanges(); } MarkAsComplete(); } public void Handle(PauseScheduledMessageIndefinitely pauseScheduling) { if (Data.LastUpdateCommandRequestUtc != null && Data.LastUpdateCommandRequestUtc > pauseScheduling.MessageRequestTimeUtc) return; Data.SchedulingPaused = true; using (var session = RavenDocStore.GetStore().OpenSession("SmsTracking")) { var scheduleTrackingData = session.Load<ScheduleTrackingData>(Data.ScheduleMessageId.ToString()); scheduleTrackingData.MessageStatus = MessageStatus.Paused; session.SaveChanges(); } Bus.Publish(new MessageSchedulePaused { CoordinatorId = Data.RequestingCoordinatorId, ScheduleId = pauseScheduling.ScheduleMessageId, Number = Data.OriginalMessage.SmsData.Mobile }); Data.LastUpdateCommandRequestUtc = pauseScheduling.MessageRequestTimeUtc; } public void Handle(ResumeScheduledMessageWithOffset scheduleSmsForSendingLater) { if (Data.LastUpdateCommandRequestUtc != null && Data.LastUpdateCommandRequestUtc > scheduleSmsForSendingLater.MessageRequestTimeUtc) return; Data.SchedulingPaused = false; var rescheduledTime = Data.OriginalMessage.SendMessageAtUtc.Add(scheduleSmsForSendingLater.Offset); Data.TimeoutCounter++; using (var session = RavenDocStore.GetStore().OpenSession("SmsTracking")) { var scheduleTrackingData = session.Load<ScheduleTrackingData>(Data.ScheduleMessageId.ToString()); scheduleTrackingData.MessageStatus = MessageStatus.Scheduled; scheduleTrackingData.ScheduleTimeUtc = rescheduledTime; session.SaveChanges(); } RequestUtcTimeout(rescheduledTime, new ScheduleSmsTimeout { TimeoutCounter = Data.TimeoutCounter }); Bus.Publish(new MessageRescheduled { CoordinatorId = Data.RequestingCoordinatorId, ScheduleMessageId = Data.ScheduleMessageId, RescheduledTimeUtc = rescheduledTime, Number = Data.OriginalMessage.SmsData.Mobile }); Data.LastUpdateCommandRequestUtc = scheduleSmsForSendingLater.MessageRequestTimeUtc; } public void Handle(RescheduleScheduledMessageWithNewTime message) { if (Data.LastUpdateCommandRequestUtc != null && Data.LastUpdateCommandRequestUtc > message.MessageRequestTimeUtc) return; Data.SchedulingPaused = false; Data.TimeoutCounter++; RequestUtcTimeout(message.NewScheduleTimeUtc, new ScheduleSmsTimeout { TimeoutCounter = Data.TimeoutCounter }); using (var session = RavenDocStore.GetStore().OpenSession("SmsTracking")) { var scheduleTrackingData = session.Load<ScheduleTrackingData>(Data.ScheduleMessageId.ToString()); scheduleTrackingData.MessageStatus = MessageStatus.Scheduled; scheduleTrackingData.ScheduleTimeUtc = message.NewScheduleTimeUtc; session.SaveChanges(); } Bus.Publish(new MessageRescheduled { CoordinatorId = Data.RequestingCoordinatorId, ScheduleMessageId = Data.ScheduleMessageId, RescheduledTimeUtc = message.NewScheduleTimeUtc, Number = Data.OriginalMessage.SmsData.Mobile }); Data.LastUpdateCommandRequestUtc = message.MessageRequestTimeUtc; } public void Handle(MessageFailedSending failedMessage) { Bus.Publish(new ScheduledSmsFailed { CoordinatorId = Data.RequestingCoordinatorId, ScheduledSmsId = Data.ScheduleMessageId, Number = failedMessage.SmsData.Mobile, SmsFailedData = failedMessage.SmsFailed }); using (var session = RavenDocStore.GetStore().OpenSession("SmsTracking")) { var scheduleTrackingData = session.Load<ScheduleTrackingData>(Data.ScheduleMessageId.ToString()); scheduleTrackingData.MessageStatus = MessageStatus.Failed; scheduleTrackingData.SmsFailureData = failedMessage.SmsFailed; session.SaveChanges(); } MarkAsComplete(); } } public class ScheduledSmsData : ISagaEntity { public Guid Id { get; set; } public string Originator { get; set; } public string OriginalMessageId { get; set; } public ScheduleSmsForSendingLater OriginalMessage { get; set; } public bool SchedulingPaused { get; set; } public Guid ScheduleMessageId { get; set; } public DateTime? LastUpdateCommandRequestUtc { get; set; } public Guid RequestingCoordinatorId { get; set; } public int TimeoutCounter { get; set; } } public class ScheduleSmsTimeout { public int TimeoutCounter { get; set; } } }<file_sep>/SmsScheduler/SmsWeb/Controllers/HomeController.cs using System; using System.Web.Mvc; using ConfigurationModels; using Raven.Client.Linq; using SmsTrackingModels; using System.Linq; using SmsWeb.Models; namespace SmsWeb.Controllers { public class HomeController : Controller { public IRavenDocStore RavenDocStore { get; set; } public ActionResult Index() { using (var session = RavenDocStore.GetStore().OpenSession("Configuration")) { var smsTechConfiguration = session.Load<SmsTechConfiguration>("SmsTechConfig"); var mailgunConfiguration = session.Load<MailgunConfiguration>("MailgunConfig"); if (smsTechConfiguration == null || mailgunConfiguration == null) { return View("IndexConfigNotSet"); } } return View("Index"); } public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Configuration() { return View("ConfigMenu"); } [HttpPost] public ActionResult Search(string id) { Guid docId; if (Guid.TryParse(id, out docId)) { using (var session = RavenDocStore.GetStore().OpenSession()) { var trackingData = session.Load<object>(docId.ToString()); if (trackingData != null) { if (trackingData is CoordinatorTrackingData) return RedirectToAction("Details", "Coordinator", new {coordinatorId = id}); throw new Exception("Type not recognised"); } } } else { using (var session = RavenDocStore.GetStore().OpenSession()) { var reduceResults = session.Query<PhoneNumberInCoordinatedMessages.ReduceResult, PhoneNumberInCoordinatedMessages>() .Where(p => p.PhoneNumber.StartsWith(id)) .Select(p => new SearchByNumberResult { CoordinatorId = p.CoordinatorId, PhoneNumber = p.PhoneNumber, SendingDate = p.SendingDate, Status = p.Status, Topic = p.Topic, }) .ToList(); return View("Results", reduceResults); } } return View("NoResults", (object)id); } } } <file_sep>/SmsScheduler/SmsMessages/CommonData/SmsConfirmationData.cs using System; namespace SmsMessages.CommonData { public abstract class SmsStatus { public string Sid { get; set; } } public class SmsFailed : SmsStatus { public SmsFailed(string sid, string code, string message) { Sid = sid; Code = code; Message = message; } public string Code { get; set; } public string Message { get; set; } } public class SmsSending : SmsStatus { public decimal Price { get; set; } public SmsSending(string sid, decimal price) { Price = price; Sid = sid; } } public class SmsQueued : SmsStatus { public SmsQueued(string sid) { Sid = sid; } } public class SmsSent : SmsStatus { public SmsSent(string sid, DateTime sentAtUtc) { Sid = sid; SentAtUtc = sentAtUtc; } public DateTime SentAtUtc { get; set; } //public SmsConfirmationData SmsConfirmationData { get; set; } } public class SmsConfirmationData { public SmsConfirmationData(string receipt, DateTime sentAtUtc, Decimal price) { Receipt = receipt; SentAtUtc = new DateTime(sentAtUtc.Ticks, DateTimeKind.Utc); Price = price; } public string Receipt { get; set; } public DateTime SentAtUtc { get; set; } public Decimal Price { get; set; } } }<file_sep>/SmsScheduler/SmsActioner/SmsActioner.cs using System; using NServiceBus.Saga; using SmsMessages.CommonData; using SmsMessages.MessageSending.Commands; using SmsMessages.MessageSending.Events; namespace SmsActioner { public class SmsActioner : Saga<SmsActionerData>, IAmStartedByMessages<SendOneMessageNow>, IHandleTimeouts<SmsPendingTimeout> { public ISmsService SmsService { get; set; } public ITimeoutCalculator TimeoutCalculator { get; set; } public void Handle(SendOneMessageNow sendOneMessageNow) { var confirmationData = SmsService.Send(sendOneMessageNow); if (confirmationData is SmsSent) throw new ArgumentException("SmsSent type is invalid - followup is required to get delivery status"); if (confirmationData is SmsQueued) throw new ArgumentException("SmsQueued type is invalid - followup is required to get delivery status"); Data.OriginalMessage = sendOneMessageNow; Data.SmsRequestId = confirmationData.Sid; ProcessConfirmationData(confirmationData); } public void Timeout(SmsPendingTimeout state) { var smsStatus = SmsService.CheckStatus(Data.SmsRequestId); ProcessConfirmationData(smsStatus); } private void ProcessConfirmationData(SmsStatus confirmationData) { if (confirmationData is SmsFailed) { var failedMessage = confirmationData as SmsFailed; Bus.Publish<MessageFailedSending>(m => { m.SmsFailed = failedMessage; m.CorrelationId = Data.OriginalMessage.CorrelationId; m.SmsData = Data.OriginalMessage.SmsData; m.SmsMetaData = Data.OriginalMessage.SmsMetaData; m.ConfirmationEmailAddress = Data.OriginalMessage.ConfirmationEmailAddress; }); MarkAsComplete(); } else if (confirmationData is SmsSent) { var sentMessage = confirmationData as SmsSent; Bus.Publish<MessageSent>(m => { m.ConfirmationData = new SmsConfirmationData(Data.SmsRequestId, sentMessage.SentAtUtc, Data.Price); m.CorrelationId = Data.OriginalMessage.CorrelationId; m.SmsData = Data.OriginalMessage.SmsData; m.SmsMetaData = Data.OriginalMessage.SmsMetaData; m.ConfirmationEmailAddress = Data.OriginalMessage.ConfirmationEmailAddress; }); MarkAsComplete(); } else { if (confirmationData is SmsSending) Data.Price = (confirmationData as SmsSending).Price; var requiredTimeout = TimeoutCalculator.RequiredTimeout(Data.NumberOfTimeoutRequests); RequestUtcTimeout<SmsPendingTimeout>(requiredTimeout); Data.NumberOfTimeoutRequests++; } } } public class SmsActionerData : ISagaEntity { public Guid Id { get; set; } public string Originator { get; set; } public string OriginalMessageId { get; set; } public string SmsRequestId { get; set; } public SendOneMessageNow OriginalMessage { get; set; } public decimal Price { get; set; } public int NumberOfTimeoutRequests { get; set; } } public class SmsPendingTimeout { } }<file_sep>/SmsScheduler/SmsActionerTests/TimeoutCalculatorTestFixture.cs using System; using NUnit.Framework; using SmsActioner; namespace SmsActionerTests { [TestFixture] public class TimeoutCalculatorTestFixture { [Test] public void NoTimeoutsSet_Return10Seconds() { var timeoutCalculator = new TimeoutCalculator(); const int numberOfTimeoutsComplete = 0; var timeout = timeoutCalculator.RequiredTimeout(numberOfTimeoutsComplete); Assert.That(timeout, Is.EqualTo(new TimeSpan(0,0,10))); } [Test] public void OneTimeoutSet_Return30Seconds() { var timeoutCalculator = new TimeoutCalculator(); const int numberOfTimeoutsComplete = 1; var timeout = timeoutCalculator.RequiredTimeout(numberOfTimeoutsComplete); Assert.That(timeout, Is.EqualTo(new TimeSpan(0,0,30))); } [Test] public void TwoTimeoutsSet_Return60Seconds() { var timeoutCalculator = new TimeoutCalculator(); const int numberOfTimeoutsComplete = 2; var timeout = timeoutCalculator.RequiredTimeout(numberOfTimeoutsComplete); Assert.That(timeout, Is.EqualTo(new TimeSpan(0,1,0))); } [Test] public void ThreeTimeoutsSet_Return5Minutes() { var timeoutCalculator = new TimeoutCalculator(); const int numberOfTimeoutsComplete = 3; var timeout = timeoutCalculator.RequiredTimeout(numberOfTimeoutsComplete); Assert.That(timeout, Is.EqualTo(new TimeSpan(0,5,0))); } [Test] public void FourTimeoutsSet_Return30Minutes() { var timeoutCalculator = new TimeoutCalculator(); const int numberOfTimeoutsComplete = 4; var timeout = timeoutCalculator.RequiredTimeout(numberOfTimeoutsComplete); Assert.That(timeout, Is.EqualTo(new TimeSpan(0,30,0))); } [Test] public void FiveTimeoutsSet_Return60Minutes() { var timeoutCalculator = new TimeoutCalculator(); const int numberOfTimeoutsComplete = 5; var timeout = timeoutCalculator.RequiredTimeout(numberOfTimeoutsComplete); Assert.That(timeout, Is.EqualTo(new TimeSpan(0,60,0))); } [Test] public void OverFiveTimeoutsSet_Return60Minutes() { var timeoutCalculator = new TimeoutCalculator(); const int numberOfTimeoutsComplete = 24; var timeout = timeoutCalculator.RequiredTimeout(numberOfTimeoutsComplete); Assert.That(timeout, Is.EqualTo(new TimeSpan(0,60,0))); } } }<file_sep>/SmsScheduler/SmsActionerTests/SmsServiceCheckTestFixture.cs using System; using System.Collections.Generic; using NUnit.Framework; using Rhino.Mocks; using SmsActioner; using SmsMessages.CommonData; using TransmitSms.Models.Recipients; using TransmitSms.Models.Sms; using SmsSentResponse = SmsActioner.SmsSentResponse; namespace SmsActionerTests { [TestFixture] public class SmsServiceCheckTestFixture { [Test] public void CheckMessageIsPending() { var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); const string sid = "sid"; smsTechWrapper .Expect(t => t.CheckMessage(sid)) .Return(new SmsSentResponse { Recipients = new List<RecipientForSms> { new RecipientForSms { DeliveryStatus = "pending" }}}); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsStatus = smsService.CheckStatus(sid); Assert.That(smsStatus, Is.TypeOf(typeof(SmsQueued))); Assert.That(smsStatus.Sid, Is.EqualTo(sid)); smsTechWrapper.VerifyAllExpectations(); } [Test] public void CheckMessageIsSent() { var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); const string sid = "123"; var sendAt = DateTime.Now; smsTechWrapper .Expect(t => t.CheckMessage(sid)) .Return(new SmsSentResponse { Recipients = new List<RecipientForSms> { new RecipientForSms { DeliveryStatus = "delivered" } }, Message = new SmsResponseBase { SendAt = sendAt, MessageId = Convert.ToInt32(sid) } }); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsStatus = smsService.CheckStatus(sid); Assert.That(smsStatus, Is.TypeOf(typeof(SmsSent))); Assert.That(smsStatus.Sid, Is.EqualTo(sid)); var smsSent = smsStatus as SmsSent; Assert.That(smsSent.SentAtUtc, Is.EqualTo(sendAt)); smsTechWrapper.VerifyAllExpectations(); } [Test] public void CheckMessageIsFailed_HardBounce() { var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); const string sid = "sid"; smsTechWrapper .Expect(t => t.CheckMessage(sid)) .Return(new SmsSentResponse { Recipients = new List<RecipientForSms> { new RecipientForSms { DeliveryStatus = "hard-bounce" } } }); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsStatus = smsService.CheckStatus(sid); Assert.That(smsStatus, Is.TypeOf(typeof(SmsFailed))); var smsFailed = smsStatus as SmsFailed; Assert.That(smsStatus.Sid, Is.EqualTo(sid)); Assert.That(smsFailed.Code, Is.EqualTo("hard-bounce")); Assert.That(smsFailed.Message, Is.EqualTo("The number is invalid or disconnected.")); smsTechWrapper.VerifyAllExpectations(); } [Test] public void CheckMessageIsFailed_SoftBounce() { var smsTechWrapper = MockRepository.GenerateMock<ISmsTechWrapper>(); const string sid = "sid"; smsTechWrapper .Expect(t => t.CheckMessage(sid)) .Return(new SmsSentResponse { Recipients = new List<RecipientForSms> { new RecipientForSms { DeliveryStatus = "soft-bounce" } } }); var smsService = new SmsService { SmsTechWrapper = smsTechWrapper }; var smsStatus = smsService.CheckStatus(sid); Assert.That(smsStatus, Is.TypeOf(typeof(SmsFailed))); var smsFailed = smsStatus as SmsFailed; Assert.That(smsStatus.Sid, Is.EqualTo(sid)); Assert.That(smsFailed.Code, Is.EqualTo("soft-bounce")); Assert.That(smsFailed.Message, Is.EqualTo("The message timed out after 72 hrs, either the recipient was out of range, their phone was off for longer than 72 hrs or the message was unable to be delivered due to a network outage or other connectivity issue.")); smsTechWrapper.VerifyAllExpectations(); } } }
b47d5a37466b42052057a1f09c8f762691f2a814
[ "C#" ]
27
C#
Compassion/SmsScheduler
878e4b08a478164af9b118a7c33381d71b6b5e61
a453a63e20900c3852c7cd07672757b485ceda99
refs/heads/master
<repo_name>marsch/grunt-preprocess<file_sep>/tasks/preprocess.js /* * preprocess * https://github.com/onehealth/grunt-preprocess * * Copyright (c) 2012 OneHealth Solutions, Inc. * Written by <NAME> - http://jarrodoverson.com/ * Licensed under the Apache 2.0 license. */ /*jshint node:true*/ 'use strict'; module.exports = init; var preprocess = require('preprocess'); var defaultEnv = {}; function init(grunt) { var _ = grunt.util._; grunt.registerMultiTask('preprocess', 'Preprocess files based off environment configuration', function() { var options = this.options(); var context = _.extend({}, defaultEnv,process.env, options.context || {}); var src,dest; context.NODE_ENV = context.NODE_ENV || 'development'; this.files.forEach(function(fileObj){ if (!fileObj.dest) { if (!options.inline) { grunt.log.error('WARNING : POTENTIAL CODE LOSS.'.yellow); grunt.log.error('You must specify "inline : true" when using the "files" configuration.'); grunt.log.errorlns( 'This WILL REWRITE FILES WITHOUT MAKING BACKUPS. Make sure your ' + 'code is checked in or you are configured to operate on a copied directory.' ); return; } fileObj.src.forEach(function(src) { preprocess.preprocessFileSync(src,src,context); }); } else { src = fileObj.src[0]; dest = fileObj.dest; dest = grunt.template.process(dest); preprocess.preprocessFileSync(src,dest,context); } }); }); }
270eca419ef11cad14bbc238b7bf425d0185b81b
[ "JavaScript" ]
1
JavaScript
marsch/grunt-preprocess
07df735a9d9adb018bdd5328cf0eac3157310a5c
1e4a5768087ebd92f0ae97b7f72fee251cef3ff8
refs/heads/master
<repo_name>springuper/springuper.github.io<file_sep>/scripts/build.sh #!/bin/bash -e cd blog cp themes/_config.yml themes/even/ npx hexo generate cd .. cp -r blog/public/* docs/ cp favicon.ico docs/ <file_sep>/blog/source/_posts/typescript-advanced.md --- layout: post title: "TypeScript 进阶" date: 2021-05-15 13:33 status: publish tags: [TypeScript, Type System] --- 请移步知乎“前端之美”专栏 [TypeScript 进阶](https://zhuanlan.zhihu.com/p/370000610) 查看全文。 <file_sep>/blog/source/_posts/hire-slow.md --- layout: post title: "Hire Slow" date: 2022-04-04 08:51:04 status: publish tags: - Recruitment - Organization --- 我曾亲眼见证过这样一个事情: 一个内部工具团队,因为业务增长太快压力山大,某个时间点 lead 在招聘方面做出了妥协,放水招进来一个看起来还凑合的工程师。 过了一小段时间,团队里其他人慢慢开始离职。有几个是我非常熟悉的伙伴,平时跟他们沟通不少,大家普遍的一些感触是:我怎么和这样的人一起工作。 再后来,团队雪崩式解散,部门领导不得不抽调其他资源维系业务运转。 有一次我也跟原来的 lead 闲聊,当谈到为什么当初招那个人的时候,他坦言:业务太多了,内部服务开发又不招人喜欢,没办法。 这些年来,随着团队管理经验的逐步积累,我越来越意识到师傅曾经教给我们的那句话的重要性:“Hire slow,fire fast”。今天我们就先聊一下前半句:Hire slow。 <!--more--> ## 业务压力大 => 不得不降低标准招人? 这是一个很自然的想法,没有人就没有资源迭代旧服务和开发新服务,要不然怎么办? 问题就在于这儿,作为团队负责人,切忌**把自己逼得只有一个选择**。 认真思考下,真的就没有别的办法了吗?譬如,是否可以尝试: - 开源 - 跟上级 lead 充分沟通,争取临时借调兄弟组资源等方式 - 请求倾斜招聘资源,并推动内推、猎头等多种形式举荐人才 - 尝试引入外包或者临时工等外部资源 - 节流 - 精简需求,把钢用到刀刃上 - 采购 SaaS 服务或者基于成熟开源方案快速开发 - 提效 - 培养团队成员的核心技能,重点是开发能力和沟通能力,让他们成长更为快速一些,早日担当大任 - 积累可复用的方案、框架、中间件等,提升工程效率 这里只是列出一些可能的办法,实际大家可能还能想出更多。 其实 lead 除了在开源节流方面做得不是很理想外,还有一个认知上的误区: > 内部服务开发又不招人喜欢 也许他本心也是这么认为的,但笔者不敢苟同。 内部系统确实有一定的局限性:用户少,需求杂,工期短,反馈多。 基本都是围绕 CRUD,做得好没人说,有问题挨批评,经常吃力不讨好。这些都是现实问题。 但跳出这个层面来看,内部系统其实某种程度上是公司成败的“秘密武器”: - 内部系统对于降本增效有极大的促进作用 <p style="margin: 0 0 0.2rem 1.4rem"> 一个好用的内部系统,实际上是围绕组织结构来深度定制的,取舍得当的话,往往可以对业务和组织的不断演进产生深远影响。 美团早期在快速上单方面做的一系列结构化深度改进让整个运营团队的效率提升了一大截,成功在千团大战等激烈竞争中脱颖而出。 </p> - 内部系统可以充分挖掘用户、业务的痛点,以及大家的正向反馈 <p style="margin: 0 0 0.2rem 1.4rem"> 用户可以轻易触达,业务也比较方便深入调研,这都是难得的差异化优势。另外,lead 要去注意抓一些用户或者数据方面的正向反馈, 以此来给团队带来更多荣誉感和正向激励,让大家明白自己做的事情的价值 </p> 类似人的五官一样,没有哪个是可以或缺的,内部系统也很重要,让团队理解自己团队的价值是 lead 的最为重要的职责之一。 ## 降低标准招人的后果 那实在是没有办法的情况下,不得不降低标准招人的话,会有什么后果呢? Netflix 创始人 Hastings 在“不拘一格”一书中提到了平庸的工程师带来的一些负面影响: - 消耗管理者的精力,使他们没有时间把精力放在优秀员工身上 - 团队讨论的质量得不到保证,拉低团队整体智商 - 强迫他人国绕着他们开展工作,致使工作效率低下 - 排挤其他追求卓越的员工 - 向团队表明你接受平庸,从而使问题更加严重 最大的问题在于:劣币驱除良币,其他的优秀工程师其实并不缺乏好机会,一旦他们确信团队水平在逐渐变差,那么离开是迟早的事。 长此以往,团队只剩下一群次等工程师,交付能力愈加堪忧,撤职跑路也就为时不远了。 因此,原则上,绝不能优先考虑在招聘标准方面做出让步,这应该是所有尝试都失败的情况下才不得已而为之,仅限于短期手段的无奈之举。 ## 招聘速度过快还有更多问题 Hire slow 除了说不要降低标准招人以外,还有一个内涵就是:不要招聘过快。 初听起来这是反直觉的,业务发展快,团队招人也很顺利,那么快速招兵买马应当是自然之举。 但事实并不是这样,和机器可以轻易水平扩容不同,工程师毕竟是人,平时工作的相当比例的时间其实是在沟通协作,扩张过快容易产生一系列问题: - 没有足够资源指导新人适应团队,任其自生自灭导致成长不稳定 - 过分多样化的人员背景导致内耗加大,很多项目推进效率低下,争论不已 - 团队优秀文化迅速稀释,认同感凝聚感逐步淡化 正如 Brooks 在“人月神话”中提到的,粗暴加人对于项目进度有可能是负面而非正面影响。 建设团队,需要“结硬寨,打呆仗”,稳扎稳打,才能在永葆精华的同时,有序提升组织能力。 <file_sep>/blog/source/_posts/yui3-in-meituan.md --- layout: post title: "YUI3在美团" date: 2011-08-04 19:51 status: publish tags: [YUI, Meituan] --- <div style="text-align:center;"><div style="width:425px; margin:0 auto;" id="__ss_8759550"><object id="__sse8759550" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=yui3-110802225931-phpapp02&stripped_title=yui3-8759550&userName=springuper" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed name="__sse8759550" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=yui3-110802225931-phpapp02&stripped_title=yui3-8759550&userName=springuper" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object></div></div> <p style="text-align:center; text-indent:0;"><a href="/assets/YUI3-in-Meituan.key_.zip">keynote下载</a> | <a href="/assets/YUI3-in-Meituan.pdf.zip">pdf下载</a></p> <!-- more --> ## Notes: 1. 常荣幸和大家一起分享我们团队在YUI3方面的一些实践。 2. 我叫尚春,他们都叫我春哥。这里是我的博客和email。我在2010年12月11日毕业后进入美团工作,到现在已有7个多月的工作经验。这段时间,在师傅的指导下迅速成长,对前端的认识不断深入。 3. 此次分享主要涉及两方面的内容。首先是关于选择YUI3作为基础库的原因,这里我们重点介绍下YUI3的模块机制;然后我们主要就我们实际迁移中遇到的一些挑战作详细表述,例如划分模块、加载策略等。 4. 简要介绍下我们的前端团队。我们是一支小而精悍的队伍,为美团网视觉界面和用户交互提供充足动力。 - 我们崇尚的是“快”,通过快速开发、快速部署、快速迭代来完成任务、优化功能 - 我们坚持“在行进中开火” - 我们认为做事不应该准备太多,一定要先做起来,然后发现不足并不断改进,宁可十年不将军,不可一日不拱卒 这些信条可能更加适合我们这样的小团队。 5. 我们首先要回答的问题是:为什么选择YUI3。第一个原因,我们原来采用的是YUI2。作为YUI团队的作品,YUI2非常正统、稳定。第二个原因,YUI团队已经把重心转移到YUI3,基本不再维护YUI2。但这都不是最有说服力的原因。 6. 最为重要的原因是YUI3本身,它足够的优秀。YUI3具有很多新的特性,例如模块机制、选择器的全面应用、更强大的自定义事件、组件框架等等。如果说YUI2是库时代杰出典范之一的话,YUI3就是框架时代一颗璀璨的明星。 7. 时间有限,我们重点介绍下YUI3的模块机制。模块是YUI3最大的变化,没有之一。这一底层设计机制改变了原有YUI2时代的规则。它为我们带来了自动加载、沙箱、combo等等特性,解放生产力的同时,提高了多人协作上的便利。使用YUI3添加模块、调用模块比较简单。 8. 我们把源码进行适当简化,主要理解一下内部的机制。YUI构造器的add方法是这样定义的,即将模块的信息注册在YUI构造器的静态属性Env中。 9. YUI的use方法主要流程是:计算调用模块所依赖的所有模块,将这些模块进行排序并输出,通过attach方法将这些模块的api依次捆绑在YUI实例(沙箱)上,将载满api的YUI实例传递到回调函数中。 10. 与直接嵌入script标签相比,模块的特点有: - 注册模块与调用模块分离,两者不是紧密耦合关系 - 所有模块都加载并绑定后才会执行回调函数,多个use间是异步关系。但,当所有模块都具备的情况下,多个use又是同步关系 - 通过实例绑定调用模块的api,实现了一种简便的沙箱机制。这一机制有利于协同开发 - 在模块定义时的一些元信息将所有模块有序组织起来,形成一个系统 11. YUI3的所有模块分为四个层级,它们构成了YUI3的架构。 - 最底层是种子文件YUI,它定义了YUI构造器以及yui模块,主要包括Lang,UA,封装的Array, Object, 以及Get等等 - 第二层为核心工具层,主要是一些工具模块,例如DOM,Node,Event - 第三层为组件框架层,主要是为构建组件提供丰富灵活的机制 - 第四层为组件层,包括了IO,JSON,Animation等重要模块 12. 我们遇到很多挑战: - 如何将原来的功能划分为模块,如何将所有模块组织起来,这是比较大的一个挑战 - Combo服务的实现。yahoo的combo只能提供YUI自身模块,而且速度在国内并不占优势。我们采用了minify,进行了一些修改和配置,能够在线上线下提供combo的支持 - 模块加载策略的研究 - 版本管理的问题。原来我们采用了query string的方式进行版本管理,现在则是用embedding的方式 13. 目前,我们已经将大多数后台系统迁移到了YUI3。本季度我们要完成主站的迁移工作。 14. 在介绍迁移之前,先看一下原来我们组织js的方式。这里主要包含三类文件:二次开发的核心文件core.js和一些widget文件,应用层级的文件,例如app-deal.js,来自第三方的文件,例如jquery.js。这种方式非常简单,但在web app时代已经不再适合较为复杂的前端开发,维护成本比较高。 15. 那如何划分模块呢,我们总结了如下几条原则: - 抽象与应用必须脱离。更通用的功能应该放在更低的层级,应用层完全面向实际问题,在解决的过程中调用抽象出来的方法 - 职责单一。保持每个模块的职责足够简单,方便维护和可持续开发 - 粒度得当。有了combo,我们可以不必担心粒度太小,文件过多导致的速度问题。但是,从可维护的角度来考虑,粒度应该适当而不宜过小,避免海底捞针的情形出现 - 我们的模块体系应该是开放的,不符合YUI规范的第三方模块,我们可以借鉴整合进来,使我们的基础框架更加完善,更加性感 16. 美团的JS架构,按照抽象与应用程度,分为四层: - 最底层交给强悍的YUI3,为我们提供很跨浏览器的api和很好的框架 - 第二层是我们二次开发的一些核心方法和控件库。mt-base中包含strtotime,getRadioValue等基础方法,对Cookie的简单操作,一些封装的页面动画等。w-base,w-autocomplete等包含一些封装的控件,提供更加高效的用户体验,且便于后端人员调用 - 第三层包含美团各个分站点的一些通用模块。例如mis-base包含后台mis系统的消息系统、checkFormChanged等通用方法。这一层更加接近应用 - 最上面一层,应用模块,这些模块的方法都是用来解决实际问题的。例如mis-deal用来处理mis系统中所有deal相关页面的交互,finance-pay用来处理财务系统中的付款相关页面的交互。一些零碎的应用方法我们放在对应站点的misc模块中 20. 为了保持向前兼容,我们定义了新的全局对象M。我们对YUI进行了简单的封装,可以使用M.add添加模块,使用M.use调用模块。请注意,每次使用M.use都会新生成一个config的实例,这个config信息主要包含一些combo服务器信息,我们自己开发模块的信息。这样loader就知道该如何计算依赖的模块了。在对use的封装中,我们还引入了debug的功能。[代码演示] 24. 目前我们采用的加载方式是:预加载通用基础模块,例如yui,node,event,io等,然后是站点级别的一些操作,例如mis系统的widget初始化、消息系统初始化等,最后是页面级别的一个特定应用入口。 25. 我们对基于PHP loader的服务器端loader进行了尝试,并准备近期进行部署。 服务器端loader优势在于速度,同时,将其整合在框架中降低了维护成本,简便易用。 26. 通过使用服务器端loader,可以做到一次性加载。 <file_sep>/blog/source/_posts/ask-with-answers.md --- layout: post title: 带着“答案”去提问 date: 2023-05-30 21:50:00 status: publish tags: - Communication - Asking --- 前几天,一位美国团队的负责人跟我谈到了他团队里的两位工程师。其中一个工程师每周和他一对一沟通的时候都提出了好几个技术性的问题,诸如: - 调试过程中发现本地环境遇到一个错误跑不起来 - 在测试环境下面各种参数如何调节 - 压力测试中发现的一些新的不及预期的现象 如此等等。总结下来,他感觉这位高级工程师更像是一个 Problem Maker,在不断地需要他介入到特别细枝末节的地方,给出具体的意见后才能进一步开展工作。 相比之下,另一位工程师则会在一对一沟通中除了汇报主要进展外,也会提出一两个接下来需要重点关注的问题。不同的是,那位工程师除了抛出问题外,还会提出几个他考虑到的可行性方案,并虚心跟他讨教。这位负责人笑着跟我说这样的团队成员才是他心目中称职的“高级”工程师,是典型的 Problem Solver。 这个案例彰显出“带着答案去提问”的重要价值,尤其在远程协作或者大型组织等沟通渠道弥足珍贵的环境中,这种能力更值得重视和培养。接下来我们从几个方面阐释其中的内涵。 <!--more--> ## 答案让问题变得更完整 在提问问题时,提供可能的答案可以帮助澄清问题的意图,并给出更为清晰的上下文。例如,假设你想问一个关于旅行目的地的问题:“我应该去哪里旅行?”如果你只问这个问题而没有提供任何上下文,对方可能会很难给出有用的建议。但如果你提供了一些可能的答案,如:“我正在考虑去巴黎、东京或者悉尼旅行”,那么回答者就可以更好地理解你的兴趣和偏好,并给出更具针对性的建议。 在技术性问题中也是类似的,如果只是说“我们应不应该在这个项目中使用 React Query?”那么对方并不知道你是建议使用这个工具,还是看到一些现有方案的问题所以在考虑一些业界流行的方案,还是有什么其他意图。但如果换成“我们应不应该在这个项目中使用 React Query?我发现这个内部系统里其实主要的客户端状态都和服务器数据交互相关,这种场景 Redux 显得臃肿了,看起来 React Query 是一个更好的选择,另外一个我了解到的方案是比较轻量级的 SWR”,估计对方就会很快领会你的问题是觉得 React Query 以及 SWR 这类新兴工具可以更好地处理服务器数据交互类场景。 ## 抛砖引玉提升沟通效率 在提问时准备的“答案”并不需要是最优的,它们更像是大海中的一座座灯塔,指明大致的方向即可,可以为对方提供一些参考,避免回答重复或不相关的信息,并促进进一步的讨论。 举一个简单的例子:小张在开发一个新功能的时候,发现需要用到的一个工具函数已经有多个版本的实现了,它们有些略微差异但是本质上可以通过一个通用方法解决。然后他去组里跟大家说:“我们代码仓库 xxx、yyy、zzz 这几个方法重复了,我们能不能重构下?” 在另外一个平行时空,面对同样的问题,小李做了一些简单的分析后,是这样跟大家沟通的:“最近我在开发一个新项目的时候,发现已经有 xxx、yyy、zzz 都用来处理数据分组问题了。我简单看了下它们各自的实现,其实是可以通过传递一些参数来整合为一个方法,重构完能减少上百行代码。或者也可以考虑直接使用一个流行的开源工具库里的 groupBy 方法。我目前想到这两个办法,权当抛砖引玉,大家一起看看怎么解决比较好呢?” 对比两种方式,明显第二种信息量要多出很多。相信如果你是他们团队中的一员,看到小张的问题你会觉得这几个方法可能有问题,但是还得实际看一看。但看到小李的描述,你应该大概已经知道这几个方法大概率是不同人不同时期添加的,属于技术债务。而且看起来引入一个比较标准的工具库会是一个更好的方案。当然,进一步可以去分析为什么这些工具函数会出现如此多的重复,是不是因为缺乏文档、缺乏规范等等。 除了提供更为丰富的信息,与问题相互印证之外,这些解决方案也提供了借鉴意义,让大家的讨论不再是天马行空,而是有了基本的“锚”,话题会围绕这几个方案的优缺点逐步展开,甚至往往能够引申出更加合理的新方案。这里其实是有一点心理学的概念的,做选择往往比给答案更容易,而且更有启发性。在《程序员修炼之道》中有一个“石头汤”的故事,本质也是类似的。 抛砖引玉,有的放矢,最终达成的效果是大家可以更有效地沟通,进而更快地达成共识,促进产出。 ## 主动思考带来更多成长 发现问题是第一步,能够主动思考并提出有效方案是更高能力的体现,是第二步。相比较而言,这种意识的培养比技术的提升更容易,但效果却出乎意料地好,可谓极具性价比。初期的“答案”可能有些初级,但你的沟通对象至少会认为你非常负责任,也对他们足够尊重,做了一些功课才来请教他们。随着这种思维模式的贯彻和深入,你会找到更多有效的办法去寻找更优的方案,例如先与团队里的领域专家沟通、使用 ChatGPT 咨询建议、进行 PoC 进行简单验证等等。日积月累,你可能就会进入第三步:给出各个方案的优缺点,并陈述你的推荐方案以及理由,这足以表明你已经具备了一定的判断力和决策能力。上级和同事们看到你积极参与和贡献解决问题的能力,会加强对你的信任和认可,从而获得更大的发展空间。 换个角度来看,实际上带着答案去提问本质上是站在对方的角度去考虑问题,甚至是站在团队负责人或上级的角度去综合评估最优解。这种格局带来的提升动力非常强劲,对个人能力的全方面提升相当重要。 ## 小结 在遇到一个新问题时,直接将问题抛出去既不专业也不负责。其他人可能会感到一头雾水,因为缺乏一些关键信息云里雾里。如果其他人发现这个问题其实行业内或团队内之前曾有过经验,或者认为提问者完全有足够能力搞定,也会降低对提问者的信任度。相反,如果每次遇到一个新问题都能够主动思考,准备一些初步的思路甚至解决方案,往往会给对方如遇春风的感觉,有助于快速达成共识。更重要的是,这种思维方式能够提升一个人的格局,为后续的发展进步奠定更为坚实的基础。 ## 参考资料 - [在职场,有问题该怎么提问?](https://36kr.com/p/1953327724501128) - [这样提问,你不可能得到想要的答案!](https://www.woshipm.com/zhichang/4239783.html) - [有效提问 - 鸟哥笔记](https://www.niaogebiji.com/article-33854-1.html) - [提问的智慧](http://cripac.ia.ac.cn/people/wwang/post/how-to-ask-questions-the-smart-way/) - [带着答案问问题](https://wenku.baidu.com/view/a8de92b352e79b89680203d8ce2f0066f5336483.html) <file_sep>/share/react-lifecycle-in-depth/demo/construction/src/Person.js import React, { Component } from 'react'; class Person extends Component { componentWillReceiveProps(nextProps) { console.log('===componentWillReceiveProps', nextProps); } render() { return ( <div> Hello, {this.props.name} </div> ); } } export default Person; <file_sep>/blog/source/_posts/yui3-practice.md --- layout: post title: "YUI3在美团的实践" date: 2013-05-10 22:35 comments: true status: publish tags: [YUI, Framework, JavaScript] --- 美团网在2010年引爆了团购行业,并在2012年销售额超过55亿,实现了全面盈利。在业务规模不断增长的背后,作为研发队伍中和用户最接近的前端团队承担着非常大的压力,比如用户量急剧上升带来的产品多样化,业务运营系统的界面交互日益复杂,代码膨胀造成维护成本增加等等。面对这些挑战,我们持续改进前端技术架构,在提升用户体验和工作效率的同时,成功支撑了美团业务的快速发展,这一切都得益于构建在YUI3框架之上稳定高效的前端代码。在应用YUI3的过程中,我们团队积累了一些经验,这里总结成篇,分享给大家。 ## 为什么选择YUI3 使用什么前端基础框架是建立前端团队最重要的技术决策之一。美团项目初期因为要加快开发进度,选择了当时团队最熟悉的YUI2(前框架时代杰出的类库),保证美团能够更快更早地上线,抢占市场先机。不久由于前端技术发展很快,YUI2的缺点逐渐凸显,例如开发方式落后、影响工作效率等等,于是我们开始考虑基础库的迁移。 经过一段时间对主流前端库、框架的反复考量,我们认为YUI3是最适合我们团队使用的基础框架。 首先,国内的开源框架及其社区刚开始起步,在代码质量、架构设计和理念创新上还难以跟YUI3比肩,所以基本排除在外。其次,国外像YUI3这样面向用户产品、文档丰富、扩展性良好的成熟框架屈指可数,例如ExtJS和Dojo则更适合业务复杂的传统企业级开发。最后,使用jQuery这种类库构建同YUI3一样强大的框架对创业团队来说并不可取,美团快速发展、竞争多变的业务特点决定了我们必须把主要精力放在更高一层的业务开发上,而不是去重复发明一个蹩脚的YUI。 YUI3成为最终选择有以下几个直接的原因: - 非常优秀,是真正的框架,真正的重型武器,具有强劲的持续开发能力,可以应对业务的快速发展。不管是规模不断增长的用户产品,还是交互日趋复杂的业务系统(美团有超过100个业务系统作全电子化的运营支撑),YUI3都游刃有余。 - 代码整齐规范,容易维护,适合有洁癖的工程师,同时能够显著提高团队协作时的开发效率。因为人手紧缺,后端工程师也需要参与前端开发,一致的代码风格使前后端配合轻松简单。 - 有出色的架构设计,是很好的框架范本,通过研究学习可以帮助工程师成长,培养良好的工程思维。人是美团最重要的产品。 随着团队成长,我们最后引入了YUI3,在迁移过程中,遇到了很多技术上的和工程上的挑战,但是我们一直在前进,一直在行进中开火。从结果来看,YUI3为我们团队提供了先进生产力,为快速开发、快速部署、快速迭代提供了源源不断的力量。 YUI3的优秀主要表现在模块和组件框架的出色设计,下面我们着重介绍这两方面的一些实践经验。 <!-- more --> ## 改变一切的模块 前端开发日益复杂化,代码组织成为一个显著的问题。受到后端代码普遍采用的模块机制启发,很多前端模块机制应运而生。目前比较著名的有CommonJS和AMD。但早在2008年8月13日,YUI3 Preview Release 1中就已经给出了YUI团队的解决方案,并在2009年9月29日YUI3正式版发布时定型。 以下是使用YUI3进行模块化开发的简单例子 ```javascript // 定义模块 YUI.add('greeting', function (Y) { Y.sayHello = function () { console.log('Hello, world!'); }; }); // 调用模块 YUI().use('greeting', function (Y) { Y.sayHello(); // output 'Hello, world!' }); ``` 模块的引入,使得更细粒度的按功能进行代码组织成为可能,也为方便的进行扩展和分层提供了基础,自底向上的彻底改变了YUI3。一套完整的模块机制,还包括解决关系依赖、自动加载的Loader和提高加载效率的Combo。 面对如此彻底的改变,我们需要解决很多挑战: - 如何将原来的功能划分为模块? - 如何管理模块元信息? - 如何高效的获取模块? ### 划分模块 经过两年来不断的实践和总结,我们归纳了如下几条划分模块的原则: - **抽象与应用脱离**。更通用的功能放在更低的层级,应用层完全面向实际问题,在解决的过程中调用抽象出来的方法。 - **职责单一**。保持每个模块的足够简单和专一,方便维护和可持续开发。 - **粒度得当**。有了Combo,我们可以不必担心粒度太小,文件过多导致的速度问题。但是,从可维护的角度来考虑,粒度应该适当而不宜过小,避免海底捞针的情形出现。 - **海纳百川**。我们的模块体系应该是开放的,不符合YUI规范的第三方模块,可以借鉴整合进来,使我们的基础框架更加完善,更加性感。 <center> <img alt="美团前端架构" src="/images/mt-fe-architecture.png" /> </center> 按照模块的层次划分,美团的JS框架可以分为四个层次: 1. **最底层交给强悍的YUI3**,为我们提供跨浏览器兼容的API和良好的框架设计。 2. **第二层是我们二次开发的核心方法、组件(Component)和控件(Widget)**。现已独立为前端核心库,为美团所有系统提供前端支持。核心库的种子文件中定义了全局变量M,除了对YUI3进行封装的代码以外,还包含了对语言层面的扩展,以及一些基础工具类。核心库有一个非常重要的组成部分,就是我们功能丰富的控件集合,比如常用的自动完成、排序表格、气泡提示、对话框等基础控件。除了这些,核心库还包含了常用的基础组件、插件(Plugin)、扩展(Extension)以及单元测试代码。 3. **第三层包含各个系统的一些通用模块**。例如www-base模块包含美团主站(www)的消息系统、用户行为追踪系统等通用功能。这一层更加接近应用。 4. **最上面一层,应用模块**。这些模块的方法都是用来解决实际业务问题。例如www-deal用来处理美团主站所有deal相关功能的交互,finance-pay用来处理财务系统中付款相关的交互。一些零碎的应用方法我们放在对应系统的misc模块中,避免模块碎片化。 这套框架仍在不断演变,以便更好的支撑业务需求。其中一个明显的方向是,在第二层和第三层之间,出现一个为了更好整合所有内部业务系统前端通用资源的中间层。 ### 管理模块元信息 模块元信息主要包括模块名称、路径、依赖关系等内容。其中最为重要的是依赖关系,这决定了有哪些模块需要加载。为了实现自动加载,需要将所有模块的元信息提供给YUI的Loader。 最初,为了更快的从YUI2迁移到YUI3,模块元信息放在PHP中进行维护。随着时间的推移,渐渐显示出很多弊端。首先,在定义模块的js文件中已经包含模块名称、依赖关系等信息,和PHP中内容重复。其次,这些元信息最终直接输出到html中,没有有效利用缓存。 随后,我们使用NodeJS开发了一系列脚本,收集所有模块元信息,保存为独立js文件,并实现了自动化。为了防止出错,在Git Hooks和上线脚本中都加入了校验过程。工程师需要做的,只是修改模块定义中的元信息。 最近一段时间,我们的精力主要放在两个方面: - **自动生成依赖**。随着模块粒度细化和模块数量的增长,依赖关系日益复杂,依靠人工配置经常出现过多依赖或过少依赖等问题。我们准备开发一套自动扫描模块引用API,并确定依赖关系的机制。 - **自动打包依赖模块**。如果在代码发布时,就已根据页面模块调用计算好所有依赖模块,并进行打包,可以避免引用全部模块元信息、Loader计算依赖等过程,提高网站性能。 ### Combo Combo可以一次请求多个文件,能够有效解决多个模块加载带来的性能问题。Yahoo提供了Combo服务,但只能提供YUI3模块,而且速度在国内并不理想。为了提供更好的体验,让用户访问速度更快,我们最终考虑搭建自己的Combo服务,并把Combo发布到CDN上。 以下是一个Combo请求的例子: ``` http://c.meituan.net/combo/?f=mt-yui-core.v3.5.1.js;fecore/mt/js/base.js ``` 为了节约时间,我们最开始采用了开源的minify,经过一些修改和配置,就可以在生产和开发环境提供Combo服务。使用一段时间后,发现minify过于复杂,以至于添加一些定制功能相当困难。我们需要的只是简单的文件合并功能,在明确需求和开发量后,着手开发自己的Combo程序。从最初的仅支持文件合并,后来陆续添加了服务器/浏览器端缓存、文件集别名、调试模式、CSS图片相对路径转URI、错误日志等特性,全部代码仅有300多行。经过两年时间以及每天几千万PV的考验,服务一直非常稳定。 ## 灵活健壮的组件框架 YUI3之所以成为纯粹的框架,真正的原因在于提供了一套灵活、健壮的组件框架。借助这套框架,可以轻松的将业务场景进行解耦、分层,并持续的进行改进。通过不断的实践,我们越发认为这是YUI3的精髓所在。 从YUI3定义的开发范式和源代码中可以看出,YUI团队非常重视AOP(Aspect Oriented Programming)和OOP(Object Oriented Programming),这一点可以在接下来的介绍中有所体会。 ### EventTarget、Attribute和Base 在介绍组件框架之前,有必要首先了解下EventTarget。YUI3创建了一套类似DOM事件的自定义事件体系,支持冒泡传播、默认行为等功能。EventTarget提供了操作自定义事件的接口,可以让任意一个对象拥有定义、监听、触发、注销自定义事件的功能。YUI组件框架中的所有类,以及在此框架之上开发的所有组件,都继承了EventTarget。 Attribute是组件框架中最底层的类,实现了数据和逻辑的完美解耦。为什么说是完美呢?存储在attribute(Attribute提供的数据存取接口)中的数据发生变化时,会触发相应的事件,为相关的逻辑处理提供了便捷的接口。从下面这个简单的例子可以感受到这一点: ```javascript // 在name属性变化时,触发nameChange事件 this.on('nameChange', function (e) { console.log(e.newVal); }); // 修改name属性 this.set('name', 'meituan'); // output 'meituan' ``` 实践中发现,妥善处理属性的分类非常重要。供实例进行操作的属性适合作为attribute,例如表单验证组件FormChecker的fields属性,方便应用层进行表单项的增删改。在类方法内部使用的一些属性可以作为私有属性,例如计时器、监听器句柄。供所有类的实例使用的一些常量适合作为类的静态属性,例如一些模板、样式类。 Base是组件框架的核心类。它模拟了C++、Java等语言的经典继承方式和生命周期管理,借助Attribute来实现数据与逻辑的分离,并提供扩展、插件支持,从而获得了良好的扩展性以及强大的可持续开发能力。YUI团队通过多年来对业务实践的抽象,最终演化而成一种开发范式,这,就是一切组件的基石——Base,实至名归。 依照这种范式,我们开发了一系列组件,例如之前提到的FormChecker,以及延迟加载器LazyLoader、地图的封装Map等。最显著的体会是,开发思路更为清晰,代码结构更有条理,维护变得简单轻松。 ```javascript // 构造方法 FormChecker.prototype.initializer = function () { var form = this.get('form'); this._handle = form.on('submit', function (e) { // check fields }); }; // 析构方法 FormChecker.prototype.destructor = function () { this._handle.detach(); }; // 创建实例时,自动执行构造方法 var checker = new FormChecker({ form: Y.one('#buy-form') }); // 销毁实例时,自动执行析构方法 checker.destroy(); ``` ### Extension和Plugin Extension(扩展)是为了解决多重继承,以一种类似组合的方式在类上添加功能的模式,它本身不能创建实例。这种设计非常像Ruby等语言中的Mixin。Plugin(插件)的作用是在对象上添加一些功能,这些功能也可以很方便的移除。 它们有什么区别呢?简单来说,Extension是在类上加一些功能,所有类的实例都拥有这些功能。Plugin只是在某些类的实例中添加功能。举两个典型的例子:一些节点需要使用动画效果,这个功能适合作为Plugin。气泡提示控件需要支持多种对齐方式,所有实例都需要此功能,因此使用YUI3的WidgetPositionAlign扩展。 ```javascript // 传统的函数方式实现动画 Effect.fadeIn(nodeTip); // 插件方式实现动画 nodeTip.plug(NodeEffect); nodeTip.effect.fadeIn(); ``` Extension和Plugin很好的解决了我们遇到的诸多功能重用问题。我们开发了提供全屏功能的WidgetFullScreen、自动对齐对话框的DialogAutoAlign等扩展,以及进行异步查询的AsyncSearch、提供动画效果的NodeEffect等插件。将这些偏重OOP的编程思想应用在前端开发中,比较深刻的体会是:有更多的概念清晰、定位明确的开发模式可以选择。 ### Widget体系 Widget(控件)建立在Base之上,主要增加了UI层面的功能,例如`renderUI`、`bindUI`、`syncUI`等生命周期方法,`HTML_PARSER`等渐进增强功能,以及样式类、HTML结构和DOM事件的统一管理。Widget提供了控件开发的通用范式。 由于前端资源相对紧张,我们倾向于大量使用控件,尤其在业务系统这样更注重功能的场景。主要出于两点考虑: - **减少不必要的重复劳动,提高产出**。通过将交互、业务逻辑合理抽象,一次解决一类问题,One Shot One Kill。 - **节约前端工程师资源**。通过自动加载和初始化控件、封装简单易用的后端方法、制作Demo和使用手册等措施,降低使用门槛,后端工程师只需要知道参数的数据结构就可以轻松调用,提高了开发效率。 以下是一个自动加载控件的例子 ```html // 页面初始化时,会扫描所有带有data-widget属性的节点,自动加载对应控件,并根据data-params数据进行初始化 <a href="…" data-widget="bubbleTip" data-params='{ "tip": "全新改版,支持随时退款" }'>下载手机版</a> ``` 目前,我们已经构建了一个包含近30个控件的Widget体系,为所有系统提供丰富、便捷、集成的解决方案。 ## 行进中开火 在整个YUI3的实践中,我们犯过很多错误,例如全局只有一个YUI实例、Combo的CSS图片依赖等等,但这些并没有成为放弃的理由。从今天回过头来看,YUI3带给我们团队的,不只是更高的开发效率、更好的可持续开发能力,还有它本身的设计思路、源码书写、辅助工具等诸多方面潜移默化的影响。这些回报的价值,比起较高的使用门槛、犯过的一些错误,要贵重百倍。 指导这一切的,是我们始终坚持的 **“行进中开火”**。在互联网这个高速发展的行业里,对于我们这种小规模的创业团队,一天不前进,就意味落后。做事不应该准备太多,一定要先做起来,然后发现不足并不断改进,宁可十年不将军,不可一日不拱卒。每天都做得更好一点,日积月累,我们才会在激烈的竞争中占据越来越大的优势。 YUI3并非完美,存在着学习成本高、对社区不够开放等问题。我们所做的更远非完美,但经过不断的尝试和经验的积累,已经渐渐摸索出一条明确的路线,并会坚持不懈的继续走下去。 关于YUI3和我们团队更多的信息请关注 http://fe.meituan.com <file_sep>/blog/source/_posts/frontend-frp.md --- layout: post title: "前端中的 Functional Reactive Programming" date: 2022-01-18 10:10:23 status: publish tags: [Functional Programming, Functional Reactive Programming, RxJS] --- 请移步知乎“前端之美”专栏 [前端中的 Functional Reactive Programming](https://zhuanlan.zhihu.com/p/77687564) 查看全文。 <file_sep>/blog/source/_posts/frontend-frp-2nd.md --- layout: post title: "前端中的 Functional Reactive Programming(二)- 进阶版 AutoComplete" date: 2022-03-21 19:34:00 status: publish tags: [Functional Programming, Functional Reactive Programming, RxJS] --- 请移步知乎“前端之美”专栏 [前端中的 Functional Reactive Programming(二)- 进阶版 AutoComplete](https://zhuanlan.zhihu.com/p/473437861) 查看全文。 <file_sep>/blog/source/_posts/birth.md --- layout: post title: "创世纪" date: 2011-03-10 13:35 status: publish tags: [Self, Life] --- 至此,自己的blog终于搭了起来。 过程并不算复杂,不过还是需要一定的热情。 建站的初衷源于个人积累的一些诉求,希望能够将一些日常的idea或problem经过思维的处理沉淀成一直留守的文字,无论何时何地何人,看到它们时都会有一些收获或感想。 不追求能有很多人来看,我把这里当成自己的自留地,肆意非常。 持续的写作需要极大热忱,希望我能保持。 <file_sep>/share/from-mathematics-to-generic-programming/demo/genericAdvanced.ts // TODO find `type` to make generic type shorter function powerAccSemigroup<MultiplicativeSemigroup extends number>(r: MultiplicativeSemigroup, n: number, a: MultiplicativeSemigroup): MultiplicativeSemigroup { while (true) { if (odd(n)) { r = (r * a) as MultiplicativeSemigroup; if (n === 1) return r; } n = half(n); a = (a * a) as MultiplicativeSemigroup; } } function powerSemigroup<MultiplicativeSemigroup extends number>(n: number, a: MultiplicativeSemigroup): MultiplicativeSemigroup { if (n === 1) return a; return powerAccSemigroup(a, half(n - 1), (a * a) as MultiplicativeSemigroup); } function odd(n: number): boolean { return !!(n & 0x1); } function half(n: number): number { return n >> 1; } console.log('powerSemigroup', powerSemigroup(3, 59)); console.log('powerSemigroup', powerSemigroup(1, 59)); function powerMonoid<MultiplicativeMonoid extends number>(n: number, a: MultiplicativeMonoid): MultiplicativeMonoid { // if (n === 0) return MultiplicativeMonoid(1); if (n === 0) return 1 as MultiplicativeMonoid; return powerSemigroup(n, a); } console.log('powerMonoid', powerMonoid(0, 59)); function powerGroup<MultiplicativeGroup extends number>(n: number, a: MultiplicativeGroup): MultiplicativeGroup { if (n < 0) { n = -n; // a = MultiplicativeGroup(1) / a a = (1 / a) as MultiplicativeGroup; } return powerMonoid(n, a); } console.log('powerGroup', powerGroup(-3, 59)); interface Operation<T> { (a: T, b: T) : T; } function operateAccSemigroup<Semigroup extends number>(r: Semigroup, n: number, a: Semigroup, op: Operation<Semigroup>): Semigroup { while (true) { if (odd(n)) { r = op(r, a); if (n === 1) return r; } n = half(n); a = op(a, a); } } function operateSemigroup<Semigroup extends number>(n: number, a: Semigroup, op: Operation<Semigroup>): Semigroup { if (n === 1) return a; return operateAccSemigroup(a, half(n - 1), op(a, a), op); } console.log('operateAccSemigroup', operateSemigroup(3, 59, (a: number, b: number) => a * b)); console.log('operateAccSemigroup', operateSemigroup(3, 59, (a: number, b: number) => a + b)); <file_sep>/blog/source/_posts/event-custom.md --- layout: post title: "YUI事件体系之Y.CustomEvent" date: 2012-09-01 19:13 comments: true status: publish tags: [YUI, Event, JavaScript] --- ![DIY](/images/DIY.jpg) 上一篇[文章](/2013/01/20/event-do/)中,简要介绍了YUI实现AOP的`Y.Do`对象。 接下来,我们继续对YUI事件体系进行探索。本次要介绍的是`Y.CustomEvent`对象,从命名上就可以看出,这个对象在整个YUI事件体系中十分重要。它建立起整个自定义事件的体系,而且,DOM事件也构建在这个体系之上。 ## Y.Subscriber Y.Subscriber的作用比较简单:执行回调函数。 ```javascript Y.Subscriber = function (fn, context) { this.fn = fn; // 回调函数 this.context = context; // 上下文 this.id = Y.stamp(this); // 设置唯一id }; Y.Subscriber.prototype = { constructor: Y.Subscriber, // 执行回调函数 notify: function (args, ce) { if (this.deleted) return null; var ret; ret = this.fn.apply(this.context, args || []); // 只监听一次 if (this.once) { ce._delete(this); } return ret; } }; ``` ## Y.CustomEvent `Y.CustomEvent`主要作用是:建立自定义事件机制,为方便的进行事件创建、监听、触发提供良好基础。自定义事件机制,实际上是[Observer Pattern](http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)([Publish–subscribe Pattern](http://en.wikipedia.org/wiki/Observer_pattern)的演化)的一种实现,这种机制能够方便的实现模块间解耦,增强模块的扩展性。 YUI的自定义事件较其它一些js库来说要强大一些,有这样一些好的features: - 支持事件接口(Event Facade),在回调函数中可以进行调用 - 支持设置默认执行方法 - 支持停止/立即停止传播,并可设定停止传播时执行的方法 - 支持阻止默认行为(默认执行方法),并可设定阻止默认行为时执行的方法 - 支持冒泡。指定冒泡目标序列,就可以顺序的触发事件(需要`Y.EventTarget`) - 支持广播。每个自定义事件,都可以设置在当前YUI实例范围内和全局YUI内进行广播 可以看出,YUI的自定义事件和DOM事件极其类似,这种设计自然到我们在用自定义事件时,丝毫感觉不到和DOM事件的差异。 <!-- more --> ### 示例 让我们先来看个简单的例子: ```javascript // 例1 简单自定义事件 YUI().use('event-custom', function (Y) { var eatEvent = new Y.CustomEvent('eat'); var onHandle = eatEvent.on(function () { Y.log('before eating'); }); var onHandle2 = eatEvent.on(function () { Y.log('before eating, too'); }); var afterHandle = eatEvent.after(function () { Y.log('after eating'); }); // output: "before eating", "before eating, too", "after eating" eatEvent.fire(); onHandle2.detach(); // output: "before eating", "after eating" eatEvent.fire(); }); ``` 有些事件只需触发一次,比如你的各种第一次~~~。来看这个例子: ```javascript // 例2 仅触发一次的自定义事件 YUI().use('event-custom', function (Y) { var birthEvent = new Y.CustomEvent('birth', { fireOnce: true // you can only birth once }); var onBirthHandle = birthEvent.on(function () { Y.log('before birth'); }); // output: "before birth" birthEvent.fire(); // nothing happened birthEvent.fire(); // 只触发一次的事件在触发后,再次添加监听方法时,会被立即执行 // output: before birth, too var onBirthHandle2 = birthEvent.on(function () { Y.log('before birth, too'); }); }); ``` 也许你还在琢磨,事件广播是什么?因为YUI使用了sandbox设计,可以生成不同实例绑定不同api,所以才有了事件广播机制。来看这个例子: ```javascript // 例3 事件广播 YUI().use('event-custom', function (Y) { var cryEvent = new Y.CustomEvent('cry', { broadcast: 2 // global broadcast }); cryEvent.on(function () { Y.log('before cry'); }); Y.on('cry', function () { Y.log('YUI instance broadcast'); }); Y.Global.on('cry', function () { Y.log('YUI global broadcast'); }); // output: "before cry", "YUI instance broadcast", "YUI global broadcast" cryEvent.fire(); }); ``` 文章之前介绍过YUI自定义事件的种种NB之处,那么用起来如何呢,来看下面的例子: ```javascript // 例4 复杂自定义事件 YUI().use('event-custom', function (Y) { var driveEvent = new Y.CustomEvent('drive', { emitFacade: true, host: { // hacking. 复杂自定义事件需要指定host,该host必须augment Y.EventTarget _yuievt: {}, _monitor: function () {} }, defaultFn: function () { Y.log('execute defaultFn'); }, preventedFn: function () { Y.log('execute preventedFn'); }, stoppedFn: function () { Y.log('execute stoppedFn'); } }); driveEvent.on(function (e) { e.stopImmediatePropagation(); }); driveEvent.on(function (e) { e.preventDefault(); }); driveEvent.after(function (e) { Y.log('after driving'); }); // output: "execute stoppedFn", "execute defaultFn" driveEvent.fire(); }); ``` 不要失望,现在还没有介绍到事件体系的精华部分`Y.EventTarget`,所以很多特性(例如冒泡)还不能体现出来,拭目以待吧。 ### 源代码分析 接下来,让我们看看YUI的内部实现吧。 注:为了更容易的看懂代码的核心,我做了适当的简化,感兴趣的朋友可以去看未删节的[源码](http://yuilibrary.com/yui/docs/api/files/event-custom_js_event-custom.js.html#l38)。 ```javascript var AFTER = 'after', // config白名单 CONFIGS = ['broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type']; Y.CustomEvent = function (type, o) { this.id = Y.stamp(this); this.type = type; this.context = Y; this.preventable = true; this.bubbles = true; this.subscribers = {}; // (前置)监听对象容器 注:YUI3.7.0将此处进行了优化 this.afters = {}; // 后置监听对象容器 注:YUI3.7.0将此处进行了优化 this.subCount = 0; this.afterCount = 0; o = o || {}; this.applyConfig(o, true); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, // 设置参数 applyConfig: function (o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, // 添加前置监听对象 on: function (fn, context) { var a = (arguments.length &gt; 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, // 添加后置监听对象 after: function (fn, context) { var a = (arguments.length &gt; 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, // 内部添加监听对象 _on: function (fn, context, args, when) { var s = new Y.Subscriber(fn, context); if (this.fireOnce &amp;&amp; this.fired) { // 仅触发一次的事件在触发后,再次添加监听方法时,会被立即执行 this._notify(s, this.firedWith); } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, // 触发事件 fire: function () { if (this.fireOnce &amp;&amp; this.fired) { // 仅触发一次的事件,如果已经触发过,直接返回true return true; } else { // 可以设置参数,传给回调函数 var args = Y.Array(arguments, 0, true); this.fired = true; this.firedWith = args; if (this.emitFacade) { // 复杂事件 return this.fireComplex(args); } else { return this.fireSimple(args); } } }, // 触发简单事件 fireSimple: function (args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); // 处理前置监听对象 this._procSubs(subs[0], args); // 处理前置监听对象 this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // 判断是否有监听对象 hasSubs: function (when) { var s = this.subCount, a = this.afterCount; if (when) { return (when == 'after') ? a : s; } return (s + a); }, // 获取所有前置/后置监听对象 getSubs: function () { var s = Y.merge(this.subscribers), a = Y.merge(this.afters); return [s, a]; }, // 获取监听对象 _procSubs: function (subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { // 回调返回false时,立即停止处理后续回调 this.stopped = 2; } if (this.stopped == 2) { // 立即停止处理后续回调,方便实现stopImmediatePropagation return false; } } } } return true; }, // 通知监听对象,执行回调方法 _notify: function (s, args, ef) { var ret = s.notify(args, this); if (false === ret || this.stopped &gt; 1) { return false; } return true; }, // 广播事件 _broadcast: function (args) { if (!this.stopped &amp;&amp; this.broadcast) { var a = Y.Array(args); a.unshift(this.type); // 在当前YUI实例Y上广播 if (this.host !== Y) { Y.fire.apply(Y, a); } // 在全局对象YUI上广播,跨实例 if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, // TODO: 在下一篇介绍Y.EventTarget的文章中再做介绍 fireComplex: function (args) {}, // 移除监听器 detach: function (fn, context) { // unsubscribe handle if (fn &amp;&amp; fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s &amp;&amp; (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, _delete: function (s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (s) { s.deleted = true; } } }; ``` ### 适用场景 自定义事件的适用场景与Publish–subscribe Pattern基本一致。具体来讲,我觉得以下一些场景是非常适合用自定义事件的: #### a) 需要暴露接口/行为以满足扩展需要 底层模块一般会设计的尽量简单,解决核心问题,并适当的开放一些接口,方便应用层进行扩展以满足实际需求。例如表单验证控件,有可能需要在某个表单项验证成功/失败后执行一些额外操作,举一个实际的例子:当用户输入的邮箱地址验证成功时,我们会检查是不是某些比较烂的邮件服务商,如果是则给出一些建议。 YUI作为一个底层基础库,在组件/控件层面加入了大量的自定义事件,以满足实际应用中的需要。例如`Y.Anim`的start、end事件,`Y.io`的success、failure、end事件,`Y.Attribute`中的属性变化事件等。 #### b) 行为可能会被其它模块/方法中止 这一点非常像DOM事件,我们经常会中止一些事件的默认行为,例如anchor的点击事件。 ### 自定义事件 VS 回调函数 这是一个比较难的问题,我自己的看法是:相对回调函数,自定义事件是一种更重但更灵活的方案。在实际应用中,如果对于关心某消息的受众不够清楚,那么就使用事件。否则,比较适合使用回调函数。 [MSDN](http://msdn.microsoft.com/en-us/library/aa733743%28v=vs.60%29.aspx)上的解释更好一些:“An event is like an anonymous broadcast, while a call-back is like a handshake. The corollary of this is that a component that raises events knows nothing about its clients, while a component that makes call-backs knows a great deal”。 另外,如果对于性能特别关心,在可能的情况下,尽量使用回调。 ## 参考 - [YUILibrary-CustomEvent](http://yuilibrary.com/yui/docs/api/files/event-custom_js_event-custom.js.html) - [YUILibrary-EventTarget](http://yuilibrary.com/yui/docs/event-custom/index.html) - [Wikipedia-Publish–subscribe Pattern](http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) - [Zakas-Custom events in JavaScript](http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/) - [When to Use Events or Call-Backs for Notifications][1] [1]:http://msdn.microsoft.com/en-us/library/aa733743(v=vs.60).aspx <file_sep>/blog/source/_posts/typescript-101.md --- layout: post title: "浅谈 TypeScript 类型系统" date: 2019-06-22 13:53 status: publish tags: [TypeScript, Type System] --- 请移步知乎“前端之美”专栏 [浅谈 TypeScript 类型系统](https://zhuanlan.zhihu.com/p/64446259) 查看全文。 <file_sep>/README.md # <NAME> Github Pages Maintain my personal website. <file_sep>/blog/source/_posts/react-design-highlights.md --- layout: post title: "React 设计中的闪光点" date: 2018-01-31 21:04 status: publish tags: [React, Virtual DOM, Fiber] --- 请移步知乎“前端之美”专栏 [React 设计中的闪光点](https://zhuanlan.zhihu.com/p/28562066) 查看全文。 <file_sep>/blog/source/_posts/change-theme.md --- layout: post title: "新外观,更优雅,更直接" date: 2011-06-05 20:20 status: publish tags: [Self, Metro] --- ![Metro](/images/metro.png) 我叫尚春,来自美团网 如你所看 我的blog彻底重建 引入了很多[Metro](http://ubelly.com/2011/01/metro-windows-phone-7-design-language/)的设计理念 因为我欣赏更加凸显内容的表达方式 而不再认为高光、阴影是现代风格所必须 这,是一种真正意义上的返璞归真 在这里 所有的图标都是用[Raphaël](http://raphaeljs.com)绘制 我写的一个小型通用库Spring也崭露头角 并将茁壮成长 一切都远未完善 我会有节奏的进行 这一切都值得期待 <file_sep>/share/node-async/demos/sync.go import ( "fmt" "net/http" "io/ioutil" ) func main() { response, _ := http.Get("http://www.10101111.com") defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body) fmt.Println(string(body)) fmt.Println("do other stuff") } <file_sep>/blog/source/_posts/fe-pipeline.md --- layout: post title: "前端中的 Pipeline" date: 2017-10-05 21:35 status: publish tags: [FrontEnd, Pipeline, Middleware, Stream, Promise] --- 请移步知乎“前端之美”专栏 [前端中的 Pipeline](https://zhuanlan.zhihu.com/p/28561932) 查看全文。 <file_sep>/blog/source/_posts/recruitment-driven-organization.md --- layout: post title: 招聘驱动的组织建设 date: 2021-11-23 21:56 status: publish tags: - Recruitment - Organization --- 今天有一位候选人问我:“你作为团队负责人,最重要的工作是什么?”,坦白来说,我自己并没有很深刻地思考过这个问题。脱口而出的答案是:招人,招足够优秀的人。 这时,我看到候选人深以为然地点了点头,似乎是非常认可我这由衷的答复。考虑到他也十足优秀,既然得到了肯定,那我不妨继续沿着这个思路畅想下,谈谈招聘驱动的组织建设。 ## 组织建设的核心? 在我们这个工程师行业,虽然很多人声称自己是码畜,只是外表光鲜地干着搬砖的体力活。不过纵观最近 20 多年互联网的飞速发展,诚如 <NAME> 所言,真正意义上的工程师,或者黑客,实际上是最具有可放大性和可测量性的工种之一。当你的代码跑在成百上千台机器上为百万千万甚至以亿计的用户服务时,毫无疑问你的价值也得到了巨大程度的放大。 进一步,优秀的工程师和普通的工程师的差距就像太阳和灯泡一样大,虽然都能发光发热,但是数量级不一样。 基于此,我粗俗地以为,工程师组织建设的核心就是招人,招足够优秀的人: - 优秀的工程师会带来优秀的解决方案,进而提升组织效能 - 优秀的工程师会自我迭代,填满组织成长过程中的内生间隙,保障组织可持续发展 - 优秀的工程师会自我管理,结果驱动且不断对齐组织目标,管理者更关注中长期问题 - 最重要的是,优秀的工程师会吸引优秀的工程师 <!--more--> ## 怎样招到足够优秀的人 老实说,地球人都知道优秀工程师非常好,可关键问题是:如何招到呢? 其实秘诀也非常简单,那就是一开始就只招优秀工程师,一旦你的团队里有三个这样的人,剩下的就是给他们足够有挑战的事情,然后专注在业务发展上就好了。 但现实很骨感: - 业务压力太大,人少活多,实在干不过来 - 头部人才抢夺严重,成本高昂 - 并不是所有的优秀人才都适合当前团队,水土不服的情况非常普遍 个中缘由林林总总,这大概也是很多团队慢慢变得平庸的原因吧。 既然今天这篇是畅想,不妨设想,如果我们的根本目标是招聘优秀人才,那这会倒逼我们做些什么决策呢? - 选择一件有意义的事情作为公司的核心业务,一方面要有梦想,另外一方面也兼具社会价值,以此来吸引初始团队 - 维系一个小而美的优秀核心团队。如果平庸的人太多,不妨逐步提高人才密度,哪怕付出高成本,以此来稳定扩充团队 - 适当利用外包、采购等外部杠杆,将团队的焦点维持在核心领域,以此来提高团队效能 - 培养和发展人才,建设起健康梯队的同时,提高团队留存度 - 通过技术交流活动、媒体传播、招聘运营活动等等方式,对外展示团队优势,获得更广泛知名度的同时,也赢得内部员工认同感 ## 鸡生蛋,蛋生鸡? 可是没有优秀的团队,怎么会有好的业务呢? 这似乎陷入了先有鸡还是先有蛋的死循环。然而众所周知,解决死循环的方式之一就是:开始的那第一个人就是个懂业务的优秀工程师!这在很多企业中比比皆是,马化腾、张小龙、任正非、雷军、李彦宏等等。 还有一个方式就是搭班子,CEO 最先找的通常是 CTO。 ## 结语 或许几年后,回过头来看,我会觉得这篇胡言乱语有些稚嫩,不过既然目前还算好使,就沿着这条路继续走下去。如果对你也还算是有所启发,那就是额外的大收益了。 <file_sep>/share/from-mathematics-to-generic-programming/demo/multiply.ts /** * First version * Recursion */ function multiplyV1(n: number, a: number): number { if (n === 1) return a; // 1a = a return multiplyV1(n - 1, a) + a; // na = (n - 1)a + a } console.log('multiplyV1', multiplyV1(5, 3)); /** * Second version * Egyptian multiplication: 4a = ((a + a) + a) + a = (a + a) + (a + a) * In further, 41 * 59 = (2^0 * 59) + (2^3 * 59) + (2^5 * 59) = 59 + 472 + 1888 = 2419 */ function multiplyV2(n: number, a: number): number { if (n === 1) return a; const result = multiplyV2(half(n), a + a); return odd(n) ? (result + a) : result; } function odd(n: number): boolean { return !!(n & 0x1); } function half(n: number): number { return n >> 1; } console.log('multiplyV2', multiplyV2(41, 59)); /** * Third version * Tail recursive */ function multiplyAccV3(r: number, n: number, a: number): number { if (n === 1) return r + a; if (odd(n)) r = r + a; return multiplyV3(r, half(n), a + a); // r + na } function multiplyV3(n: number, a: number): number { return multiplyAccV3(0, n, a); } console.log('multiplyV3', multiplyV3(41, 59)); /** * Fourth version * Strict tail recursion */ function multiplyAccV4(r: number, n: number, a: number): number { if (odd(n)) { r = r + a; if (n === 1) return r; } n = half(n); a = a + a; return multiplyAccV4(r, n, a); } function multiplyV4(n: number, a: number): number { return multiplyAccV4(0, n, a); } console.log('multiplyV4', multiplyV4(41, 59)); /** * Fifth version * Non-recursion from strict tail recursion to avoid stack costs */ function multiplyAccV5(r: number, n: number, a: number): number { while (true) { if (odd(n)) { r = r + a; if (n === 1) return r; } n = half(n); a = a + a; } } function multiplyV5(n: number, a: number): number { return multiplyAccV5(0, n, a); } console.log('multiplyV5', multiplyV5(41, 59)); <file_sep>/share/node-async/demos/babel.js require('babel-core/register'); const testAsync = require('./async-await'); // testAsync(); <file_sep>/blog/source/_posts/bitwise-not-and-logical-not.md --- layout: post title: "js 中的 !! 与 ~~" date: 2015-10-17 21:01 status: publish tags: [BitwiseNOT, LogicalNOT, JavaScript] --- 在各大 js 的开源项目中,时常见到 !! 和 ~~,偶有猜对,却总不得要领。本文旨在深入剖析下这两个运算符的原理,以及使用时的利弊。 ## ! 为了简化问题,我们首先了解下常见的逻辑非运算符 !,EcmaScript 中的定义是: > 产生式 `UnaryExpression : ! UnaryExpression` 按照下面的过程执行: > > - 令 `expr` 为解析执行 `UnaryExpression` 的结果 > - 令 `oldValue` 为 ToBoolean(GetValue(`expr`)) > - 如果 `oldValue` 为 true, 返回 false > - 返回 true GetValue 处理取值的细节,例如依附于对象的属性、执行 getter 等,不再深究。重点看下 ToBoolean,它能够将各种类型的值最终转化为布尔类型。具体的规则可参考 [ES5#9.2 ToBoolean](http://es5.github.io/#x9.2) 一节。 接下来的处理很简单,如果 ToBoolen 得到的结果 `oldValue` 是 true,那就返回 false,否则返回 true。 <!--more--> ## !! 了解了 ! 之后,!! 就很好解释了,简单来说就是: > 产生式 `UnaryExpression : !! UnaryExpression` 按照下面的过程执行: > > - 令 `expr` 为解析执行 `UnaryExpression` 的结果 > - 返回 ToBoolean(GetValue(`expr`)) 是的,比 ! 的运算过程减少了两步,执行完 ToBoolean 后就直接返回了。这也是 !! 最主要的用途:**将操作数转化为布尔类型**。例如: ```js !! null // false !! undefined // false !! '' // false !! 'hello' // true !! 5 // true !! 0 // false !! {} // true ``` 值得提示的一点是,!! 实际上等效于 `Boolean` 被当做函数调用的效果: ```js !!(value) === Boolean(value) ``` ## ~ 按位非操作符 ~ 比逻辑非操作符 ! 复杂一些,作用是将数值比特位中的 1 变成 0,0 变成 1。EcmaScript 中的定义为: > 产生式 `UnaryExpression : ~ UnaryExpression` 按照下面的过程执行: > > - 令 `expr` 为解析执行 `UnaryExpression` 的结果 > - 令 `oldValue` 为 ToInt32(GetValue(`expr`)) > - 返回 `oldValue` 按位取反的结果 与逻辑非执行过程第二步不同,按位非调用的是 ToInt32 而不是 ToBoolean。ToInt32 的处理过程比较复杂,简化为以下四步: - 令 `number` 为调用 ToNumber 将输入参数转化为数值类型的结果 - 如果 `number` 是 NaN,+0,-0,+∞ 或者 -∞,返回 +0 - 令 `posInt` 为 sign(`number`) * floor(abs(`number`)) - 将 `posInt` 进行取模处理,转化为在 −2^31 到 2^31−1 之间的 32 位有符号整数并返回 从效果上看,ToInt32 依次做了这样几件事: - 类型转换,非数值类型的需要转化为数值类型 - 特殊值处理,NaN 和 ∞ 都被转化为 0 - 取整,如果是浮点数,会损失小数点后面的精度 - 取模,将整数调整到 32 位有符号整数区间内,如果整数原本不在这个区间,会丧失精度 执行完 ToInt32 之后,将得到的 32 位有符号整数进行按位取反,并将结果返回。 需要注意的是,所有的位操作都会先将操作数转化为 32 位有符号整数。 ## ~~ 和 !! 与 ! 的关系类似,~~ 实际上是 ~ 的简化版: > 产生式 `UnaryExpression : ~~ UnaryExpression` 按照下面的过程执行: > > - 令 `expr` 为解析执行 `UnaryExpression` 的结果 > - 返回 ToInt32(GetValue(`expr`)) 因为第一次执行 ~ 时已经将操作数转化为 32 位有符号整数,第二次执行 ~ 时实际只是将按位取反的结果再次按位取反,相当于取消掉 ~ 处理过程中的第三步。那么 ~~ 的用途也就很明确了:**将操作数转化为 32 位有符号整数**。 下面来看一些具体例子: ```js ~~ null // 0 ~~ undefined // 0 ~~ NaN // 0 ~~ {} // 0 ~~ true // 1 ~~ '' // 0 ~~ 'string' // 0 ~~ '1' // 1 ~~ Number.POSITIVE_INFINITY // 0 ~~ 1.2 // 1 ~~ -1.2 // -1 ~~ 1.6 // 1 ~~ -1.6 // -1 ~~ (Math.pow(2, 31) - 1) // 2147483647 = 2^31-1 ~~ (Math.pow(2, 31)) // -2147483648 = -2^31 ~~ (-Math.pow(2, 31)) // -2147483648 = -2^31 ~~ (-Math.pow(2, 31) - 1) // 2147483647 = 2^31-1 ~~ (Math.pow(2, 32)) // 0 ``` 如果你需要将一个参数转化为 32 位有符号整数,那么 ~~ 将是最简便的方式。不过要切记,它会损失精度,包括小数和整数部分。 ## 参考 - [按位操作符-MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) - [ToBoolean - ES5](http://es5.github.io/#x9.2) - [ToInt32 - ES5](http://es5.github.io/#x9.5) - [Bitwise NOT Operator - ES5](http://es5.github.io/#x11.4.8) - [Logical NOT Operator - ES5](http://es5.github.io/#x11.4.9) <file_sep>/blog/source/_posts/yui3-intro.md --- layout: post title: "浅析YUI3" date: 2011-05-21 21:16 status: publish tags: [YUI] --- 最近因为忙于YUI2到YUI3的迁移,没时间更新博客。现在闲暇一些,觉得似乎写一点自己对于YUI3的理解再合适不过。 主要内容有以下几点: 1. 全局命名空间 2. 改变一切的模块 3. Combo 4. 链式调用 5. 更广泛的自定义事件 6. 一些问题 ## 全局命名空间 YUI3为了保持向前兼容,采用了新的全局命名空间`YUI`。新的命名空间与YUI2的全局命名空间`YAHOO`最大的不同就是:`YUI`是一个构造函数,而且是一个[无论如何也返回一个实例的构造函数](http://shangchun.net/scope-safe-contructor.html)。 ## 改变一切的模块 YUI2时代,一般都是将某方面的全部方法写在统一的命名空间下,例如DOM相关的方法均在`YAHOO.util.Dom`,在需要使用这些方法时我们直接调用即可。YUI2真正体现了**基础方法库**\(function library\)这样一种定位。 <!-- more --> YUI3最大的变化和进步在于,它采用了革新性的底层组织方式,其核心就是模块\(module\)。在YUI3中,每个方法不再属于某个文件、某个命名空间,而是属于某个模块。每个模块代表一个独立的功能,例如`DOM`、`Event`等。下面是一个简单的例子: ```js YUI.add('new-module', function (Y) { Y.sayHelloWorld = function (id) { var el = Y.DOM.byId(id); Y.DOM.set(el, 'innerHTML', 'Hello, world!'); }; }, '1.0.0', { requires: ['dom'] }); ``` 通过调用`YUI`构造器本身的`add`静态方法,我们声明了一个新的模块,模块的名称为new-module,模块为`YUI`的实例`Y`挂载了`sayHelloWorld`方法,因为这个方法使用了dom模块的方法`byId`,所以要在`add`的第四个参数中标明new-module模块依赖于dom模块。 添加模块的目的是为了使用它,下面给出调用new-module的示例: ```js // html <div id="entry"></div> // js YUI().use('new-module', function(Y) { Y.sayHelloWorld('entry'); // <div id="entry">Hello, world!</div> }); ``` 通过调用YUI实例的`use`方法,在列出模块名称之后,我们可以随意使用它们挂载的方法。需要提醒的是,YUI的[loader](http://developer.yahoo.com/yui/3/yui/#loader)会发现new-module模块依赖于dom模块,然后它去check当前页面是否已经有dom模块,没有的话则动态加载。 总结一下,发现模块为我们带来了这些好处: - **遗弃domready**:在YUI2中,页面通常要在domready之后调用js方法。在YUI3中可以省掉这一步了,因为只有在所有需要的模块都加载完毕后才会调用js方法,而我们通常都是在&lt;body&gt;最后面引入js,此时dom基本已经就绪。当然,YUI3仍然提供domready事件监听方法。 - **沙箱**(Sandbox):在使用模块时,我们只能调用这些模块以及它们依赖的所有模块给YUI实例挂载的方法。这种机制可以限定你的代码在一定范围内执行,而不是肆意妄为。 - **自动加载**:我们不必再手动添加&lt;script&gt;标签引入js,更不必为js文件间的顺序依赖问题揪心,YUI的loader会为你摆平,而它的依据正是各个模块中的`requires`参数。 - **开发框架**(Framework):基于这种方法的声明/调用机制,YUI3更像一个js开发框架而不仅仅是一个方法库。我们可以将自己需要的功能作为一个个模块,可以细分为全局通用模块、分站通用模块、分站应用模块等层级。YUI3为此提供了非常简便的接口。 我觉得用这样一句话形容模块对于YUI的意义最好不过:“[Inception](http://movie.douban.com/subject/3541415/)”中Cobb所说的“a very simple idea that changed everything”。 至于模块如何设计、如何分级,将是一个非常有挑战的问题。我准备在适当的时间做下经验总结,现在暂不展开讲。 ## Combo 在YUI3框架中,每个模块都对应一个独立的js文件\(也有所有子模块组成一个模块的特殊情况,在此不细较\),日常开发中,往往需要动态加载大量的模块,造成http请求数较YUI2时代翻几番。众所周知的是,在YUI团队的[Best Practices for Speeding Up Your Web Site](http://developer.yahoo.com/performance/rules.html)一文中提到的第一条准则就是降低http请求数。如果模块化带来的更小粒度更大规模的js文件使得页面加载速度更慢,那么它所有的优势将不再具有吸引力。好消息是,YUI团队很好的解决了这一问题,他们引入了combo的思想,即使用服务器端技术,收到包含多个js文件请求的url之后,合并这些文件为一个大文件返回。 关于Combo的具体文章,可以参考[在服务端合并和压缩JavaScript和CSS文件](http://dancewithnet.com/2010/06/08/minify-js-and-css-files-in-server)。 ## 链式调用 jQuery因为方便的链式调用而风靡全球,其write less do more的核心理念也随之深入人心。欣喜的是,YUI团队汲取了这一优点,在YUI3中引入了新的[Node/NodeList](http://developer.yahoo.com/yui/3/node)对象,并取代DOM成为YUI3 Core。这一变化无疑将增加YUI3代码的书写效率,成为有一个显著的加分点。 ## 更广泛的自定义事件 YUI3提供了简约而强大的custom event:更加dom-like的调用方法,可以冒泡,可以经历各个事件阶段,可以定义默认动作,可以设定传播范围是模块内部还是模块之间等等。目前对于这部分仍然不甚熟悉,有兴趣的朋友可以参考Luke Smith做的这个[讲座](http://developer.yahoo.com/yui/theater/video.php?v=smith-yuiconf2009-events)。 ## 一些问题 YUI3并不完美,目前为止仍然存在一些问题,列举如下: - 文档仍然不够详尽,很多时候只能去查源代码。例如YUI2中`getRegion`方法在YUI3中的对应方法为`node.get('region')`。 - Node实例只能通过`get`方法取id,value等自身属性,可以参考jQuery采用更简洁的api,例如`val()`, `height()`, `text()`等。 - 得到一个定制的YUI实例时,需要将自己开发的模块的`path`、`requires`信息作为参数传进去,而在声明自定义模块时仍需要设定`requires`,这种冗余设计是可以做优化的。 - 使用Node操作Form时非常繁琐。例如要获取一个text表单项只能使用`ndForm.one('input[name="xxx"]')`,而不能`ndForm.get('xxx')`。 - 在存在name="id"项的表单中,存在因`Y.Selector.test`失效而产生的各种问题。例如`Y.one('#input-id').ancestor('form')`取不到等等。 - 没有公开的Form的`serialize`方法。 </ul> ok,这就是我对YUI3的一些浅薄见解。欢迎讨论和指正。随着经验的不断积累,后续会奉上更深入的一些分析。 <file_sep>/blog/source/_posts/continuation.md --- layout: post title: "Continuation 在 JS 中的应用" date: 2020-05-05 20:05 status: publish tags: [Functional Programming, Continuation, Promise] --- 请移步知乎“前端之美”专栏 [Continuation 在 JS 中的应用](https://zhuanlan.zhihu.com/p/94611888) 查看全文。 <file_sep>/blog/source/_posts/react-query.md --- layout: post title: "数据请求利器 React Query" date: 2022-06-05 16:25:19 status: publish tags: [React Query, React] --- 请移步知乎“前端之美”专栏 [数据请求利器 React Query](https://zhuanlan.zhihu.com/p/522609991) 查看全文。 <file_sep>/blog/source/_posts/js-linter-history.md --- layout: post title: "JS Linter 进化史" date: 2018-05-29 19:52 status: publish tags: [JavaScript, Linter, ESLint, JSLint] --- 请移步知乎“前端之美”专栏 [JS Linter 进化史](https://zhuanlan.zhihu.com/p/34656263) 查看全文。 <file_sep>/blog/source/_posts/js-error-catch.md --- layout: post title: "Javascript错误监控机制" date: 2011-11-06 20:30 status: publish tags: [try-cacth, onerror] --- > If an error is possible, someone will make it. The designer must assume that all possible errors will occur and design so as to minimize the chance of the error in the first place, or its effects once it gets made. Errors should be easy to detect, they should have minimal consequences, and, if possible, their effects should be reversible. > *--<NAME>, author, The Design of Everyday Things* 我觉得后端工程师较前端工程师最大的便利之一就是:**良好的代码监控机制**。 每次后端工程师上线后,如果PHP运行中出现错误,会立即记录在error log中,并由脚本根据不同的错误级别进行邮件、短信报警。前端工程师在这方面被动很多,大多数情况下是通过用户反映给客服,然后客服再通知技术部门解决,中间的链条甚至会更长一些,因此前端方面的bug造成的影响往往较为严重。 有什么办法可以缓解这一点,能够让我们在错误面前变被动为主动,第一时间解决问题呢?下面就介绍一种简单的Javascript错误监控机制。 ## Javascript错误模型 ### 生命周期 <center> <img alt="error flow" src="/images/error-flow.png" /> </center> 如上图所示,一个错误发生后,首先会被`try-catch`处理,如果没有被停止,则继续传递给`window.onerror`处理,如果没有被停止,则最终传递给浏览器控制台处理。 <!-- more --> #### try-catch `try-catch`属于ECMAScript中的语句,能够捕捉到顺序执行代码中的错误,以及`throw`抛出的错误,但遗憾的是,它对于延时执行(或称异步执行,例如通过事件、计时器等触发的代码)代码却无能为力。 `try-catch`捕捉到的错误会作为catch的第一个参数,记作ex,兼容性较好的一个属性为`ex.message`,此属性在IE、FireFox、Chrome中均能够较为准确的描述错误信息。例如: ```js try { M.unexistMethod(); } catch(ex) { alert(ex.message); // IE: "Object does't support this property or method" // FF: "M.unexistMethod is not a function" // Chrome: "Object # has no method 'unexistMethod'" } ``` 被`try-catch`捕捉到的错误不会继续传播。如果需要的话,可以在`catch`中通过`throw`语句向更高层次传播错误。 #### window.onerror `window.onerror`属于DOM的范畴,其支持和实现情况自然有很多差异。`window.onerror`先由IE、FireFox支持,并被加入到HTML5标准中。现在Chrome、Safari新版本均已支持,Opera在12 alpha中会增加支持。`window.onerror`可以捕获到所有类型的js错误,包括顺序、延时代码,这是它非常明显的优点。 在错误的处理方面,各个浏览器也是有些差异的。例如,在js文件与页面不在同一个域时: ```js window.onerror = function(msg, url, line) { alert(msg + ':' + line); // IE:"Object does't support this property or method:7" // FF:"Script error.:0" // Chrome:"Script error.:0" }; M.unexistMethod(); ``` 可以看出,FireFox和Chrome下都是统一的“Script error.”,且行号错误,这样的信息除了告诉我们有错误以外没有任何意义。有人解释说这是出于同源策略的考虑。如果你的js文件与页面在同一个域中,那么恭喜,在下面的错误日志收集机制中只需使用`window.onerror`就可以了。 此外,`window.onerror`在FireFox中可以捕捉到js文件加载失败的错误。 ### 错误日志收集 综合`try-catch`和`window.onerror`两种错误捕捉方式的特点,设计一个较为简单的错误日志收集机制如下: - 考虑到`try-catch`能够获得更为准确的错误描述信息,兼容性良好,且在错误传播模型中处于最底层,所以将页面方法入口放在`try-catch`内,这样在这些方法顺序代码中出现的错误就可以被`try-catch`捕获到 - 虽然`window.onerror`非常强大,但由于`window.onerror`在兼容性方面的问题,只将延时代码中可能出现的错误交给`window.onerror`处理 - 捕获到错误后,使用简单强大的beacon将错误信息传递给日志服务器 下面是较为精简的一份代码实现: ```js // base.js var M = { toQueryString: function(o) { var res = [], p, encode = encodeURIComponent; for (p in o) { if (o.hasOwnProperty(p)) res.push(encode(p) + '=' + encode(o[p])); } return res.join('&'); }, beacon: function(msg) { var img = new Image(); img.src = 'http://xxx.com/_.gif?' + msg; }, log: function(info) { M.beacon(M.toQueryString(info)); }, runMethod: function(method) { try { method(); } catch(ex) { M.log({ msg: ex.message, type: 'try-catch' }); } } }; window.onerror = function(msg, url, line) { M.log({ msg: msg, url: url, line: line, type: 'onerror' }); return true; }; // app.js M.app = { editAddress = function() { var elForm = document.getElementById('address-form'); elForm.onsubmit = function() { if (elForm.address.value === '') return false; }; elForm.address.focus(); } }; ``` ```html <form action="address" method="post" id="address-form"> <!-- the name is misspelled, so it may cause an error --> <input type="text" name="adress" /> <input type="submit" value="Submit" /> </form> <script type="text/javascript" src="base.js"></script> <script type="text/javascript" src="app.js"></script> <script> M.runMethod(function() { M.app.editAddress(); }); </script> ``` 完整代码见[Github](https://github.com/springuper/log-error)。 ## 错误日志处理 由于javascript运行在种类、版本繁多的浏览器中,用户的网络情况也千差万别,直接造成的问题就是错误日志中包含很多垃圾信息,例如: - Script error. - Object doesn't support this property or method. 这些错误信息信息量太少,不能准确描述错误的真正原因,需要进行过滤。 在监听到一些描述准确的错误后,需要及时发送错误报警,形式可以为邮件、短信,这样就可以在短时间内将线上的问题反馈给前端工程师,减少错误响应时间。 前端工程师终于可以放心大胆的上线了! ## 参考 - [HTML5标准-window.onerror](http://www.w3.org/TR/2010/WD-html5-20100624/webappapis.html#handler-window-onerror) - [MSDN-window.onerror](http://msdn.microsoft.com/en-us/library/cc197053%28VS.85%29.aspx) - [MDN-window.onerror](https://developer.mozilla.org/en/DOM/window.onerror) - [Enterprise JavaScript Error Handling](http://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation) - [Cryptic “Script Error.” reported in Javascript in Chrome and Firefox](http://stackoverflow.com/questions/5913978/cryptic-script-error-reported-in-javascript-in-chrome-and-firefox) <file_sep>/share/from-mathematics-to-generic-programming/demo/generic.ts // function multiplyAccV1<A>(r: A, n: number, a: A): A function multiplyAccV1(r: number, n: number, a: number): number function multiplyAccV1(r: string, n: number, a: string): string function multiplyAccV1(r: any, n: number, a: any): any { while (true) { if (odd(n)) { r = r + a; if (n === 1) return r; } n = half(n); a = a + a; } } function multiplyV1(n: number, a: number): number function multiplyV1(n: number, a: string): string function multiplyV1(n: number, a: any): any { if (n === 1) return a; return multiplyAccV1(a, half(n - 1), a + a); } function odd(n: number): boolean { return !!(n & 0x1); } function half(n: number): number { return n >> 1; } console.log('multiplyAccV1', multiplyV1(41, 59)); console.log('multiplyAccV1', multiplyV1(41, '59')); // TODO find `type` to make generic type shorter function multiplyAccSemigroup<NonCommutativeAdditiveSemigroup extends number>(r: NonCommutativeAdditiveSemigroup, n: number, a: NonCommutativeAdditiveSemigroup): NonCommutativeAdditiveSemigroup { while (true) { if (odd(n)) { r = (r + a) as NonCommutativeAdditiveSemigroup; if (n === 1) return r; } n = half(n); a = (a + a) as NonCommutativeAdditiveSemigroup; } } function multiplySemigroup<NonCommutativeAdditiveSemigroup extends number>(n: number, a: NonCommutativeAdditiveSemigroup): NonCommutativeAdditiveSemigroup { if (n === 1) return a; return multiplyAccSemigroup(a, half(n - 1), (a + a) as NonCommutativeAdditiveSemigroup); } console.log('multiplySemigroup', multiplySemigroup(41, 59)); function multiplyMonoid<NonCommutativeAdditiveMonoid extends number>(n: number, a: NonCommutativeAdditiveMonoid): NonCommutativeAdditiveMonoid { // if (n === 0) return NonCommutativeAdditiveMonoid(0); if (n === 0) return 0 as NonCommutativeAdditiveMonoid; return multiplySemigroup(n, a); } console.log('multiplyMonoid', multiplyMonoid(41, 59)); console.log('multiplyMonoid', multiplyMonoid(0, 59)); function multiplyGroup<NonCommutativeAdditiveGroup extends number>(n: number, a: NonCommutativeAdditiveGroup): NonCommutativeAdditiveGroup { if (n < 0) { n = -n as NonCommutativeAdditiveGroup; // a = NonCommutativeAdditiveGroup(0) - a; a = (0 - a) as NonCommutativeAdditiveGroup; } return multiplyMonoid(n, a); } console.log('multiplyAccV4', multiplyGroup(-41, 59)); console.log('multiplyAccV4', multiplyGroup(-41, -59)); <file_sep>/blog/source/_posts/diff-great-software-engineer-from-a-good.md --- layout: post title: "[译]优秀与伟大程序员的区别" date: 2013-10-19 20:39 status: publish tags: [Programming] --- <div class="preface"> <p>在程序员的职业生涯中,总有一些理念让你眼前一亮,犹如夜空中一颗颗明亮的星,指引你不断前行。Quora上Russel Simmons的这个答案就是曾让我深受触动的三个理念,翻译出来给E文一般的童鞋。E文好的童鞋请移步,原著更加准确生动些。</p> <em>原文链接:<a href="http://www.quora.com/Software-Engineering/What-distinguishes-a-good-software-engineer-from-a-great-one/answer/Russel-Simmons?srid=mo0" target="_blank">Software Engineering: What distinguishes a good software engineer from a great one?</a></em> </div> 我并不打算给出一个全面的答案,不过我已注意到几个伟大程序员具备却不常被提及的特质: - **能够平衡实效与完美**。伟大工程师具备进行娴熟、快速而粗略的hack,和设计优雅、精炼、健壮的解决方案的两种能力,以及,根据给定问题选择恰当方式的智慧。一些稍普通的程序员们看起来缺乏对问题关键细节的极致关注,另一些人则太过坚持完美主义。 - **不排斥调试代码和修复bug**。平庸的程序员害怕、厌恶调试,甚至对自己的代码也是如此。伟大程序员会以丘吉尔般顽强的精神潜心钻研。如果问题被证明不在他们的代码中,伟大程序员会有些不愉快,他们会最终找出问题所在。 - **合理质疑**。优秀程序员会找到看似可行的解决办法并一直沿用。伟大程序员则倾向于质疑自己的代码,直到测试完备。而这一过程往往需要大量的数据分析和系统管理。一般程序员可能看到一个似乎没什么危害的细微异常,然后忽略掉了它。如果换作伟大程序员,他们会怀疑这可能是一个更大问题的线索,并投入精力研究透彻。伟大程序员乐于做更多的交叉校验和完备性检查,通过这种方式发现隐含的问题。 <file_sep>/blog/source/_posts/event.md --- layout: post title: "YUI事件体系之Y.Event" date: 2013-01-20 14:12 status: publish tags: [Y.Event, YUI] --- ![mouse event](/images/mouse.png) 在介绍了由`Y.Do`、`Y.CustomEvent`、`Y.EventTarget`构建的自定义事件体系后,本篇文章将为大家介绍建立在这一体系之上,YUI对DOM事件的封装——`Y.Event`。 ## Y.DOMEventFacade 众所周知,浏览器之间存在大量的不兼容问题,在事件方面尤其如此。`Y.DOMEventFacade`主要用来处理DOM事件对象的浏览器兼容问题,提供跨浏览器的简洁接口。事实上,我们常在`Y.one('.selector').on('click', function (e) {})`中使用的`e`就是`Y.DOMEventFacade`的实例。 具体来说,兼容处理的属性主要有: - target,专门处理了target为文本节点的情况,统一为元素节点,方便操作 - relativeTarget,关联目标节点,在mouseover/mouseout等事件中设置 - keyCode/charCode等输入信息 - pageX/clientX等位置信息 兼容处理的方法主要有: - stopPropagation/stopImmediatePropagation,不支持停止立即传播时,仅能在YUI层面模拟,不会阻止通过原生方法添加的同层回调,即,在YUI监听过el的click事件后,又通过`el.addEventListener('click', nativeCallback)`监听,如果在YUI的回调中调用`e.stopImmediatePropagation`的话,`nativeCallback`仍然会执行 - preventDefault 另外,为了方便同时停止传播和阻止默认行为,YUI还提供了`halt`方法。 <!-- more --> 我们来简单分析下`Y.DOMEventFacade`的实现: ```js // 为简化代码,省略了专门针对未实现DOM2 Events规范浏览器中的事件对象兼容性处理(代码在event-base-ie模块) var DOMEventFacade = function (ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || {}; this.init(); }; // 确定目标节点 DOMEventFacade.resolve = function (n) { if (!n) return n; try { // 如果是TEXT_NODE,则取其父节点 if (n && 3 === n.nodeType) n = n.parentNode; } catch (e) { return null; } return Y.one(n); }; Y.extend(DOMEventFacade, Object, { // 初始化。主要处理事件对象的浏览器兼容问题 init: function () { var e = this._event, resolve = DOMEventFacade.resolve; // 此处省略对key和dimension的兼容性处理 this.type = e.type; this.target = resolve(e.target); this.currentTarget = resolve(this._currentTarget); this.relatedTarget = resolve(e.relatedTarget); }, // 停止传播 stopPropagation: function () { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, // 立即停止传播,不处理同一节点的后续回调 stopImmediatePropagation: function () { var e = this._event; if (e.stopImmediatePropagation) { // 原生事件对象支持立即停止传播 e.stopImmediatePropagation(); } else { // 仅停止传播,在原生层面会继续同层传播 this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, // 阻止默认事件 preventDefault: function (returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, // 中止事件,包括停止传播和阻止默认事件 halt: function (immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); Y.DOMEventFacade = DOMEventFacade; ``` ## Y.Event `Y.Event`的主要作用是提供添加、注销DOM事件监听的接口。和我们通常的理解不一样的是,它并不是一个类,而是一个简单的对象。 YUI对DOM事件监听的处理思路大体是:根据节点、事件类型,创建一个`Y.CustomEvent`对象cewrapper。然后通过原生方法注册事件监听,回调执行`cewrapper.fire`方法。所有通过YUI添加的事件监听,都注册cewrapper上,从而实现对DOM事件的包装。 我们先来看下如何使用`Y.Event`添加事件监听: ```js // 例1 YUI().use('selector', 'event-base', function(Y) { Y.Event.attach('click', function (e) { console.log('#btn-one clicked'); }, '#btn-one'); Y.Event.attach('click', function (e) { console.log('#btn-one clicked again'); }, '#btn-one'); // click #btn-one // output '#btn-one clicked', '#btn-one clicked again' Y.Event.attach('click', function (e) { console.log('#btn-one clicked'); e.stopPropagation(); }, '#btn-two'); Y.Event.attach('click', function (e) { console.log('#btn-one clicked again'); e.stopImmediatePropagation(); }, '#btn-two'); Y.Event.attach('click', function (e) { console.log('#btn-one clicked the third time'); }, '#btn-two'); // click #btn-two // output '#btn-two clicked', '#btn-two clicked again' }); ``` 当然,也可以使用`Y.Event`注销事件监听: ```js // 例2 YUI().use('selector', 'event-base', function(Y) { var countThree = 0; var handle = Y.Event.attach('click', function (e) { console.log('#btn-three clicked', ++countThree); handle.detach(); }, '#btn-three'); // click #btn-three many times // output '#btn-three clicked 1' var countFour = 0; Y.Event.attach('click', function (e) { console.log('#btn-four clicked', ++countFour); Y.Event.detach('click', null, '#btn-four'); }, '#btn-four'); // click #btn-four many times // output '#btn-four clicked 1' }); ``` ### 源代码分析 接下来,让我们看看YUI的内部实现吧。 注:为了更容易的看懂代码的核心,我做了适当的简化,感兴趣的朋友可以去看未删节的[源码](https://github.com/yui/yui3/blob/v3.8.0/build/event-base/event-base-debug.js#L397)。 ```js var add = function (el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function (el, type, fn, capture) { if (el && el.removeEventListener) { try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, // 判断o是否为HTMLCollection或HTMLElement数组 shouldIterate = function (o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !Y.DOM.isWindow(o)); } catch (ex) { return false; } }; Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var Event = function () { var _wrappers = Y.Env.evt.dom_wrappers, _el_events = Y.Env.evt.dom_map; return { // 添加事件监听 attach: function (type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, // 创建自定义事件对象,在原生事件触发时执行该对象的fire方法, // 从而处理它上面的所有回调 _createWrapper: function (el, type) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; cewrapper = _wrappers[key]; if (!cewrapper) { cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function () { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } }); cewrapper.overrides = {}; cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; // 作为原生DOM事件回调 cewrapper.fn = function (e) { // 触发事件,回调方法可以直接调用作为第一个参数的 // DOM事件包装对象 cewrapper.fire(Event.getEvent(e, el)); }; // 重写_delete方法,执行_clean来注销原生DOM节点事件监听 cewrapper._delete = function (s) { var ret = Y.CustomEvent.prototype._delete.apply(this, arguments); if (!this.hasSubs()) { // 全部回调都被注销,则注销DOM事件监听 Event._clean(this); } return ret; }; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; // 通过原生方法注册事件监听,这是关键的入口 add(el, type, cewrapper.fn); } return cewrapper; }, // 添加事件监听的内部实现 _attach: function (args) { var handles, oEl, cewrapper, context, ret, type = args[0], fn = args[1], el = args[2]; if (!fn || !fn.call) return false; l) return false; if (Y.Node && Y.instanceOf(el, lis = Event.getListeners(oEl, type), i, lYUI().use('node-base', 'selector', 'event-base', function(Y) recursively'); }, '#btn-six'); // click #btn-six // and then, click any elements in #wrapper // output nothing }); ``` ## 通过Y和Node监听事件 YUI3借鉴了jQuery对HTMLElement/HTMLCollection的封装方式,方便进行链式调用,这就是`Y.Node`。 事件监听是不是可以不用繁琐的使用`Y.Event`,在`Y.Node`对象上直接调用呢?当然可以。主要有四个方法: - NodeInstance.on - NodeInstance.once - NodeInstance.after - NodeInstance.onceAfter 实际上,以上四个方法是通过内部调用Y的对应方法,例如`Node.prototype.on`内部调用了`Y.on`,而Y上的对应方法是由于Y本身是一个`Y.EventTarget`对象才获得的。最终,在`Y.EventTarget.prototype.on`中调用了`Y.Event`。 ```js // 例5 YUI().use('node', function(Y) { Y.Event.attach('click', function (e) { console.log('wrapper clicked'); }, '#btn-one'); // 等价的Y.on写法 Y.on('click', function (e) { console.log('btn-one clicked'); }, '#btn-one'); // 等价的Node.on写法 Y.one('#btn-one').on('click', function (e) { console.log('btn-one clicked'); }); }); ``` ## 示例代码 所有示例代码均在[GitHub](https://github.com/springuper/yuianalyser/tree/master/event)。 ## 参考 - [YUILibrary-UserGuides-Event](http://yuilibrary.com/yui/docs/event/) - [YUILibrary-Event](https://github.com/yui/yui3/blob/v3.8.0/build/event-base/event-base-debug.js) <file_sep>/blog/source/_posts/monad.md --- layout: post title: "前端中的 Monad" date: 2018-10-23 18:30 status: publish tags: [Functional Programming, Monad] --- 请移步知乎“前端之美”专栏 [前端中的 Monad](https://zhuanlan.zhihu.com/p/47130217) 查看全文。 <file_sep>/share/from-mathematics-to-generic-programming/demo/generic.js function multiplyAccV1(r, n, a) { while (true) { if (odd(n)) { r = r + a; if (n === 1) return r; } n = half(n); a = a + a; } } function multiplyV1(n, a) { if (n === 1) return a; return multiplyAccV1(a, half(n - 1), a + a); } function odd(n) { return !!(n & 0x1); } function half(n) { return n >> 1; } console.log('multiplyAccV1', multiplyV1(41, 59)); console.log('multiplyAccV1', multiplyV1(41, '59')); // TODO find `type` to make generic type shorter function multiplyAccSemigroup(r, n, a) { while (true) { if (odd(n)) { r = (r + a); if (n === 1) return r; } n = half(n); a = (a + a); } } function multiplySemigroup(n, a) { if (n === 1) return a; return multiplyAccSemigroup(a, half(n - 1), (a + a)); } console.log('multiplySemigroup', multiplySemigroup(41, 59)); function multiplyMonoid(n, a) { // if (n === 0) return NonCommutativeAdditiveMonoid(0); if (n === 0) return 0; return multiplySemigroup(n, a); } console.log('multiplyMonoid', multiplyMonoid(41, 59)); console.log('multiplyMonoid', multiplyMonoid(0, 59)); function multiplyGroup(n, a) { if (n < 0) { n = -n; // a = NonCommutativeAdditiveGroup(0) - a; a = (0 - a); } return multiplyMonoid(n, a); } console.log('multiplyAccV4', multiplyGroup(-41, 59)); console.log('multiplyAccV4', multiplyGroup(-41, -59)); <file_sep>/blog/source/_posts/yui3-event-default-action.md --- layout: post title: "YUI经验谈-自定义事件默认行为" date: 2014-02-14 10:00 comments: true status: publish tags: [YUI, Event, JavaScript] --- 纵观主流JS库和框架,YUI在自定义事件方面做的尤为出色。如果需要挑出一个代表性的feature,那么非**事件默认行为**莫属。 ## 是什么 YUI自定义事件在总体上模仿了DOM事件的设计思想。DOM中的一些事件是有默认行为的,详细见[DOM3 Event - Default actions and cancelable events](https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-flow-default-cancel)一节。简单来说,所谓默认行为,是指该事件在通常情况下所表现出来的动作,例如: - 一个链接节点的`click`事件,默认行为是转向该链接href属性对应的地址 - 表单的submit事件,默认行为是将表单包含的数据提交给表单的action 说通常情况下,是因为有时开发者会在事件的回调函数中调用 ``` e.preventDefault(); ``` 来阻止默认行为的发生。 <!-- more --> <center><img alt="Event Default Action" src="/images/event-default-action.png" /></center> YUI自定义事件遵循了同样的思路,甚至API也和DOM完全一致。 ## 有啥用 事件默认行为,本质上,是一种**管理事件和行为的对应关系**的机制。这种机制既不像回调那样死板,也不像消息那样开放。通过将通用处理逻辑作为事件默认行为,满足常见需求的同时,为定制化需求提供了一定开放性,整体上更加灵活。 在DOM事件中,和默认行为相关的场景并不少见: - 监听到链接的`click`事件时,在链接地址中加入追踪参数,利用默认行为跳转到新地址 - 阻止表单`submit`事件默认行为,改为异步提交表单,提供更好的用户体验 在自定义事件的应用中,也会遇到一些类似的例子。例如: - 注册时,有一些邮箱虽然是可用的,但对于EDM不给力,在这种情况下,阻止表单项验证成功的默认行为,展示建议用户使用其它邮箱的提示 - 表单验证组件在检查表单项失败后触发`failure`事件,对应的默认行为是在表单项下方显示错误信息。这样的处理在大部分情况下是完全OK的。不过有一天,交互设计师在一个特定场景下提出所有提示都应该放在整个表单顶部,得益于这种灵活的机制,实现这种定制化逻辑十分轻松 - 字符计数插件在输入变化时会默认更新字符数提示。在评价内容中,有更复杂的提示逻辑和展示效果,这时阻止默认行为,实现定制化内容即可 ## 怎么用 下面以表单项验证组件为例,展示如何使用事件默认行为。 首先创建`FieldValidator`组件,并使其具备`EventTarget`的功能,实现自定义事件机制: ```js var FieldValidator = function (ndField, validateFn) { var instance = this; // ... }; Y.augment(FieldValidator, Y.EventTarget); ``` 使用`publish`声明检查成功和失败的自定义事件,主要目的是定义事件的默认行为: ```js var FieldValidator = function (ndField, validateFn) { // ... // 声明检查成功事件,设置默认行为 instance.publish('success', { emitFacade: true, defaultFn: function (e) { e.field.next('.tip').setHTML('ok'); } }); // 声明检查失败事件,设置默认行为 instance.publish('failure', { emitFacade: true, defaultFn: function (e) { e.field.next('.tip').setHTML('error'); } }); }; ``` 接下来注册表单项的`focus`、`blur`事件,在`blur`触发时检查表单内容,并触发自定义事件: ```js var FieldValidator = function (ndField, validateFn) { // ... ndField.on({ focus: function (e) { ndField.next('.tip').setHTML(''); }, blur: function (e) { if (validateFn(this.get('value'))) { // 检查通过,触发检查成功事件 instance.fire('success', { field: ndField }); } else { // 检查未通过,触发检查失败事件 instance.fire('failure', { field: ndField }); } } }); }; ``` 现在就可以使用这个组件了,一般情况下,我们不需要阻止默认行为,下面是一个具体示例: ```js // 检查邮箱 new FieldValidator(Y.one('[name="email"]'), function (value) { return /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(value); }); ``` 一切看起来都很美,直到有一天你接到一个需求:Yahoo邮箱在检查通过时需要展示EDM不给力的提示,这时候默认行为就可以来拯救你了: ```js var validator = new FieldValidator(Y.one('[name="email"]'), function (value) { return /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(value); }); validator.on('success', function (e) { if (e.field.get('value').indexOf('@yahoo.com') !== -1) { // 阻止默认行为 e.preventDefault(); // 定制化行为 e.field.next('.tip').setHTML('换个邮箱吧,yahoo.com邮箱收不到优惠通知哦'); } }); ``` 在`success`事件的回调中,通过阻止默认行为,不再执行提示内容为OK的默认逻辑,而是切换成判断雅虎邮箱,并给出特定提示的定制化逻辑。 完整代码展示,请移步[JSFiddle](http://jsfiddle.net/springuper/h4XAY/)。 ## 要注意 一个好的idea,最容易被滥用。默认行为不是万能药,只适合一些这样的场景: - 需要通过事件进行消息广播。如果callback就可以解决问题,那么明智之举是使用callback - 存在定制化需求的预期,即有些情况下需要中止默认行为的发生,换之以定制化行为 ## 参考 - [DOM3 Event - Default actions and cancelable events](https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-flow-default-cancel) - [YUI EventTarget](http://yuilibrary.com/yui/docs/event-custom/index.html) <file_sep>/share/the-react-way/the-react-way.html <!DOCTYPE html> <html> <head> <title>The React Way</title> <style type="text/css"> @import url(https://fonts.googleapis.com/css?family=Droid+Serif); @import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz); @import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic); body { font-family: 'Helvetica'; } h1, h2, h3 { font-family: 'Yanone Kaffeesatz'; font-weight: 400; margin: 0.3em auto; } .remark-slide-content { padding-left: 3em; padding-right: 3em; text-align: center; vertical-align: middle; background: #212121; color: #777872; text-shadow: 0 0 5px #333; } .remark-slide-content h1 { font-size: 3.8em; } .remark-slide-content h2 { font-size: 2.4em; } .remark-slide-content h3 { font-size: 1.6em; } .footnote { position: absolute; bottom: 3em; } li p { line-height: 1.25em; margin:8px 0; } .red { color: #fa0000; } .large { font-size: 2em; } a, a > code { color: rgb(249, 38, 114); text-decoration: none; } code { -moz-border-radius: 5px; -web-border-radius: 5px; border-radius: 5px; } .hljs-monokai .hljs { background: #3D3D3D; } .remark-code, .remark-inline-code { font-size: 20px; font-family: 'Monaco'; } .pull-left { float: left; width: 47%; } .pull-right { float: right; width: 47%; } .pull-right ~ p { clear: both; } #slideshow .slide .content code { font-size: 0.8em; } #slideshow .slide .content pre code { font-size: 0.9em; padding: 15px; } .remark-slide-content ul { color: #cecece; } .remark-slide-content h1, .remark-slide-content h2 { color: #f3f3f3; line-height: 1.2em; } .remark-slide-content h3 { color: #cecece; line-height: 1.2em; } .cover { padding-left: 0; padding-right: 0; background-image: url(./golden-gate.jpg); background-size: cover !important; text-shadow: 0 0 10px #000; } .cover h1 { margin: 0.2em 0 0; font-size: 5em; } .cover p { color: #CCC; text-shadow: 0 0 3px #000; } .cover-content { position: absolute; right: 0; bottom: 0; left: 0; padding: 1em; background: rgba(0, 0, 0, 0.5); } .nobg { background-image: none; } .engineering-productivity { margin-left: 9em; font-size: 26px; color: #cecece; } .swe-duty { text-align: left; margin: 2em 0 0 11em; font-size: 26px; } .trigger-time { text-align: left; margin: 0 0 0 7em; font-size: 32px; } .trigger-time--9em { margin-left: 9em; } .trigger-time--5em { margin-left: 5em; } .trigger-time--4em { margin-left: 4em; } .trigger-time--2em { margin-left: 2em; } .trigger-time li { margin-bottom: 8px; } .code-block { text-align: left; margin: 0 3em; } .code-block--small .remark-code-line { font-size: 14px; } .referrence { text-align: left; margin-left: 2em; font-size: 26px; } /* Slide-specific styling */ #slide-inverse .footnote { bottom: 12px; left: 20px; } small { font-size: 0.6em; color: #999; } </style> </head> <body> <textarea id="source"> class: cover <div style="margin-top: -10em;"> <img src="logo.svg" style="width: 20em;" /> </div> .cover-content[ # The React Way <EMAIL> ] --- # 为何 UI 开发越发困难? -- <br /> .trigger-time.trigger-time--2em[ - 需要人工确认视觉效果 - 状态越来越多 - 缺乏与快速增长的复杂度相匹配的工具 ] --- # 栗子 <div style="margin: 3em;"> <img src="facebook-chat.png" style="width: 30em;" /> </div> --- .trigger-time.trigger-time--2em[ - 跃雷发来一条消息 - Matt 离线 - 小明 在线 - Liang He 离线 - Liang He 手机在线 - ... ] --- # 现在 UI 应该是? -- <div style="margin: 3em;"> <img src="no-idea.jpeg" style="width: 15em;" /> </div> --- # 怎么破? .trigger-time.trigger-time--2em[ - 让 UI 更可预测 - 让 UI 更可靠 ] -- ### 让 UI 能够和 Data 联动 .code-block[ ```javascript [ { name: '跃雷', status: 'online', unread: 1 }, { name: '小明', status: 'online', unread: 0 }, { name: '<NAME>', status: 'mobile-online', unread: 0 }, ] ``` ] --- # Data Binding <div style="margin: 0; background: white;"> <img src="two-way-db.png" style="width: 30em;" /> </div> --- # 不同流派 ### Key-Value Observation .trigger-time.trigger-time--2em[ - Ember - Knockout - Backbone - Meteor - Vue ] ### Dirty Check .trigger-time.trigger-time--2em[ - Angular ] --- # 问题 ### 受限于双向绑定模式本身,存在以下问题: .trigger-time.trigger-time--2em[ - 数据间关系需要小心处理,例如 computed property - 观测到数据变化的机制多少存在一些局限性,例如 dirty check ] --- # The React Way ## Single Way Data Binding ### 数据变化时,重算所有数据并更新所有 DOM 不就 ok 了? -- <br /> ### React 找到了更好的办法 .trigger-time.trigger-time--2em[ - 在数据和 DOM 之间引入 Virtual DOM - 数据变化时,re-render 得到新的 Virtual DOM - 比较新旧 Virtual DOM 的 diff - 根据 diff,按需更新 DOM ] --- # Virtual DOM .code-block[ ```html <ul id='list'> <li class='item'>Item 1</li> <li class='item'>Item 2</li> <li class='item'>Item 3</li> </ul> ``` ] .code-block.code-block--small[ ```javascript var element = { tagName: 'ul', props: { id: 'list' }, children: [ {tagName: 'li', props: {class: 'item'}, children: ["Item 1"]}, {tagName: 'li', props: {class: 'item'}, children: ["Item 2"]}, {tagName: 'li', props: {class: 'item'}, children: ["Item 3"]}, ] } ``` ] --- # Virtual DOM Diff <div style="margin: 0;"> <img src="virtual-dom-diff.png" style="width: 35em;" /> </div> --- # Reactive Functional Programming ## Data 变化 => UI 更新 ## React(props) => UI --- # 这么好用,怎么写呢? ### Rule 1 你所见的,都是组件 .code-block[ ```jsx class HelloMessage extends React.Component { render() { return React.createElement( "div", null, "Hello ", this.props.name ); } } ReactDOM.render( React.createElement(HelloMessage, { name: "Jane" }), mountNode ); ``` ] -- 看起来有些蛋疼是不是? --- # JSX ### Rule 2 JSX 让你飞 .code-block[ ```jsx class HelloMessage extends React.Component { render() { return <div>Hello {this.props.name}</div>; } } ReactDOM.render(<HelloMessage name="Jane" />, mountNode); ``` ] --- # 数据 & 状态 ### Rule 3 使用 `this.setState` 主动更新状态 .code-block.code-block--small[ ```jsx class Timer extends React.Component { constructor(props) { super(props); this.state = { secondsElapsed: 0 }; } tick() { this.setState((prevState) => ({ secondsElapsed: prevState.secondsElapsed + 1 })); } componentDidMount() { this.interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return <div>Seconds Elapsed: {this.state.secondsElapsed}</div>; } } ReactDOM.render(<Timer />, mountNode); ``` ] --- # 生命周期方法 .trigger-time.trigger-time--2em[ - getInitialState - componentWillMount - componentDidMount 组件已经挂载在 DOM 中 - shouldComponentUpdate 是否需要更新组件 - componentWillUpdate - componentDidUpdate - componentWillUnmount 组件即将从 DOM 移除 ] --- # Client-Server 同构 ### 因为 Virtual DOM,React 具备了在 Server 端渲染 HTML 的能力 --- # 周边 ### React 只是 View 层,需要配合其它工具/库才能构建完整应用 .trigger-time.trigger-time--2em[ - State Manager: Redux, MobX - Router: React-Router - Data Driven: GraphQL, Relay - Test: ReactTestUtils, Enzyme - Build Tool: Webpack, Babel ] --- # Redux <div style="margin: 0;"> <img src="redux.png" style="width: 30em;" /> </div> --- # [Demo](https://github.com/gaearon/redux-devtools/tree/master/examples/todomvc) --- # References .trigger-time.trigger-time--2em[ - [The Secrets of React's Virtual DOM](https://www.youtube.com/embed/-DX3vJiqxm4?list=FLoT2_Cq0W_xTx6YZfzUVJQw) - [React’s diff algorithm](http://calendar.perfplanet.com/2013/diff/) - [Awesome React](https://github.com/enaqx/awesome-react) ] --- name: last-page # Thanks </textarea> <script src="https://remarkjs.com/downloads/remark-0.6.5.min.js" type="text/javascript"></script> <script type="text/javascript"> var hljs = remark.highlighter.engine; </script> <script src="https://remarkjs.com/remark.language.js" type="text/javascript"></script> <script type="text/javascript"> var slideshow = remark.create({ highlightStyle: 'monokai', highlightLanguage: 'remark' }) ; </script> </body> </html> <file_sep>/blog/source/_posts/react-hooks.md --- layout: post title: "React Hooks 原理剖析" date: 2021-08-31 21:54 status: publish tags: [React, Hooks, Web] --- 请移步知乎“前端之美”专栏 [React Hooks 原理剖析](https://zhuanlan.zhihu.com/p/372790745) 查看全文。 <file_sep>/blog/source/_posts/w3ctech-meituan.md --- layout: post title: "w3cTech 21期在美团举行" date: 2011-08-04 20:05 status: publish tags: [W3CTech, Meituan, YUI] --- ![w3ctech in meituan](/images/w3ctech-meituan.jpg) 很高兴能够作为东道主参加w3cTech。 在我看来,前端行业更加团结、热情,有非常开放、分享的精神。非常喜欢这个行业的风气。 此次交流会,我做了关于我们团队在YUI3方面的一些实践([YUI3在美团](/yui3-in-meituan.html)),虽然还很初级,但我们在慢慢强大。在行进中开火,纵情向前! <file_sep>/blog/source/_posts/javascript-the-core.md --- layout: post title: "Javascript核心概念" date: 2011-12-28 23:49 status: publish tags: [Closure, Execution Context, Prototype Chain] --- <div style="text-align: center;"><iframe src="http://www.slideshare.net/slideshow/embed_code/10708244" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="425" height="355"></iframe></div> <div style="text-align: center;"><a href="/assets/the-core-of-javascript.key_.zip">keynote下载</a> | <a href="/assets/the-core-of-javascript.pdf.zip">pdf下载</a></div> <!-- more --> ## Notes 1. 这次分享一些Javascript或者说ECMAScript中的一些比较基础的知识点。这些东西在我们日常的开发和调试中发挥着非常重要而又容易被忽略的作用。希望这次分享能够让大家有一个更深入的认识。 2. 对于我们所使用的核心技术,我们要做到知其然知其所以然。这是一个非常重要的态度,只有这样,我们才能更好的理解这些技术背后蕴涵的思想,运作机制,以及优点缺陷,才能免于陷入缤纷表现的漩涡,能够做到透过现象看本质。 3. 每个人的精力都是有限的,尤其是我这种愚钝的人,所以,把你的精力放在最值得放的一些地方,而不是处处留芳。 4. 这次我们主要分享这几个知识点:原型链. 构造器. 执行上下文. 变量对象. 作用域链. 闭包和This 5. 对象是一切的基础,我们从这里起步,用一个个对象构建前端的摩天大楼!对象实际非常简单,它就是一个容器,可以以键值对的形式储藏信息,例如姓名. 性别。对象有一个非常重要的内部属性__proto__,指向它的原型对象,以实现方法. 属性的复用或着说继承。 6. 我们写过这样的代码,那它是如何执行的呢?事实上,这里涉及到一个属性查找的问题。[]对象本身没有hasOwnProperty这个方法,于是继续查找__proto__属性指向Array prototype是否有该方法,依然查找失败,于是继续查找Array prototype对象的__proto__属性指向的对象...最终找到Object.prototype上有这个方法,执行的结果为true。每个对象通过__proto__属性与自己的原型对象建立联系,而且这个过程是可以延续的,这就是js里原型链的概念。通过这个例子,我们知道:原型链在JS中的作用是查找对象的属性/方法。 7. 原型链除了方法的复用还有什么作用呢?一个重要的例子就是instanceof操作符。instanceof操作符就是通过判断第二个操作数的原型对象是否在第一个操作数原型链上来进行判别。 8. 接下来的一个疑问是:这些对象是怎么得来的呢?答案是构造器。 9. 构造器,在JS中也就是函数。这里展示下函数的创建过程。这里需要注意的几点是: - [[Class]]:因为typeof不准确,现在各个js库都是根据这个属性来判别对象类型的(Object.prototype.toString.call(obj)) - [[Prototype]]:因为函数也是一个对象,所以也有指向自己原型的内部属性 - [[Call]]:在执行函数时调用,会产生一个新的执行上下文 - [[Construct]]:在函数作为构造器调用时调用(通过new操作符) - [[Scope]]:保存函数的作用域 - length:函数期望参数数目 - prototype:用来为构造器创建对象设置[[prototype]] 10. 制造对象通过函数对象的内部属性[[Construct]]进行。 - 创建一个原生对象,这个对象是”纯洁的“ - 添加这个原生对象的内部属性[[Class]],这个属性是用来判定对象类型的 - 然后添加这个原生对象的内部属性[[Prototype]],也记做__proto__ - 执行函数对象代码,其中的this设置为刚刚创建的原生对象。记执行代码返回值为R - 如果R为对象,则返回R,否则返回创建的原生对象O 11. 一个简单的例子。 12. 只要记住一点:构造器的prototype属性是用来为创建对象设置__proto__属性的,构造器作为对象也有自身的__proto__属性,指向的是Function.prototype对象。 13. JS中的代码可以划分为三种类型:全局代码. 函数代码和eval代码。eval这个方法我们要尽量少的使用,因为不单有创建一个新解析器的开销,还有安全性方面的问题。 14. 每种类型的代码在执行时都会在相应类型的上下文中,我们称之为执行上下文。 15-31. 这个例子简单展示了执行上下文栈的运行过程。 32. 接下来我们详细了解一下执行上下文。执行上下文也可以理解为一个对象,主要的属性有三个:变量对象. 作用域链和thisValue。 - 变量对象是一个保存当前代码中所有变量. 函数声明等的对象 - 作用域链是由执行上下文的变量对象和所有父级作用域构成的,可以理解为一个数组 - thisValue用来指明当前代码中this所代表的值 33. 变量对象根据执行上下文的不同有一些差异: - 在全局执行上下文中,变量对象就是全局对象本身,而this也是指向全局对象的,所以它们三个相等。这个特性非常重要,因为我们可以通过访问全局对象来获得变量对象中储存的变量,这也是唯一可以访问变量对象的情形 - 在函数执行上下文中,变量对象增加了arguments对象和行参等,这被称为活动对象。我们是不能直接访问到活动对象的 34. 全局变量对象的一个例子。 35. 活动对象的一个例子。注意arguments对象是一个array-like的对象而不是一个array。 36. 代码的执行过程分为两步,首先进入执行上下文,主要是初始化上下文中的三个属性:变量对象. 作用域链和thisValue,然后开始执行代码。 37. 在进入执行上下文阶段,初始化变量对象的过程是非常值得注意,因为在这个过程中,函数中所有形参. 变量声明. 函数声明都会被保存至变量对象中,进而影响作用域链,最终影响到变量的查找。初始化变量分为三步,这其中要注意的是: - 所有函数声明都会将函数名添加为变量对象的一个属性,函数对象为该属性的值,所以我们可以将函数定义在任何位置。为了主体逻辑更加清晰,一般我们都将函数声明放在靠后的位置 - 所有变量声明的变量名都会作为变量对象的一个属性,其值为undefined。在执行代码阶段,解析器其实不会理会var的。为了防止忘记声明变量,所以建议在函数开始时声明所有局部变量 - 变量对象属性之间的覆盖问题。函数声明的函数名可以覆盖之前所有VO属性,变量声明的变量只能覆盖之前的重名变量 38. 声明可以不被覆盖,但是语句仍然会执行。在本例中,形参x没有被变量x覆盖,但执行var x = 10之后x的值仍然会变化。形参y会被函数声明y覆盖。 39. 一个作用域链的例子。 40. 作用域链的几个特性,静态作用域的概念非常重要,函数在声明的时候即已确定自身的作用域链内容([[Scope]])。 41. 闭包实现的基础有两个方面: - 函数是一级对象,可以像普通对象一样赋值给变量. 作为函数返回值. 作为参数传递给函数 - 函数对象会保存声明时的作用域链,也就是函数具有静态作用域 这两个特性使得JS中每个函数都是一个闭包,为这种语言增加了无限的变化和魔力。 42. 函数作为返回值,或者称为自底向上的闭包。 43. 函数作为参数,或者称为自上到下的闭包。 44. this在进入执行上下文阶段被赋值,在全局执行上下文中就是全局对象,在函数执行上下文中会随着函数的调用方式不同有所变化。 45. 本文主要参考了<NAME>的ECMA-262-3 in detail系列文章,我本人获益匪浅。 46. 谢谢大家。 ## 参考 - [The Core](http://dmitrysoshnikov.com/ecmascript/javascript-the-core/) - [ECMA-262-3 in detail](http://dmitrysoshnikov.com/tag/ecma-262-3/) - [Annotated ECMAScript 5.1](http://es5.github.com/) <file_sep>/share/node-async/demos/promise.js var fs = require('fs'); var path = require('path'); var denodeify = require('denodeify'); var fsReaddir = denodeify(fs.readdir); var fsStat = denodeify(fs.stat); function findMaxSizeFile(dir) { return fsReaddir(dir) .then(function (files) { var promises = files.map(function (file) { return fsStat(path.join(dir, file)) }) return Promise.all(promises).then(function (stats) { return { files: files, stats: stats }; }); }) .then(function (data) { var largest = data.stats .filter(function (stat) { return stat.isFile(); }) .reduce(function (prev, next) { if (prev.size > next.size) return prev; return next; }); return data.files[data.stats.indexOf(largest)] }); } findMaxSizeFile('./') .then(function (file) { console.log('the max size file is', file); }) .catch(function (error) { console.log('error', error); }); <file_sep>/blog/source/_posts/the-awakeing-age.md --- layout: post title: "“觉醒年代”有感" date: 2021-08-12 22:09 status: publish tags: [Series, Review] --- 请移步知乎“跬步千里”专栏 [“觉醒年代”有感](https://zhuanlan.zhihu.com/p/397630221) 查看全文。 <file_sep>/share/node-async/demos/callback-async.js var fs = require('fs'); var async = require('async'); var path = require('path'); function findMaxSizeFile(dir, cb) { async.waterfall([ function (next) { fs.readdir(dir, next) }, function (files, next) { var paths = files.map(function (file) { return path.join(dir, file); }); async.map(paths, fs.stat, function (err, stats) { next(err, files, stats); }); }, function (files, stats, next) { var largest = stats .filter(function (stat) { return stat.isFile(); }) .reduce(function (prev, next) { if (prev.size > next.size) return prev; return next; }); next(null, files[stats.indexOf(largest)]); } ], cb); } findMaxSizeFile('./', function (error, file) { if (error) { console.log('error', error); } console.log('the max size file is', file); }); <file_sep>/blog/source/_posts/fire-fast.md --- layout: post title: "Fire Fast" date: 2022-05-03 09:28:25 status: publish tags: - Recruitment - Organization --- [上篇文章](https://shangchun.net/hire-slow/),我们谈过了“Hire slow,fire fast”的前半句,今天我们聊下后半句,也即“fire fast”。 历经千辛万苦,新人终于到岗并开始适应新环境,大部分人都可以在两到三个月时间恢复战斗力,进而产出符合预期的价值。 但也有少数例外情况,由于种种原因,新人并没有达成预期。应该怎么处理这样的情况呢? ## 一定要 fire 吗? 首先我们要界定这个人是不是达到了需要 fire 的标准,具体各团队可能都有些适合自身的判断。 我个人比较偏向的标准是: 1. 不能达成预期的预期是长期性的,短期内很难改观 <p style="margin: 0 0 0.2rem 0"> 如果新人只是因为对于当前技术栈不熟悉,或者因为外语、远程办公等工作环境的剧烈变化导致的不符合预期,那么我们是可以考虑多给些时间以进一步考察。 但如果新人是因为自身能力问题,譬如一个高级工程师无法产出合格的系统方案设计,或者总是用两倍甚至三倍以上的时间才能交付质量下乘的项目, 这类问题通常无法短时间内通过培训等助力方式快速提升 </p> 2. 存在一些原则性的根源问题 <p style="margin: 0 0 0.2rem 0"> 每个团队可能都有一些”红线“,譬如一个非常分布式的基于信任构建的团队里,非常依赖高度自驱来推进各项目,如果新人无法自律,划水严重, 如果在管理者进行警告督促后仍无有效改正的话,可以认定存在原则性问题。类似的红线问题还有不诚信、泄露公司机密牟利等等 </p> 其实第二点只是第一点的一种特例,本质上第一点这一标准就够了。 <!--more--> ## Fire 其实阻力重重 即便我们内心的天平已经偏向于 fire,但实操层面,往往还有各种因素导致我们无法快速做出决断: - 这位工程师只是解决问题速度慢了点,其它例如沟通方面还是可以的 - 代码写的虽然糙了点,但是也能如期交付 - 自律比较差,但是多催一催也能出活 从根本上来讲,本身这个世界就是复杂的,并不是非黑即白,我们往往要在灰色地带做取舍。 大部分未达预期的新人既然能够通过层层筛选,肯定也有自己的相对优势。 那么怎么权衡要不要 fire 就高度依赖团队管理者对于情势的判断,尤其是团队定位和个人定位的调和空间。 如果他的某方面核心能力能够在未来一段时间提升团队的短板,那么即便管理者适当补位也可以接受的话,那可以先留任看看。 相反,如果他的核心能力或者很弱或者并非团队将来所需的情况下,就没有必要继续。 另外一个 fire 的阻力点是:这某种程度上证明了招聘流程存在疏漏。让人正面和解决问题需要高度自信,有的管理者可能由于这方面的疑虑, 往往都优先选择再观察一段时间,直到很久之后迫不得已才动手。其实大可不必,即便是类似 Netflix 之类的优秀团队, 也有可能遇到一些针对性比较强的候选人或者遗漏了一些要点。就像我们维护一个产品或者系统,逐步迭代查漏补缺就好。 还有人担忧说如果新人愤愤不平,故意捣乱怎么办,譬如实名或匿名开始语言攻击或者诋毁团队,破坏团结等。 其实我倒是觉得,这样的人越早暴露越说明我们做对了。 ## 容忍低绩效者是对大多数人的惩罚 在上一篇文章里我们分享过平庸的工程师带来的一些负面影响,其中我认为最重要的一条是: - 向团队表明你接受平庸,从而使问题更加严重 正如那篇文章开头的例子一样,低绩效者一旦在团队中被其他人显著地识别了出来,那么大家就会开始质疑团队是否还在一个健康发展之中。 一旦他们做出了肯定的判断,那么高绩效者们的离开只是时间问题。因此我一向认为,容忍低绩效者实际是对大多数人的惩罚,是在向大家表明这个团队越来越平庸。 对于管理者,我理解非常类似 <NAME> 这样的守夜人,核心职能之一就是能够营造出一种让团队的大部分人充分发挥自己的聪明才智为公司贡献价值的氛围。 当有一些噪音或者负面情况出现时,守夜人能够及时发现和干预,以保障团队主体免遭影响。 也因此,即便困难重重,我依然建议管理者从整体利益出发,在负面影响扩大之前,早做决断。 ## 所有的底气来自于有能力招更好的人 不少管理者在是否 fire 之间犹豫不决还有一个重要因素:招人不易。试问:如果一个月内就可以招到符合要求的候补成员,还用得着犹豫吗?当然不用! 所以,类似我在[招聘驱动的组织建设](https://shangchun.net/recruitment-driven-organization/)中提到的 > 工程师组织建设的核心就是招人,招足够优秀的人 如果我们整个组织是优秀高效稳定的,辅以适当的面向招聘的各项举措,自然能够吸引到足够的候选人,从而实现自然可持续增长。 ## 结语 ”Hire slow, fire fast" 看似简单,实则是大智慧,关乎高人才密度团队建设的一体两面。我自己在平时工作中受用良多,对于“做正确而不是容易的事情”也有了更深的理解。这两篇粗浅的思考也希望能给更多人提供参考。 <file_sep>/share/bundler-pipeline/examples/webpack-loader/components/App/App.js import React from 'react'; import styles from './App.css'; var TopNav; if (process.env.BROWSER) { TopNav = require('../TopNav/TopNav'); } const App = React.createClass({ render() { return ( <div> <div className={styles.contentWrapper}> content </div> </div> ); } }); export default App; <file_sep>/blog/source/_posts/event-do.md --- layout: post title: "YUI事件体系之Y.Do" date: 2012-07-14 17:34 comments: true status: publish tags: [YUI, Event, JavaScript] --- YUI团队在种种场合不断的夸耀自己的事件体系是多么强大: - YUI 3′s Event module is one of the strengths of the library --<NAME>, [YUI Theater — <NAME>: "Events Evolved"](http://www.yuiblog.com/blog/2009/10/30/smith-yuiconf2009-events/) - YUI 3 is not all about DOM manipulation — it also contains a robust set of class/object management tools, not to mention our powerful custom events --<NAME>, [10 Things I Learned While Interning at YUI](http://net.tutsplus.com/articles/general/10-things-i-learned-while-interning-at-yui/) - One of the strengths of the YUI App Framework is that it's integrated tightly with the rest of YUI and benefits from YUI's fantastic event system and plugin/extension infrastructure. --<NAME>, [How can I decided whether to choose YUI 3's MVC or Backbone for a new project?](http://www.quora.com/How-can-I-decided-whether-to-choose-YUI-3s-MVC-or-Backbone-for-a-new-project#ld_xJGMd1_3012) 事实的确如此吗?就使用YUI的开发者反馈来看,应该是不错的: - AFAIK YUI 3's event system is the most sophisticated of any JavaScript framework. Am I wrong in thinking that? --[<NAME>](https://twitter.com/wrumsby/status/113568040834174976) - I love the event system in YUI. Pure awesomeness. --[<NAME>](https://twitter.com/kev_nz/statuses/180472697644515328) - I am constantly impressed by the degree of excellence I find in working with the YUI3 framework --<NAME>, [Cross YUI Communication and Custom Events](http://andrewwooldridge.com/blog/2011/03/08/cross-yui-communication-and-custom-events/) 作为一名YUI用户,我对其事件体系的强大深有体会。从本篇文章起,我将对YUI事件机制做一个全面分析。 本次我们介绍的是比较基础的两个对象`Y.EventHandle`和`Y.Do`。千里之行积于跬步,YUI整套事件机制也是从这两个对象开始构筑的。 <!-- more --> ## Y.EventHandle `Y.EventHandle`的作用很简单:注销事件/消息监听。 ```javascript Y.EventHandle = function (evt, sub) { this.evt = evt; // 事件对象 this.sub = sub; // 监听对象 }; Y.EventHandle.detach = function () { this.evt._delete(this.sub); // 执行event对象的_delete方法,注销事件/消息监听 return true; }; ``` ## Y.Do `Y.Do`的作用是:向对象方法前面或者后面插入其它方法(前置、后置方法),以达到动态修改对象行为的目的。这种方式,也称作[AOP](http://en.wikipedia.org/wiki/Aspect-oriented_programming)。 ## 示例 让我们先来看个简单的例子: ```javascript // 例1 YUI().use('event-custom', function (Y) { var cat = { eat: function () { console.log('eat a fish'); } }; cat.eat(); // output: eat a fish var beforeHandle = Y.Do.before(function () { console.log('catch a fish'); }, cat, 'eat'); var afterHandle = Y.Do.after(function () { console.log('done!'); }, cat, 'eat'); cat.eat(); // output: catch a fish, eat, done! afterHandle.detach(); cat.eat(); // output: catch a fish, eat }); ``` 在不修改原对象方法的基础上,可以方便的添加前置、后置方法,并且注销这些方法也很容易。`Y.Do`非常漂亮的解决了我们动态修改对象方法的需求!很难想象,如果不用`Y.Do`代码会复杂成怎样。 ## 源代码分析 接下来,让我们看看YUI的内部实现吧。这是多么有趣的事,就像小时候买把手枪,想不明白为什么可以射击,就砸开一看究竟。 为了更容易的看懂代码的核心,我做了适当的简化,感兴趣的朋友可以去看未删节的[源码](http://yuilibrary.com/yui/docs/api/files/event-custom_js_event-do.js.html#l16)。 ```javascript // 代码版本为YUI3.4.1,YUI3.5.0对Y.Do的实现有所改进 var DO_BEFORE = 0, DO_AFTER = 1; Y.Do = { // 缓存处理对象 objs: {}, before: function (fn, obj, sFn) { return this._inject(DO_BEFORE, fn, obj, sFn); }, after: function (fn, obj, sFn) { return this._inject(DO_AFTER, fn, obj, sFn); }, _inject: function (when, fn, obj, sFn) { var id = Y.stamp(obj), o, sid; if (!this.objs[id]) this.objs[id] = {}; o = this.objs[id]; if (!o[sFn]) { // 创建保存对象、方法名的Method对象 o[sFn] = new Y.Do.Method(obj, sFn); // 修改对象方法 obj[sFn] = function () { return o[sFn].exec.apply(o[sFn], arguments); }; } sid = id + Y.stamp(fn) + sFn; // 注册插入方法 o[sFn].register(sid, fn, when); // 返回EventHandle对象,方便注销 return new Y.EventHandle(o[sFn], sid); } } Y.Do.Method = function (obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; Y.Do.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; // 注销插入方法 Y.Do.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; Y.Do.Method.prototype.exec = function () { var before = this.before, after = this.after, i, ret; // 执行插入前面的方法 for (i in before) { if (before.hasOwnProperty(i)) { ret = before[i].apply(this.obj, arguments); } } // 执行原方法 ret = this.method.apply(this.obj, arguments); // 执行插入后面的方法 for (i in after) { if (after.hasOwnProperty(i)) { ret = after[i].apply(this.obj, arguments); } } return ret; }; ``` ## 适用场景 ### a) 动态修改对象方法 请参照例1。 ### b) 动态修改原型方法 原型也是对象,所以,另外一个适用场景就是修改原型方法。 ```javascript // 例2 YUI().use('event-custom', function (Y) { function Car(brand) { this.brand = brand; }; Car.prototype.start = function () { console.log('start'); }; var myCar = new Car('bmw'); Y.Do.before(function () { console.log('open the door'); }, Car.prototype, 'start'); Y.Do.after(function () { console.log('the car is started!'); }, Car.prototype, 'start'); myCar.start(); // output: open the door, start, the car is started! }); ``` ### c) 动态修改宿主方法 为宿主对象添加插件时,插件往往需要在宿主一些方法前后执行某些操作。YUI提供了一个很好的[例子](http://yuilibrary.com/yui/docs/plugin/#methods)。 ### d) 动态修改被扩展对象方法 为对象添加扩展时,扩展对象往往需要在被扩展对象一些方法前后执行某些操作。YUI提供了一个很好的[例子](http://yuilibrary.com/yui/docs/assets/base/myextension.js.txt)。 ## 进阶使用 由于简化代码,省略了一些细节。`Y.Do`还有很多功能,例如:可以根据前置方法返回值阻止默认方法执行、替换参数等等。下面介绍一些这样的进阶使用方式: ```javascript // 例3 YUI().use('event-custom', function (Y) { function Car(brand, degree) { this.brand = brand; this.degree = degree || 0; }; Car.prototype.shift = function (degree) { console.log('change to ' + degree); }; var myCar = new Car('bmw'); // 多个前置方法 Y.Do.before(function (degree) { console.log('prepare to change'); }, Car.prototype, 'shift'); Y.Do.before(function (degree) { console.log('prepare to change again'); }, Car.prototype, 'shift'); myCar.shift(1); // output: prepare to change, prepare to change again, change to 1 // 多个后置方法 Y.Do.after(function (degree) { console.log('already change'); }, Car.prototype, 'shift'); Y.Do.after(function (degree) { console.log('already change again'); }, Car.prototype, 'shift'); myCar.shift(2); // output: ..., change to 2, already change, already change again // 中止执行 Y.Do.before(function (degree) { if (degree < 0) { console.log('halt, too low!'); return new Y.Do.Halt(); } }, Car.prototype, 'shift'); myCar.shift(-1); // output: ..., halt, too low! // 阻止默认方法 Y.Do.before(function (degree) { if (degree > 4) { console.log('prevent changing, too high!'); return new Y.Do.Prevent(); } }, Car.prototype, 'shift'); myCar.shift(5); // output: ..., prevent changing, too high!, already change, ... // 替换参数 Y.Do.before(function (degree) { var d = Math.floor(degree); if (degree !== d) { return new Y.Do.AlterArgs('degree should be a integer', [d]); } }, Car.prototype, 'shift'); myCar.shift(2.5); // output: ..., change to 2, ... // 替换返回值 Y.Do.after(function (degree) { if (degree === 0) { return new Y.Do.AlterReturn('', 'wow, your car now has no power'); } }, Car.prototype, 'shift'); var ret = myCar.shift(0); // output: ..., change to 0, ... console.log(ret); // wow, your car now has no power }); ``` ## 参考 - [YUILibrary-Do](http://yuilibrary.com/yui/docs/api/classes/Do.html) - [YUILibrary-EventTarget](http://yuilibrary.com/yui/docs/event-custom/index.html) - [Wikipedia-AOP](http://en.wikipedia.org/wiki/Aspect-oriented_programming) <file_sep>/blog/source/_posts/interview-is-bidirectional.md --- layout: post title: "面试是双向的" date: 2022-01-31 15:34:13 status: publish tags: [Interview] --- 2018 年一段真实的对话: - 小 A:你好!非常抱歉,我考虑再三,决定还是加入另外一家公司 - 我:(内心有点小崩溃,但是还想再抢救一下)嗯嗯,替你感到高兴!不过方便再问一下,你最期望在下一份工作中得到什么呢? - 小 A:主要还是想在技术方面有一些成长吧 - 我:(感觉我们还是有点竞争力)面试是双向的,可以的话,我建议你再比较下两边的面试体验,看下哪边的工程师技术更好些 - 小 A:ok,那我再考虑一下 几天后: - 小 A:我觉得还是你们这边技术方面更好些,所以我改变了主意,准备加入你们 后来小 A 入职后,成长速度的确非常非常好,业余爱好也是一个没落下,说是事业爱好双丰收也不为过。 类似的“话术”后面我也用过几次,在候选人的几个选项比较接近时,成功率还是蛮高的。 <!--more--> ## 在面试候选人的同时,候选人也在考察面试官 一般人理解面试官总是高人一等的,牢牢把握着面试中的主动权。究其根本,这种先入为主的偏见其实往往来源于层级分明的公司文化中: - 一切问题,老大说了算 - 高 P 总是掌握着更多的资源和决策权 - 新来的是龙得盘着点,是虎得卧着点,轮不到你 BB 在这种文化中,人才是不太那么受重视的。面试的时候,既然你是过来讨口饭吃,那么居高临下去审视你当然就是理所当然的了。面试中也因此出现各种乱象: - 侧重寻找不足而非挖掘亮点 - 代码可以不写,但是一定要能说 - 偏好算法、脑筋急转弯,轻视工程实践、问题解决能力 - 迟到、早退、和候选人没有实质互动 - 简单粗暴不专业,被质疑的时候气急败坏 面试作为候选人和公司进行深入交流的重要窗口,其实不只是面试官们在评估候选人是不是适合特定岗位,与此同时,候选人其实也在通过面试体验来审视这家公司是不是适合自己: - 面试官一般是将来的团队骨干,他们是不是足够资深,自己跟着他们混有没有前途? - 面试官对自己从事的工作是不是眼中有光,激情投入? - 当自己遇到了困惑,或者情绪上有些紧张的时候,面试官是不是在引导和调整自己的状态,以更好地体现出自己的真实水平?如果是的话,那么这会是一个很 supportive 的团队 - 面试体验一定程度上体现出了公司的文化,自己是不是喜欢接下来三年五年在这样的文化里工作? 简而言之,候选人会去考虑自己是不是想和这样一批人共事。 ## 如何更好适应双向的面试? 作为如此重要的双方交流窗口,如何确保面试能够筛选出我们需要的人才,同时也能够提升候选人的体验和评价呢?我有如下几点思考。 ### 营造舒适平等的面试氛围 先说舒适。 很多候选人在面试开始的时候,或者遇到了一些挑战,都会有一些紧张。实话实话,我自己为数不多的面试里,就好多次比较紧张,导致没有发挥出应有水平。因此,在面试刚刚开始的时候,最好有一些举措让整个氛围热络起来: - 给候选人倒杯水,然后聊下今天来的路上堵不堵 - 简单评价下简历上的一些亮点,譬如拿过很多次奖学金、ACM 排名等等,表达对候选人的认可 - 面试官自我介绍下,同时也介绍下该轮面试的主要流程 基本就是套套近乎,为接下来的面试主题做些铺垫,帮助对方进入状态。 在面试中间如果发现候选人还是非常紧张,不太在状态,可以给一点小提示,或者其它的合理方式帮助对方降压。如果还是很难调整过来,可以再约面试。 另外一点也很重要:平等。 能够进入面试流程的候选人基本也是有货的,作为招聘方,既然我们希望能够招揽人才,那么就不要抱着高人一等的态度。反过来,对于一些非常出色的候选人,也大可不必太过谦卑,双方有利益共同点才是真正稳固的合作。 我们应该总是秉持一种平等的心态去沟通和交流。正如在后面的工作中一样,团队负责人只是一个协助大家发挥自身所长的角色而已。具体实践中有很多可以体现的点: - 沟通方式比较专业、和睦、不卑不亢 - 一些问题点候选人有疑问的时候,面试官应该与其交流,而非单纯让其自己考虑,冷眼相对 - 最后预留一些时间,一般五分钟左右,专门回答候选人的问题 通过营造这样一个愉悦的氛围,搭建好一个候选人能够高水平发挥的舞台,为接下来面试提供良好的基础。 ### 努力挖掘相关方向的亮点 好的面试题应该是怎样的? 不同的人有不同的解答。实践中,我们也发现很多人感慨“面试造火箭,入职扭螺丝”,面试内容和实际工作大相径庭。既然这么多人吐槽,那么显然这不太像好的面试题。还有一些候选人比较喜欢“应试”,刷题几百道后,面试 so easy,然而这样的技能在实际工作中真得有用吗? 目前我对好面试题的理解是这样的: - 来源于相关领域实践,但有一定拔高 - 有较好的层次性,很容易想到一些解决办法,且有多种层层递进的进阶方案 - 能够让有才华的候选人举一反三,融会贯通 譬如说前端的一个架构能力考核面试中,可以出一个题目:如何做一个微博首页。这是一个非常开放的题目,需要候选人去考虑实际场景、核心要求、团队结构、现有技术栈等去权衡各种方案的利弊。每当候选人有了一定的见解后,面试官可以选择一些要点继续深挖,直到逼近候选人的极限为止。如果遇到难得的高水平人才,我们可以继续讨论有所关联的类似产品但不同场景、不同产品类似场景等多种方案,看对方是否融会贯通,高屋建瓴。 另外,相比于挖掘对方的缺点,一种更好的方式还是抓亮点。我们需要知道候选人的不足,但这些不是能够提升我们团队能力的关键。构建一个高绩效团队和木桶理论不太相关,团队在某个方面的天花板更大程度地体现在大家的专长上。因此,抓亮点是关键所在。准确地抓亮点是设计面试题目的目标,如果面试题目和实际问题相去甚远、没有任何层次只是闭合性问题、没有一通百通而只适用特定领域,那么这样的题目就不能达成抓亮点的目标。 ### 专业的全流程体验 面试整个流程不只有面试官,还有人力部门、当地主管等等众多角色参与。某个环节掉链子的话,也会对面试体验有一定程度负面影响。譬如: - 某个新手面试官上来就引用编程语言问题晾了候选人一会儿。这可能需要更多事前培训和传帮带流程 - 约好的面试时间发现会议室被占用。这可能需要公司办公系统方面的支持 - Offer 沟通流程过长。这可能需要决策人员和 HR 团队的紧密配合 没有完美的流程,任何事情不可能一蹴而就。本着招贤纳士的根本目标,不断优化和完善全流程体验,才会赢得越来越多候选人的芳心。 ## 写在最后 人才是公司最宝贵的资源,面试是招揽人才最为重要的渠道。打造高水平的面试体验难度很大,但是非常物有所值。期望我的一点思考能够对你有所帮助,也欢迎一起探讨面试的相关问题。 <file_sep>/blog/source/_posts/event-target.md --- layout: post title: "YUI事件体系之Y.EventTarget" date: 2012-11-25 21:25 comments: true status: publish tags: [YUI, Event, JavaScript] --- ![bubble girl](/images/bubble-girl.jpg) 上两篇文章[YUI事件体系之Y.Do](/event-do/)、[YUI事件体系之Y.CustomEvent](/event-custom/)中,分别介绍了YUI实现AOP的`Y.Do`对象,以及建立自定义事件机制的`Y.CustomEvent`对象。 本篇文章,将要介绍YUI事件体系集大成者、最为精华的部分——`Y.EventTarget`。 ## Y.EventTarget DOM事件中的目标元素为`event.target`,这类元素可以触发、监听一些事件,例如input元素的click、focus等事件。这也正是`Y.EventTarget`的命名渊源,它提供了一种让任意对象定义、监听、触发自定义事件的实现方式。 从设计上看,`Y.EventTarget`通过内部维护一系列`Y.EventCustom`对象,提供了可以通过事件名称进行事件定义、监听和触发的便捷接口。另外,推荐使用`Y.augment`将它以组合的方式加载在其它类上,而不要使用继承。关于`Y.augment`和`Y.extend`之间的异同,可以参考我之前的一篇文章:[Y.extend与Y.augment](/extend-and-augment/)。 YUI很多基础类都扩展了`Y.EventTarget`,重要的有`Y`(YUI instance,sandbox)、`Y.Global`、`Y.Node`、`Y.NodeList`、`Y.Base`等。 YUILibrary有专门一个章节介绍EventTarget,非常详尽,如果你对EventTarget的设计思路和使用方法感兴趣,请移步[YUILibrary-EventTarget](http://yuilibrary.com/yui/docs/event-custom/)。 <!-- more --> ### 示例 首先,让我们看看`Y.EventTarget`独立调用的例子: ```javascript // 例1 YUI().use('event-custom', function (Y) { var et = new Y.EventTarget(); et.on('say', function (msg) { console.log('say:', msg); }); et.on('listen', function (msg) { console.log('listen:', msg); }); // output: say: Hello, world instance.fire('say', 'Hello, world'); }); ``` <!-- more --> 这种方式实际意义不大,YUI中只有`Y.Global`使用了这种方式。 下面,让我们看下最广泛的使用方式,即通过`Y.augment`扩展其它类: ```javascript // 例2 YUI().use('event-custom', function (Y) { function MyClass() {} MyClass.prototype.add = function (item) { // do sth this.fire('addItem', { item: item }); }; MyClass.prototype.remove = function (item) { // do sth this.fire('removeItem', { item: item }); }; // 用EventTarget扩展MyClass Y.augment(MyClass, Y.EventTarget); var instance = new MyClass(); // 监听addItem事件 instance.on('addItem', function (data) { console.log('add an item:', data.item); }); // 监听removeItem事件 instance.on('removeItem', function (data) { console.log('remove an item:', data.item); }); // output: add an item: orange instance.add('orange'); // output: remove an item: red instance.remove('red'); }); ``` ### 源代码分析 接下来,让我们看看YUI的内部实现吧。 注:为了更容易的看懂代码的核心,我做了适当的简化,感兴趣的朋友可以去看未删节的[源码](http://yuilibrary.com/yui/docs/api/files/event-custom_js_event-custom.js.html#l38)。 ```javascript var AFTER_PREFIX = '~AFTER~'; // EventTarget构造器 var ET = function (opts) { var o = opts || {}; // 私有事件聚合器 this._yuievt = this._yuievt || { id: Y.guid(), events: {}, config: o, // 默认配置 defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, broadcast: o.broadcast } }; }; ET.prototype = { constructor: ET, // 创建事件 publish: function (type, opts) { var ce, events = this._yuievt.events, defaults = this._yuievt.defaults; ce = events[type]; if (ce) { // 已创建过该事件 if (opts) { ce.applyConfig(opts, true); } } else { // 基于CustomEvent,创建新事件 ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } return ce; }, // 监听事件 on: function (type, fn, context) { var ce, after, handle, args = null; // 判断是否为后置监听 if (type.indexOf(AFTER_PREFIX) &gt; -1) { after = true; type = type.substr(AFTER_PREFIX.length); } // 获取自定义事件对象,如果未创建则先创建 ce = this._yuievt.events[type] || this.publish(type); if (arguments.length &gt; 3) { args = Y.Array(arguments, 3, true); } // 调用自定义事件对象的_on方法监听事件 handle = ce._on(fn, context, args, after ? 'after' : true); return handle; }, // 监听一次事件 once: function () { var handle = this.on.apply(this, arguments); if (handle.sub) { // 监听器执行一次则失效 handle.sub.once = true; } return handle; }, // 后置监听事件 after: function (type, fn) { var a = Y.Array(arguments, 0, true); a[0] = AFTER_PREFIX + type; return this.on.apply(this, a); }, // 后置监听一次事件 onceAfter: function () { var handle = this.after.apply(this, arguments); if (handle.sub) { handle.sub.once = true; } return handle; }, // 触发事件 fire: function (type) { var ce, args; args = Y.Array(arguments, 1, true); ce = this._yuievt.events[type]; // 尚未创建事件 if (!ce) return true; return ce.fire.apply(ce, args); }, // 注销事件监听 detach: function (type, fn, context) { var events = this._yuievt.events, ce, i; // 未设置事件类型,则注销所有类型的事件 if (!type) { for (i in events) { if (events.hasOwnProperty(i)) { events[i].detach(fn, context); } } return this; } ce = events[type]; if (ce) { ce.detach(fn, context); } return this; } }; ``` ### 进阶用法 `Y.EventTarget`作为一个十分重要的类,提供了非常丰富、方便的使用方式,除了依赖内部`Y.CustomEvent`实现的事件接口、默认执行方法、事件广播等,其余主要有: #### a) 事件冒泡 多个EventTarget对象之间可以建立一定事件传播关系,类似DOM事件中的冒泡。 ```javascript // 例3 YUI().use('event-custom', function (Y) { // 父类 function Parent() { ... } Y.augment(Parent, Y.EventTarget, true, null, { emitFacade: true }); // 子类 function Child() { ... } Y.augment(Child, Y.EventTarget, true, null, { emitFacade: true }); var parent = new Parent(), child = new Child(); // 子类对象添加冒泡目标对象,child -&gt; parent child.addTarget(parent); parent.on('hear', function (e) { console.log('parent hear', e.msg); }); child.on('hear', function (e) { console.log('child hear', e.msg); }); // output: child hear Hi, parent hear Hi child.fire('hear', { msg: 'Hi' }); }); ``` #### b) 事件前缀 在事件冒泡的基础上,考虑到区分不同EventTarget对象触发相同事件,YUI引入了事件前缀(Event Prefix)。 ```javascript // 例4 YUI().use('event-custom', function (Y) { // 父类 function Parent() { ... } Y.augment(Parent, Y.EventTarget, true, null, { emitFacade: true, prefix: 'parent' // 配置事件前缀 }); // 子类 function Child() { ... } Y.augment(Child, Y.EventTarget, true, null, { emitFacade: true, prefix: 'child' // 配置事件前缀 }); var parent = new Parent(), child = new Child(); child.addTarget(parent); parent.on('hear', function (e) { // 不能捕捉到child的hear事件 console.log('parent hear', e.msg); }); child.on('hear', function (e) { console.log('child hear', e.msg); }); // output: child hear Hi child.fire('hear', { msg: 'Hi' }); parent.on('*:see', function (e) { // 要想监听到其它EventTarget对象的see事件,需要设置prefix console.log('parent see', e.thing); }); child.on('child:see', function (e) { // 等同监听see事件 console.log('child see', e.thing); }); // output: child hear MM, parent see MM child.fire('see', { thing: 'MM' }); }); ``` ## 参考 - [YUILibrary-CustomEvent](http://yuilibrary.com/yui/docs/api/files/event-custom_js_event-custom.js.html) - [YUILibrary-EventTarget](http://yuilibrary.com/yui/docs/event-custom/index.html) <file_sep>/share/from-mathematics-to-generic-programming/demo/multiply.js /** * First version */ function multiplyV1(n, a) { if (n === 1) return a; // 1a = a return multiplyV1(n - 1, a) + a; // na = (n - 1)a + a } console.log('multiplyV1', multiplyV1(5, 3)); /** * Second version * Egyptian multiplication: 4a = ((a + a) + a) + a = (a + a) + (a + a) * In further, 41 * 59 = (2^0 * 59) + (2^3 * 59) + (2^5 * 59) = 59 + 472 + 1888 = 2419 */ function multiplyV2(n, a) { if (n === 1) return a; var result = multiplyV1(half(n), a + a); return odd(n) ? (result + a) : result; } function odd(n) { return !!(n & 0x1); } function half(n) { return n >> 1; } console.log('multiplyV2', multiplyV2(41, 59)); /** * Third version * Tail recursion to avoid stack costs */ function multiplyV3(r, n, a) { if (n === 1) return r + a; if (odd(n)) r = r + a; return multiplyV3(r, half(n), a + a); } console.log('multiplyV3', multiplyV3(0, 41, 59)); /** * Fourth version * Strict tail recursion */ function multiplyV4(r, n, a) { if (odd(n)) { r = r + a; if (n === 1) return r; } n = half(n); a = a + a; return multiplyV4(r, n, a); } console.log('multiplyV4', multiplyV4(0, 41, 59)); /** * Fifth version * Non-recursion from strict tail recursion */ function multiplyV5(r, n, a) { while (true) { if (odd(n)) { r = r + a; if (n === 1) return r; } n = half(n); a = a + a; } } console.log('multiplyV5', multiplyV5(0, 41, 59)); <file_sep>/blog/source/tags/index.md --- title: Tags date: 2021-11-25 12:12:45 layout: "tags" comments: false --- <file_sep>/share/bundler-pipeline/examples/webpack-plugin/webpack.config.js const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const DumpPlugin = require('./dumpPlugin'); const src = path.join(__dirname, '/components'); const dest = path.join(__dirname, "/dest"); module.exports = { context: src, entry: { app: path.join(src, 'App/App.js') }, output: { path: dest, filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, include: src, loader: 'babel', query: { presets: ['es2015', 'react'] } }, { test: /\.css$/, loader: ExtractTextPlugin.extract( 'style?sourceMap', [ 'css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]', ] ) } ] }, plugins: [ new ExtractTextPlugin('styles.css'), // new DumpPlugin() ] }; <file_sep>/share/bundler-pipeline/examples/webpack-plugin/components/TopNav/TopNav.js import React from 'react'; import styles from './TopNav.css'; const TopNav = React.createClass({ render() { return ( <nav style={styles.nav}> top nav </nav> ); } }); export default TopNav; <file_sep>/docs/management-leverage/index.html <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/> <meta http-equiv="Cache-Control" content="no-transform" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta name="theme-color" content="#f8f5ec" /> <meta name="msapplication-navbutton-color" content="#f8f5ec"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec"> <meta name="description" content="管理的杠杆"/><link rel="alternate" href="/atom.xml" title="<NAME>un" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=2.11.0" /> <link rel="canonical" href="https://shangchun.net/management-leverage/"/> <link rel="stylesheet" type="text/css" href="/lib/fancybox/jquery.fancybox.css" /> <link rel="stylesheet" type="text/css" href="/css/style.css?v=2.11.0" /> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-48551774-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-48551774-1'); </script><script id="baidu_push"> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> <script> window.config = {"leancloud":{"app_id":null,"app_key":null},"toc":true,"fancybox":true,"pjax":"","latex":false}; </script> <title>管理的杠杆 - <NAME></title> <meta name="generator" content="Hexo 5.4.0"></head> <body><div id="mobile-navbar" class="mobile-navbar"> <div class="mobile-header-logo"> <a href="/." class="logo"><NAME></a> </div> <div class="mobile-navbar-icon"> <span></span> <span></span> <span></span> </div> </div> <nav id="mobile-menu" class="mobile-menu slideout-menu"> <ul class="mobile-menu-list"><a href="/"> <li class="mobile-menu-item">Home </li> </a><a href="/archives/"> <li class="mobile-menu-item">Archives </li> </a><a href="/tags/"> <li class="mobile-menu-item">Tags </li> </a></ul> </nav> <div class="container" id="mobile-panel"> <header id="header" class="header"><div class="logo-wrapper"> <a href="/." class="logo"><NAME></a> </div> <nav class="site-navbar"><ul id="menu" class="menu"><li class="menu-item"> <a class="menu-item-link" href="/"> Home </a> </li> <li class="menu-item"> <a class="menu-item-link" href="/archives/"> Archives </a> </li> <li class="menu-item"> <a class="menu-item-link" href="/tags/"> Tags </a> </li> </ul></nav> </header> <main id="main" class="main"> <div class="content-wrapper"> <div id="content" class="content"><article class="post"> <header class="post-header"> <h1 class="post-title">管理的杠杆 </h1> <div class="post-meta"> <span class="post-time"> 2022-07-05 </span></div> </header> <div class="post-toc" id="post-toc"> <h2 class="post-toc-title">Contents</h2> <div class="post-toc-content"> <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%A8%E5%85%A5%E4%BD%BF%E5%91%BD"><span class="toc-text">注入使命</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%9B%98%E6%B4%BB%E8%B5%84%E6%BA%90"><span class="toc-text">盘活资源</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E4%BA%AB%E5%88%A9%E7%9B%8A"><span class="toc-text">分享利益</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-text">小结</span></a></li></ol> </div> </div><div class="post-content"><p>最近听到有朋友说我比较善于使用管理的杠杆,顿觉旁观者清。坦白来说,我自己虽然在日常实践中有意无意地应用类似的思想,却还未有明确的这方面的总结和提炼。 当时就萌生了写一篇文章来整理的想法。如今终于起笔,文中所言不一定对各位管理者有实际裨益,不过也权当是兼听则明吧。</p> <p>一位好的管理者,在我理解来看,应当是一个 Multiplier,能够将大家的优势有效地发挥出来,形成合力,进而完成整个组织不断进阶的目标。 我坚持认为,群体的力量远胜于少数核心人物的智慧。为了更好地激发大家的主观能动性,用好管理的杠杆,下面介绍几点我自己的思考。</p> <h2 id="注入使命"><a href="#注入使命" class="headerlink" title="注入使命"></a>注入使命</h2><blockquote> <p>If you want to build a ship,don’t drum up people to collect wood and don’t assign them tasks and work, but rather long for the endless immensity of sea. 如果你想造一艘船,先不要雇人收集木头,也不要给人分配任务,而是激发他们对海洋的渴望。</p> </blockquote> <p>当一个项目需要一群人来完成时,我们可以有不同的方式来进行项目的启动:</p> <ol> <li>只介绍这个项目要做的具体事项</li> <li>介绍项目的优先目标以及实施方案</li> <li>介绍项目的背景、优先目标以及和公司整体战略的联系,并鼓励大家献计献策,通过沟通协作逐步确定具体方案</li> </ol> <p>第一种方式在很多公司都非常常见,大家都是公司雇员,拿钱办事,既然上面老板们决定要做那就没啥可讨论的,干就完了。 第二种方式相较而言,会跟大家分享项目想要解决的核心问题,这样一个好处是大家有了更明确的方向,这样就为调动大家积极性、激发大家审视和改良现有的实施方案提供了很大空间,对于有效完成项目目标有非常正面的意义。 第三种方案在两个点上做的更进一步:一方面会讲清楚项目对于公司的关键作用,有助于大家理解这一项目在哪些层面对于公司的进一步发展至关重要。另一方面也提高了大家的参与感,具体方案的确定是通过沟通协作来完成的,这样的方案也往往更接地气,在效率和成本方面都能做到非常出色。</p> <p>在平时的实践中,我非常有意识地在用第三种方式来为一个事情注入使命,并在前期沟通中不断和利益攸关方沟通以凝聚共识。</p> <p>以确立新人培训流程这个项目为例:</p> <ul> <li>项目的核心价值是帮助新人快速融入团队并为后续发挥战斗力打好基础,具体包括了解各团队的人和事,以及公司发展过程、产品演变历史、团队文化等内容</li> <li>跟相关老大们协调一致后,在和各个团队骨干讲师的沟通中,着重强调的是这件事对于新人和公司的重大价值:公司的发展最核心的动力在于人,而让源源不断的新人快速适应和融入团队,对于传承优秀的团队文化和打造一支精英团队至关重要</li> <li>后续的流程推进中,能够明显感觉到各位讲师在培训上投入很多,包括内容准备、讲解技巧等等方面,他们也通过培训更多地了解和认识了很多新人</li> </ul> <p>类似的例子还有很多,大到公司的一些核心项目,小到一次外出团建,我们都会竭尽所能地将其背后的重要意义跟大家阐释出来。</p> <p>我能明显感觉到具有使命感与否所产生的巨大差异,目标明确且有信念的人常常让你眼前一亮,他们不仅会主动找到更优的方案,而且在面对困难时也百折不挠,使命必达。 这也让我深刻认识到另一个道理:<strong>注入使命才会催发主人翁精神</strong>,之后的事情就变得简单起来,不需要那么多的微观管理。</p> <h2 id="盘活资源"><a href="#盘活资源" class="headerlink" title="盘活资源"></a>盘活资源</h2><p>南水北调、西气东输、精准扶贫等祖国大地上发生的重大项目都体现出了盘活资源的重要意义。和国家治理类似,管理杠杆的另一个重点是合理地利用好手里的资源,这里的资源包括人、项目、资金、活动等等,当然最重要的还是人。</p> <p>盘活资源在我理解有以下几个点:</p> <ul> <li>首先要能够识别出能够在某方面能够有所作为的资源。就人而言,有人擅长社交,有人擅长分析,有人演讲特别有感染力,有人观察细致入微,这些都是他们的一些特质,将来可能能够为团队所用</li> <li>推进一个项目时,尽量从“能不能不做 -&gt; 能不能以后做 -&gt; 能不能别人做 -&gt; 自己做”这一逻辑出发,优先选派有相对优势的同事而非自己亲力亲为,以此来秣马厉兵,培养和发展人才</li> <li>鉴于项目初期可能同事之间还没那么熟悉,同时也可能有一些重要决策需要有人来背书,可以“扶上马,送一程”,然后只做一些咨询类的支持</li> </ul> <p>以我们一个内部分享会 Tubi Talent Time 的组织为例,最初团队比较小的时候,还主要是我来具体负责协调。后来团队成长到一定规模,原来的模式频频出现各种问题,包括轮值主持人找不到讲师、讲师内容准备不够充分、缺乏反馈渠道等等。 为了更好地解决这些问题,我们就从各个团队选了一些热衷于分享的同事,组建了一个新的委员会专门负责分享会的运作。大家勠力同心,不仅帮忙收集了很多潜在分享内容,而且在很多方面将分享活动的组织进一步优化,目前已经取得了超出我预期的进展。</p> <p>我有一个很深的体会是:<strong>你能调动的资源往往比你想象的要多</strong>。甚至不光所有下属,其实你的上级、平级和其他有合作的部门都是非常重要的潜在资源。在一个非常有价值的项目的串联下,这些资源都是可以争取到的。</p> <h2 id="分享利益"><a href="#分享利益" class="headerlink" title="分享利益"></a>分享利益</h2><p>“无双赢,不合作”是我的一个信条,如果你让一个人做一件事,而他却从中毫无所得,那人家为啥有动力去把这个事情做好呢?!财聚人散,财散人聚,这是一个很简单的道理。</p> <p>因此想要最终实现管理的杠杆,让更多人有意愿发挥自己的比较优势,就应该想方设法让他们也能分到应得的利益。这里的利益并不一定是钱,也可以是荣誉、机会、人际关系等等。</p> <p>在推进导师制的过程中,我对新晋导师进行培训的时候就开门见山介绍了他们可能的一些获益:</p> <ul> <li>增强知识储备。能够做好一件事和能够传授一件事是有本质区别的,后者才能让你对这件事的理解再上一个层次,吃深吃透</li> <li>建立人际关系。我们招到的都是非常优秀的工程师,相对而言新人可能在经验方法上欠缺一些,但是都足够有智慧,相互的切磋和沟通,可以深化“亦师亦友”的良好关系</li> <li>培养管理能力。很多人走上管理岗的第一步都是从做导师开始的,通过指导新人帮助他们快速成长,能够实践和掌握诸如预期管理、沟通、激励反馈等基本的管理技能</li> </ul> <p>后来事实上因为团队发展很快,很大一部分早期的导师都慢慢开始带更大规模的团队,获得收入、成长、人脉上的多丰收。</p> <p>关于利益我的一个体会是:<strong>更多着眼在能力成长这些本源上,它们并非物质利益但会带来物质利益</strong>。一旦我们把合作关系庸俗化,弄成赤裸裸的金钱利益共同体,就可能会产生短视、腐败等问题。能力提升才是最根本的。</p> <h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>教员曾经说过:所谓政治,就是把我们的人搞得多多的,把敌人搞得少少的。虽然管理并非政治,但有些思路是相通的。 只有解放群众,发动群众,不断通过改造生产关系来释放和发展生产力,才能激发出团队的最大潜能,实现组织的可持续的成功。 这其中,通过注入使命让大家有明确方向和一定灵活度,通过盘活资源让各类型要素流通协作,通过分享利益让大家真的有所得从而更有积极性和认同感,环环相扣,紧密联系,对于杠杆的有效发挥至关重要。 管理方面我虽然不是新兵,但也还在摸索前进。如果你有更多的想法,欢迎约饭交流。</p> </div> <div class="post-copyright"> <p class="copyright-item"> <span>Author: </span> <a href="https://shangchun.net"><NAME></a> </p> <p class="copyright-item"> <span>Link: </span> <a href="https://shangchun.net/management-leverage/">https://shangchun.net/management-leverage/</a> </p> <p class="copyright-item"> <span>License: </span><a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank">知识共享署名-非商业性使用 4.0 国际许可协议</a> </p> </div> <footer class="post-footer"> <nav class="post-nav"><a class="next" href="/react-query/"> <span class="next-text nav-default">数据请求利器 React Query</span> <span class="prev-text nav-mobile">Next</span> <i class="iconfont icon-right"></i> </a> </nav></footer> </article></div><div class="comments" id="comments"><div id="utterances-container"></div> </div></div> </main> <footer id="footer" class="footer"><div class="social-links"><a href="mailto:<EMAIL>" class="iconfont icon-email" title="email"></a> <a target="_blank" rel="noopener" href="https://twitter.com/springuper" class="iconfont icon-twitter" title="twitter"></a> <a target="_blank" rel="noopener" href="https://www.linkedin.com/in/chun-shang-45a41241/" class="iconfont icon-linkedin" title="linkedin"></a> <a target="_blank" rel="noopener" href="https://github.com/springuper" class="iconfont icon-github" title="github"></a> <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/shang-chun" class="iconfont icon-zhihu" title="zhihu"></a> <a href="/atom.xml" class="iconfont icon-rss" title="rss"></a> </div><div class="copyright"> <span class="power-by"> Powered by <a class="hexo-link" target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a> </span> <span class="division">|</span> <span class="theme-info"> Theme - <a class="theme-link" target="_blank" rel="noopener" href="https://github.com/ahonn/hexo-theme-even">Even</a> </span> <span class="copyright-year">&copy;2011 - 2022<span class="heart"> <i class="iconfont icon-heart"></i> </span> <span class="author"><NAME></span> </span> </div> </footer> <div class="back-to-top" id="back-to-top"> <i class="iconfont icon-up"></i> </div> </div><script> var container = document.getElementById('utterances-container') var script = document.createElement('script') script.src = 'https://utteranc.es/client.js' script.setAttribute('repo', 'springuper/springuper.github.io') script.setAttribute('issue-term', 'pathname') script.setAttribute('theme', 'github-light') script.setAttribute('label', 'utterances') script.crossorigin = 'anonymous' script.async = true container.appendChild(script) </script><script type="text/javascript" src="/lib/jquery/jquery.min.js"></script> <script type="text/javascript" src="/lib/slideout/slideout.js"></script> <script type="text/javascript" src="/lib/fancybox/jquery.fancybox.pack.js"></script> <script type="text/javascript" src="/js/src/even.js?v=2.11.0"></script> </body> </html> <file_sep>/blog/source/_posts/management-lever.md --- layout: post title: 管理的杠杆 date: 2022-07-05 21:06:17 status: publish tags: [Management, Lever] --- 最近听到有朋友说我比较善于使用管理的杠杆,顿觉旁观者清。坦白来说,我自己虽然在日常实践中有意无意地应用类似的思想,却还未有明确的这方面的总结和提炼。 当时就萌生了写一篇文章来整理的想法。如今终于起笔,文中所言不一定对各位管理者有实际裨益,不过也权当是兼听则明吧。 一位好的管理者,在我理解来看,应当是一个 Multiplier,能够将大家的优势有效地发挥出来,形成合力,进而完成整个组织不断进阶的目标。 我一直相信群体的力量远胜于少数核心人物的智慧。为了更好地激发大家的主观能动性,用好管理的杠杆,下面介绍几点我自己的思考。 ## 注入使命 > If you want to build a ship,don't drum up people to collect wood and don't assign them tasks and work, but rather long for the endless immensity of sea. > 如果你想造一艘船,先不要雇人收集木头,也不要给人分配任务,而是激发他们对海洋的渴望。 当一个项目需要一群人来完成时,我们可以有不同的方式来进行项目的启动: 1. 只介绍这个项目要做的具体事项 2. 介绍项目的优先目标以及实施方案 3. 介绍项目的背景、优先目标以及和公司整体战略的联系,并鼓励大家献计献策,通过沟通协作逐步确定具体方案 <!--more--> 第一种方式在很多公司都非常常见,大家都是公司雇员,拿钱办事,既然上面老板们决定要做那就没啥可讨论的,干就完了。 第二种方式相较而言,会跟大家分享项目想要解决的核心问题,这样一个好处是大家有了更明确的方向,这样就为调动大家积极性、激发大家审视和改良现有的实施方案提供了很大空间,对于有效完成项目目标有非常正面的意义。 第三种方案在两个点上做的更进一步:一方面会讲清楚项目对于公司的关键作用,有助于大家理解这一项目在哪些层面对于公司的进一步发展至关重要。另一方面也提高了大家的参与感,具体方案的确定是通过沟通协作来完成的,这样的方案也往往更接地气,在效率和成本方面都能做到非常出色。 在平时的实践中,我非常有意识地在用第三种方式来为一个事情注入使命,并在前期沟通中不断和利益攸关方沟通以凝聚共识。 以确立新人培训流程这个项目为例: - 项目的核心价值是帮助新人快速融入团队并为后续发挥战斗力打好基础,具体包括了解各团队的人和事,以及公司发展过程、产品演变历史、团队文化等内容 - 跟相关老大们协调一致后,在和各个团队骨干讲师的沟通中,着重强调的是这件事对于新人和公司的重大价值:公司的发展最核心的动力在于人,而让源源不断的新人快速适应和融入团队,对于传承优秀的团队文化和打造一支精英团队至关重要 - 后续的流程推进中,能够明显感觉到各位讲师在培训上投入很多,包括内容准备、讲解技巧等等方面,他们也通过培训更多地了解和认识了很多新人 类似的例子还有很多,大到公司的一些核心项目,小到一次外出团建,我们都会竭尽所能地将其背后的重要意义跟大家阐释出来。 我能明显感觉到具有使命感与否所产生的巨大差异,目标明确且有信念的人常常让你眼前一亮,他们不仅会主动找到更优的方案,而且在面对困难时也百折不挠,使命必达。 这也让我深刻认识到另一个道理:**注入使命才会催发主人翁精神**,之后的事情就变得简单起来,不需要那么多的微观管理。 ## 盘活资源 南水北调、西气东输、精准扶贫等祖国大地上发生的重大项目都体现出了盘活资源的重要意义。和国家治理类似,管理杠杆的另一个重点是合理地利用好手里的资源,这里的资源包括人、项目、资金、活动等等,当然最重要的还是人。 盘活资源在我理解有以下几个点: - 首先要能够识别出能够在某方面能够有所作为的资源。就人而言,有人擅长社交,有人擅长分析,有人演讲特别有感染力,有人观察细致入微,这些都是他们的一些特质,将来可能能够为团队所用 - 推进一个项目时,尽量从“能不能不做 -> 能不能以后做 -> 能不能别人做 -> 自己做”这一逻辑出发,优先选派有相对优势的同事而非自己亲力亲为,以此来秣马厉兵,培养和发展人才 - 鉴于项目初期可能同事之间还没那么熟悉,同时也可能有一些重要决策需要有人来背书,可以“扶上马,送一程”,然后只做一些咨询类的支持 以我们一个内部分享会 Tubi Talent Time 的组织为例,最初团队比较小的时候,还主要是我来具体负责协调。后来团队成长到一定规模,原来的模式频频出现各种问题,包括轮值主持人找不到讲师、讲师内容准备不够充分、缺乏反馈渠道等等。 为了更好地解决这些问题,我们就从各个团队选了一些热衷于分享的同事,组建了一个新的委员会专门负责分享会的运作。大家勠力同心,不仅帮忙收集了很多潜在分享内容,而且在很多方面将分享活动的组织进一步优化,目前已经取得了超出我预期的进展。 我有一个很深的体会是:**你能调动的资源往往比你想象的要多**。甚至不光所有下属,其实你的上级、平级和其他有合作的部门都是非常重要的潜在资源。在一个非常有价值的项目的串联下,这些资源都是可以争取到的。 ## 分享利益 “无双赢,不合作”是我的一个信条,如果你让一个人做一件事,而他却从中毫无所得,那人家为啥有动力去把这个事情做好呢?!财聚人散,财散人聚,这是一个很简单的道理。 因此想要最终实现管理的杠杆,让更多人有意愿发挥自己的比较优势,就应该想方设法让他们也能分到应得的利益。这里的利益并不一定是钱,也可以是荣誉、机会、人际关系等等。 在推进导师制的过程中,我对新晋导师进行培训的时候就开门见山介绍了他们可能的一些获益: - 增强知识储备。能够做好一件事和能够传授一件事是有本质区别的,后者才能让你对这件事的理解再上一个层次,吃深吃透 - 建立人际关系。我们招到的都是非常优秀的工程师,相对而言新人可能在经验方法上欠缺一些,但是都足够有智慧,相互的切磋和沟通,可以深化“亦师亦友”的良好关系 - 培养管理能力。很多人走上管理岗的第一步都是从做导师开始的,通过指导新人帮助他们快速成长,能够实践和掌握诸如预期管理、沟通、激励反馈等基本的管理技能 后来事实上因为团队发展很快,很大一部分早期的导师都慢慢开始带更大规模的团队,获得收入、成长、人脉上的多丰收。 关于利益我的一个体会是:**更多着眼在能力成长这些本源上,它们并非物质利益但会带来物质利益**。一旦我们把合作关系庸俗化,弄成赤裸裸的金钱利益共同体,就可能会产生短视、腐败等问题。能力提升才是最根本的。 ## 小结 教员曾经说过:所谓政治,就是把我们的人搞得多多的,把敌人搞得少少的。虽然管理并非政治,但有些思路是相通的。 只有解放群众,发动群众,不断通过改造生产关系来释放和发展生产力,才能激发出团队的最大潜能,实现组织的可持续的成功。 这其中,通过注入使命让大家有明确方向和一定灵活度,通过盘活资源让各类型要素流通协作,通过分享利益让大家真的有所得从而更有积极性和认同感,环环相扣,紧密联系,对于杠杆的有效发挥至关重要。 管理方面我虽然不是新兵,但也还在摸索前进。如果你有更多的想法,欢迎约饭交流。 <file_sep>/blog/source/_posts/yui-domready-after-load.md --- layout: post title: "YUI onDOMReady滞后window.onload原因浅析" date: 2011-03-11 14:12 status: publish tags: [YUI2, domready, load] --- ## 开篇 我很好奇其他前端工程师在wp后台写新文章的时候是在用可视化还是html模式。反正我是一路打着标签过来的,呵呵。 ## 缘起 一直以来,我都先验的认为dom ready事件肯定发生在load之前。但是,最近的一个ticket上线后发现一个很奇怪的现象:在IE下,有时会发生页面load时仍没有捕捉到dom ready的时间。通过多次观察,发现发生这种现象一般是较为简单的页面。 ## 分析 首先,在反复检查代码后排除了自身bug的问题。然后,去找到YUI(我们团队主要以YUI2作为基础库,并准备近期升级到YUI3)的`onDOMReady`实现,希望通过分析源码找到问题的起源,将`onDOMReady`在不含frame的IE中分支拣出来,代码量并不多: <!-- more --> ```js // Process onAvailable/onContentReady items when the // DOM is ready. YAHOO.util.Event.onDOMReady( YAHOO.util.Event._tryPreloadAttach, YAHOO.util.Event, true); var n = document.createElement('p'); EU._dri = setInterval(function() { try { // throws an error if doc is not ready n.doScroll('left'); clearInterval(EU._dri); EU._dri = null; EU._ready(); n = null; } catch (ex) { } }, EU.POLL_INTERVAL); ``` 实现的思路非常清晰:创建一个段落元素,然后轮询这个元素是否可以运行`doScroll`方法,在IE中,所有元素都有`doScroll`方法,而且如果文档没有完全解析完成的话,运行这个方法会报错。YUI正是运用了IE的这个特点来判定dom ready。而问题恰恰出在轮询而不是原生事件上,因为轮询有一个时间差(40毫秒),如果在下次嗅探之前文档加载完成,那么YUI所得到的dom ready时间就会滞后,进一步,如果页面并不包括很多图片等额外元素时,那么在下一次嗅探前dom ready且迅速触发load的话,就会出现YUI得到的dom ready时间比load时间更晚的怪象。 ## 修正 了解清楚问题的真正原因,问题的解决办法也就非常容易想到。最简单的办法是在load触发后滞后一段时间再执行需要dom ready时间的方法。进一步,因为在Firefox、Chrome、Safari等现代浏览器可以直接利用DOMContentLoaded事件即时捕捉到dom ready的时间,没有必要滞后执行,所以可以做下相应的判断。这种细节的处理才能显示出对用户体验的追求和优秀前端的价值。 <file_sep>/blog/source/_posts/scope-safe-constructor.md --- layout: post title: "如何保证调用构造函数也会得到一个实例" date: 2011-03-10 13:36 status: publish tags: [Instanceof, Scope-safe Constructor] --- 题目比较绕,其实意思很简单,先不解释,给出如下两个场景: ## 情景1 在js中,面向对象编程方法越来越流行,构造函数作为基础概念,使用的频率较高。 ```js function spring(name){ this.name = name; } var firstIns = new spring('shang chun'); //an instance of spring ``` 众所周知,构造函数本身也是一个函数,这就意味着它可以被随意调用。随着岁月的积累或协作人员之间信息不对称,很有可能不慎如下调用了这个构造函数: ```js var secondeIns = spring('wang qiang'); // 'this' refer to window now ``` 这样的代码并不会报错,但是却给全局对象`window`增加了`name`属性,这样的失误需要一种合适的方法避免。 <!-- more --> ## 情景2 想想看,如果我们想要马上调用新生成的实例,是不是只能这样去写 ```js (new spring('shang chun')).hasOwnProperty('name'); ``` 有没有更好的方法呢? ## 解决方案 事情回到了起点,我们想要的实际上是一个只要调用就无论如何都返回一个实例的构造函数,不管用不用`new`操作符。最近在看YUI3的源码,发现他们给出一种很好的解决方案,示例: ```js function spring(name) { var _this = this; var insanceOf = function(o, type){ return (o && o.hasOwnProperty && (o instanceof type)); }; if (!instanceOf(_this, spring)) { _this = new spring(name); } else { _this.name = name; } return _this; } var ins = new spring('shang chun'); // normal constructor ins.name; // outputs 'shang chun' spring('shang chun').name; // outputs 'shang chun' ``` <file_sep>/blog/source/_posts/event-note.md --- layout: post title: "Event小记" date: 2011-03-17 00:39 status: publish tags: [Event] --- Event在javascript中的重要性不言而喻,正是它驱动着所有事情的进行。记下一些读书的心得,整理如下: - Event按类别可分为input events和semantic events。semantic events的发生通常都建立在input events之上,例如点击“提交”按钮后产生onsubmit事件。input events依赖于输入设备。Events按模块可分为HTMLEvents、MouseEvents和UIEvents,对应的接口分别为Event、MouseEvent和UIEvent,其中MouseEvent接口继承了Event接口和UIEvent接口,常用的属性有altKey、ctrlKey、shiftKey和一些位置信息。 - DOM level 0的事件响应方式得到最为广泛的支持。具体应用方式有两种,一种是在页面目标元素中添加对应属性,如&lt;input type="button" onclick="alert(this.nodeName)" /&gt;;对应的另一种方式为 elButton.onclick = function(){ alert(this.nodeName); }。显式调用响应方法也非常简单,elButton.onclick()即可。响应方法中的this指代的是触发事件的页面元素。这种事件处理方式有一些缺点,例如:每个对象的某种事件只能添加一个响应方法,当需要将多个元素绑定事件时实现较为复杂等。 - DOM level 2的事件响应方式进行了诸多改进。事件被赋予一个传播过程,细分为capturing、target node、bubbling三个阶段。这一机制是有一定渊源的,不妨细讲。在当年Netscape与IE大战的年代,当遇到多个嵌套元素绑定同一事件时,如何确定响应方法执行顺序成为大家共同的问题,不幸的是他们做出了相反的选择:NetScape按照事件捕获的顺序执行,即父级节点响应方法优先执行,而IE按照事件冒泡的顺序执行,即子级节点响应方法优先执行。之后W3C过来和稀泥,也就制定了事件传播过程这一机制。需要注意的是,可以通过设定addEventListener的第三个参数设定响应方法在capturing阶段执行(true)还是在bubbling阶段执行(false)。 - 有些元素在一些操作后会有默认动作,如果恰好添加了这类事件监听器的话,执行的顺序是:响应方法执行先于默认动作。阻止默认动作发生,DOM level 0中可以用return false(window.status是一个例外,需return true);DOM level 2中可以使用preventDefault方法。停止事件传播使用stopPropagation方法。 - IE的事件模型并未遵循W3C标准。事件传播没有capturing阶段,bubbling阶段不能获得currentTarget,不会传递给事件响应方法event对象而是有一个全局event对象,注册/移除响应方法使用attachEvent/detachEvent,阻止事件传播使用cancelBubble等等。 - 为了将鼠标动作限定在特定页面元素,即便鼠标已不在该元素区域内,可将响应方法和事件注册在document上,在IE中可使用setCapture/releaseCapture方法。一个典型的案例是在拖拽模块时,鼠标移动常常快于模块。 - keyCode代表键位编号,charCode代表键位上字符的编号。IE的键盘事件中只有keyCode属性,可以用 e.charCode || e.keyCode获得keypress事件发生时对应按键的字符编号。 - 通过Document.createEvent创建自定义事件,并用Event.initEvent进行初始化,dispatchEvent进行调度。IE中可使用Document.createEventObject创建自定义事件,并用fireEvent进行调度。这部分可以说成为高级前端必备知识,在模块化编程等方面有较为重要的应用。 <file_sep>/blog/source/_posts/promise-insight.md --- layout: post title: "剖析 Promise 之基础篇" date: 2014-05-08 22:16 status: publish tags: [Promise, Monad, JavaScript] --- 随着浏览器端异步操作的复杂程度日益增加,以及以 Evented I/O 为核心思想的 NodeJS 的火爆,Promise、Async 等异步操作封装由于解决了异步编程上面临的诸多挑战,得到了飞速发展。本文旨在剖析 Promise 的内部机制,从实现原理层面深入探讨,从而达到“知其然且知其所以然”,在使用 Promise 上更加熟练自如。如果你还不太了解 Promise,推荐阅读下 [promisejs.org](https://www.promisejs.org/) 的介绍。 ## 是什么 Promise 是一种对异步操作的封装,可以通过独立的接口添加在异步操作执行成功、失败时执行的方法。主流的规范是 [Promises/A+](http://promisesaplus.com/)。 Promise 较通常的回调、事件/消息,在处理异步操作时具有显著的优势。其中最为重要的一点是:Promise 在语义上代表了异步操作的主体。这种准确、清晰的定位极大推动了它在编程中的普及,因为具有单一职责,而且将份内事做到极致的事物总是具有病毒式的传染力。分离输入输出参数、错误冒泡、串行/并行控制流等特性都成为 Promise 横扫异步操作编程领域的重要砝码,以至于 ES6 都将其收录,并已在 Chrome、Firefox 等现代浏览器中实现。 ## 内部机制 自从看到 Promise 的 API,我对它的实现就充满了深深的好奇,一直有心窥其究竟。接下来,将首先从最简单的基础实现开始,由浅入深的逐步探索,剖析每一个 feature 后面的故事。 为了让语言上更加准确和简练,本文做如下约定: - Promise:代表由 Promises/A+ 规范所定义的异步操作封装方式; - promise:代表一个 Promise 实例。 ### 基础实现 为了增加代入感,本文从最为基础的一个应用实例开始探索:通过异步请求获取用户id,然后做一些处理。在平时大家都是习惯用回调或者事件来处理,下面我们看下 Promise 的处理方式: ```javascript // 例1 function getUserId() { return new Promise(function (resolve) { // 异步请求 Y.io('/userid', { on: { success: function (id, res) { resolve(JSON.parse(res).id); } } }); }); } getUserId().then(function (id) { // do sth with id }); ``` [JS Bin](http://jsbin.com/kebigicu/1/embed?js,console) <!-- more --> `getUserId` 方法返回一个 promise,可以通过它的 `then` 方法注册在 promise 异步操作成功时执行的回调。自然、表意的 API,用起来十分顺手。 满足这样一种使用场景的 Promise 是如何构建的呢?其实并不复杂,下面给出最基础的实现: ```javascript function Promise(fn) { var value = null, deferreds = []; this.then = function (onFulfilled) { deferreds.push(onFulfilled); }; function resolve(value) { deferreds.forEach(function (deferred) { deferred(value); }); } fn(resolve); } ``` 代码很短,逻辑也非常清晰: - 调用`then`方法,将想要在 Promise 异步操作成功时执行的回调放入 `deferreds` 队列; - 创建 Promise 实例时传入函数被赋予一个函数类型的参数,即 `resolve`,用以在合适的时机触发异步操作成功。真正执行的操作是将 `deferreds` 队列中的回调一一执行; - `resolve` 接收一个参数,即异步操作返回的结果,方便回调使用。 有时需要注册多个回调,如果能够支持 jQuery 那样的链式操作就好了!事实上,这很容易: ```javascript this.then = function (onFulfilled) { deferreds.push(onFulfilled); return this; }; ``` 这个小改进带来的好处非常明显,当真是一个大收益的小创新呢: ```javascript // 例2 getUserId().then(function (id) { // do sth with id }).then(function (id) { // do sth else with id }); ``` [JS Bin](http://jsbin.com/fedukaso/2/edit?js,console) ### 延时 如果 promise 是同步代码,`resolve` 会先于 `then` 执行,这时 `deferreds` 队列还空无一物,更严重的是,后续注册的回调再也不会被执行了: ```javascript // 例3 function getUserId() { return new Promise(function (resolve) { resolve(9876); }); } getUserId().then(function (id) { // do sth with id }); ``` [JS Bin](http://jsbin.com/fenopelo/3/edit?js,console) 此外,Promises/A+ 规范明确要求回调需要通过异步方式执行,用以保证一致可靠的执行顺序。为解决这两个问题,可以通过 `setTimeout` 将 `resolve` 中执行回调的逻辑放置到 JS 任务队列末尾: ```javascript function resolve(value) { setTimeout(function () { deferreds.forEach(function (deferred) { deferred(value); }); }, 0); } ``` ### 引入状态 Hmm,好像存在一点问题:如果 Promise 异步操作已经成功,之后调用 `then` 注册的回调再也不会执行了,而这是不符合我们预期的。 解决这个问题,需要引入规范中所说的 States,即每个 Promise 存在三个互斥状态:pending、fulfilled、rejected,它们之间的关系是: <center> <img title="states flow" src="/images/promise-states-flow.png" /> </center> 经过改进后的代码: ```javascript function Promise(fn) { var state = 'pending', value = null, deferreds = []; this.then = function (onFulfilled) { if (state === 'pending') { deferreds.push(onFulfilled); return this; } onFulfilled(value); return this; }; function resolve(newValue) { value = newValue; state = 'fulfilled'; setTimeout(function () { deferreds.forEach(function (deferred) { deferred(value); }); }, 0); } fn(resolve); } ``` [JS Bin](http://jsbin.com/lamewijo/2/edit?js,console) `resolve` 执行时,会将状态设置为 fulfilled,在此之后调用 `then` 添加的新回调,都会立即执行。 似乎少了点什么,哦,是的,没有任何地方将 state 设为 rejected,这个问题稍后会聊,方便聚焦在核心代码上。 ### 串行 Promise 在这一小节,将要探索的是 Promise 的 Killer Feature:**串行 Promise**,这是最为有趣也最为神秘的一个功能。 串行 Promise 是指在当前 promise 达到 fulfilled 状态后,即开始进行下一个 promise(后邻 promise)。例如获取用户 id 后,再根据用户 id 获取用户手机号等其他信息,这样的场景比比皆是: ```javascript // 例4 getUserId() .then(getUserMobileById) .then(function (mobile) { // do sth with mobile }); function getUserMobileById(id) { return new Promise(function (resolve) { Y.io('/usermobile/' + id, { on: { success: function (i, o) { resolve(JSON.parse(o).mobile); } } }); }); } ``` [JS Bin](http://jsbin.com/pibicefe/2/edit?js,console) 这个 feature 实现的难点在于:如何衔接当前 promise 和后邻 promise。 首先对 `then` 方法进行改造: ```javascript this.then = function (onFulfilled) { return new Promise(function (resolve) { handle({ onFulfilled: onFulfilled || null, resolve: resolve }); }); }; function handle(deferred) { if (state === 'pending') { deferreds.push(deferred); return; } var ret = deferred.onFulfilled(value); deferred.resolve(ret); } ``` `then` 方法改变很多,这是一段暗藏玄机的代码: - `then` 方法中,创建了一个新的 Promise 实例,并作为返回值,这类 promise,权且称作 bridge promise。这是串行 Promise 的基础。另外,因为返回类型一致,之前的链式执行仍然被支持; - `handle` 方法是当前 promise 的内部方法。这一点很重要,看不懂的童鞋可以去补充下闭包的知识。`then` 方法传入的形参 `onFullfilled`,以及创建新 Promise 实例时传入的 `resolve` 均被压入当前 promise 的 `deferreds` 队列中。所谓“巧妇难为无米之炊”,而这,正是衔接当前 promise 与后邻 promise 的“米”之所在。 新增的 `handle` 方法,相比改造之前的 `then` 方法,仅增加了一行代码: ```javascript deferred.resolve(ret); ``` 这意味着当前 promise 异步操作成功后执行 `handle` 方法时,先执行 `onFulfilled` 方法,然后将其返回值作为实参执行 `resolve` 方法,而这标志着后邻 promise 异步操作成功,**接力**工作就这样完成啦! 以例 2 代码为例,串行 Promise 执行流如下: <center> <img title="promise series flow" src="/images/promise-series-simple-flow.png" /> </center> 这就是所谓的串行 Promise?当然不是,这些改造只是为了为最后的冲刺做铺垫,它们在重构底层实现的同时,兼容了本文之前讨论的所有功能。接下来,画龙点睛之笔--最后一个方法 `resolve` 是这样被改造的: ```javascript function resolve(newValue) { if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then; if (typeof then === 'function') { then.call(newValue, resolve); return; } } state = 'fulfilled'; value = newValue; setTimeout(function () { deferreds.forEach(function (deferred) { handle(deferred); }); }, 0); } ``` 啊哈,`resolve` 方法现在支持传入的参数是一个 Promise 实例了!以例 4 为例,执行步骤如下: 1. `getUserId` 生成的 promise (简称 `getUserId` promise)异步操作成功,执行其内部方法 `resolve`,传入的参数正是异步操作的结果 `userid`; 2. 调用 `handle` 方法处理 `deferreds` 队列中的回调:`getUserMobileById` 方法,生成新的 promise(简称 `getUserMobileById` promise); 3. 执行之前由 `getUserId` promise 的 `then` 方法生成的 bridge promise 的 `resolve` 方法,传入参数为 `getUserMobileById` promise。这种情况下,会将该 `resolve` 方法传入 `getUserMobileById` promise 的 `then` 方法中,并直接返回; 4. 在 `getUserMobileById` promise 异步操作成功时,执行其 `deferreds` 中的回调:`getUserId` bridge promise 的 `resolve` 方法; 5. 最后,执行 `getUserId` bridge promise 的后邻 promise 的 `deferreds` 中的回调 上述步骤实在有些复杂,主要原因是 bridge promise 的引入。不过正是得益于此,注册一个返回值也是 promise 的回调,从而实现异步操作串行的机制才得以实现。 一图胜千言,下图描述了例 4 的 Promise 执行流: <center> <img title="promise series flow" src="/images/promise-series-flow.png" /> </center> ### 失败处理 本节处理之前遗留的 rejected 状态问题。在异步操作失败时,标记其状态为 rejected,并执行注册的失败回调: ```javascript // 例5 function getUserId() { return new Promise(function (resolve, reject) { // 异步请求 Y.io('/userid/1', { on: { success: function (id, res) { var o = JSON.parse(res); if (o.status === 1) { resolve(o.id); } else { // 请求失败,返回错误信息 reject(o.errorMsg); } } } }); }); } getUserId().then(function (id) { // do sth with id }, function (error) { console.log(error); }); ``` [JS Bin](http://jsbin.com/padolebi/2/edit?js,console) 有了之前处理 fulfilled 状态的经验,支持错误处理变得很容易。毫无疑问的是,这将加倍 code base,在注册回调、处理状态变更上都要加入新的逻辑: ```javascript function Promise(fn) { var state = 'pending', value = null, deferreds = []; this.then = function (onFulfilled, onRejected) { return new Promise(function (resolve, reject) { handle({ onFulfilled: onFulfilled || null, onRejected: onRejected || null, resolve: resolve, reject: reject }); }); }; function handle(deferred) { if (state === 'pending') { deferreds.push(deferred); return; } var cb = state === 'fulfilled' ? deferred.onFulfilled : deferred.onRejected, ret; if (cb === null) { cb = state === 'fulfilled' ? deferred.resolve : deferred.reject; cb(value); return; } ret = cb(value); deferred.resolve(ret); } function resolve(newValue) { if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then; if (typeof then === 'function') { then.call(newValue, resolve, reject); return; } } state = 'fulfilled'; value = newValue; finale(); } function reject(reason) { state = 'rejected'; value = reason; finale(); } function finale() { setTimeout(function () { deferreds.forEach(function (deferred) { handle(deferred); }); }, 0); } fn(resolve, reject); } ``` 增加了新的 `reject` 方法,供异步操作失败时调用,同时抽出了 `resolve` 和 `reject` 共用的部分,形成 `finale` 方法。 **错误冒泡**是上述代码已经支持,且非常实用的一个特性。在 `handle` 中发现没有指定异步操作失败的回调时,会直接将 bridge promise 设为 rejected 状态,如此达成执行后续失败回调的效果。这有利于简化串行 Promise 的失败处理成本,因为一组异步操作往往会对应一个实际功能,失败处理方法通常是一致的: ```javascript // 例6 getUserId() .then(getUserMobileById) .then(function (mobile) { // do sth else with mobile }, function (error) { // getUserId或者getUerMobileById时出现的错误 console.log(error); }); ``` [JS Bin](http://jsbin.com/joqamiko/3/edit?js,console) ### 异常处理 如果在执行成功回调、失败回调时代码出错怎么办?对于这类异常,可以使用 `try-catch` 捕获错误,并将 bridge promise 设为 rejected 状态。`handle` 方法改造如下: ```javascript function handle(deferred) { if (state === 'pending') { deferreds.push(deferred); return; } var cb = state === 'fulfilled' ? deferred.onFulfilled : deferred.onRejected, ret; if (cb === null) { cb = state === 'fulfilled' ? deferred.resolve : deferred.reject; cb(value); return; } try { ret = cb(value); deferred.resolve(ret); } catch (e) { deferred.reject(e); } } ``` 如果在异步操作中,多次执行 `resolve` 或者 `reject` 会重复处理后续回调,可以通过内置一个标志位解决。 ## 总结 Promise 作为异步操作的一种 Monad,魔幻一般的 API 让人难以驾驭。本文从简单的基础实现起步,逐步添加内置状态、串行、失败处理/失败冒泡、异常处理等关键特性,最终达到类似由 <NAME> 所完成的一个[简单 Promise 实现](https://github.com/then/promise/blob/master/core.js)的效果。在让我本人更加深刻理解 Promise 魔力之源的同时,希望为各位更加熟练的使用这一实用工具带来一些帮助。 ## 预告 下一篇关于 Promise 的文章中,将重点关注高阶应用的一些场景,例如并行 Promise、基于 Promise 的异步操作流封装、语法糖等。敬请期待。 ## 参考 - [Introduction to Promises](https://www.promisejs.org/) - [JavaScript Promises ... In Wicked Detail](http://mattgreer.org/articles/promises-in-wicked-detail/) - [A Gentle Introduction to Monads in JavaScript](http://sean.voisen.org/blog/2013/10/intro-monads-maybe/) <file_sep>/blog/source/_posts/frontend-component-practice.md --- layout: post title: "前端组件化开发实践" date: 2015-06-29 11:07 comments: true status: publish author: <EMAIL> tags: [front-end, component, reduce, turbo] --- ### 前言 一位计算机前辈曾说过: Controlling complexity is the essence of computer programming. 随着前端开发复杂度的日益提升,组件化开发应运而生,并随着 FIS、React 等优秀框架的出现遍地开花。这一过程同样发生在美团,面临业务规模的快速发展和工程师团队的不断扩张,我们历经引入组件化解决资源整合问题、逐步增强组件功能促进开发效率、重新打造新一代组件化方案适应全栈开发和共享共建等阶段,努力“controlling complexity”。本文将介绍我们组件化开发的实践过程。 ### 组件化 1.0:资源重组 在美团早期,前端资源是按照页面或者类似业务页面集合的形式进行组织的。例如 order.js 对应订单相关页面的交互,account.css 对应账户相关页面的样式。这种方式在过去的较长一段时间内,持续支撑了整个项目的正常推进,功勋卓著。 <center><img src="/images/frontend-component-practice/legacy-flow.png" alt="legacy-flow" width="500"></center> 随着业务规模的增加和开发团队的扩张,这套机制逐渐显示出它的一些不足: 1. **资源冗余** 页面的逐渐增加,交互的逐渐复杂化,导致对应的 css 和 js 都有大幅度增长,进而出现为了依赖某个 js 中的一个函数,需要加载整个模块,或者为了使用某个 css 中的部分样式依赖整个 css,冗余资源较多 2. **对应关系不直观** 没有显而易见的对应规则,导致的一个问题是修改某个业务模块的 css 或者 js 时,几乎只能依靠 grep。靠人来维护页面模块 html、css 和 js 之间的依赖关系,容易犯错,常常出现内容已经删除但是 css 或 js 还存在的问题 3. **难于单元测试** 以页面为最小粒度进行资源整合,不同功能的业务模块相互影响,复杂度太高,自动化测试难以推进 2013 年开始,在调研了 FIS、BEM 等方案之后,结合美团开发框架的实际,我们初步实现了一套轻量级的组件化开发方案。主要的改进是: - 以页面功能组件为单位聚合前端资源 - 自动加载符合约定的 css、js 资源 - 将业务数据到渲染数据的转换过程独立出来 <center><img src="/images/frontend-component-practice/component-flow.png" alt="component-flow" width="500"></center> 举例来说,美团顶部的搜索框就被实现为一个组件。 <center><img src="/images/frontend-component-practice/smart-box.png" alt="smart-box" width="500"></center> <!--more--> 代码构成: ```bash www/component/smart-box/ ├── smart-box.js # 交互 ├── smart-box.php # 渲染数据生产、组件配置 ├── smart-box.scss # 样式 ├── smart-box.tpl # 内容 └── test ├── default.js # 自动化测试 └── default.php # 单测页面 ``` 调用组件变得十足简单: ```php echo View::useComponent('smart-box', [ 'keyword' => $keyword ]); ``` 对比之前,可以看到组件化的一些特点: 1. **按需加载** 只加载必要的前端资源 2. **对应关系非常清晰** 组件所需要的前端资源都在同一目录,职责明确且唯一,对应关系显著 3. **易于测试** 组件是具备独立展现和交互的最小单元,可利用 Phantom 等工具自动化测试 此外,由于前端资源集中进行调度,组件化也为高阶性能优化提供了空间。例如实现组件级别的 BigRender、通过数据分析进行资源的合并加载等等。 ### 组件化 2.0:趋于成熟 组件化 1.0 上线后,由于简单易用,很快得到工程师的认可,并开始在各项业务中应用起来。新的需求接踵而来,一直持续到 2014 年底,这个阶段我们称之为组件化 2.0。下面介绍下主要的几个改进。 #### Lifecycle 组件在高内聚的同时,往往需要暴露一些接口供外界调用,从而能够适应复杂的页面需求,例如提交订单页面需要在支付密码组件启动完成后绑定提交时的检查。Web Components、React 等都选择了生命周期事件/方法,我们也是一样。 组件的生命周期: <center><img src="/images/frontend-component-practice/component-lifecycle.png" alt="component-lifecycle" width="800"></center> 一个组件的完整生命周期包括: - init,初始化组件根节点和配置 - fetch,加载 css 和 js 资源 - render,内容渲染,默认的渲染内容方式是 BigRender - ready,进行数据绑定等操作 - update,数据更新 - destroy,解除所有事件监听,删除所有组件节点 组件提供 pause、resume 方法以方便进行生命周期控制。各个阶段使用 Promise 串行进行,异步的管理更清晰。使用自定义语义事件,在修改默认行为、组件间通信上充分利用了 YUI 强大的自定义事件体系,有效降低了开发维护成本。 举个例子,页面初始化时组件的启动过程实际也是借助生命周期实现的: ```js var afterLoadList = []; Y.all('[data-component]').each(function (node) { var component = new Y.mt.Component(node); // 绑定 init 生命周期事件,在 init 默认行为完成后执行回调 component.after('init', function (e) { // 如果配置了延迟启动 if (e.config.afterLoad) { // 暂停组件生命周期 e.component.pause(); // 压入延迟启动数组 afterLoadList.push(e.component); } }); // 开始进入生命周期 component.start(); }); Y.on('load', function () { // 在页面 load 事件发生时恢复组件生命周期 afterLoadList.forEach(function (component) { component.resume(); }); }); ``` 回过头来看,引入生命周期除了带来扩展性外,更重要的是理顺了组件的各个阶段,有助于更好的理解和运用。 #### Data Binding 数据绑定是我们期盼已久的功能,将 View 和 ViewModel 之间的交互自动化无疑会节省工程师的大量时间。在组件化减少关注点和降低复杂度后,实现数据绑定变得更加可能。 我们最终实现的数据绑定方案主要参考了 Angular,通过在 html 节点上添加特定的属性声明绑定逻辑,js 扫描这些内容并进行相应的渲染和事件绑定。当数据发生变化时,对应的内容全部重新渲染。 ```html <ul class="addressList"> <li mt-bind-repeat="addr in addrList" mt-bind-html="addr.text" > </li> </ul> <script> Y.use(['mt-bind', 'mt-scope'], function () { Y.mt.bind.init(document.body); var scope = Y.one('.addressList').getScope(); // 将 scope.addrList 设置为一个数组,DOM 上将自动渲染其内容 scope.$set('addrList', [ { text: "first address" }, { text: "second address" } ]); }); </script> ``` 使用属性声明绑定逻辑的好处是可以同时支持后端渲染,这对于美团团购这样的偏展现型业务是非常必要的,用户可以很快看到页面内容。 #### Flux 实现数据绑定后,我们不得不面对另外一个问题:如何协同多个组件间的数据。因为某个组件的数据变化,很有可能引起其他组件的变化。例如当修改购买数量,总金额会变化,而总金额超过 500 后,还需要展示大额消费提醒。 为了解决这个问题,我们引入了 Flux,使用全局消息总线的思路进行跨组件交互。 例如因为交互复杂而一直让我们非常头疼的项目购买页,在应用组件 + Flux 重构后,各模块之间的互动更加清晰: <center><img src="/images/frontend-component-practice/component-flux.png" alt="component-flux" width="600"></center> 其他方面的改进还有很多,包括引入模板引擎 LightnCandy 约束模板逻辑、支持组件任意嵌套、支持异步加载并自动初始化等。 随着组件化 2.0 的逐步完善,基本已经可以从容应对日常开发,在效率和质量方面都上了一个台阶。 ### 组件化 3.0:重启征程 时间的车轮滚滚前行,2014 年底,我们遇到一些新的机遇和挑战: - 基于 Node 的全栈开发模式开始应用,前后端渲染有了更多的可能性 - YUI 停止维护,需要一套新的资源管理方案 - 新业务不断增加,需要找到一种组件共享的方式,避免重复造轮子 结合之前的实践,以及在这一过程中逐渐积累的对业内方案的认知,我们提出了新的组件化方案: - 基于 React 开发页面组件,使用 NPM 进行分发,方便共建共享 - 基于 Browserify 二次开发,建设资源打包工具 Reduce,方便浏览器加载 - 建设适应组件化开发模式的工程化开发方案 Turbo,方便工程师将组件应用于业务开发中 #### React 在组件化 2.0 的过程中,我们发现很多功能和 React 重合,例如 Data Binding、Lifecycle、前后端渲染,甚至直接借鉴的 Flux。除此之外,React 的函数式编程思想、增量更新、兼容性良好的事件体系也让我们非常向往。借着前端全栈开发的契机,我们开始考虑基于 React 进行组件化 3.0 的建设。 #### NPM + Reduce NPM + Reduce 构成了我们新的资源管理方案,其中: - NPM 负责组件的发布和安装。可以认为是“分”的过程,粒度越小,重用的可能性越大 - Reduce 负责将页面资源进行打包。可以认为是“合”的过程,让浏览器更快地加载 一个典型的组件包: ```bash smart-box/ ├── package.json # 组件包元信息 ├── smart-box.jsx # React Component ├── smart-box.scss # 样式 └── test └── main.js # 测试 ``` NPM 默认只支持 js 文件的管理,我们对 NPM 中的 package.json 进行了扩展,增加了 style 字段,以使打包工具 Reduce 也能够对 css 和 css 中引用的 image、font 进行识别和处理: ```js { "style": "./smart-box.scss" } ``` 只要在页面中 require 了 smart-box,经过 Reduce 打包后,js、css 甚至图片、字体,都会出现在浏览器中。 ```js var SmartBox = require('@mtfe/smart-box'); // 页面 var IndexPage = React.createClass({ render: function () { return ( <Header> <SmartBox keyword={ this.props.keyword } /> </Header> ... ); } }); module.exports = IndexPage; ``` 整体思路和组件化 1.0 如出一辙,却又那么不同。 #### Turbo 单单解决分发和打包的问题还不够,业务开发过程如果变得繁琐、难以 Debug、性能低下的话,恐怕不会受到工程师欢迎。 为了解决这些问题,我们在 Node 框架的基础上,提供了一系列中间件和开发工具,逐步构建对组件友好的前端工程化方案 Turbo。主要有: - 支持前后端同构渲染,让用户更早看到内容 - 简化 Flux 流程,数据流更加清晰易维护 - 引入 ImmutableJS,保证 Store 以外的数据不可变 - 采用 cursor 机制,保证数据修改/获取同步 - 支持 Hot Module Replacement,改进开发流自动化 通过这些改进,一线工程师可以方便的使用各种组件,专注在业务本身上。开发框架层面的支持也反过来促进了组件化的发展,大家更乐于使用一系列组件来构建页面功能。 ### 小结 发现痛点、分析调研、应用改进的解决问题思路在组件化开发实践中不断运用。历经三个大版本的演进,组件化开发模式有效缓解了业务发展带来的复杂度提升的压力,并培养工程师具备小而美的工程思想,形成共建共享的良好氛围。毫无疑问,组件化这种“分而治之”的思想将会长久地影响和促进前端开发模式。我们现在已经准备好,迎接新的机遇和挑战,用技术的不断革新提升工程师的幸福感。 <file_sep>/share/bundler-pipeline/examples/webpack-plugin/dumpPlugin.js function DumpPlugin() { } DumpPlugin.prototype.apply = function(compiler) { // compiler.plugin('emit', function(compilation, callback) { // console.log('emit', compilation); // callback(); // // var changedFiles = Object.keys(compilation.fileTimestamps).filter(function(watchfile) { // // return (this.prevTimestamps[watchfile] || this.startTime) < (compilation.fileTimestamps[watchfile] || Infinity); // // }.bind(this)); // // this.prevTimestamps = compilation.fileTimestamps; // }.bind(this)); compiler.plugin("compilation", function(compilation) { compilation.plugin('normal-module-loader', function(loaderContext, module) { //this is where all the modules are loaded //one by one, no dependencies are created yet // console.log('===== normal-module-loader loaderContext:', Object.keys(loaderContext)); console.log('===== normal-module-loader module:', module.dependencies, module.id, module.index); }); }); }; module.exports = DumpPlugin; <file_sep>/blog/source/_posts/understanding-this-keyword.md --- layout: post title: "[译]理解Javascript关键字this" date: 2011-06-21 21:52 status: publish tags: [This] --- <div class="preface"> <p>在上一次原生javascript分享时,我发现自己对this的理解仍然不够准确。在翻看了很多现有的文章后,我很失望的发现基本全是在讲种种类型的场景下this是怎样怎样,我需要的不是这些,我想看到更深入的一些解释,例如this在函数中从何而来。后来,我准备自己查阅资料后总结一篇,就在准备资料的时候我欣喜的看到了下面这篇文章,当时的心情只能用相见恨晚来表达。我认为自己不会写出更好的文章,所以就勉强翻译过来给一些E文不太好的童鞋分享,E文好的童鞋请移步,原著更加准确生动些。</p> <p>原文链接:<a href="http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/" target="_blank">Understanding JavaScript’s this keyword</a></p> </div> `this`在Javascript中应用广泛,但对它的误解却比比皆是。 ## 你需要知道 每个运行环境\(execution context,简称环境\)都含有一个与之关联的ThisBinding常量,它们具有相同的生命周期。运行环境分为三类: ### 1. 全局环境 `this`指向全局对象,在浏览器中为`window`对象。 ```js alert(this); // window ``` <!-- more --> ### 2. 函数环境 至少有5种调用函数的方式,`this`的值取决于具体的调用方式。 #### a) 作为属性调用 `this`的值为将函数作为属性调用的基本对象\([baseValue](http://javascriptweblog.wordpress.com/2010/08/09/variables-vs-properties-in-javascript/)\) ```js var a = { b: function() { return this; } }; a.b(); // a a['b'](); // a var c = {}; c.d = a.b; c.d(); // c ``` #### b) 作为变量调用 `this`指向全局对象。 ```js var a = { b: function() { return this; } }; var foo = a.b; foo(); // window var a = { b: function() { var c = function() { return this; }; return c(); } }; a.b(); // window ``` 自执行函数\(self-invoking functions\)也是如此: ```js var a = { b: function() { return (function() { return this; })(); } }; a.b(); // window ``` #### c) 通过Function.prototype.call调用 `this`的值由`call`的第一个参数决定。 #### d) 通过Function.prototype.apply调用 `this`的值由`apply`的第一个参数决定。 ```js var a = { b: function() { return this; } }; var d = {}; a.b.apply(d); // d ``` #### e) 通过new作为构造器调用 `this`指向新生成的对象。 ```js var A = function() { this.toString = function() { return "I'm an A"; }; }; new A(); // "I'm an A" ``` ### 3. eval环境 `this`的值等于调用`eval`方法的执行环境中的`this`。 ```js alert(eval('this == window')); // true - (except firebug, see above) var a = { b: function() { eval('alert(this == a)'); } }; a.b(); // true ``` ## 你也许想知道 本节以ECMA 5 262为参考,对在函数环境下`this`获取值的过程做深入探究。 我们从ECMA中的`this`定义开始: > 关键字this等于当前执行环境中ThisBinding的值。 *ECMA 5, 11.1.1* ### ThisBinding是如何设定的呢? 每个函数都定义了一个内部方法\[\[Call\]\]\(ECMA 5, 13.2.1 [[Call]]\) ,用来将invocation values传给该函数的执行环境: > 当控制器进入函数对象F的函数代码(function code)的执行环境时,依据调用对象提供的参数thisValue和argumentsList,执行以下步骤: > > 1. 若函数代码 (function code) 为严格代码 (strict code),令ThisBinding等于thisValue > 2. 否则,若thisValue为null或undefined,令ThisBinding等于全局对象 > 3. 否则,若thisValue不是Object类型,令thisBinding等于ToObject(thisValue) > 4. 否则,令thisBinding等于thisValue > 5. ⋯⋯ > *ECMA 5, 10.4.3 Entering Function Code* 也就是说,`ThisBinding`在`thisValue`为基本类型时设定为其强制转化对象,或者当`thisValue`为`undefined`、`null`时,设定为全局对象\(运行于严格模式时除外,这种情况下`ThisBinding`等于`thisValue`\)。 ### 那thisValue从何而来? 这里我们需要回到之前提到的五种调用函数的方式: #### 1. 作为属性调用 #### 2. 作为变量调用 用ECMAScript的说法,这两种方式称为Function Calls,包含两个要素:MemberExpression和Arguments list。 > 1. 令ref为执行MemberExpression后得到的结果 > 2. 令func为GetValue(ref) > 6. 若Type(ref)是引用,则 > a) 若IsPropertyReference(ref)为true,令thisValue为GetBase(ref) > b) 否则,ref的基本对象是一个Environment Record,令thisValue为执行GetBase(ref)的具体方法ImplicitThisValue得到的结果 > 7. 否则,Type(ref)不是引用,则令thisValue为undefined > 8. 令this等于thisValue,argument values等于argList,调用func内部方法[[Call]],并将结果返回 > *ECMA 5, 11.2.3 Function Calls* 那么,从本质来讲,`thisValue`成为函数表达式的baseValue\(见上面第6步。译者注:baseValue为`GetBase`方法得到的结果\)。 当函数作为属性调用时,baseValue就是在点号\(或中括号\)前面的标识符。 ```js var foo = { bar: function() { // (Comments apply to example invocation only) // MemberExpression = foo.bar // thisValue = foo // ThisBinding = foo return this; } }; foo.bar(); // foo foo['bar'](); // foo ``` 对于作为变量调用的情况,`baseValue`则是变量对象\(VariableObject,即上面提到的Environment Record\),变量对象属于声明式Environment Record。ECMA 10.2.1.1讲解道,声明式Environment Record的ImplicitThisValue为`undefined`。 ```js var bar = function() { ... }; bar(); // thisValue is undefined ``` 重温上面提到过的10.4.3 Entering Function Code后,我们可以看到,除非在严格模式下,`thisValue`为`undefined`会使`ThisBinding`的值为全局对象。因此`this`在一个作为变量调用的函数中指向全局对象。 ```js var bar = function() { // (Comments apply to example invocation only) // MemberExpression = bar // thisValue = undefined // ThisBinding = global object (e.g. window) return this; }; bar(); // window ``` #### 3. 通过Function.prototype.apply调用 #### 4. 通过Function.prototype.use调用 \(规范参见15.3.4.3 Function.prototype.apply,15.3.4.4 Function.prototype.use\) 这两个小节描述了在`call`和`apply`调用函数时,函数中的`this`参数\(它的第一个参数\)的实际值是如何作为`thisValue`传递给10.4.3 Entering Function Code的。\(注意,这一点不同于ECMA 3,后者规定`thisArg`的值为基本类型时需要转换为对象类型,为`null`或`undefined`时需要转化为全局对象——但这些区别通常可以忽略,因为`thisArg`的值会在目标函数调用时进行相同的转换过程\(参见已讲过的10.4.3 Entering Function Code\)\) #### 5. 通过new作为构造器调用 > 当函数对象F的内部方法[[Construct]]被调用时,执行以下步骤: > 1. 令obj为新生成的原生ECMAScript对象 > 8. 令thisValue等于obj,args为传入[[Construct]]的参数列表,调用F内部方法[[Call]],并将结果保存为result > 10. 返回obj > *ECMA 5, 13.2.2 [[Construct]]* 显而易见,作为构造器调用函数会生成一个新的对象,它被赋给`thisValue`。这种方式与其它`this`的使用方式截然不同。 ## 释疑 ### 严格模式 在ECMAScript的严格模式下,`thisValue`不会强制转化为一个对象。`this`的值为`null`或`undefined`时不会转化为全局对象,并且基本类型的值不会转化为包装类型对象。 ### bind函数 `Function.prototype.bind`是ECMAScript 5新添加的一个方法,使用主流框架的开发者对它已经非常熟悉。基于`call`/`apply`,`bind`可以通过简单的语法预设执行环境中`thisValue`的值。这在事件响应函数中非常有用,例如一个监听按钮点击事件的函数,它的`ThisBinding`默认为`onclick`属性的`baseValue`,即按钮元素: ```js // Bad Example: fails because ThisBinding of handler will be button var sorter = function() { sort: function() { alert('sorting'); }, requestSorting: function() { this.sort(); } }; $('sortButton').onclick = sorter.requestSorting; // Good Example: sorter baked into ThisBinding of handler var sorter = function() { sort: function() { alert('sorting'); }, requestSorting: function() { this.sort(); } }; $('sortButton').onclick = sorter.requestSorting.bind(sorter); ``` ## 延伸阅读 [ECMA 262 5th Edition \(PDF\)](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf) - 11.1.1 Definition of this - 10.4.3 Entering Function Code - 11.2.3 Function Calls - 13.2.1 [[Call]] - 10.2.1.1 Declarative Environment Record \(ImplicitThisValue\) - 13.2.2 [[Construct]] - 15.3.4.3 Function.prototype.apply - 15.3.4.4 Function.prototype.call - 15.3.4.5 Function.prototype.bind - Annex C The Strict Mode of ECMAScript <file_sep>/blog/source/_posts/event-delegate.md --- layout: post title: "YUI事件体系之Y.delegate" date: 2013-04-05 23:23 status: publish tags: [Y.delegate, YUI] --- ![relay baton](/images/delegate.jpg) 在介绍了YUI自定义事件体系和对DOM事件的封装后,本篇文章重点阐述事件方面的一种常用技术——事件代理。事件代理(Event Delegation,又称事件委托)充分运用事件传播模型,用一种十分优雅的方式实现了批量节点事件监听。具体的原理和优点请移步zakas比较古老的一篇文章[Event delegation in JavaScript](http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/)。事件代理在YUI中的实现为`Y.delegate`。 ## 基本用法 为方便讨论,约定以下名称: - 代理节点:实际监听事件的节点。在事件传播到此节点时判断是否符合代理条件,符合则执行回调函数。 - 被代理节点:希望监听事件的节点。如果不采用事件代理,那么应该直接监听这些节点的事件。 - 目标节点:事件发生的目标节点,即`event.target`。 三者的层次关系从内到外依次为:目标节点 &lt;= 被代理节点 &lt;= 代理节点。 <!-- more --> 假设html为: ```html <ul> <li> <a href="http://google.com">google</a> </li> <li> <a name="facebook" href="http://facebook.com">facebook</a> </li> <li> <a name="twitter" href="http://twitter.com">twitter</a> </li> </ul> ``` 先来看下`Y.delegate`的简单用法: ```js // 例1 // API: Y.delegate(type, fn, el, filter) YUI().use('event-delegate', function(Y) { var handle = Y.delegate('click', function (e) { e.halt(); console.log(this.get('tagName') + ' is clicked'); }, 'ul', 'a'); Y.delegate('click', function (e) { console.log(this.get('tagName') + ' is clicked'); }, 'ul', 'li'); // click first anchor // output 'A is clicked' // output 'LI is clicked' handle.detach(); // click first anchor again // output 'LI is clicked' }); ``` 可以看出,回调函数中的this指向的是使用`Y.Node`包装的被代理节点。 YUI3新加入的`Y.Node`对象也封装了delegate,例1更常见的实现如下: ```js // 例2 // API: Y.Node.prototype.delegate(type, fn, filter) YUI().use('node-event-delegate', function(Y) { var ndList = Y.one('ul'), handle; handle = ndList.delegate('click', function (e) { e.halt(); console.log(this.get('tagName') + ' is clicked'); }, 'a'); ndList.delegate('click', function (e) { console.log(this.get('tagName') + ' is clicked'); }, 'li'); // click first anchor // output 'A is clicked' // output 'LI is clicked' handle.detach(); // click first anchor again // output 'LI is clicked' }); ``` 筛选条件除了例1中使用的selector外,还支持函数: ```js // 例3 YUI().use('node-event-delegate', function(Y) { var ndList = Y.one('ul'); ndList.delegate('click', function (e) { e.halt(); console.log(this.get('tagName') + ' is clicked'); }, function (nd, e) { return nd.get('name') && e.target.get('tagName').toLowerCase() === 'a'; }); // click the first anchor // no output // click the second anchor // output 'LI is clicked' }); ``` ## 源码分析 接下来,让我们看看YUI的内部实现吧。 注:为了更容易的看懂代码的核心,我做了适当的简化,感兴趣的朋友可以去看未删节的[源码](https://github.com/yui/yui3/blob/v3.9.1/src/event/js/delegate.js)。 ```js var toArray = Y.Array, isString = Y.Lang.isString; function delegate(type, fn, el, filter) { var container = isString(el) ? Y.Selector.query(el, null, true) : el, handle; // 监听代理节点的type事件 handle = Y.Event._attach([type, fn, container], { facade: false }); handle.sub.filter = filter; // 改写事件触发回调函数 handle.sub._notify = delegate.notifySub; return handle; } // 代理节点触发事件时的回调函数 delegate.notifySub = function (thisObj, args, ce) { // 计算符合filter的被代理节点集合 var currentTarget = delegate._applyFilter(this.filter, args, ce), e, i, len, ret; if (!currentTarget) return; currentTarget = toArray(currentTarget); // 生成事件对象 e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); // 将代理节点保存在事件对象container属性上,方便回调函数调用 e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { // 将被代理节点保存在事件对象currentTarget属性上 e.currentTarget = Y.one(currentTarget[i]); // 回调函数中的this指向被代理节点 ret = this.fn.apply(e.currentTarget, args); if (ret === false) break; } return ret; }; // 计算符合filter的被代理节点集合 delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, target = e.target || e.srcElement, match = [], isContainer = false; // 处理事件目标节点为文本节点的情况 if (target.nodeType === 3) { target = target.parentNode; } // filter是selector if (isString(filter)) { while (target) { isContainer = (target === container); // 测试target是否符合selector filter if (Y.Selector.test(target, filter, (isContainer ? null : container))) { match.push(target); } if (isContainer) break; target = target.parentNode; } // filter是function } else { // 将target节点作为function filter的第一个参数, // 第二个参数为事件对象 args.unshift(Y.one(target)); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // function filter中this指向target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) break; // 更新target target = target.parentNode; args[0] = Y.one(target); } // 恢复args对象 args[1] = e; args.shift(); } return match.length <= 1 ? match[0] : match; }; Y.delegate = Y.Event.delegate = delegate; ``` ## 进阶用法 ### 批量代理 `Y.delegate`支持同时代理多种类型的事件,调用方式有如下两种: - Y.delegate({ typeA: fnA, typeB: fnB }, el, filter) - Y.delegate([typeA, typeB], fn, el, filter) ```js // 例4 YUI().use('node-event-delegate', function(Y) { var ndList = Y.one('ul'); ndList.delegate({ click: function (e) { e.halt(); console.log(e.type); }, dblclick: function (e) { e.halt(); console.log(e.type); } }, 'li'); // double click the first anchor // output 'click' // output 'click' // output 'dblclick' ndList.delegate(['click', 'dblclick'], function (e) { e.halt(); console.log(e.type); }, 'li'); // double click the first anchor // output 'click' // output 'click' // output 'dblclick' }); ``` ### 修改回调函数this,传递数据 ```js // 例5 YUI().use('node-event-delegate', function(Y) { Y.one('ul').delegate('click', function (e, args) { e.halt(); console.log(this === document.body); console.log(args.data); }, 'li', document.body, { data: 'data' }); // click the first anchor // output 'true' // output 'data' }); ``` ### focus、blur事件的代理 在DOM规范中,诸如focus、blur、load、unload、resize等事件是不冒泡的,因为这类事件只限定在某个节点上触发。但focus和blur事件有些特殊,在表单交互方面十分常用,如果能够支持冒泡,那么通过事件代理可以减少很多监听事件的操作。滑稽的是,focusin、focusout两个类似的事件却支持冒泡。 令人欣喜的是,YUI通过定义新的DOM事件实现了focus、blur事件的代理,awesome! ```js // 例6 YUI().use('node-event-delegate', 'event-focus', function(Y) { Y.one('form').delegate({ focus: function (e) { // 清除错误提示 clearErr(this); }, blur: function (e) { // 如果内容为空,则提示错误信息 if (this.get('value') === '') showErr(this); } }, 'input'); function clearErr(nd) { var ndErr = nd.next('.error'); if (ndErr) ndErr.hide().setHTML(''); }; function showErr(nd) { var ndErr = nd.next('.error'); if (!ndErr) { ndErr = Y.Node.create('<span class="error"></span>'); nd.insert(ndErr, 'after'); } ndErr.show().setHTML('请输入内容'); }; }); ``` ## 示例代码 所有示例代码均在[GitHub](https://github.com/springuper/yuianalyser/tree/master/event)。 ## 参考 - [YUILibrary-UserGuides-Event Delegation](http://yuilibrary.com/yui/docs/event/#delegation) - [Event delegation in JavaScript](http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/) - [YUILibrary-delegate](https://github.com/yui/yui3/blob/v3.9.1/src/event/js/delegate.js) <file_sep>/share/node-async/demos/generator.js var fs = require('fs'); var path = require('path'); var co = require('co'); var thunkify = require('thunkify'); var readdir = thunkify(fs.readdir); var stat = thunkify(fs.stat); function findMaxSizeFile(dir) { return co(function* () { var files = yield readdir(dir); var stats = yield files.map(function (file) { return stat(path.join(dir, file)); }); var largest = stats .filter(function (stat) { return stat.isFile(); }) .reduce(function (prev, next) { if (prev.size > next.size) return prev; return next; }); return files[stats.indexOf(largest)]; }); } findMaxSizeFile('./') .then(function (file) { console.log('the max size file is', file); }) .catch(function (error) { console.log('error', error); }); <file_sep>/blog/source/_posts/react-context.md --- layout: post title: "基于 Context 做 React 状态管理" date: 2023-03-09 09:12 status: publish tags: [React, Context, useContextSelector] --- 请移步知乎“前端之美”专栏 [基于 Context 做 React 状态管理](https://zhuanlan.zhihu.com/p/607970423) 查看全文。 <file_sep>/blog/source/_posts/extend-and-augment.md --- layout: post title: "Y.extend与Y.augment" date: 2012-02-11 21:24 comments: true status: publish tags: [YUI, OOP, JavaScript] --- 很长一段时间内,我都没有搞懂YUI3 OOP模块中的`Y.extend`方法与`Y.augment`之间的区别,尽管它们的名称如此显著。现在有些时间,我相信分析源码是最好的解决方法。为了减少不必要的干扰,我简化了这两个方法,使它们仅处理类构造器。 ## Y.extend `Y.extend`方法应用的场景很简单,就是继承。我们知道,JavaScript有多种继承方式,例如原型继承、构造器继承、组合继承、寄生继承等等。YUI采取的为寄生组合继承(Parasitic combination inheritance)。 `Y.extend`的简化代码如下: ```javascript Y.extend = function (r, s) { var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; return r; }; Y.Object = function (o) { var F = function () {}; F.prototype = o; return new F(); } ``` 首先获取一个`__proto__`指向父类原型的空对象`rp`,然后将其作为子类原型,这样子类实例就可以沿原型链父类原型方法。然后设置子类的`superclass`属性为父类原型,使得子类构造器可以访问到父类。 <!-- more --> 示例: ```javascript function Programmer(name) { this.name = name; } Programmer.prototype.getName = function () { return this.name; }; function FrontEndProgrammer(name, gender) { // 调用父类构造器 FrontEndProgrammer.superclass.constructor.call(this, name); this.gender = gender; } FrontEndProgrammer.prototype.getGender = function () { return this.gender; }; // 建立类继承关系 Y.extend(FrontEndProgrammer, Programmer); ``` ## Y.augment OOP中,继承是一种主要方式,但还有另一种方式同样重要,即组合(Composition)。组合不同于继承的是,不会在类之间建立关系,只将提供类(类似父类)的属性、原型属性和方法添加在接受类(类似子类)中。`Y.augment`就是YUI中一种用来组合类的方法。 Y.augment的简化代码如下: ```javascript Y.augment = function (receiver, supplier, args) { var rProto = receiver.prototype, sProto = supplier.prototype, copy, property; args = args ? Y.Array(args) : []; copy = function (value, key) { if (!(key in rProto)) { if (Object.prototype.toString.call(value) === '[object Function]') { rProto[key] = function () { // 将方法赋给实例 this[key] = value; // 执行提供类构造器 supplier.apply(this, args); // 执行提供类方法 return value.apply(this, arguments); }; } else { rProto[key] = value; } } }; for (property in sProto) { copy.call(null, sProto[property], property); } return receiver; }; ``` 逻辑比较简单,将提供类原型属性处理后拷贝给接受类原型。如果拷贝的是一个方法,则使用一个代理方法,主要作用是执行一次提供类构造器,使接受类对象获得提供类构造器中添加的属性。 从代码中可以发现,`Y.augment`的第三个参数`args`是传递给提供类构造器的,问题在于`args`只能在执行`Y.augment`时指定,也就是说不能在创建接受类实例时指定。这是`Y.augment`与`Y.extend`非常重要的一个区别。 另外一个问题是,接受类实例在执行不同提供类原型方法时,提供类构造器会被多次执行,在提供类构造器中逻辑比较复杂时会引起显而易见的效率问题。这个问题是由于我简化代码的缘故,[YUI源码](http://yuilibrary.com/yui/docs/api/files/oop_js_oop.js.html#l31)中采用了一种方法隔离技术,能够在第一次调用提供类方法时才将所有提供类方法赋给接收类实例,并保证只执行一次提供类构造器。 示例: ```javascript function Code(language) { this.language = language; } Code.prototype.getLanguage = function () { return this.language; }; function FrontEndProgrammer(name, gender) { this.name = name; this.gender = gender; } FrontEndProgrammer.prototype.getName = function () { return this.name; }; FrontEndProgrammer.prototype.getGender = function () { return this.gender; }; // 组合类 Y.augment(FrontEndProgrammer, Code, 'JavaScript'); ``` ## Y.extend与Y.augment区别 `Y.extend`和`Y.augment`很好的体现了OOP两种主要方式:继承和组合。设计模式中提倡使用组合方式:Favor 'object composition' over 'class inheritance' ([Gang of Four](http://en.wikipedia.org/wiki/Design_Patterns) 1995:20)。 总结一下,`Y.extend和`Y.augment`有如下区别: - `Y.extend`改变原型链,可以通过`instanceof`操作符判定子类实例与父类关系 - `Y.extend`可以在创建子类实例时指定传递给父类的参数,`Y.augment`只能在组合类时设定 - `Y.augment`会将提供类原型方法赋给接受类实例 根据各自特点,可以发现,`Y.extend`更适合从属关系非常强的两个类,例如男人和人,男人的主体属性是人,附加一些胡须、喉结、力气之类的特征;`Y.augment`更适合提供类是接受类一个扩展的情况,例如程序员和工具书,工具书只是程序员用来参考的工具,而不是主要属性。 以下是YUI3中的一些实际使用例子: ```javascript // Y.Base作为YUI组件框架的核心,为继承它的子类提供了属性管理、事件、生命周期等方法。 Y.extend(Y.Anim, Y.Base); Y.extend(ScrollView, Y.Widget); Y.extend(ACListPlugin, Y.AutoCompleteList); Y.extend(CacheOffline, Y.Cache); Y.extend(Calendar, Y.CalendarBase); // EventTarget定义了一整套自定义事件、AOP的机制,通过Y.augment可以方便的赋给接受类这些方法。 Y.augment(Y.Node, Y.EventTarget); Y.augment(Y.DataSource.Local, Pollable); Y.augment(Lines, Y.Attribute); ``` ## 参考 - [YUI OOP API](http://yuilibrary.com/yui/docs/api/files/oop_js_oop.js.html) - [Inheritance Patterns in YUI 3](http://www.yuiblog.com/blog/2010/01/06/inheritance-patterns-in-yui-3/) - [More code reuse patterns in YUI3](http://www.yuiblog.com/blog/2010/01/07/more-code-reuse-patterns-in-yui3/) - [Design Patterns](http://en.wikipedia.org/wiki/Design_Patterns)
c60da858607755c9a5e10d5b07e38337f56c59aa
[ "HTML", "Markdown", "JavaScript", "TypeScript", "Go", "Shell" ]
62
Shell
springuper/springuper.github.io
a57e87a5e3675cea2ace3c34e4ebba8ad6cdaf7a
92db648c0af27c8338c9f5e7d7068b974eedd97a
refs/heads/main
<repo_name>bezoerb/postcss-discard<file_sep>/index.d.ts import {AtRule, Declaration, Parser, Plugin, Rule} from 'postcss'; type PatternItem = | ((node: Declaration | Rule | AtRule, value: string) => boolean) | RegExp | string; type Pattern = PatternItem | PatternItem[]; export interface Options { atrule?: Pattern; rule?: Pattern; decl?: Pattern; css?: Parameters<Parser>[0]; } declare const postcssDiscard: (options?: Options) => Plugin; export default postcssDiscard; <file_sep>/README.md # PostCSS Discard [![Build Status][ci-img]][ci] [PostCSS] plugin to discard rules by selector, RegExp, or @type. Also usable to generate a diff from two stylesheets [postcss]: https://github.com/postcss/postcss [ci-img]: https://github.com/bezoerb/postcss-discard/workflows/Tests/badge.svg [ci]: https://github.com/bezoerb/postcss-discard/actions?workflow=Tests ## Usage ```js const discard = require('postcss-discard'); postcss([discard(options)]); ``` See [PostCSS] docs for examples for your environment. #### Options | Name | Type | Description | | ------ | ------------------------------ | --------------------------------------------- | | atrule | `String`, `RegExp`, `Function` | Match atrule like `@font-face` | | rule | `String`, `RegExp`, `Function` | Match rule like `.big-background-image {...}` | | decl | `String`, `RegExp`, `Function` | Match declarations | | css | `String` | CSS String or path to file containing css | You can also pass a filter function for any of the supported types. The function is invoked with two arguments (node, value). - `node` The currently processed AST node generated by [`postcss`](http://api.postcss.org/). - `value` Current value. Return true if the element should be discarded. ## Examples ### Diffing stylesheets ```js postcss(discard({css: 'STYLES TO BE REMOVED'})).process('ORIGINAL CSS').css; ``` ### Discard by specifying rules ```css .bg { width: 100%; height: 100%; background-image: url('some/big/image.png'); } @font-face { font-family: 'My awesome font'; } @media print { ...; } ``` ```js postcss([ discard({ atrule: ['@font-face', /print/], }), ]); ``` ```css .bg { width: 100%; height: 100%; } ``` <file_sep>/index.test.js /* eslint-env jest */ /* eslint import/order:0 */ /* eslint promise/prefer-await-to-then:0 */ 'use strict'; const fs = require('fs'); const path = require('path'); const postcss = require('postcss'); const {stripIndents} = require('common-tags'); const plugin = require('.'); const styles = stripIndents` html,body { margin: 0; padding: 0; } @font-face { font-family: 'Glyphicons Halflings'; } .my.awesome.selector { width: 100%; background: url('/myImage.jpg'); } main h1 > p { font-size: 1.2rem; } @media only screen and (max-width: 768px) { .test { display: block; } main h1 > p { font-size: 1rem; } } @media only print { h1 { color: #000; } } @supports not (font-variation-settings: 'XHGT' 0.7) { .testa { display: block; } @media only screen and (max-width: 768px) { .testa { display: none; } } } `; function run(input, options, output = '') { return postcss([plugin(options)]) .process(input, {from: undefined}) .then(result => { expect(result.warnings()).toHaveLength(0); if (output) { expect(result.css).toEqual(output); } return result; }); } const read = (i, type) => { return fs.readFileSync( path.join(__dirname, `test/fixtures/${i}-${type}.css`), 'utf8' ); }; const testCss = (i, r = true) => { const all = read(i, 'all'); const critical = (r && read(i, 'critical')) || `test/fixtures/${i}-critical.css`; const diff = read(i, 'diff'); return run(all, {css: critical}, diff); }; it('removes css defined as string', () => { return Promise.all([1, 2, 3, 4, 5, 6, 7].map(i => testCss(i))); }); it('removes css defined as file', () => { return Promise.all([1, 2, 3, 4, 5, 6, 7].map(i => testCss(i, false))); }); it('returns unchanged css', () => { return run(styles, {}, styles); }); it('removes @supports atrule', () => { return run(styles, {atrule: ['@supports']}).then(({css}) => { expect(css).toMatch('@font-face'); expect(css).toMatch('font-family: \'Glyphicons Halflings\''); expect(css).toMatch('html'); expect(css).toMatch('.my.awesome.selector'); expect(css).toMatch('main h1 > p'); expect(css).toMatch('.test'); expect(css).toMatch('only print'); expect(css).not.toMatch('@supports'); expect(css).not.toMatch('.testa'); }); }); it('removes @font-face atrule', () => { return run(styles, {atrule: '@font-face'}).then(({css}) => { expect(css).not.toMatch('@font-face'); expect(css).not.toMatch('font-family: \'Glyphicons Halflings\''); expect(css).toMatch('html'); expect(css).toMatch('.my.awesome.selector'); expect(css).toMatch('main h1 > p'); expect(css).toMatch('.test'); expect(css).toMatch('only print'); }); }); it('works regular expressions', () => { return run(styles, {rule: /body/}).then(({css}) => { expect(css).not.toMatch('body'); expect(css).toMatch('html'); expect(css).toMatch('font-face'); expect(css).toMatch('.my.awesome.selector'); expect(css).toMatch('main h1 > p'); expect(css).toMatch('.test'); expect(css).toMatch('only print'); }); }); it('removes everything', () => { return run(styles, {decl: /.*/}).then(({css}) => { expect(css).not.toMatch('body'); expect(css).not.toMatch('html'); expect(css).not.toMatch('font-face'); expect(css).not.toMatch('.my.awesome.selector'); expect(css).not.toMatch('main h1 > p'); expect(css).not.toMatch('.test'); expect(css).not.toMatch('only print'); }); }); it('removes all rules', () => { return run( styles, {rule: /.*/}, stripIndents` @font-face { font-family: 'Glyphicons Halflings'; } ` ); }); it('removes media queries width max-width: 768px', () => { return run( styles, {atrule: /max-width: 768px/}, stripIndents` html,body { margin: 0; padding: 0; } @font-face { font-family: 'Glyphicons Halflings'; } .my.awesome.selector { width: 100%; background: url('/myImage.jpg'); } main h1 > p { font-size: 1.2rem; } @media only print { h1 { color: #000; } } @supports not (font-variation-settings: 'XHGT' 0.7) { .testa { display: block; } } ` ); }); it('removes declarations by filter function', () => { function filter(node, value) { expect(node).toHaveProperty('type', 'decl'); return node.prop === 'width' || value === 'url(\'/myImage.jpg\')'; } return run(styles, {decl: filter}).then(({css}) => { expect(css).toMatch('body'); expect(css).toMatch('html'); expect(css).toMatch('font-face'); expect(css).not.toMatch('.my.awesome.selector'); expect(css).toMatch('main h1 > p'); expect(css).toMatch('.test'); expect(css).toMatch('only print'); expect(css).toMatch('@supports not (font-variation-setting'); }); }); it('removes font-face && print', () => { return run(styles, {atrule: ['@font-face', /print/]}).then(({css}) => { expect(css).toMatch('body'); expect(css).toMatch('html'); expect(css).not.toMatch('font-face'); expect(css).not.toMatch('@media only print'); expect(css).not.toMatch('color: #000'); expect(css).not.toMatch('Glyphicons Halflings'); expect(css).toMatch('main h1 > p'); expect(css).toMatch('.test'); expect(css).toMatch('@supports not (font-variation-setting'); }); }); it('removes media queries width @custom-media', () => { const styles = stripIndents` @custom-media --small only screen and (min-width: 480px); @custom-media --medium only screen and (min-width: 768px); @media (--small) { .media-small { color: red; } } @media (--medium) { .media-medium { color: green; } } `; return run(styles, {atrule: /--medium/}).then(({css}) => { expect(css).toMatch('@custom-media --small'); expect(css).toMatch('@media (--small)'); expect(css).not.toMatch('@custom-media --medium'); expect(css).not.toMatch('@media (--medium)'); }); }); <file_sep>/CHANGELOG.md v0.2.0 / 2018-12-18 ================== * feature: discard styles from css string/file v0.1.0 / 2018-05-06 ================== * Initial commit # Change Log This project adheres to [Semantic Versioning](http://semver.org/).
11acd8010b0db20558c78daf804685c07beaddca
[ "Markdown", "TypeScript", "JavaScript" ]
4
TypeScript
bezoerb/postcss-discard
41864f53b083b162b6f057589fe9990a80511038
bc775f01bc8870ac7201c1796ebeb60c48c80c93
refs/heads/main
<file_sep>import json import googlemaps import pandas as pd from rest_framework.common.abstracts import PrinterBase, ReaderBase, ScraperBase from selenium import webdriver class Printer(PrinterBase): def dframe(self, this): print(this) print(f'cctv 의 type \n {type(this)} 이다.') print(f'cctv 의 column \n {this.columns} 이다.') print(f'cctv 의 상위 5개 행\n {type(this.head(1))} 이다.') print(f'cctv 의 null\n {this.isnull().sum()}개') class Reader(ReaderBase): def new_file(self, file) -> str: return file._context + file._fname def csv(self, file) -> object: return pd.read_csv(f'{self.new_file(file)}.csv', encoding='UTF-8', thousands=',') def xls(self, file, header, usecols) -> object: return pd.read_excel(f'{self.new_file(file)}.xls', header=header, usecols=usecols) def json(self, file) -> object: return json.load(open(f'{self.new_file(file)}.json', encoding='UTF-8')) def gmaps(self) -> object: return googlemaps.Client(key='AIzaSyAdsgtjzlmn8G1wM1wrMrSomONGj-3vt9A') class Scraper(ScraperBase): def driver(self) -> object: return webdriver.Chrome('C:/Users/bitcamp/chromedriver') <file_sep>from rest_framework.common.entity import fileDTO class Entity(fileDTO): pass <file_sep>import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") from services import CCTVService class CCTV_Api(object): @staticmethod def main(): while 1: service = CCTVService() menu = input('0-Exit, 1-read_csv 2-read_xls 3-read_json') if menu == '0': break elif menu == '1': service.csv({'context':'./data/', 'fname':'cctv_in_seoul'}) elif menu == '2': service.xls({'context':'./data/', 'fname':'pop_in_seoul'}) elif menu == '3': service.json({'context':'./data/', 'fname':'geo_simple'}) else: continue CCTV_Api.main() <file_sep>from rest_framework.common.services import Reader, Printer, Scraper import numpy as np import pandas as pd from selenium import webdriver from rest_framework.gas_station.entity import FileDTO from glob import glob import re ''' 문제 정의! 셀프 주유소는 정말 저렴할까? 4-1 Selenium 사용하기 4-2 서울시 구별 주유소 가격 정보 얻기 4-5. 구별 주유 가격에 대한 데이터의 정리 4-6 서울시 주유 가격 상하위 10개 주유소 지도에 표기하기 ''' class Service(object): def __init__(self): self.file = FileDTO() self.reader = Reader() self.printer = Printer() self.scraper = Scraper() def get_url(self): file = self.file reader = self.reader printer = self.printer scraper = self.scraper file.url = "https://www.opinet.co.kr/user/main/mainView.do" driver = scraper.driver() print(driver.get(file.url)) gu_list_raw = driver.find_element_by_xpath("""//*[@id="SIGUNGU_NM0"]""") gu_list = gu_list_raw.find_elements_by_tag_name("option") gu_names = [option.get_attribute("value") for option in gu_list] gu_names.remove('') print(gu_names) def gas_station_price_information(self): # print(glob('./data/지역_위치별*.xls')) file = self.file reader = self.reader printer = self.printer station_files = glob(('./data/지역_위치별*.xls')) # 한 번에 여러개 파일을 적용할 때는 glob() temp_raw = [] for i in station_files: t = pd.read_excel(i, header=2) # fname, context 사용하려면 각 파일마다 일일히 modeling 해줘야 함. temp_raw.append(t) station_raw = pd.concat(temp_raw) station_raw.info() # 여기서 부터 print로 확인 print('*'*100) print(station_raw.head(2)) print(station_raw.tail(2)) stations = pd.DataFrame({'Oil_store':station_raw['상호'], '주소':station_raw['주소'], '가격':station_raw['휘발유'], '셀프':station_raw['셀프여부'], '상표':station_raw['상표']}) print(stations.head()) stations['구'] = [i.split()[1] for i in stations['주소']] stations['구'].unique() print(stations['구'] == '서울특별시') # 에러 확인 stations[stations['구'] == '서울특별시'] = '성동구' stations['구'].unique() print(stations[stations['구'] == '특별시']) # 에러 확인 2 stations[stations['구'] == '특별시'] = '도봉구' stations['구'].unique() print(stations[stations['가격'] == '-']) # 가격 표시 안된곳 찾아내기 stations = stations[stations['가격'] != ['-']] print(stations[stations['가격'] == '성동구']) # 아예 숫자가 아닌 것들을 빼버리자 -> 정규식 re 사용 -> match()함수 p = re.compile('^[0-9]+$') temp_stations = [] for i in stations: if p.match(stations['가격'][i]): temp_stations.append(stations['가격'][i]) stations['가격'] = [float(i) for i in temp_stations['가격']] stations.reset_index(inplace=True) # inplace는 confirm의 의미. 되돌릴 수 없이 바꾸라는 의미 del stations['index'] printer.dframe(stations) print(stations.columns) print(stations.head(2)) print(stations.tail(2)) if __name__ =='__main__': s = Service() s.gas_station_price_information() # s.get_url()
810607fc00ca511cfc9f8b0ba98328a63614214f
[ "Python" ]
4
Python
yunnyisgood/project-docker
4a500fdd0584c86e33ff7c0280486aff2919c0b7
bcf4f0dca264b23232dbb139c3115659dbdf103b
refs/heads/master
<repo_name>broadinstitute/sharpener-common-to-rare-disease-gene-producer<file_sep>/python-flask-server/swagger_server/controllers/transformer.py from swagger_server.models.gene_info import GeneInfo from swagger_server.models.gene_info import GeneInfoIdentifiers from swagger_server.models.attribute import Attribute from swagger_server.models.transformer_info import TransformerInfo import json import biothings_client transformer_name = 'Common-to-rare disease genes' valid_controls = ['omim_disease_id'] control_names = {'omim_disease_id': 'OMIM disease ID'} default_control_values = {'omim_disease_id': 'MIM:222100'} default_control_types = {'omim_disease_id': 'string'} def get_control(controls, control): value = controls[control_names[control]] if control_names[control] in controls else default_control_values[control] if default_control_types[control] == 'double': return float(value) elif default_control_types[control] == 'Boolean': return bool(value) elif default_control_types[control] == 'int': return int(value) else: return value def entrez_gene_id(gene: GeneInfo): """ Return value of the entrez_gene_id attribute """ if (gene.identifiers is not None and gene.identifiers.entrez is not None): if (gene.identifiers.entrez.startswith('NCBIGene:')): return gene.identifiers.entrez[9:] else: return gene.identifiers.entrez return None def transform(query): controls = {control.name:control.value for control in query.controls} omim_disease_id = get_control(controls, 'omim_disease_id') if omim_disease_id.startswith('MIM:'): omim_disease_id = omim_disease_id[4:] #biothings client disease_client = biothings_client.get_client('disease', url='http://mydisease.info/v1') #disease -> symptoms try: symptoms_json = disease_client.querymany(omim_disease_id, scopes='mondo.xrefs.omim', fields='hpo', size = 10000) all_symptoms_dic = {} for sympton in symptoms_json[0]["hpo"]["phenotype_related_to_disease"]: if sympton["hpo_id"] == 'HP:0000006': continue all_symptoms_dic[sympton["hpo_id"]] = 1 all_symptoms = sorted (all_symptoms_dic.keys()) except: msg = "Failed to get symptomps for MIM id: '"+omim_disease_id+"'" return ({ "status": 404, "title": "Not Found", "detail": msg, "type": "about:blank" }, 404 ) #symptoms -> diseases diseases_json = disease_client.querymany(all_symptoms, scopes='hpo.phenotype_related_to_disease.hpo_id', fields='mondo', size = 10000) all_diseases_dic = {} for disease in diseases_json: try: if disease['mondo']['xrefs']['omim'] == omim_disease_id: continue all_diseases_dic[disease['mondo']['xrefs']['omim']] = 1 except: continue all_diseases = sorted (all_diseases_dic.keys()) #diseases -> genes genes_json = disease_client.querymany(all_diseases, scopes='mondo.xrefs.omim', fields='disgenet', size = 10000) all_genes_dic = {} for gene in genes_json: try: gene["query"] if type (gene["disgenet"]) is list: for disgenet in gene["disgenet"]: try: if type (disgenet["genes_related_to_disease"]): for gene_id in disgenet["genes_related_to_disease"]: try: all_genes_dic[gene_id["gene_id"]] = 1 except: continue else: all_genes_dic[disgenet["genes_related_to_disease"]["gene_id"]] = 1 except: continue else: if type (gene["disgenet"]["genes_related_to_disease"]) is list: for gene_id in gene["disgenet"]["genes_related_to_disease"]: try: all_genes_dic[gene_id["gene_id"]] = 1 except: continue else: all_genes_dic[gene["disgenet"]["genes_related_to_disease"]["gene_id"]] = 1 except: continue #output gene ids output_genes = sorted (all_genes_dic.keys()) genes = {} gene_list = [] for gene_id in output_genes: if gene_id not in genes: gene_entrez_id = "NCBIGene:%s" % gene_id gene = GeneInfo( gene_id = gene_entrez_id, identifiers = GeneInfoIdentifiers(entrez = gene_entrez_id), attributes=[Attribute( name = 'related to OMIM disease', value = 'MIM:' + omim_disease_id, source = transformer_name, url = 'https://www.omim.org/entry/' + omim_disease_id )] ) genes[entrez_gene_id(gene)] = gene gene_list.append(gene) return gene_list def transformer_info(): """ Return information for this expander """ global transformer_name, control_names with open("transformer_info.json",'r') as f: info = TransformerInfo.from_dict(json.loads(f.read())) transformer_name = info.name control_names = dict((name,parameter.name) for name, parameter in zip(valid_controls, info.parameters)) return info <file_sep>/README.md # sharpener-common-to-rare-disease-gene-producer Common-to-rare disease gene-list producer
b4d225c43f57fbac9b11dfefd0df2c3f46ab5815
[ "Markdown", "Python" ]
2
Python
broadinstitute/sharpener-common-to-rare-disease-gene-producer
38f60aa4bef767c478b8ef023d14eed73661552b
86efa3b9656314c22fafc66928a92499f4628560
refs/heads/master
<repo_name>MMidwinter/sql_challenge<file_sep>/sql-challenge-query.sql -- This is item 1, joining the employee table with the salary table using emp_no as a foriegn ID select employees.emp_no, employees.last_name, employees.first_name, employees.sex, salaries.salary from employees join salaries on salaries.emp_no = employees.emp_no; -- This is for item 2, using a like string and wild card parameters to find employees hired in 1986 select first_name, last_name, hire_date from employees where hire_date like '%1986%'; --This is for item 3, joining the dept_manager table to both the departments and employee tables select dept_manager.dept_no, departments.dept_name, dept_manager.emp_no, employees.first_name, employees.last_name from dept_manager join departments on departments.dept_no = dept_manager.dept_no join employees on employees.emp_no = dept_manager.emp_no; --This section is for item 4, joining the dept_emp table to the department and employee tables. There will be some duplicate entries -- As some employees work in multiple sections select dept_emp.emp_no, employees.last_name, employees.first_name, departments.dept_name from dept_emp join departments on departments.dept_no = dept_emp.dept_no join employees on employees.emp_no = dept_emp.emp_no; --This section is for item 5, where i did equal to hercules for the first name, and used a wildcard operator after B to find all --last names starting with B select first_name, last_name, sex from employees where first_name = 'Hercules' and last_name like 'B%'; --This section is for item 6, using the code from item 4 i added a where filter to only show individuals in the sales department select dept_emp.emp_no, employees.last_name, employees.first_name, departments.dept_name from dept_emp join departments on departments.dept_no = dept_emp.dept_no join employees on employees.emp_no = dept_emp.emp_no where departments.dept_name = 'Sales'; --this section is for item 7, same code as 6 but added a or statement to include development select dept_emp.emp_no, employees.last_name, employees.first_name, departments.dept_name from dept_emp join departments on departments.dept_no = dept_emp.dept_no join employees on employees.emp_no = dept_emp.emp_no where departments.dept_name = 'Sales' or departments.dept_name = 'Development'; --This section is for item 8, list in decending order is the frequency of last names select last_name, count(last_name) as Frequency from employees group by last_name order by count(last_name) desc; --Epilogue
e519d5be05d68de4d1eaff72285b6c9da0f6ed19
[ "SQL" ]
1
SQL
MMidwinter/sql_challenge
d8feb42412aecee870cc05db5189dccb4607d906
06f5768fecea1861a96d7c92a19acb953cdaf927
refs/heads/main
<file_sep>var lettersDict = {1:"first", 2:"second", 3:"third", 4:"fourth", 5:"fifth", 6:"sixth", 7:"seventh", 8:"eighth", 9:"ninth", 10:"tenth"}; var players = 4; var totalCards = 208; let suits = ['Hearts', 'Diamond', 'Club', 'Spades']; let values = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack', 'Queen', 'King', 'Ace', 'Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack', 'Queen', 'King', 'Ace', 'Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack', 'Queen', 'King', 'Ace', 'Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack', 'Queen', 'King', 'Ace']; var deck = []; //var card = []; var tileValues = []; var cardIdToFace = {}; var faceToNumber = {"Two":2, "Three":3, "Four":4, "Five":5, "Six":6, "Seven":7, "Eight":8, "Nine":9, "Ten":10, "Jack":11, "Queen":12, "King":13, "Ace":14} var carsPos = [0,0,0,0]; var carAccelerate = "accelerate"; var carTime = [1800, 750, 850, 1200]; var enableCardCounter = 104; var enableCard = 52; var playerName = []; class Card{ constructor(suit, value){ this.suit = suit; this.value = value; } } class Deck{ constructor(){ this.deck = []; } createDeck(suits, values){ for(let suit of suits){ for(let value of values){ this.deck.push(new Card(suit,value)); } } return this.deck; } shuffle(){ // for(let i = 0; i < 5; i++){ let counter = this.deck.length, temp, i; while(counter){ i = Math.floor(Math.random() * counter--); temp = this.deck[counter]; this.deck[counter] = this.deck[i]; this.deck[i] = temp; } // } return this.deck; } deal(){ var card = this.deck.pop(); return card; } } window.onload = function(){ var playModal = id("playModal"); var winModal = id("winModal"); playModal.style.display = "block"; winModal.style.display = "none"; //card deal { deck = new Deck(); deck.createDeck(suits, values); deck.shuffle(); var base = 52; var init = base; //assign images to card tiles for(let suit = 1; suit <= suits.length; suit++){ for(let i = 1; i <= values.length; i++){ qsa = (init+i).toString(); var card = this.deck.deal(); cardIdToFace[qsa] = card.value; //console.log(qsa); id(qsa).src = "Cards\\" + card.suit + card.value + ".png"; } init = init + base*2; } } id("start-btn").addEventListener("click", function(){ let validationFlag = true; //player Names for(let playerNameIndex = 1; playerNameIndex <= 4; playerNameIndex++){ var player = "player"+playerNameIndex.toString()+"Name"; playerName[playerNameIndex] = (id(player).value === "") ? "Player" + (playerNameIndex).toString() : id(player).value; if(playerName[playerNameIndex].length > 8){ alert("Characters allowed for player name is 8"); validationFlag = false; break; } id("player" + (playerNameIndex).toString()).innerHTML = playerName[playerNameIndex]; } if(validationFlag){ var entryIndex = 0; var entryInterval = setInterval(function(){ entryIndex++; driveAnimation(entryIndex); if(entryIndex == 10){ clearInterval(entryInterval); } },300); id("card52").classList.remove("noClick"); hideCards(); flipCards(); playModal.style.display = "none"; id("roadDiv").classList.remove("hidden"); id("platformDiv").classList.remove("hidden"); } }); id("restart-btn").addEventListener("click", function(){ window.location.reload(); }); } function driveAnimation(identifier){ var top = 2; id(lettersDict[identifier]).classList.remove("hidden1"); var className = "header_animation" + lettersDict[identifier] id(lettersDict[identifier]).classList.add(className); setTimeout(function(){ id(lettersDict[identifier]).style.left = (top*(identifier-1)).toString()+"%"; id(lettersDict[identifier]).style.top = "5%"; },2500); } //hide face cards function hideCards(){ let cardsPerPlayer = totalCards / players; var stringNumber = cardsPerPlayer; var stringName = "card"; for(let player = 1; player <= players; player++){ for(let cardNumber = 1; cardNumber <= cardsPerPlayer; cardNumber++){ stringNumber = stringNumber + 1; document.getElementById(stringName + stringNumber.toString()).style.visibility = "hidden"; } stringNumber = stringNumber + cardsPerPlayer; //console.log(stringNumber); } } //flip cards on click function flipCards(){ let cardsPerPlayer = totalCards / players; var stringNumber = 0; for(let player = 1; player <= players; player++){ for(let cardNumber = 1; cardNumber <= cardsPerPlayer; cardNumber++){ stringNumber = stringNumber + 1; addclickEventListener(stringNumber, (player*cardsPerPlayer*2)-cardNumber); } stringNumber = stringNumber + cardsPerPlayer; } } //reverse flip every card on finish-futureScope /* function reverseFlipCards(){ console.log("reverseFlipCards"); //flip all tiles together var tile1BackIndex = totalCards/players; var tile1FrontIndex = tile1BackIndex + 1; var tile2BackIndex = tile1BackIndex+(totalCards/2); var tile2FrontIndex = tile2BackIndex + 1; var tile3BackIndex = tile2BackIndex+(totalCards/2); var tile3FrontIndex = tile3BackIndex + 1; var tile4BackIndex = tile3BackIndex+(totalCards/2); var tile4FrontIndex = tile4BackIndex + 1; var tile1Timer; var tile2Timer; var tile3Timer; var tile4Timer; tile1Timer = setInterval(function(){ id(tile1BackIndex.toString()).classList.remove("is_flip"); id("card"+tile1BackIndex.toString()).style.display = "block"; id(tile1FrontIndex.toString()).classList.remove("is_reverseflip"); tile1BackIndex--; tile1FrontIndex++; console.log((tile1FrontIndex+"_"+tile1BackIndex)); //stop timer if((tile1FrontIndex - tile1BackIndex) === (totalCards/2)+1){ clearTimeout(tile1Timer) } },20); tile2Timer = setInterval(function(){ id(tile2BackIndex.toString()).classList.remove("is_flip"); id("card"+tile2BackIndex.toString()).style.display = "block"; id(tile2FrontIndex.toString()).classList.remove("is_reverseflip"); tile2BackIndex--; tile2FrontIndex++; console.log((tile2FrontIndex - tile2BackIndex)); //stop timer if((tile2FrontIndex - tile2BackIndex) === (totalCards/2)+1){ clearTimeout(tile2Timer) } },20); tile3Timer = setInterval(function(){ id(tile3BackIndex.toString()).classList.remove("is_flip"); id("card"+tile3BackIndex.toString()).style.display = "block"; id(tile3FrontIndex.toString()).classList.remove("is_reverseflip"); tile3BackIndex--; tile3FrontIndex++; console.log((tile3FrontIndex - tile3BackIndex)); //stop timer if((tile3FrontIndex - tile3BackIndex) === (totalCards/2)+1){ clearTimeout(tile3Timer) } },20); tile4Timer = setInterval(function(){ id(tile4BackIndex.toString()).classList.remove("is_flip"); id("card"+tile4BackIndex.toString()).style.display = "block"; id(tile4FrontIndex.toString()).classList.remove("is_reverseflip"); tile4BackIndex--; tile4FrontIndex++; console.log((tile4FrontIndex - tile4BackIndex)); //stop timer if((tile4FrontIndex - tile4BackIndex) === (totalCards/2)+1){ clearTimeout(tile4Timer) } },20); } */ //event listener on flip; function addclickEventListener(back, face){ var stringName = "card"; var backCard = stringName + back.toString(); var faceCard = stringName + (face+1).toString(); //console.log(backCard+'_'+faceCard); id(backCard).addEventListener("click", function(){ //console.log(backCard+'_'+faceCard); enableCards(); tileValues.push(faceToNumber[cardIdToFace[face+1]]); //console.log((face+1).toString()); id(backCard).classList.toggle("is_flip"); id(faceCard).classList.toggle("is_reverseflip"); setTimeout(function(){ id(backCard).style.display = "none"; id(faceCard).style.visibility = "visible"; if(back >= 313 && back <= 364){ validateAndMoveCar() clearTileValues(); } },500); }); } function enableCards(){ if((enableCard + (totalCards/2)) > totalCards*2){ enableCard = (enableCard + (totalCards/2) - 1) % (totalCards*2); } else{ enableCard = enableCard + (totalCards/2); } id("card"+enableCard.toString()).classList.remove("noClick"); } function validateAndMoveCar(){ var carsToMove = []; var sortedTileValues = Array.from(Array(tileValues.length).keys()) .sort((a, b) => tileValues[a] > tileValues[b] ? -1 : (tileValues[b] < tileValues[a]) | 0); carsToMove.push(sortedTileValues[0]); for(let index = 1; index < sortedTileValues.length; index++){ if(tileValues[sortedTileValues[index]] === tileValues[sortedTileValues[0]]){ carsToMove.push(sortedTileValues[index]); } else{ break; } } setTimeout(function(){ accelerateCars(carsToMove); },1100); } function accelerateCars(cars){ var winners = []; for(let carIndex = 0; carIndex < cars.length; carIndex++){ carsPos[cars[carIndex]]++; var carClass = carAccelerate + (cars[carIndex]+1).toString() + "Pos" + carsPos[cars[carIndex]].toString(); id("car"+ (cars[carIndex]+1).toString()).classList.add(carClass); setTimeout(function(){ id("car"+ (cars[carIndex]+1).toString()).style.left = (120*carsPos[cars[carIndex]]).toString()+"px"; }, carTime[cars[carIndex]]); if(carsPos[cars[carIndex]] === 10){ winners.push(cars[carIndex]); } } if(winners.length > 0){ setTimeout(function(){ for(let winnerIndex = 0; winnerIndex < winners.length; winnerIndex++){ console.log(winners[winnerIndex].toString()); id("winner"+(winners[winnerIndex]+1).toString()).classList.remove("hidden"); id("winner"+(winners[winnerIndex]+1).toString()+"Name").innerHTML = playerName[winners[winnerIndex]+1]; } winModal.style.display = "block"; }, 2000) } } function clearTileValues(){ tileValues = []; } //helper functions function id(value){ return document.getElementById(value); } <file_sep># card-racing-game Card Racing Game developed without using external libraries
fd1a54d82065727bcf39b56ada52ae8b18c142cf
[ "JavaScript", "Markdown" ]
2
JavaScript
nix-dev-tech/card-racing-game
95c718a7d70513d23dfc3c99115558914648e1be
f04a6a0b54617a00829e965245f10c1bd3df45ae
refs/heads/main
<repo_name>woojong94/html<file_sep>/css/퍼블리싱/과제2/js/script.js window.onload = function() { var swiper = new Swiper(".hot_item .mySwiper", { slidesPerView: 4, spaceBetween: 5, centeredSlides: true, pagination: { el: ".swiper-pagination", clickable: true, }, }); }
7a479cc33b99c3ad40e51820fb0375e702b95829
[ "JavaScript" ]
1
JavaScript
woojong94/html
3aabbc2e665ea7513689dd5f3380a1f2902d909a
4b4edbced4d210b9188295a7525f95a709bd9247
refs/heads/master
<repo_name>Ysavn/BaxterBuilder<file_sep>/GRC/prototype_scripts/BlockIdentifier_ServicePrototype.py #!/usr/bin/env python from std_msgs.msg import Float32MultiArray, String, Float32, MultiArrayDimension, Int32 from sensor_msgs.msg import Image import rospy import numpy as np from baxter_builder.srv import * from rospy.service import ServiceManager obj_found = False obj_color = 0 # 0 is red, 1 is green, 2 is blue xb = 0 yb = 0 zb = 1.0 def update_location(msg): xb = msg obj_color = 0 obj_found = True def get_obj_location(request): global xb global yb global zb global obj_found global obj_color zb = 0 obj_found = True if request.targetcolor == "red": xb = 1 yb = 1 while xb == 0 and yb == 0: rospy.sleep(1) return ObjectLocationResponse(xb, yb, zb, obj_found, obj_color) def main(): rospy.init_node('block_identifier') print("Node initialized!") image_sub = rospy.Subscriber('counter', Int32, update_location) # this is getting continuously called? rospy.sleep(1) rospy.Service("obj_location_service", ObjectLocation, get_obj_location) print("I have created the service") if rospy.is_shutdown(): block_location_srv.shutdown() ("I have shutdown the service") rospy.spin() if __name__ == '__main__': main() <file_sep>/GRC/archive/README.txt xacro --inorder `rospack find baxter_moveit_config`/config/baxter.srdf.xacro left_electric_gripper:=true right_electric_gripper:=true left_tip_name:=left_gripper right_tip_name:=right_gripper > config/baxter.srdf <file_sep>/GRC/README.txt Baxter the Builder <NAME>, <NAME>, <NAME>, <NAME> Necessary Package Dependencies: Baxter Moveit Configuration Baxter IKFast Left Arm Plugin, Baxter IKFast Right Arm Plugin Baxter Description OpenCV 2.4 Numpy baxter_builder service Steps to run our Baxter the Builder code: Reboot laptop Turn on Baxter Verify that laptop is connected via ethernet, and on BaxterRouter wifi Terminal 1: basic setup and system checks, joint trajectory action server cd ros_ws . baxter.sh rosrun baxter_tools enable_robot.py -e rostopic list rosrun baxter_tools camera_control.py -l #If left hand camera is not enabled, do the below. #rosrun baxter_tools camera_control.py -c right_hand_camera OR head_camera #rosrun baxter_tools camera_control.py -o left_hand_camera rosrun baxter_interface joint_trajectory_action_server.py Terminal 2: run moveit thru RViz . baxter.sh cd src/GRC roslaunch baxter_moveit_config baxter_grippers.launch Terminal 3: (optional for debugging) view left hand camera . baxter.sh cd src/GRC rosrun image_view image_view image:=/cameras/left_hand_camera/image Terminal 4: run the MoveLeftHandCamera node to set up the left arm in the correct position . baxter.sh cd src/GRC rosrun GRC MoveLeftHandCamera.py NOTE: Left-hand camera postion: [x, y, z] = [0.64, 0, 0.54] Terminal 5: run the RightArmReady script to move the right arm into the correct position . baxter.sh cd src/GRC rosrun GRC RightArmReady.py Terminal 6: run the TargetIdentifier script to start publishing target_color . baxter.sh cd src/GRC rosrun GRC TargetIdentifier.py Terminal 7: run the BlockIdentifier node to identify centroid locations of blocks . baxter.sh cd src/GRC rosrun GRC BlockIdentifier.py Terminal 8: run the PickPlace script to start looping through of movement . baxter.sh cd src/GRC rosrun GRC PickPlace.py Terminal x: (optional) Echo current position and orientation of the end-effector . baxter.sh rostopic echo /robot/limb/right/endpoint_state ALTERNATIVELY: Launch the project using BaxterTheBuilderSetup.launch and BaxterTheBuilderDemo.launch, found in prototype_scripts folder Troubleshooting Notes: If getting 'package GRC not found' error upon rosrun, enter source /home/csci5551/ros_ws/devel/setup.bash into command line and try again. <file_sep>/GRC/archive/Color_Identification/tmp_txt.py #!/usr/bin/env python import rospy from sensor_msgs.msg import Image import cv2, cv_bridge import numpy as np bridge = cv_bridge.CvBridge() def callback(msg): cv_img = bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8') hsv = cv2.cvtColor(cv_img, cv2.COLOR_BGR2HSV) lower_yellow = np.array([23, 41, 133]) upper_yellow = np.array([40, 150, 255]) mask = cv2.inRange(hsv, lower_yellow, upper_yellow) masked = cv2.bitwise_and(cv_img, cv_img, mask = mask) cv2.imshow('dst', mask) #cv2.waitKey(0) #cv2.destroyAllWindows() rospy.init_node('read_target_text') sub = rospy.Subscriber('/cameras/left_hand_camera/image', Image, callback) rospy.spin() <file_sep>/GRC/archive/TargetIdentification/Baxter/textIdentify.py import numpy as np import subprocess import pytesseract import cv2 as cv from matplotlib import pyplot as plt img = cv.imread('input7.jpg') gf_img = cv.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) cv.imwrite('sampleTargetFiltered.jpg', gf_img) pass_arg = [] pass_arg.append("./whiteboardClean.sh") pass_arg.append("sampleTargetFiltered.jpg") pass_arg.append("cleanedTarget.jpg") subprocess.check_call(pass_arg) pass_arg2 = [] pass_arg2.append("./textclean.sh") subprocess.check_call(pass_arg2) cln_img = cv.imread('output.jpg') cv.imwrite('output2.jpg', cln_img) cln_img = cv.imread('output2.jpg') conf = ('-l eng --oem 3 --psm 11') text = pytesseract.image_to_string(cln_img, config=conf) print(text) plt.subplot(121), plt.imshow(img) plt.subplot(122), plt.imshow(cln_img) plt.show() <file_sep>/GRC/archive/Basics/listener.py #!/usr/bin/env python import rospy from std_msgs.msg import Int32 def callback(msg): Intg = Int32() Intg.data = msg.data * 2 pub.publish(Intg) rospy.init_node('Listener_Publisher') sub = rospy.Subscriber('counter', Int32, callback) pub = rospy.Publisher('multiply_counter', Int32) rospy.spin() <file_sep>/GRC/archive/TestClient.py #!/usr/bin/env python import sys, rospy, tf, actionlib, moveit_commander from control_msgs.msg import (GripperCommandAction, GripperCommandGoal) from std_msgs.msg import Float32MultiArray, MultiArrayDimension import moveit_msgs.msg, geometry_msgs.msg import baxter_interface from geometry_msgs.msg import Pose, Point, Quaternion #Initiate all_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ rospy.init_node('pick_and_place', anonymous=True) print("Initializing...") #Enable Baxter #print("Enabling Baxter...") #baxter_interface.RobotEnable().enable() #rospy.sleep(1.) #print("Baxter enabled successfully.") print("Initiating service clients...") print("Waiting for block_location_service...") rospy.wait_for_service("object_location_service") global blockLocationService blockLocationService = rospy.ServiceProxy("object_location_service", ObjLocation) #global targetLocationService #print("Waiting for target_location_service...") #rospy.wait_for_service("target_location_service") #targetLocationService = rospy.ServiceProxy("target_location_service", #[message type]) #moveit_commander.roscpp_initialize(sys.argv) #global robot #robot = moveit_commander.RobotCommander() #global scene #scene = moveit_commander.PlanningSceneInterface() print("Clients initiated.") while not rospy.is_shutdown(): blockLoc = blockLocationService.call(ObjLocationRequest()) print("Original: " + blockLoc) editedBlockLoc = blockLocationService.call(ObjLocationRequest()) print("Edited: x = " + editedBlockLoc.xb + " y = " + editedBlockLoc.yb) finalBlockLoc = [editedBlockLoc.xb, editedBlockLoc.yb, -0.25] print("Final xyz: " + finalBlockLoc) rospy.sleep(2) <file_sep>/GRC/archive/testing-hsv-colors.py #!/usr/bin/env python # testing out hsv colors import cv2, cv_bridge from std_msgs.msg import Float32MultiArray, String, Float32, MultiArrayDimension from sensor_msgs.msg import Image import rospy, cv2, cv_bridge, numpy as np import imutils bridge = cv_bridge.CvBridge() def image_callback(msg): #Pulls image messages, converts them to OpenCV messages in HSV color space image = bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8') # blurred = cv2.GaussianBlur(image, (5, 5), 0) # blur to reduce noise # kernel = np.ones((5,5),np.uint8) # closing = cv2.morphologyEx(blurred, cv2.MORPH_CLOSE, kernel) #dilate then erode hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) lower_red_0 = np.array([0, 100, 100]) # red needs two separate ranges since it wraps around 0 upper_red_0 = np.array([15, 255, 255]) lower_red_1 = np.array([180 -15, 100, 100]) upper_red_1 = np.array([180, 255, 255]) lower_yellow = np.array([23, 41, 133]) upper_yellow = np.array([40, 150, 255]) mask_0 = cv2.inRange(hsv, lower_red_0 , upper_red_0) mask_1 = cv2.inRange(hsv, lower_red_1 , upper_red_1 ) mask_red = cv2.bitwise_or(mask_0, mask_1) mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow) mask = mask_yellow masked = cv2.bitwise_and(image, image, mask = mask) # cv2.namedWindow('image', cv2.WINDOW_NORMAL) # cv2.resizeWindow('image', 600, 600) cv2.imshow('image', mask_yellow) cv2.waitKey(0) cv2.destroyAllWindows() rospy.init_node('testing_hsv') image_sub = rospy.Subscriber('/cameras/left_hand_camera/image', Image,image_callback) rospy.spin() <file_sep>/GRC/archive/PickPlaceHardcoded.py #!/usr/bin/env python #THIS IS THE FUNCTIONAL VERSION, DO NOT CHANGE #Make sure both services are global #Make sure to index the locations received from the service and make sure they have the correct z coordinate #Make sure there are rospy.sleep after each hand command #Add a waypoint to keep arm from knocking block after placing it import sys, rospy, tf, actionlib, moveit_commander from control_msgs.msg import (GripperCommandAction, GripperCommandGoal) from std_msgs.msg import Float32MultiArray, MultiArrayDimension import moveit_msgs.msg, geometry_msgs.msg import baxter_interface from geometry_msgs.msg import Pose, Point, Quaternion print("Testing - is this thing on?") #Initiate all_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ rospy.init_node('pick_and_place', anonymous=True) print("Initializing...") sys.argv.append("joint_states:=/robot/joint_states") #Enable Baxter #print("Enabling Baxter...") #baxter_interface.RobotEnable().enable() #rospy.sleep(1.) #print("Baxter enabled successfully.") #print("Initiating service clients...") #global blockLocationService #blockLocationService = rospy.ServiceProxy("block_location_service", #[message type]) #global targetLocationService #targetLocationService = rospy.ServiceProxy("target_location_service", #[message type]) #print("Waiting for target_location_service...") #rospy.wait_for_service("target_location_service") #targetLoc = targetLocationService() targetLoc = [0.4, -0.2, -0.245] print("Target selected.") targetCol = 0 # red, need to set through service call #blockResponse = blockLocationService.call(ObjLocationRequest()) #if blockResponse.objfound == True: #blockLoc = [blockResponse.xb, blockResponse.yb, -0.25] #blockCol = blockResponse.objcolor blockLoc = [0.5, 0.2, -0.245] print("Block selected.") moveit_commander.roscpp_initialize(sys.argv) global robot robot = moveit_commander.RobotCommander() global scene scene = moveit_commander.PlanningSceneInterface() print("Clients initiated.") #instantiate a MoveGroupCommander object for the arm and a Gripper object for the hand #Tolerance setting recommended by multiple sites; appropriate value taken from Northwestern group print("Initiating Baxter's arm and hand...") global arm arm = moveit_commander.MoveGroupCommander("right_arm") arm.set_goal_position_tolerance(0.01) arm.set_goal_orientation_tolerance(0.01) global hand hand = baxter_interface.Gripper("right") hand.calibrate() print("Arm and hand ready.") print("Initialized.") #Move to ready_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ orient = Quaternion(0, 1, 0, 0) ready = Pose(Point(0.55, -0.55, -0.05), orient) arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() print("Ready to begin.") rospy.sleep(2) #Loop through pick-and-place_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ while not rospy.is_shutdown(): #print("Waiting for block_location_service...") #rospy.wait_for_service("block_location_service") #Move to block__________________________________________________________________ blockReady = Pose(Point(blockLoc[0], blockLoc[1], -0.05), orient) arm.set_start_state_to_current_state() arm.set_pose_target(blockReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Grip block____________________________________________________________________ hand.open() rospy.sleep(1) blockGrip = Pose(Point(blockLoc[0], blockLoc[1], -0.245), orient) arm.set_start_state_to_current_state() arm.set_pose_target(blockGrip) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() hand.close() rospy.sleep(1) #Move back up___________________________________________________________________ arm.set_start_state_to_current_state() arm.set_pose_target(blockReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Move to target_________________________________________________________________ targetReady = Pose(Point(targetLoc[0], targetLoc[1], -0.05), orient) arm.set_start_state_to_current_state() arm.set_pose_target(targetReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Place block____________________________________________________________________ targetPlace = Pose(Point(targetLoc[0], targetLoc[1], -0.245), orient) arm.set_start_state_to_current_state() arm.set_pose_target(targetPlace) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() hand.open() rospy.sleep(1) #Move back up___________________________________________________________________ arm.set_start_state_to_current_state() arm.set_pose_target(targetReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Move back to ready_____________________________________________________________ arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() <file_sep>/GRC/archive/Basics/GRC.py #!/usr/bin/env python import rospy from std_msgs.msg import String rospy.init_node('GRC') pub = rospy.Publisher('targetText', String, queue_size = 10) rate = rospy.Rate(2) count = 0 while not rospy.is_shutdown(): pub.publish("Avneet") count += 1 rate.sleep() <file_sep>/GRC/scripts/BlockIdentifier.py #!/usr/bin/env python # Updated Dec 13, 2019 # node block_identifier # subscribes to '/cameras/left_hand_camera/image' topic # subscribes to 'target_color' topic # returns a ObjLocation for the PickPlace to read # Colors possible to detect: red, green, blue # import cv2, cv_bridge from std_msgs.msg import Float32MultiArray, String, Float32, MultiArrayDimension from sensor_msgs.msg import Image import rospy, cv2, cv_bridge, numpy as np from shapedetector import ShapeDetector import imutils from baxter_builder.srv import * # calculated the values for colors using opencv_color_selector lower_red_1 = np.array([0, 136, 26]) upper_red_1 = np.array([13, 255, 77]) lower_blue = np.array([101,23,15]) upper_blue = np.array([179,136,42]) lower_green = np.array([50,23,9]) upper_green = np.array([90,116,56]) # service inspired by Northwestern's ObjLocation service obj_found = False obj_color = 0 # 0 is red, 1 is green, 2 is blue xb = 0 #0.5 yb = 0 #0.2 zb = -0.25 ccx = 0.127*(1.35)/(495-430) # Camera calibration factor X axis ccy = 0.127*(1.35*0.8)/(197-139) # Camera calibration factor Y axis pose_x = 0.64 pose_y = 0 # image is 640x400 pixels row = 62 height = 264 column = 512 width = 64 kernel = np.ones((3, 3), np.uint8) target_color_msg = "" def set_color(msg): global target_color_msg if msg.data == "RED" or msg.data == "GREEN" or msg.data == "BLUE": #print("I am in set color for block identifier") target_color_msg = msg.data #print(target_color_msg) def image_callback(msg): global xb, yb, obj_color, obj_found bridge = cv_bridge.CvBridge() #Pulls image messages, converts them to OpenCV messages in HSV color space image = bridge.imgmsg_to_cv2(msg) image = cv2.GaussianBlur(image, (5, 5), 0) # blur to reduce noise kernel = np.ones((3,3),np.uint8) image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) #erode then dilate image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel) #dilate then erode hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) cv2.imwrite("hsv_BlockIdentifier.jpg", hsv) # saves the image lower = np.array([0, 136, 26]) upper = np.array([13, 255, 77]) # set the color based off of target_color if target_color_msg == "RED": print("I have been changed to red in BlockIdentifier") obj_color = 0 lower = lower_red_1 upper = upper_red_1 elif target_color_msg == "GREEN": print("I have been changed to red in BlockIdentifier") obj_color = 1 lower = lower_green upper = upper_green elif target_color_msg == "BLUE": print("I have been changed to blue in BlockIdentifier") obj_color = 2 lower = lower_blue upper = upper_blue mask = 0 # search for objects in designated ROI mask = cv2.inRange(hsv, lower , upper) mask = mask[row:row+height,column:column+width] # only consider the ROI mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) #erode then dilate mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) #dilate then erode cv2.imwrite("mask_BlockIdentifier.jpg", mask) # saves the image # sd = ShapeDetector() #TODO: can comment this out if slowing it down cnts_temp = cv2.findContours(mask.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts_temp) # cnts = [c for c in cnts_temp if sd.detect(c) == "square"] # filter out the contours so that they only detect squares cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:1] # get largest contour num_obj = len(cnts) if num_obj > 0: for c in cnts: M = cv2.moments(c) if M['m00'] > 0: cx_int = int(M['m10']/M['m00']) cy_int = int(M['m01']/M['m00']) else: cx_int = 0 cy_int = 0 cx_int += column cy_int += row print("This is cx: ") print(cx_int) print("This is cy: ") print(cy_int) xb = ((-cy_int + 200) * ccy) + pose_x yb = ((-cx_int + 320) * ccx) + pose_y print("This is xb: ") print(xb) print("This is yb: ") print(yb) cv2.circle(image, (cx_int, cy_int), 5, (255, 255, 255), -1) cv2.putText(image, "centroid", (cx_int - 25, cy_int - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.imwrite("centroid_of_BlockIdentifier.jpg", image) obj_found = True def get_obj_location(request): global xb, yb, obj_color, obj_found # TODO: might have to change this condition so that it eventually returns a response while xb == 0 and yb == 0: rospy.sleep(1) print("I am about to respond to the service in block identifier") return ObjLocationResponse(xb, yb, zb, obj_found, obj_color) # ROS has generated three classes: ObjLocation, ObjLocationRequest, ObjLocationResponse def main(): print("Let's go!") rospy.init_node('block_identifier') print("initialized node") target_color_sub = rospy.Subscriber('target_color', String, set_color) image_sub = rospy.Subscriber('/cameras/left_hand_camera/image', Image, image_callback) block_location_srv = rospy.Service("block_location_service", ObjLocation, get_obj_location) print("I have started the service") if rospy.is_shutdown(): block_location_srv.shutdown() ("I have shutdown the service") rospy.spin() if __name__ == '__main__': main() <file_sep>/README.md # Baxter the Builder CSCI 5551 Final Project Group members: <NAME>, <NAME>, <NAME>, <NAME> <file_sep>/GRC/archive/TestBasicMovement.py #!/usr/bin/env python import sys, rospy, tf, actionlib, moveit_commander from control_msgs.msg import (GripperCommandAction, GripperCommandGoal) from std_msgs.msg import Float32MultiArray, MultiArrayDimension import moveit_msgs.msg, geometry_msgs.msg import baxter_interface from geometry_msgs.msg import Pose, Point, Quaternion rospy.init_node('move_right_arm', anonymous=True) print("Initializing...") print("Initiating service clients...") sys.argv.append("joint_states:=/robot/joint_states") moveit_commander.roscpp_initialize(sys.argv) global robot robot = moveit_commander.RobotCommander() global scene scene = moveit_commander.PlanningSceneInterface() print("Clients initiated.") print("Initiating Baxter's arm...") global arm arm = moveit_commander.MoveGroupCommander("right_arm") arm.set_goal_position_tolerance(0.01) arm.set_goal_orientation_tolerance(0.01) print("Arm ready.") print("Initialized.") #Ready ready = Pose(Point(0.55, -0.55, -0.05), Quaternion(0, 1, 0, 0)) arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() print("Ready to begin.") rospy.sleep(2) blockLoc = [0.5, 0.2, -0.245] targetLoc = [0.4, -0.2, -0.245] #Position 1 ready = Pose(Point(blockLoc[0], blockLoc[1], -0.05), Quaternion(0, 1, 0, 0)) arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() rospy.sleep(2) #Position 2 ready = Pose(Point(targetLoc[0], targetLoc[1], -0.05), Quaternion(0, 1, 0, 0)) arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() rospy.sleep(2) <file_sep>/GRC/prototype_scripts/PickPlace_ServicePrototype.py #!/usr/bin/env python import sys, rospy, tf, actionlib from std_msgs.msg import Float32MultiArray, MultiArrayDimension import baxter_interface from baxter_builder.srv import * # imports all, ObjectLocation, ObjectLocationRequest, ObjectLocationResponse xb = 0.0 yb = 0.0 zb = 0.0 objfound = False objcolor = 0 #Initiate all_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ rospy.init_node('pick_and_place') print("Initiating service clients...") rospy.wait_for_service('obj_location_service') blockLocationService = rospy.ServiceProxy("obj_location_service", ObjectLocation) # creates a local proxy for simple use print("created service proxy") # could change this to a for loop while not rospy.is_shutdown(): try: print("I am in the try") request = ObjectLocationRequest("red") print("request created") rospy.wait_for_service('obj_location_service') print("finished waiting for service") blockResponse = blockLocationService.call(request) print("called the service successfully") if blockResponse.objfound == True: print("Block selected.") ros.sleep(5) except: print("Service call failed") #blockResponse = blockLocationService() #print(type(blockResponse)) #request = WordCountRequest('one two three', 3) #count,ignored = word_counter(request) print("Done.") rospy.spin() #Loop through pick-and-place_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ #while not rospy.is_shutdown(): #print("Waiting for target_location_service...") #rospy.wait_for_service("target_location_service") #targetLoc = targetLocationService() # print("Waiting for block_location_service...") # rospy.wait_for_service("block_location_service_2") # blockResponse = blockLocationService.call(ObjLocationRequest()) #blockResponse = blockLocationService() # call this like a local function # if blockResponse.objfound == True: # blockLoc = [blockResponse.xb, blockResponse.yb, -0.25] # blockCol = blockResponse.objcolor # print("Block selected.") # rospy.spin() <file_sep>/GRC/scripts/TargetIdentifier.py #!/usr/bin/env python #subscribes to left hand camera # publishes to 'target_color' topic import rospy from sensor_msgs.msg import Image import cv2 as cv, cv_bridge import numpy as np import subprocess import pytesseract from matplotlib import pyplot as plt from std_msgs.msg import String #crop dimensions row = 140 height = 150 column = 200 width = 300 bridge = cv_bridge.CvBridge() def callback(msg): #read the rgb image img = bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8') #crop the image to region containing the text img = img[row:row+height, column:column+width] #denoise filter gf_img = cv.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) #save denoised image cv.imwrite('sampleTargetFiltered.png', gf_img) #runs the whiteboardClean script taking denoised image as input pass_arg = [] pass_arg.append("./whiteboardClean.sh") pass_arg.append("sampleTargetFiltered.png") pass_arg.append("cleanedTarget.png") subprocess.check_call(pass_arg) #pass the output cleanedTarget.png from whiteboardClean script to textclean by ImageMagick further clean the text pass_arg2 = [] pass_arg2.append("./textclean.sh") subprocess.check_call(pass_arg2) cln_img = cv.imread('output.png') #configuration for usage of tesseract library #-l => language, -oem 3 => default trained engine, --psm 11 => look for sparse text conf = ('-l eng --oem 3 --psm 11') text = pytesseract.image_to_string(cln_img, config=conf) #publish the identified text otherwise try again while text!='' and not rospy.is_shutdown(): pub.publish(text) #cv.imshow('dst', cln_img) #cv.waitKey(0) #cv2.destroyAllWindows() rospy.init_node('my_camera_read') pub = rospy.Publisher('target_color', String, queue_size=10) sub = rospy.Subscriber('/cameras/left_hand_camera/image', Image, callback) rospy.spin() <file_sep>/GRC/archive/TargetIdentification/Baxter/TargetIdentifier.py #!/usr/bin/env python #subscribes to left hand camera # publishes to 'target_color' topic import rospy from sensor_msgs.msg import Image import cv2 as cv, cv_bridge import numpy as np import subprocess import pytesseract from matplotlib import pyplot as plt from std_msgs.msg import String row = 140 height = 150 column = 200 width = 300 bridge = cv_bridge.CvBridge() def callback(msg): img = bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8') cv.imwrite("ashwad.png", img) #img = cv.imread('input6.jpg') #cv.imshow('dat', img) #cv.waitKey(0) img = img[row:row+height, column:column+width] gf_img = cv.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) cv.imwrite('sampleTargetFiltered.png', gf_img) pass_arg = [] pass_arg.append("./whiteboardClean.sh") pass_arg.append("sampleTargetFiltered.png") pass_arg.append("cleanedTarget.png") subprocess.check_call(pass_arg) pass_arg2 = [] pass_arg2.append("./textclean.sh") subprocess.check_call(pass_arg2) cln_img = cv.imread('output.png') conf = ('-l eng --oem 3 --psm 11') text = pytesseract.image_to_string(cln_img, config=conf) f = open("tmpWrite.txt", "a") if text=='': f.write("Ashwad") else: f.write(text) f.close() while text!='' and not rospy.is_shutdown(): pub.publish(text) #cv.imshow('dst', cln_img) #cv.waitKey(0) #cv2.destroyAllWindows() rospy.init_node('my_camera_read') #rospy.Rate(2) pub = rospy.Publisher('target_color', String, queue_size=10) sub = rospy.Subscriber('/cameras/left_hand_camera/image', Image, callback) rospy.spin() <file_sep>/GRC/archive/Color_Identification/tmp_av.py #!/usr/bin/env python import rospy from sensor_msgs.msg import Image import cv2, cv_bridge import numpy as np bridge = cv_bridge.CvBridge() def callback(msg): cv_img = bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8') cv2.imshow('dst', cv_img) cv2.waitKey(0) #cv2.destroyAllWindows() rospy.init_node('my_camera_read') sub = rospy.Subscriber('/cameras/left_hand_camera/image', Image, callback) rospy.spin() <file_sep>/GRC/archive/TestGripper.py #!/usr/bin/env python import sys, rospy, tf, actionlib, moveit_commander from control_msgs.msg import (GripperCommandAction, GripperCommandGoal) from std_msgs.msg import Float32MultiArray, MultiArrayDimension import moveit_msgs.msg, geometry_msgs.msg import baxter_interface def init(): #Enable Baxter #print("Enabling Baxter...") #baxter_interface.RobotEnable().enable() #rospy.sleep(1.) #print("Baxter enabled successfully.") print("Initiating service clients...") #global blockLocationService #blockLocationService = rospy.ServiceProxy("block_location_service", blockLoc) #global targetLocationService #targetLocationService = rospy.ServiceProxy("target_location_service", targetLoc) moveit_commander.roscpp_initialize(sys.argv) robot = moveit_commander.RobotCommander() global scene scene = moveit_commander.PlanningSceneInterface() print("Clients initiated.") #instantiate a MoveGroupCommander object for the arm and a Gripper object for the hand #Tolerance setting recommended by multiple sites; appropriate value taken from Northwestern group print("Initiating Baxter's hand...") global hand hand = baxter_interface.Gripper("right") hand.calibrate() #CHECK IF THIS REQUIRES US TO DO ANYTHING print("Hand ready.") def grip_test(): hand.open() rospy.sleep(3) hand.close() def main(): rospy.init_node('pick_and_place', anonymous=True) print("Initializing...") init() print("Initialized.") rospy.sleep(5) while not rospy.is_shutdown(): grip_test() rospy.sleep(5) if __name__ == '__main__': main() <file_sep>/GRC/scripts/PickPlace.py #!/usr/bin/env python # Updated Dec. 13, 2019 #THIS IS THE FUNCTIONAL VERSION, DO NOT CHANGE #Make sure both services are global #Make sure to index the locations received from the service and make sure they have the correct z coordinate #Make sure there are rospy.sleep after each hand command #Add a waypoint to keep arm from knocking block after placing it import sys, rospy, tf, actionlib, moveit_commander from control_msgs.msg import (GripperCommandAction, GripperCommandGoal) from std_msgs.msg import Float32MultiArray, MultiArrayDimension, String, Int32 import moveit_msgs.msg, geometry_msgs.msg import baxter_interface from geometry_msgs.msg import Pose, Point, Quaternion from baxter_builder.srv import * # imports all ObjLocation, ObjLocationRequest, ObjLocationResponse global blockLocationService global robot global scene global arm global hand xb = 0.0 yb = 0.0 zb = 0.0 objfound = False objcolor = 0 gripper_offset_x = -0.125 gripper_offset_y = 0.05 target_color = "" def set_color(msg): global target_color if msg.data == "RED" or msg.data == "GREEN" or msg.data == "BLUE": target_color = msg.data #Initiate all_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ rospy.init_node('pick_and_place', anonymous=True) print("Initializing...") sys.argv.append("joint_states:=/robot/joint_states") #Enable Baxter #print("Enabling Baxter...") #baxter_interface.RobotEnable().enable() #rospy.sleep(1.) #print("Baxter enabled successfully.") print("Initiating service clients...") rospy.wait_for_service('block_location_service') blockLocationService = rospy.ServiceProxy("block_location_service", ObjLocation) moveit_commander.roscpp_initialize(sys.argv) robot = moveit_commander.RobotCommander() scene = moveit_commander.PlanningSceneInterface() print("Clients initiated.") #instantiate a MoveGroupCommander object for the arm and a Gripper object for the hand #Tolerance setting recommended by multiple sites; appropriate value taken from Northwestern group print("Initiating Baxter's arm and hand...") arm = moveit_commander.MoveGroupCommander("right_arm") arm.set_goal_position_tolerance(0.01) arm.set_goal_orientation_tolerance(0.01) hand = baxter_interface.Gripper("right") hand.calibrate() print("Arm and hand ready.") print("Initialized.") #Move to ready_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ orient = Quaternion(0, 1, 0, 0) ready = Pose(Point(0.55, -0.55, -0.05), orient) arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() print("Ready to begin.") rospy.sleep(2) target_color_sub = rospy.Subscriber('target_color', String, set_color) #Loop through pick-and-place_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ while not rospy.is_shutdown(): try: print("I am in the try") print(target_color) if len(target_color) > 0: # only move if it's ready and has a color targetLoc = [0.4, -0.2, -0.245] print("Target selected.") print("Waiting for block_location_service...") request = ObjLocationRequest() print("request created") rospy.wait_for_service("block_location_service") print("finished waiting for service") blockResponse = blockLocationService.call(request) print("called the service successfully") if blockResponse.objfound == True: print("Block selected.") rospy.sleep(1) blockLoc = [blockResponse.xb, blockResponse.yb, -0.25] print(blockLoc) blockCol = blockResponse.objcolor #blockLoc = [0.5, 0.2, -0.245] blockLoc[0] += gripper_offset_x blockLoc[1] += gripper_offset_y print("Block selected.") #Move to block__________________________________________________________________ blockReady = Pose(Point(blockLoc[0], blockLoc[1], -0.05), orient) arm.set_start_state_to_current_state() arm.set_pose_target(blockReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Grip block____________________________________________________________________ hand.open() rospy.sleep(1) blockGrip = Pose(Point(blockLoc[0], blockLoc[1], -0.245), orient) arm.set_start_state_to_current_state() arm.set_pose_target(blockGrip) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() hand.close() rospy.sleep(1) #Move back up___________________________________________________________________ arm.set_start_state_to_current_state() arm.set_pose_target(blockReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Move to target_________________________________________________________________ targetReady = Pose(Point(targetLoc[0], targetLoc[1], -0.05), orient) arm.set_start_state_to_current_state() arm.set_pose_target(targetReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Place block____________________________________________________________________ targetPlace = Pose(Point(targetLoc[0], targetLoc[1], -0.245), orient) arm.set_start_state_to_current_state() arm.set_pose_target(targetPlace) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() hand.open() rospy.sleep(1) #Move back up___________________________________________________________________ arm.set_start_state_to_current_state() arm.set_pose_target(targetReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() #Move back to ready_____________________________________________________________ arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() except rospy.ServiceException, e: print("Service call failed: %s", e) <file_sep>/GRC/archive/TargetIdentification/Baxter/textclean.sh #!/bin/bash ./textcleaner -g -e normalize -t 5 -s 2 -u -T cleanedTarget.png output.png convert output.png -resize 160x80 output2.png <file_sep>/GRC/archive/BaxterReady.py #!/usr/bin/env python import sys, rospy, baxter_interface #Enable Baxter print("Enabling Baxter...") baxter_interface.RobotEnable().enable() rospy.sleep(1) print("Baxter enabled successfully.") #Turning off any unneeded cameras rightCam = baxter_interface.CameraController('right_hand_camera') leftCam = baxter_interface.CameraController('left_hand_camera') print("Turning off right-hand camera...") rightCam.close() print("Right-hand camera off.") print("Turning on left-hand camera...") leftCam.open() print("Left-hand camera on.") print("Baxter ready to begin.") <file_sep>/GRC/scripts/RightArmReady.py #!/usr/bin/env python # node move_left_hand_camera # moves Baxter's left arm up into "cameraman" position using moveIt package import sys, rospy, tf, moveit_commander from geometry_msgs.msg import Pose, Point, Quaternion #from math import pi #This is only necessary if we wind up giving nonzero euler angles for orientation #Information on Baxter's coordinate frame found at https://www.researchgate.net/publication/326268262_Optimal_randomized_path_planning_for_redundant_manipulators_based_on_Memory-Goal-Biasing #Define desired orientation and pose - need to figure out where these numbers come from, what units they're in #I set it to zero for now so that we can see what Baxter's default orientation is (I think it points straight down already by default?) #orient = Quaternion(0.0454193467806, 0.885452336413, -0.451420745691, 0.100650649472) orient = Quaternion(0.0, 1.0, 0.0, 0.0) #Point and Pose are both geometry_msgs message types: #Point() defines a point in space as three floats xyz; Pose() defines a point position and quaternion orientation #Based on that document, I think these measurements are given in meters, with the origin in Baxter's midsection #By rough estimation, it looks like the table will be around 0 in z; extend from 0.5 to 0.8 in x; and from -0.3 to 0.3 in y #So "above the table" might be something like the values I've inserted here pose = Pose(Point(0.64, -0.64, -0.05), orient) sys.argv.append("joint_states:=/robot/joint_states") moveit_commander.roscpp_initialize(sys.argv) robot = moveit_commander.RobotCommander() scene = moveit_commander.PlanningSceneInterface() rospy.init_node('right_hand_ready') #MoveGroupCommander is a ROS class, so we're defining arm as a MoveGroupCommander object(?) #Arm names ("planning groups") are given here https://github.com/RethinkRobotics/sdk-docs/wiki/MoveIt-Tutorial arm = moveit_commander.MoveGroupCommander("right_arm") arm.set_goal_position_tolerance(0.01) arm.set_goal_orientation_tolerance(0.01) #Move left arm to cameraman position arm.set_start_state_to_current_state() arm.set_pose_target(pose) plan1 = arm.plan() arm.go(wait=True) arm.stop() arm.clear_pose_targets() <file_sep>/GRC/archive/TestSimpleMovement.py #!/usr/bin/env python import sys, rospy, tf, actionlib, moveit_commander from control_msgs.msg import (GripperCommandAction, GripperCommandGoal) from std_msgs.msg import Float32MultiArray, MultiArrayDimension import moveit_msgs.msg, geometry_msgs.msg import baxter_interface from geometry_msgs.msg import Pose, Point, Quaternion rospy.init_node('pick_and_place', anonymous=True) print("Initializing...") print("Initiating service clients...") #global blockLocationService #blockLocationService = rospy.ServiceProxy("block_location_service", blockLoc) #global targetLocationService #targetLocationService = rospy.ServiceProxy("target_location_service", targetLoc) moveit_commander.roscpp_initialize(sys.argv) global robot robot = moveit_commander.RobotCommander() global scene scene = moveit_commander.PlanningSceneInterface() print("Clients initiated.") #instantiate a MoveGroupCommander object for the arm #Tolerance setting recommended by multiple sites; appropriate value taken from Northwestern group print("Initiating Baxter's arm...") global arm arm = moveit_commander.MoveGroupCommander("right_arm") arm.set_goal_position_tolerance(0.01) arm.set_goal_orientation_tolerance(0.01) print("Arm ready.") print("Initialized.") ready = Pose(Point(0.55, -0.55, -0.05), Quaternion(0, 1, 0, 0)) arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() print("Ready to begin.") rospy.sleep(3) #Pause while not rospy.is_shutdown(): global blockLoc blockLoc = [0.5, 0.2, -0.245] #Hard-code block location print("Block selected.") global targetLoc targetLoc = [0.4, -0.2, -0.245] #Hard-code target location print("Target selected.") rospy.sleep(3) #Pause blockReady = Pose(Point(blockLoc[0], blockLoc[1], -0.05), Quaternion(0, 1, 0, 0)) #Move to block arm.set_start_state_to_current_state() arm.set_pose_target(blockReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() rospy.sleep(3) #Pause targetReady = Pose(Point(targetLoc[0], targetLoc[1], -0.05), Quaternion(0, 1, 0, 0)) #Move to target arm.set_start_state_to_current_state() arm.set_pose_target(targetReady) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() rospy.sleep(3) #Pause ready = Pose(Point(0.55, -0.55, -0.05), Quaternion(0, 1, 0, 0)) #Move to ready arm.set_start_state_to_current_state() arm.set_pose_target(ready) plan = arm.go(wait=True) arm.stop() arm.clear_pose_targets() rospy.sleep(3) #Pause <file_sep>/GRC/archive/TestMovement.py #!/usr/bin/env python import sys, rospy, tf, actionlib, moveit_commander from control_msgs.msg import (GripperCommandAction, GripperCommandGoal) from std_msgs.msg import Float32MultiArray, MultiArrayDimension import moveit_msgs.msg, geometry_msgs.msg from geometry_msgs.msg import Pose, Point, Quaternion import baxter_interface def init(): #Enable Baxter #print("Enabling Baxter...") #baxter_interface.RobotEnable().enable() #rospy.sleep(1.) #print("Baxter enabled successfully.") print("Initiating service clients...") #global blockLocationService #blockLocationService = rospy.ServiceProxy("block_location_service", blockLoc) #global targetLocationService #targetLocationService = rospy.ServiceProxy("target_location_service", targetLoc) moveit_commander.roscpp_initialize(sys.argv) global robot robot = moveit_commander.RobotCommander() global scene scene = moveit_commander.PlanningSceneInterface() print("Clients initiated.") #instantiate a MoveGroupCommander object for the arm #Tolerance setting recommended by multiple sites; appropriate value taken from Northwestern group print("Initiating Baxter's arm...") global arm arm = moveit_commander.MoveGroupCommander("right_arm") arm.set_goal_position_tolerance(0.01) arm.set_goal_orientation_tolerance(0.01) print("Arm ready.") def move_to_ready(): #Movement scripting taken from MoveIt! tutorial "Move Group Python Interface" ready = Pose(Point(0.55, -0.55, -0.05), Quaternion(0, 1, 0, 0)) arm.set_start_state_to_current_state() arm.set_pose_target(ready) arm.go(wait=True) arm.stop() arm.clear_pose_targets() def move_to_block(blockLoc): blockReady = Pose(Point([0.5, 0.2, -0.05], Quaternion(0, 1, 0, 0)) arm.set_start_state_to_current_state() arm.set_pose_target(blockReady) arm.go(wait=True) arm.stop() arm.clear_pose_targets() def move_to_target(targetLoc): targetReady = Pose(Point([0.4, -0.2, -0.05], Quaternion(0, 1, 0, 0)) arm.set_start_state_to_current_state() arm.set_pose_target(targetReady) arm.go(wait=True) arm.stop() arm.clear_pose_targets() def main(): rospy.init_node('pick_and_place', anonymous=True) print("Initializing...") init() rospy.sleep(5) print("Initialized.") move_to_ready() print("Ready to begin.") rospy.sleep(5) while not rospy.is_shutdown(): #blockLoc = [0.5, 0.2, -0.243] print("Block selected.") #targetLoc = [0.4, -0.2, -0.243] print("Target selected.") rospy.sleep(2) move_to_block(blockLoc) rospy.sleep(2) move_to_target(targetLoc) rospy.sleep(2) move_to_ready() rospy.sleep(2) if __name__ == '__main__': main()
63b12a1462977671cbfe8c17ad5d2c5e690ddab1
[ "Markdown", "Python", "Text", "Shell" ]
24
Python
Ysavn/BaxterBuilder
1986748b01ee30b5b4b3b082e30ff3d26ce65bab
31f78bdbc73ead70c1ae7bf4b86f7f46c579bcf8
refs/heads/master
<repo_name>JJDuru/RMAN<file_sep>/generate_backup_scripts.sh #!/bin/sh # Environment Variables random_minutes=$RANDOM random_minutes_2ndtake=$RANDOM random_hours=$RANDOM random_dayofweek=$RANDOM random_hours_2ndtake=$RANDOM minutes=$[ ( $random_minutes % 60 ) ] minutes_2ndtake=$[ ( $random_minutes_2ndtake % 60 ) ] hours=$[ ( $random_hours % 8 ) ] hours_2ndtake=$[ ( $random_hours_2ndtake % 8 ) ] dayofweek=$[($random_dayofweek % 7 )] sid=$1 if [ -z "$1" ]; then echo -e "The first (ORACLE_SID) argument cannot be null\n" exit 0 fi #DECLARE VARIABLES hostname=$2 if [ -z "$hostname" ]; then hostname=`hostname -s` fi backup_home="/backup/oracle/rman" backup_home="$backup_home/$hostname" oracle_home=`echo $ORACLE_HOME` home_variable='${HOME}' now=$(date +"%Y%m%d") username="S24RMAN" password="\"<PASSWORD>\"" catalog_username="kwt_rman" catalog_password="\"<PASSWORD>"\" #recovery window in days recovery_window=30 #zero recovery window or NONE zero_recovery_window=0 rcat_sid="RMANCAT.SECURE-24.NET" #Generating the crontab entry lines if [[ "$hostname" == *pl* ]] then echo -e "$minutes $hours * * * "$backup_home"/scripts/"$sid".full.112_64.sh >/dev/null 2>&1" echo -e "$minutes_2ndtake */2 * * * "$backup_home"/scripts/"$sid".arch.112_64.sh >/dev/null 2>&1" echo -e "$minutes $hours_2ndtake * * * "$backup_home"/scripts/"$sid".delete.obsolete.sh >/dev/null 2>&1" else echo -e "$minutes $hours * * "$dayofweek" "$backup_home"/scripts/"$sid".full.112_64.sh >/dev/null 2>&1" echo -e "$minutes_2ndtake */2 * * * "$backup_home"/scripts/"$sid".arch.112_64.sh >/dev/null 2>&1" echo -e "$minutes $hours_2ndtake * * * "$backup_home"/scripts/"$sid".delete.obsolete.sh >/dev/null 2>&1" fi now=$(date +"%Y%m%d") `mkdir -p $backup_home/$sid` `mkdir -p $backup_home/${sid}_OFFLINE` `mkdir -p $backup_home/logs` `chmod -R g+rw $backup_home/logs` `mkdir -p $backup_home/scripts` `chmod -R g+rw $backup_home/scripts` #GENERATE ARCHIVELOGS BACKUP RMAN generate_arch_rman="set echo on \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \nCONFIGURE COMPRESSION ALGORITHM 'MEDIUM' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE; \nCONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF "$recovery_window" DAYS; \nCONFIGURE DEVICE TYPE DISK PARALLELISM 4; \nCONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '"$backup_home"/"$sid"/%F'; \nCONFIGURE CONTROLFILE AUTOBACKUP ON; \nset command id to '"$sid".&1'; \n \ndelete archivelog all backed up 2 times to device type disk; \nsql 'alter system archive log current'; \n \nbackup as compressed backupset archivelog all not backed up 2 times format '"$backup_home"/"$sid"/arc_%d_%T_%s' tag '&1'; \ndelete archivelog all backed up 2 times to device type disk; \n \nCONFIGURE DEVICE TYPE DISK CLEAR; \n}" #echo -e $generate_arch_rman"\n" #GENERATE FULL ONLINE BACKUP RMAN AND SHELL generate_full_rman="set echo on \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \nCONFIGURE COMPRESSION ALGORITHM 'MEDIUM' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE; \nCONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF "$recovery_window" DAYS; \nCONFIGURE DEVICE TYPE DISK PARALLELISM 8; \nCONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '"$backup_home"/"$sid"/%F'; \nCONFIGURE CONTROLFILE AUTOBACKUP ON; \nset command id to '"$sid".&1'; \n \nbackup as compressed backupset full section size 16G filesperset 1 tag '&1' format '"$backup_home"/"$sid"/ful_%d_%T_%s_%p' (database); \n \ndelete archivelog all backed up 2 times to device type disk; \nsql 'alter system archive log current'; \nbackup as compressed backupset archivelog all not backed up 2 times format '"$backup_home"/"$sid"/arc_%d_%T_%s' tag '&2'; \ndelete archivelog all backed up 2 times to device type disk; \n \nCONFIGURE DEVICE TYPE DISK CLEAR; \n}" #echo -e $generate_full_rman generate_full_sh="#!/bin/sh \n#Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \ndbtag=\`date +'TAG.FHDW.'%Y%m%d'T'%H%M%S\` \natag=\`date +'TAG.AHDW.'%Y%m%d'T'%H%M%S\` \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".full.112_64.rman '\$dbtag' '\$atag'\" >>"$backup_home"/logs/"$sid".full.112_64.log \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/resync_catalog.rman\" >> "$backup_home"/logs/"$sid".full.112_64.log \n \nexit 0" #echo -e $generate_full_sh #GENERATE BACKUP VALIDATE CHECK LOGICAL #This is for detecting logical and physical corruption purposes. generate_check_logical_rman="set echo on \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \nCONFIGURE DEVICE TYPE DISK PARALLELISM 4; \nset command id to '"$sid".&1'; \n \nbackup validate check logical database; \n \nCONFIGURE DEVICE TYPE DISK CLEAR; \n}" #echo -e $generate_check_logical_rman generate_check_logical_sh="#!/bin/sh \n#Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \ndbtag=\`date +'TAG.CKLOG.'%Y%m%d'T'%H%M%S\` \natag=\`date +'TAG.CKLOG.'%Y%m%d'T'%H%M%S\` \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".check.logical.rman '\$dbtag' '\$atag'\" >>"$backup_home"/logs/"$sid".check.logical.log \n \nexit 0" #echo -e $generate_check_logical_sh #GENERATE BLOCKRECOVER CORRUPTION LIST #This is for fixing logical and physical corruption purposes. generate_blockrecover_rman="set echo on \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \nCONFIGURE DEVICE TYPE DISK PARALLELISM 4; \nset command id to '"$sid".&1'; \n \nBLOCKRECOVER CORRUPTION LIST; \n \nCONFIGURE DEVICE TYPE DISK CLEAR; \n}" #echo -e $generate_blockrecover_rman generate_blockrecover_sh="#!/bin/sh \n#Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \ndbtag=\`date +'TAG.BLCKREC.'%Y%m%d'T'%H%M%S\` \natag=\`date +'TAG.BLCKREC.'%Y%m%d'T'%H%M%S\` \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".blockrecover.rman '\$dbtag' '\$atag'\" >>"$backup_home"/logs/"$sid".blockrecover.log \n \nexit 0" #echo -e $generate_blockrecover_sh #GENERATE FULL ONLINE INCLUDES ARCHIVELOGS BACKUP RMAN AND SHELL generate_fullarch_rman="set echo on \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \nCONFIGURE COMPRESSION ALGORITHM 'MEDIUM' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE; \nCONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF "$recovery_window" DAYS; \nCONFIGURE DEVICE TYPE DISK PARALLELISM 8; \nCONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '"$backup_home"/"$sid"/%F'; \nCONFIGURE CONTROLFILE AUTOBACKUP ON; \nset command id to '"$sid".&1'; \n \ndelete archivelog all backed up 2 times to device type disk; \nsql 'alter system archive log current'; \n \nbackup as compressed backupset full section size 16G filesperset 1 tag '&1' format '"$backup_home"/"$sid"/ful_%d_%T_%s_%p' (database) plus archivelog format '"$backup_home"/"$sid"/arc_%d_%T_%s' tag '&2'; \n}" #echo -e $generate_fullarch_rman generate_fullarch_sh="#!/bin/sh \n#Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \ndbtag=\`date +'TAG.FHDW.'%Y%m%d'T'%H%M%S\` \natag=\`date +'TAG.AHDW.'%Y%m%d'T'%H%M%S\` \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".fullarch.rman '\$dbtag' '\$atag'\" >>"$backup_home"/logs/"$sid".fullarch.log \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/resync_catalog.rman\" >> "$backup_home"/logs/"$sid".fullarch.log \n \nexit 0" #echo -e $generate_fullarch_sh #GENERATE FULL OFFLINE BACKUP RMAN generate_full_offline_rman=" \nconnect target "$username"/"$password"@"$sid"; \nconnect catalog "$catalog_username"/"$catalog_password"@"$rcat_sid" \nrun \n{ \nCONFIGURE DEVICE TYPE DISK PARALLELISM 8; \nCONFIGURE COMPRESSION ALGORITHM 'MEDIUM' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE; \nCONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '"$backup_home"/"$sid"_OFFLINE/%F'; \nCONFIGURE CONTROLFILE AUTOBACKUP ON; \nset command id to '"$sid".&1'; \n \nbackup as compressed backupset full section size 16G filesperset 1 tag '&1' format '"$backup_home"/"$sid"_OFFLINE/ful_offline_%d_%T_%s_%p' keep forever (database); \n}" #echo -e $generate_full_offline_rman home_variable='${HOME}' ##GENERATE SHELL WRAPPERS #GENERATE ARCHIVELOG BACKUP SHELL generate_arch_sh="#!/bin/sh \n#Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \natag=\`date +'TAG.AHHD.'%Y%m%d'T'%H%M%S\` \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".arch.112_64.rman '\$atag'\" >>"$backup_home"/logs/"$sid".arch.112_64.log \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/resync_catalog.rman\" >>"$backup_home"/logs/"$sid".arch.112_64.log \n \nexit 0" #echo -e $generate_arch_sh #GENERATE FULL OFFLINE BACKUP SHELL generate_full_offline_sh="#!/bin/sh \n# Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \ndbtag=\`date +'TAG.FCSD.'%Y%m%d'T'%H%M%S\` \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".full.offline.112_64.rman '\$dbtag'\" >>"$backup_home"/logs/"$sid".full.offline.112_64.log \n \nexit 0" #GENERATE LIST BACKUP RMAN generate_list_backup_rman=" \nconnect target "$username"/"$password"@"$sid"; \nlist backup;" #GENERATE LIST BACKUP SHELL generate_list_backup_sh="#!/bin/sh \n# Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".list.backup.rman\" >>"$backup_home"/logs/"$sid".list.backup.txt \n \nexit 0" #GENERATE LIST BACKUP SUMMARY RMAN generate_list_backup_summary_rman="set echo on \nconnect target "$username"/"$password"@"$sid"; \nlist backup summary;" #echo $generate_list_backup_summary_rman #GENERATE LIST BACKUP SUMMARY SHELL generate_list_backup_summary_sh="#!/bin/sh \n# Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".list.backup.summary.rman\" >"$backup_home"/logs/"$sid".list.backup.summary.txt \n \nexit 0" #echo $generate_list_backup_summary_sh #GENERATE RESTORE DATABASE VALIDATE generate_restore_database_validate_rman="set echo on \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \nCONFIGURE DEVICE TYPE DISK PARALLELISM 8; \nRESTORE DATABASE VALIDATE; \n} " #echo $generate_restore_database_validate_rman #GENERATE RESTORE DATABASE VALIDATE SHELL generate_restore_database_validate_sh="#!/bin/sh \n# Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".restore.database.validate.rman\" >"$backup_home"/logs/"$sid".restore.database.validate.log \n \nexit 0" #echo $generate_restore_database_validate_sh #GENERATE DELETE OBSOLETE RMAN generate_delete_obsolete_rman=" \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \nCONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 30 DAYS; \ndelete noprompt obsolete; \ncrosscheck backup; \ncrosscheck archivelog all; \ndelete noprompt expired backup; \ndelete noprompt expired archivelog all; \n}" #GENERATE DELETE OBSOLETE SHELL generate_delete_obsolete_sh="#!/bin/sh \n# Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".delete.obsolete.rman\" >>"$backup_home"/logs/"$sid".delete.obsolete.log \nexit 0" #GENERATE RESYNC CATALOG generate_resync_catalog_rman=" \nconnect target "$username"/"$password"@"$sid"; \nconnect catalog "$catalog_username"/"$catalog_password"@"$rcat_sid" \nrun \n{ \nresync catalog; \n}" #GENERATE CROSSCHECK ARCHIVELOG RMAN generate_crosscheck_archivelog_rman=" \nconnect target "$username"/"$password"@"$sid"; \nrun \n{ \ncrosscheck archivelog all; \n}" #GENERATE CROSSCHECK ARCHIVELOG SHELL generate_crosscheck_archivelog_sh="#!/bin/sh \n# Environment Variables \n. "$home_variable"/.profile \n \nexport NLS_LANGUAGE=\"AMERICAN_AMERICA.UTF8\" \nexport NLS_DATE_FORMAT=\"DD-MON-YYYY HH24:MI:SS\" \n \n\$ORACLE_HOME/bin/rman cmdfile=\""$backup_home"/scripts/"$sid".crosscheck.archivelog.rman\" >>"$backup_home"/logs/"$sid".crosscheck.archivelog.log \nexit 0" #echo -e $generate_crosscheck_archivelog_sh echo -e $generate_arch_rman >$backup_home/scripts/$sid.arch.112_64.rman echo -e $generate_full_rman >$backup_home/scripts/$sid.full.112_64.rman echo -e $generate_check_logical_rman >$backup_home/scripts/$sid.check.logical.rman echo -e $generate_blockrecover_rman >$backup_home/scripts/$sid.blockrecover.rman echo -e $generate_fullarch_rman >$backup_home/scripts/$sid.fullarch.rman echo -e $generate_full_offline_rman >$backup_home/scripts/$sid.full.offline.112_64.rman echo -e $generate_list_backup_rman >$backup_home/scripts/$sid.list.backup.rman echo -e $generate_list_backup_summary_rman >$backup_home/scripts/$sid.list.backup.summary.rman echo -e $generate_restore_database_validate_rman >$backup_home/scripts/$sid.restore.database.validate.rman echo -e $generate_delete_obsolete_rman >$backup_home/scripts/$sid.delete.obsolete.rman echo -e $generate_crosscheck_archivelog_rman >$backup_home/scripts/$sid.crosscheck.archivelog.rman echo -e $generate_resync_catalog_rman >$backup_home/scripts/resync_catalog.rman echo -e $generate_arch_sh >$backup_home/scripts/$sid.arch.112_64.sh chmod u+x $backup_home/scripts/$sid.arch.112_64.sh echo -e $generate_full_sh >$backup_home/scripts/$sid.full.112_64.sh chmod u+x $backup_home/scripts/$sid.full.112_64.sh echo -e $generate_check_logical_sh >$backup_home/scripts/$sid.check.logical.sh chmod u+x $backup_home/scripts/$sid.check.logical.sh echo -e $generate_blockrecover_sh >$backup_home/scripts/$sid.blockrecover.sh chmod u+x $backup_home/scripts/$sid.blockrecover.sh echo -e $generate_fullarch_sh >$backup_home/scripts/$sid.fullarch.sh chmod u+x $backup_home/scripts/$sid.fullarch.sh echo -e $generate_full_offline_sh >$backup_home/scripts/$sid.full.offline.112_64.sh chmod u+x $backup_home/scripts/$sid.full.offline.112_64.sh echo -e $generate_list_backup_sh >$backup_home/scripts/$sid.list.backup.sh chmod u+x $backup_home/scripts/$sid.list.backup.sh echo -e $generate_list_backup_summary_sh >$backup_home/scripts/$sid.list.backup.summary.sh chmod u+x $backup_home/scripts/$sid.list.backup.summary.sh echo -e $generate_restore_database_validate_sh >$backup_home/scripts/$sid.restore.database.validate.sh chmod u+x $backup_home/scripts/$sid.restore.database.validate.sh echo -e $generate_delete_obsolete_sh >$backup_home/scripts/$sid.delete.obsolete.sh chmod u+x $backup_home/scripts/$sid.delete.obsolete.sh echo -e $generate_crosscheck_archivelog_sh >$backup_home/scripts/$sid.crosscheck.archivelog.sh chmod u+x $backup_home/scripts/$sid.crosscheck.archivelog.sh
96fb3f02530293757bd9fa33d527053d0aceed84
[ "Shell" ]
1
Shell
JJDuru/RMAN
77e9ac39880e5455d047dd864037302653b07ff7
99e161e4684050ca0add6b423d8844d596eeef2b
refs/heads/master
<repo_name>hkz-dev/spring-data-jpa-test<file_sep>/src/test/java/test/RepositoryTests.java package test; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Repository tests */ @SpringApplicationConfiguration(classes = DataConfiguration.class) @RunWith(SpringJUnit4ClassRunner.class) public class RepositoryTests { /** * {@link Logger} */ @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(RepositoryTests.class); /** * {@link user.ClubRepository} */ @Autowired private user.ClubRepository userClubRepository; /** * {@link golf.ClubRepository} */ @Autowired private golf.ClubRepository golfClubRepository; /** * Test */ @Test public void test() { this.userClubRepository.joinClub(100, 10); this.golfClubRepository.useClub(100, "wood"); } }<file_sep>/src/main/java/golf/ClubRepositoryCustom.java package golf; /** * {@link ClubRepository} custom interface */ public interface ClubRepositoryCustom { /** * Use club * * @param userId User ID * @param type Club type */ void useClub(Integer userId, String type); }<file_sep>/src/test/resources/data/user.sql CREATE SCHEMA IF NOT EXISTS "user"; CREATE TABLE IF NOT EXISTS "user"."club" ( "id" BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, "name" TEXT NOT NULL, PRIMARY KEY ("id"));<file_sep>/src/test/resources/data/golf.sql CREATE SCHEMA IF NOT EXISTS "golf"; CREATE TABLE IF NOT EXISTS "golf"."club" ( "id" BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, "type" TEXT NOT NULL, PRIMARY KEY ("id"));<file_sep>/src/main/java/golf/ClubRepositoryImpl.java package golf; import org.springframework.stereotype.Component; /** * {@link ClubRepository} custom implementation */ @Component("golf.ClubRepositoryImpl") public class ClubRepositoryImpl implements ClubRepositoryCustom { @Override public void useClub(Integer userId, String type) { // TODO implementation } }<file_sep>/src/main/java/golf/ClubRepository.java package golf; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * {@link Club} repository */ @Repository("golf.ClubRepository") public interface ClubRepository extends JpaRepository<Club, Integer>, ClubRepositoryCustom { /* NOP */ }<file_sep>/README.md # spring-data-jpa-test * Tests for spring-data-jpa.<file_sep>/src/main/java/user/ClubRepositoryImpl.java package user; import org.springframework.stereotype.Component; /** * {@link ClubRepository} custom implementation */ @Component("user.ClubRepositoryImpl") public class ClubRepositoryImpl implements ClubRepositoryCustom { @Override public void joinClub(Integer userId, Integer clubId) { // TODO implementation } }
23fad14bbebe6e7ffeaa057b037d3d942b62e8c8
[ "Markdown", "Java", "SQL" ]
8
Java
hkz-dev/spring-data-jpa-test
134e0437a0971843c82c7d915301803fe357f0e4
b518b2af022e3f27d91594df4cf08d31e6465220
refs/heads/master
<repo_name>rochefort/homebrew-cask<file_sep>/Casks/nomachine.rb class Nomachine < Cask version '4.2.27_1' sha256 'b210543612f9f99e120b356ef38754bd9b8f20c54d5d657e88a1d73b644cf145' url "http://download.nomachine.com/download/#{version.split('.')[0..1].join('.')}/MacOSX/nomachine_#{version}.dmg" homepage 'http://www.nomachine.com' install 'NoMachine.pkg' uninstall :files => ['/Applications/NoMachine.app'] end
6d4859d4a3842703f8821d21912571c905c7b042
[ "Ruby" ]
1
Ruby
rochefort/homebrew-cask
7ac0e12f61ce166503adfb86680f5d219efea400
3f28fca727fc5faf03b26cd2ba2d4f9fc96547ba