text:
# Keeping iTunes podcasts up to date

The problem is that I still like to use my iPod nano. Or that I’ve come to rely on Downcast so much. Maybe I should just blame Apple and iTunes. Yeah, that sounds right—it’s Apple’s fault for making iTunes think it knows what I want better than I do.

I like listening to podcasts while I ride my bike, and when I do, I use a nano because:

1. It’s smaller and lighter than my iPhone.
2. I already have an armband for it.
3. It has a click wheel (5th gen) that’s easier to operate than a touchscreen while riding.
4. I can use it during a drizzle without freaking out.

For years I subscribed to podcasts in iTunes, synced them to the nano (or its predecessor, a 2nd gen nano, or its predecessor, a 2nd gen mini), and all was right with the world. Then things got complicated with the iPhone.

For quite a while, the iPhone wasn’t a complication. It synced through iTunes, too, and I seldom went more than a couple of days between syncs, so everything stayed up to date. Then iOS 5 came along and iPhone syncing became untethered from iTunes. Then apps like Instacast (which I used for a while) and Downcast (which is what I’ve used for the past year) cropped up, breaking the podcast link between the iPhone and iTunes. The iPhone became my main podcast listening device because it could download shows any time, anywhere.

The nano accepted its reduced status dutifully, but iTunes has balked. If I delete several episodes of a podcast from iTunes without listening to them on the nano (because I listened to them on the iPhone through Downcast), it pouts and refuses to automatically download any more. The little button that tells iTunes to check for and get new episodes turns from a curved arrow

into an exclamation point, and when you click on it you get this passive aggressive reply:

It’s almost like having a teenager in your computer.

There’s no setting in iTunes’ Preferences that turns this presumptuous behavior off—no doubt because iTunes is such a spare, minimal application that Apple couldn’t bear to clutter it with another option—and my Googling for a defaults write setting came up empty. So I complained about this on Twitter this morning, hoping that someone out there knew of a solution. The answer came from the improbably named h1ro,1 who pointed me to this script from the great Doug Adams and his collection of AppleScripts for iTunes. I should have known Doug would have figured this out already.

The script is called “Update Expired Podcasts” and it does exactly what you’d think from the title.2 As good as the script itself is, what’s even better is that Doug also provides a Launch Services plist file that’ll run the script periodically so I don’t have to do it by hand. I still have to manage episodes on each device separately, but at least my nano’s episode list won’t go stale anymore.

I suppose I could drop Downcast and use Apple’s own Podcasts app. That would, I think, keep episodes in sync with iTunes and my nano. But despite the recent update, Podcasts is still subpar. Until Apple puts some effort behind turning it into a decent app, I’m sticking with Downcast and Doug.

1. People who use pseudonyms on the internet are weird, don’t you think?

2. I’m really tired of Americans saying “it does what it says on the tin.” Stop adopting Britishisms, you wankers.


text:
# [kuangbin带你飞]专题五 并查集：A - Wireless Network（并查集）

An earthquake takes place in Southeast Asia. The ACM (Asia Cooperated Medical team) have set up a wireless network with the lap computers, but an unexpected aftershock attacked, all computers in the network were all broken. The computers are repaired one by one, and the network gradually began to work again. Because of the hardware restricts, each computer can only directly communicate with the computers that are not farther than d meters from it. But every computer can be regarded as the intermediary of the communication between two other computers, that is to say computer A and computer B can communicate if computer A and computer B can communicate directly or there is a computer C that can communicate with both A and B.

In the process of repairing the network, workers can take two kinds of operations at every moment, repairing a computer, or testing if two computers can communicate. Your job is to answer all the testing operations.

The first line contains two integers N and d (1 <= N <= 1001, 0 <= d <= 20000). Here N is the number of computers, which are numbered from 1 to N, and D is the maximum distance two computers can communicate directly. In the next N lines, each contains two integers xi, yi (0 <= xi, yi <= 10000), which is the coordinate of N computers. From the (N+1)-th line to the end of input, there are operations, which are carried out one by one. Each line contains an operation in one of following two formats:

1. “O p” (1 <= p <= N), which means repairing computer p.
2. “S p q” (1 <= p, q <= N), which means testing whether computer p and q can communicate.

The input will not exceed 300000 lines.

For each Testing operation, print “SUCCESS” if the two computers can communicate, or “FAIL” if not.

• 如果是字母‘O’，接下来会输入一个数字，代表中央会派出人员修好这台电脑；
• 如果是字母‘S’，接下来会输入两个数字u，v，询问u，v是否可以联机工作。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
struct node
{
int x,y;
} a[1010];
int fa[1010];
bool vis[1010];
int findf(int x)
{
if(fa[x]==x)   //就是这个地方困扰了我1个多小时，我眼瞎
{
return x;
}
else
{
return fa[x]=findf(fa[x]);
}
}
void unite(int x,int y)
{
x=findf(x);
y=findf(y);
if(x!=y)
fa[x]=y;
else
return ;
}
int main()
{
int n,m;
cin>>n>>m;
memset(vis,false,sizeof(vis));
for(int i=1; i<=n; i++)
scanf("%d%d",&a[i].x,&a[i].y);
for(int i=1; i<=n; i++)
fa[i]=i;
char s;
int pos;
while(~scanf(" %c",&s))
{
if(s=='O')
{
scanf("%d",&pos);
vis[pos]=true;
for(int i=1; i<=n; i++)
{
if(vis[i]==true&&i!=pos)
{
if((a[pos].x-a[i].x)*(a[pos].x-a[i].x)+(a[pos].y-a[i].y)*(a[pos].y-a[i].y)<=m*m)   //看距离够不够
{
unite(pos,i);
}
}
}
}
if(s=='S')
{
int u,v;
scanf("%d%d",&u,&v);
if(findf(u)==findf(v))
printf("SUCCESS\n");
else
printf("FAIL\n");
}
}
}

“男人啊，只要记得1就能活下去了。”

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

想要「替身」的伊丽莎白aru

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

03-04 599

11-01 665
02-23 1875
03-29 1753
01-27 2116
10-25 1398
09-27 239
02-14 177
04-07 671
09-17 1340
03-22 370
05-05 829
01-16 366

format: plain


text:
# Bounded convex function with no continuous boundary extension

Suppose ${f\colon \Omega\rightarrow\mathbb R}$ is a convex function on a bounded convex domain ${\Omega\subset\mathbb R^n}$. Does it have a continuous extension to ${\overline{\Omega}}$?

Of course not if ${f}$ is unbounded, like ${f(x)=1/x}$ on the interval ${(0,1)}$. So let’s assume ${f}$ is bounded. Then the answer is positive on one dimension, and easy to prove: ${f}$ is monotone in some neighborhood of a boundary point, and being bounded, must have a finite limit there.

In higher dimensions, the above argument does not work anymore. And indeed, a bounded convex function on a nice domain (like a disk) may fail to have a limit at some boundary points.

The example I describe is geometrically natural, but doesn’t seem to have a neat closed form equation. Let ${U}$ be the upper half of the open unit disk. Its boundary consists of the diameter ${I}$ and the semicircle ${C}$. Define

$\displaystyle f(x,y) = \sup \{\ell(x,y) : \ell \text{ is affine }, \ \ell \le 0 \text{ on }I, \ \ell\le 1 \text{ on }C\}$

Equivalently, take the convex hull of the set ${(I\times \{0\} )\cup( C\times \{1\})}$ in ${\mathbb R^3}$, and let ${z=f(x,y)}$ be the equation of its bottom surface.

This is a convex function by construction. It takes a bit of (routine) work to show that ${f}$ has limit ${0}$ everywhere on ${I}$, except the endpoints, and that it has limit ${1}$ on ${C}$, again except the endpoints. Consequently, there is no limit of ${f(x,y)}$ as ${(x,y)\rightarrow (1,0)}$.

Here’s a plot of ${f}$:

To obtain it in a reasonably efficient way, I had to narrow down the class of affine functions without changing the supremum. Note that if ${\sup_U \ell<1}$, then dividing ${\ell}$ by ${\sup_U \ell}$ gives a better contributor to the supremum. (This increases ${\ell}$ where it is positive, and the parts where it is negative do not matter anyway since ${f\ge0}$.)

Let ${(\cos t, \sin t)}$ be the point of ${C}$ where ${\ell }$ attains the value ${1}$. Then ${\nabla \ell}$ is parallel to the radius at that point. To fulfill the condition ${\ell\le 0}$ on ${I}$, the function must decay quickly enough along the radius toward the center. The required rate is found by projecting ${(\pm 1,0)}$ onto the radius: it is ${(1-|\cos t|)^{-1}}$. Hence, we only need to consider

$\displaystyle \ell(x,y) = \frac{x\cos t+y\sin t-|\cos t|}{1-|\cos t|}$

The one-parameter supremum over ${0 is not hard to evaluate numerically. Here is the Matlab code that produced the plot above.

[R,T] = meshgrid(0:.01:1, 0:.01:pi);
X = (2-R).*R.*cos(T); Y = (2-R).*R.*sin(T);
Z = zeros(size(X));
t = .001:.001:pi-.001;
for k = 1:length(t)
Z = max(Z, (X*cos(t(k))+Y*sin(t(k))-abs(cos(t(k))))./(1-abs(cos(t(k)))));
end
Z = min(Z, 1);
surf(X, Y, Z)

The truncation step Z = min(Z, 1); would be unnecessary in exact arithmetics, but it helps to cut out floating point errors.

The factor (2-R) is attached to polar coordinate transformation so that there are more polar circles near the boundary, where the function changes most rapidly.

Finally, note that the nonsmoothness of domain ${U}$ is not an issue here. The function ${f}$ naturally extends to a convex function on the open unit disk, by letting ${f=0}$ in the bottom half.

(Adapted from Extension of bounded convex function to boundary)


text:
# What goes on in a vacuum

1. May 29, 2005

### BoTemp

Generalized uncertainty principle: ((dA)*(dB)) >= 1/2*|<[A,B]>|
dA= standard deviation of the operator A, <Q>= <psi|Q|psi>

Now, I know people say that there can't be such thing as a true vacuum,
particles must be created and destroyed all the time, or else we'd know the
exact position & momentum, which would violate the heisenberg uncertainty
principle, a special case of the general uncertainty principle above
([pos,mom]= hbar*i). Normally, <psi|psi> is required to be 1, but in a true
vacuum, devoid of anything, psi=0. This would (trivially) satisfy the Schrodinger
equation, and though it wouldn't be normalizable, I don't see why it would have
to be, since by assumption there's nothing to be found there. In the above
equation, we'd get (dA)*(dB) >= 0. Presumably, we could measure both position
and momentum to be 0 every time.

So why can't a true vacuum exist?

2. May 29, 2005

### dextercioby

Nope.We can't.Vacuum state is normalized,therefore,even for the vacuum state,the uncertainty position-momentum holds.

Daniel.

3. May 29, 2005

### BoTemp

Can you explain that a bit more? I don't really see how a vacuum state is
normalized, if it's 0. psi = 0 solves the Schrodinger equation, allows for perfect
certainty in all measurements (0), but isn't normalizable. Basically, I'm asking
why it being non-normalizable is a problem.

4. May 29, 2005

### dextercioby

Nope.Vacuum state is defined as the Fock space vector which verifies

$$\langle 0|0\rangle =1$$

$$\hat{a}|0\rangle =0$$

for both bosonic & fermionic fields.

Daniel.

5. May 30, 2005

### BoTemp

Is $$\hat{a}$$ a symbol for any operator, or is it a specific operator?

6. May 30, 2005

### dextercioby

The annihilation operator for a spin 0 bosonic field.The notation is generic,though.

Daniel.

7. May 30, 2005

### BoTemp

Why must that necessarily be true? |0> can't be found as a function of
position, so there's no way to check it that way. My understanding is that
$$\langle \psi|\psi\rangle =1$$ is based on the fact that were we
to search the entire universe, we would necessarily find the particle. But in
the case of a vacuum, we wouldn't find anything. If

$$\langle \psi|\psi\rangle =0$$

then of course $$\psi = 0$$ mathematically, but I don't really see
anything wrong with that.

8. May 30, 2005

### dextercioby

Nah.It all comes from mathematics.Hilbert spaces,Fock spaces.Physics comes with probability conservation and necessity of unitary evolution.

The underlying structure is really mathematics.

Daniel.

9. May 31, 2005

### vanesch

Staff Emeritus
You are already assuming we work with a specific quantum system, namely a single point particle. The vacuum state of any specific quantum system is the state (or the states, in the case of a degenerate vacuum) of lowest energy (eigenstate of the hamiltonian).

Now, if you have a free particle, then the vacuum state doesn't correspond to psi(x) = 0, but to psi(x) = constant (you'll need box normalization here), which is the state of momentum 0.
Note that the state "there is no particle" which you probably identify with the "vacuum" state, is simply not a part of this quantum system, because in its very construction one has assumed the existence of a particle. So the "no particle" state is not a possible state of the system under consideration, in the same way it is impossible to give you the x,y and z coordinates of the vacuum in Newtonian mechanics.
If you work with a harmonic oscillator, then the vacuum state is the state which corresponds to the lowest energy, namely 1/2 hbar omega (a gaussian in position representation). In this case too, the vacuum state doesn't correspond to psi(x) = 0.

But usually, vacuum states are used when the quantum system is not a (set of) point particles, but rather a field. Then, there is no simple position representation psi(x) anymore. You just write out the theory, with the hamiltonian, and you look at the hilbert space vector which is the eigenstate with lowest eigenvalue for the hamiltonian. That's by definition the vacuum state.

cheers,
Patrick.

10. May 31, 2005

### BoTemp

Okay, I think I see what you're saying. We can't describe a space without any particles because the machinery of quantum mechanics is based on particle(s) existing. But does that prove that a space without particles
cannot exist? All it proves is that QM can't talk about it. Unless the theory
has been shown to be "complete", something which I don't think any physical theory could ever be proven to be, there still could be systems, like this one,
that QM won't work for.

Also, for a free particle, none of the energy states aren't normalizable:
$$\psi = A e^\frac{\pm i2mEx}{\hbar^2} +B e^\frac{\pm i2mEy}{\hbar^2} + C e^\frac{\pm i2mEz}{\hbar^2}$$ (I'm not sure about the constants
since this is from memory/extrapolation, but the gen. form should be right)

The psi above isn't normalizable; the only way $$\langle \psi|\psi\rangle$$ is finite is if A=B=C=0, and then $$\langle \psi|\psi\rangle =0$$. So one could use that to argue that QM can't describe particles in
a uniform potential of 0 (although such a thing doesn't exist in the universe
so it's not a big hole). So how can we be sure QM can be applied in any
way to a space with no potential and no particles (from now on I'll avoid
calling that a vacuum, since that definition isn't problematic in QM at all.)?

11. Jun 1, 2005

### dextercioby

Nope,those functions are normalizable in a rigged Hilbert space (a.k.a."Hilbertian triade").QM and QFT work with rigged Hilbert spaces only.So normalization is not a problem.Incidentally,the fact that a state vector is not normalizable in the Hilbert space of states,but in a larger space (the dual of the nuclear subspace),doesn't mean that free particles are not physical,it means they are not described by a plane wave,but by wave packets which are normalizable in $\tilde{M}$.

Daniel.

12. Jun 1, 2005

### vanesch

Staff Emeritus
No that's not what I said. QFT can describe a state without particles (indeed, the vacuum state). But then you don't have a wavefunction psi(x) anymore, which presupposes a single-particle position basis ; you have other descriptions (Fock space for instance) in which psi(x) doesn't really make much sense.

What I said was: IF YOU ASSUME PSI(x) to exist, you work with a VERY SPECIFIC QUANTUM SYSTEM, namely a one-particle quantum system. In THAT system, the notion of "no particle" is not present. But only because you set it up explicitly that way !

I tried to make an analogy with classical configuration space: imagine a 2-particle classical configuration space, which is R^6 (with tuples (x1,y1,z1,x2,y2,z2) ). So ALL configurations of the classical system correspond to a point in this R^6 configuration space. Now try to find me a point in R^6 that corresponds to: "there is only one particle" ; or "there are no particles" or "there are 3 particles". You can't. Each possible tuple of 6 numbers corresponds to two particles being somewhere in space.
Does that mean that classical physics cannot describe the situation "there is only one particle" ; or "there are no particles" or "there are 3 particles" ?
No, absolutely not. We just looked at A SPECIFIC EXAMPLE OF A CLASSICAL theory, which was built up around "there are 2 particles". What you don't put in, you can't get out, so you shouldn't be surprised that there are no possibilities, in this specific example, of describing 0, 1 or 3 particles.

In the same way, psi(x) only makes sense in the case of a single-particle quantum theory. So if you insist on having a psi(x), you are in this specific case, and then you shouldn't be surprised that you cannot describe 0 particles, or 2 particles, for that matter.

cheers,
Patrick.

13. Jun 4, 2005

### BoTemp

Ahhhhh, now I gotcha. Sorry for misunderstanding, that makes a certain amount of
sense. Would anybody happen to know a good introductory QFT text? I've only taken one semester of QM and I'm looking for more info. Thanks.

14. Jun 5, 2005

### Anomalous

Is it possible that space is infact matter but a different kinda something like waves but not waves. A matter not made of any particles but a continious lump. There reason I am asking this question is because it is said that space bends near blackholes, which means if we an instantly make the BH disapear then space would return to its normal dimensions in that region, so thats make me ask this question , can any body put some light on it ?


text:
# Public Lab Research note

This is an upgrade for thermal-flashlight. Try building it and report back how it goes.

# Visualight board for Thermal Flashlights

by warren | 15 Nov 17:35

### What I want to do

Leif Percifield's Visualight is an affordable Arduino-compatible USB-stick with a powerful RGB LED on it -- perfect for a thermal flashlight! So I jumped into just getting the colors to change. I'll try something with the Melexis infrared sensor later, but Leif left i2c pins open specifically so that we at Public Lab could connect such sensors! It's also open source. Leif is the best.

### My attempt and results

I made this Arduino sketch: https://gist.github.com/jywarren/7488213

It just blinks each LED in succession; real simple.

### Questions and next steps

Next up: connecting a power source (just a 2 AA battery USB power source) and the IR sensor. This thing is so compact, it'll fit nicely into a tube or other enclosure.

Help out by offering feedback!

### People who made this (0)

None yet. Be the first to post one!

Help out by offering feedback!

### People who did this (0)

None yet. Be the first to post one!

### 6 Comments

Leif's awesome, but I didn't get my visualight yet. I NEED. Where did you get this one?

Is this a question? Click here to post it to the Questions page.

Reply to this comment...

this wasn't the complete thing, just the stuffed boards, which Leif handed to me at the Barnraising.

Reply to this comment...

They've shipped!

Anyhow, I need to ask Leif where to connect the Melexis; on an Arduino Uno you can use the Analog 4 and 5 (as shown here: http://publiclab.org/notes/warren/12-12-2011/circuit-diagram-simple-thermal-flashlight)

From this page: http://arduino.cc/en/Main/ArduinoBoardLeonardo it looks like the 4th and 5th pin clockwise from the dot are A4 and A5 (as in the below image, marked with two magenta arrows); on the Visualight, these aren't used and might be quite hard to get to. But maybe Leif knows something we don't -- maybe on the Leonardo's chip, i2c (the protocol to connect to the Melexis temperature sensor) is assigned to different pins.

Reply to this comment...

Leif sez:

On the leonardo the I2C pins have separate pinouts on the board above the D13 connector. The visualight board exposes the I2C pins next to the LED and the should have silk screen markings...

Reply to this comment...

So i think those are the SDA/SCL pins marked here:

I'm reading on a pinout diagram of the Arduino Uno that A4 = SDA and A5 = SCL, so here's a crude Photoshopped diagram replacing the Arduino with the Visualight:

Be aware -- the Visualight supplies 5V so we have to use the 5V version of the Melexis sensor. Also, the resistors are 4.7k Ohm.

Who's gonna try it? Or better yet, make a little shield so we can make a bunch of these? We'd have to attach them to a USB battery pack, but it'll be really cool -- super bright and very compact.

Is this a question? Click here to post it to the Questions page.

Reply to this comment...

While I don't have a VisuaLight board to test on yet (I did just order what appears to be one of the last ones on Square?) I tried connecting the IR Eval board to a Leonardo as part of the work in this research note- http://publiclab.org/notes/code4maine/01-22-2014/thermal-flashlight-using-mlx90614-ir-evaluation-board-from-sparkfun.

While the original intent was to enable the outputs on the Eval board so as to eliminate the need for another Arduino, I have yet to get this to work. It does work as a standalone sensor with SCL-A5/SDA-A4 on the Uno. I wanted to try the same sketch (the standard bildr.org sketch) on an Arduino Micro as it is much smaller and would yield clues as to how the sensor would work with a 32u4. As both the Micro and Leonardo have dedicated SCL-SDA pins, I figured I would use these instead of A5-A4 on the Uno. Oddly enough, I couldn't even get that far as it wouldn't even let me compile the sketch while a Leonardo was selected in the dropdown. As soon as I change back to an Uno, it compiles and loads fine. I thought maybe the error output might be of some help-

ThermalReadingsRGBMapping_LED.ino: In function ‘void setup()’: ThermalReadingsRGBMapping_LED:29: error: ‘PORTC4’ was not declared in this scope ThermalReadingsRGBMapping_LED:29: error: ‘PORTC5’ was not declared in this scope ThermalReadingsRGBMapping_LED.ino: In function ‘void loop()’: ThermalReadingsRGBMapping_LED.ino:57: warning: unused variable ‘frac’[/code]

Is this a question? Click here to post it to the Questions page.

Reply to this comment...

Login to comment.


text:
## Introduction

Further climate change is inevitable1, but other pressing environmental and ecological threats are also widespread and intensify on Earth2, including land use changes, pollution, species invasions, diseases and resource overexploitation. These human-based impacts pose imminent hazards to people and species that compose and sustain ecosystems3,4,5. Quantifying the vulnerability of biodiversity—i.e., the degree to which biodiversity and associated functions are likely to change when exposed to multiple threats6—is thus crucial2,7 to rationalize ecosystem management and conservation actions8. Such a quantification is especially needed in the current context of budget limitations while new global CO2 emission and conservation targets are being set9. Despite major advances in our understanding of ecosystem vulnerability, shortcomings persist10,11,12,13. For example, the majority of studies only estimate vulnerability based on correlative species-environment relationships or expert judgements14. Further, vulnerability assessments generally focus on specific disturbances such as fishing15, flood events16, fire17, trawling18, wind farms19 or climate change20. However, the complexity of biological responses and the multi-threat nature of the Anthropocene demands conservation scientists to consider a wide range of disturbances in a more generalizable, standardized, and operational framework to assess ecosystem vulnerability21,22,23.

One of the main difficulties in ecosystem health assessment is the need for benchmarks, most often called ‘reference conditions’, to evaluate the status of ecosystems based on indices24,25,26. A reference condition is broadly defined as a baseline measure of an ecosystem variable (biological, chemical, or physical attributes) representative of minimal human influence or stress24,25,27. Despite the intuitive relevance of this concept for ecological assessment, the majority of ecological measures—including community-scale indices—are rarely compared to reference conditions, preventing end-users from fairly and operationally gauging impacts or restoration actions. Considering reference conditions to assess the vulnerability of any observed community therefore appears as a necessary step: it allows situating community’s response to disturbances relative to the widest range of possibilities, i.e., from the ‘least’ to the ‘most’ vulnerable community. Such conditions—or quasi-pristine areas—are now virtually absent for most ecosystems on Earth28,29 however, and past data about pre-human conditions are often biased and limited27. Moreover, the natural stochasticity in the Earth’s climate (e.g., volcanism, extreme meteorological events), the lack of data relative to the combined effects of various disturbances on biodiversity, and the extreme complexity of biological responses themselves30, still prevent accurate predictions of species community shifts under global changes31,32. Such unpredictability hampers our ability to cope with future environmental and socioeconomic changes, weakening management and conservation efforts. Assessing vulnerability therefore requires estimating community sensitivity and exposure by considering a wide range of disturbances rather than focusing only on a specific threat21,22,23.

Examining the diversity of organismal traits instead of their taxonomic classification can provide a more mechanistic understanding of community dynamics33,34,35, including their resilience to various environmental conditions and human impacts7,36. Here, we assume that the ‘functional vulnerability’ of a community to a wide range of disturbances relies on two components: (i) functional redundancy36,37, i.e. the extent to which different species share similar traits and are thus likely to sustain similar functions, and (ii) how species respond to different disturbances15,36. However, community functional redundancy is still often ignored in functional vulnerability assessments while responses to multiple threats are poorly known. Ecological theory predicts that communities composed of species with low redundancy across multiple traits may be more vulnerable to multiple disturbances since having only few functionally similar species, if not one, responding in diverse ways to these disturbances. In contrast, high functional redundancy is expected to provide many species per threat-response, i.e., a more even distribution of species redundancy across traits, which may buffer functional extinction risk38. Moreover, functionally distinct species are known to be highly vulnerable to many pressures such as overexploitation39, habitat loss40 and climate change41. Considering species traits, including their distinctiveness42, and their abundance, is therefore a necessary step in assessing the functional vulnerability of communities to multiple threats. Yet, a framework that considers the irreducible uncertainty and complexity of nature in terms of current and future environmental disturbances as well as species responses is still missing.

Here, we develop an integrative trait-based framework to quantify the functional vulnerability of biological communities to a wide set of potential disturbances while taking into account extreme cases of community responses as reference conditions. Based on species position, species abundances redistribution in the functional trait space and in silico simulations of disturbances, our framework considers functional rarity, redundancy and species abundances to quantify vulnerability in a multi-threats context. This study shows that our framework constitutes a promising tool to guide protection efforts even if trait-environment relationships and disturbance regimes are unknown, unpredictable or poorly documented. To test the applicability of our framework in both time and space, we consider three contrasting marine case studies: the past temporal dynamics of species abundances in North Sea fish communities, the current occurrences of marine mammals at global scale, and the projections of reef fish communities at global scale according to future climate.

## Results

### Functional vulnerability framework

To estimate the functional vulnerability of a given community, our framework estimates its capacity to maintain its set of traits using in silico simulations of random disturbances. More precisely, we compared the response of a given observed community with the response of virtual communities built from the observed community itself. These virtual communities are based on changes in (i) the distribution of functional redundancy across the trait space, (ii) abundance distribution across species, and (iii) relationship between species abundance and functional distinctiveness (Fig. 1a), all of which are key aspects of ecosystem functioning and resilience to disturbance. This results in a set of 15 virtual communities (Fig. 1a). Even if the objective of the framework is not to identify which community characteristic determines functional vulnerability, we expect the functional vulnerability of communities to decrease with (i) species redundancy across the trait space, (ii) more balanced abundances across species and (iii) positive relationship between species abundance and functional distinctiveness.

For any observed community, we built a regular grid cell on a two-dimensional trait space where species are located according to their traits43, the limits of the grid being defined by the upper, lower, leftmost and rightmost species in the trait space. We defined each cell as a ‘functional entity’ since the position in the trait space can be considered a proxy of species roles in ecosystems. This framework could be extended to multidimensional spaces, where the functional entities would then be defined as hypercubes. We then simulated a series of disturbances on the observed community and on each of its associated virtual communities. For each disturbance, we applied a decrease in the abundance of randomly selected species and recalculated new abundances. The number of functional entities, or grid cells, with at least one species still present was then quantified. These simulated disturbances were applied successively until total species and functional entity extinction (see rarefaction curves, Fig. 1b). The functional vulnerability index was then computed by quantifying the position of the rarefaction curve corresponding to the observed community in comparison to the most vulnerable virtual community and the least vulnerable virtual community (Fig. 1b, c).

To test the applicability of our framework in both time—e.g., recovery after abrupt and intense disturbance—and space—e.g., spatial prioritization for ecosystem management—we considered three contrasting marine case studies.

### Temporal vulnerability of North Sea fishes

We first applied our functional vulnerability framework on the past temporal dynamics of North Sea fishes (Fig. 2a). The North Sea has been subject to intense overfishing throughout the 20th century but has been managed since the end of the 1970s by the Common Fisheries Policy, with a progressive decrease in catch quotas and improvement in gears’ selectivity. We used abundance data from the International Bottom Trawl Survey (IBTS), an annual monitoring campaign designed to monitor fish and invertebrate communities in the North Sea annually since the 1980s (Fig. 2a) and to assess commercial species stocks. In combination with species abundance, and for each fish taxa, we selected eight traits linked to ecosystem functioning: age at maturity, asymptotic length, fecundity, offspring size, habitat (water column position), trophic level, feeding mode, and spawning type.

Our framework revealed a high functional vulnerability of fish communities in the North Sea. The functional vulnerability of observed communities was very close to that of the most vulnerable virtual community, with a value of 90% on average. We found a significant decrease in functional vulnerability throughout the last four decades of about 1.1% per decade (Pearson’s correlation test, r = −0.79, P < 0.001, n = 36), dropping from 92 to 86% (Fig. 2b). During the same period, species richness increased from 74 species in the 1980s to 117 species in the 2010s. The analysis also revealed that whatever the number of iterations performed, the vulnerability index remained almost unchanged (relative SD = 0.75%; see variation between light blue lines in Fig. 2b), indicating a high robustness in functional vulnerability assessment. The intra-year variability of functional vulnerability (i.e., the standard deviation of the 99 vulnerability values at each year; see Fig. 2b) was on average two times inferior to the inter-year variability, therefore indicating a good capacity of the framework to detect small temporal changes.

### Global patterns of marine mammals vulnerability

To test our framework on occurrence data, we used global range maps of 122 marine mammal species (http://www.iucnredlist.org). We transformed these range maps into a presence/absence matrix by overlaying species’ range maps and summed the number of species that occurred in each 1° grid cell20. Finally, we collected fourteen traits usually included in climate change vulnerability assessments, i.e. diet, foraging water depth, foraging location, fasting strategy, terrestriality, female sexual maturity, weaning, gestation length, inter-litter interval, breeding location, social group size, social behavior, adult body mass, sexual dimorphism (see ref. 20 for further details).

We detected a latitudinal gradient in the functional vulnerability of marine mammal communities, with the most vulnerable communities living at northern temperate latitudes (Fig. 3a, c). Opposite to the North Sea case study, we observed a weak but noticeable positive relationship between species richness and functional vulnerability for marine mammals (slope = 1.68; Pearson’s correlation test, r = 0.32, P < 0.001, n = 19681; Fig. 3b, d). This result suggests that species-rich communities may have lower trait redundancy across functional entities than species-poor communities. However, some species-poor regions display high functional vulnerability such as the eastern Mediterranean Sea, the Red Sea and the northeast Pacific. Similarly, certain areas—like Indonesian Islands or the South African coast—with high species richness have very low functional vulnerability, therefore supporting the expectation that species-rich communities may have, on average, lower functional vulnerability. Finally, we observed a substantial variation in functional vulnerability values in species-rich communities, starting around 25 species (Fig. 3d) suggesting a species richness threshold above which functional redundancy counterbalances the buffering effect of species richness on vulnerability.

### Future changes in reef fish vulnerability

We finally estimated how climate change could affect the global patterns of functional vulnerability in shallow-water reef fishes over the coming 60 years (2041–2070 compared to the period 1981–2015). To do so, we used species distribution models44 (see supplementary information) to forecast habitat suitability for 2320 species after integrating >12 million records of species occurrences extracted from open access databases (GBIF45, OBIS46) and local SCUBA transects (Reef Life Survey47,48, SERF49, GASPAR50). We used the SSP1-2.6 climate change scenario (Shared Socioeconomic Pathways combined with the Representative Concentration Pathway 2.623) that is inherent to the Paris Agreement that aims to sustainably limit global warming to less than 2 °C51. We chose twelve fish traits: age and length at maturity, maximum age, the asymptotic mass and length, the Von Bertalanffy growth coefficient (from FISHLIFE52), mobility, period of activity, schooling, vertical position, diet, and reef association (from the GASPAR traits database50).

Under the 2 °C warming scenario (i.e. SSP1-2.6), the forecasted functional vulnerability of fish communities on shallow-water coral and rocky reefs for the period 2041–2070 is expected to be lower in the tropics (Fig. 4a) where species richness is expected to remain high (Supplementary Fig. 11). As for the North Sea (case study 1), functional vulnerability is expected to be negatively related to species richness (Fig. 2b), yet with a threshold in species richness -of about 800 species- above which functional vulnerability rebounds towards higher values (Fig. 4b). As for marine mammals (case study 2), the distribution of functional redundancy in coastal fish communities, as well as their abundance distribution, counterbalanced the buffering effect of species richness above a certain richness threshold. Future functional vulnerability hotspots are identified around Southern Latin America, South Africa, Northern Hudson Bay, Nova Scotia and the Bering Sea (Fig. 4a). Conversely, the least vulnerable communities are located in Easter Islands, Northeast of French Polynesia and Saint Helena in the Southern Atlantic (Fig. 4a).

The global vulnerability of reef fish communities is expected to increase by 3 ± 10% on average until the end of the 21st century. Around 65% of the considered area is expected to experience an increase in functional vulnerability, with a mean increase of about 12%. Likewise, regions with decreasing functional vulnerability would experience a 11% decrease on average. Globally, polar areas, and especially in the Northern hemisphere, would benefit from a decrease in functional vulnerability whereas tropical, subtropical and some temperate latitudes would suffer from an increase in functional vulnerability over the coming decades (Fig. 4c). We also reveal the existence of certain peculiar locations like the Mediterranean Sea, Latin America and Africa (Fig. 4c) where functional vulnerability is expected to decrease.

## Discussion

Decision-makers are forced to minimize risk for adaptive management using partial or biased knowledge and by testing particular hypotheses14,53,54, whereas integrative approaches should provide a safer strategy. To overcome these difficulties, our framework offers a promising tool for assessing the level of functional vulnerability in biological communities and guide protection efforts where they are most needed. Moreover, our framework has the major advantage of estimating functional vulnerability by considering reference conditions and even if trait-environment relationships and disturbance regimes are unknown, unpredictable, or poorly documented, a step forward in comparison with previous works20,39.

Although a few previous works have investigated functional vulnerability43,55, our framework combines species functional distinctiveness, species abundance distribution and the distribution of functional redundancy across trait space. Most of all, it gives the advantage to provide an index with absolute values that allows end-users to gauge the intensity of functional vulnerability and to compare sites or periods. Beyond this novelty, our framework is agnostic to how traits mediate specific driver-effect relationships, so we can consider a large range of potential threats that could alter biological communities. Our framework then allows end-users to consider the vulnerability of a system more broadly than when vulnerability is assessed at the species scale or for only one given disturbance20. Indeed, considering the lack of knowledge inherent to the variety of pressures and the complexity of biological interactions at the community scale is a necessary step towards efficient ecosystem management56,57. Finally, our assessment of functional vulnerability can be applied on any kind of ecosystem or data across space and time (abundance, presence/absence, probability of presence).

Applied to North Sea fishes, we highlight a progressive recovery in demersal communities, which is consistent with previous studies showing the positive ecosystem response to the decrease in demersal destructive fishing (for example, trawling) observed in many European countries39,58. Such a congruence between our algorithm predictions and the recovery of the majority of North Sea fish stocks59, functionally common and distinct species39, further supports the robustness of our framework, which is based on no preconceived trait-environment relationships. This robustness is also reinforced by finding that functional vulnerability variation due to simulated random disturbances was three times lower than inter-annual variation. Despite the observed decrease in functional vulnerability over the study period, these results remind us that North Sea fish communities remain particularly vulnerable (90% on average during the last four decades), which is likely explained by the extreme intensity of human pressures in the North Sea during the 20th century60,61. Since the end of the 1970s, the exploitation of fish communities in Northeast Atlantic ecosystems has followed the Common Fisheries Policy, mainly characterized by the reduction of catch quotas and the improvement of gear selectivity39,62. These management regulations have therefore contributed to a progressive recovery of fish communities, including functionally common and distinct species in the North Sea39, which translates into a decrease of functional vulnerability. Even if the North Sea fish communities appear to be slowly recovering, efforts in the ecosystem approach to fisheries management (EAFM) must be maintained, as the absolute value of functional vulnerability remains particularly high. Because of the footprint left by the overfishing era in this part of the world, the observed decreases in functional vulnerability may not translate into healthier ecosystems.

We find that even in high-diversity systems, such as temperate and tropical regions, the richest communities of marine mammals are among the most vulnerable, supporting the idea that species richness should not be always considered as an umbrella but more likely acting as a buffer against vulnerability55. The higher marine mammal vulnerability at northern temperate latitudes was also documented by Albouy et al.20, who applied a different trait-based approach considering only the effect of climate change. This spatial congruence between the two studies supports the validity of our vulnerability framework, even where trait-environment relationships and disturbance regimes are poorly known. The detection of a positive relationship between species richness and functional vulnerability reinforces the idea that redundancy, and more specifically the distribution of redundancy within a given trait space, is a key element to consider, as the richest communities are not necessarily the most functionally redundant. Conversely, low functional vulnerability was observed in species-poor areas at polar latitudes. So relying on species richness as a proxy for functional redundancy is no longer valid.

Applied on the forecasted reef fish communities, our quantitative framework both revealed a latitudinal gradient in functional vulnerability and how that vulnerability will change in the next decades according to climate change. As expected, species richness appears as a buffer against functional vulnerability (Fig. 4b). However, as for marine mammals (case study 2), a threshold was observed above which the benefit of species richness is counterbalanced by other community characteristics like functional redundancy. The way species traits are distributed within communities can depend on species richness63 suggesting that the marked functional over-redundancy in species-rich communities may render them more vulnerable to disturbances. It should be noted that the forecasting models that we used only consider fishes’ realised environmental niches but ignore biotic habitat availability, which remains a critical step for further development. Additionally, sites where forecasted temperatures were outside of the species’ upper thermal niche limit were excluded to prevent any extrapolation. Finally, the selected climate change scenario and horizon in this paper are conservative since it follows SSP1-2.6 scenario by mid-century.

Beyond a simple assessment of functional vulnerability, which is necessary to better plan management actions, our framework also provides the fundamental benefit of better understanding how functional redundancy distribution, abundance distribution, and functional distinctiveness drive the vulnerability of communities. Moreover, despite constructing our index of functional vulnerability to be independent of species richness, in order to prevent trivial effects of species richness, contrasting and highly variable patterns were observed in the relationship between species richness and functional vulnerability. A positive effect of species richness was observed in the North Sea, while a negative relationship was observed for marine mammals. Such a result continues to fuel the diversity-stability debate where the positive effect of species richness is not ubiquitous64. Our study is another example showing that functional redundancy, and more specifically its distribution within species trait spaces, may exceed and sometimes counterbalance the effect of species richness, especially when species synchrony is high under random fluctuations, which is the case in most communities64,65.

Even if our framework provides an integrative assessment of functional vulnerability, meaning that it reflects the vulnerability to a wide panel of potential disturbances, we suggest that future studies could perform similar approaches based on virtual communities differing in functional structure (i.e., functional redundancy, abundances distribution and distinctiveness) where the probability to be impacted differs according to species sensitivity to specific disturbances instead of a random selection of species like we did here. We also highlight that our approach does not consider the extrinsic vulnerability inherent to the magnitude of environmental changes (i.e. exposure). Indeed, by performing repeated random disturbances on each community (i.e. each site or period), the amount of exposure is constant, so the only factor that drives the level of vulnerability is the species richness, trait and abundance composition within communities. To better define management and conservation strategies in space, the spatial heterogeneity of environmental and anthropogenic disturbances66,67 needs to be considered in combination with the intrinsic vulnerability requested by decision-makers. Additionally, selected traits should reflect well‐defined ecological roles or functions68 but the lack of data and consensus on the way to choose traits remains a limiting weakness in functional ecology69,70. In the worst case where no trait data exist, phylogenetic distances between species can be used as an alternative to compute phylogenetic instead of functional distinctiveness, as proposed by Carmona et al.71. We also highlight that our framework could be applied at very local scales when intraspecific trait information is available, all the way through to broad genus or family level traits when trait information is poor. While we assessed functional vulnerability by considering mean trait values for each species, we were unable to account for potential spatio-temporal variation in trait values due to insufficient data. Traits can be highly plastic and can vary in response to environmental (local adaptation) or ecological pressures (phenotypic plasticity) which in turn partly determine the level of functional vulnerability within communities. Finally, we argue that trait-based assessments of ecosystem vulnerability are important to help decision-makers and conservation policy. However, we raise the critical issue that taxonomic biases in trait data availability must be alleviated to avoid further conservation biases orientated towards emblematic and well-studied groups. Nonetheless, trait information is continuously growing72 for an increasing number of clades, therefore encouraging the confident use of trait-based integrative approaches for conservation perspectives.

The present framework provides only a relative assessment of the functional vulnerability (i.e. relative to all virtual communities constructed from the assessed observed community). The relative approach was chosen to prevent any trivial effect of species richness on vulnerability assessment71,73. Indeed, without a relative approach, a species-rich community would need more disturbances to collapse, therefore leading to higher AUC values (from rarefaction curves) and thus lower vulnerability values. The most undesired effect of a non-relative approach would be that some species-poor communities would be trivially identified as the most vulnerable ones while they may not be, and that most management efforts would have to focus on these communities74. For example, whilst species-poor temperate assemblages often show higher functional diversity than several richer tropical areas75, D’agata et al.76 and Parravicini et al.55 showed that species-rich systems are not functionally buffered against trait loss. Finally, although the spatio-temporal patterns generated by our framework are congruent with the few previous works that exist, none of these works has proposed an integrated assessment of vulnerability that takes a wide set of potential disturbances into account, therefore preventing an accurate assessment of the robustness relative to vulnerability magnitude.

Preventing ecological impacts of specific disturbance regimes is clearly insufficient, so considering both traits, reference conditions and all potential disturbance regimes appears critical for ecosystem health assessment. By minimizing the error risk in ecosystem health assessment inherent when integrating multiple disturbances, our framework therefore appears as a reliable tool for quantifying the effectiveness of management actions towards more resilient communities and identifying areas where conservation is and will be needed. Concretely, our framework provides an integrative estimate of ecosystem functional vulnerability that could provide key insight for achieving some Sustainable Development Goals targets77. The present framework will provide a critical tool for decision-makers to help identify management priorities based on the inherent vulnerability of ecosystem functions to disturbances and better guide the expansion of the current network of protected areas towards the next target of 30% coverage by 203078. Additionally, our framework can contribute to better identify which properties determine vulnerability to the myriad of threats biological communities will face in an uncertain future.

## Methods

### Virtual communities framework

The first step of the framework is to generate a multi-dimensional trait space that represents the functional similarity among all species79,80,81, to characterize the functional structure of a given community. The second step is to compute a distance matrix that quantifies the dissimilarity between all pairs of species based on their trait combinations. Here, we used the flexible Gower pairwise distance since it can handle multiple data types (from continuous to categorical traits) and is less sensitive to missing data than other distances81. We used the compute_dist_matrix() function in the funrar R package82. Finally, we performed a Principal Coordinates Analysis using the pcoa() function (ape R package) to transform pairwise species distances into a multi-dimensional space83. From this trait space of the observed community, we generated virtual communities by creating scenarios crossing three community properties: (i) distribution of functional redundancy in the trait space, (ii) distribution of abundance across species and iii) relationship between species trait distinctiveness and species abundance (Fig. 1). These virtual communities represented a panel of theoretical extremes of trait configurations within communities. For each of the three community properties, we used several modalities to characterize extreme cases.

For functional redundancy, we used three modalities: homogeneous, heterogeneous and the distribution of the observed community (Fig. 1). We achieved homogeneous and heterogeneous distributions by moving species within the trait space. To do so, we placed a 20 × 20 regular grid cell on the observed two-dimensional trait space (note that functional entities can be defined as multidimensional cells when the trait space has more dimensions), the limits of the grid being defined by the upper, lower, leftmost and rightmost species in the trait space. We defined each cell as a ‘functional entity’ since the position in the trait space is a proxy of species roles in ecosystems. We recommend considering only the two first PCoA axes as considering more axes would scatter species into a very high number of functional entities (i.e. grid resolution^number of selected PCoA axes) resulting in many more cells with only few or only one species in them. In extreme cases, every single functional entity would only hold one species, reducing the interest of the framework, since it is not likely to have so many functions and so few species per cell/functional entity/function. For homogeneous redundancy, the number of species per functional entity corresponds to the rounded (down) value of the ratio between the total number of species in the community (i.e., species richness S) and the number of functional entities (N) for which at least one species is present. For heterogeneous redundancy, we placed only one species within each functional entity and the rest of the species (S minus N) were all placed in the last functional entity having over-redundancy43.

We used three modalities to represent the distribution of abundances across species: homogeneous, heterogeneous, and the observed distribution of abundances between species (Fig. 1). We obtained the homogeneous distribution by attributing the same abundance to all species. We obtained the heterogeneous distribution of abundance by attributing only one individual to each species, except for the last one to which the rest of the total abundance was attributed. The total number of individuals in the virtual communities always equaled the total abundance of the observed community.

To infer the relationship between species trait distinctiveness and abundance, we selected two modalities: negative and positive (Fig. 1). Trait distinctiveness Di is an index quantifying how functionally dissimilar, on average, a given species is compared to all other species in the regional pool42,82

$${D}_{i}=\frac{{\sum }_{j=1,j\ne i}^{S}{d}_{{ij}}}{S-1}$$
(1)

where S is the total number of species within the species pool, and dij is the dissimilarity between species i and j. In this index trait dissimilarity was standardized and consequently the distinctiveness ranged between 0 and 1. A functionally distinct species, i.e., with a high value of Di, corresponds to a species with original trait values compared to the rest of the regional species pool. Distinctiveness values were computed using the distinctiveness() function of the funrar R package. To obtain negative or positive relationships between Di and species abundance, we ordered Di values and species abundances to attribute the highest abundances to the least or the most functionally distinct species, respectively.

For a given community that we aim to quantify the functional vulnerability, we simulated a series of disturbances on each of its associated virtual communities and on the observed community itself. At each disturbance, we applied a decrease in the abundance of randomly selected species (we recommend to apply a decrease of 5% of the total abundance of the community, the selected number of impacted species only impacting time calculation) and we recalculated new abundances and then the number of functional entities (i.e., grid cells) with at least one species still present. These simulated disturbances were applied successively until there were no remaining species in any functional entities (see rarefaction curves, Fig. 1b). Finally, the functional vulnerability of a community varied between 0 and 100% and was computed as follows:

$${Functional}\,{vulnerability}=100\,\times \frac{{{AUC}}_{{{{{\rm{obs}}}}}}-{{AUC}}_{{\min }}}{{{AUC}}_{{\max }}-{{AUC}}_{{\min }}}$$
(2)

With AUCmax being the area under the rarefaction curve relative to the least vulnerable virtual community (Fig. 1b), AUCmin the area under the curve (AUC) relative to the most vulnerable virtual community (Fig. 1b), and AUCobs the area under the curve relative to the observed community (Fig. 1b). A community for which functional vulnerability is equal to 0% will be the community that will lose its functions the slowest among all virtual communities (i.e., when the curve of the observed real community is superimposed to the one of the least vulnerable virtual community). By contrast, a community with functional vulnerability equal to 100% can be considered as the most vulnerable virtual community (i.e., when the curve of the observed real community is superimposed to the one of the most vulnerable virtual community). The entire statistical procedure can be repeated several times to prevent any overinterpretation (see the ‘Sensitivity analyses’ section).

### Adaptation of the algorithm to occurrence and habitat suitability data

Because presence/absence information is more accessible in ecological surveys, we developed a second algorithm to assess functional vulnerability when species abundance data are not available. While the statistical procedure was the same as the one developed in the abundance-based approach, the rarefaction curve of the observed community is here compared to the rarefaction curves of only two virtual communities characterized by opposite functional redundancy distributions (Supplementary Fig. 1) and species extinction were used as disturbance. To account for datasets containing probabilities of presence (or habitat suitability) usually computed from presence/absence data, we developed a third version of the algorithm. Disturbances are here characterized by a diminution of 0.05 on each value of habitat suitability (i.e. 5% of the maximum value 1). We applied three case studies demonstrating the application of our algorithms to these different forms of biodiversity data (i.e., abundance estimates, range maps, and habitat suitability models).

### Case study 1: Temporal vulnerability of North Sea fish communities

We applied our quantitative framework to estimate the functional vulnerability of the North Sea fish communities. We gathered abundance data from the International Bottom Trawl Survey (IBTS), an annual monitoring campaign that uses stratified random sampling to survey fish and invertebrate communities in 1° longitude × 0.5° latitude cells covering the entire North Sea each year in winter (Fig. 2a). Every year, at least two hauls were performed within each cell with a 3‐m vertical opening bottom trawl (GOV trawl) with a 10‐mm mesh codend during 30 min at an average speed of 4 knots. In each survey, fishes were identified and counted, and the resulting abundances were standardized to numbers of individuals per hour of trawling. The fish abundance data set included 168 taxa across 154 survey cells over 38 years (1983-2020), which represents a total of 13,433 hauls. Prior to statistical analyses, species abundances (across all survey cells and years) were log10(x + 1) transformed. We calculated the yearly mean abundance of each species at the scale of the North Sea to obtain one regional community per year from 1983 to 2020. Abundance data were downloaded from the International Council for Exploitation of the Sea data portal (ICES; https://datras.ices.dk/Data_products/Download/Download_Data_public.aspx). For this case study, each simulated disturbance corresponded to a decrease of 5% of the total abundance in the observed community.

In combination with species abundance, and for each fish taxa, eight traits encompassing life history, habitat use and trophic ecology—chosen because they are documented to mediate species influences on ecosystem functioning39,84—were collected from the PANGAEA traits database:85 age at maturity, asymptotic length, fecundity, offspring size, habitat (water column position), trophic level, feeding mode, and spawning type. We applied the abundance-based version of the algorithm to estimate the functional vulnerability of the North Sea fish community per year (https://figshare.com/s/9d3cd1d6f68a73dcea11).

### Case study 2: Global distribution of marine mammals vulnerability

Marine mammals range maps for 122 species were downloaded from the IUCN website (http://www.iucnredlist.org). From these range maps, we computed a presence/absence matrix by overlapping the species’ range maps and counted the number of species that occured in each 1° grid cell20. We collected fourteen traits covering five main functions (feeding, habitat, reproduction, social behavior) usually included in climate change vulnerability assessments (i.e., diet, foraging depth range, foraging fasting strategy, terrestriality, female sexual maturity, weaning, gestation length, inter-litter interval, social group size, adult mass body mass, sexual dimorphism, breeding location, social behavior; see ref. 20 for further details). For this case study, we applied the presence–absence version of our algorithm to estimate the functional vulnerability of each marine mammal community at global scale (https://figshare.com/s/5dcefa52f529ad34dc02).

### Case study 3: Future changes in functional vulnerability of reef fishes

In this last study case, we applied our algorithm to estimate how climate change could affect the functional vulnerability of global reef fish communities in 60 years (2041–2070 compared to the period of reference 1981–2015). To do so, we estimated the functional vulnerability of contemporary and future communities using species distribution models of 2320 species. The species distribution modeling framework is detailed in the supplementary information. In brief, we integrated > 12 million records of species presence from open access databases (GBIF45, OBIS46) and local SCUBA transects (Reef Life Survey47,48, SERF49, GASPAR50) (Supplementary Fig. 12). We extracted the environmental conditions of species’ presences for 6 environmental variables: sea surface temperature (SST; minimum and maximum), pH (minimum), sea surface salinity (SSS; minimum), net primary productivity (NPP; mean), degree heating weeks (mean; DHW86) and gravity of human impacts within 500 km2 (mean) and used these variables as covariates. Although we used three metrics containing information on sea surface temperature, SST-min and SST-max were not correlated with degree heating weeks which is a measure of heat stress rather than absolute temperature. We used generalized linear models, generalized additive models, and random forests—algorithms that cover a range of complexity relating the response variable to covariates—to explain the relationship between species presence and the local environmental conditions (see Supplementary Methods). For each model, we checked that the Pearson correlation between pairs of variables was <0.7, and if not, retained the variable with the highest deviance explained and lowest error rate (depending on the model algorithm, see below). We iterated this process until we obtained a set of uncorrelated and maximally explanatory variables. We used a target-group pseudo-absence approach87, whereby we generate 5-folds of background data which reduces model biases occurring in modeling presence-only data. We performed model evaluations using spatially blocked 5-fold out-of-sample predictions retaining only models with a true-skill statistic > 0.3588. Our models were well-calibrated having a mean sensitivity of 0.89 ± 0.06, specificity of 0.75 ± 0.09, TSS of 0.64 ± 0.12, and an AUC statistic of 0.84 ± 0.07 (Supplementary Fig. 13). Having well-performing models for 2320 species, we next predicted the habitat suitability of species in present-day environmental conditions and under environmental conditions for 2041–2070 under SSP1-2.6 climate change scenario (making separate suitability predictions based on projection outputs of seven CMIP6, Coupled Model Intercomparison Project phase 6, Earth system models89). We then assembled (mean-averaged) all predictions across all model algorithms, CMIP6 models and background data iterations to avoid spurious model outputs from these sources of uncertainty. We presented the SSP1-2.6 climate change scenario (Shared Socioeconomic Pathways 1 combined with the Representative Concentration Pathway 2.623) as it is inherent to the Paris Agreement that aims to limit global warming to less than 2 °C51. We modified the SST, SSS, pH, and NPP under future conditions but retained all other variables at their current day values. We only included DHW as a static variable for multiple reasons: (i) primarily to capture the effects of past thermal disturbances on current distributions, (ii) most locations globally will have degree heating weeks well beyond current values, leading to a high level of extrapolation in predicting into future scenarios90 (oppose to temperature which is only extrapolated in the tropics). Note that DHW had by far the lowest explanatory power of all variables on average across all species such that our results are likely to be robust to excluding degree heating week projections (if temperature change is already included as SST-min and SST-max). Finally, dispersal rates of species were constrained to 10 km per year, corresponding approximately to observed realized latitudinal range shifts of marine species91. All species maps were produced on a consistent 0.25° global grid that represents coastal and reef systems.

For this last case study, 12 traits were chosen: length at maturity, age at maturity, maximum age, the asymptotic mass and length, the Von Bertalanffy growth coefficient (from FISHLIFE52), mobility, period of activity, schooling, vertical position, diet, and reef association (from the GASPAR traits database50). We applied the suitability-based version of the algorithm to estimate the functional vulnerability (https://figshare.com/s/2c5fb050f2d2b9e01170).

### Sensitivity analyses

To test the potential influence of the number of disturbances series on AUC value and, therefore, on the functional vulnerability index, we performed sensitivity analyses (Supplementary Fig. 2). Applied to the North Sea fish community (case study 1), this analysis revealed that the relative standard deviation of AUC values remained particularly low (always less than 2% by median), regardless of the number of disturbances. For a good compromise between computation time and robustness, we applied 2 series of 500 disturbances on each community, which corresponds to 1.8% in uncertainty (see Supplementary Fig. 2). A sensitivity analysis was also carried out to test the influence of the grid resolution applied to the species traits space. A 20 × 20 grid cell resolution was the minimal resolution needed to get the most representative values of functional vulnerability (Supplementary Fig. 3).

Several analyses were performed to quantify the effect of missing trait data (i.e., Not Available, or NA in traits datasets) on final vulnerability values. To do so, the spatio-temporal distribution of NAs was firstly investigated and vulnerability values were recomputed by removing all species for which a NA was observed for at least one trait. We then compared the new vulnerability values to those obtained from the entire trait dataset (i.e., with all NAs). Additionally, we re-ran the analyses considering implemented traits tables (i.e., with all NAs replaced by estimated values), which were obtained using a random Forest technique (missForest: MissForest R package; Stekhoven and Bürhlmann92). For all case studies, vulnerability values presented a very low sensitivity to the NA items present in traits datasets, as their deletion and/or imputation did not substantially affect spatio-temporal patterns of vulnerability (Supplementary Figs. 49).

To investigate the effect of trait deletion on vulnerability patterns, the algorithm was applied for several trait combinations and by varying the total number of selected traits. For each number of selected traits, we performed 20 iterations (i.e. 20 combinations of randomly selected traits). We then compared final outputs to our reference values coming from the analysis based on all traits. For all case studies, vulnerability values present a very low sensitivity to trait deletion, as spatio-temporal patterns of the vulnerability were similar to those obtained from analyses using all traits (Supplementary Fig. 10).

All statistical analyses were performed under the R environment (version 4.1.0; R Core Team, 2021).

### Reporting summary

Further information on research design is available in the Nature Research Reporting Summary linked to this article.


text:
## Wednesday, March 6, 2019

### Philippines: Grid Impact Study for 120 MW Kalinga Geothermal Power Project Green-Lighted

DOE okays GIS of 11 power firms (BusinessMirror)

The Philippines Department of Energy (DOE) has issued the green light to 11 power firms to proceed with the conduct of a grid impact study (GIS) on their planned power projects with over 1,200 megawatts (MW) of capacity.

A clearance for the conduct of a grid impact study is necessary for a power firm before it can proceed with the construction of its power project.

Included in the list is the 120-MW geothermal power project of Aragorn Power & Energy Corp. in Kalinga, Luzon.


text:
×

CAKEWALK

PREREQUISITES:

Basics of looping, conditional statements in any language.

PROBLEM:

Given a string $s$, find whether exactly two different letters alternate in it or not. e.g. if $s$ = "ABABAB", then the answer will be yes or if $s$ = "ABC", then the answer would be no, if $s$ = "AA" answer would be no because the alternating characters should be different as stated in the problem.

EXPLANATION:

Given a string, first check the starting two characters, if they are the same (character is in consecutive position instead of alternating) then clearly the answer is NO. Otherwise we just have to check whether the first two characters (i.e. $s[0]$ and $s[1]$) are occurring in even and odd positions respectively or not.

Pseudo Code

 if(S[0]==S[1]) return false;
for(i=0; i+2 < N; i++)
if(S[i]!= S[i+2]) return false;
return true;

The above code first checks the first two character and if they are different then check the whole string whether it follows the alternating character condition. The time complexity of the algorithm is $\mathcal{O}(|s|)$ as we are iterating over all the characters of string s only once.

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution can be found here.
Tester's solution can be found here.

This question is marked "community wiki".

1951916
accept rate: 0%

19.8k350498541

 1 Your pseudo code is working wrong, cuz if u use a string for example: ABABABAAAAAAAAAA, then it gives true, which is false. answered 02 Mar '17, 18:42 12 accept rate: 0%
 0 Consider the test case when the string is : "ABA" What should be the output of this string? what does the alternate mean?:- "Pair of characters" should be in alternate for or "Single character" should be in alternate form. answered 23 Jun '16, 23:51 1 accept rate: 0% it will be true ABABABA format is correct if ABA is incorrect then strlen(s)%2!=0 cases directly gives NO but it;s not the case if strlen is 1 then it's true so u can understand it with this case. but odd length of string should be in test cases (07 Sep '16, 15:59)
 0 import java.util.*; class test { public void check() { Scanner sc=new Scanner(System.in); System.out.println("Enter the Stirng pattern"); String s=sc.nextLine(); int l=s.length(); int i=2; boolen flag=True; char c=s.charAt(0); char cc=s.charAt(1); if(c!=cc) { while(flag!=False) { while(i

include<string.h>

int main() { int t,i,len; char str[101]; scanf("%d",&t); while(t--) { int flag=0; scanf("%s",str); len=strlen(str); for(i=2;i<len;i++) { if(i%2==0) { if(str[i]==str[0]) { flag=1; } else { flag=0;break; } } else if(i%2!=0) { if(str[i]==str[1]) flag=1; else { flag=0;break; } } } if(flag==1) printf("YES\n"); else if(flag==0) printf("NO\n"); } return 0; }

1
accept rate: 0%

 0 Hi, for this exercise, i'm running the below code. But it keeps saying wrong answer on all the subtasks. I couldn't figure out why. Please review. t = int(input()) for i in range(t): str = input() if str[0] == str[1]: print('No') else: x = ''.join(set(str[::2])) y = ''.join(set(str[1::2])) if len(x) > 1 or len(y) > 1: print('No') else: print('Yes') answered 12 Sep '16, 17:47 1●1 accept rate: 0%
 0 how to solve it ?? help answered 11 Oct '16, 20:23 0★arjarjun 1 accept rate: 0%
 0 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class CodeChef1 { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Integer t = Integer.valueOf(reader.readLine()); while (t > 0) { String s = reader.readLine(); if(s.charAt(0)==s.charAt(2) && s.charAt(1)==s.charAt(3)) System.out.println("YES"); else System.out.println("NO"); t--; } }  } what is wrong in my code its showing runtime error.why? answered 20 Oct '16, 00:19 1 accept rate: 0%
 0 I am getting wrong answer for this plz someone tell whats the error int main() { string temp; long int k,x; cin>>k; while(k--){ long int count = 0,count1=0; cin >> temp; x=temp.length(); for(int i=0;i
 0 @shivamsst You're just checking only the first 3 characters of the string to make your decision. If the string, say s, is "ABABCDCD" your code will print "YES" since s[0] == s[2] ("A" == "A") and also s[0] != s[1] (since "A" != "B") but you did not check the rest of string if it matches the criteria! You should follow the pseudo-code given in the editorial. It is clean and compact. You will understand it easily. answered 18 Dec '16, 10:32 371●2 accept rate: 23%

include<bits stdc++.h="">

using namespace std; int main() { int t; scanf("%d",&t); while(t--) { string s; cin>>s; char a,b; int l=s.size(),f=0; for(int i=0;i<l;i++) { if(i==0) a=s[i]; if(i==1 && s[i]!=a) b=s[i]; else if(s[i]==a && i==1) { f=1; break; } if((i%2!=0 && s[i]!=b)||(i%2==0 && s[i]!=a)) { f=1; break; } } if(f==0) cout<<"YES"; else cout<<"NO"; cout<<endl; } return 0; }

5★salman_1
1
accept rate: 0%

what is wrong in this code not understanding

include <stdio.h>

int main() { int t,i,c; char s[110]; scanf("%d",&t); while(t--) { scanf("%s",s); c=0; int l=strlen(s); if(l==2&&s[0]!=s[1]) {printf("YES\n");} for(i=0;i<l-2&&l>2;i++) { if(s[i]==s[i+2]) c=1; else{ c=0; } if(c==0) printf("NO\n"); break; }

    if(c==1)
{
printf("YES\n");
}

} }

1
accept rate: 0%

 0 Umm there could be a better approach but it isn't working and I really don't know why... My logic was to extract a string from index 0 to 1 and then replace its occurrences in the original string by "", now if the length of resultant string is empty o/p "YES" else "NO"... here's my snippet for this : if(s.length()%2!=0) return "NO"; else { String temp = s.substring(0,2); s = s.replaceAll(temp, ""); if(s.length()==0) return "YES"; else return "NO"; } but it shows wrong o/p pls help answered 17 Jun '17, 19:46 1 accept rate: 0% Your method is actually better. The only problem is- your code ouputs "NO" for all cases where the length is odd numbered. This is not correct. Example- "ABA" answer should be YES, but your code gives no. Same goes with ABABA, which should actually give "YES". (26 Jun '17, 16:40)
 0 should ABA and ABABAC give YES? answered 17 Jul '17, 14:07 20●5 accept rate: 0%
 0 should ABA and ABABAC give YES? answered 17 Jul '17, 14:07 20●5 accept rate: 0%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×1,652
×54

question asked: 16 Apr '15, 16:01

question was seen: 4,799 times

last updated: 26 Jun '17, 16:40


text:
# Array flatten with recursion

I'd been using this form for a while now with the functional methods map, filter, reduce:

// For example...
$result = array_reduce(array_map(function($value) {
return explode('-', $value); },$input), function($carry,$item) {
return array_merge($carry,$item);
}, array());

The array_reduce() part, where I need to collapse depth in the result. So I was thinking about this, and this is what I came up with. It actually works as a callback to array_reduce() too:

/**
* Flatten a multi-dimensional array to a single-level array,
* sorting the entries in order to depth first.
*
* @param array $carry Array to initialize, will be the subject if the only argument passed. * @param mixed$subject Optional Array or value that has data in potential multi-dimensions.
*
* @return array
*/
function array_flatten(?array $carry = [],$subject = null): array
{
return array_reduce((array) ($subject ??$carry), function(array $carry,$item) {
return is_array($item) ? array_flatten($carry, $item) : array_merge($carry, (array) $item); },$subject !== null ? (array) $carry : []); // Don't merge onto the$subject...
}

https://3v4l.org/J1NeJ

Thing is, the way it works, I think it literally goes one level further than there are levels to traverse. The reason I think this is because the array_merge() is getting passed a "boxed" element. So the way I'm adding to the array is to box/unbox an array wrapper so it can be merged.

That seems like the most amount of extra effort for one little thing; it happens to every non-array it comes across. Questioning whether I should use it.

It can be called like array_reduce():

array_reduce([1,2,[3,[4]],5], 'array_flatten');

Or more likely:

array_flatten([1,2,[3,[4]],5]);

Is this something I should avoid?

array_walk_recursive() traverses your "leaf nodes" for you in one step:

Code: (Demo)

//$multi=[1,2,[3,[4]],5];$multi=[array('A',
array('B',
array('CC','CCCC','CCCCCC'),
array('DDD','EFG','HIJ','LMNOP')
)
),
array('2'),
'b',
array(array(),array(),array())];
array_walk_recursive($multi,function($v)use(&$flat){$flat[]=$v;}); var_export($flat);

Output:

array (
0 => 'A',
1 => 'B',
2 => 'CC',
3 => 'CCCC',
4 => 'CCCCCC',
5 => 'DDD',
6 => 'EFG',
7 => 'HIJ',
8 => 'LMNOP',
9 => '2',
10 => 'b',
)

• Yeah, but passing and using a referenced array in functional programming is entirely beside the point. That's simply a shorthand-ish way of writing a recursive for loop without the for syntax. – Jared Farrish Oct 1 '17 at 14:26
• – Jared Farrish Oct 1 '17 at 14:56

I don't see the benefit of being able to call array_flatten() from array_reduce(). If there is an important use, please let me know as I'd like to be educated on this point. My code to follow cannot be called like this: array_reduce([1,2,[3,[4]],5], 'array_flatten'); as yours was designed to do.

I have made a few modifications and have a php<7 friendly version to offer... more specifically, I've omitted the type (and nullable) declarations and null coalescing operator so that PHP<7 versions can use the snippet. I'm not suggesting that your type declarations are a bad idea, I only mean to make the function more usable to a wider audience.

Code: (Demo)

$multi=[['A',['B',['CC','CCCC','CCCCCC'],['DDD','EFG','HIJ','LMNOP']]],['2'],'b',[[],[],[]]]; function array_flatten($array,$accumulator=[]){ return array_reduce($array,function($carry,$item){
return is_array($item) ? array_flatten($item,$carry) : array_merge($carry,[$item]); },$accumulator);
}
var_export(array_flatten($multi));  • There isn't a benefit, it's just that it fits the same signature. That was for the recursion. – Jared Farrish Oct 2 '17 at 13:30 If you're just working on arrays this might satisfy your functional urge for selecting out of a deep data structure: function recursive_select($data,
callable $callback,$flag = RecursiveIteratorIterator::SELF_FIRST,
$preserve_keys = FALSE ) { return iterator_to_array(new CallbackFilterIterator( new RecursiveIteratorIterator( new RecursiveArrayIterator($data),
$flag ),$callback
), $preserve_keys); }  Usage here: https://3v4l.org/TDIvu $multi=[['A',['B',['CC','CCCC','CCCCCC'],['DDD','EFG','HIJ','LMNOP']]],['2'],'b',[[],[],[]]];
$array = array(1,2,[3,4],5,'six',array(array('78',9)),10);$multi_output = recursive_select($multi, function ($value, $key,$iterator) : bool {
return is_string($value); });$array_output = recursive_select($array, function ($value, $key,$iterator) : bool {
return is_numeric($value) || is_string($value);
});

var_dump($multi_output,$array_output);

Output:

Array
(
[0] => A
[1] => B
[2] => CC
[3] => CCCC
[4] => CCCCCC
[5] => DDD
[6] => EFG
[7] => HIJ
[8] => LMNOP
[9] => 2
[10] => b
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => six
[6] => 78
[7] => 9
[8] => 10
)

If you need something that works like that on objects and arrays I've got a version for that, its not a quite a one liner though because behaviour changed subtly in RecursiveArrayIterator between PHP 5 and 7 despite what the PHP documentation says on this :|

The $iterator parameter has a method on it called getDepth() which can be used for fetching from a particular level within the comparison function • Sorry for the late response. I like it, with the only quibble I have being that the $callback requires a signature that embeds a requirement the function itself doesn't have, which makes it feel weird to me. So it really feels like syntactic glue. – Jared Farrish Dec 3 '17 at 14:38
• The signature of the callable of recursive_select is compatible with array_filter rather than array_reduce, if you wanted to accumulate I'd suggest filtering with recursive_select and then accumulating after, filtering and accumulating in the same loop with array_reduce is closer to common foreach behaviour imo, where as the result of array_filter/recursive_select forces you to name your selection, which means it's easy to do multiple operations on it, whilst inside array_reduce accumulation and filtering is tightly coupled and hard to pass outside the function in a non accumulated fashion – arcanine Dec 11 '17 at 13:24
• That said, there can always be other things to consider like performance , or you may know you will not need access to the filtered data ever again, context trumps all if you're not ignorant to the trade offs being made, personally I err on the side of profiling first and being ready for code mutations that will need to occur in the future – arcanine Dec 11 '17 at 13:45


text:
# INCANG

Returns the included angle defined using three markers: I,J, K. Angle between the line connecting I with J and the line connecting J with K is reported. As the simulation proceeds, the first non-zero value is always positive.

INCANG(I,J,K)

## Arguments

I, J, K
The markers used to define the included angle.

## Example

<Reference_Variable
id   = "100"
type = "EXPRESSION"
expr = "INCANG(112, 113, 114)"
/>


text:
Project deliverable Open Access

# WhoLoDancE: Deliverable 1.3 - Workshop report

El Raheb, Katerina; Katifori, Akrivi

### DataCite XML Export

<?xml version='1.0' encoding='utf-8'?>
<identifier identifierType="DOI">10.5281/zenodo.1042369</identifier>
<creators>
<creator>
<creatorName>El Raheb, Katerina</creatorName>
<givenName>Katerina</givenName>
<familyName>El Raheb</familyName>
<affiliation>Coventry University</affiliation>
</creator>
<creator>
<creatorName>Katifori, Akrivi</creatorName>
<givenName>Akrivi</givenName>
<familyName>Katifori</familyName>
<affiliation>Coventry University</affiliation>
</creator>
</creators>
<titles>
<title>WhoLoDancE: Deliverable 1.3 - Workshop report</title>
</titles>
<publisher>Zenodo</publisher>
<publicationYear>2016</publicationYear>
<subjects>
<subject>workshop</subject>
<subject>dance</subject>
<subject>technology</subject>
<subject>learning</subject>
</subjects>
<dates>
<date dateType="Issued">2016-08-31</date>
</dates>
<language>en</language>
<resourceType resourceTypeGeneral="Text">Project deliverable</resourceType>
<alternateIdentifiers>
<alternateIdentifier alternateIdentifierType="url">https://zenodo.org/record/1042369</alternateIdentifier>
</alternateIdentifiers>
<relatedIdentifiers>
<relatedIdentifier relatedIdentifierType="DOI" relationType="IsVersionOf">10.5281/zenodo.1042368</relatedIdentifier>
<relatedIdentifier relatedIdentifierType="URL" relationType="IsPartOf">https://zenodo.org/communities/wholodance_eu</relatedIdentifier>
</relatedIdentifiers>
<version>6.0</version>
<rightsList>
<rights rightsURI="info:eu-repo/semantics/openAccess">Open Access</rights>
</rightsList>
<descriptions>
<description descriptionType="Abstract">
This document reports on the activities of the&nbsp;WhoLoDancE&nbsp;workshop which took place on the 6th and 7th of July in Thessaloniki, entitled &quot;Dancing with Technologies: Interact to learn, analyze to create&quot;. The workshop has been mainly organized by ATHENA RC with the collaboration and support of all other&nbsp;partners of the WhoLoDancE&nbsp;project&nbsp;and it was a Satellite event of the 3rd International Symposium on Movement Computing.&nbsp;At first,&nbsp;we describe the objectives of the workshop which are in alignment with the objectives of the first stage of the WhoLoDancE&nbsp;project in general and WP1 Learning Models and Technical Requirements. In particular, this work package&nbsp;aims&nbsp;to&nbsp;create&nbsp;a common&nbsp;understanding&nbsp;about&nbsp;the needs of dance learning in terms of technology and&nbsp;define&nbsp;its&nbsp;relations&nbsp;with whole-body interaction experiences within the context of the state-of-the-art and relevant achievements.&nbsp;In what follows the report&nbsp;describes&nbsp;the collaboration with the&nbsp;3rd International Symposium&nbsp;on&nbsp;Movement Computing (MOCO2016) and the organization of&nbsp;WhoLoDancE&nbsp;workshop&nbsp;as a&nbsp;satellite&nbsp;event of MOCO2016. In the following sections, this document&nbsp;includes&nbsp;information on the logistics and organization details,&nbsp;as well as a short report on the activities held,&nbsp;and&nbsp;the discussions during the event.&nbsp;In the next section, the invited and&nbsp;WhoLoDancE&nbsp;speakers&nbsp;are presented&nbsp;through bios and a summary of their presentations. Finally, the activities and outcomes of the&nbsp;hands-on and demo sessions&nbsp;are described. In the last section we present an evaluation of the workshop, and in the Appendix all the relevant material is included.
</description>
</descriptions>
<fundingReferences>
<fundingReference>
<funderName>European Commission</funderName>
<funderIdentifier funderIdentifierType="Crossref Funder ID">10.13039/501100000780</funderIdentifier>
<awardNumber awardURI="info:eu-repo/grantAgreement/EC/H2020/688865/">688865</awardNumber>
<awardTitle>Whole-Body Interaction Learning for Dance Education</awardTitle>
</fundingReference>
</fundingReferences>
</resource>

11
9
views


text:
# Blogger Operator: sourceSet()

Blogger responsive image sourceSet operators are very useful when you want to ensure that an image is displayed in a suitable size for different devices. Generally this will be used to get a cropped thumbnail of an image, or to create a responsive image for a mobile-friendly template.

### Syntax

sourceSet(imageUrl, newSizes, optionalRatio)

#### Syntax Details

imageUrl
The original URL of the resizable image.

newSizes
An array of new widths of the image

optionalRatio
The integer ratio of width to height for the resized image, e.g. “1:1” or “4:3”

### Fallback

If the image URL parameter is not a resizable image, the sourceSet function will return an empty string.

### Example Usages

<img expr:src=’data:post.firstImageUrl’ expr:srcset=’sourceSet(data:post.firstImageUrl, [128, 256, 512])’ />

The above returns 3 images sizes in 3 different breakpoints for screen widths.

On mobile devices screens, the image size of 128px will be used while on medium screen sizes ie tablets, the image size of 256px will be used instead.

Later the post image size of 512px will be used for larger screens.


text:
# Custom vector class, destructors and constructors

This topic is 4854 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello everyone, I recently tried to recode a vector class (like the STL vector) from scratch, using C++ templates. Basically, the class has some functions which allow the user to insert elements, delete them, and so forth... The data structure holding the objects is doubled if needed and shrinks back dynamically. This is the code:
template <class F> int vector<F>::reserve(unsigned long size){
F *pNew;

if(size <= iReserved)
return iReserved;
else{
pNew = new F[size];

if(pNew == NULL)
return 0;

memcpy(pNew, vData, sizeof(F) * iFilled);	//Copy filled data cells

delete [] vData;
vData = pNew;

iReserved = size;

return size;
}
};
This all works perfectly with "simple" data types, but if I instanciate a vector storing another class, which has its own constructors and destructors, the delete[] operator automatically calls the destructor of all allocated objects, invalidating the data stored in the new array. Is there any way to prevent new and delete from calling the destructor? Should I use malloc and free instead? (doesn't seem right, to me) I could as well allocate an array of pointers to the data type specified by the user, but I fear that would waste the benefits of using an array: direct-access of data, locality of reference (cache), and so on... Is there another solution? Thank you very much :-)

##### Share on other sites
You could try using std::copy() instead of memcpy().

##### Share on other sites
the std::vector allows for this to happen - it also copies data across in a way that causes the constructors to be called for the instances in the new vector. The class being stored in the vector is responsible for ensuring that this is OK, by implementing a proper copy constructor and destructor if needed.

You might do well to crack open your compiler's implementation of std::vector, if you can find it :)

##### Share on other sites
I'm pretty sure a std::vector never actually shrinks. Your best bet is to swap it with another, smaller vector. But that's beside the point...

You could go the placement new/delete route. That lets you allocate a chunk of memory (using new, not malloc) without calling the constructor. Then you control when the constructor gets called. Likewise for delete.

However you certainly do want to call the object's constructor at some point. And calling a constructor without ever calling a destructor is not wise. So trying to remove the destructor from the picture is perhaps not a good solition. Zahlman mentioned this earlier so I'm just saying "I agree."

##### Share on other sites
I'd love to know where you got the idea that 'unsigned long' is for size. Use std::size_t. You should never use 'memcpy' to copy an object - that's what copy constructors are for. Open up the standard and read about what a std::vector is supposed to do, then open up the source code for an implementation and study it.

##### Share on other sites
One problem here is that reserve() does not create elements -- it simply allocates space. Because of that, "new F[size]" is wrong. In reserve(), you should use "new char[size*sizeof(F)]" and then use placement new in push_back() and resize().

##### Share on other sites
Several points:

• You need to seperate memory allocation and memory deallocation from object construction/destruction. Use operator new and operator delete for memory and use placement new and explicit destructor calls for object construction/destruction

• memcpy can't be used for any class that have a non-trival copy constructor - you need to call the copy constuctor using placement new instead

• if you're actually trying to code an implementation of std::vector, then you're missing support for allocators.

##### Share on other sites
Quote:
 Original post by SiCraneYou could try using std::copy() instead of memcpy().

Quote:
 Original post by RDragon1I'd love to know where you got the idea that 'unsigned long' is for size. Use std::size_t. You should never use 'memcpy' to copy an object - that's what copy constructors are for. Open up the standard and read about what a std::vector is supposed to do, then open up the source code for an implementation and study it.

Well, I'm not trying to code a standard vector, I'm just trying to build a very simple class to handle arrays. Thus I'm not using std:copy() nor std:size_t.
Should I replace 'memcpy' by an assignment cycle (which should call the copy constructor)?

Quote:
 Original post by JohnBoltonOne problem here is that reserve() does not create elements -- it simply allocates space. Because of that, "new F[size]" is wrong. In reserve(), you should use "new char[size*sizeof(F)]" and then use placement new in push_back() and resize()

Perfect, that was the kind of solution I was looking for. Then I'll have to call new and delete only on the functions that actually insert or remove items on the vector.

Thank you very much for your help.

##### Share on other sites
Quote:
 Original post by LckWell, I'm not trying to code a standard vector, I'm just trying to build a very simple class to handle arrays. Thus I'm not using ... std:size_t.

While you might not want to use std::size_t, you should definately be using some sort of typedef'd type. Something like:
template<typename T> vector {   typedef unsigned long size_type;   size_type size();   void reserve(size_type);   ...};

That way, you avoid potentially dangerous casts later down the road, and provide additional type information to the end users. The compiler might not distinguish between vector<T>::size_type and unsigned long, but it still provides information to readers.

Also, rename the class to something else. The last thing you need is a test going haywire because you accidentally used a standard vector instead of your custom one.

CM

##### Share on other sites
Quote:
 Original post by Conner McCloudThat way, you avoid potentially dangerous casts later down the road, and provide additional type information to the end users. The compiler might not distinguish between vector::size_type and unsigned long, but it still provides information to readers.

Ok, I'll do it.

Quote:
 Original post by Conner McCloudAlso, rename the class to something else. The last thing you need is a test going haywire because you accidentally used a standard vector instead of your custom one.

I actually defined the class in a different namespace, so there shouldn't be this kind of problem.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 10
• 23
• 12
• 12
• 11
• ### Forum Statistics

• Total Topics
634779
• Total Posts
3019240
×


text:
# H шаблон supernova rus

Section 2 provides a background to H ii regions, star clusters and massive stars. Basic properties of these ccSNe are listed in Tables 2 and 3 for Type Ib/c and Type II ccSNe, respectively, with positions adopted from Asiago except where noted. Nothing visible at this position on images taken on 2009 June 3-July 17 (limiting mag about 22.5). (K0910-001) Pan-STARRs survey. For example, SN 1923A lies 4 arcsec from an H ii region whose radius is ∼4 arcsec, while SN 1964H lies 5 arcsec from an H ii region, whose radius is 2 arcsec. Indeed, 30 Doradus would only subtend ∼1 arcsec at a distance of 50 Mpc.

Похожие записи:


text:
# How do you find the antiderivative of int (arctan(sqrtx)) dx?

Nov 7, 2016

$\left(x + 1\right) \arctan \left(\sqrt{x}\right) - \sqrt{x} + C$

#### Explanation:

$I = \int \arctan \left(\sqrt{x}\right) \mathrm{dx}$

Integration by parts takes the form $\int u \mathrm{dv} = u v - \int v \mathrm{du}$. So, for $\int \arctan \left(\sqrt{x}\right) \mathrm{dx}$, we should let $u = \arctan \left(\sqrt{x}\right)$ and $\mathrm{dv} = \mathrm{dx}$.

Differentiating $u$ gives $\frac{\mathrm{du}}{\mathrm{dx}} = \frac{1}{1 + {\left(\sqrt{x}\right)}^{2}} \cdot \frac{d}{\mathrm{dx}} \sqrt{x}$ or $\mathrm{du} = \frac{1}{2 \sqrt{x} \left(1 + x\right)} \mathrm{dx}$. From $\mathrm{dv} = \mathrm{dx}$ we integrate to show that $v = x$. Thus:

$I = u v - \int v \mathrm{du}$

$\textcolor{w h i t e}{I} = x \arctan \left(\sqrt{x}\right) - \int \frac{x}{2 \sqrt{x} \left(1 + x\right)} \mathrm{dx}$

$\textcolor{w h i t e}{I} = x \arctan \left(\sqrt{x}\right) - \frac{1}{2} \int \frac{\sqrt{x}}{1 + x} \mathrm{dx}$

Letting $t = \sqrt{x}$ implies that ${t}^{2} = x$ and furthermore, that $2 t \mathrm{dt} = \mathrm{dx}$ through differentiating. Thus:

$I = x \arctan \left(\sqrt{x}\right) - \frac{1}{2} \int \frac{t}{1 + {t}^{2}} \left(2 t \mathrm{dt}\right)$

$\textcolor{w h i t e}{I} = x \arctan \left(\sqrt{x}\right) - \int {t}^{2} / \left(1 + {t}^{2}\right) \mathrm{dt}$

$\textcolor{w h i t e}{I} = x \arctan \left(\sqrt{x}\right) - \int \frac{1 + {t}^{2} - 1}{1 + {t}^{2}} \mathrm{dt}$

$\textcolor{w h i t e}{I} = x \arctan \left(\sqrt{x}\right) - \int \frac{1 + {t}^{2}}{1 + {t}^{2}} \mathrm{dt} + \int \frac{1}{1 + {t}^{2}} \mathrm{dt}$

$\textcolor{w h i t e}{I} = x \arctan \left(\sqrt{x}\right) - \int \mathrm{dt} + \arctan \left(t\right)$

$\textcolor{w h i t e}{I} = x \arctan \left(\sqrt{x}\right) - t + \arctan \left(t\right)$

Since $t = \sqrt{x}$:

$I = x \arctan \left(\sqrt{x}\right) - \sqrt{x} + \arctan \left(\sqrt{x}\right)$

$\textcolor{w h i t e}{I} = \left(x + 1\right) \arctan \left(\sqrt{x}\right) - \sqrt{x} + C$