Tree Size Problem
问题描述 :
Trees are used to represent the evolutionary relationship of species. An evolutionary tree is a edge-weighted tree with each leaf representing one species. The distance between two leaves on the tree represents the dissimilarity of these two species. An important issue in computational biology is to construct the evolutionary tree from the observed dissimilarities.
Let N = {1..n}. An n*n matrix M is a metric over N if it is symmetric, nonnegative, and M[i, j] + M[j, k] >= M[i, k] for any 1<= i, j, k <=n (i.e., triangle inequality). A metric is a tree metric if it can be realized by a tree, i.e., there exists an edge-weighted tree T such that
1. the leaf set is N;
2. the weight of each edge is nonnegative;
3. and d(T, i, j) = M[i, j] for any i, j <= N, where d(T, i, j) is the shortest path length between i and j on the tree T.
For example, the following matrix is a tree metric. The corresponding tree is given in Figure 8.
The size of a tree is defined to be the total weight of the tree edges. For a tree metric, it has been shown that the tree size is unique, i.e., it is impossible to find two trees of different sizes realizing the same tree metric. Your task is to design a program to compute the tree sizes of the given tree metrics. The following simple example may be helpful. For the case of only two species, the tree has only one edge and the tree size is just the distance between the two species. Let us consider the case of three species a, b, and c. Let T be the corresponding tree. Since T has three leaves, there is an internal node x. By definition, the path length d(T, a, b) = M[a, b]. Since x is a vertex on the path between a and b, all we need to do is to determine the weight (length) of edge (x, c). Let w(x, c) denote the weight of edge (x, c). We have
w(x, c) + w(x, a) = M[a, c],
w(x, c) + w(x, b) = M[b, c],
and w(x, a) + w(x, b) = M[a, b].
Therefore, w(x, c) = (M[a, c] +M[b, c] -M[a, b])/2.
Let N = {1..n}. An n*n matrix M is a metric over N if it is symmetric, nonnegative, and M[i, j] + M[j, k] >= M[i, k] for any 1<= i, j, k <=n (i.e., triangle inequality). A metric is a tree metric if it can be realized by a tree, i.e., there exists an edge-weighted tree T such that
1. the leaf set is N;
2. the weight of each edge is nonnegative;
3. and d(T, i, j) = M[i, j] for any i, j <= N, where d(T, i, j) is the shortest path length between i and j on the tree T.
For example, the following matrix is a tree metric. The corresponding tree is given in Figure 8.
The size of a tree is defined to be the total weight of the tree edges. For a tree metric, it has been shown that the tree size is unique, i.e., it is impossible to find two trees of different sizes realizing the same tree metric. Your task is to design a program to compute the tree sizes of the given tree metrics. The following simple example may be helpful. For the case of only two species, the tree has only one edge and the tree size is just the distance between the two species. Let us consider the case of three species a, b, and c. Let T be the corresponding tree. Since T has three leaves, there is an internal node x. By definition, the path length d(T, a, b) = M[a, b]. Since x is a vertex on the path between a and b, all we need to do is to determine the weight (length) of edge (x, c). Let w(x, c) denote the weight of edge (x, c). We have
w(x, c) + w(x, a) = M[a, c],
w(x, c) + w(x, b) = M[b, c],
and w(x, a) + w(x, b) = M[a, b].
Therefore, w(x, c) = (M[a, c] +M[b, c] -M[a, b])/2.
输入:
The input file consists of several test cases. The first line of each test case is a positive integer n, 2 < n < 30. The following n - 1 lines represent the upper triangle of the tree metric, but the diagonal is not included. Each line is for one row, and elements are separated by spaces. All the elements are nonnegative integers less than 100. The last case is followed by a "0" to indicate the end of input. You may assume that the test data are all tree metrics, and it is not necessary to check them.
Furthermore, the size of a tree is the sum of all integers in the test case except the integers in the first line of the test case.
Furthermore, the size of a tree is the sum of all integers in the test case except the integers in the first line of the test case.
输出:
For each test case, output the tree size in one line.
样例输入:
5 5 9 12 8 8 11 7 5 1 4 4 15 36 60 31 55 36 0
样例输出:
15 71
解题代码:
//* @author: import java.util.*; public class Main { static int value[][]=new int[50][50]; static int ans,n; static void calc() { int i, j, temp, k, s; for( k=0; k< n-2; k++ ) { s = 10000000; for( i = k+1; i < n; i++ ) for( j = i+1; j < n; j++ ) { if( (temp = (value[i][k]+value[j][k]-value[i][j])/2 ) < s ) s = temp; } for( i = k+1; i < n; i++ ){ value[i][k] -= s; value[k][i] -= s; } ans += s; } ans += value[n-2][n-1]; } public static void main(String[] args){ Scanner in = new Scanner(System.in); int i, j; while( in.hasNext()) { n=in.nextInt(); if( n == 0 ) break; for( i=0; i< n; i++ ) { for( j=i+1; j< n; j++ ) { value[i][j]=in.nextInt(); value[j][i] = value[i][j]; } value[i][i] = 0; } ans = 0; calc(); System.out.printf( "%d\n",ans ); } } }
(adsbygoogle = window.adsbygoogle || []).push({});
能不能说下这个是用的什么算法策略？
漂亮。佩服。
P.S. unsigned 应该去掉。换行符是n 不是/n
还可以稍微优化一下，
int main() {
int m,n,ai,aj,bi,bj,ak,bk;
while (scanf("%d%d",&m,&n)!=EOF) {
ai = sqrt(m-1);
bi = sqrt(n-1);
aj = (m-ai*ai-1)>>1;
bj = (n-bi*bi-1)>>1;
ak = ((ai+1)*(ai+1)-m)>>1;
bk = ((bi+1)*(bi+1)-n)>>1;
printf("%dn",abs(ai-bi)+abs(aj-bj)+abs(ak-bk));
}
}
程序只能输出一个子序列
这道题目的核心一句话是：取还是不取。
如果当前取，则index+1作为参数。如果当前不取，则任用index作为参数。
int L[m+1][n+1];这样定义出错，这个在gcc上可以编译通过 在VS上不行 应该改为new 或者vector
网站不错，支持一个
您没有考虑 树的根节点是负数的情况， 若树的根节点是个很大的负数，那么就要考虑过不过另外一边子树了
学算法中的数据结构学到一定程度会乐此不疲的，比如其中的2－3树，类似的红黑树，我甚至可以自己写个逻辑文件系统结构来。
厉害啊，我遇见数学问题就头疼！
5.1处，反了；“上一个操作符的优先级比操作符ch的优先级大，或栈是空的就入栈。”如代码所述，应为“上一个操作符的优先级比操作符ch的优先级小，或栈是空的就入栈。”
多谢支持！
嗯，是写错了，文中以更改。此时的数据量还是很小的，耗时却不短。这种方法确实可以，当然或许还有其他的优化方案，但是优化只能针对某些数据，不太可能在所有情况下都能在可接受的时间内求解出答案。


shelton cal ripken tournament 2009
Fort Scott Tribune: Sports : Baseball
Fort Scott's 11-year-old Cal Ripken baseball team went 1-2 in pool play at the State . The Most Valuable Player for Fort Scott was Braden Shelton while the WOW Award, . Cal Ripken League district tournaments under way (07/08/11) . NEVADA, Mo -- Not all of the 2009 Griffons players have arrived and they have only .
http://www.fstribune.com/topic/sportshighschoolbaseball
Baseball awards - Wikipedia, the free encyclopedia
Retrieved 2009-12-07. ^ For footnotes re World Series honors and photos of championship teams, see #Babe Ruth League (below). ^ a b The Cal Ripken World .
http://en.wikipedia.org/wiki/Baseball_awards
Who's better: Cal Ripken or Derek Jeter? |
Jun 21, 2012 . Former Baltimore Orioles shortstop/third baseman Cal Ripken Jr. is known as the Iron . 35 wins in his career above the league average shortstop (mind you, league average . This column originally ran on October 15, 2009. . Gary Shelton of the Tampa Bay Times expressed concern the Rays don't have .
http://couchsideshow.wordpress.com/2012/06/21/whos-better-cal-ripken-or-derek-jeter/
Things You'll Need
- Certified copies of public records evidence in your case
Instructions
-
-
1
City of Springfield, MA Official web site: Cal Ripken, Sr. Foundation ...
Dec 27, 2011 . The Cal Ripken, Sr. Foundation, a nonprofit serving at-risk youth in . marching band practices, youth tournaments, regional tournaments, and .
http://www3.springfield-ma.gov/cos/1144.0.htmlPuerto Rico Baseball League - BR Bullpen
Jan 28, 2013 . It is a winter league that consisting of six teams with the league's champion . It returned to play in 2008-2009 with a new name (the Puerto Rico Baseball League). . 1980-81 Rusty Torres, Mayagüez 41; 1981-82 Cal Ripken Jr., . 1978-79 Steve McCatty, Ponce & Sheldon Burnside, Mayagüez 8 (tie) .
http://www.baseball-reference.com/bullpen/Puerto_Rico_Baseball_League -
2
Cal Ripken District Baseball
The Osawatomie 11 year old Cal Ripken All Stars fell to the Fort Scott All-Stars in District Tournament play at Osawatomie on Monday, July 13, 2009. The Oz All .
http://www.miamicountysports.com/Babe%20Ruth%20Baseball/calripkendistric.htmlEvents - COOS BAY COAST CAL RIPKEN LEAGUE : Babe Ruth ...
Cal Ripken State Tournament, Jul 16 2010 5:00PM, Coos Bay, Oregon - BACAPA Field . Cal Ripken Tournament - Minors, Jul 10 2009 1:00PM, Eugene .
http://cbcoastleague.baberuthonline.com/engine.asp?area=league&aid=1938&content=events -
-
3
Charlotte Knights - Wikipedia, the free encyclopedia
The Charlotte Knights are a minor league baseball team representing Charlotte, North Carolina. . baseman in 1976), Cal Ripken (1980) and Curt Schilling (mid- 1980s) played for the O's. . On October 8, 2009 the Charlotte Knights and York County agreed in principle . Kyle Shelton, 3B, 8, 20, 1, 4, 1, 0, 1, 2, 2, 5 .200, 0 .
http://en.wikipedia.org/wiki/Charlotte_Knights -
4
13th of Apr | Story - A Minor League Season
Time for minor league trivia. The Charlotte Stone Crabs are the third minor league team to be purchased by Ripken Baseball yes, Cal Ripken Jr. and his .
http://www.aminorleagueseason.com/?stories=28Our 2011 Annual Report - Cal Ripken, Sr. Foundation
May 10, 2012 . Cal Ripken, Sr. Foundation's 2011 Annual . Shelton. Stamford. Waterbury. West Haven. Willimantic. New Jersey . program in 2009, 2010, and 2011. . 2011 Tournament Champions from Kelly & Associates Insurance .
http://www.ripkenfoundation.org/documents/2011annualreport.pdf
-
1
References
Resources
- Photo Credit Justice image by MVit from formula in determining the sample size


Lucien (Lucy) Minor is the resident odd duck in the bucolic hamlet of Bury.  When Lucy accepts employment assisting the majordomo of the remote, forbidding castle of the Baron Von Aux he meets thieves, madmen, aristocrats, and a puppy. He also meets Klara, a delicate beauty who is, unfortunately, already involved with an exceptionally handsome partisan soldier. Thus begins a tale of polite theft, bitter heartbreak, domestic mystery and cold-blooded murder in which every aspect of human behaviour is laid bare for our hero to observe. Lucy must stay safe, and protect his puppy, because someone or something is roaming the corridors of the castle late at night.
Undermajordomo Minor is a triumphant ink-black comedy of manners by the Man Booker shortlisted author of The Sisters Brothers. It is an adventure story, and a mystery, and a searing portrayal of rural Alpine bad behaviour with a brandy tart, but above all it is a love story. And Lucy must be careful, for love is a violent thing.
Lucien Minor's mother had not wept, had not come close to weeping at their parting. All that day he;d felt a catch in his throat and his every movement was achieved in chary degrees, as though swift activity would cause a breach of emotion. They had eaten breakfast and lunch together but neither had spoken a word, and now it was time for him to go but he couldn't step away from his bed, upon which he lay fully dressed, in coat and boots, sheepsin cap pulled low, to his brow. Lucy was seventeen years old, and this had been his room since birth; all that he could see and put his hand to was permeated with the bewildering memories of childhood. When he heard his mother positing unknowable questions to herself from the scullery downstairs he was nearly overcome with sorrow. A valise stood alertly on the floor beside him.


Data Acquisition Workflow¶
A typical data acqusition workflow contains the following steps:
Physical Syetem: indentify the physical system/phynomenon.
Sensors: determine the sensor group that is appropriate for measuring the physical system.
Signal Conditioning: Condition the raw analog signal to safe and measurable range, filter noise if necessary.
ADC: Choose an appropriate analog to digital converter for converting the conditioned analog signal to digital signal.
Computer: Monitor and record the signal.
Example: Axial Strain of Rock Cylinder¶
In this example, we want to measure the axial strain (\(\epsilon\)) of a cylindrical rock specimen during uniaxial compression test.
where \(\Delta L\) is the change of axial length due to the compression; \(L\) is the initial length of the specimen.
For more on mechanics and deformation please refer to the wiki page about deformation
Physical System¶
In a uniaxial compression test, a cylindrical rock specimen is placed vertically inside a loading frame. The load is applied on the axial direction of the rock specimen. An example of the physical system is shown below.
Sensor: Strain Gauge¶
For a small strain system scenario, a linear strain gauge is usually implemented to measure the axial strain. A strain gauge consists of an insulating flexible backing which supports a metallic foil pattern . A strain gauge is attached to the object by a suitable adhesive. As the object is deformed, the attached strain gauge is deformed as well, causing its electrical resistance to change. (learn more about strain gauge on Wikipedia)
In practice, a Wheatstone Bridge is implemented for measuring the voltage output caused by the resistance change of the strain gauge. In this specific case, the configuration is called quarter bridge. A Wheatstone bridge circuit is capable of precisely measuring an unknown electrical resistance change by balancing its two legs.
The strain can be approximated by the following equation for quarter bridge configuration,
where \(V_0\) is the measured volatge; \(V_S\) is the excitation voltage (supply voltage); \(G\) is the gauge factor determined by the strain gauge manufacturer.
Signal Conditioning¶
Raw analog signals contain some degrees of interference. For example, an AC line nearby may introduce high frequency interference, the periodic temperature change over time can introduce low frequency interference. Signal filters are common signal conditioning tools to block or extract signal components of a certain frequency range.
Filtering is a very common signal conditioning procedure (learn more). There are many other signal conditioning techniques, but I will leave this topic open for you to explore.
Analog to Digital Conversion¶
After proper signal conditioning, the analog signal is sampled and converted to digital signal by an analog to digital converter (ADC). The following figure shows a resolution difference of a 3-bit and a 16-bit ADC. Note that ADC with higher resolution are increasing more expensive.
Monitor and Record¶
The converted digital signals can be transfered to a computing device such as a laptop to monitor and record. Generally, this procedure is done by a software interface between the DAQ harware and the computer system.


{% extends "base.html" %} {% block title %}
Medieval catalogues > CARTHUSIANS > London > Loans to Hinton, early 16th cent.
{% endif %}6 identified entries found.
All data was derived from the List of Identifications by Professor Richard Sharpe.
{% if not printing %}
A key to codes used in the List is available (opens in new tab).{% endif %}


I’m currently working to replace an older legacy app with a Rails 3 app using Devise for authentication. One of the problems we encountered was was that the legacy app was using a non-standard approach for generating and encrypting passwords, so to migrate over user accounts, Devise’s built-in encryption strategies were completely useless. Fortunately, it turns out in Devise it is incredibly easy to build your own encryptor.
Basically, all you have to do is create an file in config/initializers like the following:
Then, in your config/initializers/devise.rb, its as simple as adding (or editing) a line that references the class you created.
As long as your encryptor returned the encrypted version of your password, you’re good to go.
Now migrating your accounts should be fairly straightforward. We were using restful auth in the legacy app, so I just mapped the important differences and then converted the passwords (being sure to save with false, in order to bypass devise validations)


--- title: Virtual Service description: Configuration affecting label/content routing, sni routing, etc. location: https://istio.io/docs/reference/config/networking/virtual-service.html layout: protoc-gen-docs generator: protoc-gen-docs schema: istio.networking.v1alpha3.VirtualService aliases: [/docs/reference/config/networking/v1alpha3/virtual-service] number_of_entries: 24 ---
Configuration affecting traffic routing. Here are a few terms useful to define in the context of traffic routing.
Service
a unit of application behavior bound to a unique name in a
service registry. Services consist of multiple network endpoints
implemented by workload instances running on pods, containers, VMs etc.
Service versions (a.k.a. subsets)
- In a continuous deployment
scenario, for a given service, there can be distinct subsets of
instances running different variants of the application binary. These
variants are not necessarily different API versions. They could be
iterative changes to the same service, deployed in different
environments (prod, staging, dev, etc.). Common scenarios where this
occurs include A/B testing, canary rollouts, etc. The choice of a
particular version can be decided based on various criterion (headers,
url, etc.) and/or by weights assigned to each version. Each service has
a default version consisting of all its instances.
Source
- A downstream client calling a service.
Host
- The address used by a client when attempting to connect to a
service.
Access model
- Applications address only the destination service
(Host) without knowledge of individual service versions (subsets). The
actual choice of the version is determined by the proxy/sidecar, enabling the
application code to decouple itself from the evolution of dependent
services.
A VirtualService
defines a set of traffic routing rules to apply when a host is
addressed. Each routing rule defines matching criteria for traffic of a specific
protocol. If the traffic is matched, then it is sent to a named destination service
(or subset/version of it) defined in the registry.
The source of traffic can also be matched in a routing rule. This allows routing to be customized for specific client contexts.
The following example on Kubernetes, routes all HTTP traffic by default to pods of the reviews service with label “version: v1”. In addition, HTTP requests with path starting with /wpcatalog/ or /consumercatalog/ will be rewritten to /newcatalog and sent to pods with label “version: v2”.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- name: "reviews-v2-routes"
match:
- uri:
prefix: "/wpcatalog"
- uri:
prefix: "/consumercatalog"
rewrite:
uri: "/newcatalog"
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v2
- name: "reviews-v1-route"
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- name: "reviews-v2-routes"
match:
- uri:
prefix: "/wpcatalog"
- uri:
prefix: "/consumercatalog"
rewrite:
uri: "/newcatalog"
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v2
- name: "reviews-v1-route"
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
{{}} {{}}
A subset/version of a route destination is identified with a reference
to a named service subset which must be declared in a corresponding
DestinationRule
.
{{
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: reviews-destination
spec:
host: reviews.prod.svc.cluster.local
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: reviews-destination
spec:
host: reviews.prod.svc.cluster.local
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
{{}} {{}}
Configuration affecting traffic routing.
Destination indicates the network addressable service to which the request/connection will be sent after processing a routing rule. The destination.host should unambiguously refer to a service in the service registry. Istio’s service registry is composed of all the services found in the platform’s service registry (e.g., Kubernetes services, Consul services), as well as services declared through the ServiceEntry resource.
Note for Kubernetes users: When short names are used (e.g. “reviews” instead of “reviews.default.svc.cluster.local”), Istio will interpret the short name based on the namespace of the rule, not the service. A rule in the “default” namespace containing a host “reviews will be interpreted as “reviews.default.svc.cluster.local”, irrespective of the actual namespace associated with the reviews service. To avoid potential misconfigurations, it is recommended to always use fully qualified domain names over short names.
The following Kubernetes example routes all traffic by default to pods of the reviews service with label “version: v1” (i.e., subset v1), and some to subset v2, in a Kubernetes environment.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews-route
namespace: foo
spec:
hosts:
- reviews # interpreted as reviews.foo.svc.cluster.local
http:
- match:
- uri:
prefix: "/wpcatalog"
- uri:
prefix: "/consumercatalog"
rewrite:
uri: "/newcatalog"
route:
- destination:
host: reviews # interpreted as reviews.foo.svc.cluster.local
subset: v2
- route:
- destination:
host: reviews # interpreted as reviews.foo.svc.cluster.local
subset: v1
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews-route
namespace: foo
spec:
hosts:
- reviews # interpreted as reviews.foo.svc.cluster.local
http:
- match:
- uri:
prefix: "/wpcatalog"
- uri:
prefix: "/consumercatalog"
rewrite:
uri: "/newcatalog"
route:
- destination:
host: reviews # interpreted as reviews.foo.svc.cluster.local
subset: v2
- route:
- destination:
host: reviews # interpreted as reviews.foo.svc.cluster.local
subset: v1
{{}} {{}}
And the associated DestinationRule
{{
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: reviews-destination
namespace: foo
spec:
host: reviews # interpreted as reviews.foo.svc.cluster.local
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: reviews-destination
namespace: foo
spec:
host: reviews # interpreted as reviews.foo.svc.cluster.local
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
{{}} {{}}
The following VirtualService sets a timeout of 5s for all calls to productpage.prod.svc.cluster.local service in Kubernetes. Notice that there are no subsets defined in this rule. Istio will fetch all instances of productpage.prod.svc.cluster.local service from the service registry and populate the sidecar’s load balancing pool. Also, notice that this rule is set in the istio-system namespace but uses the fully qualified domain name of the productpage service, productpage.prod.svc.cluster.local. Therefore the rule’s namespace does not have an impact in resolving the name of the productpage service.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: my-productpage-rule
namespace: istio-system
spec:
hosts:
- productpage.prod.svc.cluster.local # ignores rule namespace
http:
- timeout: 5s
route:
- destination:
host: productpage.prod.svc.cluster.local
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: my-productpage-rule
namespace: istio-system
spec:
hosts:
- productpage.prod.svc.cluster.local # ignores rule namespace
http:
- timeout: 5s
route:
- destination:
host: productpage.prod.svc.cluster.local
{{}} {{}}
To control routing for traffic bound to services outside the mesh, external services must first be added to Istio’s internal service registry using the ServiceEntry resource. VirtualServices can then be defined to control traffic bound to these external services. For example, the following rules define a Service for wikipedia.org and set a timeout of 5s for HTTP requests.
{{
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
name: external-svc-wikipedia
spec:
hosts:
- wikipedia.org
location: MESH_EXTERNAL
ports:
- number: 80
name: example-http
protocol: HTTP
resolution: DNS
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: my-wiki-rule
spec:
hosts:
- wikipedia.org
http:
- timeout: 5s
route:
- destination:
host: wikipedia.org
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: ServiceEntry
metadata:
name: external-svc-wikipedia
spec:
hosts:
- wikipedia.org
location: MESH_EXTERNAL
ports:
- number: 80
name: example-http
protocol: HTTP
resolution: DNS
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: my-wiki-rule
spec:
hosts:
- wikipedia.org
http:
- timeout: 5s
route:
- destination:
host: wikipedia.org
{{}} {{}}
Describes match conditions and actions for routing HTTP/1.1, HTTP2, and gRPC traffic. See VirtualService for usage examples.
Describes the delegate VirtualService.
The following routing rules forward the traffic to /productpage
by a delegate VirtualService named productpage
,
forward the traffic to /reviews
by a delegate VirtualService named reviews
.
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: bookinfo
spec:
hosts:
- "bookinfo.com"
gateways:
- mygateway
http:
- match:
- uri:
prefix: "/productpage"
delegate:
name: productpage
namespace: nsA
- match:
- uri:
prefix: "/reviews"
delegate:
name: reviews
namespace: nsB
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: productpage
namespace: nsA
spec:
http:
- match:
- uri:
prefix: "/productpage/v1/"
route:
- destination:
host: productpage-v1.nsA.svc.cluster.local
- route:
- destination:
host: productpage.nsA.svc.cluster.local
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews
namespace: nsB
spec:
http:
- route:
- destination:
host: reviews.nsB.svc.cluster.local
Message headers can be manipulated when Envoy forwards requests to,
or responses from, a destination service. Header manipulation rules can
be specified for a specific route destination or for all destinations.
The following VirtualService adds a test
header with the value true
to requests that are routed to any reviews
service destination.
It also romoves the foo
response header, but only from responses
coming from the v1
subset (version) of the reviews
service.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- headers:
request:
set:
test: true
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v2
weight: 25
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
headers:
response:
remove:
- foo
weight: 75
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- headers:
request:
set:
test: true
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v2
weight: 25
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
headers:
response:
remove:
- foo
weight: 75
{{}} {{}}
Describes match conditions and actions for routing unterminated TLS traffic (TLS/HTTPS) The following routing rule forwards unterminated TLS traffic arriving at port 443 of gateway called “mygateway” to internal services in the mesh based on the SNI value.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: bookinfo-sni
spec:
hosts:
- "*.bookinfo.com"
gateways:
- mygateway
tls:
- match:
- port: 443
sniHosts:
- login.bookinfo.com
route:
- destination:
host: login.prod.svc.cluster.local
- match:
- port: 443
sniHosts:
- reviews.bookinfo.com
route:
- destination:
host: reviews.prod.svc.cluster.local
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: bookinfo-sni
spec:
hosts:
- "*.bookinfo.com"
gateways:
- mygateway
tls:
- match:
- port: 443
sniHosts:
- login.bookinfo.com
route:
- destination:
host: login.prod.svc.cluster.local
- match:
- port: 443
sniHosts:
- reviews.bookinfo.com
route:
- destination:
host: reviews.prod.svc.cluster.local
{{}} {{}}
Describes match conditions and actions for routing TCP traffic. The following routing rule forwards traffic arriving at port 27017 for mongo.prod.svc.cluster.local to another Mongo server on port 5555.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: bookinfo-Mongo
spec:
hosts:
- mongo.prod.svc.cluster.local
tcp:
- match:
- port: 27017
route:
- destination:
host: mongo.backup.svc.cluster.local
port:
number: 5555
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: bookinfo-Mongo
spec:
hosts:
- mongo.prod.svc.cluster.local
tcp:
- match:
- port: 27017
route:
- destination:
host: mongo.backup.svc.cluster.local
port:
number: 5555
{{}} {{}}
HttpMatchRequest specifies a set of criterion to be met in order for the
rule to be applied to the HTTP request. For example, the following
restricts the rule to match only requests where the URL path
starts with /ratings/v2/ and the request contains a custom end-user
header
with value jason
.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- match:
- headers:
end-user:
exact: jason
uri:
prefix: "/ratings/v2/"
ignoreUriCase: true
route:
- destination:
host: ratings.prod.svc.cluster.local
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- match:
- headers:
end-user:
exact: jason
uri:
prefix: "/ratings/v2/"
ignoreUriCase: true
route:
- destination:
host: ratings.prod.svc.cluster.local
{{}} {{}}
HTTPMatchRequest CANNOT be empty. Note: No regex string match can be set when delegate VirtualService is specified.
Each routing rule is associated with one or more service versions (see glossary in beginning of document). Weights associated with the version determine the proportion of traffic it receives. For example, the following rule will route 25% of traffic for the “reviews” service to instances with the “v2” tag and the remaining traffic (i.e., 75%) to “v1”.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v2
weight: 25
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
weight: 75
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v2
weight: 25
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
weight: 75
{{}} {{}}
And the associated DestinationRule
{{
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: reviews-destination
spec:
host: reviews.prod.svc.cluster.local
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: reviews-destination
spec:
host: reviews.prod.svc.cluster.local
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
{{}} {{}}
Traffic can also be split across two entirely different services without having to define new subsets. For example, the following rule forwards 25% of traffic to reviews.com to dev.reviews.com
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews-route-two-domains
spec:
hosts:
- reviews.com
http:
- route:
- destination:
host: dev.reviews.com
weight: 25
- destination:
host: reviews.com
weight: 75
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews-route-two-domains
spec:
hosts:
- reviews.com
http:
- route:
- destination:
host: dev.reviews.com
weight: 25
- destination:
host: reviews.com
weight: 75
{{}} {{}}
L4 routing rule weighted destination.
L4 connection match attributes. Note that L4 connection matching support is incomplete.
TLS connection match attributes.
HTTPRedirect can be used to send a 301 redirect response to the caller, where the Authority/Host and the URI in the response can be swapped with the specified values. For example, the following rule redirects requests for /v1/getProductRatings API on the ratings service to /v1/bookRatings provided by the bookratings service.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- match:
- uri:
exact: /v1/getProductRatings
redirect:
uri: /v1/bookRatings
authority: newratings.default.svc.cluster.local
...
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- match:
- uri:
exact: /v1/getProductRatings
redirect:
uri: /v1/bookRatings
authority: newratings.default.svc.cluster.local
...
{{}} {{}}
HTTPRewrite can be used to rewrite specific parts of a HTTP request before forwarding the request to the destination. Rewrite primitive can be used only with HTTPRouteDestination. The following example demonstrates how to rewrite the URL prefix for api call (/ratings) to ratings service before making the actual API call.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- match:
- uri:
prefix: /ratings
rewrite:
uri: /v1/bookRatings
route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- match:
- uri:
prefix: /ratings
rewrite:
uri: /v1/bookRatings
route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
{{}} {{}}
Describes how to match a given string in HTTP headers. Match is case-sensitive.
Describes the retry policy to use when a HTTP request fails. For example, the following rule sets the maximum number of retries to 3 when calling ratings:v1 service, with a 2s timeout per retry attempt.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
retries:
attempts: 3
perTryTimeout: 2s
retryOn: gateway-error,connect-failure,refused-stream
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
retries:
attempts: 3
perTryTimeout: 2s
retryOn: gateway-error,connect-failure,refused-stream
{{}} {{}}
Describes the Cross-Origin Resource Sharing (CORS) policy, for a given
service. Refer to CORS
for further details about cross origin resource sharing. For example,
the following rule restricts cross origin requests to those originating
from example.com domain using HTTP POST/GET, and sets the
Access-Control-Allow-Credentials
header to false. In addition, it only
exposes X-Foo-bar
header and sets an expiry period of 1 day.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
corsPolicy:
allowOrigin:
- example.com
allowMethods:
- POST
- GET
allowCredentials: false
allowHeaders:
- X-Foo-Bar
maxAge: "24h"
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
corsPolicy:
allowOrigin:
- example.com
allowMethods:
- POST
- GET
allowCredentials: false
allowHeaders:
- X-Foo-Bar
maxAge: "24h"
{{}} {{}}
HTTPFaultInjection can be used to specify one or more faults to inject while forwarding HTTP requests to the destination specified in a route. Fault specification is part of a VirtualService rule. Faults include aborting the Http request from downstream service, and/or delaying proxying of requests. A fault rule MUST HAVE delay or abort or both.
Note: Delay and abort faults are independent of one another, even if both are specified simultaneously.
PortSelector specifies the number of a port to be used for matching or selection for final routing.
Percent specifies a percentage in the range of [0.0, 100.0].
HeaderOperations Describes the header manipulations to apply
Delay specification is used to inject latency into the request forwarding path. The following example will introduce a 5 second delay in 1 out of every 1000 requests to the “v1” version of the “reviews” service from all pods with label env: prod
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- match:
- sourceLabels:
env: prod
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
fault:
delay:
percentage:
value: 0.1
fixedDelay: 5s
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews-route
spec:
hosts:
- reviews.prod.svc.cluster.local
http:
- match:
- sourceLabels:
env: prod
route:
- destination:
host: reviews.prod.svc.cluster.local
subset: v1
fault:
delay:
percentage:
value: 0.1
fixedDelay: 5s
{{}} {{}}
The fixedDelay field is used to indicate the amount of delay in seconds. The optional percentage field can be used to only delay a certain percentage of requests. If left unspecified, all request will be delayed.
Abort specification is used to prematurely abort a request with a pre-specified error code. The following example will return an HTTP 400 error code for 1 out of every 1000 requests to the “ratings” service “v1”.
{{
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
fault:
abort:
percentage:
value: 0.1
httpStatus: 400
{{}}
{{
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: ratings-route
spec:
hosts:
- ratings.prod.svc.cluster.local
http:
- route:
- destination:
host: ratings.prod.svc.cluster.local
subset: v1
fault:
abort:
percentage:
value: 0.1
httpStatus: 400
{{}} {{}}
The httpStatus field is used to indicate the HTTP status code to return to the caller. The optional percentage field can be used to only abort a certain percentage of requests. If not specified, all requests are aborted.
Wrapper message for uint32
.
The JSON representation for UInt32Value
is JSON number.


HTTP Feature Testing
Feature testing allows you to view the results of a single call to your application. This might be returning the results of a single web form, hitting an API endpoint, and more. This is handy because it allows you to test the entire life-cycle of a single request, ensuring that the routing works, the response is the correct format, analyze the results, and more.
The Test Class
Feature testing requires that all of your test classes use the CodeIgniter\Test\DatabaseTestTrait
and CodeIgniter\Test\FeatureTestTrait
traits. Since these testing tools rely on proper database
staging you must always ensure that parent::setUp()
and parent::tearDown()
are called if you implement your own methods.
<?php
namespace App;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;
class TestFoo extends CIUnitTestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;
protected function setUp(): void
{
parent::setUp();
$this->myClassMethod();
}
protected function tearDown(): void
{
parent::tearDown();
$this->anotherClassMethod();
}
}
Requesting a Page
Essentially, feature tests simply allows you to call an endpoint on your application and get the results back.
To do this, you use the call()
method.
The first parameter is the HTTP method to use (most frequently either GET or POST).
The second parameter is the URI path on your site to test.
The third parameter
$params
accepts an array that is used to populate the superglobal variables for the HTTP verb you are using. So, a method of GET would have the $_GET variable populated, while a POST request would have the $_POST array populated. The$params
is also used in Formatting the Request.Note
The
$params
array does not make sense for every HTTP verb, but is included for consistency.
<?php
// Get a simple page
$result = $this->call('get', '/');
// Submit a form
$result = $this->call('post', 'contact', [
'name' => 'Fred Flintstone',
'email' =><EMAIL_ADDRESS>]);
Shorthand Methods
Shorthand methods for each of the HTTP verbs exist to ease typing and make things clearer:
<?php
$this->get($path, $params);
$this->post($path, $params);
$this->put($path, $params);
$this->patch($path, $params);
$this->delete($path, $params);
$this->options($path, $params);
Setting Different Routes
You can use a custom collection of routes by passing an array of “routes” into the withRoutes()
method. This will
override any existing routes in the system:
<?php
$routes = [
['get', 'users', 'UserController::list'],
];
$result = $this->withRoutes($routes)->get('users');
Each of the “routes” is a 3 element array containing the HTTP verb (or “add” for all), the URI to match, and the routing destination.
Setting Session Values
You can set custom session values to use during a single test with the withSession()
method. This takes an array
of key/value pairs that should exist within the $_SESSION
variable when this request is made, or null
to indicate
that the current values of $_SESSION
should be used. This is handy for testing authentication and more.
<?php
$values = [
'logged_in' => 123,
];
$result = $this->withSession($values)->get('admin');
// Or...
$_SESSION['logged_in'] = 123;
$result = $this->withSession()->get('admin');
Setting Headers
You can set header values with the withHeaders()
method. This takes an array of key/value pairs that would be
passed as a header into the call:
<?php
$headers = [
'CONTENT_TYPE' => 'application/json',
];
$result = $this->withHeaders($headers)->post('users');
Bypassing Events
Events are handy to use in your application, but can be problematic during testing. Especially events that are used
to send out emails. You can tell the system to skip any event handling with the skipEvents()
method:
<?php
$result = $this->skipEvents()->post('users', $userInfo);
Formatting the Request
You can set the format of your request’s body using the withBodyFormat()
method. Currently this supports either
json
or xml
.
This is useful when testing JSON or XML APIs so that you can set the request in the form that the controller will expect.
This will take the parameters passed into call()
, post()
, get()
… and assign them to the
body of the request in the given format.
This will also set the Content-Type header for your request accordingly.
<?php
// If your feature test contains this:
$result = $this->withBodyFormat('json')->post('users', $userInfo);
// Your controller can then get the parameters passed in with:
$userInfo = $this->request->getJson();
Setting the Body
You can set the body of your request with the withBody()
method. This allows you to format the body how you want
to format it. It is recommended that you use this if you have more complicated XMLs to test.
This will not set
the Content-Type header for you. If you need that, you can set it with the withHeaders()
method.
Checking the Response
FeatureTestTrait::call()
returns an instance of a TestResponse
. See Testing Responses on
how to use this class to perform additional assertions and verification in your test cases.


QUnit example
test markup, will be hidden
aaaaaaaaaaaa
bbbbbbbbbbbb
cccccccccccc
dddddddddddd
eeeeeeeeeeee
ffffffffffff
gggggggggggg
hhhhhhhhhhhh
iiiiiiiiiiii
jjjjjjjjjjjj
kkkkkkkkkkkk
llllllllllll
mmmmmmmmmmmm
nnnnnnnnnnnn
oooooooooooo
pppppppppppp
qqqqqqqqqqqq
rrrrrrrrrrrr
ssssssssssss
tttttttttttt
uuuuuuuuuuuu
vvvvvvvvvvvv
wwwwwwwwwwww
xxxxxxxxxxxx
yyyyyyyyyyyy
zzzzzzzzzzzz
aaaaaaaaaaaa
bbbbbbbbbbbb
cccccccccccc
dddddddddddd
eeeeeeeeeeee
ffffffffffff
111111111111


public class GameMap
extends Observable
| Modifier and Type | Field and Description |
|---|---|
private static int |
armiesTradedForSet
Number of armies traded in for each set
|
private Map<String,Set<String>> |
borders
Stores an adjacency list of all borders.
|
private Map<String,Continent> |
continents
Stores a map of all continents.
|
private Map<String,Country> |
countries
Stores a map of all countries.
|
private Context |
currentContext
The current phase of the game.
|
private static int |
currentPlayerIndex
Maintains whose turn it is (index).
|
ArrayList<Card> |
deck
This maintains a list of RISK cards in the deck.
|
private String |
fileName
The name of the map file.
|
private ArrayList<String> |
fileSectionData
Contains the information in the [File] section.
|
static GameMap |
gameMap
The singleton instance of the game's state
|
static boolean |
isGameOver
check if the game finishes
|
private boolean |
isMapTypeDomination
The type of the map, true if domination false for conquest
|
private boolean |
isSavePossible
variable that indicates if savegame command is possible
|
static int |
numberOfRounds
number of rounds in a game
|
private static int |
numberOfTradedSet
Maintains the number of sets traded in game
|
static int |
numOfTurns
variable to store number of turns
|
StringBuilder |
phaseLog
This maintains a log of phase-wise activity in the game
|
ArrayList<Player> |
playersList
This maintains a list of players currently in the game.
|
private static Random |
randomGenerator
random Generator for the game
|
| Constructor and Description |
|---|
GameMap()
The constructor for the GameMap.
|
| Modifier and Type | Method and Description |
|---|---|
boolean |
addBorder(String country1,
String country2)
Adds a border between two countries making them neighbors
|
boolean |
addContinent(String continentName,
int value)
Add a continent to the gameMap
|
boolean |
addCountry(String countryName,
String continentName)
Adds a country to the game map
|
boolean |
addGamePlayer(String playerName,
String strategy)
Adds a game player to the current state
|
void |
assignCard()
Assigns a random card to the player from the deck
|
static void |
buildDeck(GameMap gameMap)
Builds the deck of RISK cards
|
boolean |
checkGameReady()
Checks if the setup is complete and the game is ready to begin
|
static void |
destroyGameMap()
Destroys the GameMap object resetting the state.
|
boolean |
equals(Object o)
Checks whether one GameMap object is equal to another.
|
boolean |
gameSetup()
Sets up the army count for each payer, populates countries
|
static int |
getArmiesTradedForSet()
Gets the number of armies traded for a card set.
|
Map<String,Set<String>> |
getBorders()
This method returns all the borders.
|
Map<String,Continent> |
getContinents()
This method returns a Map object with all the continents.
|
Map<String,Country> |
getCountries()
Returns a Map object of countries.
|
Set<String> |
getCountriesByContinent(String continentName)
Get all countries in a continent
|
Context |
getCurrentContext()
Returns the current context
|
Player |
getCurrentPlayer()
A getter for the current player object.
|
static int |
getCurrentPlayerIndex()
Gets the current player's index in the list.
|
ArrayList<Card> |
getDeck()
Returns the Deck of cards.
|
String |
getFileName()
Returns the name of the file.
|
ArrayList<String> |
getFileSectionData()
Returns a section parsed from the file.
|
static GameMap |
getGameMap()
A method to get the existing instance of gameMap, or creating one if it doesn't exist.
|
boolean |
getIsSavePossible()
Getter for isSavePossible
|
static int |
getNumberOfTradedSet()
Returns the number of card sets traded in.
|
static int |
getNumOfTurns()
getter for number of turns
|
String |
getPhaseLog()
Returns the messages logged for the phase.
|
ArrayList<Player> |
getPlayersList()
Gets current playerlist from the game state
|
static Random |
getRandomGenerator()
getter for random generator
|
int |
hashCode() |
boolean |
isMapTypeDomination()
getter for map type
|
static void |
modifyInstance(GameMap gameMap)
Setter for GameMap instance, used in case a map is loaded from file.
|
boolean |
placeAll()
Places army one at a time randomly to each player owned countries in round robin fashion
|
boolean |
placeArmy(String countryName,
int numArmies)
This method places an army in a country that the player owns
|
Map<String,Country> |
populateCountries(ArrayList<Player> playerList)
This method randomly populates all the countries on the map.
|
void |
populateGameMap(ArrayList<String> fileSectionData,
Map<String,Set<String>> borders,
Map<String,Continent> continents,
Map<String,Country> countries,
String fileName)
This is the constructor for the GameMap class.
|
boolean |
removeBorder(String country1,
String country2)
Removes a border between two countries
|
boolean |
removeContinent(String continentName)
Removes a continent and all its countries from the gameMap
|
boolean |
removeCountry(String countryName)
Removes a country from the game map
|
void |
removeCountryBorders(String countryName)
Removes all borders that a country is part of
|
boolean |
removeGamePlayer(String playerName)
Removes a game player from the current models.state
|
static void |
setArmiesTradedForSet(int armiesTradedForSet)
Sets the number of armies traded for a card set.
|
void |
setBorders(Map<String,Set<String>> borders)
This sets the borders instance variable for the game map class.
|
void |
setContinents(Map<String,Continent> continents)
This method sets the continents object for the GameMap class.
|
void |
setCountries(Map<String,Country> countries)
Sets the countries instance variable for the GameMap
|
void |
setCurrentContext(Context currentContext)
Sets the current context
|
static void |
setCurrentPlayerIndex(int currentPlayerIndex)
Setter for currentPlayerIndex
|
void |
setDeck(ArrayList<Card> deck)
Sets the deck object.
|
void |
setFileName(String fileName)
Sets the name of the map file.
|
void |
setFileSectionData(ArrayList<String> fileSectionData)
Sets the fileSectionData variable for the GameMap class.
|
void |
setIsSavePossible(boolean isSavePossible)
Setter for isSavePossible
|
void |
setMapTypeDomination(boolean mapTypeDomination)
setter for map type
|
static void |
setNumberOfTradedSet(int numberOfTradedSet)
Sets the number of card sets traded in.
|
void |
setNumOfTurns(int numOfTurns)
Setter for numOfTurns
|
void |
setPhaseLog(String phaseLog,
boolean flushLog)
Sets the log.
|
void |
setPlayersList(ArrayList<Player> playersList)
Sets playerList to the game state
|
static void |
setRandomGenerator(long randomGeneratorSeed)
Setter for random generator seed
|
String |
showBorderByOwnerShip(Map.Entry<String,Set<String>> border)
Displays all the borders of the game map by ownership
|
static String |
showBorders(Map.Entry<String,Set<String>> border)
Displays all the borders of the game map.
|
void |
showMapByContinents()
Displays the map grouped by continents.
|
String |
showMapByOwnership() |
String |
showMapByOwnershipByCurrentPlayer(String currentPlayer)
This method shows the map for the fortify and reinforce phases
|
String |
toString()
Pretty prints the game map.
|
void |
updatePlayerIndex()
Updates the current player index (round robin fashion)
|
boolean |
validatePlayerCount()
Validates the count of players in the game.
|
public static GameMap gameMap
public static int numberOfRounds
public static boolean isGameOver
public static int numOfTurns
private static int currentPlayerIndex
private static int numberOfTradedSet
private static int armiesTradedForSet
private static Random randomGenerator
public ArrayList<Player> playersList
public StringBuilder phaseLog
public ArrayList<Card> deck
private ArrayList<String> fileSectionData
private Map<String,Set<String>> borders
private Map<String,Continent> continents
private Map<String,Country> countries
private String fileName
private Context currentContext
private boolean isMapTypeDomination
private boolean isSavePossible
public static int getNumberOfTradedSet()
public static void setNumberOfTradedSet(int numberOfTradedSet)
numberOfTradedSet
- An integer.public static int getArmiesTradedForSet()
public static void setArmiesTradedForSet(int armiesTradedForSet)
armiesTradedForSet
- An integer.public static int getCurrentPlayerIndex()
public static void setCurrentPlayerIndex(int currentPlayerIndex)
currentPlayerIndex
- index of the player to set topublic static int getNumOfTurns()
public void setNumOfTurns(int numOfTurns)
numOfTurns
- int to set the number of turns topublic static Random getRandomGenerator()
public static void setRandomGenerator(long randomGeneratorSeed)
randomGeneratorSeed
- Random object generator seedpublic static void buildDeck(GameMap gameMap)
gameMap
- The GameMap object to save.public static GameMap getGameMap()
public static void destroyGameMap()
public static void modifyInstance(GameMap gameMap)
gameMap
- contains game statepublic static String showBorders(Map.Entry<String,Set<String>> border)
border
- The adjacency list of each borderpublic boolean isMapTypeDomination()
public void setMapTypeDomination(boolean mapTypeDomination)
mapTypeDomination
- boolean for appropriate map typepublic void populateGameMap(ArrayList<String> fileSectionData, Map<String,Set<String>> borders, Map<String,Continent> continents, Map<String,Country> countries, String fileName)
fileSectionData
- Contains the information in the [File] section.borders
- Stores an adjacency list of all borders.continents
- Stores a map of all continents.countries
- Stores a map of all countries.fileName
- contains map namepublic ArrayList<Card> getDeck()
public void setDeck(ArrayList<Card> deck)
deck
- A collection of Card objects.public void updatePlayerIndex()
public Player getCurrentPlayer()
public String showBorderByOwnerShip(Map.Entry<String,Set<String>> border)
border
- The adjacency list of each borderpublic void showMapByContinents()
public Set<String> getCountriesByContinent(String continentName)
continentName
- name of the continentpublic boolean addContinent(String continentName, int value)
continentName
- continent to addvalue
- control value of continentpublic boolean removeContinent(String continentName)
continentName
- continent to removepublic boolean addCountry(String countryName, String continentName)
countryName
- country to addcontinentName
- continent the country belongs topublic boolean removeCountry(String countryName)
countryName
- country to removepublic boolean addBorder(String country1, String country2)
country1
- neighboring country 1country2
- neighboring country 2public boolean removeBorder(String country1, String country2)
country1
- neighboring country 1country2
- neighboring country 2public void removeCountryBorders(String countryName)
countryName
- country whose borders are to be removedpublic String toString()
toString
in class Object
public String showMapByOwnership()
public boolean addGamePlayer(String playerName, String strategy)
playerName
- player to addstrategy
- player's strategy (aggressive,human,benevolent,random,cheater)public boolean removeGamePlayer(String playerName)
playerName
- player to addpublic Map<String,Set<String>> getBorders()
public void setBorders(Map<String,Set<String>> borders)
borders
- A Map, consisting of the country name and the adjacency of borders.public Map<String,Continent> getContinents()
public void setContinents(Map<String,Continent> continents)
continents
- A Map object, mapping the name with the Continent object.public ArrayList<String> getFileSectionData()
public void setFileSectionData(ArrayList<String> fileSectionData)
fileSectionData
- An ArrayList with file sections as strings.public String getFileName()
public void setFileName(String fileName)
fileName
- the name of the file.public Map<String,Country> getCountries()
public void setCountries(Map<String,Country> countries)
countries
- a Map object of country names and Country objects.public ArrayList<Player> getPlayersList()
public void setPlayersList(ArrayList<Player> playersList)
playersList
- list of playerspublic Map<String,Country> populateCountries(ArrayList<Player> playerList)
playerList
- list of players in the gamepublic boolean validatePlayerCount()
public boolean gameSetup()
public void assignCard()
public boolean placeArmy(String countryName, int numArmies)
countryName
- name of the country to place an armynumArmies
- armies to placepublic boolean checkGameReady()
public boolean placeAll()
public String showMapByOwnershipByCurrentPlayer(String currentPlayer)
currentPlayer
- name of the current playerpublic boolean equals(Object o)
equals
in class Object
public int hashCode()
hashCode
in class Object
public Context getCurrentContext()
public void setCurrentContext(Context currentContext)
currentContext
- the context to be setpublic String getPhaseLog()
public void setPhaseLog(String phaseLog, boolean flushLog)
phaseLog
- the String to append to the log.flushLog
- whether the log should be cleared.public boolean getIsSavePossible()
public void setIsSavePossible(boolean isSavePossible)
isSavePossible
- true if save is allowed false if it isnt


The bluebird wore yellow rain boots and carried a red umbrella. In the old days, you could find him on the roof of the goat barn dancing a jig and wearing a thimble for a hat. Once, my brother and I spied him on the steering wheel of a ‘49 Ford tractor singing an aria from Purcell’s “The Fairy-Queen.” When he discovered our inquisitive eyes, he smiled and blushed at the same time. We dreamed we’d sell tickets and astonish our friends but never made one crinkled dollar once the farm cat spun him into a whirl of blue feathers.
This was created on 9/17/2016


I'm Durgesh Kumar a second year undergradute in Indian Institute of Technology, Roorkee having major's of Civil Engineering (India's best civil engineering department).
As my intrest lies around Computational Development, Research and Artificial Intelligance which drown me into the sea of binary world(me and my tech).
During my journey, I acquired the knowledge about Software Development, Web Development, Linux Architecture and shell scripts, Artificial Intelligence and Data Science, Computational Biology and Physics, Competitive programming and mathematics.
I'm working on various different projects in Computational Biology Lab at IIT Roorkee, under the supervision of Dr. Deepak Sharma, member of three groups in IIT Roorkee and volunteered many events and summits.


[name]
Supporting classes for file loaders and web worker based loaders.
Sub-Classes
[page:LoaderSupport.Builder]
[page:LoaderSupport.LoadedMeshUserOverride]
[page:LoaderSupport.WorkerSupport]
[page:LoaderSupport.WorkerRunnerRefImpl]
[page:LoaderSupport.WorkerDirector]
[page:LoaderSupport.PrepData]
[page:LoaderSupport.Commons]
[page:LoaderSupport.Callbacks]
[page:LoaderSupport.Validator]
[page:LoaderSupport.ConsoleLogger]
Example
[example:webgl_loader_obj2_meshspray] - Example using [page:LoaderSupport.LoaderWorkerDirector] and [page:LoaderSupport.LoaderWorkerSupport].
Classes
Builder
Constructor
Builder()
Builds one or many [page:Mesh] from one raw set of Arraybuffers, materialGroup descriptions and further parameters.
Supports vertex, vertexColor, normal, uv and index buffers.
Methods
[method:null setMaterials] ( Array of [page:Material materials] )
Array of [page:Material materials] - Array of [page:Material Materials]
Set materials loaded by any supplier of an Array of [page:Material Materials].
[method:Array buildMeshes] (Object payload)
[page:Object payload] - Raw mesh description (buffers, params, materials) used to build one to many meshes.
Builds one or multiple meshes from the data described in the payload (buffers, params, material info.
LoadedMeshUserOverride
Constructor
LoadedMeshUserOverride( [page:Boolean disregardMesh], [page:BufferGeometry bufferGeometry] )
[page:Boolean disregardMesh] - Tell implementation to completely disregard this mesh
[page:Boolean alteredMesh] - Tell implementation that mesh(es) have been altered or added
Object to return by callback onMeshAlter. Used to disregard a certain mesh or to return one to many meshes.
Methods
[method:null addMesh] ( [page:Mesh mesh] )
[page:Mesh mesh] - Mesh
Add a mesh created within callback.
[method:boolean isDisregardMesh] ()
Answers if mesh shall be disregarded completely.
[method:boolean providesAlteredMeshes] ()
Answers if new mesh(es) were created.
WorkerSupport
Constructor
WorkerSupport( [page:LoaderSupport.ConsoleLogger logger] )
[page:LoaderSupport.ConsoleLogger logger] - logger to be used
This class provides means to transform existing parser code into a web worker.
It defines a simple communication protocol which allows to configure the worker and receive raw mesh data during execution.
Methods
[method:null validate] ( [page:Function functionCodeBuilder], [page:Boolean forceWorkerReload], [page:LoaderSupport.WorkerRunnerRefImpl runnerImpl] )
[page:Function functionCodeBuilder] - Function that is invoked with funcBuildObject and funcBuildSingelton that allows stringification of objects and singletons.
[page:Boolean forceWorkerReload] - Force re-build of the worker code.
[page:LoaderSupport.WorkerRunnerRefImpl runnerImpl] - The default worker parser wrapper implementation (communication and execution). An extended class could be passed here.
Validate the status of worker code and the derived worker.
[method:null setTerminateRequested] ( [page:Boolean terminateRequested] )
[page:Boolean terminateRequested] - True or false.
Request termination of worker once parser is finished.
[method:null terminateWorker] ()
Terminate the worker and the code.
[method:null setCallbacks] ( [page:Function builder], [page:Function onLoad] )
[page:Function builder] - The builder function. Default is [page:LoaderSupport.Builder].
[page:Function onLoad] - The function that is called when parsing is complete.
Specify functions that should be build when new raw mesh data becomes available and when the parser is finished.
[method:null run] ( [page:Object payload] )
[page:Object payload] - Raw mesh description (buffers, params, materials) used to build one to many meshes.
Runs the parser with the provided configuration.
WorkerRunnerRefImpl
Constructor
WorkerRunnerRefImpl()
Default implementation of the WorkerRunner responsible for creation and configuration of the parser within the worker.
Methods
[method:null applyProperties] ( [page:Object parser], [page:Object params] )
[page:Object parser] - The parser instance
[page:Object params] - The parameter object
Applies values from parameter object via set functions or via direct assignment.
[method:null run] ( [page:Object payload] )
[page:Object payload] - Raw mesh description (buffers, params, materials) used to build one to many meshes.
Configures the Parser implementation according the supplied configuration object.
WorkerDirector
Constructor
WorkerDirector( [page:String classDef], [page:LoaderSupport.ConsoleLogger logger] )
[page:String classDef] - Class definition to be used for construction
[page:LoaderSupport.ConsoleLogger logger] - logger to be used
Orchestrate loading of multiple OBJ files/data from an instruction queue with a configurable amount of workers (1-16).
- Workflow:
- prepareWorkers
- enqueueForRun
- processQueue
- deregister
Methods
[method:null prepareWorkers]( [page:WWOBJLoader2.Callbacks globalCallbacks], [page:Number maxQueueSize], [page:Number maxWebWorkers] )
[page:LoaderSupport.Callbacks globalCallbacks] - Register global callbacks used by all web workers
[page:Number maxQueueSize] - Set the maximum size of the instruction queue (1-1024)
[page:Number maxWebWorkers] - Set the maximum amount of workers (1-16)
Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers.
[method:null enqueueForRun]( [page:LoaderSupport.PrepData runParams] )
[page:LoaderSupport.PrepData runParams]
Store run instructions in internal instructionQueue.
[method:null processQueue]()
Process the instructionQueue until it is depleted.
[method:null deregister]()
Terminate all workers.
[method:null getMaxQueueSize]()
Returns the maximum length of the instruction queue.
[method:null getMaxWebWorkers]()
Returns the maximum number of workers.
[method:null setCrossOrigin]( [page:String crossOrigin] )
[page:String crossOrigin] - CORS value
Sets the CORS string to be used.
PrepData
Constructor
PrepData( [page:String modelName] )
[page:String modelName] - Overall name of the model
Configuration instructions to be used by run method.
Methods
[method:null setStreamMeshesTo] ( [page:Object3D streamMeshesTo] )
[page:Object3D streamMeshesTo] - Object already attached to scenegraph where new meshes will be attached to
Set the node where the loaded objects will be attached directly.
[method:null setMaterialPerSmoothingGroup] ( [page:boolean materialPerSmoothingGroup] )
[page:boolean materialPerSmoothingGroup]
Tells whether a material shall be created per smoothing group.
[method:null setUseIndices]( [page:Boolean useIndices] )
[page:Boolean useIndices] - Default is false
Instructs loaders to create indexed [page:BufferGeometry].
[method:null setDisregardNormals]( [page:Boolean disregardNormals] )
[page:Boolean disregardNormals]
Tells whether normals should be completely disregarded and regenerated.
[method:Callbacks getCallbacks]()
Returns all callbacks as [page:LoaderSupport.Callbacks].
[method:null setCrossOrigin]( [page:String crossOrigin] )
[page:String crossOrigin] - CORS value
Sets the CORS string to be used.
[method:null addResource]( [page:LoaderSupport.ResourceDescriptor resource] )
[page:LoaderSupport.ResourceDescriptor resource]
Add a resource description.
[method:null setUseAsync]( [page:Boolean useAsync] )
[page:Boolean useAsync]
If true uses async loading with worker, if false loads data synchronously.
Commons
Constructor
Commons( [page:LoaderSupport.ConsoleLogger logger], [page:LoadingManager manager] )
[page:LoaderSupport.ConsoleLogger logger] - logger to be used
[page:LoadingManager manager] - The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Base class to be used by loaders.
Methods
[method:ConsoleLogger getLogger] ()
Returns [page:LoaderSupport.ConsoleLogger].
[method:null setModelName] ( [page:String modelName] )
[page:String modelName]
Set the name of the model.
[method:null setPath] ( [page:String path] )
[page:String path] - URL
The URL of the base path.
[method:null setStreamMeshesTo] ( [page:Object3D streamMeshesTo] )
[page:Object3D streamMeshesTo] - Object already attached to scenegraph where new meshes will be attached to
Set the node where the loaded objects will be attached directly.
[method:null setMaterials] ( Array of [page:Material materials] )
Array of [page:Material materials] - Array of [page:Material Materials]
Set materials loaded by MTLLoader or any other supplier of an Array of [page:Material Materials].
[method:null setUseIndices]( [page:Boolean useIndices] )
[page:Boolean useIndices]
Instructs loaders to create indexed [page:BufferGeometry].
[method:null setDisregardNormals]( [page:Boolean disregardNormals] )
[page:Boolean disregardNormals]
Tells whether normals should be completely disregarded and regenerated.
[method:null onProgress]( [page:String type], [page:String text], [page:Number numericalValue] )
[page:String type] - The type of event
[page:String text] - Textual description of the event
[page:Number numericalValue] - Numerical value describing the progress
Announce feedback which is give to the registered [page:LoaderSupport.Callbacks].
Callbacks
Constructor
Callbacks()
Callbacks utilized by loaders and builder.
Methods
[method:null setCallbackOnProgress]( [page:Function callbackOnProgress] )
[page:Function callbackOnProgress] - Callback function for described functionality
Register callback function that is invoked by internal function "announceProgress" to print feedback.
[method:null setCallbackOnMeshAlter]( [page:Function callbackOnMeshAlter] )
[page:Function callbackOnMeshAlter] - Callback function for described functionality
Register callback function that is called every time a mesh was loaded.
Use [page:LoadedMeshUserOverride] for alteration instructions (geometry, material or disregard mesh).
[method:null setCallbackOnLoad]( [page:Function callbackOnLoad] )
[page:Function callbackOnLoad] - Callback function for described functionality
Register callback function that is called once loading of the complete OBJ file is completed.
Validator
Constructor
Validator()
Validation functions.
Methods
[method:null isValid]( [page:Object input] )
[page:Object input] - Can be anything
If given input is null or undefined, false is returned otherwise true.
[method:null verifyInput]( [page:Object input], [page:Object defaultValue] )
[page:Object input] - Can be anything
[page:Object defaultValue] - Can be anything
If given input is null or undefined, the defaultValue is returned otherwise the given input.
ConsoleLogger
Constructor
ConsoleLogger( [page:Boolean enabled], [page:Boolean debug] )
[page:Boolean enabled] - Tell if logger is enabled.
[page:Boolean debug] - Toggle debug logging.
Logging wrapper for console.
Methods
[method:null setDebug]( [page:Boolean debug] )
[page:Boolean debug] - True or False
Enable or disable debug logging.
[method:Boolean isDebug]()
Returns if is enabled and debug.
[method:null setEnabled]( [page:Boolean enabled] )
[page:Boolean enabled] - True or False
Enable or disable info, debug and time logging.
[method:Boolean isEnabled]()
Returns if is enabled.
[method:null logDebug]( [page:String message] )
[page:String message] - Message to log
Log a debug message if enabled and debug is set.
[method:null logInfo]( [page:String message] )
[page:String message] - Message to log
Log an info message if enabled.
[method:null logWarn]( [page:String message] )
[page:String message] - Message to log
Log a warn message (always).
[method:null logError]( [page:String message] )
[page:String message] - Message to log
Log an error message (always).
[method:null logTimeStart]( [page:String id] )
[page:String id] - Time identification
Start time measurement with provided id.
[method:null logTimeEnd]( [page:String id] )
[page:String id] - Time identification
Stop time measurement started with provided id.
Source
[link:https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/LoaderSupport.js examples/js/loaders/LoaderSupport.js]


Welcome to Handshake
This is a flexml mock toolkit.
You can paste flexml's "package.json" file to change the locked package.
Please scan the QR code below with the playground app.
template output (compiled xml)


| COMP2521 17s2 |
Week 02 Lab Exercise Linked Lists, Performance |
Data Structures and Algorithms |
| Marks | 5=outstanding, 4=very good, 3=adequate, 2=sub-standard, 1=hopeless |
| Demo | in the Week02 Lab or in the Week03 Lab |
| Submit | give cs2521 lab02 IntList.c timing.txt or via WebCMS |
| Deadline | must be submitted by 11:59pm Sunday 06 August |
Note: you need to do something truly outstanding, above and beyond the "call of duty" to get 5 marks. Doing the exercise just as specified will generally get you 4-4.5 marks.
At the end of COMP1511, you dealt with linked lists. Over the break, you haven't forgotten linked lists (have you?), but a bit of revision never hurts, especially when many of the data structures we'll deal with later are based on linked lists. So ... on with this simple linked list exercise ...
To keep your files manageable, it's worth doing each lab exercise in a separate directory (folder). I'd suggest creating a subdirectory in your home directory called "cs2521", and then creating a subdirectory under that called "labs", and then subdirectories "week02", "week03", etc. Let's assume that the directory you finally set up for this lab is Week02LabDir.
Change into your Week02LabDir directory and run the following command:
$ unzip /home/cs2521/web/17s2/labs/week02/lab.zip
If you're working at home, download lab.zip by right-clicking on the above link and then run the above command on your local machine.
If you've done the above correctly, you should now find the following files in the directory:
| Makefile | a set of dependencies used to control compilation |
| IntList.h | interface definition for the IntList ADT |
| IntList.c | implementation for the IntList ADT |
| useIntList.c | main program for testing the IntList ADT |
| randList.c | main program for generating random sequences of numbers |
| timing.txt | template for your results file; you need to add more rows |
Before you start using these programs, it's worth looking at the code. Are there any constructs that you don't understand? Try to work them out with your lab partner, or ask your tutor.
Once you've understood the programs, the next thing to do is to run the command:
$ make
It's worth taking a look at the Makefile to see if you can work out what it's doing. Don't worry if you don't understand it all; we'll be taking a longer look at make in later labs. Note: you will need to run make to recompile the system each time you make changes to the source code file and are ready to test the program again.
The make command will produce messages about compiling with gcc and will eventually leave two executable files in your directory (along with some .o files).
You can run the usel command by typing the command name, followed by return. It will then patiently wait for you to type some numbers, and will store them in a list, display the list, then call the function that is supposed to sort the list, and then display the "sorted" list. Of course, this doesn't currently work, because the list sorting function is incomplete. You can, however, fake it by typing the numbers in in order, e.g.
$ ./usel -v
1 2 3 4
Here you type control-D to finish your input
Original:
1
2
3
4
Sorted:
1
2
3
4
When usel eventually works properly, this is the kind of output you'll expect to see ... except that you won't be giving it sorted lists as input. To see the existing behaviour on an unsorted list, type a few numbers not sorted in ascending order, e.g.
$ ./usel -v
1 3 2
Once again, you type control-D to finish your input
Original:
1
3
2
Sorted
1
3
2
usel: useIntList.c:20: main: Assertion `IntListIsSorted(myOtherList)' failed.
Aborted
If you omit the -v command-line parameter, the the usel program only displays the final sorted list (which is not yet sorted, of course).
$ ./usel
1 3 2
Once again, you type control-D to finish your input
1
3
2
usel: useIntList.c:20: main: Assertion `IntListIsSorted(myOtherList)' failed.
Aborted
Now it's time to play with the list generator. If you execute the command:
$ /.randl 10
it should display a list of 10 random numbers. If you run it again, you'll get a different list of random numbers. Enjoy generating small lists of random numbers until you are bored.
If you then execute the command:
$ ./randl 10 | ./usel
the randl command will generate 10 random numbers and give them to the usel command which will print the list of numbers twice (separated by the word Sorted) and then fail the assertion as above.
You can adjust the number of numbers that randl generates via the command-line argument, e.g.
$ ./randl 100 | less
will produce 100 random numbers. If you want to change the range of numbers produced (e.g. to only make numbers in the range 1..10) edit the randList.c code and add extra command-line arguments to set the range.
If you supply only one command-line argument, randl will generate a completely random (well, pseudo-random) sequence each time you run it. If you want to generate a large sequence of pseudo-random numbers, and be able to generate the same sequence consistently, you can use the second command-line argument to specify a seed for the random number generator. If you give the same seed each time you run randl, you'll get the same sequence each time. To see the difference between using and not using the second command-line argument, try the following commands:
$ ./randl 10 $ ./randl 10 $ ./randl 10 $ ./randl 10 13 $ ./randl 10 13 $ ./randl 10 13
The first three commands will generate different sequences. The second three commands all generate the same sequence.
While ./randl is useful for producing large amounts of data, you don't need to use ./randl to produce input to ./usel. An alternative is to use the echo command and enter the numbers yourself, e.g.
$ echo 5 4 3 2 1 | ./usel
Another alternative, which will be more useful for testing, is to use the seq command, in combination with the sort command, e.g.
$ seq 10 # gives 1 2 3 4 5 6 7 8 9 10 $ seq 10 | sort -n # gives 1 2 3 4 5 6 7 8 9 10 $ seq 10 | sort -nr # gives 10 9 8 7 6 5 4 3 2 1 $ seq 10 | sort -R # gives 1..10 in a random order
The -nr argument to the sort command tells it to treat the input as numbers and sort them in reverse order. The -R argument to the sort command tells it to put the input in random order. You can find more details about sort via the command man sort.
One thing to remember is that sort orders items lexically, not numerically, by default. The following pipeline may not produce what you expect. Try it.
$ seq 10 | sort
The IntListInsertInorder() function is incomplete. In fact, it's just a stub function that invokes the IntListInsert() function, which inserts the number, but not in order. You should re-write the IntListInsertInorder() function so that it takes an IntList and an integer and inserts the value into the appropriate place in the list, so that the list always remains sorted (in ascending order). The function should fail if the original list (before insertion) is not sorted. Don't forget to handle the cases of (a) empty list, (b) smallest value, (c) largest value, (d) second-smallest value, (e) second-largest value, (f) value somewhere in the middle. Why were these kinds of values chosen? Discuss with your partner and propose test cases that test these and any other cases that you can think of.
Make a directory called tests, and place files containing your test cases in that directory with one test case in each file. A useful name strategy is to call the test files 01, 02, etc. You could create test files in various ways, e.g.
$ mkdir tests
$ seq 10 | sort -R > tests/01
$ seq 10 | sort -nr > tests/02
$ randl 10 11 > tests/03
etc. etc. etc.
In order to check that your program is producing the correct results, you could compare it to the output of a known correct sorting program. The diff command can help here (see man diff for details). For example, you could put each test case in a file, then run both your usel program and the built-in sort command, save the results of each output in a file, and then compare the files using diff. If your program is correct, there should be no difference. The following shows an example of how to do this:
$ sort -n < tests/01 > tests/01.expected # generate correct result $ ./usel < tests/01 > tests/01.observed # generate *your* result $ diff tests/01.expected tests/01.observed # if correct, no output
If you produce a decent number of tests (10-20), as you should, then testing them one by one using the above is a bit tedious. You could simplify carrying out the testing by writing a small shell script like:
#!/bin/sh
for t in 01 02 03 04 05 ... and the rest of your test files
do
echo === Test $t ===
sort -n < tests/$t > tests/$t.expected
./usel < tests/$t > tests/$t.observed
diff tests/$t.expected tests/$t.observed
done
rm tests/*.expected tests/*.observed
If you put the above in a file called e.g. run_tests, and then run the command:
$ sh run_teststhe script will run all your test cases and any that fail will either produce an assertion message or show you the difference between your output and the expected output.
You will have some confidence that your IntListInsertInorder() function is working properly when, for all test cases, the assertions in useIntList.c no longer fail.
Once IntListInsertInorder() is working correctly, modify useIntList.c so that it behaves as a sorting program: it reads a list of numbers from its standard input, and writes a sorted version of the numbers to its standard output. This is a simple change to the existing program, and can be accomplished by commenting a couple of lines.
Recompile and check that the new version of usel behaves correctly. Once you're satisfied, run some tests to compare the time taken by usel with the time taken by the Unix sort command for the same task.
The first thing to do is to check that both commands are producing the same result (otherwise, it's not useful to compare them). Try the following commands:
$ ./randl 1000 > nums $ ./usel < nums > out1 $ sort -n < nums > out2 $ diff out1 out2
If the diff command gives no output, then the files have no difference (i.e. the observed output is he same as the expected output). If you try the above a number of times with different sets of numbers each time and get the same result, then you can be more confident that both commands are producing the same result. (However, you cannot be absolutely certain that they will always produce the same result for any input. Why not?)
Note that you need to use the -n option to sort because the default sorting order is lexcial, not numeric. If you don't use -n, then e.g. 111 is treated as being less than 12. (See man sort for details.)
The next thing to do is to devise a set of test cases and collect some timing data. There is a command called time that will produce the timing data for you. Use it as follows:
$ ./randl 100000 > nums $ time ./usel < nums > out1 $ time sort -n < nums > out2
As before, check that both commands are producing the same result. This time, however, you will also see output that contains some timing information (note that the output format may vary depending on which shell you're using):
| user time | time spent executing the code of the command |
| system time | time spent executing system operations, such as input/output |
| elapsed/real time | wall-clock time between when the command starts and finishes |
The elapsed/real time is affected by the load on the machine, and so is not reliable. The system time should be similar for both commands (same amount of input/output). The value that's most useful is the user time, which represents the time that the program spent doing computation. Note that the time will vary if you run the same command multiple times. This is because the timing uses sampling and may sample the program at different points during the different executions. Collect results from a number of executions on the same output and take an average.
You will need to use large numbers of values (large argument to randl) to observe any appreciable difference. Of course, if you use very large numbers of values, the nums file may become too large to store in your directory. In this case, you could store nums under the /tmp directory:
$ ./randl 10000 > /tmp/nums $ time ./usel < /tmp/nums > /tmp/out1 $ time sort -n < /tmp/nums > /tmp/out2 $ diff /tmp/out1 /tmp/out2
It would also be worth taking your /tmp/nums file and modifying it to check the timings for sorted and reverse sorted inputs:
$ sort -n /tmp/nums > alreadySortedWithDuplicates $ sort -nr /tmp/nums > reverseSortedWithDuplicates
As well as lists produced by randl, it would be worth trying lists produced using the seq/sort combinations mentioned above. These will be different to the lists produced by randl in that they won't have any duplicate values. For example, you could generate data files like:
$ seq 10000 > alreadySortedNoDuplicates $ seq 10000 | sort -nr > reverseSortedNoDuplicates $ seq 10000 | sort -R > randomOrderNoDuplicates
and use these in place of /tmp/nums to generate more timing data.
Once the data files get big enough, and once you've checked that both programs are producing the same output for a wide selection of cases, you can avoid generating and comparing large output files by running the timing commands as follows:
$ time ./usel < /tmp/nums > /dev/null $ time sort -n < /tmp/nums > /dev/null
The above commands do all of the computation that we want to measure, but send their very large output to the Unix/Linux "data sink" (/dev/null), so it never takes up space on the file system.
If you do write results to files, don't forget to remove them after you've finished the lab.
You should take note of the timing output and build a collection of test results for different sizes/types of input and determine roughly the point at which it becomes impractical to use usel as a sort program (rather than using the Unix sort command).
You'll find that the timing data for relatively small lists (e.g. up to 10000) doesn't show much difference between usel and sort, and shows time pretty close to zero. Try using list sizes such as 5000, 10000, 20000, 50000, 100000, and as high as you dare to go after that. Also, try varying the kinds of input that you supply. Consider the cases for the order of the input: random, already sorted, reverse sorted. Also, consider the proportion of duplicate values in the input, e.g. all distinct values, some duplicates. Note that ./randl will most likely include duplicates as soon as you specify a relatively large list size.
Put your results and some brief comments explaining the results, in a file called timing.txt. The file should contain a table of results, with major rows dealing with a particular size of data, and sub-rows dealing with the order of the input. You should have three columns: one to indicate how many runs of each program were used to compute the average time-cost, one to give the average time-cost for usel and the other to give the average time-cost for sort. The table should look something like the following:
| Input Size |
Initial Order |
Has Duplicates |
Number of runs |
Avg Time for usel |
Avg Time for sort |
| 5000 | random | no | N | T1sec | T2sec |
| 5000 | sorted | no | N | T1sec | T2sec |
| 5000 | reverse | no | N | T1sec | T2sec |
| 5000 | random | yes | N | T1sec | T2sec |
| 5000 | sorted | yes | N | T1sec | T2sec |
| 5000 | reverse | yes | N | T1sec | T2sec |
| 10000 | random | no | N | T1sec | T2sec |
| 10000 | sorted | no | N | T1sec | T2sec |
| 10000 | reverse | no | N | T1sec | T2sec |
| 10000 | random | yes | N | T1sec | T2sec |
| 10000 | sorted | yes | N | T1sec | T2sec |
| 10000 | reverse | yes | N | T1sec | T2sec |
| etc. etc. |
You should also write a short paragraph to explain any patterns that you notice in the timing results. Don't just re-state the timing result in words; try to explain why they happened.
If you're looking for a challenge, and know how to write scripts, write e.g. a Linux shell script to automate the testing for you, and maybe even produce the timing file for you.
Another interesting challenge would be to plot graphs using the R system, available as the Linux command R (a single upper-case letter). I'd suggest plotting a separate graph for each type (random, ascedning, descending) for a range of values (e.g. 5000, 10000, 20000, 50000, ... as far as you can be bothered, given how long larger data files take to sort). Alternatively, produce your timing.txt as a tab-separated file and load it into a spreadsheet, from where you could also produce graphs.
If you're feeling brave, try to find out how large input sort can deal with. However, you should try such testing on a machine where you are the sole user. Also, you shouldn't try to store the data files; use commands like:
$ seq SomeVeryLargeNumber | time sort -n > /dev/null $ seq SomeVeryLargeNumber | sort -nr | time sort -n > /dev/null $ seq SomeVeryLargeNumber | sort -R | time sort -n > /dev/null
You need to submit two files: IntList.c and timing.txt. You can submit these via the command line using give or you can submit them from within WebCMS. After submitting them (either in this lab class or the next) show your tutor, who'll give you feedback on your coding style, your timing results, and award a mark.
Have fun, jas


Child Application
loading...
Communication to the parent application
Post message to a named child window of the parent application:
or
Communication received from the parent application
Received message from Parent app UUID: 'interapp-api-example'
This is where the inter app messages will appear
Thrown Error messages.
Errors will appear here
The box below will resize in response to the Parent Application being resized


--- layout: post title: Automated Tasks author: josh tags: - quote ---
I (…) am rarely happier than when spending an entire day programming my computer to perform automatically a task that would otherwise take me a good ten seconds to do by hand.
Douglas Adams


Hanieka
Balint
The Boston Globe
For six months I worked at Boston Globe Media Partners as a Brand Marketing Design Co-op. I worked with a small marketing team to create print, digital, and on-site promotional materials.
To advertise a virtual cocktail class hosted by Boston.com, I made an instagram ad, a facebook ad, and a video slide.
I made ads for GlobeDocs events that were printed in The Boston Globe's newspaper, as well as created weekly GlobeDocs subscriber emails using HTML.
To promote a virtual town hall for Boston students, I made a series of digital ads that appeared on The Boston Globe's website.
I designed a background screen for panelists to sit in front of at a Globe event.
The Boston Globe has a section on its site as well as two newsletters dedicated to cannabis related news stories. I designed a set of stickers promoting these newsletters that were distributed at the Northeast Cannabis Business Conference.
Rm 29 Designs
In 2019 my college roommate and I started a company called Rm 29 Designs. Named after the room where we met our freshman year, Rm 29 is a design studio that specializes in covering small business's graphic design and web development needs. I created all materials for Rm 29's brand, including our logo, style guide, business cards, and website illustrations. Much of the work displayed on this portfolio was done for Rm 29 clients.
Search Sustainable
Search Sustainable is a web application that helps users find everyday products from sustainable sources. I worked with three developers to create Search Sustainable during a weekend-long Hackathon. The goal of this project is to create a helpful tool that directs consumers to better purchasing options. My role as the designer and front end developer was to develop the UX design strategy, then implement it using HTML and CSS.
Users can search for a product name and our app will query our database of carefully selected sustainable items. If we do not have enough results in our database our application will use a web socket to connect to our web crawling API. Our custom crawler will query the products of sustainable vendors and show them as results to the users. These items will also be added to our catalog. Our database will learn from the preferences of our users to improve itself.
If the users find a sustainable item from a source outside of our database they can request to add the product to our site by filling out a request form. Administrators are notified of these requests and can look them over and decide if the product should be added to our database. If so, admins can use the dashboard tools to add it.
If a user finds a product that is not sustainable or otherwise unworthy of being on our site they can report it by pressing the report button in the bottom corner of the product card. The user enters a brief reason for the report and our admins are notified of the possible flawed product. Using the admin tools, our team can choose to remove the product or resolve the report in a manner they see fit.
Our admin user authentication process is powered by Firebase. If an administrator forgets their password they can use the forgot password link. They will get an email with a reset link fitted with a verification token that will allow them to securely reset their password.
Click here for more details on how the web app works
I used Figma and Adobe Creative Suite to research and create the design strategy for our brand. Search Sustainable is a helpful tool for making environmentally-conscious decisions, and so I created a style guide and logo that is clean, modern, and user-friendly.
Album Covers
Aeris is an independent musician who released their debut single "Cottagecore" in March 2021. I illustrated and designed the cover for this single, as well as for their second single "No No No."
For the "No No No" cover, I took a photo of a casette tape, then used photoshop to add Aeris's handwriting and adjust the colors, creating the final cover below.
Family Memories
During the summer of 2021 I worked on a personal project with my great-aunt. Over the course of the past year she had been writing stories about her life and about various members of our family, including my great-grandparents. I took these stories and the many photos that she scanned from family photo albums and designed a book and cover.
Each page is 8 x 10 inches, with a large outer margin to allow space for photo captions. All photos were constrained to the same margins as the text, with the exception of photos beside the chapter titles.
Every chapter title comes with a full bleed photo beside it. The chapter titles, running heads, and captions are set in small caps Mr. Eaves, while the body text is set in 11 pt Corundum with a 14 pt leading.
For the front cover I used a photo of my great aunt and my grandfather as children. For the back cover I used a scan of a page of my great-grandmother's scrapbook, which includes three rough proof photos and a hand written caption.
Keep the T Running
In the fall of 2021 I designed a campaign to advocate for continuous 24/7 MBTA service as a semester-long class project. The final deliverable was a campaign book, outlining my cause, the campaign's brand, and applications.
Click here to view the final brand bookThe Circuit
In the fall of 2021 I was a Project Lead for Scout, Northeastern University's student-led design organization. I managed a team of three designers and one developer to create a new brand and website for The Circuit.
The Circuit (formerly known as Tech for the People) is a student-run editorial and media platform that highlights the multifaceted uses and effects of technology. They came to Scout looking to add relevance and credibility to the organization through a rebrand and website update. User testing of the existing platform revealed that students viewed the organization as a blog rather than a credible editorial or a citable source.
We began the project by conducting research to understand what Tech for the People is and determine what Tech for the People could be. We worked with the client on brand exercises, conducted user interviews on the existing site, and wrote an elevator pitch that summarized the organization.
Once we understood the goals of the rebrand, we started to explore visual identities with moodboarding. Based on client feedback from our moodboards we created a design strategy that outlined the new brand’s typography, color palette, UX components, and imagery to guide us through the remainder of the project.
As part of Tech for the People’s relaunch, the client requested a new name as well as a new logo. Our team and the client agreed that The Circuit was the name that represents the organization the best, referencing both themes of technology and connection.
With a design strategy and logo in place, it was time for us to build a website that represented The Circuit’s brand. We began by writing user stories to help us determine what features the new site needed. Once a list of features was finalized and approved by the client, we created a sitemap that guided us through the designing of lo-fi and eventually hi-fi wireframes.
While a new website was our most prioritized deliverable, the client was also planning for a relaunch of The Circuit’s instagram page and newsletter. We created a new email template using Mailchimp as well as custom Canva templates for instagram posts.
To guide the client through The Circuit’s relaunch, we created a brand book that outlined how to use the new color palette, typography, imagery, and components effectively. Our final deliverables included this brand book as well as a folder of logo files, social media and email templates, and a newly published website.
The Farmer's Daughter Gravel Grinder
The Farmer's Daughter Gravel Grinder is an annual 65 mile long bike ride and fundraiser that starts in Chatham, NY. Using Wordpress I created a new website for the Farmer's Daughter, and created a new version of their logo that was more eye-catching to be used on branded merchandise.
Check out the finished website at farmersdaughtergravelgrinder.com
I was also the photographer at the Farmer's Daughter 2021. To see my photos, check out the photography section of this site.
PowerHouse
In the spring of 2021 I joined Scout, Northeastern University's student-led design organization. I joined a studio team of 7 designers and developers to work on PowerHouse, a startup that created moveable solar panel sheds. Over the course of the Spring semester, the team created a branding strategy for Powerhouse as well as a UX design.
Accessible & Inclusive Design At Scout
In the spring of 2022 I worked with a team on an internal project for Scout, Northeastern University's design organization. Together we researched and compiled a standardized set of accessibility guidelines for designers and developers, then strategized and executed different ways of ensuring that these guidelines are implemented. My job on the team was to design a book that explained these guidelines with examples. I decided that the format for this document should be a binder, to allow future Scout members to edit and add to the document as our understanding of accessible design deepens.
New Renaissance Theatre Company
In the fall of 2021 I joined New Renaissance Theatre Company, one of Northeastern University's student-led theatre organizations, as a graphic designer. Over the course of the semester I created the creative direction for the fall production of Stop Kiss by Diana Son, then executed this direction through print posters, social media posts, a mobile program, and a t-shirt design. The following semester I created the creative direction for the company's spring production of Gruesome Playground Injuries by Rajiv Joseph, and similarly executed this direction.
I was also the photographer in charge of Stop Kiss headshots.