Bayesian phylogenetics
Erick Matsen
Review
- What does likelihood mean?
- What is its interpretation in terms of simulation?
Sometimes we want to make confident statements
using trees that are highly uncertain.
Tracking SARS-CoV-2 transmission (colors)
Tracking SARS-CoV-2 transmission (colors)
What if we only care about transmission from country to country?
Working with random variables \(X\):
We can solve for \(X\) in “equations” like \(f(X) \sim Y\), obtaining expressions such as \(\mathbb P(X \mid Y);\) this is called inference.
We can also average with respect to \(X\):
\[
\int g(X) \, d\mathbb P(X \mid Y)
\]
where now we are averaging out with respect to a probability.
Probabilistic approach to prediction
- \(Y\): horizontal distance traveled by a cannonball (random variable)
- \(X\): cannon angle (inferred random variable)
- Problem 1: given observed distribution \(Y\), infer distribution of \(X\).
- Problem 2: find probability that a 10% bigger charge will hit castle.
- Solve \(f(X) \sim Y\) to get \(\mathbb P(X \mid Y)\).
- Integrate \(\int \text{hit}_{10}(X) \, d\mathbb P(X \mid Y)\).
Biological experiments are measurements with uncertainty
Model-based statistical inference ✓
We can solve for \(X\) in “equations” like \(f(X) \sim Y\),
inferring an unknown distribution for \(X\)
(what can we learn about the angle of the cannon).
We can push uncertainty through an analysis using integrals like \[
\int_a^b g(X) \, d\mathbb P(X \mid Y).
\] (we don’t care what the angle of the cannon is really, we just want to know with what probability the shot is going to hit the castle!)
\[
P(X \mid D) = \frac{P(D \mid X) P(X)}{P(D)}
\]
\[
P(D) = \sum_{X} P(D \mid X) P(X)
\]
What is our height divided by the average elevation?
Now, what is model-based statistical inference on discrete mathematical objects?
Motivation: we would like to decide whether an individual has been superinfected, i.e. infected with a second viral variant in a separate event
Integrate out phylogenetic uncertainty
To decide superinfection, we would like to calculate \[
\int_S g(T) \, d\mathbb P(T \mid Y)
\] where \(T\) is now a phylogenetic-tree-valued random variable.
If we can sample from the posterior distribution \(P(T \mid Y)\) of trees given data, then \[
\int_S g(T) \, d\mathbb P(T \mid Y) = \sum_{T \sim P(T \mid Y)} g(T)
\]
Tracking SARS-CoV-2 transmission (colors)
Integrating over phylogenetic trees?
Phylogenetic trees have discrete topologies, there is no canonical distance between them, nor a natural total order.
But we still want to do inference and integration in this setting!
Subtree-prune-regraft (rSPR) definition
These trees are then distance 1 apart.
Tree graph connected by rSPR moves
- If you jump to a better tree, accept that move
- If you jump to a worse tree, accept that move with a non-zero probability
- It’s all arranged so that you sample trees in proportion to their posterior probability
Try out MCMC robot!
Markov chain Monte Carlo
Subset to high probability nodes
The top 4096 trees for a data set
The posterior probability of a tree is the probability that the observed tree is correct (given the model and priors)
- Bayesians sample from this posterior
- If you can deal with a prior, it’s the statistically right thing to do
- Sometimes we aren’t actually interested in the tree, so we can integrate it out
- But! Short alignment, 100 taxa = hours
Why is random-walk Markov chain Monte Carlo so slow?
The efficiency of MCMC depends on the fraction of good neighbors.
# good neighbors for 41 sequences
# good neighbors for 41 sequences (!)
… we are very unlikely to hit another good tree by randomly trying a neighbor. No wonder random walk MCMC is so slow.
Whidden & Matsen IV. (2015). Quantifying MCMC exploration of phylogenetic tree space. Systematic Biology.
Variational inference is an alternate strategy
MCMC strategy: sample under this curve
Variational inference: fit a distribution \(q_\phi(\mathbf{z})\) to it


public class Configurations
extends java.util.Observable
| Modifier and Type | Field and Description |
|---|---|
private java.lang.String |
bestPlayerName |
private int |
bestScores |
private java.lang.String |
playerName |
private static java.util.prefs.Preferences |
preferences |
private int |
searchTreeLevel |
private int |
sleepTime |
| Constructor and Description |
|---|
Configurations()
Constructs a configuration object.
|
| Modifier and Type | Method and Description |
|---|---|
java.lang.String |
getBestPlayerName()
Obtains the player's name who achieves the best scores stored in the
configuration file.
|
int |
getBestScores()
Obtains the best scores stored in the configuration file.
|
java.lang.String |
getPlayerName()
Obtains the player's name stored in the configuration file.
|
int |
getSearchTreeLevel()
Obtains the level of the search tree stored in the configuration file.
|
int |
getSleepTime()
Obtains the sleep time between each move of the auto player stored in
the configuration file.
|
void |
reset()
Resets all the properties to their default values.
|
void |
setBestRecord(java.lang.String bestPlayerName,
int bestScores)
Changes the best player's record, i.e.
|
void |
setPlayerName(java.lang.String playerName)
Changes the current player's name to a given new name, and save this change
to the configuration file.
|
void |
setSearchTreeLevel(int searchTreeLevel)
Changes the level of the search tree to a given new one, and save this
change to the configuration file.
|
void |
setSleepTime(int sleepTime)
Changes the current auto player's sleep time to a new one, and save this
change to the configuration file.
|
private java.lang.String bestPlayerName
private int bestScores
private java.lang.String playerName
private static final java.util.prefs.Preferences preferences
private int searchTreeLevel
private int sleepTime
public java.lang.String getBestPlayerName()
public int getBestScores()
public java.lang.String getPlayerName()
public int getSearchTreeLevel()
public int getSleepTime()
public void reset()
public void setBestRecord(java.lang.String bestPlayerName, int bestScores)
bestPlayerName
- the new best player's namebestScores
- the new best scorespublic void setPlayerName(java.lang.String playerName)
playerName
- the player's new namepublic void setSearchTreeLevel(int searchTreeLevel)
searchTreeLevel
- the new search tree levelpublic void setSleepTime(int sleepTime)
sleepTime
- the new sleep time between each move of the auto player


|
| CUDA_ONLY_HOS | managed_object () |
| | Default constructor: no allocation. More...
|
| |
| template<class ArrLike , class disabler = std::enable_if_t< ! std::is_integral_v<ArrLike> >> |
| CUDA_ONLY_HOS | managed_object (ArrLike &a, const bool copy=default_is_copy) |
| | Constructs from something that is like an array. More...
|
| |
| CUDA_HOS_DEV | managed_object (const managed_object &m, const bool copy=default_is_copy) |
| | Copy-constructs. If, by any reason, the user wants to force the pointer to be copied instead of performing allocations, copy can be put to false. More...
|
| |
| template<class other_manager , bool other_bool> |
| CUDA_ONLY_HOS | managed_object (const managed_object< Type, indexer, other_manager, other_bool > &m, const bool copy=default_is_copy) |
| | Copy-constructs from another memory context. If, by any reason, the user wants to force the pointer to be copied instead of performing allocations, copy can be put to false, which happens if and only if the memory locations are the same. More...
|
| |
| CUDA_ONLY_HOS | managed_object (const Type &val) |
| | Constructs an object equal to val . More...
|
| |
| CUDA_HOS_DEV | managed_object (managed_object &&m) |
| | Move-constructs. More...
|
| |
| template<class other_manager , bool other_bool> |
| CUDA_ONLY_HOS | managed_object (managed_object< Type, indexer, other_manager, other_bool > &&m) |
| | Move-constructs from another memory context. More...
|
| |
| CUDA_HOS_DEV | ~managed_object () |
| |
| template<class stream > |
| CUDA_ONLY_HOS void | binary_input (stream &s) |
| |
| template<class stream > |
| CUDA_ONLY_HOS void | binary_output (stream &s) const |
| |
| CUDA_ONLY_HOS void | clear () |
| | Clears the memory allocated for the object. If deallocatable() is false, just sets the internal pointer to nullptr . More...
|
| |
| CUDA_HOS_DEV bool | deallocatable () const |
| | Returns true if the object can be deallocated (which should be the usual case) and false if not (when default_is_copy is false and the pointer has been copied from another object). More...
|
| |
| CUDA_HOS_DEV Type *& | get_access_to_pointer () |
| | Gives direct access to the internal pointer. More...
|
| |
| CUDA_HOS_DEV const Type * | get_access_to_pointer () const |
| | Gives direct access to the internal pointer. More...
|
| |
| CUDA_HOS_DEV | operator Type () const |
| | Returns an object of type Type . More...
|
| |
| CUDA_HOS_DEV | operator Type * () const |
| | Returns a pointer to the object. More...
|
| |
| CUDA_HOS_DEV managed_object & | operator= (const managed_object &m) |
| | Assignment operator. The behaviour will depend on the template parameter default_is_copy , with there being allocations if true and a simple pointer copy if it is false . More...
|
| |
| template<class other_manager , bool other_bool> |
| CUDA_ONLY_HOS managed_object & | operator= (const managed_object< Type, indexer, other_manager, other_bool > &m) |
| | Assignment operator from another memory context. The behaviour will depend on the template parameter default_is_copy , with there being allocations if true and a simple pointer copy if it is false and the memory locations are the same. More...
|
| |
| CUDA_HOS_DEV managed_object & | operator= (const Type &val) |
| | Assignment operator from an object of the managed type. The behaviour will depend on the template parameter default_is_copy , with there being allocations if true and a simple pointer copy if it is false . More...
|
| |
| CUDA_HOS_DEV managed_object & | operator= (managed_object &&m) |
| | Move-assignment operator. More...
|
| |
| template<class other_manager , bool other_bool> |
| CUDA_ONLY_HOS managed_object & | operator= (managed_object< Type, indexer, other_manager, other_bool > &&m) |
| | Move-assignment operator from another memory context. More...
|
| |
| template<class stream > |
| CUDA_ONLY_HOS void | textual_input (stream &s) |
| |
| template<class stream , class str = std::basic_string<typename stream::char_type>> |
| CUDA_ONLY_HOS void | textual_output (stream &s, const str &separator=" ") const |
| |
| CUDA_HOS_DEV bool | valid () const |
| | Returns true if this holds an actual object and false if not. More...
|
| |
template<class Type, class indexer = g24_lib::Definitions::default_unsigned_indexer, class memory_manager = default_memory_manager<Type, indexer>, bool default_is_copy = true>
class g24_lib::managed_object< Type, indexer, memory_manager, default_is_copy >
A container that holds an object in a given memory context.
- Template Parameters
-
| Type | The type of the object being managed. |
| indexer | A type that is appropriate to hold sizes of objects. |
| memory_manager | The memory manager corresponding to the memory context where the object will be held. |
| default_is_copy | Determines the behaviour of copy constructors and assignment operators: if false , instead of allocating a copy of the object, only the pointer is copied (and the memory will not be deleted upon destruction). In essence, if true , this acts as something akin to an std::unique_ptr , while, if false , it is more like an std::weak_ptr . (This is currently only used to pass object into CUDA kernels. For the end user, default_is_copy should be true.) |
- Warning
- When acting as a raw pointer, the memory may become invalid if the object from which that pointer was copied is destructed or resized.
- Precondition
indexer
must satisfy the constraints placed on the choice of g24_lib::Definitions::default_unsigned_indexer.
-
memory_manager
must be a valid memory manager, that is, g24_lib::is_memory_manager<memory_manager>
should be true
.
- Warning
- Due to the possible need to copy objects between different memory contexts, namely when interfacing with CUDA-enabled GPUs, copy constructors or assignment operators of
Type
will not be invoked during these transfers: Type
will only be shallow-copied (that is, operations akin to std::memcpy
that copy bytes). For most numerical applications, this shouln't pose too much of a problem, but it is a limitation one must take into account carefully.
- Todo:
- Try to accomodate copy constructors/assignment operators into this.
Definition at line 77 of file managed_object.h.
template<class Type , class indexer = g24_lib::Definitions::default_unsigned_indexer, class memory_manager = default_memory_manager<Type, indexer>, bool default_is_copy = true>
template<class other_manager , bool other_bool>
Copy-constructs from another memory context. If, by any reason, the user wants to force the pointer to be copied instead of performing allocations, copy
can be put to false, which happens if and only if the memory locations are the same.
Definition at line 287 of file managed_object.h.
template<class Type , class indexer = g24_lib::Definitions::default_unsigned_indexer, class memory_manager = default_memory_manager<Type, indexer>, bool default_is_copy = true>
template<class ArrLike , class disabler = std::enable_if_t< ! std::is_integral_v<ArrLike> >>
Constructs from something that is like an array.
- Precondition
- The address of the first element of the array,
&a[0]
, is taken to point to a valid Type
.
Definition at line 435 of file managed_object.h.
template<class Type , class indexer = g24_lib::Definitions::default_unsigned_indexer, class memory_manager = default_memory_manager<Type, indexer>, bool default_is_copy = true>
template<class other_manager , bool other_bool>
Assignment operator from another memory context. The behaviour will depend on the template parameter default_is_copy
, with there being allocations if true
and a simple pointer copy if it is false
and the memory locations are the same.
Definition at line 348 of file managed_object.h.


Oops. Looks like you've upgraded from an old version
No worries. Qbana has a new build system. Now its faster and lighter than ever before.
To fix this
If you really want to run from source you can do so from the src/ folder. After upgrading you may need to clear your browsers cache to see all of the new features.


| 002:237 Khan | : |
And if you divorce them before you have touched (had a sexual relation with) them, and you have appointed unto them the Mahr (bridal money given by the husbands to his wife at the time of marriage), then pay half of that (Mahr), unless they (the women) agree to forego it, or he (the husband), in whose hands is the marriage tie, agrees to forego and give her full appointed Mahr. And to forego and give (her the full Mahr) is nearer to At-Taqwa (piety, right-eousness, etc.). And do not forget liberality between yourselves. Truly, Allah is All-Seer of what you do. |
| 002:237 Maulana | : |
And if you divorce them before you have touched them and you have appointed for them a portion, (pay) half of what you have appointed unless they forgo or he forgoes in whose hand is the marriage tie. And it is nearer to dutifulness that you forgo. Nor neglect the giving of free gifts between you. Surely Allah is Seer of what you do. |
| 002:237 Pickthal | : |
If ye divorce them before ye have touched them and ye have appointed unto them a portion, then (pay the) half of that which ye appointed, unless they (the women) agree to forgo it, or he agreeth to forgo it in whose hand is the marriage tie. To forgo is nearer to piety. And forget not kindness among yourselves. Allah is Seer of what ye do. |
| 002:237 Rashad | : |
If you divorce them before touching them, but after you had set the dowry for them, the compensation shall be half the dowry, unless they voluntarily forfeit their rights, or the party responsible for causing the divorce chooses to forfeit the dowry. To forfeit is closer to righteousness. You shall maintain the amicable relations among you. GOD is Seer of everything you do. |
| 002:237 Sarwar | : |
If you divorce your wives before the consummation of the marriage and the amount of dowry has been fixed, pay your wives half of the amount of their dowry unless she or her guardians drop their demand for payment. To drop such a demand is closer to piety. Be generous to each other. God is Well-Aware of what you do. |
| 002:237 Shakir | : |
And if you divorce them before you have touched them and you have appointed for them a portion, then (pay to them) ha!f of what you have appointed, unless they relinquish or he should relinquish in whose hand is the marriage tie; and it is nearer to righteousness that you should relinquish; and do not neglect the giving of free gifts between you; surely Allah sees what you do. |
| 002:237 Sherali | : |
And if you divorce them before you have touched them, but have settled upon them a dowry, then half of what you have settled shall be due from you, unless they remit, or he, in whose hands is the tie of marriage, should remit. And that you should remit is nearer to righteousness. And do not forget to do good to one another. Surely ALLAH sees what you do. |
| 002:237 Yusufali | : |
And if ye divorce them before consummation, but after the fixation of a dower for them, then the half of the dower (Is due to them), unless they remit it or (the man's half) is remitted by him in whose hands is the marriage tie; and the remission (of the man's half) is the nearest to righteousness. And do not forget Liberality between yourselves. For Allah sees well all that ye do. |
Concepts/Themes Covered: أركان الإسلام > التوحيد > توحيد الله تعالي > صفات الله تعالى > البصير Pillars of Islam> Islamic> Oneness of Allah> His Glory's Characteristics> All Seer العمل > العمل الصالح > التقوى Action(Work)> The Good Deeds>The Piety الإنسان والعلاقات الأخلاقية > الأخلاق الحميدة > العفو عن الناس Man and The Moral Relations> Good Morals>Forgiving People الإنسان والعلاقات الاجتماعية > الأسرة > الطلاق > الاحكام التى تترتب على الطلاق Man and The Social Relations>The Family>Divorce> Its Rules الإنسان والعلاقات الاجتماعية > المجتمع > العفو والصفح وكظم الغيظ Man and The Social Relations>The Society>Forgiveness, Tolerance and Supressing Distress
This tool uses eight English parallel translations for the Holy Quran imported from Mr. Clay Smith. You can also visit Qurany Concepts for browsing the Quran themes or topics. If you want to search the Holy Quran for keywords, please visit Qurany Keywords.


We're prototyping different ways of presenting data from government services.
If you work in government and you want to work with a data scientist, get in touch.
These prototypes may break at any time, and may disappear temporarily or permanently. They may not be accessible or work in older browsers.
A comparative study of the current demand and the potential for growth in visitor numbers to the UK.
Visualisations of British ambassadors' Twitter networks with simplified community detection.
Machine learning approach to anomaly detection in hourly GOV.UK traffic patterns.
A prototype dashboard measuring the ongoing performance of major projects and programmes across all of government.
Prototype dashboards measuring the performance of selected government policies.
A prototype dashboard measuring the performance of a local authority's online service.
Uses open data released by London Fire Brigade to visualise all incidents that occurred during 2012.
Environment Agency and Met Office data updated regularly to give a snapshot of the current river level situation in England and Wales.
Uses GOV.UK browsing data to show how views of travel advice have changed relative to the previous day.
Uses data from data.gov.uk to show staff numbers in Government Central Civil Estate properties.


A ValueList option type refers to the options that have a list of option values.
It is also widely used in console applications. Suppose there is a console application that takes multiple files as input files, we can define a /input option which is the ValueList type, and use this application like this:
|
D:\>my_app /input:a.dat,b.dat,c.dat ... |
The separator character, which can be customized within ACF, must be used between the values in order to separate the values in a ValueList option.


Hello and welcome to my profile. My name is Brian Crisp and i would like to share a little bit about who i am. Currently i am studying to become a full stack web developer at Johns Hopkins. During the day i am a automotive state inspector who is also preparing to become a father later this year. In the past few months i have discovered that i really love learning to become a developer and i wish i had discovered that a long time ago but, here i am. I am so excited to see the where the road ahead takes me and i couldn't be more ready for the journey. I am looking for my first job in the programming field and i am very eager to learn. Thank you for visiting and i hope you enjoy.
Skills
Fun Fact: I have been learning spanish everyday for the last 130 days and i love every minute of it.


Without the help of our sponsors HackTheMidlands simply would not be possible. Our sponsors are wonderful, have loads of experience and are here to help! We will be releasing more sponsors as we get closer to the event, and if you're interested in becoming a sponsor for HackTheMidlands 2020 then please register your interest below!
Platinum Sponsor
{% for sponsor in site.data.sponsors.building %}
{% endfor %}
Gold Sponsors
{% for sponsor in site.data.sponsors.gold %}
{% endfor %}
Silver Sponsors
{% for sponsor in site.data.sponsors.silver %}
{% endfor %}
Bronze Sponsors
{% for sponsor in site.data.sponsors.bronze %}
{% endfor %}
Partners
{% for sponsor in site.data.sponsors.partners %}
{% endfor %}
Meet the team
Without a team of dedicated volunteers this hackathon simply would not happen. Here's your chance to meet the awesome people who are behind HackTheMidlands.


Gateway
BOT
15-Aug-18 01:43 PM
[dscrdeql] <Jellysmash> someone playing silly buggers
[dscrdeql] <Jellysmash> with a bot or script or something
[dscrdeql] <Catalyst> invite links?
[dscrdeql] <SwimedDragon> Damn that's a lot of spam
[dscrdeql] <ghost> the beginning of the bounty :)
Much more messages
[dscrdeql] <ghost> scroll... scroll...
[dscrdeql] <Jellysmash> yea, so much activity
[dscrdeql] <Jellysmash> some people have filled in the bitcoinalk reply with their links already
[dscrdeql] <Jellysmash> so many new faces as well.
[dscrdeql] <Jellysmash> been really good
[dscrdeql] <Jellysmash> the bounty looks like it's making a big difference
[dscrdeql] <Jellysmash> and it's only been day 1
[dscrdeql] <Jellysmash> we have a long way to go
[dscrdeql] <MassimoStyle> I had to scroll through at least 200 messages
[dscrdeql] <Jellysmash> a number of weeks
[dscrdeql] <Jellysmash> hope this can be sustained
[dscrdeql] <Jellysmash> I bet the founders must be pleased
[dscrdeql] <Jellysmash> coming up with a plan
[dscrdeql] <Jellysmash> and seeing everyone respond to that
[dscrdeql] <Jellysmash> really makes it all worthwhile
[dscrdeql] <MassimoStyle> I have seen a lot of growth
[dscrdeql] <Jellysmash> yea, it's been exciting to be part of
[dscrdeql] <MassimoStyle> More and more people are joining every single day
[dscrdeql] <Jellysmash> I'm glad i was able to get in on equaliser now in the beginning
[dscrdeql] <Jellysmash> and I'm sure others feel the sasme way
[dscrdeql] <MassimoStyle> Yep
[dscrdeql] <Jellysmash> we'll look back in a year and ......
[dscrdeql] <Jellysmash> be astonished at teh changes
[dscrdeql] <Jellysmash> and what's gone on and how we were there
[dscrdeql] <MassimoStyle> Agree
[dscrdeql] <CombatWombat-Mod> and the person/people who dumped on exrates going to be like those guys who sold bitcoin for 100 dollars
[dscrdeql] <MassimoStyle> What is the cmd to check how many people have been joining in the past wk and 24 hours
[dscrdeql] <MassimoStyle> I heard like a month someone dumped around one mil
[dscrdeql] <MassimoStyle> Eqli
[dscrdeql] <CombatWombat-Mod> it was more then that some stupid person
[dscrdeql] <Jellysmash> yea, the dumper will be like that guy that bought a pizza with btc
[dscrdeql] <Jellysmash> sometingn likea few thousand for a pizza
[dscrdeql] <Jellysmash> now worth millions
[dscrdeql] <SwimedDragon> For @everyone that joined in recently, don't forget to type ?begin in #tipsy-begin
[dscrdeql] <MassimoStyle> I know
[dscrdeql] <Jellysmash> good incentive to buy more for sure
[dscrdeql] <MassimoStyle> Crazy now u look back on it
[dscrdeql] <SwimedDragon> I think we need to point it out a lot because there seem to be lots of people who don't type it
[dscrdeql] <Jellysmash> yes, agreed
[dscrdeql] <MassimoStyle>
[dscrdeql] <Jellysmash> good to point that out
[dscrdeql] <Jellysmash> i think new people may not have realised that
[dscrdeql] <Jellysmash> so yes, good to mention
[dscrdeql] <MassimoStyle> Laszlo Hanyecz made the first real-world transaction by buying two pizzas in Florida for 10,000 BTC.


Toggle navigation
Chris Hollenbeck
About Me
Certifications
Projects
Shop Rewiring
Sophmore Cisco Final
Glitch
PC Build
Career Action Plan
Shop Projects
Rewiring
Final Cisco Project: Sophmore Year
Glitch Project
PC Build


Resume Builder
TOKEN GENERATED
GENERATED TOKEN
TOKEN SEARCH
SUBMIT
NAME
CONTACT NO.


Hi there! 👋 Thank you for visiting my website! Whatever you are looking for, I hope you will find it. If you want to reach out, you can contact me anywhere you'd like. You can find my social media channels right above the main navigation. If you want to say hi via email, write me at<EMAIL_ADDRESS>Latest post: {{post.title}}Dear recruiters & HR professionals, please find my profile on LinkedIn and always try to contact me via email please. You can find my resumé at my LinkedIn or you can download it here.


A MATHEMATICAL AND EXPERIMENTAL INVESTIGATION OF
MICROCYCLE SPECTRAL ESTIMATES OF SEMICONDUCTOR FLICKER NOISE
‘Thesis by
.-". .Michael A. Caloyannides
In Partial Fulfillment of the Requirements For the Degree of
Doctor of Philosophy
California Institute of Technology
Pasadena, California
1972
(Submitted July 6, 1971)


As a novice to the technology and programming fields, unknown answers are part of my everyday struggle. While working on assignments all week long, dozens of questions pop into my head. Usually I struggle with them on my own and resort to google to help me solve them. I would say about 90% of the time either I am able to figure out the solution on my own or google leads me to someone who has already answered this question for someone else. What happens the other 10% of the time?
I ask my DBC cohort members for help. Sometimes this process is painless: I post to the google plus community and within a couple of hours a number of people have responded to my question with solutions to my problems. However, if the question is not phrased well, this process can become tedious.
Here is an example of one of my questions to which a cohort member provided me with a quick and clear solution:
-------------------------------------------------------------------------------------------
I'm working on the bonus part of the bingo challenge and I'm trying to create an array length 5 with 5 arrays inside of that array also of length five...I have loops within loops but I've tried to break the problem down using IRB:
irb(main):014:0> bingo_board = Array.new(5,Array.new(5))
=> [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]
irb(main):015:0> one = (1..15).to_a.shuffle
=> [14, 12, 3, 5, 13, 1, 10, 6, 2, 15, 11, 4, 8, 9, 7]
irb(main):016:0> bingo_board[0][0]= one.pop
=> 7
irb(main):017:0> bingo_board
=> [[7, nil, nil, nil, nil], [7, nil, nil, nil, nil], [7, nil, nil, nil, nil],
[7, nil, nil, nil, nil], [7, nil, nil, nil, nil]]
irb(main):018:0>
I think that the line bingo_board[0][0] = one.pop should only populate the first array and the first position in that array (index 0) with 7. However, as you see in the last output of IRB it is populating position bingo_board[0,0], bingo_board[1,0], bingo_board[2,0], bingo_board[3,0], bingo_board[4,0] with 7. Can someone tell me what I'm doing wrong? Thanks in advance!
-------------------------------------------------------------------------------------------
Answer that helped me realize what I was doing wrong:
g = Array.new(5, Array.new(5)) is different from h = Array.new(5) {Array.new(5)} because each element of g will be the same empty array, but h will make a different empty array for each element. Calling that external block allows you do more elaborate things as well.
-------------------------------------------------------------------------------------------
So I was able to change the way I was creating the array and my program started working. There are a number of reasons this question led to good responses. First off, I explained my problem and then I gave an example of my problem by simplifying it and showing the problem using IRB. It also helped that I described what I thought the code should be doing and how that differed from what it was actually doing. This allowed people to better understand where I was getting stuck. To be clear, this is one of my best thought out questions. I don't always get the answers I'm looking for because oftentimes my questions aren't phrased in a meaningful way.
Asking questions is important and seems like a no brainer but the way you phrase your questions can have a large impact on the length of time it takes you to get an accurate response. For me, it is easier to write my questions out because I have time to read and reread them before someone else sees them. During this process I like to take a step back and think about whether or not I would understand this question without the background I already have for it. However, when I ask questions in person it is usually a different story. I can't decide what information to present first, causing me to just babble out information in any random order.
During phase 0, I've really focused on how I present questions to my cohort online. The clearer I am the more likely I am to get a correct answer in a short amount of time. Going into phase 1, I need to take all the same tools I've been using to write questions and apply them when I ask questions out loud. Here are some useful tools for asking good questions:
For written questions - Title Questions The title draws the attention of the reader. It should be a specific and quick summary of your problem. For written questions - Context This isn't as important when you are asking questions in person because those people will most likely understand the context. However, when asking questions online it is important to provide context: what language are you programming in, do you have any constraints, what platform are you using, etc. For written and in person questions: Problem Statement Make sure the people you are asking know what you want to get out of the question. Saying, "I did x and y but it doesn't work" isn't really showing someone what you expect to get out of your question. For written and in person questions: Data/Research It often helps to show the person you are asking what you tried to do to fix your problem and how you thought it might fix it. Showing your previous research helps the person answering the questions see where you are getting off track.
Questions are and always will be a crucial part of learning. It's important to feel comfortable asking them, and knowing how to ask them efficiently.


Dr. Bey: [stutters in disbelief] Oh, look at this! Sons of the pharaohs! Give me frogs, flies, locusts! Anything but you! Compared to you the other plagues were a joy!
Evelyn: I am so very sorry. It was an accident!
Dr. Bey: My darling girl, when Ramses destroyed Syria, that was an accident.
Evelyn: I am so very sorry. It was an accident!
Dr. Bey: My darling girl, when Ramses destroyed Syria, that was an accident.
In the library or archive, there are always stacks upon stacks of books, and so many bookcases in so many rows. The fight begins, and a bookcase falls... into its neighbor, which falls onto its neighbor, and causes a chain reaction that levels the whole library.
See also: Disaster Dominoes, the Super-Trope.
Note: This is not possible in Real Life, as bookcases are both designed to be very stable, and when loaded with books, are very heavy. Not to mention, most library bookcases are anchored.
Examples:
open/close all folders
Advertising
- In an ad for Australian insurance company AAMI, a stripper jumping out of a cake at a party supplies store sets one of these off. The last shelf hits electrical wiring, setting the store on fire...
- An ad for some laxative brand showed a librarian who had taken "the leading brand" laxative, causing her to double over with intestinal cramps, knocking over a bunch of shelves. The ad then goes on to say that if she had taken the brand they were advertising, she would have gotten the relief she needed without the cramping, and none of that would have happened.
Anime & Manga
- This happens momentarily in Mahou Sensei Negima! when Nodoka came under the effects of the Love Potion Negi had just drunk. A large section of the library ends up toppled over.
- In Detective Conan, they set one up on purpose in order to nail a perp.
- Happens in an early chapter of Yu-Gi-Oh!. When Yugi tries to debunk a classmate claiming to be psychic. Said classmate predicts that Yugi would be crushed by "countless letters", and tries to make this prediction come true by pushing a bookshelf onto Yugi.
Films — Animation
- An Extremely Goofy Movie: During the scene where Goofy apologizes to Sylvia. He stuck his head in a bookshelf to talk to her, and when he tries to extricate himself, this happens.
- Turned into a literal site/sight gag in Disney's Hercules. The title character bumps into a column, which tips over and falls into its neighbor, causing a chain reaction to go all the way around the agora. Especially when he threw the pillar that caused the first part of the reaction, causing the second part, a repeat of the first one, all over again.
- In the beginning of DuckTales the Movie: Treasure of the Lost Lamp, Launchpad's airplane landing knocked down two columns causing a chain reaction from both sides.
Films — Live-Action
- The Mummy Trilogy:
- In the first movie, Evey's introduction has her doing this by accident because she's a klutz.
- This is echoed in The Mummy Returns, where the child of the main characters causes a series of pillars in an ancient temple to smash into each other, one by one. They can hardly be mad at him, though, as the last pillar broke open the wall to the sealed room where they were "drinking from the Nile".
- Happens in Tremors in a grocery store. This time, it's the monster's fault, forcing the heroes to escape onto the roof. In this case, the heroine happens to be standing on top of the shelves, and is flung out the window by their collapse!
- Done in Zombieland in the souvenir shop.
- Jury Duty used this to signal the security guard, only to knock him out.
- In the film version of Angels & Demons, Robert Langdon intentionally topples the shelves in the Vatican Archives in an attempt to escape the hermetically sealed (and locked) library, which is quickly running out of breathable air. The glass is reinforced and bulletproof, however, so it fails to work... initially.
- In Three O'Clock High, a fight in a library leads to entire bookshelves getting knocked down like dominoes.
- Done deliberately in Foul Play. Tony is in a shootout with Stiltskin, the lead hitman, in a wine cellar. After trading shots, Tony realizes the shelves of wine bottles are lined up, and he knocks the first one down, causing the others to follow suit. Then he runs out while the Stiltskin is distracted and opens fire. It's not clear whether Tony got Stiltskin with his shot or Stiltskin was crushed by the falling shelf, but either way he's just as dead.
- Done intentionally in GoldenEye, forcing the mooks to go downstairs and shoot through the floor.
- In Giant, Bick Benedict (Rock Hudson) does this to Jett Rink (James Dean)'s wine cellar.
- In Geo Storm, this happens to actual buildings in Hong Kong as a heat wave strikes and the underground gas lines explode.
Literature
- Occurs in the book Angels & Demons so Robert Langdon can break out of the sealed chambers in the Vatican Archives.
- Freddy is beaten this way in Freddy Krueger's Tales of Terror: Twice Burned, being pinned under knocked-over bookshelves while the library is burning to the ground.
- In the climax of the Stephen King novella "The Library Policeman", during the battle with the parasitic Ardelia, one character manages to topple all the library bookshelves in an attempt to stop her advance.
- Harry Potter and the Order of the Phoenix has a variation of this, where the shelves in question do not contain books, but glass receptacles of spoken and recorded prophecies. This doesn't make the shelves themselves any lighter however, and it is implied one of the Death Eaters unlucky enough to be caught underneath the whole collapse is so badly injured that the others, though all skilled and wand-bearing adult wizards, would rather leave him to his fate than try to heal him, as it would take too much of their time away from the pursuit of Harry and his friends.
- Princesses of the Pizza Parlor: The Academy's library, according to Book 1, it looked:
like a children's game of dominoes. All it would take was one push and it would all come tumbling down. From the look of things, this may have happened in the past, on more than one occasion.
- In The Phantom Tollbooth, the Spelling Bee and Humbug start brawling in the Word Market of Dictionopolis, and knock down all the dealers' stalls this way.
Live-Action TV
- Used in a sketch in The Armstrong and Miller Show, a British comedy clip show.
- Happens in the Doctor Who two-parter "Silence in the Library"/"Forest of the Dead" two-parter when the Doctor, River Song, and the archeological team are running from the Vashta Nerada.
- Buffy the Vampire Slayer:
- Happens in the episode when there is an earthquake.
- And again later on during a large fight, with Willow getting crushed underneath them and being put in a coma.
- A David Letterman Top Ten list, "Top Ten Ways to Get Kicked Out of a Bookstore"; has as its number one method, "Knock over the bookshelves like giant dominoes."
- Subverted in the "Bull in a China Shop" episode of MythBusters. Bulls have very sensitive ears and will be careful to avoid crashing ceramics.
- Happens in The Office in the episode "Boys and Girls" when Michael accidentally drives the warehouse forklift into a large metal storage rack causing the other racks to topple over like dominoes.
Video Games
- In the second Manor level of the original Max Payne, triggering a landmine on one of the massive archive shelves makes them fall like this, allowing Max to climb up to the otherwise inaccessible catwalk.
Webcomics
- Implied in this Precocious strip.
Web Original
- Whateley Universe: In The Three Little Witches:
Palantir and Abra reached up and applied all their might into keeping the shelf from falling. Clover scrambled to her feet and pushed. Together, they shoved the tall bookshelf back-
-so far back that the bookcase tipped over the other way, hitting the bookcase on the other side, tipping IT over, creating a domino effect. Fortunately, it only tipped over three more bookcases, but from where the Three Little Witches stood, it was a scene of horrific devastation.
Western Animation
- The Amazing World of Gumball: In The Mystery, The Bet and The Society.
- El Tigre: causes it in his mother's library because the bad guys duck his Rocket Punch. The falling bookcases end up getting them in the end.
- In Megas XLR, a flashback shows Coop doing this while trying to get a book off a high shelf. The same episode ends with the same thing happening to an alien ringworld library.
- Happened in the first arc of W.I.T.C.H..
- Kick Buttowski: Suburban Daredevil: the episode "If Books Could Kill" has Kick escaping from an evil librarian. The last shelf misses her when it falls against a statue, but then the books fall and bury her.
- Star Wars: The Clone Wars: In "Duel of the Droids" Ahsoka knocks over several shelves in a storage room by pushing the first into its neighbor while escaping from Grievous.
- Young Justice: Red Inferno does this in an attempt to trap Robin and Artemis as the two heroes flee through the base library in "Homefront".
- Monster Buster Club: It happens in the episode "Comic Book Heroes", with enormous piles of comics toppling each other at the end of the fight against a giant robot clown.
- Happened in Rugrats when Tommy wonders around the high school library when Didi brought him to class.
- SheZow: In "She Phat", SheZow's super-heavy footsteps cause this to happen to the shelves full of delicate china in the delicate china warehouse.
- In The Smurfs episode "Unsound Smurfs", the Smurflings cause this to happen when they look through the Noisemaker's sounds to find the one that would be sufficient enough to break the magical sound barrier cast over the entire Smurf Village.
Real Life
- In 1978, when architecture student Diane Hartley reported a dangerous flaw in the stilted design of Manhattan's Citicorp Center (now 601 Lexington), civil engineers calculated that if a windstorm struck the building at the right angle, it could topple over sideways, potentially striking adjacent buildings and setting off a domino-effect mass collapse. Ultimately averted via emergency repairs to reinforce the skyscraper's structural supports, although a close call with Hurricane Ella nearly kicked off this trope on a catastrophic scale in the middle of Midtown.


The example shows how to use the MessageBox class. Some of the buttons have animations, some are normal.
The js is not minified so it is readable. See msg_box.js.
Confirm
Standard Yes/No dialog.
Prompt
Standard prompt dialog.
Multi-line Prompt
A multi-line prompt dialog.
Yes/No/Cancel
Standard Yes/No/Cancel dialog.
Progress Dialog
Dialog with measured progress bar.
Wait Dialog
Dialog with indefinite progress bar and custom icon (will close after 8 sec).
Alert
Standard alert message dialog.
Icons
Standard alert with optional icon.
Custom button text
MessageBox with custom button text.


agl-low-collector-service
Subscribe
Unsubscribe
list-devices
list-device-capabilities
start-polling
stop-polling


Fortunate is a modern application that aims to be a simple best-in-class, cross-platform sample. It comes with a bundle of fortune files -- lists of fortunes to show -- and allows users to add their own fortune files.
It's currently available as a Progressive Web App, and versions are planned for other platforms as well.
For any feedback, please reach out to me on GitHub.
{
"vars": { "account": "UA-71060232-1" }
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
}
}
}


"Watch it!!"
The words below will be replaced by "Hello World" which is pulled from the 'myfirstprogram.php' file via AJAX.
AJAX DEMO
Pay attention... Notice when you click the button that only this section changes.
The words below will be replaced by "Hello World" which is pulled from the 'myfirstprogram.php' file via AJAX.


{{ post.title }}
Published: {{ post.date | date: "%B %e, %Y" }}{{ post.excerpt }}
Read more »
---
layout: single-column
title: Yeoman Team Blog
category: blog
class: blog
type: list
---
{% for post in site.posts limit:8 %}
{{ post.title }}
Published: {{ post.date | date: "%B %e, %Y" }}
{{ post.excerpt }}
Read more »


Match Play. Double Match Point. How should Red play 53?
pips Red=108 White=133
(CorrectAnswer= 0/0, ErrorScore= 0)
Should Red make the five-point prime with 10/5, 8/5 (which is what I did over the board) or take a tempo with a hit to reduce White’s chances of making a full prime?
It turns out that both games plans are viable. Either of the hits, 10/7*, 8/3 or the apparently risky 10/7*, 10/5 (this is double match point so put them where you want them) have identical equities and the priming play 10/5, 8/5 is a mere 0.014 behind.
Virtually impossible to figure out over the board but I think I should have hit on principle!
It turns out that both games plans are viable. Either of the hits, 10/7*, 8/3 or the apparently risky 10/7*, 10/5 (this is double match point so put them where you want them) have identical equities and the priming play 10/5, 8/5 is a mere 0.014 behind.
Virtually impossible to figure out over the board but I think I should have hit on principle!
1. Cubeful 2-ply 10/7* 8/3 Eq.: -0.470 0.265 0.094 0.005 - 0.735 0.209 0.012 2. Cubeful 2-ply 10/7* 10/5 Eq.: -0.488 (-0.019) 0.256 0.088 0.005 - 0.744 0.264 0.015 3. Cubeful 2-ply 10/5 8/5 Eq.: -0.512 (-0.042) 0.244 0.072 0.003 - 0.756 0.135 0.005 4. Cubeful 2-ply 10/7* 6/1 Eq.: -0.519 (-0.049) 0.241 0.082 0.004 - 0.759 0.285 0.027 5. Cubeful 2-ply 6/1 4/1 Eq.: -0.584 (-0.115) 0.208 0.065 0.002 - 0.792 0.176 0.007


If you would like to Force Delete
{{system.namespace}}/{{system.name}}-{{system.version}}, please check with
your system administrator before running this command. This will follow
the standard shutdown process for
{{system.namespace}}/{{system.name}}-{{system.version}}. If an error
occurs, {{system.namespace}}/{{system.name}}-{{system.version}} will still
be deleted from the database.
If you would like to Force Delete
{{system.namespace}}/{{system.name}}-{{system.version}}, please check with
your system administrator before running this command.
{{system.namespace}}/{{system.name}}-{{system.version}} is managed by
another Garden, this request will only be executed locally. This only
deletes {{system.namespace}}/{{system.name}}-{{system.version}} from the
database and will not shutdown
{{system.namespace}}/{{system.name}}-{{system.version}} or remove RabbitMQ
queues.
Please review the original error message before proceeding.


WITNESS LIST Financial Institutions Committee February 25, 1997-2:00P HB 166 For: HENNEBERGER, JOHN (HIMSELF) HB 313 For: MAXEY, REP. GLEN (HIMSELF) HB 453 For: EILAND, REP. CRAIG (HIMSELF) HB 1266 For: BARRAZA, HECTOR (STEWART TITLE GUARANTY) GARCIA, KEVIN (HIMSELF) OLIVEIRA, REP. RENE (HIMSELF) WILLAIMS, REP. TOMMY (HIMSELF) On: PETTIJOHN, LESLIE (OFC CONSUMER CREDIT COM) HB 1375 For: NEELY, KAREN (IBAT) RODGERS, KELLY (TX BANKERS ASSOC) SANDBERG, ERIC (TX SAV & COMMUNTY BNKRS) HB 1402 For: TILLERY, REP. DALE (HIMSELF) Against: CLAYBAR, WILLIAM (TX FUNERAL DIRECTORS)


Blacksmith Camcad:
Welcome! What brings you here to see me? My family has been in the blacksmith business for more than 3 generations, so there's no job w can't handle. Ask me anything.
Craft a Dualsword.
Craft an item.
Learn skills.
Ask about Skill Enchanting.
Ask about the local lord and tax rate.
Quest


Sharepoint¶
Assuming an authenticated account, create a Sharepoint instance, and connect to a Sharepoint site.
#Create Sharepoint instance and connect to a site
from O365 import Account
acct = Account(('app_id', 'app_pw'))
sp_site = acct.sharepoint().get_site('root', 'path/tosite')
Common commands for sp_site
include .display_name
,
.get_document_library()
, .get_subsites()
, .get_lists()
,
and .get_list_by_name('list_name')
.
Accessing Subsites
If a Sharepoint site contains subsites they can be returned as a list of
Sharepoint sites by the .get_subsites()
function.
#Return a List of subsites
sp_site_subsites = sp_site.get_subsites()
print(sp_sites_subsites)
[Site: subsitename1, Site: subsitename2]
#Make another Site object from a desired subsite
new_sp_site = sp_site_subsites[0] #return the first subsite
Sharepoint Lists¶
Sharepoint Lists are accessible from their Sharepoint site using .get_lists()
which
returns a Python list of Sharepoint list objects. A known list can be accessed
by providing a list_name
to .get_list_by_name('list_name')
which will return
the requested list as a sharepointlist
object.
#Return a list of sharepoint lists
sp_site_lists = sp_site.get_lists()
#Return a specific list by name
sp_list = sp_site.get_list_by_name('list_name')
Commmon functions on a Sharepoint list include .get_list_columns()
,
.get_items()
, .get_item_by_id()
, .create_list_item()
,
.delete_list_item()
.
Sharepoint List Items¶
Accessing a list item from a Sharepoint list is done by utilizing .get_items()
,
or .get_item_by_id(item_id)
.
#Return a list of sharepoint list Items
sp_list_items = sp_list.get_items()
#Return a specific sharepoint list item by its object ID
sp_list_item = sp_list.get_item_by_id(item_id)
Creating & Deleting Sharepoint Items
A Sharepoint list item can be created by passing the new data in a dictionary
consisting of {'column_name': 'new_data'}
. Not all columns in the Sharepoint list have to
be accounted for in the dictionary, any Sharepoint List column not in the dictionary
will be filled with a blank. The column_name must be the internal column name
of the sharepoint list. .column_name_cw
of a sharepoint list will provide a
dictionary of {'Display Name': 'Internal Name'}
if needed.
#Create a new sharepoint list item
new_item = sp_list.create_list_item({'col1': 'New Data Col 1',
'col2': 'New Data Col 2'})
#Delete the item just created
sp_list.delete_list_item(new_item.object_id) #Pass the item ID to be deleted
Updating a Sharepoint List Item
Sharepoint list items can be updated by passing a dictionary of
{'column_name': 'Updated Data'}
to the .update_fields()
function of a
Sharepoint list item. The column_name keys of the dictionary must again refer
to the internal column name, otherwise an error will occur.
#Update a Sharepoint List item
new_item.update_fields({'col1': 'Updated Data Col1',
'col2': 'Updated Data Col2'})
#Once done updating a sharepoint item save changes to the cloud
new_item.save_updates() #Returns True if successful


Remote work¶
Because of the COVID-19 situation, the entire course will be done remotely. I have not done this before, so bear with me while I figure it out. Constructive feedback is encouraged!
Class time¶
The class is scheduled to start at 9:00 am, MWF. I will start a zoom meeting around 8:50 am each day. I will post the link in the slack
#general
channel.Please mute your microphone unless you are speaking
Breakout Rooms: We will make liberal use of breakout rooms during class. Be prepared to work in assigned pairs and small groups during class.
Please reserve the
#in_class
channel for discussions of class material. If something wacky is going on (you’re in a breakout room alone, you just got kicked off of zoom, jupyter suddenly stopped working etc.), please post this on#help.
We’ll monitor this as well and can chat with you there.When we start a breakout session, we will post a message on
#in_class
that says “WE NEED A TA!” While you’re in your breakout room, you can reply to the “WE NEED A TA” message to get help. Include your breakout room name in the message. (The breakout room name will be in the title bar of your main zoom window). We’ll react with a thumbs up and someone in as soon as we can.When there are a couple minutes left in the breakout session, we will post three interactive messages:
POINTS FOR DISCUSSION: Reply to this message with questions or thoughts you’d like to discuss in the main session. Emoji reactions on others’ questions help us judge which questions are most important to address as a whole group.
SOMETHING I LEARNED: Reply to this message with something(s) you learned during the breakout session that you did not know previously. Again, feel free to react to others.
ASSESSMENT POLL: Answer the poll so we can get a feel for overall understanding of the material.
If you have a question during the in-class discussion, you can Raise your blue hand
Material¶
Slack¶
Slack is going to be the primary means of communication in this class. You should have gotten an invitation to the slack organization for the class. If not, please email me.
Direct messages¶
I prefer slack to email; this is the best way to reach me for class business.
For content questions, please post on
#help
rather than sending a direct message so others can see.
Channels¶
#general
:I’ll post announcements here.
I’ll post zoom links to class and office hours here.
Feel free to use this to organize study sessions, group work, etc.
#random
:Fun stuff not directly related to the class.
Great for building community.
Remember to keep things respectful.
#in_class
:This channel is for conversations, questions, and polls from class.
Post questions and thoughts about course content on this channel at any time during the class session itself. (If you are having technical difficulties, please use
#help
during class).Reactions and replies to others’ questions will be very helpful.
I will post the
#in_class
log after each class.
#help
:Use this any time throughout the week if you have questions on homework or content.
Before posting, check recent entries to see if someone has already posed the question.
Do not email the TAs or me with content questions; put them on the channel so everyone can see them.
Feel free to reply to others, comment, etc. on each thread.
Use threads


--- layout: post title: Creating an array from a generic Java collection published: 1 category: - Programming ---
Whilst working on Jaggregate, I ran into some surprises involving Java generics (shocking, no?). Today's subject: turning a generic collection into an array.
The uppermost interface in Jaggregate's type hierarchy is Collection<E>. We might wish to ask such a collection for an array of its elements. If we don't really want to do anything with specific elements, we can simply define a toArray() method which answers an object of type Object[]:
interface Collection<E> {
Object[] toArray();
}
If you do want to manipulate the elements, you really want something like:
interface Collection<E> {
E[] toArray();
}
This method would need to create an array of the appropriate component type, populate the array, and return it. However, at runtime, the information about the type of E is no longer around; it gets discarded (erased) during compilation. Thus an invocation such as:
Collection<String> names;
String[] namesAsArray = names.toArray();
would raise a ClassCastException -- the best the runtime can do is create an Object[], which is-not-a String[], even if you try to cast the created array to E[] internally.
Fortunately, we can get around this problem by making the caller tell us what she wants the component type of the result to be:
interface Collection<E> {
Object[] toArray( Class<? super E> componentType );
}
Now, the client can hand us a Class object that represents E or any one of its ancestors, and the runtime can create an array of the appropriate component type via java.lang.reflect.Array.newInstance(componentType,size()). But wait, the return type of toArray() is still Object[]. The client has to downcast to, say, String[], but at least it will be a safe cast.
Can we do better? We want the return type to be some array type where the array's component type is a specified ancestor of E. Maybe making toArray() a generic method will help?
interface Collection<E> {
<T> T[] toArray( Class<T super E> componentType );
}
Doesn't compile.
interface Collection<E> {
<T,E extends T> T[] toArray( Class<T> componentType );
}
Doesn't compile either.
interface Collection<E> {
<T super E> T[] toArray( Class<T> componentType );
}
Nope. Bummer!
I resorted to a utility method:
class Collections {
public static <T,E extends T> T[] toArray(
final Collection<E> collection,
final Class<T> componentType ) {
}
}
Does anyone have a better idea? Note that I'm not interested in having the client create the array to populate and pass it to toArray(), as java.util.Collection requires.


In the previous chapter we tested our grammar to parse the nested elements,
but we have very limited (none, I would say) knowledge about how does the extracted structure look like.
So let us improve the output from the parser and add more information.
The direct output of a parser is typically very detailed and not well-readable.
It is called concrete syntax tree (CST), which is (in the case of PetitParser) array of arrays of arrays of ... with characters and strings as terminals.
It is the time to return a more convenient representation of the input: an abstract syntax tree (AST).
AST, contrary to the very low-level and detailed CST, is conceptually closer to the target domain.
In our case the domain should be some kind of a tree with html elements and javascript.
It is considered to be a good practice in PetitParser to split grammar, which returns CST, from parser, which returns AST.
We do this by subclassing WebGrammar:
1. Testing First
Parsing is great use case for test driven development.
So let us start with tests first.
Anyway, tests give us a clear idea what kind of interface we expect from abstract syntax tree:
And for malformed elements, we expect the following results:
And of course, we expect javascript code to be extracted as follows:
2. AST Nodes
If we want to pass these test, the result of a parse should be a tree consisting of three different nodes:
a javascript code;
an html element; and
a text.
We define these nodes as follows, starting with its abstract predecessor WebElement with some convenience methods.
JavascriptElement follows:
As well as HtmlElement:
Last but not least UnknownText:
3. From a Grammar to a Parser
Now we override the rules of WebGrammar in WebParser so that the javascript rule returns JavascriptElement, the element rule returns HtmlElement and the text rule returns UnknownText:
And finally, for convenience, we trim whitespaces around html elements:
There is trimRight in elOpen, which means that only the whitespace on the right is trimmed. This makes caching of PetitParser slightly more efficient, because element always starts at the first non-whitespace character. If there is a trimming from left and right (using the trim), it might start at any preceding whitespace or the first non-whitespace character and this would lead into lower cache-hit ratio (we will talk about caches later).
By this time all the tests should pass:
4. Structured Document
Now let us construct the whole HTML document.
All the pieces we need are already ready we just need to put them together.
In the previous chapters, we defined document (represented by the document rule) in WebGrammar as a repetition of javascript seas.
Now we define a structured document (structuredDocument), i.e. a document with an html structure.
Of course, we write tests first and we start with WebGrammarTest:
From the tests we see that the root of an html file is an element that can be surrounded by some other information (e.g. doctype or comments), therefore we define structured document as an element surrounded by a sea:
Furthermore, we verify that we extract the correct structure of the document.
This can be done in the WebParserTest:
In order to pass these tests, we create a root element called DOCUMENT in structuredDocument.
Furthermore we add to it the html element as well a its surroundings:
And we should remember to change the start method.
By this time all the tests should pass:
5. Comments
In this section we focus on HTML comments.
Comments can contain scripts or other elements that are not part of the html document (they are just comments that look the same).
And they may confuse the parser.
Actually they do and they do so in our tests as well!
There is an error in WebParser that we have not found.
It extracts one extra HTML element, which is not part of the HTML document.
Inspect the following and switch to the tree view:
There is a <p> element in the <body>.
But <p> is a part of a comment, it should not be included in the document structure.
First, we should fix the testStructuredDocument to cover this case:
So where does the problem come from?
The cause is the same as in the case of prematurely ended javascript.
WebGrammar has no notion of a comment and handles a content of a comment as an ordinary html code.
In order to teach it what is an html comment, we have to define it:
And now we can redefine text so that it takes comments into an account:
If you are interested in the details of the starLazy operator, check out the The starLazy Operator chapter.
This is it, we can parse all of it!
6. Conclusion
In this chapter we have applied the test-driven approach to define our AST nodes.
We defined WebParser, which extends the WebGrammar and builds the AST nodes.
Last but not least, we had a look how to avoid false positives caused by comments.


The computer is stuck thinking...
The computer is thinking of a clue...
The computer is choosing a tile...
-
{{ viewService.game.winner.toUpperCase() }} team wins!
-
{{ viewService.game.findPlayer(move.playerID).first }}
CPU
gave clue {{ move.word }} with {{ move.numMatches | number:0 }} matches
{{ viewService.game.findPlayer(move.playerID).first }}
CPU
guessed {{ move.word }}
Result:
{{ move.result }}
{{ viewService.game.findPlayer(move.playerID).first }}
CPU
passed


(info, amplitudes, phases) = rawRealFFT(u);
Raw interface to a function of the Kiss_FFT package to compute the FFT of a real, sampled signal. The input argument of this function is a Real vector u. size(u,1) must be even. An efficient computation is performed, if size(u,1) = 2^a*3^b*5^c (a,b,c Integer ≥ 0). The function computes a real FFT (Fast Fourier Transform) of u and returns the result in form of the outputs amplitudes and phases. Argument info provides additional information:
info = 0: Successful FFT computation. info = 1: size(u,1) is not even. info = 2: size(work,1) is not correct (= a protected utility array). info = 3: Another error.
Note, in the original publication about the efficient computation of FFT (Cooley and Tukey, 1965), the number of sample points must be 2^a. However, all newer FFT algorithms do not have this strong restriction and especially not the open source software KissFFT from Mark Borgerding used in this function.
(info, A, phases) = realFFT({0,0.1,0.2,0.4,0.5, 0.6})
function rawRealFFT extends Modelica.Icons.Function; input Real u[:] "Signal for which FFT shall be computed (size(nu,1) MUST be EVEN and should be an integer multiple of 2,3,5, that is size(nu,1) = 2^a*3^b*5^c, with a,b,c Integer >= 0)"; output Integer info "Information flag (0: FFT computed, 1: nu is not even, 2: nwork is wrong, 3: another error)"; output Real amplitudes[div(size(u, 1), 2) + 1] "Amplitudes of FFT"; output Real phases[div(size(u, 1), 2) + 1] "Phases of FFT"; end rawRealFFT;
| Date | Description |
|---|---|
| Nov. 29, 2015 | Initial version implemented by Martin R. Kuhn and Martin Otter (DLR Institute of System Dynamics and Control. |


Student at Girls Who Code Summer Immersion Program
Description:
Language Used: Scratch
Paddle ball is a game in which a ball bounces around a window, and the player moves a paddle back and forth across the screen to try and keep the ball up in the air.
Description:
Each turn, a player repeatedly rolls a die until either a 1 is rolled or the player holds and scores the sum of the rolls (i.e. the turn total). At any time during a player's turn, the player is faced with two options:
Roll: If the player rolls a 1, the player scores nothing for this turn, and it becomes the next player's turn. If the player rolls a number 2 - 6, the number on the die is added to the player's turn total, and the player's turn continues.
Hold: The player turn total is added to the player's overall score, and it becomes the next player's turn.
Language Used: Scratch
Description:
Include a clear user interface.
Allow users to create a playlist and play or stop the playlist entirely.
Allow users to choose between at least 3 different songs.
Language Used: Scratch
Description:
You can get a similar effect if you look at each pixel RGB, or red green blue, values. RGB values work like light.
If you add all the values together, you get a number that correlates to how “light the color is. Lighter colors get colorized yellow. Medium/light colors get coded as light blue. Medium/dark colors are red and very dark colors get coded as dark blue.Language Used: Python
Description:
We added multiple balls that bounce around the screen and flash different colors. Additionally, the ball will change sizes each time it hits the edge of the screen
Language Used: Python
Description:
Have you ever played a 2D video game and noticed how the background changes? Some of it moves slowly, like the clouds or mountains, and other parts move quickly, like the trees. You will utilize Python and Pygame to create a similar 2D animation where the background moves continuously across the screen.
Language Used: Python
Description:
Using your City Scroller as a background, create a game and make it your own with sprites!
Language Used: Python


Sidekiq monitoring apps
Asset Manager
Collections Publisher
Content Data Admin
Content Data API
Content Publisher
Content Tagger
Email Alert API
Imminence
Link Checker API
Locations API
Manuals Publisher
Publisher
Publishing API
Search Admin
Search API
Signon
Specialist Publisher
Support API
Transition
Travel Advice Publisher
Whitehall


Vote
Online
HOME
HOW IT WORKS
LOGIN
REGISTER AS A VOTER
Vote Here
#
CandidateProfile
CandidateName
Vote
1
Barrack Obama
2
Donald Trump
3
George W.Bush
4
Kanye-West
5
Mitchelle Obama
Show Result
Copyright (c) 2020 Collins Akumu


An interface to resources via HTTP.
The http library provides an interface to resources on the network via HTTP.
Begins an HTTP request.
The request function begins a request with the specified options. Returns a request object that may be resolved or canceled. Throws an error if the request could not be started.


For each email account, all the data for the account is stored (directly or indirectly) under one directory in the host file system. This is the "account directory". The account directory holds these kinds of data:
- The original MBOX files that are to be loaded into the DArcMail database.
- External content files
- .raw files produced by the DArcMail loading process.
- .xml files for email attachments produced by the DArcMailXml converson process.
The account directory may contain multiple subdirectories; for example, there may be a separate subdirectory for each email folder in the account. But while subdirectories are recommended for larger accounts, this is not necessary.
In DARcMail, every MBOX file corresponds to an email folder, and the host directory containing the MBOX file is the folder's "folder directory". If the MBOX file is located directly under the account directory, then the account directory and the folder directory are the same.


|
libcoap
4.3.0
|
Default implementation of internal clock. More...
Macros | |
| #define | COAP_TICKS_PER_SECOND ((coap_tick_t)(1000U)) |
| Use ms resolution on POSIX systems. More... | |
Typedefs | |
| typedef uint64_t | coap_tick_t |
| This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution. More... | |
| typedef time_t | coap_time_t |
| CoAP time in seconds since epoch. More... | |
| typedef int64_t | coap_tick_diff_t |
| This data type is used to represent the difference between two clock_tick_t values. More... | |
Functions | |
| void | coap_clock_init (void) |
| Initializes the internal clock. More... | |
| void | coap_ticks (coap_tick_t *t) |
Sets t to the internal time with COAP_TICKS_PER_SECOND resolution. More... | |
| coap_time_t | coap_ticks_to_rt (coap_tick_t t) |
| Helper function that converts coap ticks to wallclock time. More... | |
| uint64_t | coap_ticks_to_rt_us (coap_tick_t t) |
| Helper function that converts coap ticks to POSIX wallclock time in us. More... | |
| coap_tick_t | coap_ticks_from_rt_us (uint64_t t) |
| Helper function that converts POSIX wallclock time in us to coap ticks. More... | |
| COAP_STATIC_INLINE int | coap_time_lt (coap_tick_t a, coap_tick_t b) |
Returns 1 if and only if a is less than b where less is defined on a signed data type. More... | |
| COAP_STATIC_INLINE int | coap_time_le (coap_tick_t a, coap_tick_t b) |
Returns 1 if and only if a is less than or equal b where less is defined on a signed data type. More... | |
Default implementation of internal clock.
| #define COAP_TICKS_PER_SECOND ((coap_tick_t)(1000U)) |
Use ms resolution on POSIX systems.
Definition at line 137 of file coap_time.h.
| typedef int64_t coap_tick_diff_t |
This data type is used to represent the difference between two clock_tick_t values.
This data type must have the same size in memory as coap_tick_t to allow wrapping.
Definition at line 134 of file coap_time.h.
| typedef uint64_t coap_tick_t |
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition at line 122 of file coap_time.h.
| typedef time_t coap_time_t |
CoAP time in seconds since epoch.
Definition at line 127 of file coap_time.h.
| void coap_clock_init | ( | void | ) |
Initializes the internal clock.
| void coap_ticks | ( | coap_tick_t * | t | ) |
Sets t
to the internal time with COAP_TICKS_PER_SECOND resolution.
| coap_tick_t coap_ticks_from_rt_us | ( | uint64_t | t | ) |
Helper function that converts POSIX wallclock time in us to coap ticks.
| t | POSIX time is us |
| coap_time_t coap_ticks_to_rt | ( | coap_tick_t | t | ) |
Helper function that converts coap ticks to wallclock time.
On POSIX, this function returns the number of seconds since the epoch. On other systems, it may be the calculated number of seconds since last reboot or so.
| t | Internal system ticks. |
| uint64_t coap_ticks_to_rt_us | ( | coap_tick_t | t | ) |
Helper function that converts coap ticks to POSIX wallclock time in us.
| t | Internal system ticks. |
| COAP_STATIC_INLINE int coap_time_le | ( | coap_tick_t | a, |
| coap_tick_t | b | ||
| ) |
Returns 1
if and only if a
is less than or equal b
where less is defined on a signed data type.
Definition at line 193 of file coap_time.h.
| COAP_STATIC_INLINE int coap_time_lt | ( | coap_tick_t | a, |
| coap_tick_t | b | ||
| ) |
Returns 1
if and only if a
is less than b
where less is defined on a signed data type.
Definition at line 185 of file coap_time.h.


| Home | Libraries | People | FAQ | More |
STL and most other containers value initialize new elements in common operations
like vector::resize(size_type n)
or explicit
vector::vector(size_type n)
.
In some performance-sensitive environments, where vectors are used as a replacement for variable-size buffers for file or network operations, value initialization is a cost that is not negligible as elements are going to be overwritten by an external source shortly after new elements are added to the container.
Boost.Container offers two new members for
vector
, static_vector
and stable_vector
: explicit container::container(size_type n, default_init_t)
and explicit
container::resize(size_type n, default_init_t)
, where new elements are constructed using
default
initialization.
When filling associative containers big performance gains can be achieved
if the input range to be inserted is guaranteed by the user to be ordered
according to the predicate. This can happen when inserting values from a
set
to a multiset
or between different associative container families ([multi]set/map
vs. flat_[multi]set/map
).
Boost.Container has some overloads for constructors
and insertions taking an ordered_unique_range_t
or an ordered_range_t
tag
parameters as the first argument. When an ordered_unique_range_t
overload is used, the user notifies the container that the input range is
ordered according to the container predicate and has no duplicates. When
an ordered_range_t
overload
is used, the user notifies the container that the input range is ordered
according to the container predicate but it might have duplicates. With this
information, the container can avoid multiple predicate calls and improve
insertion times.
set
, multiset
,
map
and multimap
associative containers are implemented as binary search trees which offer
the needed complexity and stability guarantees required by the C++ standard
for associative containers.
Boost.Container offers the possibility to
configure at compile time some parameters of the binary search tree implementation.
This configuration is passed as the last template parameter and defined using
the utility class tree_assoc_options
.
The following parameters can be configured:
tree_type
).
By default these containers use a red-black tree but the user can use
other tree types:
optimize_size
).
By default this option is activated and is only meaningful to red-black
and avl trees (in other cases, this option will be ignored). This option
will try to put rebalancing metadata inside the "parent" pointer
of the node if the pointer type has enough alignment. Usually, due to
alignment issues, the metadata uses the size of a pointer yielding to
four pointer size overhead per node, whereas activating this option usually
leads to 3 pointer size overhead. Although some mask operations must
be performed to extract data from this special "parent" pointer,
in several systems this option also improves performance due to the improved
cache usage produced by the node size reduction.
See the following example to see how tree_assoc_options
can be used to customize these containers:
#include <boost/container/set.hpp> #include <cassert> int main () { using namespace boost::container; //First define several options // //This option specifies an AVL tree based associative container typedef tree_assoc_options< tree_type<avl_tree> >::type AVLTree; //This option specifies an AVL tree based associative container //disabling node size optimization. typedef tree_assoc_options< tree_type<avl_tree> , optimize_size<false> >::type AVLTreeNoSizeOpt; //This option specifies an Splay tree based associative container typedef tree_assoc_options< tree_type<splay_tree> >::type SplayTree; //Now define new tree-based associative containers // //AVLTree based set container typedef set<int, std::less<int>, std::allocator<int>, AVLTree> AvlSet; //AVLTree based set container without size optimization typedef set<int, std::less<int>, std::allocator<int>, AVLTreeNoSizeOpt> AvlSetNoSizeOpt; //Splay tree based multiset container typedef multiset<int, std::less<int>, std::allocator<int>, SplayTree> SplayMultiset; //Use them // AvlSet avl_set; avl_set.insert(0); assert(avl_set.find(0) != avl_set.end()); AvlSetNoSizeOpt avl_set_no_szopt; avl_set_no_szopt.insert(1); avl_set_no_szopt.insert(1); assert(avl_set_no_szopt.count(1) == 1); SplayMultiset splay_mset; splay_mset.insert(2); splay_mset.insert(2); assert(splay_mset.count(2) == 2); return 0; }
In the first C++ standard list::size()
was not required to be constant-time, and
that caused some controversy in the C++ community. Quoting Howard Hinnant's
On
List Size paper:
There is a considerable debate on whether
std::list<T>::size()
should be O(1) or O(N). The usual argument notes that it is a tradeoff with:
splice(iterator position, list& x, iterator first, iterator last);
If size() is O(1) and this != &x, then this method must perform a linear operation so that it can adjust the size member in each list
C++11 definitely required size()
to be O(1), so range splice became O(N).
However, Howard Hinnant's paper proposed a new splice
overload so that even O(1) list:size()
implementations could achieve O(1) range splice when the range size was known
to the caller:
void splice(iterator position, list& x, iterator first, iterator last, size_type n);
Effects: Inserts elements in the range [first, last) before position and removes the elements from x.
Requires: [first, last) is a valid range in x. The result is undefined if position is an iterator in the range [first, last). Invalidates only the iterators and references to the spliced elements. n == distance(first, last).
Throws: Nothing.
Complexity: Constant time.
This new splice signature allows the client to pass the distance of the input range in. This information is often available at the call site. If it is passed in, then the operation is constant time, even with an O(1) size.
Boost.Container implements this overload
for list
and a modified version
of it for slist
(as slist::size()
is also O(1)
).
Many C++ programmers have ever wondered where does good old realloc fit in
C++. And that's a good question. Could we improve vector
performance using memory expansion mechanisms to avoid too many copies? But
vector
is not the only
container that could benefit from an improved allocator interface: we could
take advantage of the insertion of multiple elements in list
using a burst allocation mechanism that could amortize costs (mutex locks,
free memory searches...) that can't be amortized when using single node allocation
strategies.
These improvements require extending the STL allocator interface and use make use of a new general purpose allocator since new and delete don't offer expansion and burst capabilities.
allocator
,
adaptive_pool
and node_allocator
classes.
allocator
: This
extended allocator offers expansion, shrink-in place and burst allocation
capabilities implemented as a thin wrapper around the modified DLMalloc.
It can be used with all containers and it should be the default choice
when the programmer wants to use extended allocator capabilities.
node_allocator
:
It's a Simple
Segregated Storage allocator, similar to Boost.Pool
that takes advantage of the modified DLMalloc burst interface. It does
not return memory to the DLMalloc allocator (and thus, to the system),
unless explicitly requested. It does offer a very small memory overhead
so it's suitable for node containers ([boost::container::list list],
[boost::container::slist slist] [boost::container::set set]...) that
allocate very small value_type
s
and it offers improved node allocation times for single node allocations
with respecto to allocator
.
adaptive_pool
:
It's a low-overhead node allocator that can return memory to the system.
The overhead can be very low (< 5% for small nodes) and it's nearly
as fast as node_allocator
.
It's also suitable for node containers.
Use them simply specifying the new allocator in the corresponding template argument of your favourite container:
#include <boost/container/vector.hpp> #include <boost/container/flat_set.hpp> #include <boost/container/list.hpp> #include <boost/container/set.hpp> //"allocator" is a general purpose allocator that can reallocate //memory, something useful for vector and flat associative containers #include <boost/container/allocator.hpp> //"adaptive_pool" is a node allocator, specially suited for //node-based containers #include <boost/container/adaptive_pool.hpp> int main () { using namespace boost::container; //A vector that can reallocate memory to implement faster insertions vector<int, allocator<int> > extended_alloc_vector; //A flat set that can reallocate memory to implement faster insertions flat_set<int, std::less<int>, allocator<int> > extended_alloc_flat_set; //A list that can manages nodes to implement faster //range insertions and deletions list<int, adaptive_pool<int> > extended_alloc_list; //A set that can recycle nodes to implement faster //range insertions and deletions set<int, std::less<int>, adaptive_pool<int> > extended_alloc_set; //Now user them as always extended_alloc_vector.push_back(0); extended_alloc_flat_set.insert(0); extended_alloc_list.push_back(0); extended_alloc_set.insert(0); //... return 0; }
The document C++ Extensions for Library Fundamentals (Final draft: N4480) includes classes that provide allocator type erasure and runtime polymorphism. As Pablo Halpern, the author of the proposal, explains in the paper (N3916 Polymorphic Memory Resources (r2)):
“A significant impediment to effective memory management in C++ has been the inability to use allocators in non-generic contexts. In large software systems, most of the application program consists of non-generic procedural or object-oriented code that is compiled once and linked many times.”
“Allocators in C++, however, have historically relied solely on compile-time polymorphism, and therefore have not been suitable for use in vocabulary types, which are passed through interfaces between separately-compiled modules, because the allocator type necessarily affects the type of the object that uses it. This proposal builds upon the improvements made to allocators in C++11 and describes a set of facilities for runtime polymorphic memory resources that interoperate with the existing compile-time polymorphic allocators.”
Boost.Container implements nearly all classes
of the proposal under the namespace boost::container::pmr
.
There are two groups,
polymorphic_allocator
.
monotonic_buffer_resource
.
unsynchronized_pool_resource
.
synchronized_pool_resource
.
get_default_resource
/
set_default_resource
/
new_delete_resource
/
null_memory_resource
pmr::vector
,
etc.)
Boost.Container's polymorphic resource library is usable from C++03 containers, and offers some alternative utilities if the required C++11 features of the Library Fundamentals specification are not available.
Let's review the usage example given in N3916 and see how it can be implemented using Boost.Container: Suppose we are processing a series of shopping lists, where a shopping list is a container of strings, and storing them in a collection (a list) of shopping lists. Each shopping list being processed uses a bounded amount of memory that is needed for a short period of time, while the collection of shopping lists uses an unbounded amount of memory and will exist for a longer period of time. For efficiency, we can use a more time-efficient memory allocator based on a finite buffer for the temporary shopping lists.
Let's see how ShoppingList
can be defined to support an polymorphic memory resource that can allocate
memory from different underlying mechanisms. The most important details are:
allocator_type
typedef. This allocator_type
will be of type memory_resource *
,
which is a base class for polymorphic resources.
ShoppingList
has
constructors taking memory_resource*
as the last argument.
ShoppingList
has
constructors taking allocator_arg_t
as the first argument and memory_resource*
as the second argument.
Note: In C++03 compilers, it is
required that the programmer specializes as true
constructible_with_allocator_suffix
or constructible_with_allocator_prefix
as in C++03 there is no way to automatically detect the chosen option at
compile time. If no specialization is done, Boost.Container
assumes the suffix option.
//ShoppingList.hpp #include <boost/container/pmr/vector.hpp> #include <boost/container/pmr/string.hpp> class ShoppingList { // A vector of strings using polymorphic allocators. Every element // of the vector will use the same allocator as the vector itself. boost::container::pmr::vector_of <boost::container::pmr::string>::type m_strvec; //Alternatively in compilers that support template aliases: // boost::container::pmr::vector<boost::container::pmr::string> m_strvec; public: // This makes uses_allocator<ShoppingList, memory_resource*>::value true typedef boost::container::pmr::memory_resource* allocator_type; // If the allocator is not specified, "m_strvec" uses pmr::get_default_resource(). explicit ShoppingList(allocator_type alloc = 0) : m_strvec(alloc) {} // Copy constructor. As allocator is not specified, // "m_strvec" uses pmr::get_default_resource(). ShoppingList(const ShoppingList& other) : m_strvec(other.m_strvec) {} // Copy construct using the given memory_resource. ShoppingList(const ShoppingList& other, allocator_type a) : m_strvec(other.m_strvec, a) {} allocator_type get_allocator() const { return m_strvec.get_allocator().resource(); } void add_item(const char *item) { m_strvec.emplace_back(item); } //... };
However, this time-efficient allocator is not appropriate for the longer lived collection of shopping lists. This example shows how those temporary shopping lists, using a time-efficient allocator, can be used to populate the long lived collection of shopping lists, using a general purpose allocator, something that would be annoyingly difficult without the polymorphic allocators.
In Boost.Container for the time-efficient
allocation we can use monotonic_buffer_resource
,
providing an external buffer that will be used until it's exhausted. In the
default configuration, when the buffer is exhausted, the default memory resource
will be used instead.
#include "ShoppingList.hpp" #include <cassert> #include <boost/container/pmr/list.hpp> #include <boost/container/pmr/monotonic_buffer_resource.hpp> void processShoppingList(const ShoppingList&) { /**/ } int main() { using namespace boost::container; //All memory needed by folder and its contained objects will //be allocated from the default memory resource (usually new/delete) pmr::list_of<ShoppingList>::type folder; // Default allocator resource //Alternatively in compilers that support template aliases: // boost::container::pmr::list<ShoppingList> folder; { char buffer[1024]; pmr::monotonic_buffer_resource buf_rsrc(&buffer, 1024); //All memory needed by temporaryShoppingList will be allocated //from the local buffer (speeds up "processShoppingList") ShoppingList temporaryShoppingList(&buf_rsrc); assert(&buf_rsrc == temporaryShoppingList.get_allocator()); //list nodes, and strings "salt" and "pepper" will be allocated //in the stack thanks to "monotonic_buffer_resource". temporaryShoppingList.add_item("salt"); temporaryShoppingList.add_item("pepper"); //... //All modifications and additions to "temporaryShoppingList" //will use memory from "buffer" until it's exhausted. processShoppingList(temporaryShoppingList); //Processing done, now insert it in "folder", //which uses the default memory resource folder.push_back(temporaryShoppingList); assert(pmr::get_default_resource() == folder.back().get_allocator()); //temporaryShoppingList, buf_rsrc, and buffer go out of scope } return 0; }
Notice that the shopping lists within folder
use the default allocator resource whereas the shopping list temporaryShoppingList
uses the short-lived
but very fast buf_rsrc
. Despite
using different allocators, you can insert temporaryShoppingList
into folder because they have the same ShoppingList
type. Also, while ShoppingList
uses memory_resource directly, pmr::list
,
pmr::vector
and
pmr::string
all
use polymorphic_allocator
.
The resource passed to the ShoppingList
constructor is propagated to the vector and each string within that ShoppingList
. Similarly, the resource used
to construct folder
is propagated
to the constructors of the ShoppingLists that are inserted into the list
(and to the strings within those ShoppingLists
).
The polymorphic_allocator
template is designed to be almost interchangeable with a pointer to memory_resource
,
thus producing a bridge between the template-policy
style of allocator and the polymorphic-base-class style of allocator.
This example actually shows how easy is to use Boost.Container to write type-erasured allocator-capable classes even in C++03 compilers.


Self-Organizing Maps implementation.
More...
#include <SOM.h>
|
| | SOM (int w, int h, int d) |
| | Overloaded Constructor. Weights are randomly assigned between [0,1). More...
|
| |
| | SOM (int w, int h, int d, BMDistType bmdistType, DistanceType distanceType) |
| | Overloaded Constructor. Weights are randomly assigned between [0,1). More...
|
| |
| void | train (const std::vector< std::vector< T >> &samples, unsigned int iterations, double s_learn_rate, double f_learn_rate, double neighborhoodSize) |
| | trains the SOM. If there are less samples than th #N of iterations, then the samples are repeated cyclically. More...
|
| |
| std::vector< T > | cluster (const std::vector< T > &sample) |
| | clusters the input sample. More...
|
| |
| virtual | ~SOM () |
| | Empty destructor. More...
|
| |
| T *const | nodeAt (int i, int j) const |
| | get node (neuron) weights at given position. More...
|
| |
| void | setNodeAt (int i, int j, const std::vector< T > &val) |
| | assign values to weights of the neuron at given indices. More...
|
| |
| void | load (const std::string &model_path, const SOMFileFormat &ff) |
| | loads the trained SOM network from the file. More...
|
| |
| void | save (const std::string &model_path, const SOMFileFormat &ff) |
| | saves the trained SOM to the file. More...
|
| |
| int | cols () |
| | get #N of columns (width) of SOM lattice More...
|
| |
| int | rows () |
| | get #N of rows (height) of SOM lattice More...
|
| |
| int | dims () |
| | get dimensions (codebook vector size) of SOM More...
|
| |
| T | calcBestMatchingUnit (const std::vector< T > &sample, int &y, int &x) const |
| | calculates Best Matching Unit (winning neuron). More...
|
| |
|
| T | euclideanDistance (const std::vector< T > &v1, const std::vector< T > &v2) const |
| | calculates Euclidean Distance between 2 vectors. More...
|
| |
| T | squaredEuclideanDistance (const std::vector< T > &v1, const std::vector< T > &v2) const |
| | calculates squared euclidean distance between 2 vectors. More...
|
| |
| T | calcGaussian (T mean, T stdDev, T x) const |
| | calculates Gaussian function of given x. More...
|
| |
| T | calcGaussian2D (T meanX, T meanY, T sigmaX, T sigmaY, T x, T y) const |
| | calculates 2D Gaussian function of given input pair (x,y). More...
|
| |
| T | calcGaussian2D (int meanX, int meanY, T sigma, int x, int y) const |
| | calculates 2D Gaussian function of given input pair (x,y). This method uses the same sigma for X and Y dimensions. More...
|
| |
| T | euclideanDistance (const std::vector< T > &v1, const T *v2) const |
| | calculates Euclidean Distance between 2 vectors. This method overloads () as second parameter is pointer to T for performance reasons. More...
|
| |
| T | dotProduct (const std::vector< T > &v1, const T *v2) const |
| | calculates Dot Product of 2 vectors. More...
|
| |
| T | cosineSimilarity (const std::vector< T > &v1, const T *v2) const |
| | calculates cosine similarity of 2 vectors. More...
|
| |
| T | L2norm (const std::vector< T > &v1) |
| | calculates L2 norm of a vector More...
|
| |
|
|
YAML::Emitter & | operator<< (YAML::Emitter &out, const SOM< T > &som) |
| |
|
void | operator>> (const YAML::Node &node, SOM< T > &som) |
| |
template<class T>
class SOM< T >
Self-Organizing Maps implementation.
◆ SOM() [1/2]
template<class T>
| SOM< T >::SOM |
( |
int |
w, |
|
|
int |
h, |
|
|
int |
d |
|
) |
| |
|
inline |
Overloaded Constructor. Weights are randomly assigned between [0,1).
- Parameters
-
| w | width |
| h | height |
| d | #N of dimensions (codebook size). |
◆ SOM() [2/2]
Overloaded Constructor. Weights are randomly assigned between [0,1).
- Parameters
-
| w | Width. |
| h | Height. |
| d | #N of Dimensions. |
| bmdistType | BMU update coefficients type. |
| distanceType | Distance metric type to use. |
◆ ~SOM()
◆ calcBestMatchingUnit()
template<class T>
| T SOM< T >::calcBestMatchingUnit |
( |
const std::vector< T > & |
sample, |
|
|
int & |
y, |
|
|
int & |
x |
|
) |
| const |
|
inline |
calculates Best Matching Unit (winning neuron).
- Parameters
-
| sample | input sample |
| y | index of the 0th dimension (rows) of the winning neuron |
| x | index of the 1th dimension (columns) of the winning neuron |
- Returns
- distance between BMU and sample
◆ calcGaussian()
template<class T>
| T SOM< T >::calcGaussian |
( |
T |
mean, |
|
|
T |
stdDev, |
|
|
T |
x |
|
) |
| const |
|
inlineprivate |
calculates Gaussian function of given x.
\( f(x)=\frac{1}{(\sigma \sqrt{(2\pi)}}e^{(\frac{-(x-\mu)^2}{2\sigma^2})} \)
- Parameters
-
| mean | mean of the Gaussian distribution |
| stdDev | standarad deviation |
| x | input value |
- Returns
- Gaussian function of the given x.
◆ calcGaussian2D() [1/2]
template<class T>
| T SOM< T >::calcGaussian2D |
( |
T |
meanX, |
|
|
T |
meanY, |
|
|
T |
sigmaX, |
|
|
T |
sigmaY, |
|
|
T |
x, |
|
|
T |
y |
|
) |
| const |
|
inlineprivate |
calculates 2D Gaussian function of given input pair (x,y).
\( f(x,y)=\frac{1}{(2\pi\sigma_x\sigma_y)}e^{(-[(x-\mu_x)^2/(2\sigma_x^2)+(y-\mu_y)^2 /(2\sigma_y^2)])} \) .
- Parameters
-
| meanX | mean value in X dimension. |
| meanY | mean value in Y dimension. |
| sigmaX | standarad deviation in X dimension. |
| sigmaY | standarad deviation in Y dimension. |
| x | input value (X dimension). |
| y | input value (Y dimension). |
- Returns
- 2d gaussian function value of the given (x,y) pair.
◆ calcGaussian2D() [2/2]
template<class T>
| T SOM< T >::calcGaussian2D |
( |
int |
meanX, |
|
|
int |
meanY, |
|
|
T |
sigma, |
|
|
int |
x, |
|
|
int |
y |
|
) |
| const |
|
inlineprivate |
calculates 2D Gaussian function of given input pair (x,y). This method uses the same sigma for X and Y dimensions.
\( f(x,y)=\frac{1}{(2\pi\sigma^2)}e^{(-[(x-\mu_x)^2+(y-\mu_y)^2]/(2\sigma^2))} \).
- Parameters
-
| meanX | mean value in X dimension. |
| meanY | mean value in Y dimension. |
| sigma | standarad deviation (sigmaVector=[sigma, sigma]) |
| x | input value (X dimension). |
| y | input value (Y dimension). |
- Returns
- 2d gaussian function value of the given (x,y) pair.
◆ cluster()
template<class T>
| std::vector<T> SOM< T >::cluster |
( |
const std::vector< T > & |
sample | ) |
|
|
inline |
clusters the input sample.
- Parameters
-
- Returns
- Winner neuron's weight vector, which corresponds to the most similar weights to input pattern.
◆ cols()
get #N of columns (width) of SOM lattice
- Returns
◆ cosineSimilarity()
template<class T>
| T SOM< T >::cosineSimilarity |
( |
const std::vector< T > & |
v1, |
|
|
const T * |
v2 |
|
) |
| const |
|
inlineprivate |
calculates cosine similarity of 2 vectors.
- Parameters
-
- Returns
- resulting scalar value of cosine similarity
◆ dims()
get dimensions (codebook vector size) of SOM
- Returns
◆ dotProduct()
template<class T>
| T SOM< T >::dotProduct |
( |
const std::vector< T > & |
v1, |
|
|
const T * |
v2 |
|
) |
| const |
|
inlineprivate |
calculates Dot Product of 2 vectors.
- Parameters
-
- Returns
- resulting scalar value of dot product
◆ euclideanDistance() [1/2]
template<class T>
| T SOM< T >::euclideanDistance |
( |
const std::vector< T > & |
v1, |
|
|
const std::vector< T > & |
v2 |
|
) |
| const |
|
inlineprivate |
calculates Euclidean Distance between 2 vectors.
- Parameters
-
- Returns
- euclidean distance
◆ euclideanDistance() [2/2]
template<class T>
| T SOM< T >::euclideanDistance |
( |
const std::vector< T > & |
v1, |
|
|
const T * |
v2 |
|
) |
| const |
|
inlineprivate |
calculates Euclidean Distance between 2 vectors. This method overloads () as second parameter is pointer to T for performance reasons.
- Parameters
-
- Returns
- euclidean distance
◆ L2norm()
template<class T>
| T SOM< T >::L2norm |
( |
const std::vector< T > & |
v1 | ) |
|
|
inlineprivate |
calculates L2 norm of a vector
- Parameters
-
- Returns
- scalar value of L2 norm.
◆ load()
template<class T>
| void SOM< T >::load |
( |
const std::string & |
model_path, |
|
|
const SOMFileFormat & |
ff |
|
) |
| |
|
inline |
loads the trained SOM network from the file.
- Parameters
-
///
- Parameters
-
◆ nodeAt()
template<class T>
| T* const SOM< T >::nodeAt |
( |
int |
i, |
|
|
int |
j |
|
) |
| const |
|
inline |
get node (neuron) weights at given position.
- Parameters
-
| i | index of the first dimension (rows) of the SOM lattice. |
| j | index of the second dimension (columns) of the SOM lattice. |
- Returns
- returns the pointer to Type T, which is the first element in the weight (codebook) vector of the corresponding SOM node.
◆ rows()
get #N of rows (height) of SOM lattice
- Returns
◆ save()
template<class T>
| void SOM< T >::save |
( |
const std::string & |
model_path, |
|
|
const SOMFileFormat & |
ff |
|
) |
| |
|
inline |
saves the trained SOM to the file.
- Parameters
-
| model_path | model file path |
| ff | file format |
◆ setNodeAt()
template<class T>
| void SOM< T >::setNodeAt |
( |
int |
i, |
|
|
int |
j, |
|
|
const std::vector< T > & |
val |
|
) |
| |
|
inline |
assign values to weights of the neuron at given indices.
- Parameters
-
| i | index at 0th dimension (rows) |
| j | index at 1th dimension (columns) |
| val | value to set. |
◆ squaredEuclideanDistance()
template<class T>
| T SOM< T >::squaredEuclideanDistance |
( |
const std::vector< T > & |
v1, |
|
|
const std::vector< T > & |
v2 |
|
) |
| const |
|
inlineprivate |
calculates squared euclidean distance between 2 vectors.
- Parameters
-
- Returns
- euclidean distance
◆ train()
template<class T>
| void SOM< T >::train |
( |
const std::vector< std::vector< T >> & |
samples, |
|
|
unsigned int |
iterations, |
|
|
double |
s_learn_rate, |
|
|
double |
f_learn_rate, |
|
|
double |
neighborhoodSize |
|
) |
| |
|
inline |
trains the SOM. If there are less samples than th #N of iterations, then the samples are repeated cyclically.
- Parameters
-
| samples | training samples with size of N*D where N is the number of samples and D is the number of dimensions of SOM. |
| iterations | #N of iterations |
| s_learn_rate | starting learning_rate |
| f_learn_rate | ending learning_rate |
| neighborhoodSize | neighborhood size, currently only sqare neighborhood is supported. |
◆ bmdistType
Best Matching Unit neighbour distance update type of the SOM.
size of the weight vector of the each node.
◆ distanceType
distance metric that is used when BMU is calculated see ()
◆ weights
template<class T>
| std::vector<T> SOM< T >::weights |
|
private |
The documentation for this class was generated from the following file: