text
stringlengths 121
672k
|
|---|
Tornadoes are the most intense storms on the planet, and they’re never discussed without at least some mention of the term wind shear. Many of us sitting at home, though, have no idea what wind shear is, or if we do, how it affects tornado production.
What is Wind Shear
Wind shear, although it might sound complex, is a simple concept. Wind shear is merely the change in wind with height, in terms of wind direction and speed. I think that we all understand that the wind is generally stronger in the atmosphere over our heads than it is here on the ground, and if we think of the atmosphere in terms of the three dimensions that it has, it should not be surprising that the wind above us might also be blowing from a different direction than the wind at the ground. When that happens–the wind speed and direction vary with height–wind shear is occurring.
Wind Shear and Supercell Thunderstorms
This wind shear is an important part of the process in the development of a supercell thunderstorm, from which the vast majority of strong tornadoes form.
All thunderstorms are produced by a powerful updraft–a surge of air that rises from the ground into the upper levels of the atmosphere, and when this updraft forms in an area where wind shear is present, the updraft is influence by this speed and different direction of the wind above, pushing the column of air in the updraft into a more vertical alignment.
Rain’s Influence on Tornado Production
Needless to say, thunderstorms typically produce very heavy rain, and rain-cooled air is much heavier than the warm air of the updraft, so the rain-cooled air, produces a compensating downdraft (what comes up, must come down). This downdraft pushes the part of the rotating air that was forced in its direction by the stronger wind aloft downward, and the result is a horizontal column of rotating air.
That’s Not a Tornado!
I know what you’re thinking that you’ve seen enough TLC or Discovery Channel shows to know that a horizontal column of air is NOT a tornado; you need a vertical column of air.
This Can Be a Tornado
You’re right, but remember the updraft that is driving the thunderstorm is still working, and it’s able to pull the horizontal, spinning column of air into the thunderstorm, resulting in a vertical column of spinning air.
(NOAA image showing vertical column of air in a supercell thunderstorm)
The result is a rotating thunderstorm capable of producing a tornado, and it would not be possible without wind shear.
(NOAA image showing tornado formation in supercell thunderstorm)
|
YY Chat- The Development of Online Chat Platform
As the online technology has been developing in high speed, online video chat platform, which is one of the most useful functions of IT tools, has been used in many different ways. The distance between becomes shorter and shorter, which increases the speed of globalization. From E-mail texts to Internet phone, that owns to the development of wide band. Most video chat apps and websites, are free, people can easily use them now, based on which plenty of company have become well known by Internet users. For most people, they cannot image the life without online video chat. In this report, I will focus on one of the video chat platform- YY Chat, which is one of the most popular online video chat website. The report will analyze the development of YY chat in China and the comparison of different online chat platforms.
What is YY Chat?
YY Chat began in 2005 creating Duowan.com, a gaming portal for gamers in China. Duowan company launched YY in 2008, a voice-based gaming communications service, which enabled gamers to voice chat over the Internet and text chat in real-time while slaying monsters or coordinating gaming missions.
In the beginning, YY was just common audio-chat software for the famous online game World of Warcraft (WoW), which is one of the most classic games made by Blizzar Entertainment. The players in a same team could easily create a channel, in which they can communicate well by their voice without typing texts on the screen.
However, YY has since grown beyond gaming into a much larger social communication platform, added video streaming, and grown to 310 million registered users and 60 million monthly active users.
On YY.com, users could play different games, talk to their friends, get educated or broadcast a video show program, or use virtual coins for social deals à la Groupon. Slutsky (2012) analyzes that what really makes YY standout is the fact that it has a built in system that enables site users to earn real profit.
As a website which originates from game function software, YY.com still treat the game broadcast as its most important part. When there are some top game competitions, YY’s live broadcast will attract a lot of game players to watch and join in the discussion. WangYi website (2013) shows that the 2013 WCG competition attracted 2 million users to watch live broadcast in 3 days, and on the top time, there were 400 thousands users watching the game at the same time, which had made a new record.
How can YY develop so fast?
Firstly, China has arround 520 million net users in 2012, which includes almost 5 million World of Warcraft game players. These players play an important part in YY users. Because YY Chat has stable and high quality of its online chat function. Even the game company develop its own software UC chat, most game players still prefer to using YY, which they are familiar with, to have group playing.
YY Chat is much easier to use than other chat software like QQ that when the players want to speak to others, they just need to press “F2” button on keyboard. Moreover, when the players create rooms in YY, others can easily join in without send any request. The most important reason YY has amount of users, as Bake website states is because that, YY has set its rules and operated strictly, which is forbidding any advertisement, solving any broadcast issues in 1 minute and avoiding any sexual, violent or selling contents. These rules help YY keeping most of its users.
As the technology is developing, Duowan game company, which YY belongs to, has gradually strengthened and consummated its function. By YY service, singers, teachers, or other people can earn money on its via virtual goods. Slutsky (2012) shows that the top performers on YY.com can earn more than $20,o00 monthly–a remarkable figure. Audience members buy and give virtual roses to performers they like and the performers cash them in for real money. Thus the singers have an incentive to deliver high quality performances. As li says, YY could help “rejuvenate a lot of industries. As many know it’s very difficult to make real money on the music business because of rampant piracy. But if you’re a talented singer or performer, and you have YY, a webcam and an Internet connection, then you can perform (and make money).”
How further can YY develop?
For Chinese video chat platform YY, now meet some problems. On one hand, the Chinese government has published some laws to control what can be broadcast on website and what cannot. They are very strict with the texts, pictures and videos, which will be put onto website. They create a system, which is called Great Wall to limit a lot of foreign websites and monitor everything from Chinese websites. These solutions limit the development of YY. On the other hand, when YY Chat is going to develop western users, it is also blocked. Echo who is senior analyst with the Maxim Group says, “If YY tried to expand into the US market, it would be unlikely to succeed. While it would be difficult for anyone to scale this business model, Western start-ups would have a better chance.” As some other video chat platforms enlarge their users, YY Chat has to consider the issue about replacement by others.
Other sides of online video chats
Firstly, online video chat platform serve people a more convenient way of life. However, some people use this platform in an unhealthy way that they broadcast sex video and strippers dancing in front of the camera. Such kinds of videos can be easily found that they attract young generations who cannot control themselves well, which probably lead to an unexpected terrible way of life in the future.
Secondly, because of the convenience of online video, some people can easily get information from others. They might cheat other’s money as their friends. WangYI website reported that due to 2012, the Internet fraud had reached a number of more than 30 billion RMB in China. Furthermore, some single girls’ safety is threatened because of their “nice” net friends.
Now, there are thousands of online video chat platforms. When some big companies attract more and more users, the small companies will disappear some day. However, there are still a lot of chance will be left for these small video chat companies.
In the future, live video chat may become the most popular way to communicate with people in distance.
Dan Ye, 2013, “YY借力WCG布局赛事直播” from网易website
Forbes. June, 2012.”YY.com: China’s Unique Real-Time Voice And Video Service With A Virtual Goods Twist“. Retrieved November 21, 2012. http://www.forbes.com/sites/tomiogeron/2012/06/11/yy-com-chinas-unique-real-time-voice-and-video-service-with-a-virtual-goods-twist/
Ross Slutsky , 2012, “The Largest Social Network You’ve Never Heard Of”,
published in Washington DC
YY语音” 百度百科
Leave a Reply
WordPress.com Logo
Twitter picture
Facebook photo
Google+ photo
Connecting to %s
|
// Author : Jihong Shin (snowapril)
#include <pch.h>
#include <VulkanFramework/Commands/CommandBuffer.h>
#include <VulkanFramework/Device.h>
#include <VulkanFramework/Descriptors/DescriptorSetLayout.h>
#include <VulkanFramework/Descriptors/DescriptorSet.h>
#include <VulkanFramework/Descriptors/DescriptorPool.h>
#include <VulkanFramework/Images/Image.h>
#include <VulkanFramework/Images/ImageView.h>
#include <VulkanFramework/Images/Sampler.h>
#include <VulkanFramework/RenderPass/Framebuffer.h>
#include <VulkanFramework/RenderPass/RenderPass.h>
#include <VulkanFramework/Pipelines/GraphicsPipeline.h>
#include <VulkanFramework/Pipelines/PipelineLayout.h>
#include <VulkanFramework/Pipelines/PipelineConfig.h>
#include <VulkanFramework/FrameLayout.h>
#include <VulkanFramework/Buffers/Buffer.h>
#include <RenderPass/ShadowMapPass.h>
#include <RenderPass/RenderPassManager.h>
#include <Camera.h>
#include <SceneManager.h>
namespace vfs
{
ShadowMapPass::ShadowMapPass(CommandPoolPtr cmdPool, VkExtent2D resolution)
: RenderPassBase(cmdPool), _shadowMapResolution(resolution)
{
// Do nothing
}
ShadowMapPass::~ShadowMapPass()
{
// Do nothing
}
void ShadowMapPass::onBeginRenderPass(const FrameLayout* frameLayout)
{
CommandBuffer cmdBuffer(frameLayout->commandBuffer);
_pipeline->bindPipeline(frameLayout->commandBuffer);
VkViewport viewport = {};
viewport.x = 0;
viewport.y = 0;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
viewport.width = static_cast<float>(_shadowMapResolution.width);
viewport.height = static_cast<float>(_shadowMapResolution.height);
cmdBuffer.setViewport({ viewport });
VkRect2D scissor = {};
scissor.offset = { 0, 0 };
scissor.extent.width = _shadowMapResolution.width;
scissor.extent.height = _shadowMapResolution.height;
cmdBuffer.setScissor({ scissor });
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(), 2,
{ _descriptorSet }, {});
VkClearValue depthClear;
depthClear.depthStencil = { 1.0f, 0 };
cmdBuffer.beginRenderPass(_renderPass, _framebuffer, { depthClear });
}
void ShadowMapPass::onEndRenderPass(const FrameLayout* frameLayout)
{
CommandBuffer cmdBuffer(frameLayout->commandBuffer);
cmdBuffer.endRenderPass();
}
void ShadowMapPass::onUpdate(const FrameLayout* frameLayout)
{
CommandBuffer cmdBuffer(frameLayout->commandBuffer);
SceneManager* sceneManager = _renderPassManager->get<SceneManager>("SceneManager");
sceneManager->cmdDraw(frameLayout->commandBuffer, _pipelineLayout, 0);
}
void ShadowMapPass::drawGUI(void)
{
_directionalLight->drawGUI();
}
ShadowMapPass& ShadowMapPass::setDirectionalLight(std::unique_ptr<DirectionalLight>&& dirLight)
{
// Move framebuffer and directional light to proper storage
_directionalLight = std::move(dirLight);
_debugUtils.setObjectName(_directionalLight->getShadowMap()->getImageHandle(), "ShadowMap");
_debugUtils.setObjectName(_directionalLight->getShadowMapView()->getImageViewHandle(), "ShadowMap View");
// Create framebuffer for depth render target
std::vector<VkImageView> imageViews{ _directionalLight->getShadowMapView()->getImageViewHandle() };
_framebuffer = std::make_shared<Framebuffer>(_device, imageViews, _renderPass->getHandle(), _shadowMapResolution);
// Descriptor set update
_descriptorSet->updateUniformBuffer({ _directionalLight->getViewProjectionBuffer() }, 0, 1);
_renderPassManager->put("DirectionalLight", _directionalLight.get());
return *this;
}
ShadowMapPass& ShadowMapPass::createRenderPass(void)
{
// TODO(snowapril) : check depth attachment format support
VkAttachmentDescription depthDesc = {};
depthDesc.format = VK_FORMAT_D32_SFLOAT;
depthDesc.samples = VK_SAMPLE_COUNT_1_BIT;
depthDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
depthDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthDesc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
std::vector<VkSubpassDependency> subpassDependencies(2, VkSubpassDependency{});
subpassDependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
subpassDependencies[0].dstSubpass = 0;
subpassDependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
subpassDependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
subpassDependencies[0].dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
subpassDependencies[0].dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
subpassDependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
subpassDependencies[1].srcSubpass = 0;
subpassDependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
subpassDependencies[1].srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
subpassDependencies[1].srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
subpassDependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
subpassDependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
subpassDependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
VkAttachmentReference depthAttachmentRef = {};
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depthAttachmentRef.attachment = 0;
VkSubpassDescription subpassDesc = {};
subpassDesc.pDepthStencilAttachment = &depthAttachmentRef;
subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
_renderPass = std::make_shared<RenderPass>();
assert(_renderPass->initialize(_device, { depthDesc }, subpassDependencies, { subpassDesc }));
return *this;
}
ShadowMapPass& ShadowMapPass::createPipeline(const DescriptorSetLayoutPtr& globalDescLayout)
{
assert(_renderPass != nullptr);
SceneManager* sceneManager = _renderPassManager->get<SceneManager>("SceneManager");
std::vector<VkDescriptorPoolSize> poolSizes = {
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}
};
_descriptorPool = std::make_shared<DescriptorPool>(_device, poolSizes, 1, 0);
_descriptorLayout = std::make_shared<DescriptorSetLayout>(_device);
_descriptorLayout->addBinding(VK_SHADER_STAGE_VERTEX_BIT, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0);
_descriptorLayout->createDescriptorSetLayout(0);
_descriptorSet = std::make_shared<DescriptorSet>(_device, _descriptorPool, _descriptorLayout, 1);
_pipelineLayout = std::make_shared<PipelineLayout>();
_pipelineLayout->initialize(
_device,
{ globalDescLayout, sceneManager->getDescriptorLayout(), _descriptorLayout },
{ sceneManager->getDefaultPushConstant() }
);
PipelineConfig config;
PipelineConfig::GetDefaultConfig(&config);
const std::vector<VkVertexInputBindingDescription>& bindingDesc = sceneManager->getVertexInputBindingDesc(0);
const std::vector<VkVertexInputAttributeDescription>& attribDescs = sceneManager->getVertexInputAttribDesc(0);
config.vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attribDescs.size());
config.vertexInputInfo.pVertexAttributeDescriptions = attribDescs.data();
config.vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDesc.size());;
config.vertexInputInfo.pVertexBindingDescriptions = bindingDesc.data();
config.inputAseemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
config.rasterizationInfo.cullMode = VK_CULL_MODE_NONE; // VK_CULL_MODE_BACK_BIT;
config.dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
config.dynamicStateInfo.dynamicStateCount = static_cast<uint32_t>(config.dynamicStates.size());
config.dynamicStateInfo.pDynamicStates = config.dynamicStates.data();
config.renderPass = _renderPass->getHandle();
config.pipelineLayout = _pipelineLayout->getLayoutHandle();
_pipeline = std::make_shared<GraphicsPipeline>(_device);
_pipeline->attachShaderModule(VK_SHADER_STAGE_VERTEX_BIT, "Shaders/shadowPass.vert.spv", nullptr);
_pipeline->attachShaderModule(VK_SHADER_STAGE_FRAGMENT_BIT, "Shaders/shadowPass.frag.spv", nullptr);
_pipeline->createPipeline(&config);
return *this;
}
};
|
Reversal of fortune
To unlock the vast, untapped potential of the world’s drylands, we must learn from the people who live in them, says Dr Jonathan Davies.
Drylands are a major global biome, home to a great diversity of species and some of our most treasured natural heritage. They are also home to over 2 billion people and in the developing world in particular they are associated with poverty and social inequity. Global development and environment goals are not being met in the drylands: by 2015 many dryland regions are set to fail to achieve the Millennium Development Goals, whilst progress towards the goals and objectives of the UN environmental conventions (the Convention to Combat Desertification and the Convention on Biological Diversity in particular) is generally poor.
Recent experiences in the drylands of emerging countries, such as China and India, illustrate that economic development in drylands can outpace that in areas that are usually considered “high potential”. Although development is often associated with degradation, experiences in Sub Saharan Africa illustrate that economic development can be greatly enhanced through protection of biodiversity as a source of income. By taking an even broader, global view of drylands and examining industrialised dryland countries, it becomes clear that for every seemingly-insurmountable challenge we are able to find evidence of a viable solution somewhere in the world.
To address the challenges of the drylands, we need to understand their unique features and how these have to be managed. Perhaps the most important of these is climate unpredictability: the amount of precipitation varies enormously between areas, between seasons and between years. The sheer magnitude of this uncertainty is hard to grasp, but in many drylands the normal range of rainfall, drought-years aside, can be plus or minus 50% of the average. Yet development in many water-deficit areas continues to favour agricultural practices that expose farmers to huge risks whilst simultaneously degrading the natural resource base on which they depend.
Climate change is a cause for concern in dryland areas, but also an opportunity for new approaches and new learning that illustrate the value of dryland areas. Dryland ecosystems and people are highly adaptable and can survive in their uncertain climate.. Whether drylands become wetter or drier as a result of climate change, they will almost invariably become more unpredictable and their adaptive capacity will be vital to their future. Drylands more than any other ecosystem have the capacity to deal with that unpredictability and we have a great deal to learn from them.
Contrary to popular perception, drylands are not necessarily poverty traps. Dryland ecosystems and their goods and services already contribute significantly to national and international economies. The vibrant tourism sector in Eastern and Southern Africa relies heavily on the biodiversity of drylands. Globally-important dryland commodities include grain, meat and milk and dryland goods like Gum Arabic, Henna, Aloe, and Frankincense. Recent years have seen the commercial development of natural medicines from drylands, and untold numbers of medicinal plants remain un-researched, known only to the dryland inhabitants who have used and conserved them for centuries.
Local knowledge of the drylands is rich and is a powerful resource to be harnessed. There has been a tendency to dismiss this knowledge, because local dryland practices have been portrayed as backward or inappropriate and in need of replacing. The current emergency in the Horn of Africa graphically illustrates the outcome of this attitude: populations are exposed to insupportable risk as a result of losing their traditional strategies and being pushed into new ways of life that simply don’t work. Where people are driven towards catastrophe it is almost guaranteed that the environment will face similar consequences. Customs and cultures that are intimately connected to biodiversity become contorted into a system of pure survival where respect for the environment becomes an unaffordable luxury.
The scientific explanation of the rationale behind traditional strategies has been known for long enough to develop innovative new approaches to sustainable drylands management. Development support has to enable management of the extreme climatic uncertainty of drylands and needs to be built on understanding of the drivers of continuous change in dryland ecosystems. These are dynamic ecosystems in which adaptation and flexibility are pre-requisites for survival. We need to learn from past failures and successes and ensure that development and humanitarian interventions recognize dryland characteristics and build on local knowledge and capacity to turn the existing opportunities into equitable and sustainable wealth creation. In particular we need to generate greater awareness of the tremendous opportunities for strengthening biodiversity-based livelihoods to diversify dryland economies and strengthen resilience.
IUCN’s vision 2020 emphasizes the need to strengthen the Union’s work on conserving the diversity of life while also connecting nature conservation to wider societal objectives such as security and poverty reduction. This vision cannot be reached if we fail to understand and address the unique challenges of the drylands. IUCN, with its great diversity of members and commission members, has a vital role to play in securing effective global action to address dryland issues and in enabling dryland communities to develop their nature-based solutions to risk management and sustainable development.
Dr Jonathan Davies is Coordinator of IUCN’s Global Drylands Initiative.
|
|Retinal Pigment Epithelium (RPE) Detachment
Signs and Symptoms
In most instances, serous detachment of the RPE occurs asymptomatically.
Only in those cases in which the macula is affected will patients report blurred vision,
metamorphopsia, micropsia, or positive scotomas. Other associated clinical findings may
include induced hyperopia and delayed retinal recovery time on the photostress test. Most
individuals with RPE detachment are male, between the ages of 20 and 60 years. The history
often reveals predisposing or concurrent ocular conditions such as macular degeneration,
idiopathic central serous chorioretinopathy (ICSC), angioid streaks, presumed ocular
histoplasmosis syndrome (POHS), or hereditary choroidal degeneration. In other cases, the
condition occurs idiopathically.
RPE detachment appears ophthalmoscopically as single or multiple,
well-circumscribed round or oval lesions within the posterior fundus. The lesions are
typically dome-shaped with slight elevation and appear yellow to orange in color. A
reddish "halo" is often seen around the base of the detachment, and overlying
pigment defects such as clumping or mottling are commonplace. Lesions may vary in size
from one-fifth to over 5 disc diameters (DD), but most are less than 1 DD. Fluorescein and
indocyanine green (ICG) angiography show early hyperfluorescence of the entire RPE
detachment, which persists throughout the angiogram demonstrating late pooling. Leakage
into the sensory retina occurs only in cases of concurrent serous retinal detachment.
RPE detachment is a non-specific anatomical alteration that may result from
any number of choroidal disorders that disrupt the normal junction between the basement
membrane of the RPE and the inner collagenous layer of Bruchs membrane. This
disruption permits serous fluid from the underlying choriocapillaris to gain access into
the sub-RPE space. Age-related macular degeneration, choroidal neovascular membranes, high
myopia, angioid streaks, hereditary choroidal degeneration, POHS, and tumors of the
choroid have all been identified as precipitating conditions in the development of RPE
detachment. Idiopathic cases are sometimes associated with ICSC; some believe these two
conditions to represent a continuum of a similar underlying pathology. Uncomplicated
idiopathic serous detachments of the RPE often resolve spontaneously, however, those
associated with more generalized damage to the choriocapillaris may be complicated by
hemorrhage, choroidal neovascular membrane formation, and disciform scarring.
Most patients under the age of 55 who present with small serous RPE
detachments without evidence of other retinal or choroidal disease enjoy an excellent
prognosis without intervention. This is particularly true if the lesion is outside of the
fovea and there is no associated subretinal fluid.
Older patients who manifest RPE detachment without angiographic evidence
of a choroidal neovascular membrane have a 25-30 percent chance of developing such
membranes during their lifetime, and therefore warrant careful observation as well as
weekly home monitoring with an Amsler grid.
Those patients over the age of 55 who present with associated choroidal
neovascular membranes and/or hemorrhagic RPE detachments have an exceedingly poor visual
prognosis. Focal laser photocoagulation is indicated for these patients.
Approximately 90 percent of cases of RPE detachment have
or will manifest concurrent serous retinal detachment over the natural history of the
disorder. In cases of idiopathic RPE detachment, a striking similarity with ICSC is seen
in the predisposed patient population; i.e. male, average age of 44 years, and a moderate
to severe emotional stress level.
The presentation of RPE detachment is quite
characteristic. Nonetheless, one must be sure to rule out other conditions that may appear
similar from an ophthalmoscopic perspective. These include: ICSC, malignant melanoma,
metastatic carcinoma, choroidal hemangioma, and Bests disease (vitelliform
dystrophy). History and angiography are the most helpful factors in making this
RPE detachment in patients over 55 years of age should be
considered secondary to choroidal neovascular membrane, rather than idiopathic, until
proven otherwise. Prompt fluorescein angiography is mandatory in these cases.
Other reports in this section
|
Word of the Day: Nondimensional
How often have you used the word nondimensional in a sentence? There are occasions when I might have used it, had I known that was the word for what I was doing.
For example, when making calculations that involve physical quantities such as mass, length, time, velocity, and the like, it’s not enough to keep track of the numbers or variables as you calculate, you must also keep track of their units. As students know from bitter experience, it’s easy to confuse, or even lose, units along the way. I remember assignments returned with red ink circling my final result, beside which my teacher had posed the simple question: “Units?”
Had I known better, I might have answered that in fact I was employing a technique of mathematical analysis called nondimensionalization in which you deliberately drop the units from equations involving physical quantities. Among its other advantages, this technique can simplify problems. No kidding! It can also, as one MIT professor put it, “eliminate the possibility of reporting nonsense such as the logarithm of a kilogram.”
My own acquaintance with this word has humbler origins. This summer I decided to build steps from our deck to the ground. A total drop of just 32 inches. How hard could that be? Not very. Unless you use nondimensional lumber.
I inadvertently made nondimensionality part of my design the moment I had the bright idea to build the steps out of cedar logs lying around on the property, instead of using conventional, dimensional milled lumber. That one bright idea turned what could have been a weekend project into something more elaborate. For in sad contrast to nondimensional analysis, nondimensional lumber does not make calculations easier.
Practically speaking, for me nondimensional meant harder to measure, harder to calculate, harder to work with, harder to build. The roundness of the logs, their knottiness, and their continuously changing dimensions helped me appreciate why carpenters call unmilled wood nondimensional lumber. And why that’s not necessarily a compliment. Unlike your milled 2×8, who is a straight, reliable and measured fellow, your natural log is an irresolute, shifty, and dimensionless type who feels no compunction about his rough wavering character, nor gives a damn that his diameter is changing continuously from one end to the other.
I first heard of this exotic character—the more exotic for describing something as plain as lumber—the day my neighbor friend dropped off the cedar logs he’d split lengthwise down the middle for me. (He owns a sawmill.) Three of the four halves we unloaded from his truck eventually became my 12-foot-long steps, or treads, as they’re called in the trade.
But only after I’d done my dimensional analysis featuring nondimensional lumber, followed by headscratching and more than a little guesswork. Then I knew, roughly, how to size, cut and place the two stringers (the term of art for the logs that support the treads from below) that run from the underside of the deck down to the ground, where they’re fastened to footings set in concrete. After that, there was just the headache of measuring, notching, fitting, then re-measuring, re-notching, and re-fitting, before, finally, leveling and fastening the round (continuously changing) underside of the treads to the round (continuously changing) stringers, so that each step rises exactly 8 inches.
The finished treads, with stringers peeking through
The finished treads, with stringers peeking through
My work wasn’t finished until nearly a month after that day when my friend, a builder by trade, casually dropped nondimensional into the conversation. We’d hauled the treads from his truck to the worksite, and I was asking him what he thought of my design, and what advice he had for me. He looked at me from under his cap, a mischievous smile playing on his lips, and said, “Oh, so you’re gonna use nondimensional lumber. That will make things more interesting, but I’m sure they’ll turn out great. Just keep measuring and figuring, measuring and figuring.”
A tip of the hat to my father-in-law, who helped me get the treads on the stringers, and to my father, who helped me measure, mark and stake out the plan.
This entry was posted in Carpentry and tagged , , , , , , . Bookmark the permalink.
Leave a Reply
WordPress.com Logo
Twitter picture
Facebook photo
Google+ photo
Connecting to %s
|
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/planner/filter/conjunction_filter.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/planner/table_filter.hpp"
#include "duckdb/common/vector.hpp"
namespace duckdb {
class ConjunctionFilter : public TableFilter {
public:
ConjunctionFilter(TableFilterType filter_type_p) : TableFilter(filter_type_p) {
}
virtual ~ConjunctionFilter() {
}
//! The filters of this conjunction
vector<unique_ptr<TableFilter>> child_filters;
public:
virtual FilterPropagateResult CheckStatistics(BaseStatistics &stats) = 0;
virtual string ToString(const string &column_name) = 0;
virtual bool Equals(const TableFilter &other) const {
return TableFilter::Equals(other);
}
};
class ConjunctionOrFilter : public ConjunctionFilter {
public:
ConjunctionOrFilter();
public:
FilterPropagateResult CheckStatistics(BaseStatistics &stats) override;
string ToString(const string &column_name) override;
bool Equals(const TableFilter &other) const override;
};
class ConjunctionAndFilter : public ConjunctionFilter {
public:
ConjunctionAndFilter();
public:
FilterPropagateResult CheckStatistics(BaseStatistics &stats) override;
string ToString(const string &column_name) override;
bool Equals(const TableFilter &other) const override;
};
} // namespace duckdb
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Logging.h"
#include "Runtime/Core/Public/Misc/FileHelper.h"
#include "Runtime/Core/Public/HAL/PlatformFilemanager.h"
#include "Runtime/Core/Public/Misc/DateTime.h"
#include "Util.h"
//#include "../Private/Util.cpp"
Logging::Logging()
{
}
Logging::~Logging()
{
}
//String
void Logging::Log(FString inputString, const char comment[], bool bConsole)
{
FDateTime date;
FString log = "[ APPLICATIONTIME : ";
log.Append(date.GetDate().ToString());
log.Append(date.GetTimeOfDay().ToString());
log.Append(" ] -> ");
log.Append(FString(comment));
log.Append(" ");
log.Append(inputString);
log.Append("\r\n");
IPlatformFile& logFile = FPlatformFileManager::Get().GetPlatformFile();
//test id directory exists
if (!logFile.DirectoryExists(*LOG_DIRECTORY))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't find log directory ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Trying to create log directory ..."));
logFile.CreateDirectoryTree(*LOG_DIRECTORY);
if (!logFile.DirectoryExists(*LOG_DIRECTORY))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't create log directory ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Cancelling ..."));
return;
}
}
//test file
if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*LOG_PATH))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't find log file ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Trying to create log file ..."));
FFileHelper::SaveStringToFile(log, *LOG_PATH);
if(!FPlatformFileManager::Get().GetPlatformFile().FileExists(*LOG_PATH))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't create log file ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Trying to create log file ..."));
if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*LOG_PATH))
{
UE_LOG(LogTemp, Warning, TEXT("*** *** *** Couldn't create log file ***"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("*** *** *** Log file created ***"));
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("*** *** *** Log file created ***"));
}
}
else
{
FString oldLog;
FFileHelper::LoadFileToString(oldLog, *LOG_PATH);
oldLog.Append(log);
FFileHelper::SaveStringToFile(oldLog, *LOG_PATH);
}
if (bConsole)
{
UE_LOG(LogTemp, Warning, TEXT("%c"), *inputString);
}
}
void Logging::Log(FString inputString, bool bConsole)
{
Logging::Log(inputString, "", bConsole);
}
void Logging::Log(FString inputString)
{
Logging::Log(inputString, false);
}
void Logging::Log(FString inputString, const char comment[])
{
Logging::Log(inputString, comment, false);
}
//Char
void Logging::Log(const char inputString[], const char comment[], bool bConsole)
{
Logging::Log(FString(inputString), comment, bConsole);
}
void Logging::Log(const char inputString[], bool bConsole)
{
Logging::Log(inputString, "", bConsole);
}
void Logging::Log(const char inputString[])
{
Logging::Log(inputString, false);
}
void Logging::Log(const char inputString[], const char comment[])
{
Logging::Log(inputString, comment, false);
}
//Vector 3D
void Logging::Log(FVector inputVector, const char comment[], bool bConsole)
{
FString log = " VECTOR : { X: ";
log.Append(FString::SanitizeFloat(inputVector.X));
log.Append(" | Y: ");
log.Append(FString::SanitizeFloat(inputVector.Y));
log.Append(" | Z: ");
log.Append(FString::SanitizeFloat(inputVector.Z));
log.Append(" }");
Log(log, comment, bConsole);
}
void Logging::Log(FVector inputVector, bool bConsole)
{
Logging::Log(inputVector, "", bConsole);
}
void Logging::Log(FVector inputVector)
{
Logging::Log(inputVector, false);
}
void Logging::Log(FVector inputVector, const char comment[])
{
Logging::Log(inputVector, comment, false);
}
//Vector 2D
void Logging::Log(FVector2D inputVector, const char comment[], bool bConsole)
{
FString log = " VECTOR2D : { X: ";
log.Append(FString::SanitizeFloat(inputVector.X));
log.Append(" | Y: ");
log.Append(FString::SanitizeFloat(inputVector.Y));
log.Append(" }");
Logging::Log(log, comment, bConsole);
}
void Logging::Log(FVector2D inputVector, bool bConsole)
{
Logging::Log(inputVector, "", bConsole);
}
void Logging::Log(FVector2D inputVector)
{
Logging::Log(inputVector, false);
}
void Logging::Log(FVector2D inputVector, const char comment[])
{
Logging::Log(inputVector, comment, false);
}
//Float
void Logging::Log(float inputFloat, const char comment[], bool bConsole)
{
FString log = FString(" FLOAT : ").Append(FString::SanitizeFloat(inputFloat));
Logging::Log(log, comment, bConsole);
}
void Logging::Log(float inputFloat, bool bConsole)
{
Logging::Log(inputFloat, "", bConsole);
}
void Logging::Log(float inputFloat)
{
Logging::Log(inputFloat, false);
}
void Logging::Log(float inputFloat, const char comment[])
{
Logging::Log(inputFloat, comment, false);
}
//Integer
void Logging::Log(int inputInt, const char comment[], bool bConsole)
{
FString log = FString(" INTEGER : ").Append(FString::SanitizeFloat(inputInt));
Log(log, comment, bConsole);
}
void Logging::Log(int inputInt, bool bConsole)
{
Log(inputInt, "", bConsole);
}
void Logging::Log(int inputInt)
{
Logging::Log(inputInt, false);
}
void Logging::Log(int inputInt, const char comment[])
{
Logging::Log(inputInt, comment, false);
}
//Compound
void Logging::Log(ECompound inputCompound, const char comment[], bool bConsole)
{
FString log = FString(" ECOMPOUND : ");
log.Append(Util::EnumToString(inputCompound));
//switch (inputCompound)
//{
//case ECompound::EO2:
// log.Append(" O2 ");
// break;
//case ECompound::ECO2:
// log.Append(" CO2 ");
// break;
//case ECompound::EAminoAcid:
// log.Append(" Amino Acid ");
// break;
//case ECompound::EGlucose:
// log.Append(" Glucose ");
// break;
//case ECompound::ELipid:
// log.Append(" Lipid ");
// break;
//case ECompound::ENothing:
// log.Append(" Nothing ");
// break;
//}
Logging::Log(log, comment, bConsole);
}
void Logging::Log(ECompound inputCompound, bool bConsole)
{
Logging::Log(inputCompound, "", bConsole);
}
void Logging::Log(ECompound inputCompound)
{
Logging::Log(inputCompound, false);
}
void Logging::Log(ECompound inputCompound, const char comment[])
{
Logging::Log(inputCompound, comment, false);
}
//Player State
void Logging::Log(EPlayerState inputState, const char comment[], bool bConsole)
{
FString log = FString(" EPLAYERSTATE : ");
log.Append(Util::EnumToString(inputState));
//switch (inputState)
//{
//case EPlayerState::EDead:
// log.Append(" Dead ");
// break;
//case EPlayerState::EAlive:
// log.Append(" Alive ");
// break;
//}
Logging::Log(log, comment, bConsole);
}
void Logging::Log(EPlayerState inputState, bool bConsole)
{
Logging::Log(inputState, "", bConsole);
}
void Logging::Log(EPlayerState inputState)
{
Logging::Log(inputState, false);
}
void Logging::Log(EPlayerState inputState, const char comment[])
{
Logging::Log(inputState, comment, false);
}
//Control Setting
void Logging::Log(EControlSettings inputControls, const char comment[], bool bConsole)
{
FString log = FString(" ECONTROLSETTING : ");
log.Append(Util::EnumToString(inputControls));
//switch (inputControls)
//{
//case EControlSettings::EFollowMouse:
// log.Append(" FollowMouse ");
// break;
//case EControlSettings::EWASD:
// log.Append(" WASD ");
// break;
//case EControlSettings::EClick:
// log.Append(" Click ");
// break;
//}
Logging::Log(log, bConsole);
}
void Logging::Log(EControlSettings inputControls, bool bConsole)
{
Logging::Log(inputControls, "", bConsole);
}
void Logging::Log(EControlSettings inputControls)
{
Logging::Log(inputControls, false);
}
void Logging::Log(EControlSettings inputControls, const char comment[])
{
Logging::Log(inputControls, comment, false);
}
//FColor
void Logging::Log(FColor color, const char comment[], bool bConsole)
{
FString log = FString(" FCOLOR : ");
log.Append(Util::ColorToString(color));
Logging::Log(log, bConsole);
}
void Logging::Log(FColor color, bool bConsole)
{
Logging::Log(color, "", bConsole);
}
void Logging::Log(FColor color)
{
Logging::Log(color, false);
}
void Logging::Log(FColor color, const char comment[])
{
Logging::Log(color, comment, false);
}
|
#ifndef UPNPNAT_H
#define UPNPNAT_H
#include <string>
#include <vector>
#pragma warning(disable: 4251)
#define DefaultTimeOut 10
#define DefaultInterval 200
class __declspec (dllexport) UPNPNAT
{
public:
bool init(int time_out=DefaultTimeOut,int interval=DefaultInterval); //init
bool discovery();//find router
/****
**** _description: port mapping name
**** _destination_ip: internal ip address
**** _port_ex:external: external listen port
**** _destination_port: internal port
**** _protocal: TCP or UDP
***/
bool add_port_mapping(char * _description, char * _destination_ip, unsigned short int _port_ex, unsigned short int _destination_port, char * _protocal);//add port mapping
const char * get_last_error(){ return last_error.c_str();}//get last error
private:
bool get_description(); //
bool parser_description(); //
bool tcp_connect(const char * _addr,unsigned short int _port);
bool parse_mapping_info();
int udp_socket_fd;
int tcp_socket_fd;
typedef enum
{
NAT_INIT=0,
NAT_FOUND,
NAT_TCP_CONNECTED,
NAT_GETDESCRIPTION,
NAT_GETCONTROL,
NAT_ADD,
NAT_DEL,
NAT_GET,
NAT_ERROR
} NAT_STAT;
NAT_STAT status;
int time_out;
int interval;
std::string service_type;
std::string describe_url;
std::string control_url;
std::string base_url;
std::string service_describe_url;
std::string description_info;
std::string last_error;
std::string mapping_info;
};
#endif
|
Is this bone a Neanderthal flute?
Cave Bear femur fragment from Slovenia, 43+kya
DOUBTS AIRED OVER NEANDERTHAL BONE 'FLUTE'
(AND REPLY BY MUSICOLOGIST BOB FINK)
Science News 153 (April 4, 1998): 215.
By B. Bower
Amid much media fanfare, a research team in 1996 trumpeted an ancient, hollowed out bear bone pierced on one side with four complete or partial holes as the earliest known musical instrument. The perforated bone, found in an Eastern European cave, represents a flute made and played by Neandertals at least 43,000 ye us ago, the scientists contended.
Now it's time to stop the music, say two archaeologists who examined the purported flute last spring. On closer inspection, the bone appears to have been punctured and gnawed by the teeth of an animal -- perhaps a wolf -- as it stripped the limb of meat and marrow report, April Nowell and Philip G. Chase, both of the University of Pennsylvania in Philadelphia. "The bone was heavily chewed by one or more carnivores, creating holes that became more rounded due to natural processes after burial," Nowell says. "It provides very weak evidence for the origins of [Stone Age] music." Nowell presented the new analysis at the annual meeting of the Paleoanthropology Society in Seattle last week.
Nowell and Chase examined the bone with the permission of its discoverer, Ivan Turk of the Slovenian Academy of Sciences in Ljubljana (S.N.: 11/23/96, p. 328). Turk knows of their conclusion but still views the specimen as a flute.
Both open ends of the thighbone contain clear signs of gnawing by carnivores, Nowell asserts. Wolves and other animals typically bite off nutrient-rich tissue at the ends of limb bones and extract available marrow. If Neandertals had hollowed out the bone and fashioned holes in it, animals would not have bothered to gnaw it, she says.
Complete and partial holes on the bone's shaft were also made by carnivores, says Nowell. Carnivores typically break open bones with their scissor like cheek teeth. Uneven bone thickness and signs of wear along the borders of the holes, products of extended burial in the soil, indicate that openings made by cheek teeth were at first less rounded and slightly smaller, the researchers hold.
Moreover, the simultaneous pressure of an upper and lower tooth produced a set of opposing holes, one partial and one complete, they maintain.
Prehistoric, carnivore-chewed bear bones in two Spanish caves display circular punctures aligned in much the same way as those on the Slovenian find. In the March Antiquity, Francesco d'Errico of the Institute of Quaternary Prehistory and Geology in Talence, France, and his colleagues describe the Spanish bones.
In a different twist, Bob Fink, an independent musicologist in Canada, has reported
on the Internet
(http://www.webster.sk.ca/greenwich/fl-compl.htm) that the spacing of the two complete and two partial holes on the back of the Slovenian bone conforms to musical notes on the diatonic (do, re, mi. . .) scale.
The bone is too short to incorporate the diatonic scale's seven notes, counter Nowell and Chase. Working with Pennsylvania musicologist Robert Judd, they estimate that the find's 5.7-inch length is less than half that needed to cover the diatonic spectrum. The recent meeting presentation is "a most convincing analysis," comments J. Desmond Clark of the University of California, Berkeley, although it's possible that Neandertals blew single notes through carnivore-chewed holes in the bone.
"We can't exclude that possibility," Nowell responds. "But it's a big leap of faith to conclude that this was an intentionally constructed flute."
TO THE EDITOR, SCIENCE NEWS (REPLY BY BOB FINK, May 1998)
(See an update of this discussion on Bob Fink's web site, November 2000)
The doubts raised by Nowell and Chase (April 4th, DOUBTS AIRED OVER NEANDERTHAL BONE 'FLUTE') saying the Neanderthal Bone is not a flute have these weaknesses:
The alignment of the holes -- all in a row, and all of equivalent diameter, appear to be contrary to most teeth marks, unless some holes were made independently by several animals. The latter case boggles the odds for the holes ending up being in line. It also would be strange that animals homed in on this one bone in a cave full of bones, where no reports of similarly chewed bones have been made.
This claim is harder to believe when it is calculated that chances for holes to
be arranged, by chance, in a pattern that matches the spacings of 4 notes of a
diatonic flute, are only one in hundreds to occur .
The analysis I made on the Internet (http://www.webster.sk.ca/greenwich/fl-compl.htm) regarding the bone being capable of matching 4 notes of the do, re, mi (diatonic) scale included the possibility that the bone was extended with another bone "mouthpiece" sufficiently long to make the notes sound fairly in tune. While Nowell says "it's a big leap of faith to conclude that this was an intentionally constructed flute," it's a bigger leap of faith to accept the immense coincidence that animals blindly created a hole-spacing pattern with holes all in line (in what clearly looks like so many other known bone flutes which are made to play notes in a step-wise scale) and blindly create a pattern that also could play a known acoustic scale if the bone was extended. That's too much coincidence for me to accept. It is more likely that it is an intentionally made flute, although admittedly with only the barest of clues regarding its original condition.
The 5.7 inch figure your article quoted appears erroneous, as the centimeter scale provided by its discoverer, Ivan Turk, indicates the artifact is about 4.3 inches long. However, the unbroken femur would originally have been about 8.5 inches, and the possibility of an additional hole or two exists, to complete a full scale, perhaps aided by the possible thumbhole. However, the full diatonic spectrum is not required as indicated by Nowell and Chase: It could also have been a simpler (but still diatonic) 4 or 5 note scale. Such short-scale flutes are plentiful in homo sapiens history.
Finally, a worn-out or broken flute bone can serve as a scoop for manipulation of food, explaining why animals might chew on its ends later. It is also well-known that dogs chase and maul even sticks, despite their non-nutritional nature. What appears "weak" is not the case for a flute, but the case against it by Nowell and Chase.
Letter to the Editor: Antiquity Journal:
"A Bone to Pick"
By Bob Fink
I have a bone to pick with Francesco d'Errico's viewpoint in the March issue of Antiquity (article too long to reproduce here) regarding the Neanderthal flute found in Slovenia by Ivan Turk. D'Errico argues the bone artifact is not a flute.
D'Errico omits dealing with the best evidence that this bone find is a flute.
Regarding the most important evidence, that of the holes being lined up, neither d'Errico nor Turk make mention of this.
This line-up is remarkable especially if they were made by more than one carnivore, which apparently they'd have to be, based on Turk's analysis of the center-spans of the holes precluding their being made by a single carnivore or bite (Turk,* pp.171-175). To account for this possible difficulty, some doubters do mention "one or more" carnivores (Chase & Nowell, Science News 4/4/98).
My arguments over the past year pointed out the mathematical odds of the lining up of the holes occurring by chance-chewing are too difficult to believe.
The Appendix in my essay ("Neanderthal Flute --A Musicological Analysis") proves that the number of ways a set of 4 random holes could be differently spaced (to produce an audibly different set of tones) are 680 ways. The chances a random set would match the existing fragment's spacing [which also could produce a match to four diatonic notes of the scale] are therefore only one in hundreds. If, in calculating the odds, you also allowed the holes to be out of line, or to be less than 4 holes as well, then the chance of a line-up match is only one from many tens of thousands.
And yet randomness and animal bites still are acceptable to account for holes being in line that could also play some notes of the scale? This is too much coincidence for me to believe occurred by chance.
D'Errico mentions my essay in his article and what he thought it was about, but he overstates my case into being a less believable one. My case simply was that if the bone was long enough (or a shorter bone extended by a mouthpiece insert) then the 4 holes would be consistent and in tune with the sounds of Do, Re, Mi, Fa (or flat Mi, Fa, Sol, and flat La in a minor scale).
In the 5 points I list below, extracted from Turk's monograph in support of this being a flute, d'Errico omits dealing with much of the first, and all of the second, fourth and sixth points.
Turk & Co's monograph shows the presence on site of boring tools, and includes experiments made by Turk's colleague Guiliano Bastiani who successfully produced similar holes in fresh bone using tools of the type found at the site (pp. 176-78 Turk).
They also wrote (pp. 171-75) that:
1. The center-to-center distances of the holes in the artifact are smaller than that of the tooth spans of most carnivores. The smallest tooth spans they found were 45mm, and the holes on the bone are 35mm (or less) apart;
2. Holes bitten are usually at the ends of bones rather than in the center of them;
3. There is an absence of dents, scratches and other signs of gnawing and counter-bites on the artifact;
4. The center-to-center distances do not correspond to the spans of carnivores which could pierce the bone;
5. The diameters of the holes are greater than that producible by a wolf exerting the greatest jaw pressure it had available -- it's doubtful that a wolf's jaws would be strong enough (like a hyena's) to have made the holes, especially in the thickest part of the wall of the artifact.
6. If you accept one or more carnivores, then why did they over-target one bone, when there were so many other bones in the cave site? Only about 4.5% of the juvenile bones were chewed or had holes, according to Turk (p. 117).
* Turk, Ivan (ed.) (1997). Mousterian Bone Flute. Znanstvenoraziskovalni
Center Sazu, Ljubljana, Slovenia.
Maintained by Francis F. Steen, Communication Studies, University of California Los Angeles
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctime>
#include <vector>
#include <float.h>
#include <unistd.h>
#include <Dataset.hpp>
#include <Utils.hpp>
#include "net/my_Facenet.hpp"
#include "LFWDataset.hpp"
#include "LFWSampler.hpp"
#include "../../WICWIU_src/KNearestNeighbor.hpp"
#define NUMBER_OF_CLASS 5749 // for lfw_funneled
//#define NUMBER_OF_CLASS 143 // for lfw_little
#define BATCH 45
//#define EPOCH 500
#define EPOCH 10000
//#define GPUID 0
#define GPUID 1
#define LOG_LENGTH 1
#define LEARNING_RATE_DECAY_RATE 0.1
#define LEARNING_RATE_DECAY_TIMING 100
//#define SAMPLE_PER_CLASS 5
#define SAMPLE_PER_CLASS 3
//#define KNN_K 3
#define KNN_K 1
#define BLOCK_SIZE 360 // block to find positive and negative samples
// #define IMAGE_SIZE 48400 // defined in LFWDataset.hpp (220*220)
// #define INPUT_DIM 145200 // defined in LFWDataset.hpp (3 * 220 * 200)
#define FEATURE_DIM 128
#define ENABLE_TRAINING
#define ENABLE_TEST
void GetReferenceSamples(LFWDataset<float> *dataset, int dim, int noClass, int samplePerClass, std::vector<float*> &vSamples, std::vector<int> &vLabels, std::vector<int> *pvRefIndex = NULL, int startIdx = 0); // designed for k-NN
void FindPostiveNegativeSamples(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, int outDim, int blockSize, int batchSize, int *pPosIndex, int *pNegIndex);
void ExtractFeature(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, std::vector<int> &shuffle, int from, int to, int outDim, float *pFeature[], int batchSize);
int main(int argc, char const *argv[])
{
srand(time(NULL));
time_t startTime = 0;
struct tm *curr_tm = NULL;
double nProcessExcuteTime = 0.;
char filename[] = "another_params";
// create input, label data placeholder -> Tensorholder
Tensorholder<float> *x = new Tensorholder<float>(1, BATCH, 1, 1, 145200, "x");
Tensorholder<float> *label = new Tensorholder<float>(1, BATCH, 1, 1, NUMBER_OF_CLASS, "label");
// ======================= Select net ===================
NeuralNetwork<float> *net = new my_FaceNet<float>(x, label, NUMBER_OF_CLASS);
// net->PrintGraphInformation();
if(access(filename, 00) == 0){
net->Load(filename);
printf("Parameters loaded from %s\n", filename);
fflush(stdout);
}
#ifdef __CUDNN__
net->SetDeviceGPU(GPUID);
#endif // __CUDNN__
// std::cout << "/* Prepare Data */" << '\n';
// ======================= Prepare Data ===================
vision::Compose *transform = new vision::Compose({new vision::Resize(224), new vision::CenterCrop(220)});
// LFWDataset<float> *train_dataset = new LFWDataset<float>("./data", "lfw_little", NUMBER_OF_CLASS, transform);
LFWDataset<float> *train_dataset = new LFWDataset<float>("./data", "lfw_funneled", NUMBER_OF_CLASS, transform);
#ifdef __DEBUG__
LogMessageF("lfw_funneled_label.txt", TRUE, "%d samples\n", train_dataset->GetLength());
for(int i = 0; i < train_dataset->GetLength(); i++)
LogMessageF("lfw_funneled_label.txt", FALSE, "%d\t%d\n", i, train_dataset->GetLabel(i));
for(int i = 0; i < NUMBER_OF_CLASS; i++){
printf("count[%d] = %d\n", i, train_dataset->GetSampleCount(i));
LogMessageF("lfw_funneled_count.txt", FALSE, "count[%d] = %d\n", i, train_dataset->GetSampleCount(i));
}
// MyPause(__FUNCTION__);
#endif // __DEBUG__
DataLoader<float> *train_dataloader = new LFWSampler<float>(NUMBER_OF_CLASS, train_dataset, BATCH, TRUE, 1, FALSE);
std::cout << "test" << '\n';
#ifdef ENABLE_TEST
// get referece idxs for k-NN
std::vector<float*> vRefSamples;
std::vector<int> vRefLabels;
std::vector<int> vPosIndex;
std::vector<int> vNegIndex;
std::cout << "test1" << '\n';
GetReferenceSamples(train_dataset, INPUT_DIM, NUMBER_OF_CLASS, SAMPLE_PER_CLASS, vRefSamples, vRefLabels);
#endif // ENABLE_TEST
std::cout << "test2" << '\n';
// LFWDataset<float> *test_dataset = new LFWDataset<float>("./data", "lfw_Test", 60, transform);
float best_acc = 0.f;
int startEpoch = -1; // epoch starts from startEpoch + 1
// int startEpoch = 2614;
int loop_for_train = (train_dataset->GetLength() - train_dataset->GetNoMinorClass(2))/ BATCH;
float min_lr = 0.000001F;
int pos_neg_cycle = 3;
std::cout << "filename : " << filename << '\n';
std::cout << "best_acc : " << best_acc << '\n';
std::cout << "start epoch : " << startEpoch << '\n';
std::cout << "end epoch : " << EPOCH << '\n';
std::cout << "min_lr : " << min_lr << '\n';
std::cout << "pos_neg_cycle : " << pos_neg_cycle << '\n';
if (startEpoch / LEARNING_RATE_DECAY_TIMING) {
float lr = net->GetOptimizer()->GetLearningRate();
float new_lr = lr * pow(0.1, (int)(startEpoch / LEARNING_RATE_DECAY_TIMING));
if(new_lr < min_lr)
new_lr = min_lr;
net->GetOptimizer()->SetLearningRate(new_lr);
std::cout << "lr : " << new_lr << '\n';
}
for (int epoch = startEpoch + 1; epoch < EPOCH; epoch++) {
std::cout << "epoch : " << epoch << '\n';
float train_avg_loss = 0.f;
float train_cur_loss = 0.f;
#ifdef ENABLE_TRAINING
if(epoch == startEpoch + 1 || (epoch - 1) % pos_neg_cycle == 0){
printf("Searching for positive and negative samples...\n"); fflush(stdout);
LogMessageF("log.txt", FALSE, "Finding positive and negative samples...\n");
train_dataset->GetPositiveIndices().resize(train_dataset->GetLength());
train_dataset->GetNegativeIndices().resize(train_dataset->GetLength());
FindPostiveNegativeSamples(net, INPUT_DIM, *train_dataset, FEATURE_DIM, BLOCK_SIZE, BATCH,
&train_dataset->GetPositiveIndices()[0], &train_dataset->GetNegativeIndices()[0]);
printf("Searching for positive and negative samples... Done.\n"); fflush(stdout);
#ifdef __DEBUG__
for(int i = 0; i < 100; i++)
printf("%d (%s): anchor: %d, pos:%d, neg: %d\n", i, train_dataset->GetImagePath(i).c_str(), train_dataset->GetLabel(i), train_dataset->GetPositiveIndex(i), train_dataset->GetNegativeIndex(i));
// MyPause(__FUNCTION__);
#endif // __DEBUG__
}
startTime = time(NULL);
curr_tm = localtime(&startTime);
std::cout << curr_tm->tm_hour << "\'h " << curr_tm->tm_min << "\'m " << curr_tm->tm_sec << "\'s" << '\n';
float lr = net->GetOptimizer()->GetLearningRate();
if (epoch % LEARNING_RATE_DECAY_TIMING == 0 && lr > min_lr) {
// adjust learning rate
std::cout << "Change learning rate!" << '\n';
float new_lr = lr * LEARNING_RATE_DECAY_RATE;
if(new_lr < min_lr)
new_lr = min_lr;
net->GetOptimizer()->SetLearningRate(new_lr);
std::cout << "lr : " << new_lr << '\n';
} else {
std::cout << "lr : " << lr << '\n';
}
// ======================= Train =======================
net->SetModeTrain();
for (int j = 0; j < loop_for_train; j++) {
std::vector<Tensor<float> *> * temp = train_dataloader->GetDataFromGlobalBuffer();
#ifdef __CUDNN__
(*temp)[0]->SetDeviceGPU(GPUID); // 異뷀썑 ?먮룞???꾩슂
(*temp)[1]->SetDeviceGPU(GPUID);
#endif // __CUDNN__
net->FeedInputTensor(2, (*temp)[0], (*temp)[1]);
delete temp;
temp = NULL;
net->ResetParameterGradient();
net->Train();
train_cur_loss = net->GetLoss();
train_avg_loss += train_cur_loss;
printf("\r%d / %d -> cur_loss : %f", j + 1, loop_for_train, train_avg_loss / (j + 1));
fflush(stdout);
}
printf("\n");
#endif // ENABLE_TRAINING
// ======================= Test ======================
float test_accuracy = 0.f;
// float test_avg_loss = 0.f;
#ifdef ENABLE_TEST
net->SetModeInference();
printf("Start testing...\n"); fflush(stdout);
// LFWDataset<float> &dataset = *test_dataset;
LFWDataset<float> &dataset = *train_dataset; // only for debug
// create k-NN classifier using net and (vRefLabels, vRefSamples)
// printf("Feature fxtraction (reference images)\n"); fflush(stdout);
std::vector<float*> vRefFeatures;
AllocFeatureVector(FEATURE_DIM, vRefSamples.size(), vRefFeatures);
net->InputToFeature(INPUT_DIM, vRefSamples.size(), &vRefSamples[0], FEATURE_DIM, &vRefFeatures[0], BATCH); // convert reference images to feature vectors using CNN
KNearestNeighbor knn(FEATURE_DIM, NUMBER_OF_CLASS, vRefSamples.size(), &vRefLabels[0], &vRefFeatures[0]); // create k-NN classifier
DeleteFeatureVector(vRefFeatures);
// test
int correct = 0;
int noTestSample = dataset.GetLength();
int noBatch = (noTestSample + BATCH - 1) / BATCH;
int remained = noTestSample;
std::vector<float*> vTestSample;
std::vector<float*> vTestFeature;
vPosIndex.resize(dataset.GetLength());
vNegIndex.resize(dataset.GetLength());
printf("Recognizing using knn...\n"); fflush(stdout);
for(int batchIdx = 0; batchIdx < noBatch; batchIdx++){
int curBatch = MIN(remained, BATCH);
// extract feature using CNN
AllocFeatureVector(INPUT_DIM, curBatch, vTestSample);
AllocFeatureVector(FEATURE_DIM, curBatch, vTestFeature);
//printf("\rReading test images (batchIdx = %d)... (%s %d)\n", batchIdx, __FILE__, __LINE__); fflush(stdout);
for(int i = 0; i < curBatch; i++){
// printf("Reading test image (i = %d)... (%s %d)\n", i, __FILE__, __LINE__); fflush(stdout);
dataset.CopyData(batchIdx * BATCH + i, vTestSample[i]);
}
// printf("Extracting feature ... (%s %d)\n", __FILE__, __LINE__); fflush(stdout);
net->InputToFeature(INPUT_DIM, vTestSample.size(), &vTestSample[0], FEATURE_DIM, &vTestFeature[0], BATCH);
// printf("Recognizing test images ... (%s %d)\n", __FILE__, __LINE__); fflush(stdout);
// recognize using k-NN classifier
for(int i = 0; i < curBatch; i++){
int result = knn.Recognize(vTestFeature[i], KNN_K);
if(result == dataset.GetLabel(batchIdx * BATCH + i))
correct++;
}
DeleteFeatureVector(vTestFeature);
DeleteFeatureVector(vTestSample);
remained -= curBatch;
if((batchIdx + 1) % 10 == 0){
printf("batch = %d / %d test accuracy = %f (%d / %d)\n", batchIdx + 1, noBatch, correct / (float)(batchIdx * BATCH + curBatch), correct, batchIdx * BATCH + curBatch);
fflush(stdout);
}
}
test_accuracy = correct / (float)noTestSample;
printf("\repoch = %d, test accuracy = %f (%d / %d)\n", epoch, correct / (float)noTestSample, correct, noTestSample); fflush(stdout);
LogMessageF("log.txt", FALSE, "epoch = %d, lr = %f, training loss = %f, test accuracy = %f (%d / %d)\n", epoch, net->GetOptimizer()->GetLearningRate(), train_avg_loss / (float)loop_for_train, correct / (float)noTestSample, correct, noTestSample);
if(test_accuracy > best_acc){
best_acc = test_accuracy;
printf("Saving best model into %s (best_acc = %f)\n", filename, best_acc);
net->Save(filename);
}
#ifndef ENABLE_TRAINING
break; // if training is disabled, repeating test is meaningless
#endif // ENABLE_TRAINING
#endif // ENABLE_TEST
if(test_accuracy > best_acc){
// save the best model
best_acc = test_accuracy;
net->Save(filename);
printf("Model was saved in %s. (best_acc = %f)\n", filename, best_acc);
fflush(stdout);
}
printf("\n");
}
delete net;
delete train_dataloader;
delete train_dataset;
// delete test_dataset;
return 0;
}
void GetReferenceSamples(LFWDataset<float> *dataset, int dim, int noClass, int samplePerClass, std::vector<float*> &vSamples, std::vector<int> &vLabels, std::vector<int> *pvRefIndex, int startIdx) // designed for k-NN
{
DeleteFeatureVector(vSamples);
vLabels.resize(0);
if(pvRefIndex != NULL)
pvRefIndex->resize(0);
if(startIdx = -1)
startIdx = rand() % dataset->GetLength();
std::vector<int> vCount;
vCount.resize(noClass);
for(int i = 0; i < noClass; i++)
vCount[i] = 0;
int noComplete = 0;
for(int i = 0; i < dataset->GetLength() && noComplete < noClass; i++){
int idx = (startIdx + i) % dataset->GetLength();
int label = dataset->GetLabel(idx);
if(label >= noClass){
printf("Error! label = %d, noClass = %d\n", label, noClass);
printf("Press Enter to continue (%s)...", __FUNCTION__); fflush(stdout);
getchar();
}
if(vCount[label] < samplePerClass){
vLabels.push_back(label);
if(pvRefIndex)
pvRefIndex->push_back(idx);
float *pSample = new float[dim];
if(pSample == NULL){
printf("Failed to allocate memory, dim = %d in %s (%s %d)\n", dim, __FUNCTION__, __FILE__, __LINE__);
exit(-1);
}
dataset->CopyData(idx, pSample);
vSamples.push_back(pSample);
vCount[label]++;
if(vCount[label] == samplePerClass)
noComplete++;
}
}
#ifdef __DEBUG__
for(int i = 0; i < vLabels.size(); i++){
printf("vLabels[%d] = %d\n", i, vLabels[i]);
}
#endif // __DEBUG__
}
void FindPostiveNegativeSamples(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, int outDim, int blockSize, int batchSize, int *pPosIndex, int *pNegIndex)
{
int noSample = dataset.GetLength();
int noBlock = (noSample + blockSize - 1) / blockSize;
std::vector<float*> vBlockFeature;
AllocFeatureVector(outDim, blockSize, vBlockFeature);
std::vector<int> shuffle;
std::vector<float> vMinNegative;
std::vector<float> vMaxPositive;
try {
shuffle.resize(noSample);
vMinNegative.resize(blockSize);
vMaxPositive.resize(blockSize);
} catch(...){
printf("Failed to allocate memory in %s (%s %d)\n", __FUNCTION__, __FILE__, __LINE__);
return;
}
for(int i = 0; i < noSample; i++){
shuffle[i] = i;
pPosIndex[i] = -1;
pNegIndex[i] = -1;
}
// random shuffle
// for(int i = 0; i < noSample; i++){
// int j = rand() % noSample;
// int temp = shuffle[i];
// shuffle[i] = shuffle[j];
// shuffle[j] = temp;
// }
std::random_shuffle(shuffle.begin(), shuffle.end());
int remained = noSample;
for(int block = 0; block < noBlock; block++){
int from = block * blockSize;
if(block % 5 == 0){
printf("\rProcessing block %d / %d\n", block, noBlock);
fflush(stdout);
}
int curBlock = MIN(blockSize, remained);
int to = from + curBlock;
// printf("Extracting feature\n"); fflush(stdout);
ExtractFeature(pNN, inDim, dataset, shuffle, from, to, outDim, &vBlockFeature[0], batchSize);
for(int i = 0; i < curBlock; i++){
vMinNegative[i] = FLT_MAX;
vMaxPositive[i] = -FLT_MAX;
}
//printf("Finding positive and negative samples\n"); fflush(stdout);
for(int i = 0; i < curBlock; i++){
int idx_i = shuffle[from + i];
for(int j = i + 1; j < curBlock; j++){
int idx_j = shuffle[from + j];
int dist2 = GetSquareDistance(outDim, vBlockFeature[i], vBlockFeature[j]);
if(dataset.GetLabel(idx_i) == dataset.GetLabel(idx_j)){ // same label
if(dist2 > vMaxPositive[i]){
pPosIndex[idx_i] = idx_j;
vMaxPositive[i] = dist2;
}
if(dist2 > vMaxPositive[j]){
pPosIndex[idx_j] = idx_i;
vMaxPositive[j] = dist2;
}
if(dataset.GetLabel(idx_i) != dataset.GetLabel(idx_j)){
printf("Error! Wrong positive sample! (%s %d)\n", __FILE__, __LINE__);
MyPause(__FUNCTION__);
}
} else { // different label
if(dist2 < vMinNegative[i]){
pNegIndex[idx_i] = idx_j;
vMinNegative[i] = dist2;
}
if(dist2 < vMinNegative[j]){
pNegIndex[idx_j] = idx_i;
vMinNegative[j] = dist2;
}
if(dataset.GetLabel(idx_i) == dataset.GetLabel(idx_j)){
printf("Error! Wrong negative sample! (%s %d)\n", __FILE__, __LINE__);
MyPause(__FUNCTION__);
}
}
}
}
#ifdef __DEBUG__
for(int i = 0; i < curBlock; i++){
int anchorIdx = shuffle[from + i];
int posIdx = pPosIndex[anchorIdx];
int negIdx = pNegIndex[anchorIdx];
int posLabel = (posIdx >= 0 ? dataset.GetLabel(posIdx) : -1);
int negLabel = (negIdx >= 0 ? dataset.GetLabel(negIdx) : -1);
printf("%d: anchor: %d (%d),\tpos = %d (%d),\tneg = %d (%d)\n", i, anchorIdx, dataset.GetLabel(anchorIdx), posIdx, posLabel, negIdx, negLabel);
// if(dataset.GetLabel(anchorIdx) != dataset.GetLabel(posIdx) || dataset.GetLabel(anchorIdx) == dataset.GetLabel(negIdx)){
// printf("Error! Wrong positive or negative sample! (%s %d)\n", __FILE__, __LINE__);
// MyPause(__FUNCTION__);
// }
}
MyPause(__FUNCTION__);
#endif// __DEBUG__
remained -= blockSize;
//printf("Done\n"); fflush(stdout);
}
DeleteFeatureVector(vBlockFeature);
printf("Done\n"); fflush(stdout);
}
void ExtractFeature(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, std::vector<int> &shuffle, int from, int to, int outDim, float *pFeature[], int batchSize)
{
from = MIN(from, dataset.GetLength());
to = MIN(to, dataset.GetLength());
if(from == to){
printf("No data to process in %s (%s %d)\n", __FUNCTION__, __FILE__, __LINE__);
return;
}
int noSample = to - from;
batchSize = MIN(batchSize, noSample);
int noBatch = (noSample + batchSize - 1) / batchSize;
int remained = noSample;
// allocate temporary buffers
std::vector<float*> vTmpSample;
std::vector<float*> vTmpFeature;
try {
AllocFeatureVector(inDim, batchSize, vTmpSample);
AllocFeatureVector(outDim, batchSize, vTmpFeature);
} catch (...){
printf("Failed to allocate memory in %s (%s %d)\n", __FUNCTION__, __FILE__, __LINE__);
MyPause(__FUNCTION__);
return;
}
// extract feature using CNN
for(int batchIdx = 0; batchIdx < noBatch; batchIdx++){
int curBatch = MIN(remained, batchSize);
// printf("Reading batch %d\n", batchIdx); fflush(stdout);
for(int i = 0; i < curBatch; i++)
dataset.CopyData(shuffle[from + batchIdx * batchSize + i], vTmpSample[i]);
// printf("Calling InputToFeature()"); fflush(stdout);
AllocFeatureVector(outDim, vTmpSample.size(), vTmpFeature);
pNN->InputToFeature(inDim, vTmpSample.size(), &vTmpSample[0], outDim, &vTmpFeature[0], batchSize);
// printf("Copying feature"); fflush(stdout);
for(int i = 0; i < curBatch; i++)
// memcpy(pFeature[batchIdx * batchSize + i], vTmpFeature[i], outDim * sizeof(vTmpFeature[i][0]));
memcpy(pFeature[batchIdx * batchSize + i], vTmpFeature[i], outDim * sizeof(float));
DeleteFeatureVector(vTmpFeature);
// printf("Done."); fflush(stdout);
remained -= batchSize;
}
DeleteFeatureVector(vTmpSample);
}
|
/*
author: [email protected]
*/
#include "graph.hpp"
using namespace std;
graph::graph(int n): n(n){
adj.resize(n);
grp.resize(n);
fill_n(grp.begin(), n, -1);
}
graph::graph(int n, vector<int>& val): n(n){
adj.resize(n);
grp.resize(n);
fill_n(grp.begin(), n, -1);
value = val;
}
void graph::group(){
int gid = -1;
for (int i=0; i<n; ++i) {
if (grp[i] == -1) {
++gid;
grp_size.push_back(0);
dfs(i, grp, gid);
}
}
grp_cnt = gid+1;
}
int graph::max_grp_size(){
int res = 0;
for (int i=0; i<grp_cnt; ++i) {
res=max(res, grp_size[i]);
}
return res;
}
void graph::dfs(int i, vector<int>& grp, int gid){
grp[i] = gid;
for (auto j : adj[i]){
if (grp[j] == -1){
dfs(j, grp, gid);
}
}
}
void graph::add_edge(int i, int j){
adj[i].push_back(j);
adj[j].push_back(i);
}
|
// -*- C++ -*-
#if !defined(__geom_ISS_SimplexQuery_ipp__)
#error This file is an implementation detail of the class ISS_SimplexQuery.
#endif
namespace geom {
template<class ISS>
inline
void
ISS_SimplexQuery<ISS>::
build() {
std::vector<BBox> boxes(_iss.getSimplicesSize());
Simplex simplex;
// For each simplex.
for (std::size_t n = 0; n != _iss.getSimplicesSize(); ++n) {
_iss.getSimplex(n, &simplex);
// Make a bounding box around the simplex.
boxes[n].bound(simplex.begin(), simplex.end());
}
// Build the tree from the bounding boxes.
_bboxTree.build(boxes.begin(), boxes.end());
}
//
// Queries.
//
// Get the indices of the simplices that contain the point.
template<class ISS>
template <typename IntOutIter>
inline
void
ISS_SimplexQuery<ISS>::
computePointQuery(IntOutIter iter, const Vertex& x) const {
std::size_t n;
Simplex s;
std::vector<std::size_t> candidates;
_bboxTree.computePointQuery(std::back_inserter(candidates), x);
for (std::vector<std::size_t>::const_iterator i = candidates.begin();
i != candidates.end(); ++i) {
n = *i;
// Get the simplex.
_iss.getSimplex(n, &s);
if (isIn(s, x)) {
*iter++ = n;
}
}
}
// Get the indices of the simplices that overlap the window.
template<class ISS>
template <typename IntOutIter>
inline
void
ISS_SimplexQuery<ISS>::
computeWindowQuery(IntOutIter iter, const BBox& window) const {
_bboxTree.computeWindowQuery(iter, window);
}
// Return the index of the simplex of minimum distance.
template<class ISS>
inline
int
ISS_SimplexQuery<ISS>::
computeMinimumDistanceAndIndex(const Vertex& x, Number* minDistance) const {
// If there are no simplices.
if (_iss.getSimplicesSize() == 0) {
// Return an invalid index.
return -1;
}
std::size_t n;
Simplex s;
//
// Get the candidates simplices.
//
std::vector<std::size_t> candidates;
_bboxTree.computeMinimumDistanceQuery(std::back_inserter(candidates), x);
//
// Calculate distance to the candidate simplices.
//
std::vector<Number> distances(candidates.size());
const std::size_t i_end = candidates.size();
for (std::size_t i = 0; i != i_end; ++i) {
n = candidates[i];
// Get the simplex.
_iss.getSimplex(n, &s);
// Calculate the signed or unsigned distance to the simplex.
distances[i] = computeDistance(s, x);
// CONTINUE REMOVE
//std::cerr << "simplex = " << s << " d = " << distances[i] << "\n";
}
//
// Choose the one of minimum distance.
//
typename std::vector<Number>::const_iterator minIter =
std::min_element(distances.begin(), distances.end());
assert(minIter != distances.end());
// Record the minimum distance.
*minDistance = *minIter;
// Return the index of the closest simplex.
return candidates[minIter - distances.begin()];
}
// Return the minimum distance to the mesh.
template<class ISS>
inline
typename ISS_SimplexQuery<ISS>::Number
ISS_SimplexQuery<ISS>::
computeMinimumDistance(const Vertex& x) const {
// If there are no simplices.
if (_iss.getSimplicesSize() == 0) {
// Return infinity.
return std::numeric_limits<Number>::max();
}
// REMOVE
//std::cerr << "x = " << x << "\n";
std::size_t n;
Simplex s;
//
// Get the candidates simplices.
//
std::vector<std::size_t> candidates;
// REMOVE
//std::cerr << "start\n";
_bboxTree.computeMinimumDistanceQuery(std::back_inserter(candidates), x);
// REMOVE
//std::cerr << "finish\n";
// REMOVE
//std::cerr << "size = " << candidates.size() << "\n";
//
// Calculate distance to the candidate simplices.
//
Number d;
Number minDist = std::numeric_limits<Number>::max();
const std::size_t iEnd = candidates.size();
for (std::size_t i = 0; i != iEnd; ++i) {
n = candidates[i];
// Get the simplex.
_iss.getSimplex(n, &s);
// Calculate the signed distance to the simplex.
d = computeDistance(s, x);
// REMOVE
//std::cerr << "d = " << d << "\n";
// Update the minimum distance.
if (d < minDist) {
minDist = d;
}
}
assert(minDist != std::numeric_limits<Number>::max());
return minDist;
}
} // namespace geom
|
Light infantry
From Infogalactic: the planetary knowledge core
Jump to: navigation, search
For other uses, see Light infantry (disambiguation).
Portuguese Army light infantry (caçador) of the Peninsular War
History of the light Infantry
Modern Age
Contemporary Light Infantry Forces
Today the term "light" denotes, in the United States table of organization and equipment, units lacking heavy weapons and armor or with a reduced vehicle footprint. Light infantry units lack the greater firepower, operational mobility and protection of mechanized or armored units, but possess greater tactical mobility and the ability to execute missions in severely restrictive terrain and in areas where weather makes vehicular mobility difficult.
Light infantry forces typically rely on their ability to operate under restrictive conditions, surprise, violence of action, training, stealth, field craft, and fitness levels of the individual soldiers to address their reduced lethality. Despite the usage of the term "light", forces in a light unit will normally carry heavier individual loads versus other forces; they must carry everything they require to fight, survive and win due to lack of vehicles. Although units like the 101st Airborne (Air Assault) and the 82nd Airborne Division are categorized as Air Assault Infantry and Airborne Infantry respectively, they fall under the overall concept of light infantry.
During the Falklands War in 1982, both Argentina and the United Kingdom made heavy use of light infantry and its doctrines during the campaign, most notably the Argentine 5th Naval Infantry Battalion (Argentina) and 25th Infantry Regiment (Argentina) and the British Parachute Regiment and Royal Marines of 3 Commando Brigade. Due to the rocky and mountainous terrain of the Falkland Islands, operations on the ground were only made possible with the use of light infantry because the use of mechanized infantry or armour was severely limited by of the terrain, leading to the "Yomp" across the Falklands, in which Royal Marines and Paras yomped (and tabbed) with their equipment across the islands, covering 56 miles (90 km) in three days carrying 80-pound (36 kg) loads after disembarking from ships at San Carlos on East Falkland, on 21 May 1982.
During the 1990s, the concept of purely light forces in the US military came under scrutiny due to their decreased lethality and survivability. This scrutiny has resulted in the Stryker Brigade Combat Team, a greater focus on task organized units (such as Marine Expeditionary Units) and a reduction of purely light forces.
Modern Light Infantry Units
Light Infantry in Different Countries
The 7 battalions are composed of:
• Two battalions of mechanized infantry
• Two battalions of motorized infantry
• Two battalions of light infantry
• One battalion of paratroop infantry
Main article: Jægerkorpset
Chasseurs from a light infantry regiment of Napoléon's Grande Armée
The light infantry was organised in France in the 1.
Ancient régime
The name Chasseurs à pied (light infantry) was originally used for infantry units in the French Army recruited from hunters or woodsmen. Recognized for their marksmanship and skirmishing skills, the chasseurs were comparable to the German Jäger or the British light infantry. The Chasseurs à Pied, as the marksmen of the French army, were regarded as elite light companies and regiments.[2] The first unit was Jean Chrétien Fischer's Free Hunter Company in 1743. These units were often a mix of cavalry and infantry. In 1776 all the Chasseurs units were re-organized in six battalions, each one linked to a cavalry regiment (Chasseurs à cheval). In 1788, the special link between infantry battalions and cavalry regiment was broken.
Revolution and Napoleon
In 1793, the Ancient Régime Chasseurs battalions were merged with volunteers battalions in new units called Light Infantry Half-Brigades (demi-brigades d’infanterie légère). In 1803, the half-brigades were rebranded regiment. These units had three battalions of three regular Chasseurs companies, one elite Carabiniers company and one reconnaissance voltigeurs company.
Imperial Guard
In Napoléon’s IImperial Guard, many units used names linked to light infantry :
• Chasseurs à pied regiments : three regiments (1809-1815 ; 1815-1815 ; 1815-1815). The regiments were the elite of the light infantry regiments.
• Fusilier-Chasseurs regiment : originally the first Guard Fusilier Regiment (1809-1815)
• Voltigeurs regiments : 16 regiments, originally two regiments of Tirailleurs-chasseur and two regiments of Conscrits-chasseurs (1810-1815), then twelve new regiments (1811-1815). These regiments were expected to became Chasseurs à pieds regiments.
• Flanqueurs-Chasseurs regiments : two regiments, from drafted Forest Service members (1811-1815 ; 1813-1815)
XIXth Century
Light Infantry
The Napoléon-type Light Infantry regiment existed till 1854, but with very few differences from the line infantry regiment, so the 25 remaining light infantry regiments were transformed in line infantry in 1854.
Chasseurs à pied
The Duke of Orléans, heir to the throne, created in 1838 a new light infantry unit, the Tirailleurs battalion. It soon became, under the name Chasseur à Pied, the main light infantry unit in the French Army. The number of battalions grew up steadily through the century. The current Chasseurs battalions drew their lineage form this unit.
Chasseurs alpins
Some of Chasseurs à pied battalions were converted to specialized mountain units as Bataillons de Chasseurs Alpins in 1888, as an answer to the Italian Alpine (Alpini) regiments stationed along the Alpine frontier.
Chasseurs Forestiers
The Chasseurs forestiers (Forest Huntsmen) were militarized units of the Forest Service. They were organized in companies. The Chasseurs forestiers existed between 1875 and 1924.
The Zouaves battalions and regiments were colonial troops, formed originally by Algerians, then by European settlers and colonists. The first Zouave battalion was created in 1831 and changed its recruiting to Europeans in 1841.
Tirailleurs (Skirmishers) were light infantry who formed a shallow line ahead of the line of battle during the Revolutionary/Napoleonic Wars and subsequently. The name was also used for the locally recruited colonial troops in the French Empire between 1841 and 1962.
XXth Century
Chasseurs à pied
The Chasseurs à pieds evolved during the mid-XXth century into mechanized infantry units (Chasseurs mécanisés) or armored division infantry (chasseurs portés). After World War Two, all Chasseur units were organized on the mechanized infantry model.
Chasseurs alpins
The Chasseurs alpins' became the only mountain warfare units in the French Army in 1945.
Chasseurs pyrénéens
The Chasseurs pyrénéens were the short-lived (1939-1940) mountain warfare units formed in the Pyrénées.
The Chasseurs-parachutistes were airborne infantry units formed in 1943 from Air Force infantry compagnies transferred to the Army.
Zouaves and Tirailleurs'
After the independence of the countries that made up the French Colonial Empire, the Zouaves and the Tirailleurs units, save for one, were disbanded.
Modern French Army Light Infantry
Although the traditions of these different branches of the French Army are very different, there is still a tendency to confuse one with the other. For example, when World War I veteran Léon Weil died, the AFP press agency stated that he was a member of the 5th "Regiment de Chasseurs Alpins". It was in fact the 5th Bataillon.
Main article: Jäger (military)
Of the 28 Infantry regiment of the modern Indian Army, the following 10 are designated as "Rifles". They are distinguished by their black rank badges, black buttons on their service and ceremonial uniforms and also a beret which is a darker shade of green than the other regiments. Apart from these two paramilitary forces: the Assam Rifles and the Eastern Frontier Rifles, also follows the traditions of the rifle regiment.
Rajputana Rifles
Garhwal Rifles
Jammu and Kashmir Rifles
1st Gorkha Rifles (The Malaun Regiment)
3 Gorkha Rifles
4 Gorkha Rifles
5 Gorkha Rifles (Frontier Force)
8 Gorkha Rifles
9 Gorkha Rifles
11 Gorkha Rifles
Basic training ("Tironut"):
• Non-combat soldiers are trained as Rifleman 02.
• Combat-support troops are trained as Rifleman 03.
Advance training ("Imun Mitkadem"):
Additional training for combat soldiers:
• Combat class commanders are trained as Rifleman 08.
• Combat Senior Sergeants are trained as Rifleman 10.
• Combat officers are trained as Rifleman 12.
Italian Rifle units were designated Cacciatori or Bersaglieri.
The Netherlands
Main article: Caçadores
In the 1950s, the title "Caçadores" was also given to the light infantry battalions and independent companies responsible for garrisoning the Portuguese overseas territories. Colonial troops with this title were recruited from both Portuguese settlers and from the indigenous populations in each overseas territory.
In 1975, the designation "Caçadores" was discontinued in the Portuguese Armed Forces. All former units of caçadores were redesigned as "Infantry".
The Rhodesia Regiment had an affiliation with the King's Royal Rifle Corps since World War I. The regiment's badge was the Maltese Cross, the colours were red, black and rifle green and rifle green berets were worn. A private soldier had the title of "Rifleman".
• Vânători de Munte, or "Mountain Huntsmen" comprised elite units of the Romanian infantry prior to 1945.
The Imperial Russian Army, which was heavily influenced by the Prussian and Austrian military systems, included fifty Jäger or yegerskii [егерский] regiments in its organisation by 1812, including the Egersky Guards Regiment. These regiments were disbanded in 1917-18.
Spanish Riflemen were designated as Cazadores.
United Kingdom
A historical reenactment with the British 95th Rifles regiment.
The rank of Rifleman instead of Private was officially introduced in 1923.[3]
United States
In 1808, the United States Army created its first Regiment of Riflemen. During the War of 1812 three more Rifle Regiments were raised but disbanded after the war. The Rifle Regiment was disbanded in 1821.
Riflemen were listed as separate to infantry up to the American Civil War.[4]
References and notes
3. "About the Royal Green Jackets". Retrieved 6 June 2011.
Further reading
External links
|
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
#include <string>
#include <set>
#include <queue>
#include <map>
using namespace std;
typedef long double ld;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll,ll> pll;
typedef pair<char, char> pc;
typedef pair<string, string> ps;
typedef tuple<int, int, int> ti;
typedef tuple<ll, ll, ll> tll;
typedef tuple<string, string, string> ts;
typedef tuple<char, char, char> tc;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pi> vpi;
typedef vector<pll> vpll;
typedef vector<ti> vti;
typedef vector<bool> vb;
typedef vector<ts> vts;
typedef multiset<int> msi;
typedef multiset<ll> msll;
typedef multiset<string> mss;
typedef multiset<char> mc;
typedef queue<char> qc;
typedef queue<int> qi;
typedef queue<ll> qll;
typedef queue<string> qs;
typedef set<int> si;
typedef set<ll> sll;
typedef set<string> ss;
typedef set<char> sc;
#define FOR(a, b, c) for (int a=(b); a<(c); a++)
#define F0R(i, a) for (int i=0; i<(a); i++)
#define F1R(i, a) for (int i=1; i<(a); i++)
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define popb pop_back
#define f first
#define sec second
#define ub upper_bound
#define lb lower_bound
#define beg begin
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
void setIO(string name = "evolution"){
ios_base::sync_with_stdio(0); cin.tie(0);
if(name.size()){
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
int n;
vs v[25];
vs v2;
bool check(int x, int y){
int c1 = 0, c2 = 0, c3 = 0;
F0R(a, n){
bool A = false, B = false;
F0R(b, sz(v[a])){
if(v[a][b] == v2[x]){
A = true;
}
if(v[a][b] == v2[y]){
B = true;
}
}
if(A && B){
c1++;
} else if(A){
c2++;
} else if(B){
c3++;
}
}
if(c1 > 0 && c2 > 0 && c3 > 0){
return true;
}
return false;
}
void solve(){
cin >> n;
F0R(a, n){
int c;
cin >> c;
F0R(b, c){
string s; cin >> s;
v[a].pb(s);
bool done = false;
F0R(d, v2.size()){
if(v2[d] == s){
done = true;
}
}
if(!done){
v2.pb(s);
}
}
}
string ans = "yes";
F0R(a, v2.size()){
bool done = false;
FOR(b, a+1, v2.size()){
if(check(a, b)){
done = true;
break;
}
}
if(done){
ans = "no";
break;
}
}
cout << ans;
}
int main(){
setIO();
int t = 1;
//cin >> t;
while(t--){
solve();
}
}
|
The plant collections of the Smithsonian Institution began with the acquisition of specimens collected by the United States Exploring Expedition (1838-1842). These formed the foundation of a national herbarium which today numbers 4.8 million historical plant records, placing it among the world's largest and most important.
Nearly 800,000 specimen records (including over 90,000 type specimens with images) are currently available in this online catalog.
Select a tab on this page to search by Keyword or Selected Fields. If you don't know what you want to see, you may want to look at the sample records in the Quick Browse section below. Searches are limited to 2000 records and the results are sorted by taxonomic group. If you need to retrieve a larger record set, contact the Department of Botany's Data Manager.
See the Help tab to learn more about searching and then exploring your returned results (sorting, exporting, etc.).
||Sample Records from the DC Flora Collection
||2205692 2197595 2191752 2175968 2213272 2196389 2200318 2192830 2219158 2200909 2208745 2223985 2175937 2192264 2220376
||Sample Records from the Botanical Type Register
||2119407 2149872 2161549 2790611 2105614 2099734 2134596 2116358 2166713 2151580 2158541 2143664 2097212 2076608 2167306 2121665 2095940 2075490
||Sample Records from the Wilkes Expedition
||2524597 2705372 2705371 2743367 2699717 2741233 2741229 2733613 2741227 2680776 2741226 2741217 2741216 2687168 2702446 2684992 2680753 2680752 2741176 2741175 2693758 2680751 2678261
Enter your keywords separated by spaces and click Search. Records that match your search terms will be returned.
- Using parentheses to clarify the logic, you can create complex queries with OR and NOT (here capital letters are required, otherwise they will be treated as keyword terms).
- You can also use double-quotes to specify terms that should be treated as one.
- Lastly, you can include the terms image(s) or type(s) to find records that have images or that are type specimens.
Note that searching for common (vernacular) names may not yield the expected results. Associating common names with specimen records is a work in progress.
Keyword search example: marantaceae ("new guinea" OR australia) images
Use the By Field search to find specimen data that match values in specific database fields. Enter a value or choose one from the dropdown lists.
- Click the Search button to initiate a search. Clear resets all fields.
- Some lists are linked, so for example, choosing a Country narrows the choices for Province/State/Territory, and District/County. Dropdown choices also narrow as you type, for example, typing zing in the Family field might narrow the choice to Zingiberaceae.
- Note that the Province/State dropdown is populated only after you have chosen a Country. You can type a Province/State without selecting a Country.
- Check Only Records with Images if you want to restrict the search to records with multimedia content.
- You will receive a warning when you enter invalid information in the text fields. For example, Catalog Numbers are composed strictly of letters and numbers; other characters will raise a warning.
The results of your searches can be displayed in Grid (a sortable, customizable table)
or Gallery View (best for reviewing images). Use the Switch button to cycle between these views.
- You can choose whether to display 5, 10, 20, 50, or 100 records at a time.
In Sheet View:
- Click on the scientific name to view the full record.
- Click on the thumbnail to view larger resolutions of the image. Use Control+Click (Command+Click) to open a new browser tab.
In Grid View:
- You can choose the columns to display from any column's dropdown menu (mouse into a column header and click the dropdown icon). Under Columns, click the name to display or hide the field (you do not need to click the checkbox specifically).
- You can drag a column header to change its order of appearance in the grid.
- You can also drag the edge of a column to make it wider or narrower.
- Click in the expansion () column to view the full record.
In Gallery View:
- Click the image to view the full record.
See Exporting Results for information on downloading results to, for example, Excel or Google Earth.
Open the full collection record by clicking the expansion button () in Grid View,
on the scientific name in Sheet View,
or anywhere within the image frame in Gallery View. Inverse expansion buttons () indicate records with multimedia (typically, images).
- In the Record window, metadata for the multimedia content is available when you mouseover the thumbnail.
- Clicking the thumbnail opens the content in your browser or other appropriate application.
- Record windows may be resized or moved within the browser window.
- You may have up to ten Record windows open at any one time.
Sort results in Grid View by clicking the column header (or by choosing Sort from the column's dropdown menu).
- Sort on multiple columns by consecutively sorting columns in reverse order. For example, to view results sorted by Country and Province/State, first sort by Province/State and then sort again by Country.
- For any column you can choose to sort in Ascending or Descending order.
Export all or selected results by clicking the Export Results as CSV button in the bottom toolbar in Grid,
or Gallery View.
- Select individual records for Export by checking the export selection box (along the left edge of the Grid View grid).
- Clear all selections with the Clear Selections button in the bottom toolbar.
- Results are exported as comma-separated-values, one record per line, which can be saved to disk or opened directly with applications such as Microsoft Excel.
You can also export all or selected results to a KML file for viewing with Google Earth or other KML viewers, by clicking the Export as KML button. This button is grayed when all or selected results lack latitude/longitude values.
To create a link to specific records at NMNH provide the appropriate unit and querystring to:
where UNIT is:
- anth, birds, botany, ento, fishes, herps, iz, mammals, ms, or paleo
and QUERYSTRING is (use a plus-sign to separate words):
- One or more CATALOG NUMBERS, e.g.
- One or more BARCODES, e.g.
- The NAME of a TYPE specimen, e.g.:
- The NAME of a specimen or object, e.g.:
- The NAME (qn) and/or TYPE STATUS (qt) of a specimen, and/or its COLLECTOR (co), and/or the COLLECTION (cn) it is part of, e.g.:
(Holotypes whose name includes Torre and Bartsch collected by Webb and part of the Henderson Collection)
- To open the Collections Search to a specific search tab, e.g.
Tabs are numbered left to right, beginning with zero.
- iz/?ti=1 (Invertebrate Zoology Keywords Search)
- mammals/?ti=3 (Mammals Whale Collection Search)
There are ways to speed up your queries (or slow them down!) and to find specific information.
- The more specific you make your queries the faster they will execute. Using more, rather than fewer, terms will very likely speed up your search.
- These following special characters modify the interpretation of search terms (use with as many other terms as possible to avoid slowing your search):
- * matches any number of characters, e.g. *pseudo*
- ? matches a single character, e.g. young?lus frank?
- ! negates the presence of a term, e.g. !new
- ~ matches all terms with the given stem, e.g. ~spear for spear, spears, spearing, etc.
- = match is case-sensitive, e.g. =Paris
- Query results are typically limited to 5000 records. Avoid general queries, when you can, that are likely to bring back very large numbers of records, e.g. searching for poaceae.
- Long running queries are automatically terminated, with no results returned.
Please use the Feedback page to report back any problems you find with the data, or with using these search pages.
|
|reference frame (rěf'ər-əns) Pronunciation Key
A basis of a four-dimensional coordinate system in which the first coordinate is understood as a time coordinate, while the other three coordinates represent spatial dimensions. Inertial frames and non-inertial frames are both examples of reference frames. Also called frame of reference. See also General Relativity, space-time, Special Relativity.
|a gadget; dingus; thingumbob.|
|a stew of meat, vegetables, potatoes, etc.|
|
One of the best perks of a solar system is having the ability to monitor your system’s energy production. Property owners can see in real-time the productivity on a daily, monthly, and annual basis. What makes monitoring such an important factor of a solar home or business is having the cabability to track how thesystem is generating solar power in relation to the energy that’s coming from the utility company. It’s a great tool to visualize your electricity offset between the two.
Here are some key factors you should know about solar monitoring:
1. Is monitoring included
2. When and how is it installed
3. How do I know what my system is reporting
Before you understand more about the monitoring, it’s best to learn about the various types of monitoring.
Types of Monitoring
The type of monitoring will be determined by the type of inverter that’s been installed. An inverter is much like control center; gathering data, converting the electric signal, and distributing the energy to your property’s main electric panel box. A standard string/central inverter will have monitoring capability directly inside the inverter box that’s attached by the electric box while an inverter with optimizers and microinverters provides monitoring access via internet. In this blog, I will discuss monitoring with optimizer and microinverter systems.
Monitoring Access
If you have SolarEdge with Optimizer Inverter or Enphase, access your monitoring system portal here.
1. Is Monitoring Included
As a property owner with a solar system, there’s really no reason to not have monitoring included with an installation. It goes hand-in-hand with solar. There’s no additional cost to a solar system with monitoring and will always be accessible 365/24/7.
2. When And How Is Monitoring Installed
Intergrating monitoring with the soalr system will depend on the type of inverter. For an inverter with optimizers, monitoring will be installed directly after the system has been installed on the property. Microinverter systems on the other hand are installed after the system is officially turned on by the utility. A small wireless or ethernet device will be connected to the home’s or business’s internet connection to allow the inverter to send its production data through manufacturer’s online portal to which you will have log-in account to gain access. Monitoring is accessible via desktop, tablet, and smartphone app.
3. Knowing What The Solar System is Reporting
As you monitor your solar system, it’s important to be educated on what you see. The goal is to ensure that the system’s production is at or above what was guaranteed annually. Production will vary when tracking its results. The time of year, weather, clouds, the sun’s orientation and angle in the sky do determine your production for that day. Also, shading from roofing ventilation pipes, an HVAC unit, chimney, and tree branches will fluctuate production for the panels that may be effected by such obstructions. There also may be times when no production is being reported. If the property’s internet connection has been tampered with or changed, such as being moved or unplugged after the monitoring has been installed to the system, this will reset the data connection and no production report will be available.
Nevertheless, having the support you need is most important of all. Whenever any questions arise about the system and how it’s reporting production, it’s crucial to get immediate response and assistance to bring resolve to a concern to ensure that your solar system is bringing optimal solar energy to your home or business.
We do get common questions from homeowners asking about their monitoring and what it all means. For example questions asking why they see dramatic fluctuations with their system’s production. Solar panels produce energy based on certain factors such as time of day, time of season, any shading, and temperature. Also, at times the panels may actually over produce more of wattage than they are originally designed to. Daily data may present some inaccuracies and fluctuations to the production reports so we suggest homeowners to track and manage their solar monthly, quarterly, and annually.
Because the monitoring details can be accessed only via online, the home will need an to have internet connection so the inverter can send solar data to the homeowner. If for some reason, there’s no monitoring being displayed, that means that the inverter has lost connection with the home’s internet signal. But if was to happen, it doesn’t mean your solar system is not working. The system is still functioning at a 100%, it’s the details that are not be displayed in the monitoring portal.
When such issues occur, LA Solar Group ensures that we’re on top of it and will repair or readjust setting to bring the monitoring back online. Because we guarantee production with our warranty, we understand it’s important to for homeowners to manage their solar. What we do is set a specific threshold for the production so we can make sure that the system doesn’t under produce. The failure rate for a solar system a 0.01% which is close to nothing. Failure rate for a solar panel is .022%. This is why manufactures stand behind their production and product warranties.
4. Software updates
Software updates for the inverter and gateway monitoring device are run during weekends. If you notice on your monitoring portal that the inverter is offline over the weekend it is most likely due to the software update. The system will be back online by Monday and if it is not or if the monitoring system is offline for more than 72 hours please make a service ticket request on our website. Communication issues with the inverter and monitoring system usually resolve themselves.
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
// Copyright (C) 2015 Faust Logic, Inc.
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
#include "T3D/physicalZone.h"
#include "core/stream/bitStream.h"
#include "collision/boxConvex.h"
#include "collision/clippedPolyList.h"
#include "console/consoleTypes.h"
#include "math/mathIO.h"
#include "scene/sceneRenderState.h"
#include "T3D/trigger.h"
#include "gfx/gfxTransformSaver.h"
#include "renderInstance/renderPassManager.h"
#include "gfx/gfxDrawUtil.h"
#include "console/engineAPI.h"
//#include "console/engineTypes.h"
#include "sim/netConnection.h"
IMPLEMENT_CO_NETOBJECT_V1(PhysicalZone);
ConsoleDocClass( PhysicalZone,
"@brief Physical Zones are areas that modify the player's gravity and/or velocity and/or applied force.\n\n"
"The datablock properties determine how the physics, velocity and applied forces affect a player who enters this zone.\n"
"@tsexample\n"
"new PhysicalZone(Team1JumpPad) {\n"
"velocityMod = \"1\";"
"gravityMod = \"0\";\n"
"appliedForce = \"0 0 20000\";\n"
"polyhedron = \"0.0000000 0.0000000 0.0000000 1.0000000 0.0000000 0.0000000 0.0000000 -1.0000000 0.0000000 0.0000000 0.0000000 1.0000000\";\n"
"position = \"273.559 -166.371 249.856\";\n"
"rotation = \"0 0 1 13.0216\";\n"
"scale = \"8 4.95 28.31\";\n"
"isRenderEnabled = \"true\";\n"
"canSaveDynamicFields = \"1\";\n"
"enabled = \"1\";\n"
"};\n"
"@endtsexample\n\n"
"@ingroup enviroMisc\n"
);
bool PhysicalZone::smRenderPZones = false;
DefineEngineMethod(PhysicalZone, activate, void, (),, "Activate the physical zone's effects.\n"
"@tsexample\n"
"// Activate effects for a specific physical zone.\n"
"%thisPhysicalZone.activate();\n"
"@endtsexample\n"
"@ingroup Datablocks\n"
)
{
if (object->isClientObject())
return;
object->activate();
}
DefineEngineMethod(PhysicalZone, deactivate, void, (),, "Deactivate the physical zone's effects.\n"
"@tsexample\n"
"// Deactivate effects for a specific physical zone.\n"
"%thisPhysicalZone.deactivate();\n"
"@endtsexample\n"
"@ingroup Datablocks\n"
)
{
if (object->isClientObject())
return;
object->deactivate();
}
//--------------------------------------------------------------------------
//--------------------------------------
//
PhysicalZone::PhysicalZone()
{
mNetFlags.set(Ghostable | ScopeAlways);
mTypeMask |= PhysicalZoneObjectType;
mVelocityMod = 1.0f;
mGravityMod = 1.0f;
mAppliedForce.set(0, 0, 0);
mConvexList = new Convex;
mActive = true;
force_type = VECTOR;
force_mag = 0.0f;
orient_force = false;
fade_amt = 1.0f;
}
PhysicalZone::~PhysicalZone()
{
delete mConvexList;
mConvexList = NULL;
}
ImplementEnumType( PhysicalZone_ForceType, "Possible physical zone force types.\n" "@ingroup PhysicalZone\n\n" )
{ PhysicalZone::VECTOR, "vector", "..." },
{ PhysicalZone::SPHERICAL, "spherical", "..." },
{ PhysicalZone::CYLINDRICAL, "cylindrical", "..." },
// aliases
{ PhysicalZone::SPHERICAL, "sphere", "..." },
{ PhysicalZone::CYLINDRICAL, "cylinder", "..." },
EndImplementEnumType;
//--------------------------------------------------------------------------
void PhysicalZone::consoleInit()
{
Con::addVariable( "$PhysicalZone::renderZones", TypeBool, &smRenderPZones, "If true, a box will render around the location of all PhysicalZones.\n"
"@ingroup EnviroMisc\n");
}
void PhysicalZone::initPersistFields()
{
addGroup("Misc");
addField("velocityMod", TypeF32, Offset(mVelocityMod, PhysicalZone), "Multiply velocity of objects entering zone by this value every tick.");
addField("gravityMod", TypeF32, Offset(mGravityMod, PhysicalZone), "Gravity in PhysicalZone. Multiplies against standard gravity.");
addField("appliedForce", TypePoint3F, Offset(mAppliedForce, PhysicalZone), "Three-element floating point value representing forces in three axes to apply to objects entering PhysicalZone.");
addField("polyhedron", TypeTriggerPolyhedron, Offset(mPolyhedron, PhysicalZone),
"The polyhedron type is really a quadrilateral and consists of a corner"
"point followed by three vectors representing the edges extending from the corner." );
endGroup("Misc");
addGroup("AFX");
addField("forceType", TYPEID<PhysicalZone::ForceType>(), Offset(force_type, PhysicalZone));
addField("orientForce", TypeBool, Offset(orient_force, PhysicalZone));
endGroup("AFX");
Parent::initPersistFields();
}
//--------------------------------------------------------------------------
bool PhysicalZone::onAdd()
{
if(!Parent::onAdd())
return false;
if (mVelocityMod < -40.0f || mVelocityMod > 40.0f) {
Con::errorf("PhysicalZone: velocity mod out of range. [-40, 40]");
mVelocityMod = mVelocityMod < -40.0f ? -40.0f : 40.0f;
}
if (mGravityMod < -40.0f || mGravityMod > 40.0f) {
Con::errorf("PhysicalZone: GravityMod out of range. [-40, 40]");
mGravityMod = mGravityMod < -40.0f ? -40.0f : 40.0f;
}
static const char* coordString[] = { "x", "y", "z" };
F32* p = mAppliedForce;
for (U32 i = 0; i < 3; i++) {
if (p[i] < -40000.0f || p[i] > 40000.0f) {
Con::errorf("PhysicalZone: applied force: %s out of range. [-40000, 40000]", coordString[i]);
p[i] = p[i] < -40000.0f ? -40000.0f : 40000.0f;
}
}
Polyhedron temp = mPolyhedron;
setPolyhedron(temp);
switch (force_type)
{
case SPHERICAL:
force_mag = mAppliedForce.magnitudeSafe();
break;
case CYLINDRICAL:
{
Point3F force_vec = mAppliedForce;
force_vec.z = 0.0;
force_mag = force_vec.magnitudeSafe();
}
break;
}
addToScene();
return true;
}
void PhysicalZone::onRemove()
{
mConvexList->nukeList();
removeFromScene();
Parent::onRemove();
}
void PhysicalZone::inspectPostApply()
{
Parent::inspectPostApply();
setPolyhedron(mPolyhedron);
setMaskBits(PolyhedronMask | MoveMask | SettingsMask | FadeMask);
}
//------------------------------------------------------------------------------
void PhysicalZone::setTransform(const MatrixF & mat)
{
Parent::setTransform(mat);
MatrixF base(true);
base.scale(Point3F(1.0/mObjScale.x,
1.0/mObjScale.y,
1.0/mObjScale.z));
base.mul(mWorldToObj);
mClippedList.setBaseTransform(base);
if (isServerObject())
setMaskBits(MoveMask);
}
void PhysicalZone::prepRenderImage( SceneRenderState *state )
{
// only render if selected or render flag is set
if ( !smRenderPZones && !isSelected() )
return;
ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
ri->renderDelegate.bind( this, &PhysicalZone::renderObject );
ri->type = RenderPassManager::RIT_Editor;
ri->defaultKey = 0;
ri->defaultKey2 = 0;
state->getRenderPass()->addInst( ri );
}
void PhysicalZone::renderObject(ObjectRenderInst *ri,
SceneRenderState *state,
BaseMatInstance *overrideMat)
{
if (overrideMat)
return;
GFXStateBlockDesc desc;
desc.setZReadWrite(true, false);
desc.setBlend(true);
desc.setCullMode(GFXCullNone);
GFXTransformSaver saver;
GFXDrawUtil *drawer = GFX->getDrawUtil();
Point3F start = getBoxCenter();
Box3F obb = mObjBox; //object bounding box
F32 baseForce = 10000; //roughly the ammount of force needed to push a player back as it walks into a zone. (used for visual scaling)
Point3F forceDir = getForce(&start);
F32 forceLen = forceDir.len()/ baseForce;
forceDir.normalizeSafe();
ColorI guideCol = LinearColorF(mFabs(forceDir.x), mFabs(forceDir.y), mFabs(forceDir.z), 0.125).toColorI();
if (force_type == VECTOR)
{
Point3F endPos = start + (forceDir * mMax(forceLen,0.75f));
drawer->drawArrow(desc, start, endPos, guideCol, 0.05f);
}
MatrixF mat = getRenderTransform();
mat.scale(getScale());
GFX->multWorld(mat);
start = obb.getCenter();
if (force_type == VECTOR)
{
drawer->drawPolyhedron(desc, mPolyhedron, ColorI(0, 255, 0, 45));
}
else if (force_type == SPHERICAL)
{
F32 rad = obb.getBoundingSphere().radius/ 2;
drawer->drawSphere(desc, rad, start, ColorI(0, 255, 0, 45));
rad = (rad + (mAppliedForce.most() / baseForce))/2;
desc.setFillModeWireframe();
drawer->drawSphere(desc, rad, start, ColorI(0, 0, 255, 255));
}
else
{
Point3F bottomPos = start;
bottomPos.z -= obb.len_z() / 2;
Point3F topPos = start;
topPos.z += obb.len_z() / 2;
F32 rad = obb.len_x() / 2;
drawer->drawCylinder(desc, bottomPos, topPos, rad, ColorI(0, 255, 0, 45));
Point3F force_vec = mAppliedForce; //raw relative-applied force here as oposed to derived
F32 hieght = (force_vec.z / baseForce);
if (force_vec.z<0)
bottomPos.z = (bottomPos.z + hieght)/2;
else
topPos.z = (topPos.z + hieght) / 2;
if (force_vec.x > force_vec.y)
rad = (rad + (force_vec.x / baseForce)) / 2;
else
rad = (rad + (force_vec.y / baseForce)) / 2;
desc.setFillModeWireframe();
drawer->drawCylinder(desc, bottomPos, topPos, rad, guideCol);
}
desc.setFillModeWireframe();
drawer->drawPolyhedron(desc, mPolyhedron, ColorI::BLACK);
}
//--------------------------------------------------------------------------
U32 PhysicalZone::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
{
U32 i;
U32 retMask = Parent::packUpdate(con, mask, stream);
if (stream->writeFlag(mask & PolyhedronMask))
{
// Write the polyhedron
stream->write(mPolyhedron.mPointList.size());
for (i = 0; i < mPolyhedron.mPointList.size(); i++)
mathWrite(*stream, mPolyhedron.mPointList[i]);
stream->write(mPolyhedron.mPlaneList.size());
for (i = 0; i < mPolyhedron.mPlaneList.size(); i++)
mathWrite(*stream, mPolyhedron.mPlaneList[i]);
stream->write(mPolyhedron.mEdgeList.size());
for (i = 0; i < mPolyhedron.mEdgeList.size(); i++) {
const Polyhedron::Edge& rEdge = mPolyhedron.mEdgeList[i];
stream->write(rEdge.face[0]);
stream->write(rEdge.face[1]);
stream->write(rEdge.vertex[0]);
stream->write(rEdge.vertex[1]);
}
}
if (stream->writeFlag(mask & MoveMask))
{
stream->writeAffineTransform(mObjToWorld);
mathWrite(*stream, mObjScale);
}
if (stream->writeFlag(mask & SettingsMask))
{
stream->write(mVelocityMod);
stream->write(mGravityMod);
mathWrite(*stream, mAppliedForce);
stream->writeInt(force_type, FORCE_TYPE_BITS);
stream->writeFlag(orient_force);
}
if (stream->writeFlag(mask & FadeMask))
{
U8 fade_byte = (U8)(fade_amt*255.0f);
stream->write(fade_byte);
}
stream->writeFlag(mActive);
return retMask;
}
void PhysicalZone::unpackUpdate(NetConnection* con, BitStream* stream)
{
Parent::unpackUpdate(con, stream);
bool new_ph = false;
if (stream->readFlag()) // PolyhedronMask
{
U32 i, size;
Polyhedron tempPH;
// Read the polyhedron
stream->read(&size);
tempPH.mPointList.setSize(size);
for (i = 0; i < tempPH.mPointList.size(); i++)
mathRead(*stream, &tempPH.mPointList[i]);
stream->read(&size);
tempPH.mPlaneList.setSize(size);
for (i = 0; i < tempPH.mPlaneList.size(); i++)
mathRead(*stream, &tempPH.mPlaneList[i]);
stream->read(&size);
tempPH.mEdgeList.setSize(size);
for (i = 0; i < tempPH.mEdgeList.size(); i++) {
Polyhedron::Edge& rEdge = tempPH.mEdgeList[i];
stream->read(&rEdge.face[0]);
stream->read(&rEdge.face[1]);
stream->read(&rEdge.vertex[0]);
stream->read(&rEdge.vertex[1]);
}
setPolyhedron(tempPH);
new_ph = true;
}
if (stream->readFlag()) // MoveMask
{
MatrixF temp;
stream->readAffineTransform(&temp);
Point3F tempScale;
mathRead(*stream, &tempScale);
//if (!new_ph)
//{
// Polyhedron rPolyhedron = mPolyhedron;
// setPolyhedron(rPolyhedron);
//}
setScale(tempScale);
setTransform(temp);
}
if (stream->readFlag()) //SettingsMask
{
stream->read(&mVelocityMod);
stream->read(&mGravityMod);
mathRead(*stream, &mAppliedForce);
force_type = stream->readInt(FORCE_TYPE_BITS); // AFX
orient_force = stream->readFlag(); // AFX
}
if (stream->readFlag()) //FadeMask
{
U8 fade_byte;
stream->read(&fade_byte);
fade_amt = ((F32)fade_byte)/255.0f;
}
else
fade_amt = 1.0f;
mActive = stream->readFlag();
}
//--------------------------------------------------------------------------
void PhysicalZone::setPolyhedron(const Polyhedron& rPolyhedron)
{
mPolyhedron = rPolyhedron;
if (mPolyhedron.mPointList.size() != 0) {
mObjBox.minExtents.set(1e10, 1e10, 1e10);
mObjBox.maxExtents.set(-1e10, -1e10, -1e10);
for (U32 i = 0; i < mPolyhedron.mPointList.size(); i++) {
mObjBox.minExtents.setMin(mPolyhedron.mPointList[i]);
mObjBox.maxExtents.setMax(mPolyhedron.mPointList[i]);
}
} else {
mObjBox.minExtents.set(-0.5, -0.5, -0.5);
mObjBox.maxExtents.set( 0.5, 0.5, 0.5);
}
MatrixF xform = getTransform();
setTransform(xform);
mClippedList.clear();
mClippedList.mPlaneList = mPolyhedron.mPlaneList;
MatrixF base(true);
base.scale(Point3F(1.0/mObjScale.x,
1.0/mObjScale.y,
1.0/mObjScale.z));
base.mul(mWorldToObj);
mClippedList.setBaseTransform(base);
}
//--------------------------------------------------------------------------
void PhysicalZone::buildConvex(const Box3F& box, Convex* convex)
{
// These should really come out of a pool
mConvexList->collectGarbage();
Box3F realBox = box;
mWorldToObj.mul(realBox);
realBox.minExtents.convolveInverse(mObjScale);
realBox.maxExtents.convolveInverse(mObjScale);
if (realBox.isOverlapped(getObjBox()) == false)
return;
// Just return a box convex for the entire shape...
Convex* cc = 0;
CollisionWorkingList& wl = convex->getWorkingList();
for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) {
if (itr->mConvex->getType() == BoxConvexType &&
itr->mConvex->getObject() == this) {
cc = itr->mConvex;
break;
}
}
if (cc)
return;
// Create a new convex.
BoxConvex* cp = new BoxConvex;
mConvexList->registerObject(cp);
convex->addToWorkingList(cp);
cp->init(this);
mObjBox.getCenter(&cp->mCenter);
cp->mSize.x = mObjBox.len_x() / 2.0f;
cp->mSize.y = mObjBox.len_y() / 2.0f;
cp->mSize.z = mObjBox.len_z() / 2.0f;
}
bool PhysicalZone::testObject(SceneObject* enter)
{
// TODO: This doesn't look like it's testing against the polyhedron at
// all. And whats the point of building a convex if no collision methods
// are implemented?
if (mPolyhedron.mPointList.size() == 0)
return false;
mClippedList.clear();
SphereF sphere;
sphere.center = (mWorldBox.minExtents + mWorldBox.maxExtents) * 0.5;
VectorF bv = mWorldBox.maxExtents - sphere.center;
sphere.radius = bv.len();
enter->buildPolyList(PLC_Collision, &mClippedList, mWorldBox, sphere);
return mClippedList.isEmpty() == false;
}
bool PhysicalZone::testBox( const Box3F &box ) const
{
return mWorldBox.isOverlapped( box );
}
void PhysicalZone::activate()
{
AssertFatal(isServerObject(), "Client objects not allowed in ForceFieldInstance::open()");
if (mActive != true)
setMaskBits(ActiveMask);
mActive = true;
}
void PhysicalZone::deactivate()
{
AssertFatal(isServerObject(), "Client objects not allowed in ForceFieldInstance::close()");
if (mActive != false)
setMaskBits(ActiveMask);
mActive = false;
}
void PhysicalZone::onStaticModified(const char* slotName, const char*newValue)
{
if (dStricmp(slotName, "appliedForce") == 0 || dStricmp(slotName, "forceType") == 0)
{
switch (force_type)
{
case SPHERICAL:
force_mag = mAppliedForce.magnitudeSafe();
break;
case CYLINDRICAL:
{
Point3F force_vec = mAppliedForce;
force_vec.z = 0.0;
force_mag = force_vec.magnitudeSafe();
}
break;
}
}
}
const Point3F& PhysicalZone::getForce(const Point3F* center) const
{
static Point3F force_vec;
if (force_type == VECTOR)
{
if (orient_force)
{
getTransform().mulV(mAppliedForce, &force_vec);
force_vec *= fade_amt;
return force_vec;
}
force_vec = mAppliedForce;
force_vec *= fade_amt;
return force_vec;
}
if (!center)
{
force_vec.zero();
return force_vec;
}
if (force_type == SPHERICAL)
{
force_vec = *center - getPosition();
force_vec.normalizeSafe();
force_vec *= force_mag*fade_amt;
return force_vec;
}
if (orient_force)
{
force_vec = *center - getPosition();
getWorldTransform().mulV(force_vec);
force_vec.z = 0.0f;
force_vec.normalizeSafe();
force_vec *= force_mag;
force_vec.z = mAppliedForce.z;
getTransform().mulV(force_vec);
force_vec *= fade_amt;
return force_vec;
}
force_vec = *center - getPosition();
force_vec.z = 0.0f;
force_vec.normalizeSafe();
force_vec *= force_mag;
force_vec *= fade_amt;
return force_vec;
}
bool PhysicalZone::isExcludedObject(SceneObject* obj) const
{
for (S32 i = 0; i < excluded_objects.size(); i++)
if (excluded_objects[i] == obj)
return true;
return false;
}
void PhysicalZone::registerExcludedObject(SceneObject* obj)
{
if (isExcludedObject(obj))
return;
excluded_objects.push_back(obj);
setMaskBits(FadeMask);
}
void PhysicalZone::unregisterExcludedObject(SceneObject* obj)
{
for (S32 i = 0; i < excluded_objects.size(); i++)
if (excluded_objects[i] == obj)
{
excluded_objects.erase(i);
setMaskBits(FadeMask);
return;
}
}
|
Music, Arts & Culture » Music
School for Soul
Numero Group's 'database of weirdness' now includes kids' songs
There is no record label in the country today reissuing decades-old soul recordings with more avidity, frequency and sense for archaeology than the Numero Group, an academic and semi-mysterious company possessing the secret added ingredient of impeccable taste. While soul and funk reissue labels have flourished since the turn of the millennium, many of them, particularly of the highly elastic "heavy funk" or "northern soul" persuasion, are perfect examples of curators who confuse mediocrity with authenticity. The Numero Group got off on a similar foot, focusing on arcane recordings from the Capsoul and Bandit labels, which at best were historical facsimiles (the sounds of copied sounds) and at worst, painful to listen to (poorly recorded a cappella tracks).
But then the Numero Group took a vacation to Belize, which most Americans know as a trendy and inexpensive getaway offering empty beaches, scuba diving and, if you know where to look, cheap blow. Who could have guessed that there was such a rich musical legacy down there? The unearthed music from Belize City Boil Up, released early this year, runs the gamut, covering funk, soul, reggae, calypso and highlife, all with a hard-to-define Belizean twist that is as peculiar as it is intoxicating.
Next came the label's foray to the Bahamas, which produced the incredible Grand Bahama Goombay, the gold star of the label's work so far. Outputted from a single studio on the island, the tracks envelop everything attractive about music: rhythm, politics, love, sex and poetry, all done in such an innocent, unaffected fashion that you almost feel guilty listening to it, like traipsing uninvited into a private party. But by providing extensive liner notes and reproduced cover art from the original Bahaman albums, the Numero Group essentially shoves the invitation into your hands.
The latest addition to the label's catalogue is Home Schooled: The Sound of Kid Soul, which revisits American shores by spotlighting the attempts of grade-school children to capitalize on the Jackson 5's 1970 breakthrough success. Most of these recordings were masterminded by overzealous parents, but it's clear that the kids of Home Schooled are the ones in charge. The songs are largely sweet and unrefined, as in the particular case of the sublime and otherworldly "Time After Time" by a group of forgotten Milwaukee brothers called Step by Step, though other tracks flirt with youth empowerment, like the leadoff track "Trust Your Child" and the campy "Now That School Is Through" by a group called Cindy and the Playmates.
How did all of this great music come to suddenly see the light of day with proper licensing, royalties and historical perspective? Ken Shipley, head of the Numero Group, credits the curiosity of his small group of record-collector friends, who for purely personal reasons had taken to tracking down the original artists of obscure 45s that they had collectively discovered, pored over and fallen in love with. "I figured that as long as we're finding these people," Shipley says from his Chicago office, "why don't we document what we're doing?"
Part hoarder, part musicologist, part detective, Shipley as a child collected baseball cards and comic books and, more obsessively, G.I. Joes and Transformers (he still boasts owning complete sets of both). Coming of age in the early '90s San Jose punk scene, he started collecting records, booking shows and running a small indie label, all by the age of 18.
Around 10 years ago, Shipley discovered soul music, particularly of the unknown, thrift-store, what-the-hell-is-this variety, and after a stint at reissue label Rykodisc, he finally launched his dream label in Chicago. Right next to the Jackson 5's hometown of Gary, Ind., there's possibly no better city in which to compile the kid-group sounds of Home Schooled.
"The Jackson 5 actually set off something pretty important," Shipley emphasizes. "When you think about the Jackson 5, you think, 'OK, there might have been a couple other groups, like the Osmonds.' But you don't realize that hundreds and hundreds of groups were set off! People were really trying to ride this phenomenon."
The obstacles involved in finding now-grown singers on records made 30 years ago are myriad. The children of famed organist Merl Saunders, who contribute to Home Schooled a psychedelic, black-power jam in "Right On," were relatively easy to locate. But the adults often retained the rights, and in some cases, like the Three Simmons' playfully innocent "You Are My Dream (School Time)," the copyright holders turned out to be drug-smuggling criminals using record production as a tax shelter.
"Here's the real rub with the record: we were only able to find half the actual kids," Shipley says. "Like the Atons, for instance—nobody knows who that group is. Nobody knows who the Triads are. But these producers, they were just pumping kid groups out. They were like, 'You got some kids? All right, let's throw these three kids in the studio and see what happens.'"
Another problem Shipley faced was the Embarrassing Childhood Photos factor. The Eight Minutes' Wendell Sudduth was easy to find—he still lives in Chicago—but nearly impossible to convince that reissuing his group's killer track "Here's Some Dances" was a good idea. "A lot of this stuff, it isn't a positive note for most people," Shipley admits. "When they think about this stuff, they don't think, 'This is exactly how I want to be viewed in my life.'"
The Numero Group makes deluxe packaging, especially for vinyl releases, which always include extra tracks, heavy gatefolds, inner sleeves and full-color illustrated liner notes. There's a cohesion of style in the label's design, inspired by the matching spines of Impulse Records and Jim Thompson's crime books, and a variety of projects on deck for the future (this year's Ladies of the Canyon explores unknown female singers from the era of Joni Mitchell's Blue, which Shipley cites as his favorite album).
But the biggest task, always at hand, is the musical detective work, the Indiana Jones&–like passion for discovery. Shipley knows that even the tiniest clues from seemingly insignificant people can lead to goldmines, like the box of original tapes from long-lost soul singer Helene Smith that he listens to in the background during our interview, which he recently rescued from someone's ex-wife's basement in Miami, or the singers in the Bahamas who opened the nooks and crannies of their archives and shared every minute detail of their lives with him for Grand Bahama Goombay.
"If you keep cataloguing it and cataloguing it," Shipley says, referring to his reams of notes and boxes of old photos, "you get a real database of weirdness."
Add a comment
|
Teeth grinding and snoring
Teeth grinding and Snoring
I am amazed at how many people grind their teeth and are recommended to use mouth guards at night. That’s not my idea of a sexy evening!
Now, it could be there is a problem with teeth alignment and a guard is needed, fair enough. On the other hand stress plays a big part in this. Tension in the body is commonly stored in shoulders, neck and jaw. When jaw muscles tighten up they clamp your teeth and the behaviour of grinding starts. Teeth grinding can lead to worn and broken teeth, aching, clicky and even broken jaws, and certainly to huge dental bills.
How do you know you grind your teeth? Well, some people don’t know until their dentist tells them their teeth are worn. Others are heard by their partners, while others have sore and aching jaws the next day. Some people clamp and grind during the day. Many, many people do it.
There are all sorts of treatments, including mouth guards. Some people get regular botox to release the tension in the muscles, others take tablets, plug their noses, and I am sure there are plenty of old wives tales and interesting things on pharmacy shelves.
If you grind here is something to consider immediately. What is going on in your life? Is there, or has there been, something you are angry or frustrated about? Are you worried? Uncertain work, money and relationship problems can be creating tension in your jaw. You may be completely unaware why. It is wise to come and get it checked out and healed before spending any sums on treatment that may be only a patch.
Those coming to see me to release jaw tension start with hypnotherapy to relax the muscles, a habit change which makes them aware of when they grind so they immediately loosen up, whether asleep or awake. The next session is an EFT tapping session looking for stress and releasing it. Should there be a deeper causal issue this will be addressed next, and the last session consolidates all.
There is a real sense of letting go, a real relief, resulting from this process. No more grinding. In fact, lots of other muscles relaxed at the same time. Perhaps quite a saving on dental procedures.
Snoring is an interesting one. Many people snore and don’t realise it. Their partners, though, are quite aware of it and get fed up having to put up with the noise. Some even move to another bed.
Everyone has the right to sleep properly so we need to get the snorers being more aware of when they start and turning themselves over, breathing better, losing weight stopping smoking, or going easier on the alcohol. Yes, all these things influence snoring. Send them along for some help, it will make all the difference to them and benefit the whole family.
Leave a Reply
WordPress.com Logo
Twitter picture
Facebook photo
Google+ photo
Connecting to %s
%d bloggers like this:
|
Thursday, February 27, 2014
the Junians
Monday, February 17, 2014
the Athomians
Athomian lives are rigidly dictated by social status, measured by both strength and artistic talent. Athomians are presumed to be descended from the Noblei, as their clans migrated north along with the Junians and the Eldragoths. Their society spread further north following the last Turning. Forced to compete with the Beastmen of the northern hills and plains, they have become fiercely barbaric and truly anarchic.
Athomians do not have a traditional family structure, nor do they perform weddings. When Athomians have children they form families that last only until the child, or children, are capable of taking care of themselves. However, they are not as divided as outsiders believe them to be, there is little to no rivalry between clans. Conflicts are always resolved by individual warriors, and clan members respect the outcome of the battle or contest.
Athomians are rarely encountered as single individuals. Outcasts from the Athomian clans are scarred or branded in some way so that other Athomians will know them and reject them as well. The most important thing to an Athomian is their place in the clan. To be cast out is to be dead in the eyes of their goddess, because of this many outcasts would rather commit suicide than try to integrate into other cultures.
Athomians value both skill with a weapon and artistic ability. The leader of a clan is often both the best fighter and the one who spends most of their time working a trade for the benefit or glory of the clan. Athomians have perfected the art of swordfighting, as well as swordmaking. Their intricate but sturdy weapons are highly prized and sought after. Disputes that are not settled by dueling are resolved by a comparison of talent by the two opponents, this usually entails both parties forging a sword and allowing other members of the clan to inspect them, but it can also involve skills as decorative as embroidery or as practical as woodworking.
An Athomian always keeps their personal equipment immaculately clean and weapons are kept perfectly maintained and oiled. Athomians prefer to wear vivid colors that many consider unpleasant, such as vibrant orange, bright green, and deep purple. They will also tattoo their entire bodies in these colors. Paradoxically, their grooming habits are awful and their focus on outward appearance means they are actually very dirty and unkempt, and many jokes have been made about how their awful color coordination cannot mask their awful body odor. Athomians do not prize bodily hygiene as much as their fashion sense or a perfectly balanced blade.
Every clan worships the same vicious and secretive goddess. Her name is never revealed to outsiders, and she grants power to a very select few. Sacrifices to her are common among all Athomian clans. The formal rituals and ceremonies performed in her esoteric name last for hours and sometimes climax in a brutal death, of a member of the clan if an outsider hasn't been acquired.
Friday, February 14, 2014
the Eldragoths
The Eldragoths represent a competitive culture that exalted fighting, but they have turned their savagery inward and suffered as a result. The Eldragoths are the poorest of the five major human cultures, and also the most savage. Their society spread to the far north following the last Turning, and rather than compete with Athomians and Beastmen for resources they fell into raiding and pillaging most of the settlements they encountered.
The Eldragoths are a divided people, clustered together into nomadic tribes that will hunt game in one area until the population withers, then forced to move on to more populous lands. Whole tribes frequently compete with other Eldragoth tribes for the best resources. A single Eldragoth, either an outcast or one who was dislodged from a role of command, will often fight as a mercenary for other races. The most important thing to an Eldragoth is food, and if fighting for gold or silver brings them food than that is what they do, even though they disdain the use of money as a sign of weakness.
Might makes right in their eyes, and the leader is always the strongest of the tribe. He or she may take whatever they like from the weaker members of the tribe, including life and property. All forms of disputes, as mundane as personal grudges or as inevitable as challenges to leadership, are settled by contests of physical strength - usually fights - and serious grievances involve bloody and prolonged fistfights that don't end until an opponent is bludgeoned to death.
Eldragoths always prefer to fight with their fists and they disdain large weaponry, an Eldragoth will never use a weapon to kill another Eldragoth, even in a tribal conflict. But outsiders should always be wary as Eldragoths have no disdain for picking up knives or bows to slay outsiders. An Eldragoth with a knife is a foe to be feared!
Anyone who is unable to fight or hunt is considered useless and will become an outcast. One who fights and loses is not considered dishonorable, but just of a lower station than one who wins. The children of these Eldragoth tribes learn how to fight at an early age, or they die. A few tribes will abandon their weaker children, these few usually become slaves to other tribes, or in worse cases become victims of the Beastmen.
No single tribe worships a god or pantheon of deities, but each seems to have their own form of religion revolving around the worship of nature spirits. These spirits often have elaborate names that are never pronounced the same way twice. The spirits across various tribes all have one thing in common, they respond to blood. The greater the sacrifice of blood, the greater the boon.
Eldragoths have spread out farther from the northern plains, and have not localized to one area for at least 140 years. Some tribes are spotted as far west as the Black Plateau. They hunt anything with meat on it, and it is an acknowledged fact that a few tribes have turned to cannibalism, willing to hunt other humans or dwarves when food is scarce. They don't ever seem to eat each other, just as they don't kill each other. An important facet of Eldragoth culture that must be remembered by anybody who wishes to hire one as a bodyguard or soldier.
Tuesday, February 11, 2014
promoting kickstarters for a change
I usually only post about kickstarters when I'm complaining about their tardiness. I've grown really selective with what I invest my money into, and recently a few projects have come up that are really cool and I want to see them succeed.
LotFP Free RPG Day 2014
(left image is the cover for Doom Cave of the Crystal-Headed Children, art by Gennifer Bone; right image is the cover for World of the Lost by Rafael Chandler, art by Malcolm McClinton)
He's cutting it close to the wire to release for Free RPG Day this year, but I could see James Raggi doing a funding project like this every year now. I'm expecting the next project he throws up might be a "LotFP Free RPG Day 2015" project, and I would back that one too because I've only ever been disappointed by one of Raggi's projects (and it's one I never hear people talking about). This project is particularly interesting because it's set up to put some responsibility into the hands of the donor, you have to email James to tell him what rewards you want. One of the rewards is an adventure written by Rafael Chandler and the only way it will ever be published is through this campaign!
The Islands of Purple-Haunted Putrescence (an OSR module)
(art by Faustie)
A modest little kickstarter campaign from an accomplished self-publisher and a gamer in my neck of the woods. Seriously, he lives about 5 minutes away from me. He and I have the same haunts though we've never played a game together. I'd like to see him succeed both because he's a local and judging from his work we have similar tastes. I'm not sure where he comes up with his titles but I wish I had that same level of crazy creativity.
Darkest Dungeon
I think anybody who is an OSR gamer will want to take a look at this one even though it's a video game. I've been on their mailing list for a couple of months now and I knew this kickstarter campaign was coming. After one day of being live they're already very close to funding, because it's a video game I expect feature creep to potentially be an issue but this is one game that I would love to see hit some stretch goals.
And that's it. Go forth and spend some of your money to help make these projects happen and get cool games in return!
Friday, February 7, 2014
monster: the Quilid
the Quilid
This long furry, serpentine creature has thick, sharp spines all along it's segmented body. It has short legs ending in suction-cups along every part of it's body allowing it to crawl along walls and ceiling. It is constantly hungry and attacks by trying to devour the nearest, most magical target. It seems to crave a spellcaster's flesh!
Initiative: +3
Attack: +6
Bite (2d8+poison, save or stunned for 1 round)
Armor Class: 14 (ascending)
HD 6d6 (hp 24)
MV 80' (wall-crawling)
Save Fort +2 Ref -1 Will -1
Morale: nil
Special: attackers must Reflex save or get poked with spines taking 2d4-1 damage
Tactics: always attacks person with most magical items, failing that attacks spellcasters, wizards before clerics
monster: the Orsect
the Orsect
Alien insectile humanoids, they are sometimes found in nests where they number in the hundreds. They are larger than the average human at full maturity, but their torso is fragile and spindly. Their muscles are thin and lithe. Orsects have underdeveloped retractable wings that lie under a carapace, they can glide short distances and even hover momentarily, but the wings are too frail to support their size for long. Orsects can crawl along walls and ceilings, and their faces have large venomous fangs reminiscent of a spider's cephalothorax. Their chitinous skin often has stocks of black or brown hair sticking out between the plates.
Initiative: +1
Attack: +1
Claw x2 (1d6+1) or Bite (1d6; save vs poison/Fort, 1d6 damage over next 2 rounds)
Armor Class: 13 (ascending)
Hit Dice: 1d8 (hp 4)
Move: 30' (wall-crawling) / 60' (flight, once per four rounds)
Saves: Fort +0 Ref +2 Will -1
Morale: 8
Tactics: attacks smallest/weakest PC first
Wednesday, February 5, 2014
Bargaining, or The Partial Success
My favorite part of the Apocalypse World rules is the partial success. The feature of the partial success is most illustrative with the "acting under fire" move. "Acting under fire" is trying to do something that requires unusual discipline or concentration or with reserves of willpower or under threat of violence or something like that. AW hacks have reinterpreted this move as "Defy Danger" "Act Under Pressure" "Strive Against Peril" etc. When you "act under fire" and you get the partial success, it specifically states that the MC (the GM) might offer you a worse outcome, an ugly choice or a hard bargain. The rulebook implies that the MC should pick one and offer it as the result, but during play this usually comes down to more than one option offered to the player who then chooses which result occurs.
Worse Outcome. Ugly Choice. Hard Bargain. It sounds like three things, but it's actually four. Let me give you a few examples to illustrate this:
We're going to follow Cyril for a bit. He's a bit of an untalented goon with no real skills to speak of, but he's got a knack for being in the right place at the right time and he's got a tongue that's as sharp as a cleaver. One big thing he has going for himself is that he's a Hocus, so he's got his own personal cult of about 15 devotees who worship him, hang on his every word, and follow him around like lost puppy dogs.
A biker gang is moving through the town where Cyril preaches to his flock and before they leave town they've decided to have a little fun. The gang's leader is trying to lasso Cyril with an old plastic rope that looks hand woven. When Cyril tries to escape he's acting under fire and rolls a 9. The MC can offer...
• a worse outcome: Cyril will take 4 harm as he runs into another biker and gets knocked down to the ground, unconscious, but he will get left alone afterward as the gang laughs their asses off in the assumption that he got accidentally killed.
• an ugly choice: Cyril will dive through a window, taking 2 harm, and escape through the back of the building losing sight of the gang and his followers, or get away down an alleyway but drop something important/valuable, like the wrought iron staff that he uses to focus his followers' attention during his sermons.
• a hard bargain: Cyril will get away, but his loyal followers will definitely not avoid the gang's attention.
Cyril takes the hard bargain and gets away, his followers are not so lucky. The MC gauges from the gang's size (small) and harm (3) that Cyril will lose 4 of his followers to the gang, 2 of them are killed and 2 of them are kidnapped.
The gang makes camp in a grassy ravine near town and Cyril, upon learning that 2 of his flock have been kidnapped, decides to sneak into their camp to liberate them. The closest thing to a sneak move in Apocalypse World is acting under fire so that's what Cyril is doing, and he rolls a 9 again. The MC offers...
• a worse outcome: Cyril is caught and captured, but not harmed, by the gang.
• an ugly choice: Cyril was followed by some of his enthusiastic cultists and they get caught but the distraction will allow him to sneak in undetected, or Cyril is spotted by the camp lookout and gets shot, taking 3 harm, but his enthusiastic followers make it into the camp from his distraction.
• a hard bargain: Cyril sneaks in, but his kidnapped followers have been tortured and killed and there's nothing he can do for them now.
Cyril takes the ugly choice this time and tells the MC that his enthusiastic followers get caught. The MC declares them dead, but Cyril is in the camp and his other followers who were kidnapped are there, and relatively unharmed.
The MC declares that the whole gang's encampment is now on high alert, it's going to be pretty tough sneaking out of here so Cyril is going to need to do something tricky to get his kidnapped followers to safety. Cyril is now keenly aware that 4 of his people got killed today and he might get 2 more killed, he's resolved not to let anybody else from his cult die. Cyril frees his followers and instructs them to get out of the camp and back home while he creates a distraction. Cyril runs out of hiding straight for the gang leader with his staff, and declares he wants to use the focusing power of the staff to heel the leader of the gang to Cyril's will. The MC decides that this isn't a manipulation and it doesn't fall under Cyril's normal use of his Hocus powers, she declares that this is another use of acting under fire but Cyril is being inventive and taking a huge risk, she lets him roll his best stat this time, but he still rolls a 9. The MC offers...
• a worse outcome: Cyril is shot, point-blank, by the gang's leader. 5-harm. His followers will get away clean.
• an ugly choice: He creates enough of a distraction that his followers get away, but they've been seen fleeing and he's captured, or he has the full attention of the gang leader but his followers won't leave without him and all eyes in the camp are on Cyril right now.
• a hard bargain: Cyril has the gang's leader under his command, but that doesn't sway the rest of the gang at all.
Regardless of where you're sitting at the table, this is my favorite mechanic. As a player it gives you a brief moment of control, like rolling with a punch or flipping between two choices in a Choose Your Own Adventure novel. As an MC, it offers a challenging moment of looking at ugly/hard/worse options and offering them up as a meal. It is really hard to pull off well as a MC, since a partial success is still fundamentally a success, but I believe that mastering this on-the-spot thinking is what can make or break GMing properly.
Tuesday, February 4, 2014
Apocalypse World of Darkness (brainstorming)
Apocalypse World, from now on AW. World of Darkness, from now on WoD
AW has playbooks, WoD has splats; I'm ambivalent about both but recognize the value for players to have easy choices
AW has 5 stats and a plethora of moves, WoD has 9 attributes and 21 skills; I like a simple system, so let's keep WoD's attributes but get rid of the skills
AW has countdown clocks, WoD has dots and points; I like dots and points
AW rolls 2d6, WoD rolls pools of d10s; I like pools of dice, but let's use d6s because this isn't WoD, this is AWoD
AW has complications and partial successes, WoD has exceptional successes and dramatic failures; I like complications and varying levels of success
Trying to fuse the Apocalypse World moves dynamic with the standard World of Darkness stat blocks: Everything is kept the same, roll dice pools and only count the highest number on any rolled dice.
Any result of '5' or higher can be used as a success for the roll.
All dice rolling at 4 or less means the GM can make a hard move, or mark a hard move for use later.
A dice that comes up a '6' allows you to roll another dice.
I'm not sure how the math would work out. Combat and damage would have to be tweaked slightly anyway. For now, let's see how it works.
From the WoD core rulebook: Perception
Dice Pool:
Wits + Composure
Roll Results
Dramatic Failure:
Your character notices something strange or out of place, but it’s not what has actually occurred, or he makes a dangerous assumption about the event. A picture hanging at an odd angle indicates that someone has moved it, but your character assumes that a door has been slammed, shifting the piece of art.
Failure: Your character notices nothing amiss or out of place.
Success: Your character recognizes that something has happened.
Exceptional Success: Your character not only recognizes when something unusual or quick happens nearby, he sees it all happen and gets a good look. Or he notices a variety of things that are amiss in his surroundings, just by entering the room.
My interpretation: Perception when you roll Wits+Composure, spend successes to ask questions.
• what does this mean?
• what happened here recently?
• what is about to happen?
• what here is not what it appears to be?
• what here is useful or valuable to me?
• what is this?
• where’s my best escape route / way in / way past?
• which enemy is most vulnerable to me?
• which enemy is the biggest threat?
• who’s in control here?
• is __ telling the truth?
• what does __ intend to do?
• what does __ wish I’d do?
• what’s __ really feeling?
I think that works but I'm not sure how partial successes would work out, because that's my favorite thing about AW. I'd be curious to figure out how combat would work, but that would require more work and I have to shelve this idea for now. I want to get back to working on... a few other things. I've got two D&D scenarios I'm writing, two maps I'm drawing, a new playbook for AW, rules for Fantasy Heartfucker or whatever I'm going to call it. I've got too many projects that I keep working on a little bit at a time, I need to focus on one and finish it sometime soon.
|
#ifdef _WIN32
#define BUILDING_DLL
#ifdef BUILD_RENDERER
#define RENDERER_API __declspec(dllexport)
#else
#define RENDERER_API __declspec(dllimport)
#endif
#elif linux
#define RENDERER_API
#endif
#include "gWindow.h"
// RENDERER API for creating shared libraries to call methods from Python.
// Creating window.
extern "C" RENDERER_API Window* create_window(const unsigned int WIDTH,
const unsigned int HEIGHT,
const char* title);
// Close window.
extern "C" RENDERER_API void close(Window* window);
// Check the window is closed or not.
extern "C" RENDERER_API bool is_close(Window* window);
// Render the window.
extern "C" RENDERER_API void render(Window* window);
// Terminate the OpenGL.
extern "C" RENDERER_API void terminate();
// Create model with its shaders.
extern "C" RENDERER_API Model* create_model(char* model_path, char* vertex_shader_file_path, char* fragment_shader_file_path);
// Add model as permanent drawables object to window.
extern "C" RENDERER_API void add_permanent_to_window(Window* window, Model* model);
// Add model as instantaneous drawables object to window.
extern "C" RENDERER_API void add_instantaneous_to_window(Window* window, Model* model);
// Translate model to locations. Locations will be in OpenGL coordinates.
extern "C" RENDERER_API void translate_model(Model* model, float x, float y, float z);
// Rotate model to angle. From will be an rotation around arbitrary angle.
extern "C" RENDERER_API void rotate_model(Model* model, float angle, float x, float y, float z);
// Scale model to the ratios for each axis.
extern "C" RENDERER_API void scale_model(Model* model, float x, float y, float z);
// Get FPS from the window.
extern "C" RENDERER_API float get_fps(Window* window);
// Set FPS of the window.
extern "C" RENDERER_API void set_fps(Window* window, float fps);
// Get Camera pointer of the window.
extern "C" RENDERER_API Camera* get_camera(Window* window);
// Set Camera position of each axis.
extern "C" RENDERER_API void set_camera_pos(Camera* camera, float x, float y, float z);
// Get camera position as float array.
extern "C" RENDERER_API float* get_camera_pos(Camera * camera);
// Check whether the window is visible or not.
extern "C" RENDERER_API bool is_visible(Window* window);
// Hide the window.
extern "C" RENDERER_API void hide_window(Window* window);
// Show the window.
extern "C" RENDERER_API void show_window(Window* window);
// Create guiText vector.
extern "C" RENDERER_API int create_guiTextVector(Window * window, const char* title,
float pos_x, float pos_y,
float size_x, float size_y);
// Add the str and val to guiText vector.
extern "C" RENDERER_API void add_guiText(Window* window, int v_guiText_ind, int size, char** _str, float* _val);
// Set the guiText of vector.
extern "C" RENDERER_API void set_guiText(Window* window, int v_guiText_ind, float* _val);
// Rotate the model Main Rotor with each angle which are in radians.
extern "C" RENDERER_API void rotate_MR(Model* model, float phi, float theta, float psi);
// Rotate the model Tail Rotor with each angle which are in radians.
extern "C" RENDERER_API void rotate_TR(Model* model, float phi, float theta, float psi);
|
/**
* @file
* @brief Deprecated precision menu code.
**/
#include "AppHdr.h"
#include "menu.h"
#include "precision-menu.h"
#include <functional>
#include "libutil.h"
#include "stringutil.h"
/**
* Performs regular rectangular AABB intersection between the given AABB
* rectangle and a item in the menu_entries
* <pre>
* start(x,y)------------
* | |
* ------------end(x,y)
* </pre>
*/
static bool _AABB_intersection(const coord_def& item_start,
const coord_def& item_end,
const coord_def& aabb_start,
const coord_def& aabb_end)
{
// Check for no overlap using equals on purpose to rule out entities
// that only brush the bounding box
if (aabb_start.x >= item_end.x)
return false;
if (aabb_end.x <= item_start.x)
return false;
if (aabb_start.y >= item_end.y)
return false;
if (aabb_end.y <= item_start.y)
return false;
// We have overlap
return true;
}
PrecisionMenu::PrecisionMenu() : m_active_object(nullptr),
m_select_type(PRECISION_SINGLESELECT)
{
}
PrecisionMenu::~PrecisionMenu()
{
clear();
}
void PrecisionMenu::set_select_type(SelectType flag)
{
m_select_type = flag;
}
/**
* Frees all used memory
*/
void PrecisionMenu::clear()
{
// release all the data reserved
deleteAll(m_attached_objects);
}
/**
* Processes user input.
*
* Returns:
* true when a significant event happened, signaling that the player has made a
* menu ending action like selecting an item in singleselect mode
* false otherwise
*/
bool PrecisionMenu::process_key(int key)
{
if (m_active_object == nullptr)
{
if (m_attached_objects.empty())
{
// nothing to process
return true;
}
else
{
// pick the first object possible
for (auto mobj : m_attached_objects)
{
if (mobj->can_be_focused())
{
m_active_object = mobj;
break;
}
}
}
}
#ifdef TOUCH_UI
if (key == CK_TOUCH_DUMMY)
return true; // mouse click in title area, which wouldn't usually be handled
#endif
// Handle CK_MOUSE_CLICK separately
// This signifies a menu ending action
if (key == CK_MOUSE_CLICK)
return true;
bool focus_find = false;
PrecisionMenu::Direction focus_direction;
MenuObject::InputReturnValue input_ret = m_active_object->process_input(key);
switch (input_ret)
{
case MenuObject::INPUT_NO_ACTION:
break;
case MenuObject::INPUT_SELECTED:
if (m_select_type == PRECISION_SINGLESELECT)
return true;
else
{
// TODO: Handle multiselect somehow
}
break;
case MenuObject::INPUT_DESELECTED:
break;
case MenuObject::INPUT_END_MENU_SUCCESS:
return true;
case MenuObject::INPUT_END_MENU_ABORT:
clear_selections();
return true;
case MenuObject::INPUT_ACTIVE_CHANGED:
break;
case MenuObject::INPUT_FOCUS_RELEASE_UP:
focus_find = true;
focus_direction = PrecisionMenu::UP;
break;
case MenuObject::INPUT_FOCUS_RELEASE_DOWN:
focus_find = true;
focus_direction = PrecisionMenu::DOWN;
break;
case MenuObject::INPUT_FOCUS_RELEASE_LEFT:
focus_find = true;
focus_direction = PrecisionMenu::LEFT;
break;
case MenuObject::INPUT_FOCUS_RELEASE_RIGHT:
focus_find = true;
focus_direction = PrecisionMenu::RIGHT;
break;
default:
die("Malformed return value");
break;
}
if (focus_find)
{
MenuObject* find_object = _find_object_by_direction(m_active_object,
focus_direction);
if (find_object != nullptr)
{
m_active_object->set_active_item((MenuItem*)nullptr);
m_active_object = find_object;
if (focus_direction == PrecisionMenu::UP)
m_active_object->activate_last_item();
else
m_active_object->activate_first_item();
}
}
// Handle selection of other objects items hotkeys
for (MenuObject *obj : m_attached_objects)
{
MenuItem* tmp = obj->select_item_by_hotkey(key);
if (tmp != nullptr)
{
// was it a toggle?
if (!tmp->selected())
continue;
// it was a selection
if (m_select_type == PrecisionMenu::PRECISION_SINGLESELECT)
return true;
}
}
return false;
}
#ifdef USE_TILE_LOCAL
int PrecisionMenu::handle_mouse(const wm_mouse_event &me)
{
// Feed input to each attached object that the mouse is over
// The objects are responsible for processing the input
// This includes, if applicable for instance checking if the mouse
// is over the item or not
for (MenuObject *obj : m_attached_objects)
{
const MenuObject::InputReturnValue input_return = obj->handle_mouse(me);
switch (input_return)
{
case MenuObject::INPUT_SELECTED:
m_active_object = obj;
if (m_select_type == PRECISION_SINGLESELECT)
return CK_MOUSE_CLICK;
break;
case MenuObject::INPUT_ACTIVE_CHANGED:
// Set the active object to be this one
m_active_object = obj;
break;
case MenuObject::INPUT_END_MENU_SUCCESS:
// something got clicked that needs to signal the menu to end
return CK_MOUSE_CLICK;
case MenuObject::INPUT_END_MENU_ABORT:
// XXX: For right-click we use CK_MOUSE_CMD to cancel out of the
// menu, but these mouse-button->key mappings are not very sane.
clear_selections();
return CK_MOUSE_CMD;
case MenuObject::INPUT_FOCUS_LOST:
// The object lost its focus and is no longer the active one
if (obj == m_active_object)
m_active_object = nullptr;
default:
break;
}
}
return 0;
}
#endif
void PrecisionMenu::clear_selections()
{
for (MenuObject *obj : m_attached_objects)
obj->clear_selections();
}
/**
* Finds the closest rectangle to given entry start on a cardinal
* direction from it.
* If no entries are found, nullptr is returned.
*
* TODO: This is exact duplicate of MenuObject::_find_item_by_direction();
* maybe somehow generalize it and detach it from class?
*/
MenuObject* PrecisionMenu::_find_object_by_direction(const MenuObject* start,
Direction dir)
{
if (start == nullptr)
return nullptr;
coord_def aabb_start(0,0);
coord_def aabb_end(0,0);
// construct the aabb
switch (dir)
{
case UP:
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = 0; // top of screen
aabb_end.y = start->get_min_coord().y;
break;
case DOWN:
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = start->get_max_coord().y;
// we choose an arbitrarily large number here, because
// tiles saves entry coordinates in pixels, yet console saves them
// in characters
// basically, we want the AABB to be large enough to extend to the
// bottom of the screen in every possible resolution
aabb_end.y = 32767;
break;
case LEFT:
aabb_start.x = 0; // left of screen
aabb_end.x = start->get_min_coord().x;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
case RIGHT:
aabb_start.x = start->get_max_coord().x;
// we again want a value that is always larger then the width of screen
aabb_end.x = 32767;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
default:
die("Bad direction given");
}
// loop through the entries
// save the currently closest to the index in a variable
MenuObject* closest = nullptr;
for (MenuObject *obj : m_attached_objects)
{
if (!obj->can_be_focused())
{
// this is a noselect entry, skip it
continue;
}
if (!_AABB_intersection(obj->get_min_coord(), obj->get_max_coord(),
aabb_start, aabb_end))
{
continue; // does not intersect, continue loop
}
// intersects
// check if it's closer than current
if (closest == nullptr)
closest = obj;
switch (dir)
{
case UP:
if (obj->get_min_coord().y > closest->get_min_coord().y)
closest = obj;
break;
case DOWN:
if (obj->get_min_coord().y < closest->get_min_coord().y)
closest = obj;
break;
case LEFT:
if (obj->get_min_coord().x > closest->get_min_coord().x)
closest = obj;
break;
case RIGHT:
if (obj->get_min_coord().x < closest->get_min_coord().x)
closest = obj;
}
}
// TODO handle special cases here, like pressing down on the last entry
// to go the the first item in that line
return closest;
}
vector<MenuItem*> PrecisionMenu::get_selected_items()
{
vector<MenuItem*> ret_val;
for (MenuObject *obj : m_attached_objects)
for (MenuItem *item : obj->get_selected_items())
ret_val.push_back(item);
return ret_val;
}
void PrecisionMenu::attach_object(MenuObject* item)
{
ASSERT(item != nullptr);
m_attached_objects.push_back(item);
}
// Predicate for std::find_if
static bool _string_lookup(MenuObject* item, string lookup)
{
return item->get_name().compare(lookup) == 0;
}
MenuObject* PrecisionMenu::get_object_by_name(const string &search)
{
auto it = find_if(begin(m_attached_objects), end(m_attached_objects),
bind(_string_lookup, placeholders::_1, search));
return it != m_attached_objects.end() ? *it : nullptr;
}
MenuItem* PrecisionMenu::get_active_item()
{
if (m_active_object != nullptr)
return m_active_object->get_active_item();
return nullptr;
}
void PrecisionMenu::set_active_object(MenuObject* object)
{
if (object == m_active_object)
return;
// is the object attached?
auto find_val = find(m_attached_objects.begin(), m_attached_objects.end(),
object);
if (find_val != m_attached_objects.end())
{
m_active_object = object;
m_active_object->activate_first_item();
}
}
void PrecisionMenu::draw_menu()
{
for (MenuObject *obj : m_attached_objects)
obj->render();
}
MenuItem::MenuItem(): m_min_coord(0,0), m_max_coord(0,0), m_selected(false),
m_allow_highlight(true), m_dirty(false), m_visible(false),
m_link_left(nullptr), m_link_right(nullptr),
m_link_up(nullptr), m_link_down(nullptr), m_item_id(-1)
{
#ifdef USE_TILE_LOCAL
m_unit_width_pixels = tiles.get_crt_font()->char_width();
m_unit_height_pixels = tiles.get_crt_font()->char_height();
#endif
set_fg_colour(LIGHTGRAY);
set_bg_colour(BLACK);
set_highlight_colour(BLACK);
}
MenuItem::~MenuItem()
{
}
#ifdef USE_TILE_LOCAL
void MenuItem::set_height(const int height)
{
m_unit_height_pixels = height;
}
#endif
/**
* Override this if you use eg funky different sized fonts, tiles etc
*/
void MenuItem::set_bounds(const coord_def& min_coord, const coord_def& max_coord)
{
#ifdef USE_TILE_LOCAL
// these are saved in font dx / dy for mouse to work properly
// remove 1 unit from all the entries because console starts at (1,1)
// but tiles starts at (0,0)
m_min_coord.x = (min_coord.x - 1) * m_unit_width_pixels;
m_min_coord.y = (min_coord.y - 1) * m_unit_height_pixels;
m_max_coord.x = (max_coord.x - 1) * m_unit_width_pixels;
m_max_coord.y = (max_coord.y - 1) * m_unit_height_pixels;
#else
m_min_coord = min_coord;
m_max_coord = max_coord;
#endif
}
/**
* This is handly if you are already working with existing multiplied
* coordinates and modifying them
*/
void MenuItem::set_bounds_no_multiply(const coord_def& min_coord,
const coord_def& max_coord)
{
m_min_coord = min_coord;
m_max_coord = max_coord;
}
void MenuItem::move(const coord_def& delta)
{
m_min_coord += delta;
m_max_coord += delta;
}
// By default, value does nothing. Override for Items needing it.
void MenuItem::select(bool toggle, int /*value*/)
{
select(toggle);
}
void MenuItem::select(bool toggle)
{
m_selected = toggle;
m_dirty = true;
}
bool MenuItem::selected() const
{
return m_selected;
}
void MenuItem::allow_highlight(bool toggle)
{
m_allow_highlight = toggle;
m_dirty = true;
}
bool MenuItem::can_be_highlighted() const
{
return m_allow_highlight;
}
void MenuItem::set_highlight_colour(COLOURS colour)
{
m_highlight_colour = colour;
m_dirty = true;
}
COLOURS MenuItem::get_highlight_colour() const
{
return m_highlight_colour;
}
void MenuItem::set_bg_colour(COLOURS colour)
{
m_bg_colour = colour;
m_dirty = true;
}
void MenuItem::set_fg_colour(COLOURS colour)
{
m_fg_colour = colour;
m_dirty = true;
}
COLOURS MenuItem::get_fg_colour() const
{
return m_fg_colour;
}
COLOURS MenuItem::get_bg_colour() const
{
return static_cast<COLOURS> (m_bg_colour);
}
void MenuItem::set_visible(bool flag)
{
m_visible = flag;
}
bool MenuItem::is_visible() const
{
return m_visible;
}
void MenuItem::add_hotkey(int key)
{
m_hotkeys.push_back(key);
}
void MenuItem::clear_hotkeys()
{
m_hotkeys.clear();
}
const vector<int>& MenuItem::get_hotkeys() const
{
return m_hotkeys;
}
void MenuItem::set_link_left(MenuItem* item)
{
m_link_left = item;
}
void MenuItem::set_link_right(MenuItem* item)
{
m_link_right = item;
}
void MenuItem::set_link_up(MenuItem* item)
{
m_link_up = item;
}
void MenuItem::set_link_down(MenuItem* item)
{
m_link_down = item;
}
MenuItem* MenuItem::get_link_left() const
{
return m_link_left;
}
MenuItem* MenuItem::get_link_right() const
{
return m_link_right;
}
MenuItem* MenuItem::get_link_up() const
{
return m_link_up;
}
MenuItem* MenuItem::get_link_down() const
{
return m_link_down;
}
#ifdef USE_TILE_LOCAL
int MenuItem::get_vertical_offset() const
{
return m_unit_height_pixels / 2 - tiles.get_crt_font()->char_height() / 2;
}
#endif
TextItem::TextItem()
#ifdef USE_TILE_LOCAL
: m_font_buf(tiles.get_crt_font())
#endif
{
}
TextItem::~TextItem()
{
}
/**
* Rewrap the text if bounds changes
*/
void TextItem::set_bounds(const coord_def& min_coord, const coord_def& max_coord)
{
MenuItem::set_bounds(min_coord, max_coord);
_wrap_text();
m_dirty = true;
}
/**
* Rewrap the text if bounds changes
*/
void TextItem::set_bounds_no_multiply(const coord_def& min_coord,
const coord_def& max_coord)
{
MenuItem::set_bounds_no_multiply(min_coord, max_coord);
_wrap_text();
m_dirty = true;
}
void TextItem::render()
{
if (!m_visible)
return;
#ifdef USE_TILE_LOCAL
if (m_dirty)
{
m_font_buf.clear();
// TODO: handle m_bg_colour
m_font_buf.add(m_render_text, term_colours[m_fg_colour],
m_min_coord.x, m_min_coord.y + get_vertical_offset());
m_dirty = false;
}
m_font_buf.draw();
#else
// Clean the drawing area first
// clear_to_end_of_line does not work for us
string white_space(m_max_coord.x - m_min_coord.x, ' ');
textcolour(BLACK);
for (int i = 0; i < (m_max_coord.y - m_min_coord.y); ++i)
{
cgotoxy(m_min_coord.x, m_min_coord.y + i);
cprintf("%s", white_space.c_str());
}
// print each line separately, is there a cleaner solution?
size_t newline_pos = 0;
size_t endline_pos = 0;
for (int i = 0; i < (m_max_coord.y - m_min_coord.y); ++i)
{
endline_pos = m_render_text.find('\n', newline_pos);
cgotoxy(m_min_coord.x, m_min_coord.y + i);
textcolour(m_fg_colour);
textbackground(m_bg_colour);
cprintf("%s", m_render_text.substr(newline_pos,
endline_pos - newline_pos).c_str());
if (endline_pos != string::npos)
newline_pos = endline_pos + 1;
else
break;
}
// clear text background
textbackground(BLACK);
#endif
}
void TextItem::set_text(const string& text)
{
m_text = text;
_wrap_text();
m_dirty = true;
}
const string& TextItem::get_text() const
{
return m_text;
}
/**
* Wraps and chops the #m_text variable and saves the chopped
* text to #m_render_text.
* This is done to preserve the old text in case the text item
* changes size and could fit more text.
* Override if you use font with different sizes than CRTRegion font.
*/
void TextItem::_wrap_text()
{
m_render_text = m_text; // preserve original copy intact
int max_cols;
int max_lines;
max_cols = (m_max_coord.x - m_min_coord.x);
max_lines = (m_max_coord.y - m_min_coord.y);
#ifdef USE_TILE_LOCAL
// Tiles saves coordinates in pixels
max_cols = max_cols / m_unit_width_pixels;
max_lines = max_lines / m_unit_height_pixels;
#endif
if (max_cols == 0 || max_lines == 0)
{
// escape and set render text to nothing
m_render_text = "";
return;
}
int num_linebreaks = linebreak_string(m_render_text, max_cols);
if (num_linebreaks > max_lines)
{
size_t pos = 0;
// find the max_line'th occurrence of '\n'
for (int i = 0; i < max_lines; ++i)
pos = m_render_text.find('\n', pos);
// Chop of all the nonfitting text
m_render_text = m_render_text.substr(pos);
}
// m_render_text now holds the fitting part of the text, ready for render!
}
EditableTextItem::EditableTextItem() : TextItem(),
editable(true), in_edit_mode(false), edit_width(-1),
tag("generic_text_box")
{
}
void EditableTextItem::set_editable(bool e, int width)
{
editable = e;
edit_width = width;
}
/**
* A rudimentary textbox editing mode.
*
* This uses a line_reader to read some text at the location of the TextItem.
* It does not do anything with the edit results! You will need to call this
* function at the right point in the gui, and do something appropriate with
* the results elsewhere.
*
* @param custom_prefill a string to populate the box; if null, this will use
* the current text.
* @param keyproc_fun an optional keyproc for the line_reader
* (see lin_reader::set_keyproc).
*
* @return the result of the editing, including the string and the int
* returned by the line_reader.
*/
edit_result EditableTextItem::edit(const string *custom_prefill,
const line_reader::keyproc keyproc_fun)
{
char buf[80];
if (!editable)
return edit_result(string(m_text), 0);
// this is needed because render will get called during the input loop.
unwind_bool e_mode(in_edit_mode, true);
int e_width;
int box_width = m_max_coord.x - m_min_coord.x;
if (edit_width <= 0)
e_width = box_width;
else
e_width = edit_width;
e_width = min(e_width, (int) sizeof buf - 1);
// TODO: make width not dependent on prefill string
string prefill = make_stringf("%-*s", e_width,
custom_prefill ? custom_prefill->c_str() : m_text.c_str());
strncpy(buf, prefill.c_str(), e_width);
buf[e_width] = 0;
mouse_control mc(MOUSE_MODE_PROMPT);
#ifdef USE_TILE_LOCAL
m_line_buf.clear();
m_line_buf.add_square(m_min_coord.x, m_min_coord.y,
m_max_coord.x, m_max_coord.y, term_colours[RED]);
m_line_buf.draw();
unwind_bool dirty(m_dirty, false);
fontbuf_line_reader reader(buf, e_width+1, m_font_buf, 80);
reader.set_location(coord_def(m_min_coord.x,
m_min_coord.y + get_vertical_offset()));
#else
line_reader reader(buf, e_width+1, 80);
reader.set_location(m_min_coord);
#endif
reader.set_edit_mode(EDIT_MODE_OVERWRITE);
if (keyproc_fun)
reader.set_keyproc(keyproc_fun);
#ifdef USE_TILE_WEB
reader.set_prompt(prompt);
reader.set_tag(tag);
#endif
reader.set_colour(COLOUR_INHERIT, m_highlight_colour);
int result = reader.read_line(false, true);
#ifdef USE_TILE_LOCAL
m_line_buf.clear();
m_line_buf.draw();
#endif
return edit_result(string(buf), result);
}
void EditableTextItem::set_tag(string t)
{
tag = t;
}
void EditableTextItem::set_prompt(string p)
{
prompt = p;
}
bool EditableTextItem::selected() const
{
return false;
}
bool EditableTextItem::can_be_highlighted() const
{
// TODO: make this work better
return false;
}
void EditableTextItem::render()
{
#ifdef USE_TILE_LOCAL
if (in_edit_mode)
{
m_line_buf.add_square(m_min_coord.x, m_min_coord.y,
m_max_coord.x, m_max_coord.y,
term_colours[m_highlight_colour]);
m_line_buf.draw();
// this relies on m_font_buf being modified by the reader
m_font_buf.draw();
}
else
{
m_line_buf.clear();
m_line_buf.draw();
TextItem::render();
}
#else
TextItem::render();
#endif //USE_TILE_LOCAL
}
NoSelectTextItem::NoSelectTextItem()
{
}
NoSelectTextItem::~NoSelectTextItem()
{
}
// Do not allow selection
bool NoSelectTextItem::selected() const
{
return false;
}
// Do not allow highlight
bool NoSelectTextItem::can_be_highlighted() const
{
return false;
}
void FormattedTextItem::render()
{
if (!m_visible)
return;
if (m_max_coord.x == m_min_coord.x || m_max_coord.y == m_min_coord.y)
return;
#ifdef USE_TILE_LOCAL
if (m_dirty)
{
m_font_buf.clear();
// FIXME: m_fg_colour doesn't work here while it works in console.
m_font_buf.add(formatted_string::parse_string(m_render_text,
m_fg_colour),
m_min_coord.x, m_min_coord.y + get_vertical_offset());
m_dirty = false;
}
m_font_buf.draw();
#else
// Clean the drawing area first
// clear_to_end_of_line does not work for us
ASSERT(m_max_coord.x > m_min_coord.x);
ASSERT(m_max_coord.y > m_min_coord.y);
string white_space(m_max_coord.x - m_min_coord.x, ' ');
for (int i = 0; i < (m_max_coord.y - m_min_coord.y); ++i)
{
cgotoxy(m_min_coord.x, m_min_coord.y + i);
cprintf("%s", white_space.c_str());
}
cgotoxy(m_min_coord.x, m_min_coord.y);
textcolour(m_fg_colour);
display_tagged_block(m_render_text);
#endif
}
#ifdef USE_TILE_LOCAL
TextTileItem::TextTileItem()
{
for (int i = 0; i < TEX_MAX; i++)
m_tile_buf[i].set_tex(&tiles.get_image_manager()->m_textures[i]);
m_unit_height_pixels = max<int>(m_unit_height_pixels, TILE_Y);
}
TextTileItem::~TextTileItem()
{
}
void TextTileItem::add_tile(tile_def tile)
{
m_tiles.push_back(tile);
m_dirty = true;
}
void TextTileItem::set_bounds(const coord_def &min_coord, const coord_def &max_coord)
{
// these are saved in font dx / dy for mouse to work properly
// remove 1 unit from all the entries because console starts at (1,1)
// but tiles starts at (0,0)
m_min_coord.x = (min_coord.x - 1) * m_unit_width_pixels;
m_max_coord.x = (max_coord.x - 1) * m_unit_width_pixels + 4;
m_min_coord.y = (min_coord.y - 1) * m_unit_height_pixels;
m_max_coord.y = (max_coord.y - 1) * m_unit_height_pixels + 4;
}
void TextTileItem::render()
{
if (!m_visible)
return;
if (m_dirty)
{
m_font_buf.clear();
for (int t = 0; t < TEX_MAX; t++)
m_tile_buf[t].clear();
for (const tile_def &tdef : m_tiles)
{
int tile = tdef.tile;
TextureID tex = tdef.tex;
m_tile_buf[tex].add_unscaled(tile, m_min_coord.x + 2, m_min_coord.y + 2,
tdef.ymax,
(float)m_unit_height_pixels / TILE_Y);
}
// center the text
// TODO wrap / chop the text
const int tile_offset = m_tiles.empty() ? 0 : (m_unit_height_pixels + 6);
m_font_buf.add(m_text, term_colours[m_fg_colour],
m_min_coord.x + 2 + tile_offset,
m_min_coord.y + 2 + get_vertical_offset());
m_dirty = false;
}
m_font_buf.draw();
for (int i = 0; i < TEX_MAX; i++)
m_tile_buf[i].draw();
}
#endif
MenuObject::MenuObject() : m_dirty(false), m_allow_focus(true), m_min_coord(0,0),
m_max_coord(0,0), m_object_name("unnamed object")
{
#ifdef USE_TILE_LOCAL
m_unit_width_pixels = tiles.get_crt_font()->char_width();
m_unit_height_pixels = tiles.get_crt_font()->char_height();
#endif
}
MenuObject::~MenuObject()
{
}
#ifdef USE_TILE_LOCAL
void MenuObject::set_height(const int height)
{
m_unit_height_pixels = height;
}
#endif
void MenuObject::init(const coord_def& min_coord, const coord_def& max_coord,
const string& name)
{
#ifdef USE_TILE_LOCAL
// these are saved in font dx / dy for mouse to work properly
// remove 1 unit from all the entries because console starts at (1,1)
// but tiles starts at (0,0)
m_min_coord.x = (min_coord.x - 1) * m_unit_width_pixels;
m_min_coord.y = (min_coord.y - 1) * m_unit_height_pixels;
m_max_coord.x = (max_coord.x - 1) * m_unit_width_pixels;
m_max_coord.y = (max_coord.y - 1) * m_unit_height_pixels;
#else
m_min_coord = min_coord;
m_max_coord = max_coord;
#endif
m_object_name = name;
}
bool MenuObject::_is_mouse_in_bounds(const coord_def& pos)
{
// Is the mouse in our bounds?
if (m_min_coord.x > static_cast<int> (pos.x)
|| m_max_coord.x < static_cast<int> (pos.x)
|| m_min_coord.y > static_cast<int> (pos.y)
|| m_max_coord.y < static_cast<int> (pos.y))
{
return false;
}
return true;
}
MenuItem* MenuObject::_find_item_by_mouse_coords(const coord_def& pos)
{
// Is the mouse even in bounds?
if (!_is_mouse_in_bounds(pos))
return nullptr;
// Traverse
for (MenuItem *item : m_entries)
{
if (!item->can_be_highlighted())
{
// this is a noselect entry, skip it
continue;
}
if (!item->is_visible())
{
// this item is not visible, skip it
continue;
}
if (pos.x >= item->get_min_coord().x
&& pos.x <= item->get_max_coord().x
&& pos.y >= item->get_min_coord().y
&& pos.y <= item->get_max_coord().y)
{
// We're inside
return item;
}
}
// nothing found
return nullptr;
}
MenuItem* MenuObject::find_item_by_hotkey(int key)
{
// browse through all the Entries
for (MenuItem *item : m_entries)
for (int hotkey : item->get_hotkeys())
if (key == hotkey)
return item;
return nullptr;
}
MenuItem* MenuObject::select_item_by_hotkey(int key)
{
MenuItem* item = find_item_by_hotkey(key);
if (item)
select_item(item);
return item;
}
vector<MenuItem*> MenuObject::get_selected_items()
{
vector<MenuItem *> result;
for (MenuItem *item : m_entries)
if (item->selected())
result.push_back(item);
return result;
}
void MenuObject::clear_selections()
{
for (MenuItem *item : m_entries)
item->select(false);
}
void MenuObject::allow_focus(bool toggle)
{
m_allow_focus = toggle;
}
bool MenuObject::can_be_focused()
{
if (m_entries.empty())
{
// Do not allow focusing empty containers by default
return false;
}
return m_allow_focus;
}
void MenuObject::set_visible(bool flag)
{
m_visible = flag;
}
bool MenuObject::is_visible() const
{
return m_visible;
}
MenuFreeform::MenuFreeform(): m_active_item(nullptr), m_default_item(nullptr)
{
}
MenuFreeform::~MenuFreeform()
{
deleteAll(m_entries);
}
void MenuFreeform::set_default_item(MenuItem* item)
{
m_default_item = item;
}
void MenuFreeform::activate_default_item()
{
m_active_item = m_default_item;
}
MenuObject::InputReturnValue MenuFreeform::process_input(int key)
{
if (!m_allow_focus || !m_visible)
return INPUT_NO_ACTION;
if (m_active_item == nullptr)
{
if (m_entries.empty())
{
// nothing to process
return MenuObject::INPUT_NO_ACTION;
}
else if (m_default_item == nullptr)
{
// pick the first item possible
for (auto mentry : m_entries)
{
if (mentry->can_be_highlighted())
{
m_active_item = mentry;
break;
}
}
}
}
if (m_active_item == nullptr && m_default_item != nullptr)
{
switch (key)
{
case CK_UP:
case CK_DOWN:
case CK_LEFT:
case CK_RIGHT:
case CK_ENTER:
set_active_item(m_default_item);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
}
MenuItem* find_entry = nullptr;
switch (key)
{
case CK_ENTER:
if (m_active_item == nullptr)
return MenuObject::INPUT_NO_ACTION;
select_item(m_active_item);
if (m_active_item->selected())
return MenuObject::INPUT_SELECTED;
else
return MenuObject::INPUT_DESELECTED;
break;
case CK_UP:
find_entry = _find_item_by_direction(m_active_item, UP);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_UP;
break;
case CK_DOWN:
find_entry = _find_item_by_direction(m_active_item, DOWN);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_DOWN;
break;
case CK_LEFT:
find_entry = _find_item_by_direction(m_active_item, LEFT);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_LEFT;
break;
case CK_RIGHT:
find_entry = _find_item_by_direction(m_active_item, RIGHT);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_RIGHT;
break;
default:
find_entry = select_item_by_hotkey(key);
if (find_entry != nullptr)
{
if (find_entry->selected())
return MenuObject::INPUT_SELECTED;
else
return MenuObject::INPUT_DESELECTED;
}
break;
}
return MenuObject::INPUT_NO_ACTION;
}
#ifdef USE_TILE_LOCAL
MenuObject::InputReturnValue MenuFreeform::handle_mouse(const wm_mouse_event& me)
{
if (!m_allow_focus || !m_visible)
return INPUT_NO_ACTION;
if (!_is_mouse_in_bounds(coord_def(me.px, me.py)))
{
if (m_active_item != nullptr)
{
_set_active_item(nullptr);
return INPUT_FOCUS_LOST;
}
else
return INPUT_NO_ACTION;
}
MenuItem* find_item = _find_item_by_mouse_coords(coord_def(me.px, me.py));
if (find_item && find_item->handle_mouse(me))
return MenuObject::INPUT_SELECTED; // The object handled the event
else if (me.event == wm_mouse_event::MOVE)
{
if (find_item == nullptr)
{
if (m_active_item != nullptr)
{
_set_active_item(nullptr);
return INPUT_NO_ACTION;
}
}
else
{
if (m_active_item != find_item)
{
set_active_item(find_item);
return INPUT_ACTIVE_CHANGED;
}
}
return INPUT_NO_ACTION;
}
InputReturnValue ret = INPUT_NO_ACTION;
if (me.event == wm_mouse_event::PRESS)
{
if (me.button == wm_mouse_event::LEFT)
{
if (find_item != nullptr)
{
select_item(find_item);
if (find_item->selected())
ret = INPUT_SELECTED;
else
ret = INPUT_DESELECTED;
}
}
else if (me.button == wm_mouse_event::RIGHT)
ret = INPUT_END_MENU_ABORT;
}
// all the other Mouse Events are uninteresting and are ignored
return ret;
}
#endif
void MenuFreeform::render()
{
if (!m_visible)
return;
if (m_dirty)
_place_items();
for (MenuItem *item : m_entries)
item->render();
}
/**
* Handle all the dirtyness here that the MenuItems themselves do not handle
*/
void MenuFreeform::_place_items()
{
m_dirty = false;
}
MenuItem* MenuFreeform::get_active_item()
{
return m_active_item;
}
/**
* Sets item by ID
* Clears active item if ID not found
*/
void MenuFreeform::set_active_item(int ID)
{
auto it = find_if(m_entries.begin(), m_entries.end(),
[=](const MenuItem* item) { return item->get_id() == ID; });
m_active_item = (it != m_entries.end()) ? *it : nullptr;
m_dirty = true;
}
/**
* Sets active item based on index
* This function is for internal use if object does not have ID set
*/
void MenuFreeform::_set_active_item(MenuItem* item)
{
ASSERT(!item || item->can_be_highlighted());
m_active_item = item;
m_dirty = true;
}
void MenuFreeform::set_active_item(MenuItem* item)
{
bool present = find(m_entries.begin(), m_entries.end(), item) != m_entries.end();
m_active_item = (present && item->can_be_highlighted()) ? item : nullptr;
m_dirty = true;
}
void MenuFreeform::activate_first_item()
{
auto el = find_if(m_entries.begin(), m_entries.end(),
[=](const MenuItem* item) { return item->can_be_highlighted(); });
if (el != m_entries.end())
_set_active_item(*el);
}
void MenuFreeform::activate_last_item()
{
auto el = find_if(m_entries.rbegin(), m_entries.rend(),
[=](const MenuItem* item) { return item->can_be_highlighted(); });
if (el != m_entries.rend())
_set_active_item(*el);
}
bool MenuFreeform::select_item(int index)
{
if (index >= 0 && index < static_cast<int> (m_entries.size()))
{
// Flip the selection flag
m_entries.at(index)->select(!m_entries.at(index)->selected());
}
return m_entries.at(index)->selected();
}
bool MenuFreeform::select_item(MenuItem* item)
{
ASSERT(item != nullptr);
// Is the given item in menu?
auto find_val = find(m_entries.begin(), m_entries.end(), item);
if (find_val != m_entries.end())
{
// Flip the selection flag
item->select(!item->selected());
}
return item->selected();
}
bool MenuFreeform::attach_item(MenuItem* item)
{
// is the item inside boundaries?
if ( item->get_min_coord().x < m_min_coord.x
|| item->get_min_coord().x > m_max_coord.x
|| item->get_min_coord().y < m_min_coord.y
|| item->get_min_coord().y > m_max_coord.y
|| item->get_max_coord().x < m_min_coord.x
|| item->get_max_coord().x > m_max_coord.x
|| item->get_max_coord().y < m_min_coord.y
|| item->get_max_coord().y > m_max_coord.y)
{
return false;
}
// It's inside boundaries
m_entries.push_back(item);
return true;
}
/**
* Finds the closest rectangle to given entry begin_index on a caardinal
* direction from it.
* if no entries are found, -1 is returned
*/
MenuItem* MenuFreeform::_find_item_by_direction(const MenuItem* start,
MenuObject::Direction dir)
{
if (start == nullptr)
return nullptr;
coord_def aabb_start(0,0);
coord_def aabb_end(0,0);
// construct the aabb
switch (dir)
{
case UP:
if (start->get_link_up())
return start->get_link_up();
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = 0; // top of screen
aabb_end.y = start->get_min_coord().y;
break;
case DOWN:
if (start->get_link_down())
return start->get_link_down();
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = start->get_max_coord().y;
// we choose an arbitrarily large number here, because
// tiles saves entry coordinates in pixels, yet console saves them
// in characters
// basically, we want the AABB to be large enough to extend to the
// bottom of the screen in every possible resolution
aabb_end.y = 32767;
break;
case LEFT:
if (start->get_link_left())
return start->get_link_left();
aabb_start.x = 0; // left of screen
aabb_end.x = start->get_min_coord().x;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
case RIGHT:
if (start->get_link_right())
return start->get_link_right();
aabb_start.x = start->get_max_coord().x;
// we again want a value that is always larger then the width of screen
aabb_end.x = 32767;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
default:
die("Bad direction given");
}
// loop through the entries
// save the currently closest to the index in a variable
MenuItem* closest = nullptr;
for (MenuItem *item : m_entries)
{
if (!item->can_be_highlighted())
{
// this is a noselect entry, skip it
continue;
}
if (!item->is_visible())
{
// this item is not visible, skip it
continue;
}
if (!_AABB_intersection(item->get_min_coord(), item->get_max_coord(),
aabb_start, aabb_end))
{
continue; // does not intersect, continue loop
}
// intersects
// check if it's closer than current
if (closest == nullptr)
closest = item;
switch (dir)
{
case UP:
if (item->get_min_coord().y > closest->get_min_coord().y)
closest = item;
break;
case DOWN:
if (item->get_min_coord().y < closest->get_min_coord().y)
closest = item;
break;
case LEFT:
if (item->get_min_coord().x > closest->get_min_coord().x)
closest = item;
break;
case RIGHT:
if (item->get_min_coord().x < closest->get_min_coord().x)
closest = item;
}
}
// TODO handle special cases here, like pressing down on the last entry
// to go the the first item in that line
return closest;
}
BoxMenuHighlighter::BoxMenuHighlighter(PrecisionMenu *parent): m_parent(parent),
m_active_item(nullptr)
{
ASSERT(parent != nullptr);
}
BoxMenuHighlighter::~BoxMenuHighlighter()
{
}
vector<MenuItem*> BoxMenuHighlighter::get_selected_items()
{
vector<MenuItem*> ret_val;
return ret_val;
}
MenuObject::InputReturnValue BoxMenuHighlighter::process_input(int /*key*/)
{
// just in case we somehow end up processing input of this item
return MenuObject::INPUT_NO_ACTION;
}
#ifdef USE_TILE_LOCAL
MenuObject::InputReturnValue BoxMenuHighlighter::handle_mouse(const wm_mouse_event &/*me*/)
{
// we have nothing interesting to do on mouse events because render()
// always checks if the active has changed
return MenuObject::INPUT_NO_ACTION;
}
#endif
void BoxMenuHighlighter::render()
{
if (!m_visible)
return;
if (!m_visible)
return;
_place_items();
#ifdef USE_TILE_LOCAL
m_line_buf.draw();
m_shape_buf.draw();
#else
if (m_active_item != nullptr)
m_active_item->render();
#endif
}
void BoxMenuHighlighter::_place_items()
{
MenuItem* tmp = m_parent->get_active_item();
if (tmp == m_active_item)
return;
#ifdef USE_TILE_LOCAL
m_line_buf.clear();
m_shape_buf.clear();
if (tmp != nullptr)
{
const VColour& c = term_colours[tmp->get_highlight_colour()];
const VColour bg_colour(c.r, c.g, c.b, 80);
const VColour line_colour(c.r, c.g, c.b, 127);
const coord_def tl = tmp->get_min_coord() + coord_def(1, 1);
const coord_def br = tmp->get_max_coord();
m_line_buf.add_square(tl.x, tl.y, br.x, br.y, line_colour);
m_shape_buf.add(tl.x, tl.y, br.x, br.y, bg_colour);
}
#else
// we had an active item before
if (m_active_item != nullptr)
{
// clear the background highlight trickery
m_active_item->set_bg_colour(m_old_bg_colour);
// redraw the old item
m_active_item->render();
}
if (tmp != nullptr)
{
m_old_bg_colour = tmp->get_bg_colour();
tmp->set_bg_colour(tmp->get_highlight_colour());
}
#endif
m_active_item = tmp;
}
|
#pragma once
#include <memory>
#include <vector>
#include <random>
using namespace std;
class Node {
//public:
private:
static mt19937 generator;
static uniform_real_distribution<> distribution;
static int get_a_height(double probability);
vector<shared_ptr<Node>> next_nodes;
int value;
public:
static void initialize_randomness();
Node(double probability);
Node(int height);
void initialize_next_nodes(int height);
int height();
void increase_height_to(int new_height);
shared_ptr<Node> get_next_node_at_index(int index);
void set_next_node_at_index(int index, shared_ptr<Node> node);
int get_value();
void set_value(int value);
};
|
Workers’ Compensation: Benefits The Employer Or Employee?
Daniel Stahl was working as a nurse for Hialeah hospital in 2003, just a few months after the state made changes to its workers’ compensation system. During one of his workdays, Stahl lifted a patient and ended up injuring his back from the movement. In October of 2005, his treating physician found he had reached his maximum medical improvement (MMI) and assigned him to a 6 percent impairment rating. At this point, he was entitled to impairment income benefits stretching 12 weeks and compensated for $5,472. He was eventually left with a permanent impairment and was restricted from lifting heavy weights—eventually ending his career. Still, it was later determined that Stahl did not meet the definition of permanent total disability (PTD) and his claim for PTD benefits was denied. He was then forced to pick up a teaching position at a nursing school.
Background Information
According to the Insurance Journal, “In his petition to the court, Stahl claims that the benefits available to him, and all injured employees since October 1, 2003 when state’s workers’ comp reforms went into effect are “inadequate and therefore cannot be the exclusive remedy for on the job injuries.” The court documents filed say the state’s workers’ comp law, as it is today violates the U.S. Constitution. The plaintiffs also argue that the Florida legislature has eliminate injured employees’ right to sue and the availability of partial disabilities benefits without providing an adequate replacement. The suit also takes issue with the addition of a copay for medical visits after a claimant reaches their MMI.”[1]
As such, the petitioners help to argue what many worker’s comp advocacy groups have been stressing since the implementation of changes. To advocates, Florida’s lawmakers have disregarded worker’s rights in several instances, including retracting the right to withdraw from the system in 1970, reducing the temporary disability benefits limit to 104 weeks in 1993 and approving the 2003 amendment removing benefits for partial disability. Before such measures, temporary total disability benefits were limited to 350 weeks, while temporary permanent disability benefits were not to exceed five years [2].
Having to play into the worker’s comp system means that employees must give up their right to sue their employers for negligently inflicted injures in exchange for all over coverage. While this is the essence of workers’ comp–American workers used to rely on that compact in exchange for if/when they were to be injured on the job, their employers would pay for their medical bills and enough of their wages to help them get by while they recovered. Where other states allow the employees to opt out, in Florida, employees are getting the raw end of the deal; they have no choice but to suffer through the possibility of being denied coverage. As proof of this denial, ProPublica described in their article that they found, “Florida has cut benefits to its most severely disabled workers by 65 percent since 1994.”
They also found that, “Many states have not only shrunk the payments to injured workers, they’ve also cut them off after an arbitrary time limit—even if workers haven’t recovered.” What makes all of this worse is that there has been no federal government involvement after they stopped monitoring state workers’ comp laws more than a decade ago.
How does Florida’s Workers’ Comp Work Against You
In several ways, the laws that govern Florida’s workers’ compensation process works against the employee, rather than the employer or insurance company.
• The law limits the amount of times you can receive worker’s comp payments. As described in the situation with Stahl, the system is built to get people back to work as soon as possible, sometimes overlooking proper treatment in favor of paying out lower amounts. As such, once doctors release you back to work, the insurance company does not have to keep issuing workers’ comp reimbursements to the injured employee, forcing an employee to go back to work, even when they aren’t 100% recovered.
• The insurance company picks the doctor. Knowing that the doctor’s diagnosis is critical to the amount of benefits you receive, insurance companies vet out doctors that end up restricting benefits by giving the insurance company a diagnoses that allows them to deny coverage. The process of going to the doctor is to prove that you have suffered a work-related injury and to recommend a treatment plan, but if the doctor is employer-friendly, they may not offer up the best solution; they would rather offer up the option with minimal impact for insurance companies to pay out. By doing so, they may gloss over an underlying problem so that you get back to work before you really should.
• There is no protection of your job. As the last two issues have stated how the program ensures that some employees will go back to work without fully being recovered, another issue is that there is no guarantee that your job is still there. Employers do not have to hold open the job for you for when you are able to return to work.
• It’s challenging to validate disability. The insurance company is concerned with limiting liability and payouts to inured employees. To achieve those objectives, they will often deny benefits if the injured employee is able to perform any other job. That means that if you are injured to the point where you cannot perform your usual job, but there is another job you can perform, you could be denied benefits. Even if this job pays substantially less than your previous job, it doesn’t matter. As long as you are working, the insurance company does not have to fill the gap [3].
Dolman Law Group
Laws also make it tough for workers’ compensation attorneys to get paid. Lawyers are not paid directly by the clients they represent; rather they are paid either by the employer through a payout from the insurance company or directly by the insurance company. Other times, attorneys aren’t paid until the case is settled, which could take a long time. These restrictive and employer-friendly laws and policies make it even more imperative to consult an experienced workers’ compensation attorney in Clearwater.
If you or a love one has sustained an injury while working, it is important to speak with a workers’ compensation attorney to discuss your rights and legal remedies. The worker’s compensation carrier may provide some reason for denying your benefits that sounds legitimate or follow along with the discrepancies mentioned in this post. It’s often a difficult and challenging time, thus, it is crucial to get the proper representation. This is our job. The attorneys at Dolman Law Group have extensive experience in handling workers’ comp benefits and insurance carriers/ employers. Let us help you get what you deserve today. Contact us at (727) 853-6275 for a free consultation.
Dolman Law Group
5435 Main Street
New Port Richey, FL 34652
(727) 853-6275
|
/**
* @file TestReadGroupsExtension.cpp
* @brief Unit tests of writing GroupsExtension
* @author Akiya Jouraku
*
* $Id: $
* $HeadURL: $
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2009-2011 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ---------------------------------------------------------------------- -->*/
#include <limits>
#include <iostream>
#include <check.h>
#include <sbml/SBMLTypes.h>
#include <sbml/common/extern.h>
#include <sbml/extension/SBMLExtensionRegistry.h>
#include <sbml/packages/groups/common/GroupsExtensionTypes.h>
#include <string>
/** @cond doxygenIgnored */
using namespace std;
LIBSBML_CPP_NAMESPACE_USE
/** @endcond doxygenIgnored */
CK_CPPSTART
extern char *TestDataDirectory;
START_TEST (test_GroupsExtension_read_L3V1V1)
{
char *filename = safe_strcat(TestDataDirectory, "groups-example1.xml");
SBMLDocument *document = readSBMLFromFile(filename);
fail_unless(document->getPackageName() == "core");
Model *model = document->getModel();
fail_unless(model != NULL);
fail_unless(model->getPackageName() == "core");
fail_unless(document->getNumErrors() == 0);
// get the Group
GroupsModelPlugin* mplugin = static_cast<GroupsModelPlugin*>(model->getPlugin("groups"));
fail_unless(mplugin != NULL);
fail_unless(mplugin->getNumGroups() == 1);
fail_unless(mplugin->getListOfGroups()->getPackageName() == "groups");
Group* group = mplugin->getGroup(0);
fail_unless(group->getId() == "ATP");
fail_unless(group->getSBOTermID() == "SBO:0000252");
fail_unless(group->getKind() == GROUP_KIND_CLASSIFICATION);
fail_unless(group->getNumMembers() == 2);
fail_unless(group->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getPackageName() == "groups");
Member* member = group->getMember(0);
fail_unless(member->getIdRef() == "ATPc");
fail_unless(member->getPackageName() == "groups");
member = group->getMember(1);
fail_unless(member->getIdRef() == "ATPm");
fail_unless(member->getPackageName() == "groups");
delete document;
}
END_TEST
START_TEST (test_GroupsExtension_read_L3V1V1_defaultNS)
{
char *filename = safe_strcat(TestDataDirectory, "groups-example1-defaultNS.xml");
SBMLDocument *document = readSBMLFromFile(filename);
fail_unless(document->getPackageName() == "core");
Model *model = document->getModel();
document->printErrors();
fail_unless(model != NULL);
fail_unless(document->getNumErrors() == 0);
// get the Group
GroupsModelPlugin* mplugin = static_cast<GroupsModelPlugin*>(model->getPlugin("groups"));
fail_unless(mplugin != NULL);
fail_unless(mplugin->getNumGroups() == 1);
fail_unless(mplugin->getListOfGroups()->getPackageName() == "groups");
Group* group = mplugin->getGroup(0);
fail_unless(group->getId() == "ATP");
fail_unless(group->getSBOTermID() == "SBO:0000252");
fail_unless(group->getKind() == GROUP_KIND_CLASSIFICATION);
fail_unless(group->isSetKind() == true);
fail_unless(!strcmp(GroupKind_toString(group->getKind()), "classification"));
fail_unless(group->getNumMembers() == 2);
fail_unless(group->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getPackageName() == "groups");
Member* member = group->getMember(0);
fail_unless(member->getIdRef() == "ATPc");
fail_unless(member->getPackageName() == "groups");
member = group->getMember(1);
fail_unless(member->getIdRef() == "ATPm");
fail_unless(member->getPackageName() == "groups");
delete document;
}
END_TEST
START_TEST (test_GroupsExtension_read_L3V1V1_unknown_elements)
{
const char* s1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" xmlns:groups=\"http://www.sbml.org/sbml/level3/version1/groups/version1\" level=\"3\" version=\"1\" groups:required=\"false\">\n"
" <model>\n"
" <listOfCompartments>\n"
" <compartment id=\"cytosol\" constant=\"true\"/>\n"
" <compartment id=\"mitochon\" constant=\"true\"/>\n"
" </listOfCompartments>\n"
" <listOfSpecies>\n"
" <species id=\"ATPc\" compartment=\"cytosol\" initialConcentration=\"1\" hasOnlySubstanceUnits=\"false\" boundaryCondition=\"false\" constant=\"false\"/>\n"
" <species id=\"ATPm\" compartment=\"mitochon\" initialConcentration=\"2\" hasOnlySubstanceUnits=\"false\" boundaryCondition=\"false\" constant=\"false\"/>\n"
" </listOfSpecies>\n"
" <groups:listOfGroups>\n"
" <groups:group sboTerm=\"SBO:0000252\" groups:kind=\"partonomy\" groups:id=\"ATP\" groups:unknown=\"unknown\" >\n"
" <groups:listOfMembers>\n"
" <groups:member groups:idRef=\"ATPc\" groups:unknown=\"unknown\"/>\n"
" <groups:member groups:idRef=\"ATPm\"/>\n"
" </groups:listOfMembers>\n"
" <groups:unknown>\n"
" </groups:unknown>\n"
" </groups:group>\n"
" </groups:listOfGroups>\n"
" </model>\n"
"</sbml>\n"
;
SBMLDocument *document = readSBMLFromString(s1);
Model *model = document->getModel();
fail_unless(model != NULL);
fail_unless(document->getNumErrors() == 4);
delete document;
}
END_TEST
START_TEST (test_GroupsExtension_read_memberConstraints)
{
char *filename = safe_strcat(TestDataDirectory, "groups_speciestype_example.xml");
SBMLDocument *document = readSBMLFromFile(filename);
fail_unless(document->getPackageName() == "core");
Model *model = document->getModel();
fail_unless(model != NULL);
fail_unless(model->getPackageName() == "core");
fail_unless(document->getNumErrors() == 0);
// get the Group
GroupsModelPlugin* mplugin = static_cast<GroupsModelPlugin*>(model->getPlugin("groups"));
fail_unless(mplugin != NULL);
fail_unless(mplugin->getNumGroups() == 1);
fail_unless(mplugin->getListOfGroups()->getPackageName() == "groups");
Group* group = mplugin->getGroup(0);
fail_unless(group->getId() == "ATP");
fail_unless(group->getKind() == GROUP_KIND_CLASSIFICATION);
fail_unless(group->getNumMembers() == 2);
fail_unless(group->getNumMemberConstraints() == 3);
fail_unless(group->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getSBOTermID() == "SBO:0000248");
Member* member = group->getMember(0);
fail_unless(member->getIdRef() == "ATPc");
fail_unless(member->getPackageName() == "groups");
member = group->getMember(1);
fail_unless(member->getIdRef() == "ATPm");
fail_unless(member->getPackageName() == "groups");
ListOfMemberConstraints* lomcs = group->getListOfMemberConstraints();
fail_unless(lomcs->getPackageName() == "groups");
fail_unless(lomcs->isSetMembersShareType() == true);
fail_unless(lomcs->getMembersShareType() == true);
MemberConstraint* mc = group->getMemberConstraint(0);
fail_unless(mc->isSetDistinctAttribute() == true);
fail_unless(mc->isSetIdenticalAttribute() == false);
fail_unless(mc->getDistinctAttribute() == "compartment");
fail_unless(mc->getPackageName() == "groups");
mc = group->getMemberConstraint(1);
fail_unless(mc->isSetDistinctAttribute() == false);
fail_unless(mc->isSetIdenticalAttribute() == true);
fail_unless(mc->getIdenticalAttribute() == "initialConcentration");
fail_unless(mc->getPackageName() == "groups");
mc = group->getMemberConstraint(2);
fail_unless(mc->isSetDistinctAttribute() == false);
fail_unless(mc->isSetIdenticalAttribute() == true);
fail_unless(mc->getIdenticalAttribute() == "constant");
fail_unless(mc->getPackageName() == "groups");
delete document;
}
END_TEST
Suite *
create_suite_ReadGroupsExtension (void)
{
Suite *suite = suite_create("ReadGroupsExtension");
TCase *tcase = tcase_create("ReadGroupsExtension");
tcase_add_test( tcase, test_GroupsExtension_read_L3V1V1);
tcase_add_test( tcase, test_GroupsExtension_read_L3V1V1_defaultNS);
tcase_add_test( tcase, test_GroupsExtension_read_L3V1V1_unknown_elements);
tcase_add_test( tcase, test_GroupsExtension_read_memberConstraints);
suite_add_tcase(suite, tcase);
return suite;
}
CK_CPPEND
|
/**
* oakmodelview - version 0.1.0
* --------------------------------------------------------
* Copyright (C) 2017, by Mikkel Nøhr Løvgreen ([email protected])
* Report bugs and download new versions at http://oakmodelview.com/
*
* This library is distributed under the MIT License.
* See accompanying file LICENSE in the root folder.
*/
#pragma once
namespace Oak::Model {
// =============================================================================
// Class definition
// =============================================================================
class NodeSettings
{
public:
NodeSettings();
NodeSettings& operator=(const NodeSettings& copy);
bool hideVariantInstance() const;
void sethideVariantInstance(bool value);
private:
bool m_hideVariantInstance = false;
};
} // namespace Oak::Model
|
/*
* Copyright (c) 1991 Michael Landy
*
* Disclaimer: No guarantees of performance accompany this software,
* nor is any responsibility assumed on the part of the authors. All the
* software has been tested extensively and every effort has been made to
* insure its reliability.
*/
/*
* ahc3.c - 3D adaptive hierarchical coding into binary trees of binary images
*
* usage: ahc3 [-t stackrow stackcol] [-f stackdepth]
* [-d] [-s] [-v] [-g | -a > outseq] < inseq
*
* stackrow, stackcol and stackdepth determine the size of the area
* which is ahc3-encoded as a tree in the forest. All must be powers of
* 2, stackrow and stackcol must be divisors of their corresponding
* spatial dimensions. Stackdepth defaults to the largest power of 2
* divisor of the number of frames, and stackrow and stackcol default to
* the largest power of 2 which is a divisor of the number of rows and
* the number of columns, respectively.
*
* -g indicates that actual code should be generated. The full code
* is: {W,B,V,H,D}-->{10,11,00,010,011}. (If only two cuts are possible
* they are encoded by {00,01}; if one only, by {0}.) The output is in a
* special format: PFAHC3, each frame is bit-packed, with the last word
* of the tree padded with zeroes to the right. The number of output
* bytes is reported on "stderr". -a specifies that actual code be generated
* in ASCII. Only one of -g and -a may be specified. if -a is specified the
* output is not in HIPS format (there is no header). Specification of -s
* produces statistics for each frame in addition to totals. -v (verbose)
* is useful only for debugging purposes, and prints messages about the
* program's progress. -d (debug) is another debugging flag, which outputs
* the entire stored tree structure.
*
* The input must be in byte-unpacked-format with 1 bit per pixel (in other
* words, ahc3 only codes nonzero vs zero pixels). The coding
* assumptions are 2 bits per black or white node, 2 or 3 bits per meta
* symbol. Except at the lowest level where the two pixels are coded as a
* "nibble" in 1 bit. Also if an area is divided into two homogenous
* areas, the second area is coded in 1 bit (0) , since it must be of
* color different from that of the first area. (If -g is specified, the actual
* code is generated. It is left shifted and packed, with the last word of
* each tree padded with 1's to the right.) Compression statistics are
* given on "stderr". The program computes the number of input bits,
* output bits and compression ratio.
*
* to load: cc -o ahc3 ahc3.c -lhips
*
* Yoav Cohen - 4/10/83
* modified by Mike Landy - 6/21/83
* HIPS 2 - msl - 7/22/91
*/
#include <stdio.h>
#include <hipl_format.h>
static Flag_Format flagfmt[] = {
{"t",{LASTFLAG},1,{{PTINT,"-1","stackrow"},{PTINT,"-1","stackcol"},
LASTPARAMETER}},
{"f",{LASTFLAG},1,{{PTINT,"-1","stackdepth"},LASTPARAMETER}},
{"s",{LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"d",{LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"v",{LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"g",{"a",LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
{"a",{"g",LASTFLAG},0,{{PTBOOLEAN,"FALSE"},LASTPARAMETER}},
LASTFLAG};
int types[] = {PFBYTE,LASTTYPE};
#define AHCNULL 0
#define B 1
#define W 2
#define V 3
#define H 4
#define D 5
byte *inpic;
struct node {
int len;
char sym;
union {
struct node *pt;
char ch;
} lch;
union {
struct node *pt;
char ch;
} rch;
};
struct node ******p;
int nnr,nnc,nnd;
char *obuf;
int bufindex,bitindex,bytesout=0;
h_boolean gsw,asw,vsw,dsw;
int nr,nc,nrc,stackrow,stackcol,stackdepth,enc2(),encode();
int outbit(),flushbuf(),acode(),asons(),aprint(),lenprint();
int main(argc,argv)
int argc;
char **argv;
{
struct header hd,hdp,hdo;
Filename filename;
FILE *fp;
h_boolean ssw;
byte *in;
struct node *****p1,****p2,***p3,**p4,*p5;
struct node *****tp1,****tp2,***tp3,**tp4,*tp5,*pt;
int f,ifr,i,j,k,l,m,n,sumlen,len,v,h,d,s,ofr,it1,it2,r,c,low;
int method;
Progname = strsave(*argv);
parseargs(argc,argv,flagfmt,&stackrow,&stackcol,&stackdepth,&ssw,
&dsw,&vsw,&gsw,&asw,FFONE,&filename);
fp = hfopenr(filename);
fread_header(fp,&hd,filename);
nr = hd.orows;
nc = hd.ocols;
f = hd.num_frame;
if (nr<=0 || nc<=0 || f<=0)
perr(HE_MSG,"input image dimensions must be greater than zero");
if (stackrow < 0) {
for (i=1;nr%(1<<i)==0;i++);
stackrow = 1 << (i-1);
}
if (stackcol < 0) {
for (i=1;nc%(1<<i)==0;i++);
stackcol = 1 << (i-1);
}
if (stackdepth < 0) {
for (i=1;f%(1<<i)==0;i++);
stackdepth = 1 << (i-1);
}
if (stackrow<1 || stackcol<1 || stackdepth<1)
perr(HE_MSG,"stack args must be >= 1");
for (nnr=0;(1<<nnr)<stackrow;nnr++);
for (nnc=0;(1<<nnc)<stackcol;nnc++);
for (nnd=0;(1<<nnd)<stackdepth;nnd++);
fprintf(stderr,"%s: stacksize is %d x %d x %d\n",Progname,stackrow,
stackcol,stackdepth);
if ((1<<nnr)!=stackrow || (1<<nnc)!=stackcol || (1<<nnd)!=stackdepth)
perr(HE_MSG,"stack dimensions must be powers of 2");
if ((nr % stackrow) != 0 || (nc % stackcol) != 0)
perr(HE_MSG,
"stack sizes must divide the number of rows and columns");
if (f < stackdepth)
perr(HE_MSG,"stackdepth is too large");
if (nnr==0 && nnc==0 && nnd==0)
perr(HE_MSG,"stack size must be bigger than 1 x 1 x 1");
nrc = nr*nc;
ofr = f - (f%stackdepth);
if (ofr!=f)
fprintf(stderr,"%s: only %d frames are encoded\n",Progname,ofr);
/* alloc several frames (stackdepth, to be precise) */
setsize(&hd,nr*stackdepth,nc);
alloc_image(&hd);
method = fset_conversion(&hd,&hdp,types,filename);
if (hdp.numcolor > 1 && stackdepth > 1)
perr(HE_MSG,"can't handle color images with stackdepth > 1");
if (hdp.numcolor > 1)
f = ofr = hdp.num_frame;
inpic = hdp.image;
if (gsw)
obuf=(char *)halloc(512,sizeof(char));
p = (struct node ******) halloc(nnr+1,sizeof(struct node *****));
p1 = (struct node *****)
halloc((nnr+1)*(nnc+1),sizeof(struct node ****));
p2 = (struct node ****)
halloc((nnr+1)*(nnc+1)*(nnd+1),sizeof(struct node ***));
p3 = (struct node ***)
halloc(((nnc+1)*(nnd+1)*((1<<(nnr+1))-1)) - (1<<nnr),
sizeof(struct node **));
p4 = (struct node **)
halloc(((nnd+1)*((1<<(nnr+1))-1)*((1<<(nnc+1))-1)) -
((1<<nnr)*(1<<nnc)),
sizeof(struct node *));
p5 = (struct node *)
halloc((((1<<(nnr+1))-1)*((1<<(nnc+1))-1)*((1<<(nnd+1))-1)) -
((1<<nnr)*(1<<nnc)*(1<<nnd)),
sizeof(struct node));
/* internal allocation */
tp1=p1; tp2=p2; tp3=p3; tp4=p4; tp5=p5;
for (i=0;i<=nnr;i++) {
p[i]=tp1; tp1 += (nnc+1);
r=1<<(nnr-i);
for (j=0;j<=nnc;j++) {
p[i][j]=tp2; tp2 += (nnd+1);
c=1<<(nnc-j);
for (k=0;k<=nnd;k++) {
if (i==0 && j==0 && k==0) continue;
p[i][j][k]=tp3; tp3 += r;
s=1<<(nnd-k);
for (l=0;l<r;l++) {
p[i][j][k][l]=tp4; tp4 += c;
for (m=0;m<c;m++) {
p[i][j][k][l][m]=tp5; tp5 += s;
}
}
}
}
}
if (vsw)
fprintf(stderr,"%s: done allocation\n",Progname);
if (gsw) {
setsize(&hdp,nr,nc);
dup_headern(&hdp,&hdo);
hdo.pixel_format=PFAHC3;
hdo.num_frame=ofr;
setparam(&hdo,"stackrow",PFINT,1,stackrow);
setparam(&hdo,"stackcol",PFINT,1,stackcol);
setparam(&hdo,"stackdepth",PFINT,1,stackdepth);
write_headeru(&hdo,argc,argv);
setsize(&hdp,nr*stackdepth,nc);
}
sumlen=0;
for (ifr=0;ifr<ofr/stackdepth;ifr++) {
fread_imagec(fp,&hd,&hdp,method,ifr,filename);
in = inpic;
for (i=0;i<nrc*stackdepth;i++,in++)
*in = (*in==0) ? B : W;
if (vsw)
fprintf(stderr,"%s: done initialization\n",Progname);
for (it1=0;it1<nr/stackrow;it1++)
for (it2=0;it2<nc/stackcol;it2++) {
if (vsw)
fprintf(stderr,"%s: it1=%d, it2=%d\n",
Progname,it1,it2);
enc2(inpic+it1*nc*stackrow+it2*stackcol);
if (vsw)
fprintf(stderr,"%s: done enc2()\n",Progname);
for (m=2;m<=nnr+nnc+nnd;m++)
for (v=0;v<=nnr && v<=m;v++)
for (h=0;h<=nnc && h<=m;h++) {
d=m-v-h;
if (d<0||d>nnd)continue;
if (vsw)
fprintf(stderr,"%s: calling encode(%d,%d,%d) ",
Progname,v,h,d);
encode(v,h,d);
if (vsw)
fprintf(stderr,"...done\n");
}
len=p[nnr][nnc][nnd][0][0][0].len;
sumlen+=len;
if (ssw&&f>1)
fprintf(stderr,"%s: frame #%d, CR=%5.3f\n",Progname,
ifr,(double)len/(stackrow*stackcol*stackdepth));
if (dsw) {
for (i=0;i<=nnr;i++) {
r=1<<(nnr-i);
for (j=0;j<=nnc;j++) {
c=1<<(nnc-j);
for (k=0;k<=nnd;k++) {
if (i==0 && j==0 && k==0)
continue;
if ((i+j+k)==1)
low=1;
else
low=0;
s=1<<(nnd-k);
for (l=0;l<r;l++)
for (m=0;m<c;m++)
for (n=0;n<s;n++) {
pt= &p[i][j][k][l][m][n];
printf("%p ",(void *) pt);
printf("p[%d][%d][%d][%d][%d][%d] ",i,j,k,l,m,n);
printf("sym=%d, len=%d, ",pt->sym,pt->len);
if (!low)
printf("pointers: %p %p",pt->lch.pt,pt->rch.pt);
printf("\n");
}
}
}
}
}
if (asw||gsw)
acode(ifr);
}
}
i=ofr*nrc;
j=sumlen;
fprintf(stderr,"%s: Total Compression Ratio = %5.4f\n",Progname,
(double) sumlen/(ofr*nrc));
if (gsw)
fprintf(stderr," %d bytes written out\n",bytesout);
return(0);
}
/**************************************************************************/
int enc2(pic)
char *pic;
{
struct node *pt;
char *in1,*in2,*in11,*in22,*in111,*in222,p1,p2;
int ir,ic,il;
/* To encode the m=1 diagonal */
/* vertical pairs */
in1=pic; in2=pic+nc;
for (il=0;il<stackdepth;il++,in1+=nrc,in2+=nrc)
for (ir=0,in11=in1,in22=in2;ir<stackrow/2;
ir++,in11+=(nc+nc),in22+=(nc+nc))
for (ic=0,in111=in11,in222=in22;ic<stackcol;ic++) {
p1= *in111++; p2= *in222++;
pt= &p[1][0][0][ir][ic][il];
pt->len = 2;
if (p1==p2)
pt->sym = p1;
else {
pt->sym = H;
pt->lch.ch = p1; pt->rch.ch = p2;
}
}
/* horizontal pairs */
in1=pic; in2=pic+1;
for (il=0;il<stackdepth;il++,in1+=nrc,in2+=nrc)
for (ir=0,in11=in1,in22=in2;ir<stackrow;ir++,in11+=nc,in22+=nc)
for (ic=0,in111=in11,in222=in22;ic<stackcol/2;ic++,in111+=2,in222+=2) {
p1= *in111; p2= *in222;
pt= &p[0][1][0][ir][ic][il];
pt->len = 2;
if (p1==p2)
pt->sym = p1;
else {
pt->sym = V;
pt->lch.ch = p1; pt->rch.ch = p2;
}
}
/* pairs across layers */
in1=pic; in2=pic+nrc;
for (il=0;il<stackdepth/2;il++,in1+=(nrc+nrc),in2+=(nrc+nrc))
for (ir=0,in11=in1,in22=in2;ir<stackrow;ir++,in11+=nc,in22+=nc)
for (ic=0,in111=in11,in222=in22;ic<stackcol;ic++) {
p1= *in111++; p2= *in222++;
pt= &p[0][0][1][ir][ic][il];
pt->len = 2;
if (p1==p2)
pt->sym = p1;
else {
pt->sym = D;
pt->lch.ch = p1; pt->rch.ch = p2;
}
}
return(0);
}
int encode(v,h,d)
int v,h,d;
{
struct node *pt,*hch1,*hch2,*vch1,*vch2,*dch1,*dch2;
char hsym,vsym,dsym,hsym1,hsym2,vsym1,vsym2,dsym1,dsym2;
int ir,ic,il,hlen,vlen,dlen;
int nbits,max;
nbits=0; if (v>0) nbits++; if (h>0) nbits++; if (d>0) nbits++;
if (nbits<=0||nbits>3)
perr(HE_MSG,"error1 in encode()");
for (il=0;il<(1<<(nnd-d));il++)
for (ir=0;ir<(1<<(nnr-v));ir++)
for (ic=0;ic<(1<<(nnc-h));ic++) {
pt= &p[v][h][d][ir][ic][il];
/* is a h-cut possible ? */
if (v==0) hlen=0; /* no */
else { /* yes */
hch1 = &p[v-1][h][d][ir+ir][ic][il];
hch2 = &p[v-1][h][d][ir+ir+1][ic][il];
hsym1 = hch1->sym;
hsym2 = hch2->sym;
/* is it uniform ? */
if ((hsym1==B && hsym2==B) || (hsym1==W && hsym2==W)) {
/* yes */
hsym=hsym1;
hlen=2;
}
else { /* non-uniform */
hlen = hch1->len + hch2->len + nbits;
hsym = H;
if ((hsym1==B||hsym1==W) &&
(hsym2==B||hsym2==W))
--hlen;
}
}
/* is a v-cut possible ? */
if (h==0)
vlen=0; /* no */
else { /* yes */
vch1 = &p[v][h-1][d][ir][ic+ic][il];
vch2 = &p[v][h-1][d][ir][ic+ic+1][il];
vsym1 = vch1->sym;
vsym2 = vch2->sym;
/* is it uniform ? */
if ((vsym1==B && vsym2==B)
|| (vsym1==W && vsym2==W)) { /* yes */
vsym=vsym1;
vlen=2;
}
else { /* non-uniform */
vlen = vch1->len + vch2->len +
((nbits==3)?2:nbits);
vsym = V;
if ((vsym1==B||vsym1==W) &&
(vsym2==B||vsym2==W))
--vlen;
}
}
/* is a d-cut possible ? */
if (d==0) dlen=0; /* no */
else { /* yes */
dch1 = &p[v][h][d-1][ir][ic][il+il];
dch2 = &p[v][h][d-1][ir][ic][il+il+1];
dsym1 = dch1->sym;
dsym2 = dch2->sym;
/* is it uniform ? */
if ((dsym1==B && dsym2==B)
||(dsym1==W && dsym2==W)) { /* yes */
dsym=dsym1;
dlen=2;
}
else { /* non-uniform */
dlen = dch1->len + dch2->len + nbits;
dsym = D;
if ((dsym1==B||dsym1==W) &&
(dsym2==B||dsym2==W))
--dlen;
}
}
max=hlen; if (vlen>max)max=vlen; if (dlen>max)max=dlen; max++;
if (hlen==0)hlen=max;
if (vlen==0)vlen=max;
if (dlen==0)dlen=max;
if (hlen<= vlen && hlen<= dlen) {
pt->sym = hsym; pt->len = hlen;
if (hsym==H)
{ pt->rch.pt = hch2; pt->lch.pt = hch1; }
else
{ pt->rch.pt = AHCNULL; pt->lch.pt = AHCNULL; }
}
else if (vlen <= dlen) {
pt->sym = vsym;
pt->len = vlen;
if (vsym==V)
{ pt->rch.pt = vch2; pt->lch.pt = vch1; }
else
{ pt->rch.pt = AHCNULL; pt->lch.pt = AHCNULL; }
}
else {
pt->sym = dsym;
pt->len = dlen;
if (dsym==D)
{ pt->rch.pt = dch2; pt->lch.pt = dch1; }
else
{ pt->rch.pt = AHCNULL; pt->lch.pt = AHCNULL; }
}
}
return(0);
}
int outbit(bit)
int bit;
{
/* on entry bufindex and bitindex point to the new available location */
if (gsw) {
if (bit<0 || bit>1)
perr(HE_MSG,"error in outbit()");
obuf[bufindex] += bit;
bitindex++;
if (bitindex<8)
obuf[bufindex] = obuf[bufindex]<<1;
else {
bufindex++; bitindex=0;
if (bufindex>511) {
fwrite(obuf,512,1,stdout);
bytesout+=512; bufindex=0;
}
obuf[bufindex]=0;
}
}
return(0);
}
int flushbuf()
{
if (bufindex==0 && bitindex==0)
return(0);
if (bitindex>0) {
obuf[bufindex]=obuf[bufindex]<<(7-bitindex);
bufindex++;
}
fwrite(obuf,bufindex,1,stdout);
bytesout += (bufindex);
return(0);
}
int acode(frame)
int frame;
{
struct node *pt;
char sym;
if (gsw)
{bufindex=bitindex=0;obuf[0]=0;}
else
printf("\n\nAHC: Code for batch # %d\n\n",frame);
pt = &p[nnr][nnc][nnd][0][0][0];
sym=pt->sym;
switch(sym) {
case W: aprint(0,'W','2');outbit(1);outbit(0);
break;
case B: aprint(0,'B','2');outbit(1);outbit(1);
break;
case V: if (nnr==0&&nnd==0)
{ aprint(0,'V','1');outbit(0); }
else { aprint(0,'V','2');outbit(0);outbit(0); }
break;
case H: if (nnc==0&&nnd==0)
{ aprint(0,'H','1');outbit(0); }
else if (nnd==0)
{ aprint(0,'H','2');outbit(0);outbit(1); }
else if (nnc==0)
{ aprint(0,'H','2');outbit(0);outbit(0); }
else { aprint(0,'H','3');outbit(0);outbit(1);outbit(0); }
break;
case D: if (nnr==0&&nnc==0)
{ aprint(0,'D','1');outbit(0); }
else if (nnr==0||nnc==0)
{ aprint(0,'D','2');outbit(0);outbit(1); }
else { aprint(0,'D','3');outbit(0);outbit(1);outbit(1); }
break;
default: perr(HE_MSG,"error in acode()");
}
lenprint(pt->len);
if (sym==H||sym==V||sym==D)
asons(pt,nnc,nnr,nnd,0);
if (gsw)
flushbuf();
else
putchar('\n');
return(0);
}
int asons(pt,h,v,d,level)
struct node *pt;
int h,v,d,level;
{
char sym,sym1,sym2;
int level1,hh,vv,dd;
sym=pt->sym;
if (sym==W||sym==B)
perr(HE_MSG,"error 0 in asons()");
level1=level+1;
/* sons are single pixels: */
if (h+v+d==1) {
if (pt->lch.ch==W)
{ aprint(level1,'W','1');outbit(0); }
else
{ aprint(level1,'B','1');outbit(1); }
return(0);
}
/* other cases */
hh=h;vv=v;dd=d;
if (sym==D)
dd--;
else if (sym==H)
vv--;
else if (sym==V)
hh--;
sym1=pt->lch.pt->sym; sym2=pt->rch.pt->sym;
switch(sym1) {
case W: aprint(level1,'W','2');outbit(1);outbit(0);
lenprint(pt->lch.pt->len);
break;
case B: aprint(level1,'B','2');outbit(1);outbit(1);
lenprint(pt->lch.pt->len);
break;
case V: if (vv==0&&dd==0)
{ aprint(level1,'V','1');outbit(0); }
else { aprint(level1,'V','2');outbit(0);outbit(0); }
lenprint(pt->lch.pt->len);
asons(pt->lch.pt,hh,vv,dd,level1);
break;
case H: if (hh==0&&dd==0)
{ aprint(level1,'H','1');outbit(0); }
else if (dd==0)
{ aprint(level1,'H','2');outbit(0);outbit(1); }
else if (hh==0)
{ aprint(level1,'H','2');outbit(0);outbit(0); }
else { aprint(level1,'H','3');outbit(0);outbit(1);outbit(0); }
lenprint(pt->lch.pt->len);
asons(pt->lch.pt,hh,vv,dd,level1);
break;
case D: if (vv==0&&hh==0)
{ aprint(level1,'D','1');outbit(0); }
else if (vv==0||hh==0)
{ aprint(level1,'D','2');outbit(0);outbit(1); }
else { aprint(level1,'D','3');outbit(0);outbit(1);outbit(1); }
lenprint(pt->lch.pt->len);
asons(pt->lch.pt,hh,vv,dd,level1);
break;
default: fprintf(stderr,"%s: funny character: %d-%c-\n",
Progname,(unsigned int)sym1,sym1);
perr(HE_MSG,"error 1 in asons");
}
switch(sym2) {
case W: if (sym1==B || sym1==W)
{aprint(level1,'U','1');outbit(1);
(pt->rch.pt->len)--;}
else
{aprint(level1,'W','2');outbit(1);outbit(0);}
lenprint(pt->rch.pt->len);
break;
case B: if (sym1==B || sym1==W)
{aprint(level1,'U','1');outbit(1);
(pt->rch.pt->len)--;}
else
{aprint(level1,'B','2');outbit(1);outbit(1);}
lenprint(pt->rch.pt->len);
break;
case V: if (vv==0&&dd==0)
{ aprint(level1,'V','1');outbit(0); }
else { aprint(level1,'V','2');outbit(0);outbit(0); }
lenprint(pt->rch.pt->len);
asons(pt->rch.pt,hh,vv,dd,level1);
break;
case H: if (hh==0&&dd==0)
{ aprint(level1,'H','1');outbit(0); }
else if (dd==0)
{ aprint(level1,'H','2');outbit(0);outbit(1); }
else if (hh==0)
{ aprint(level1,'H','2');outbit(0);outbit(0); }
else { aprint(level1,'H','3');outbit(0);outbit(1);outbit(0); }
lenprint(pt->rch.pt->len);
asons(pt->rch.pt,hh,vv,dd,level1);
break;
case D: if (vv==0&&hh==0)
{ aprint(level1,'D','1');outbit(0); }
else if (vv==0||hh==0)
{ aprint(level1,'D','2');outbit(0);outbit(1); }
else { aprint(level1,'D','3');outbit(0);outbit(1);outbit(1); }
lenprint(pt->rch.pt->len);
asons(pt->rch.pt,hh,vv,dd,level1);
break;
default: fprintf(stderr,"%s: funny character: %d -%c-\n",
Progname,(unsigned int) sym2,sym2);
perr(HE_MSG,"error 2 in asons");
}
return(0);
}
int aprint(level,ch1,ch2)
int level;
char ch1,ch2;
{
int i;
if (asw) {
putchar('\n');
while(level-- >0) { for (i=0;i<7;i++)putchar(' ');}
putchar(ch1);putchar(ch2);
}
return(0);
}
int lenprint(len)
int len;
{
if (asw)
printf(" (%d)",len);
return(0);
}
|
Creating Windows With Ruby Tk
A GUI application may consist of the following types of objects:
• Widgets – basic GUI objects that can be put directly in the window. Most of them generate events as a response to user actions. A label is a widget, too, but, usually does not generate events.
• Shapes – lines, arcs, circles, polygons and other that belong on a canvas.
• Timers – threads that perform an action the number of times specified and sleep for the specified duration. From the definition “thread” you can understand that they run in parallel.
The simplest Ruby Tk program is:
require 'tk'
This program displays the following window:
This is the default window. It is displayed on the screen when the line ‘Tk.mainloop’ is performed. Until this window is closed, no commands that are not responses to events will be executed.
“Programing Ruby – The Pragmatic Programmers Guide” suggests that you look at Perl/Tk guides to learn how to use Tk. A good place to look for Perl’s objects and their methods is Active Perl. I’m not going to write here the complete guide to Ruby Tk, but I hope the following chapters will help you understand how it works.
To be continued.
When you write for the web, you may want to send data to another server or to a client. A common way to transfer that data is in XML format. The data will then be processed using SAX, DOM or XPath. Every language support it.
If what you want is to define a variable, an object or an array in Javascript, you can use the JSON extension. JSON is an acronym for ‘Java Script Object Notation’. In Javascript you can use it as follows:
var myObject=<?php echo json_encode($php_object); >;
Here no parsers are required.
Here’s an example of using it in PHP:
class my_class {
public $prop1;
public $prop2;
function __construct(){
$obj=new my_class();
echo json_encode($obj);
The output looks like:
In addition to encoding, a JSON string can be decoded into an object in a language other than Javascript. Thus, you can pass data in the JSON format to any program supporting JSON, and, as you can see in, most languages used today support it.
The ability to encode varibles into JSON and decode it back in any language is not the only reason why JSON can replace XML. If you go to, you can see links in the bottom referring to other sites. For example, JSONPath, that allows you to access a member just like XPath. JSONPath is available in PHP and Javascript.
|
// Final Project Milestone 1
// Date.cpp
// Date 2019-07-11
// Author DucTai Nguyen - [email protected] - 147942171
/////////////////////////////////////////////////////////////////
#include <iostream>
#include "Date.h"
using namespace std;
namespace aid {
int Date::mdays(int year, int mon) {
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31,-1};
int month = mon >= 1 && mon <= 12 ? mon : 13;
month--;
return days[month] + int((month == 1)*((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}
void Date::errCode(int err) {
this->m_err = err;
}
int Date::errCode() const{
return (this->m_err);
}
bool Date::bad() const{
return (this->m_err); // 0 will be false otherwise true
}
Date::Date() {
this->m_year = 0;
this->m_day = 0;
this->m_month = 0;
this->m_compare = 0;
this->errCode(NO_ERROR);
}
Date::Date(int year, int month, int day) {
int comp = year*372 + month * 31 + day;
if ( year < min_year || year > max_year ||
month > 12 || month < 1 ||
day < 1 || day > mdays(year, month) ||
comp < min_date ){
*this = Date();
}
else {
this->m_year = year;
this->m_day = day;
this->m_month = month;
this->m_compare = comp;
this->errCode(NO_ERROR);
}
}
istream& Date::read(istream& istr) {
int year, mon, day;
char dim = '/';
istr >> year >> dim >> mon >> dim >> day;
if(istr.fail()){
this->errCode(CIN_FAILED);
istr.ignore(2000);
}
else if (year > max_year || year < min_year) {
this->errCode(YEAR_ERROR);
}
else if (mon > 12 || mon < 1) {
this->errCode(MON_ERROR);
}
else if (day > Date::mdays(year, mon) || day < 1) {
this->errCode(DAY_ERROR);
}
else if (!Date::isValid(year, mon, day)) {
this->errCode(PAST_ERROR);
}
else {
*this = Date(year, mon, day);
}
return istr;
}
istream& operator>>(istream& is, Date& rhs) {
rhs.read(is);
return is;
}
ostream& Date::write(ostream& ostr) const{
if (this->m_compare == 0) { // empty object
ostr << "0/00/00";
}
else {
ostr << this->m_year << '/';
ostr.width(2);
ostr.fill('0');
ostr << this->m_month << '/' << this->m_day;
}
return ostr;
}
ostream& operator<<(ostream& os, const Date& rhs) {
rhs.write(os);
return os;
}
bool Date::operator!=(const Date & rhs) const{
return (this->m_compare != rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator==(const Date & rhs) const
{
return (this->m_compare == rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator<(const Date & rhs) const
{
return (this->m_compare < rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator>(const Date & rhs) const
{
return (this->m_compare > rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator<=(const Date & rhs) const
{
return (this->m_compare <= rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator>=(const Date & rhs) const
{
return (this->m_compare >= rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::isValid(int year, int mon, int day)const { //private
return (year * 372 + mon * 31 + day) > min_date;
}
}
|
Dictionary and translator for handheld
New : sensagent is now available on your handheld
A windows (pop-into) of information (full-content of Sensagent) triggered by double-clicking any word on your webpage. Give contextual explanation and translation from your sites !
With a SensagentBox, visitors to your site can access reliable information on over 5 million pages provided by Sensagent.com. Choose the design that fits your site.
Improve your site content
Add new content to your site from Sensagent by XML.
Crawl products or adds
Get XML access to reach the best products.
Index images and define metadata
Get XML access to fix the meaning of your metadata.
Please, email us to describe your idea.
Lettris is a curious tetris-clone game where all the bricks have the same square shape but different content. Each square carries a letter. To make squares disappear and save space for other squares you have to assemble English words (left, right, up, down) from the falling squares.
Boggle gives you 3 minutes to find as many words (3 letters or more) as you can in a grid of 16 letters. You can also try the grid of 16 letters. Letters must be adjacent and longer words score better. See if you can get into the grid Hall of Fame !
Change the target language to find translations.
Tips: browse the semantic fields (see From ideas to words) in two languages to learn more.
1.the language of educated people in ancient Rome"Latin is a language as dead as dead can be. It killed the ancient Romans--and now it's killing me"
classical Latin (n.)
Latin inscription in the Colosseum
|Spoken in||Roman republic, Roman empire|
|Region||mare nostrum (Mediterranean)|
|Era||75 BC to the 3rd century AD, when it developed into Late Latin|
|Writing system||Latin alphabet|
|Official language in||Roman republic, Roman empire|
|Regulated by||Schools of grammar and rhetoric|
The range of Latin, 60 AD
Classical Latin in simplest terms is the socio-linguistic register of the Latin language regarded by the enfranchised and empowered populations of the late Roman republic and the Roman empire as good Latin. Most writers during this time made use of it. Any unabridged Latin dictionary informs moderns that Marcus Tullius Cicero and his contemporaries of the late republic while using lingua Latina and sermo Latinus to mean the Latin language as opposed to the Greek or other languages, and sermo vulgaris or sermo vulgi to refer to the vernacular of the uneducated masses, regarded the speech they valued most and in which they wrote as Latinitas, "Latinity", with the implication of good. Sometimes it is called sermo familiaris, "speech of the good families", sermo urbanus, "speech of the city" or rarely sermo nobilis, "noble speech", but mainly besides Latinitas it was Latine (adverb), "in good Latin", or Latinius (comparative degree of adjective), "good Latin."
Latinitas was spoken as well as written. Moreover, it was the language taught by the schools. Prescriptive rules therefore applied to it, and where a special subject was concerned, such as poetry or rhetoric, additional rules applied as well. Now that the spoken Latinitas has become extinct (in favor of various other registers later in date) the rules of the, for the most part, polished (politus) texts may give the appearance of an artificial language, but Latinitas was a form of sermo, or spoken language and as such retains a spontaneity. No authors are noted for the type of rigidity evidenced by stylized art, except possibly the repetitious abbreviations and stock phrases of inscriptions.
Good Latin in philology is "classical" Latin literature. The term refers to the canonicity of works of literature written in Latin in the late Roman republic and the early to middle Roman empire: "that is to say, that of belonging to an exclusive group of authors (or works) that were considered to be emblematic of a certain genre." The term classicus (masculine plural classici) was devised by the Romans themselves to translate Greek ἐγκριθέντες (egkrithentes), "select", referring to authors who wrote in Greek that were considered model. Before then, classis, in addition to being a naval fleet, was a social class in one of the diachronic divisions of Roman society according to property ownership by the Roman constitution. The word is a transliteration of Greek κλῆσις (klēsis) "calling", used to rank army draftees by property from first to fifth class.
Classicus is anything primae classis, "first class", such as the authors of the polished works of Latinitas, or sermo urbanus. It had nuances of the certified and the authentic: testis classicus, "reliable witness." It was in this sense that Marcus Cornelius Fronto (an African-Roman lawyer and language teacher) in the 2nd century AD used scriptores classici, "first-class" or "reliable authors" whose works could be relied upon as model of good Latin. This is the first known reference, possibly innovated at this time, to classical applied to authors by virtue of the authentic language of their works.
In imitation of the Greek grammarians, the Roman ones, such as Quintilian, drew up lists termed indices or ordines on the model of the Greek lists, termed pinakes, considered classical: the recepti scriptores, "select writers." Aulus Gellius includes many authors, such as Plautus, who are currently considered writers of Old Latin and not strictly in the period of classical Latin. The classical Romans distinguished Old Latin as prisca Latinitas and not sermo vulgaris. Each author (and work) in the Roman lists was considered equivalent to one in the Greek; for example Ennius was the Latin Homer, the Aeneid was a new Iliad, and so on. The lists of classical authors were as far as the Roman grammarians went in developing a philology. The topic remained at that point while interest in the classici scriptores declined in the medieval period as the best Latin yielded to medieval Latin, somewhat less than the best by classical standards.
The Renaissance brought a revival of interest in restoring as much of Roman culture as could be restored and with it the return of the concept of classic, "the best." Thomas Sebillet in 1548 (Art Poétique) referred to "les bons et classiques poètes françois", meaning Jean de Meun and Alain Chartier, which was the first modern application of the word. According to Merriam Webster's Collegiate Dictionary, the term classical, from classicus, entered modern English in 1599, some 50 years after its re-introduction on the continent. Governor William Bradford in 1648 referred to synods of a separatist church as "classical meetings" in his Dialogue, a report of a meeting between New-England-born "young men" and "ancient men" from Holland and England. In 1715 Laurence Echard's Classical Geographical Dictionary was published. In 1736 Robert Ainsworth's Thesaurus Linguae Latinae Compendarius turned English words and expressions into "proper and classical Latin." In 1768 David Ruhnken (Critical History of the Greek Orators) recast the mold of the view of the classical by applying the word canon to the pinakes of orators, after the Biblical canon or list of authentic books of the Bible. Ruhnken had a kind of secular catechism in mind.
In 1870 Wilhelm Sigismund Teuffel in Geschichte der Römischen Literatur (A History of Roman Literature) innovated the definitive philological classification of classical Latin based on the metaphoric uses of the ancient myth of the Ages of Man, a practice then universally current: a Golden Age and a Silver Age of classical Latin were to be presumed. The practice and Teuffel's classification, with modifications, are still in use. His work was translated into English as soon as published in German by Wilhelm Wagner, who corresponded with Teuffel. Wagner published the English translation in 1873. Teuffel divides the chronology of classical Latin authors into several periods according to political events, rather than by style. Regarding the style of the literary Latin of those periods he had but few comments.
Teuffel was to go on with other editions of his history, but meanwhile it had come out in English almost as soon as it did in German and found immediate favorable reception. In 1877 Charles Thomas Cruttwell produced the first English work along the same lines. In his Preface he refers to "Teuffel's admirable history, without which many chapters in the present work could not have attained completeness" and also gives credit to Wagner.
Cruttwell adopts the same periods with minor differences; however, where Teuffel's work is mainly historical, Cruttwell's work contains detailed analyses of style. Nevertheless like Teuffel he encounters the same problem of trying to summarize the voluminous detail in a way that captures in brief the gist of a few phases of writing styles. Like Teuffel, he has trouble finding a name for the first of the three periods (the current Old Latin phase), calling it mainly "from Livius to Sulla." The language, he says, is "…marked by immaturity of art and language, by a vigorous but ill-disciplined imitation of Greek poetical models, and in prose by a dry sententiousness of style, gradually giving way to a clear and fluent strength…" These abstracts have little meaning to those not well-versed in Latin literature. In fact, Cruttwell admits "The ancients, indeed, saw a difference between Ennius, Pacuvius, and Accius, but it may be questioned whether the advance would be perceptible by us."
Some of Cruttwell's ideas have become stock in Latin philology for better or for worse. While praising the application of rules to classical Latin, most intensely in the Golden Age, he says "In gaining accuracy, however, classical Latin suffered a grievous loss. It became cultivated as distinct from a natural language… Spontaneity, therefore, became impossible and soon invention also ceased… In a certain sense, therefore, Latin was studied as a dead language, while it was still a living." These views are certainly debatable; one might ask how the upper classes of late 16th century Britain, who shared the Renaissance zealousness for the classics, managed to speak spontaneous Latin to each other officially and unofficially after being taught classical Latin by tutors hired for the purpose. Latinitas in the Golden Age was in fact sermo familiaris, the spoken Latin of the Roman upper classes, who sent their children to school to learn it. The debate continues.
A second problem is the appropriateness of Teuffel's scheme to the concept of classical Latin, which Teuffel does not discuss. Cruttwell addresses the problem, however, altering the concept of the classical. As the best Latin is defined as golden Latin, the second of the three periods, the other two periods considered classical are left hanging. While on the one hand assigning to Old Latin the term pre-classical and by implication the term post-classical (or post-Augustan) to silver Latin Cruttwell realizes that this construct is not according to ancient usage and asserts "…the epithet classical is by many restricted to the authors who wrote in it [golden Latin]. It is best, however, not to narrow unnecessarily the sphere of classicity; to exclude Terence on the one hand or Tacitus and Pliny on the other, would savour of artificial restriction rather than that of a natural classification." (This from a scholar who had just been complaining that golden Latin was not a natural language.) The contradiction remains; Terence is and is not a classical author depending on context.
After defining a "First Period" of inscriptional Latin and the literature of the earliest known authors and fragments, to which he assigns no definitive name (he does use the term "Old Roman" at one point), Teuffel presents "the second period", his major, "das goldene Zeitalter der römischen Literatur", the Golden Age of Roman Literature, dated 671 – 767 AUC or 83 BC – 14 AD according to his time reckoning, between the dictatorship of Lucius Cornelius Sulla and the death of the emperor Augustus. Of it Wagner translating Teuffel writes
The golden age of the Roman literature is that period in which the climax was reached in the perfection of form, and in most respects also in the methodical treatment of the subject-matters. It may be subdivided between the generations, in the first of which (the Ciceronian Age) prose culminated, while poetry was principally developed in the Augustan Age.
The Ciceronian Age was dated 671–711 AUC (83 BC – 43 BC), ending just after the assassination of Gaius Julius Caesar, and the Augustan 711–67 AUC (43 BC – 14 AD), ending with the death of Augustus. The Ciceronian Age is further divided by the consulship of Cicero in 691 AUC or 63 BC into a first and second half. Authors are assigned to these periods by years of principal achievements.
The Golden Age had already made an appearance in German philology but in a less systematic way. In Bielfeld's 1770 Elements of universal erudition the author says (in translation): "The Second Age of Latin began about the time of Caesar [his ages are different from Teuffel's], and ended with Tiberius. This is what is called the Augustan Age, which was perhaps of all others the most brilliant, a period at which it should seem as if the greatest men, and the immortal authors, had met together upon the earth, in order to write the Latin language in its utmost purity and perfection." and of Tacitus "…his conceits and sententious style is not that of the golden age…". Teuffel evidently received the ideas of a golden and silver Latin from an existing tradition and embedded them in a new system, transforming them as he thought best.
In Cruttwell's introduction, the Golden Age is dated 80 BC – 14 AD ("from Cicero to Ovid"), which is about the same as Teuffel's. Of this "Second Period" Cruttwell says that it "represents the highest excellence in prose and poetry," paraphrasing Teuffel. The Ciceronian Age is now "the Republican Period" and is dated 80–42 BC through the Battle of Philippi. Later in the book Cruttwell omits Teuffel's first half of the Ciceronian and starts the Golden Age at Cicero's consulship of 63 BC, an error perpetuated into Cruttwell's second edition as well. He must mean 80 BC as he includes Varro in Golden Latin. Teuffel's Augustan Age is Cruttwell's Augustan Epoch, 42 BC – 14 AD.
The literary histories list all authors canonical to the Ciceronian Age even though their works may be fragmentary or may not have survived at all. With the exception of a few major writers, such as Cicero, Caesar, Lucretius and Catullus, ancient accounts of Republican literature are glowing accounts of jurists and orators who wrote prolifically but who now can't be read because their works have been lost, or analyses of language and style that appear insightful but can't be verified because there are no surviving instances. In that sense the pages of literary history are peopled with shadows: Aquilius Gallus, Quintus Hortensius Hortalus, Lucius Licinius Lucullus and many others who left a reputation but no readable works; they are to be presumed in the Golden Age by their associations. A list of some canonical authors of the period, whose works have survived in whole or in part (typically in part, some only short fragments) is as follows:
The Golden Age is divided by the assassination of Julius Caesar. In the wars that followed the Republican generation of literary men was lost, as most of them had taken the losing side; Marcus Tullius Cicero was beheaded in the street as he enquired from his litter what the disturbance was. They were replaced by a new generation that had grown up and been educated under the old and were now to make their mark under the watchful eye of the new emperor. As the demand for great orators was more or less over, the talent shifted emphasis to poetry. Other than the historian Livy, the most remarkable writers of the period were the poets Vergil, Horace, and Ovid. Although Augustus evidenced some toleration to republican sympathizers, he exiled Ovid, and imperial tolerance ended with the continuance of the Julio-Claudian Dynasty.
Augustan writers include:
In his second volume, on the Imperial Period, Teuffel initiated a slight alteration in approach, making it clearer that his terms applied to the Latin and not just to the age, and also changing his dating scheme from years AUC to modern. Although he introduces das silberne Zeitalter der römischen Literatur, "the Silver Age of Roman Literature", 14–117 AD, from the death of Augustus to the death of Trajan, he also mentions regarding a section of a work by Seneca the Elder a wenig Einfluss der silbernen Latinität, a "slight influence of silver Latin." It is clear that he had shifted in thought from golden and silver ages to golden and silver Latin, and not just Latin, but Latinitas, which must at this point be interpreted as classical Latin. He may have been influenced in that regard by one of his sources, E. Opitz, who in 1852 had published a title specimen lexilogiae argenteae latinitatis, mentioning silver Latinity. Although Teuffel's First Period was equivalent to Old Latin and his Second Period was equal to the Golden Age, his Third Period, die römische Kaiserheit, encompasses both the Silver Age and the centuries now termed Late Latin, in which the forms seemed to break loose from their foundation and float freely; that is, literary men appeared uncertain as to what "good Latin" should mean. The last of the Classical Latin is the Silver Latin. The Silver Age is the first of the Imperial Period and is divided into die Zeit der julischen Dynastie, 14–68; die Zeit der flavischen Dynastie, 69–96; and die Zeit des Nerva und Trajan, 96–117. Subsequently Teuffel goes over to a century scheme: 2nd, 3rd, etc., through 6th. His later editions (which came out in the rest of the late 19th century) divide the Imperial Age into parts: the 1st century (Silver Age), the 2nd century: Hadrian and the Antonines and the 3rd through the 6th Centuries. Of the Silver Age proper, pointing out that anything like freedom of speech had vanished with Tiberius, Teuffel says
…the continual apprehension in which men lived caused a restless versatility… Simple or natural composition was considered insipid; the aim of language was to be brilliant… Hence it was dressed up with abundant tinsel of epigrams, rhetorical figures and poetical terms… Mannerism supplanted style, and bombastic pathos took the place of quiet power.
The content of new literary works was continually proscribed by the emperor (by executing or exiling the author), who also played the role of literary man (typically badly). The talent therefore went into a repertory of new and dazzling mannerisms, which Teuffel calls "utter unreality." Crutwell picks up this theme:
The foremost of these [characteristics] is unreality, arising from the extinction of freedom… Hence arose a declamatory tone, which strove by frigid and almost hyterical exaggeration to make up for the healthy stimulus afforded by daily contact with affairs. The vein of artificial rhetoric, antithesis and epigram… owes its origin to this forced contentment with an uncongenial sphere. With the decay of freedom, taste sank…
In Crutwell's view (which had not been expressed by Teuffel), Silver Latin was a "rank, weed-grown garden", a "decline." Cruttwell had already decried what he saw as a loss of spontaneity in Golden Latin. That Teuffel should regard the Silver Age as a loss of natural language and therefore of spontaneity, implying that the Golden Age had it, is passed without comment. Instead, Tiberius brought about a "sudden collapse of letters." The idea of a decline had been dominant in English society since Edward Gibbon's Decline and Fall of the Roman Empire. Once again, Cruttwell evidences some unease with his stock pronouncements: "The Natural History of Pliny shows how much remained to be done in fields of great interest." The idea of Pliny as a model is not consistent with any sort of decline; moreover, Pliny did his best work under emperors at least as tolerant as Augustus had been. To include some of the best writings of the Silver Age, Cruttwell found he had to extend the period through the death of Marcus Aurelius, 180 AD. The philosophic prose of that good emperor was in no way compatible with either Teuffel's view of unnatural language or Cruttwell's depiction of a decline. Having created these constructs, the two philologists found they could not entirely justify them; apparently, in the worst implications of their views, there was no classical Latin by the ancient definition at all and some of the very best writing of any period in world history was a stilted and degenerate unnatural language.
Writers of the Silver Age include the following.
Of the additional century granted by Cruttwell and others of his point of view to Silver Latin but not by Teuffel the latter says "The second century was a happy period for the Roman State, the happiest indeed during the whole Empire… But in the world of letters the lassitude and enervation, which told of Rome's decline, became unmistakeable… its forte is in imitation." Teuffel, however, excepts the jurists; others find other "exceptions," recasting Teuffels's view.
The style of language refers to repeatable features of speech that are somewhat less general than the fundamental characteristics of the language. The latter give it a unity allowing it to be referenced under a single name. Thus Old Latin, Classical Latin, Vulgar Latin, etc., are not considered different languages, but are all referenced under the name of Latin. This is an ancient practice continued by moderns rather than a philological innovation of recent times. That Latin had case endings is a fundamental feature of the language. Whether a given form of speech prefers to use prepositions such as ad, ex, de for "to", "from" and "of" rather than simple case endings is a matter of style. Latin has a large number of styles. Each and every author has a style, which typically allows his prose or poetry to be identified by experienced Latinists. The problem of comparative literature has been to group styles finding similarities by period, in which case one may speak of Old Latin, Silver Latin, Late Latin as styles or a phase of styles.
The ancient authors themselves first defined style by recognizing different kinds of sermo, or "speech." In making the value judgement that classical Latin was "first class" and that it was better to write with Latinitas they were themselves selecting the literary and upper-class language of the city as a standard style and all sermo that differed from it was a different style; thus in rhetoric Cicero was able to define sublime, intermediate and low styles (within classical Latin) and St. Augustine to recommend the low style for sermons (from sermo). Style therefore is to be defined by differences in speech from a standard. Teuffel defined that standard as Golden Latin.
|
Loading presentation...
Present Remotely
Send the link below via email or IM
Present to your audience
Start remote presentation
• Invited audience members will follow you as you navigate and present
• People invited to a presentation do not need a Prezi account
• This link expires 10 minutes after you close the presentation
• A maximum of 30 users can follow your presentation
• Learn more about this feature in our knowledge base article
Do you really want to delete this prezi?
Make your likes visible on Facebook?
You can change this under Settings & Account at any time.
No, thanks
Chapters 13, 14, 15, and 17
No description
Juliet Morales
on 18 March 2014
Comments (0)
Please log in to add your comment.
Report abuse
Transcript of Chapters 13, 14, 15, and 17
Gene Expression: From Gene to Protein
Gene Expression is a process by which a gene (DNA) is used to synthesize proteins.
- An example such as albinism is attributed to a faulty gene that codes the wrong information.
-In such cases, the gene could code the wrong protein, or even be absent.
Archibald Garrod proposed the idea that inherited diseases could be from the lack of a specific enzyme.
-Ex: Phenylketonuria
Neurospora experiment: Neurospora cells had a single gene disabled and noticed the mutant Neurospora were unable to grow on minimal medium while the non-mutants were able. Beadle and Tatum concluded that the mutants could not synthesize an important nutrient. This proved that "the function of a gene is to dictate the production of a specific enzyme."
Mutations are changes to genes.
-Point mutations change a single nucleotide pair.
-Substitution mutations replaces a nucleotide and its corresponding nucleotide with another pair
-Insertions and deletions are the addition or removal of nucleotide pairs.
These changes to genes can cause a silent mutation, missense mutation, or nonsense mutation.
-A silent mutation has no effect on the outcome trait of the gene.
-A missense mutation will have little effect on the protein since only 1 amino acid changes.
-A nonsense mutation stops translation because when the pair was changed, it was changed into a stop codon
Important Contributors
In Bacteria:
In Eukaryotes:
Regulation of Chromatin
Chapters 13, 14, 15, and 17
DNA contains the nucleotides: Adenine, Cytosine, Guanine, and Thymine
RNA is the same except that instead of Thymine, there is Uracil.
Transcription is the synthesis of RNA from an original strand of DNA.
- In DNA replication, a DNA strand is made from the original DNA (template) strand.
- Then, that DNA strand serves as a template strand to make RNA. This is done by the RNA polymerase.
- Assembles in 5' to 3' direction.
- RNA polymerase starts at the promotor and the DNA sequence transcribed into RNA is a transcription unit.
- The pre-mRNA is given a 5' cap and a Poly-A tail and is removed of all introns and left with the exons (RNA splicing). After, it is moved into the nucleus.
The resulting mRNA strand from transcription is used in the synthesis of a polypeptide in a process called translation.
- The mRNA nucleotide sequence leaves the nucleus and into the ribosomes, the sites of translation (in eukaryotes).
- In the ribosomes, the mRNA undergoes translation to produce the amino acids for the protein.
Codons are mRNA nucleotide triplets.
There are 20 different amino acids which are made from making triplets of nucleotides. There is a combination of 64 different triplets.
60 of these combinations make up the amino acids while 1 makes a start codon, signaling the start of a nucleotide sequence and the other 3 make stop codons that signals when that nucleotide sequence ends for the protein.
Amino acids are read from 5' to 3'.
tRNA is used to transfer amino acids to the polypeptide in the ribosome by pairing up its anticodon to the codon in the mRNA. tRNA is 3' to 5'
It starts at a start codon and ends at a stop codon.
The Molecular Basis of Inheritance
DNA is the genetic material
DNA is the molecule that carries the genome
long thought to be proteins
Made in double helix, with specific base pairs (A-T; G-C)
DNA replication takes many proteins
Helicase separates two parent strands
DNA pol III creates leading strand continously and the lagging strand in Okazaki fragments
Primase adds RNA primers
DNA pol I changes primers to DNA
DNA ligase connects DNA fragments
DNA Polymerase corrects any mismatched nucleotides
A Chromosome is DNA molecule tightly wound around proteins
DNA of bacteria supercoils into a dense nucleoid
DNA in eukaryotes condenses around many histones
Frederick Griffith
Derrick Chen, Francis McMahon, Juliet Morales, and Anthony Velte
Chapter 13
Chapter 14
Chapter 15
Regulation of Gene Expression
Chapter 17
Adolf Mayer rubbed sap from Tobacco Mosaic Disease infected plants with sap from healthy plants. Believed small bacteria not visible under microscope
Second attempt at experiment by Dimitri Ivanowsky by using filter to catch bacteria. Disease still produced. Still believed bacteria were cause.
Martinus Baijerinck's experiments revealed that pathogen infected within host cell.
Wendall Stanley crystallized Tobacco Mosaic Virus. How? Are they cells?
can be single- or double-stranded, RNA or DNA
protein shell enclosing genome,
may be rod-shaped, polyhedral, or more complex
subunits called capsomers
- membranes derived from previous host
phospholipids, glycoproteins, and proteins
help to infect host
other cells!
"Obligate intracellular parasites"
Lacking equipment for protein synthesis!
Need a host cell to replicate
Limit on number of host species, called host range of the virus
Identify host cells with "lock and key" fit
Viral protein encoded reprograms the cell
only replicates through lytic cycle
replicates through either cycle depending on conditions
Simplified Viruses
With DNA:
With RNA:
*viruses that use reverse transcriptase*
Fighting Viruses!
Some viruses can mutate regularly, like the flu virus!
Further research is being conducted.
variant of the virus that causes the
immune system to create antibodies against pathogen
*HIV is a retrovirus!
Works Cited:
Biology in focus. (2014). Boston, MA: Pearson Education.
The lytic and lysogenic cycles of phage lamda, a temperate phage [Image]. (n.d.). Retrieved from http://thegeneticsofvirusesandbacteria.weebly.com/diagrams.html
The lytic cycle of phage T4, a virulent phage [Image]. (n.d.). Retrieved from http://thegeneticsofvirusesandbacteria.weebly.com/diagrams.html
[Phage]. (n.d.). Retrieved from https://dbscience4.wikispaces.com/Jillian
The reproductive cycle of an enveloped RNA virus [Image]. (n.d.). Retrieved from http://thegeneticsofvirusesandbacteria.weebly.com/diagrams.html
A simplified viral reproductive cycle [Image]. (n.d.). Retrieved from http://thegeneticsofvirusesandbacteria.weebly.com/diagrams.html
Viruses [Image]. (n.d.). Retrieved from http://www.bbc.co.uk/bitesize/ks3/science/organisms_behaviour_health/disease/revision/2/
Respond to environmental changes through
Inducible Operon/
Catabolic Pathways
Reg. protein is typically active, no transcription
An inducer, typically the substance the structural proteins break down, will inactivate it
RNA polymerase is no longer blocked
Repressible Operon/
Anabolic Pathways
Reg. protein is typically inactive, transcription occurs
An corepressor, typically the substance the structural proteins synthesizes, will activate it
RNA polymerase is now blocked
Structure & Function:
promoter for synthesizing regulatory protein for gene
regulatory gene codes for reg. protein that controls operon
itself consists of:
for operon (including
) and
structural genes
promoter for binding RNA polymerase for transcription of structural genes
operator will stop transcription if reg. gene is bound to it (site of inhibition)
structural genes code for various proteins/enzymes to perform certain metabolic processes
Two types....
Funny thing about the lac operon...
Positive gene regulation also plays a role.
Because lactose isn't the cells first choice as an energy source (glucose is),
in presence of lactose and glucose, some lac operon is synthesized
in presence of lactose and absence of glucose, lots of lac operon is synthesized
Histone Acetylation - promotes transcription by opening chromatin
DNA methylation - reduces transcription
- epigenetics (licking rat pups!)
RNA Processing
miRNA / siRNA
mRNA Degradation:
if bases complimentary, mRNA is degraded
if bases not complimentary, translation is blocked
regulation of transcription factors
has life span before degradation
Genetic Recombination in Prokaryotes
uptake of foreign DNA from surroundings
through 3rd party temporarily joined
Hershey and Chase
Meselson and Stahl
Full transcript
|
/***************************************************************************
* Copyright (C) Codeplay Software Limited
* Copyright (C) 2022 Heidelberg University, Engineering Mathematics and Computing Lab (EMCL) and Computing Centre (URZ)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* For your convenience, a copy of the License has been included in this
* repository.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include "rocblas_helper.hpp"
#include "rocblas_task.hpp"
#include "oneapi/mkl/exceptions.hpp"
#include "oneapi/mkl/blas/detail/rocblas/onemkl_blas_rocblas.hpp"
namespace oneapi {
namespace mkl {
namespace blas {
namespace rocblas {
namespace column_major {
// Buffer APIs
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, float alpha, sycl::buffer<float, 1> &a, int64_t lda,
sycl::buffer<float, 1> &b, int64_t ldb, float beta, sycl::buffer<float, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, double alpha, sycl::buffer<double, 1> &a, int64_t lda,
sycl::buffer<double, 1> &b, int64_t ldb, double beta, sycl::buffer<double, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<float> alpha, sycl::buffer<std::complex<float>, 1> &a,
int64_t lda, sycl::buffer<std::complex<float>, 1> &b, int64_t ldb,
std::complex<float> beta, sycl::buffer<std::complex<float>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<double> alpha, sycl::buffer<std::complex<double>, 1> &a,
int64_t lda, sycl::buffer<std::complex<double>, 1> &b, int64_t ldb,
std::complex<double> beta, sycl::buffer<std::complex<double>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
// USM APIs
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, float alpha, const float *a, int64_t lda, const float *b,
int64_t ldb, float beta, float *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, double alpha, const double *a, int64_t lda, const double *b,
int64_t ldb, double beta, double *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<float> alpha, const std::complex<float> *a,
int64_t lda, const std::complex<float> *b, int64_t ldb, std::complex<float> beta,
std::complex<float> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<double> alpha, const std::complex<double> *a,
int64_t lda, const std::complex<double> *b, int64_t ldb,
std::complex<double> beta, std::complex<double> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
} // namespace column_major
namespace row_major {
// Buffer APIs
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, float alpha, sycl::buffer<float, 1> &a, int64_t lda,
sycl::buffer<float, 1> &b, int64_t ldb, float beta, sycl::buffer<float, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, double alpha, sycl::buffer<double, 1> &a, int64_t lda,
sycl::buffer<double, 1> &b, int64_t ldb, double beta, sycl::buffer<double, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<float> alpha, sycl::buffer<std::complex<float>, 1> &a,
int64_t lda, sycl::buffer<std::complex<float>, 1> &b, int64_t ldb,
std::complex<float> beta, sycl::buffer<std::complex<float>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<double> alpha, sycl::buffer<std::complex<double>, 1> &a,
int64_t lda, sycl::buffer<std::complex<double>, 1> &b, int64_t ldb,
std::complex<double> beta, sycl::buffer<std::complex<double>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
// USM APIs
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, float alpha, const float *a, int64_t lda, const float *b,
int64_t ldb, float beta, float *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, double alpha, const double *a, int64_t lda, const double *b,
int64_t ldb, double beta, double *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<float> alpha, const std::complex<float> *a,
int64_t lda, const std::complex<float> *b, int64_t ldb, std::complex<float> beta,
std::complex<float> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<double> alpha, const std::complex<double> *a,
int64_t lda, const std::complex<double> *b, int64_t ldb,
std::complex<double> beta, std::complex<double> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
} // namespace row_major
} // namespace rocblas
} // namespace blas
} // namespace mkl
} // namespace oneapi
|
Saturday, December 10, 2016
A Person Who Maybe Motivated More People than Anyone Ever Had
Honestly, I can't think of anyone who had an effect on a greater number of people,
Get that part about the Ev's. Yea, Maybe no Beatles.
Hope you like it,.
1. two tunes at the same time--awesome!!
1. C-CS, PS, if you have the same stuff on the right sidebar as I do when I click that link I gave you, the top 3 at least are worth the time.
2. gave them a 'listen' and smiled the entire time -- thank you :-)
3. C-CS, So much out there. 50 years worth. What a body of work. And he was becoming an elderly man when this one was made.
2. Chet was not only a great guitar player, but a very nice man, too.
1. Adrienne, I think everyone who knew him would say even more of a person than a guitar player.
3. "I can't think of anyone who had an effect on a greater number of people,"
I can.
The calendar starts on the year of His birth.
1. Well, Geeezix Ed. I was talking mere mortals! :-)
2. Ed, PS, many would claim Chet wasn't a mere mortal, but certainly no candle to the Boy King regardless.
3. He is a joy to listen to, they have that much in common :)
4. The power of music to transform lives –– and entire cultures –– is either unknown or ignored by the majority. However, –– whether you believe it or not ––, what we surround ourselves with be it Music, Interior Decor, TV, the Internet, Movies, Stage shows, or SmartPhones, what we wear what we eat, who we date, what we talk about with our friends, what we do with our free time, etc. molds our character as individuals and shapes our destiny.
Not of us lives in a vacuum, therefore it's important for us to choose the way we occupy our time wisely. Chet certainly was a good influence on a whole generation of fellow musicians. I recognize that, even though I have to say I much prefer the profound influences great figures like Bach, Handel, Haydn, Mozart and Beethoven, et al.
Few of us realize it, but without the great classical composers, Chet Atkins and Tommy .Emmanuel could not possibly have been what they are. To a large extent all significant musicians learned from each other, built on each other's work, and stood on each other's shoulders (metaphorically) in the constant search for "new sounds" for want of a better term.
As I said at the beginning, we rarely recognize what influences us most profoundly.
Learning how to differentiate between the good, the bad and the mediocre is important, but few get that far, because our culture does not give music a high priority.
1. FT, Yes, so much is reliant on the past and present. Few of us are creative. We are inspired by those who are. They call Chet country guitar but he as nothing in common with modern country and said modern country destroyed country music.
His earliest albums have a very eclectic makeup including classical. Fingerstyle Guitar for example. 1950 something.
5. Great guy. Inspirational, talented, good, .....
1. Z, I remember being at an outing our company had in Tempe Az while we were working on an RJ Reyonlds software project. One of the guys from RJR, as we stood around a fire in the desert having a beer, asked me if I had any heroes. I hadn't really thought about it to that point but fairly quickly answered Chet Atkins. He said Good hero to have. Chet honestly was selfless. Excellence was always his goal and he was never satisfied with his performance. Hard to do better than that regardless what you're doing. He inspired millions around the world.
6. This comment has been removed by a blog administrator.
7. What an inspirational credo for all of life's endeavors. He was way more than just an excellent guitar player.
1. Yes he was Cube. He had no enemies that's for sure.
8. ~• A Visit with Pa Grouch •~
'Twas two days before Christmas
And Papa Grouch here
Made a pact with the Devil
To stay home this year.
The cupboard was bare
And the table unclad
Because of this grumpy
Self-centered old Dad,
Who'd decided it all
Was too much of a strain
That denuded his wallet
And caused him great pain.
Mama was despondent
The babe on her lap
Did nothing but howl
And spit up its pap.
The children were mopey
Their eyes sullen slits
They thought Papa'd gone mad
And had lost all his wits
When on the front lawn
There arose a great clatter
The neighbors had come
To see what was the matter
With no wreath on the door
Or lights on the eaves
They thought Papa'd grown poor
Or been looted by thieves
So up to the housetop
With garlands they climbed
Stringing green'ry and lights
Till they got all begrimed
The ladies walked in
With caskets of food
Then set up a tree
While the children they wooed
With carols in harmony
Sung at the door
With lighted red candles
That dripped on the floor.
Then in marched Tom Turkey,
Who went straight to the oven,
Saying, "Pluck me and stuff me,
I'm dyin' for lovin.'"
He made not a squawk
While they chopped off his head
Plucked out all his feathers
And stuffed him with bread
And onions and apples
And sausage and sage
And quite enough butter
To pay a week's wage.
The cranberry mold
Like a rubicund belly
Shook and shimmered itself
Like a gem made of jelly.
The scent of cinnamon
Ginger and pine
Along with the turkey
Smelled simply divine
A baker on crutches
Who only could hobble
Said, "Soon that old bird
Will be ready to gobble."
The men midst cold ashes
Placed branches for Yule
Their crackling splendor
A marvelous tool
For cheering and warming
Pa Grouch with his pain,
Who was soon moved to say,
"I've no right to complain.
"With neighbors like you,
I feel it's a shame
I ever indulged
A desire to maim
"The Spirit of Joy,
Good Will, and Good Cheer.
I promise you all
I'll be nicer –– NEXT YEAR."
Then placing his thumb
At the tip of his nose
He waved them Good Night
And to bed up he rose.
But I heard him exclaim,
As he moved past our sight,
"Don't let the door hit your butt,
When you leave. Now GOOD NIGHT!"
~ FreeThinke
Have Yourself a JOCULAR Christmas!
|
#pragma once
#include <geometry.h>
#include "../Material.h"
namespace RayTracer {
enum ShapeType {
ESphere,
EPlane
};
class Shape {
public:
const Vec3f position;
const Material material;
const ShapeType type;
Shape(const Vec3f& position, const Material& material, const ShapeType type) : position(position), material(material), type(type) {}
virtual bool RayIntersect(const Vec3f& orig, const Vec3f& dir, float& t0) = 0;
};
}
|
I will only point out two caveats:
- We cannot assume that click speakers of the African Southwest are necessarily indigenous to that region, and
- It is possible that, the greater phonemic diversity is due to ancient admixture between quite divergent peoples who possessed two different types of phonemic inventories, while most Africans inherited only the phonemic inventory of one of these peoples, which then decayed as per the author's theory away from Africa.
Science 15 April 2011:
Vol. 332 no. 6027 pp. 346-349
Phonemic Diversity Supports a Serial Founder Effect Model of Language Expansion from Africa
Quentin D. Atkinson
Human genetic and phenotypic diversity declines with distance from Africa, as predicted by a serial founder effect in which successive population bottlenecks during range expansion progressively reduce diversity, underpinning support for an African origin of modern humans. Recent work suggests that a similar founder effect may operate on human culture and language. Here I show that the number of phonemes used in a global sample of 504 languages is also clinal and fits a serial founder–effect model of expansion from an inferred origin in Africa. This result, which is not explained by more recent demographic history, local language diversity, or statistical non-independence within language families, points to parallel mechanisms shaping genetic and linguistic diversity and supports an African origin of modern human languages.
|
Need Help? Want to Talk?
24-hour on-call services
Call 609-258-3310
The students, faculty, and staff of Princeton University have traveled from all fifty states in the nation and from nations around the world to be a part of our community. Because state laws vary greatly and SHARE-related terms can mean a lot of different things to different people, we have provided the following definitions to ensure that we can speak a common language around issues of interpersonal violence and abuse.
Note: Situations need not rise to the level of a criminal act or violation to Rights, Rules, Responsibilities in order for a person to obtain services at SHARE.
Interpersonal violence and abuseThe intentional use of force or power, threatened or actual, against another person, that can result in physical or psychological harm. Interpersonal violence and abuse includes sexual harassment, sexual assault, domestic/dating violence, and stalking. (Adapted from the World Health Organization's definition)
Consent: The voluntary, informed, uncoerced agreement through words and actions freely given, which a reasonable person would interpret as a willingness to participate in mutually agreed-upon sex acts. Consent cannot be given when an individual is 1) incapacitated due to alcohol and/or drugs (lacking cognitive ability to make or act on conscious decisions); 2) unconscious; 3) mentally or physically incapacitated; or 4) underage.
Sexual Harassment: When a person making unwelcome sexual advances, requests for sexual favors, or other verbal or physical conduct of a sexual nature and/or based on one's sexual orientation or gender identity 1) threatens or rewards academics, employment or participation in any University activity or benefit based on willingness to submit to such conduct; 2) gives grades or makes personnel decisions based on willingness to submit to such conduct; 3) interferes with a person’s educational experience or living/working conditions, due to the severe and/or pervasive nature of the conduct, by creating an intimidating, hostile, or offensive environment.
Sexual Assault: This is an umbrella term that encompasses any form of unwanted or involuntary touching or penetration of intimate body parts, by a person of any gender. This includes being forced to touch someone else. "Unwanted or involuntary" sexual contact means that:
1) consent is not given, and the contact may include the use of threats, intimidation, coercion, or physical force
2) consent cannot be given because the contact is with those who are unable to give consent due to their age, physical helplessness, mental incapacitation, or incapacitation by alcohol or other drugs
Dating/Domestic Violence or Intimate Partner Violence (IPV): The actual or threatened physical, sexual, emotional, or financial abuse of an individual by someone with whom they have a current/prior intimate relationship or shared residence. These relationships may include: partner/spouse, family member, caretaker, someone with whom a child is shared, household member or roommate.
Stalking: Purposefully or knowingly engaging in a course of conduct directed at a specific person that would cause a reasonable person to fear for their safety, the safety of a third person, or suffer other emotional distress. “Course of conduct” is two or more acts of maintaining a visual or physical proximity to a person, either directly or indirectly by any action, method, device, or means.
*Confidential Resource: A resource that is not obligated to report information that is given to them. This allows the client to explore their options in a non-pressured environment in order to make informed decisions. The only exceptions to this rule are in cases that involve imminent risk of serious harm, emergent hospitalization, or a court order. While specific information may be kept confidential, these incidents may be counted for statistical purposes, as per the Clery Act.
Non-Confidential Resource: A resource that is required by law to report incidents/violations and take legal, disciplinary or other action accordingly.
Princeton University
217 McCosh Health Center
Washington Road, Princeton, NJ 08544
|
Xantusiidae is a clade of viviparous (live bearing) lizards that ranges from southwestern North America and Baja California (Xantusia) into Central America (Lepidophyma) and Cuba (Cricosaura). Xantusia magdalena occurs in Baja California. Xantusiidae is a relatively small clade, with 3 genera and approximately 30 living species. Lepidophyma is the most speciose (~17 species), whereas Cricosaura is monotypic. Xantusiids have a reasonably good fossil record extending from the mid-Paleocene onward in western North America.
Xantusiids are fascinating lizards for several reasons. First, although they are almost uniformly diminuitive (Xantusia magdalena measures less than 4 cm snout-vent length, and the largest xantusiid species measure about 10 cm snout-vent length), xantusiids generally take several years to reach sexual maturity, and several species give birth to just 1 or 2 offspring. It is a more usual reproductive strategy for small lizards to mature quickly and produce large numbers of offspring, to increase their chances of survival. Despite this low reproductive potential, xantusiid neonates actually have a high life expectancy; this can be attributed at least in part to their secretive lifestyle, which leads to the second reason why xantusiids are particularly interesting -- microhabitat specialization.
Microhabitat specialization is an ecological hallmark of Xantusiidae. Many populations are narrowly restricted to specific niches -- crevices (e.g., Xantusia henshawi in exfoliating granitic cap rocks), interstices in agaves and yuccas in dry climates (e.g., X. magdalena), decaying logs in wet climates (e.g., Lepidophyma flavimaculatum) -- and individuals may be found under the same patch of cover throughout their lives!
These microhabitat restrictions result in extremely disjunct geographical distributions, and also may be responsible for some morphological convergence within the group (e.g., flattened skulls for crevice dwelling). Xantusiidae also includes two insular endemics: the Cuban Cricosaura typica is the only xantusiid found in the West Indies and is interpreted as one of the Caribbean's few ancient endemic vertebrate lineages; and Xantusia riversiana (formerly Klauberina riversiana) is limited to three of the Channel Islands off the coast of California.
The phylogenetic relationships of Xantusiidae are problematic. Morphology and molecules produce different topologies within the clade: morphology recovers a Cricosaura + Lepidophyma clade, while mitochondrial genes recover a Lepidophyma + Xantusia clade. Lack of resolution of relationships within Xantusiidae has hindered the placement of this clade within the squamate tree. Xantusiidae is a "tree-changing" taxon: it causes homoplasy wherever it is placed, and its placement can tip the balance between the two primary competing hypotheses of scleroglossan relationships. Xantusiidae is traditionally placed within Scincomorpha, but some analyses have placed it near Gekkota. Thus, Xantusiidae is either a highly derived, or extremely basal, scleroglossan clade. Previous analyses of squamate phylogeny have almost certainly suffered in relying on species of the readily available -- but relatively derived -- genus Xantusia as exemplars for Xantusiidae. Cricosaura or a species of Lepidophyma would be more appropriate, but both are exceedingly rare in collections; indeed, some species of Lepidophyma are known from only 1 or 2 specimens.
Whatever the placement of Xantusiidae within squamates, there is no doubt that xantusiids are monophyletic. The following are some of the hypothesized synapomorphies of the lineage (from Estes et al., 1988), most of which can be seen in the skull reconstructions above: supratemporal fenestra closed primarily by postorbital; parietals paired well into postembryonic ontogeny; parietal table extensive posteriorly, largely obscuring braincase in dorsal view, supratemporal process short; vomers fused; ectopterygoid contacts palatine anterolaterally, excluding maxilla from suborbital fenestra; ectopterygoid enlarged medially, restricting suborbital fenestra.
About the Species
This specimen was collected in Baja California Sur, Mexico. It was made available to the University of Texas High-Resolution X-ray CT Facility for scanning by Dr. Jessie Maisano of The University of Texas and Dr. Jacques Gauthier of Yale University. Funding for scanning was provided by an NSF grant (DEB-0132227) to Dr. Jack Sites of Brigham Young University. Funding for image processing was provided by a National Science Foundation Digital Libraries Initiative grant to Dr. Timothy Rowe of The University of Texas at Austin.
About this Specimen
The specimen was scanned by Matthew Colbert on 18 May 2005 along the coronal axis for a total of 615 1024x1024 pixel slices. Each slice is 0.0152 mm thick, with an interslice spacing of 0.0152 mm and a field of reconstruction of 7 mm.
Bezy, R. L. 1982. Xantusia vigilis. Catalogue of American Amphibians and Reptiles 302.1-302.4.
Bezy, R. L. 1988. The natural history of the night lizards, family Xantusiidae, p. 1-12. In H. F. DeLisle et al. (eds.), Proceedings of the Conference on California Herpetology. Southwest Herpetological Society Special Publication 4.
Bezy, R. L. 1989. Night lizards: the evolution of habitat specialists. Terra 28:29-34.
Bezy, R. L., and J. L. Camarillo. 2002. Systematics of xantusiid lizards of the genus Lepidophyma. Los Angeles County Museum Contributions in Science 493:1-41.
Crother, B. I., M. M. Miyamoto, and W. F. Presch. 1986. Phylogeny and biogeography of the lizard family Xantusiidae. Systematic Zoology 35:37-45.
Estes, R. 1983. Sauria Terrestria, Amphisbaenia. Handbuch der Palaoherpetologie, Part 10A. Gustav Fischer Verlag, Stuttgart.
Estes, R., K. de Queiroz, and J. Gauthier. 1988. Phylogenetic relationships within Squamata, p. 119-281. In R. G. Estes and G. K. Pregill (eds.), Phylogenetic Relationships of the Lizard Families: Essays Commemorating Charles L. Camp. Stanford University Press, Stanford.
Fellers, G. M., and C. A. Drost. 1991. Ecology of the island night lizard, Xantusia riversiana, on Santa Barbara Island, California. Herpetological Monographs 5:28-78.
Hedges, S. B., R. L. Bezy, and L. B. Maxson. 1991. Phylogenetic relationships and biogeography of xantusiid lizards, inferred from mitochondrial DNA sequences. Molecular Biology and Evolution 8:767-780.
Lee, M. S. Y. 1998. Convergent evolution and character correlation in burrowing reptiles: towards a resolution of squamte relationships. Biological Journal of the Linnean Society 63:369-453.
Macey, J. R., A. Larson, N. B. Ananjeva, and T. J. Papenfuss. 1997. Evolutionary shifts in three major structural features of the mitochondrial genome among iguanian lizards. Journal of Molecular Evolution 44:660-674.
Savage, J. M. 1955. The lizard family Xantusiidae: an evolutionary study. Ph.D. Dissertation, Stanford University.
Savage, J. M. 1963. Studies on the lizard family Xantusiidae. IV. The genera. Los Angeles County Museum Contributions in Science 71:3-38.
Sinclair, E. A., Bezy, R. L., Bolles, K., Camarillo R., J. L., Crandall, K. A. and J. W. Sites Jr. 2004. Testing species boundaries in an ancient species complex with deep phylogeographic history: Genus Xantusia (Squamata: Xantusiidae). The American Naturalist 164:396-414.
Van Denburgh, J. 1895. The species of the genus Xantusia
. Proceedings of the California Academy of Sciences (Series 2) 5:523-534.
Zweifel, R. G., and C. H. Lowe. 1966. The ecology of a population of Xantusia vigilis
, the desert night lizard. American Museum Novitates 2247:1-57.
Xantusiidae page on the EMBL Reptile Database
Three-dimensional volumetric renderings of the skull with the scleral ossicles, hyoid and jaw removed, and of the isolated left mandible. All are 2mb or less.
|
#include "expr.h"
#include "scope.h"
#include "scratch.h"
#include "label.h"
#include "library.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
extern int type_val;
extern int resolve_val;
extern int yylineno;
extern int reg_table[6];
/* create an expression*/
/*
inputs
- kind: expression type
- L: sitting to the left of the expression
- R: sitting to the right of the expression
output
- e: expr struct
*/
struct expr * expr_create( expr_t kind,
struct expr *L,
struct expr *R )
{
struct expr *e = calloc(1, sizeof(*e));
e->kind = kind;
e->left = L;
e->right = R;
return e;
}
/* create a name for an expression */
struct expr * expr_create_name(const char *name)
{
struct expr *e = expr_create(EXPR_NAME, 0, 0);
e->name = name;
return e;
}
/* create an integer literal for an expression */
struct expr * expr_create_integer_literal(int int_val)
{
struct expr *e = expr_create(EXPR_INT_LITERAL, 0, 0);
e->literal_value = int_val;
return e;
}
/* create a boolean for an expression */
struct expr * expr_create_boolean_literal(int bool_val)
{
struct expr *e = expr_create(EXPR_BOOLEAN_LITERAL, 0, 0);
e->literal_value = bool_val;
return e;
}
/* create a char for an expression */
struct expr * expr_create_char_literal(char char_val)
{
struct expr *e = expr_create(EXPR_CHAR_LITERAL, 0, 0);
e->literal_value = char_val;
return e;
}
/* create a string for an expression */
struct expr * expr_create_string_literal(const char *str_val)
{
struct expr *e = expr_create(EXPR_STRING_LITERAL, 0, 0);
// printf("Adding string %s\n",str_val);
e->string_literal = str_val;
return e;
}
/* expr_resolve - resolve the current expression by looking it up in the scope */
/*
inputs
- e: expr struct
*/
void expr_resolve(struct expr *e)
{
// resolve nothing if it doesn't exist
if (!e) return;
// check if the kind of expression is an identifier
if (e->kind == EXPR_NAME)
{
// printf("assigning a symbol to %s\n",e->name);
// try to link a symbol from the existing scope to the variable name
e->symbol = scope_lookup(e->name);
// scope_bind(e->name,e->symbol);
// if we can't actually link any sorta symbol name to our identifier theres a resolution error
if (!e->symbol)
{
printf("resolve error: %s is not defined\n",e->name);
resolve_val++;
}
// printf("COMPLETED assigning a symbol to %s\n",e->name);
}
// if we don't have an identifier just look at every other expression linked to this one until we do
expr_resolve(e->next); // resolve the "next" expression, which will be some new array element
expr_resolve(e->left); // resolve the left expression
expr_resolve(e->right); // resolve the right expression
}
/* exprs_resolve - resolve multiple expressions joined together by some linked list, for function parameter lists or array elements */
/*
inputs
- e: expr struct, has a next attribute associated
*/
void exprs_resolve(struct expr *e)
{
// resolve nothing if it doesn't exist
if (!e) return;
// resolve our current expression
expr_resolve(e);
// but also resolve the next expression, doesn't matter if it exists or not
exprs_resolve(e->next);
}
/* expression type checker */
/*
- computes the type of an expression recursively and return a new type object to represent it
- should check for errors within the expresision
- the result of this typecheck method should be used to compare against expectations in stmt_typecheck and decl_typecheck
*/
struct type * expr_typecheck(struct expr *e)
{
// if expression doesn't exist we gotta go
if (!e) return 0;
// fflush(stdout);
struct type *l = expr_typecheck(e->left);
struct type *r = expr_typecheck(e->right);
struct type *res;
// printf("expr typecheck ");
// expr_print(e);
// printf("\n");
// if (e->name) printf("expr name: %s\n",e->name);
// if (e->literal_value)
// {
// if (e->kind == EXPR_CHAR_LITERAL) printf("expr literal value: %c\n",e->literal_value);
// else printf("expr literal value: %i\n",e->literal_value);
// }
// if (e->string_literal)printf("expr string literal: %s\n",e->string_literal);
switch (e->kind)
{
case EXPR_ASSIGN: // 0
// if the left expression exists
if (l)
{
if (l->kind == TYPE_AUTO) // type auto must be reassigned to a new type
{
l = type_copy(r); // just copy the type of the RHS of the assignment
printf("notice: type of %s is ",e->left->name);
type_print(r);
printf("\n");
}
else if (!type_compare(l,r)) // if the types of the exprs on the left and the right side don't match at all
{
printf("type error: you can't assign a variable %s with a value of a different type silly\n", e->left->name);
type_val++;
}
else if (l->kind == TYPE_ARRAY && r->kind == TYPE_ARRAY) // do we have arrays on the left and right sides
{
if (!type_compare(l->subtype,r->subtype))
{
printf("type error: cannot assign two arrays %s and %s of different subtypes\n", e->left->name, e->right->name);
}
}
res = type_copy(l);
}
break;
case EXPR_ADD: // 1
case EXPR_SUB: // 2
case EXPR_MUL: // 3
case EXPR_DIV: // 4
case EXPR_MOD: // 5
case EXPR_EXP: // 6
// check to see if either side of the epxression is a non-integer
if (l->kind != TYPE_INTEGER || r->kind != TYPE_INTEGER)
{
// printf("type error: cannot perform a binary operation on a non-integer type\n");
printf("type error: cannot perform a binary operation between ");
type_print(r);
printf(" (");
expr_print(e->right);
printf(") and");
type_print(l);
printf(" (");
expr_print(e->left);
printf(")\n");
type_val++;
}
// create an integer type for this expression
res = type_create(TYPE_INTEGER, 0, 0, 0);
break;
case EXPR_LE: // 7
case EXPR_LT: // 8
case EXPR_GE: // 9
case EXPR_GT: // 10
// check to see if either operation of the comparison is a non-integer
if (l->kind != TYPE_INTEGER || r->kind != TYPE_INTEGER)
{
printf("type error: cannot perform a logical operation on non-integer type ");
// print an error message for an invalid left hand side
if (l->kind != TYPE_INTEGER)
{
type_print(l);
printf(" (");
expr_print(e->left);
printf(")\n");
type_val++;
}
// print an error message for an invalid right hand side
if (r->kind != TYPE_INTEGER)
{
type_print(r);
printf(" (");
expr_print(e->right);
printf(")\n");
type_val++;
}
// type_val++;
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_EQ: // 11
case EXPR_NEQ: // 12
// the types on both sides of this comparison need to be the same, check to see if this is true
if (!type_compare(l,r))
{
printf("type error: ");
type_print(l);
expr_print(e->left);
printf(" and ");
type_print(r);
expr_print(e->right);
printf("are of different types\n");
type_val++;
}
if (l->kind == TYPE_FUNCTION ||
l->kind == TYPE_ARRAY ||
l->kind == TYPE_VOID )
{
printf("type error: cannot compare equality for ");
type_print(l);
printf("\n");
type_val++;
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_AND: // 13
case EXPR_OR: // 14
// may only be applied to boolean values nice
if (l->kind != TYPE_BOOLEAN || r->kind != TYPE_BOOLEAN)
{
printf("type error: cannot perform logical operation on non-boolean ");
// print an error message for an invalid left hand side
if (l->kind != TYPE_BOOLEAN)
{
type_print(l);
printf("(");
expr_print(e->left);
printf(")");
type_val++;
}
// print an error message for an invalid right hand side
if (r->kind != TYPE_BOOLEAN)
{
if (l->kind != TYPE_BOOLEAN) printf(" and ");
type_print(r);
printf("(");
expr_print(e->right);
printf(") ");
type_val++;
}
printf("\n");
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_NOT: // 15
// may only be applied to boolean values nice
if (r->kind != TYPE_BOOLEAN)
{
printf("type error: cannot negate a non-boolean ");
type_print(r);
printf("(");
expr_print(e->right);
printf(")\n");
type_val++;
}
// create a boolean type for this expression
res = type_create(TYPE_BOOLEAN, 0, 0, 0);
break;
case EXPR_NEG: // 16
if (r->kind != TYPE_INTEGER)
{
printf("type error: cannot negate non-integer ");
type_print(r);
printf(" (");
expr_print(e->right);
printf(")\n");
type_val++;
}
res = type_create(TYPE_INTEGER, 0, 0, 0);
break;
case EXPR_INCR: // 17
case EXPR_DECR: // 18
if (l->kind != TYPE_INTEGER)
{
printf("type error: cannot perform a postfix operation on non-integer ");
type_print(l);
printf(" (");
expr_print(e->left);
printf(")\n");
type_val++;
}
res = type_create(TYPE_INTEGER, 0, 0, 0);
break;
case EXPR_GROUP: // 19
// printf("GROUP ");
// type_print(expr_typecheck(e->right));
// printf("\n");
// copy the type
res = type_copy(expr_typecheck(e->right));
break;
case EXPR_ARRELEM: // 20
// are we looking at an array's elements here
if (l->kind == TYPE_ARRAY)
{
// are we trying to get into a non-integer access
if (r->kind != TYPE_INTEGER)
{
printf("type error: cannot access %s array with non-integer \n", e->left->name);
type_val++;
}
// if the array multi-dimensional
if (e->right->right)
{
struct expr *r_expr = e->right;
while (r_expr)
{
// constantly look at each consecutive array access
if (expr_typecheck(r_expr)->kind != TYPE_INTEGER)
{
printf("type error: cannot access %s array with non-integer \n", e->left->name);
type_val++;
}
if (r_expr->right) r_expr = r_expr->right;
else r_expr = 0;
}
}
// add multiple array accesses
res = type_copy(l->subtype);
}
else // hey we got an error, this ain't an array
{
printf("type error: cannot index string %s with non-integer\n", e->left->name);
res = type_copy(l);
type_val++;
}
break;
case EXPR_INT_LITERAL: // 21
res = type_create(TYPE_INTEGER, 0, 0, 0); // create a new integer type
break;
case EXPR_BOOLEAN_LITERAL: // 22
res = type_create(TYPE_BOOLEAN, 0, 0, 0); // create a new boolean type
break;
case EXPR_CHAR_LITERAL: // 23
res = type_create(TYPE_CHARACTER, 0, 0, 0); // create a new character type
break;
case EXPR_STRING_LITERAL: // 24
res = type_create(TYPE_STRING, 0, 0, 0); // create a new string type
break;
case EXPR_NAME: // 25
// printf("copying identifier %s\n",e->name);
// printf("kind %i\n",e->symbol->type->kind);
// if (e->symbol)
// {
// printf("theres a symbol here\n");
// }
// else
// {
// printf("there's no symbol here\n");
// }
res = type_copy(e->symbol->type); // copy the symbol type
break;
case EXPR_FUNCCALL: // 26
// printf("Function call has been MADE\n");
if (l->kind == TYPE_FUNCTION)
{
struct param_list *p = e->left->symbol->type->params; // pointer to param list of actual function decl
struct expr *er = e->right; // pointer to the first param of a linked list for the function call
// make sure the types of the vars used in the function call are the same as the types of the variables in the declaration
if (!param_list_compare_call(p, er))
{
printf("type error: parameters not matching in function call of %s\n", e->left->name);
type_val++;
}
res = type_copy(l->subtype); // this is the return type of the function call
}
else // you're making a call to a non-function, stop that
{
printf("type error: cannot call non-function %s\n", e->left->name);
res = type_copy(l); // create a type copy to return anyway
type_val++;
}
break;
}
type_delete(l);
type_delete(r);
return res;
}
/*
- recursively calls itself for its left and right children
- each child will generate code such that the result will be left in the reg num noted in the reg field
- current node generates code using those registers
- current node frees the registers it no longer needs
extra stuff
- not all symbols are simple global vars
- when a symbol forms part of an instruction, symbol_codegen needs to return the string that gives the specific address for that symbol
*/
/* expression code generation */
void expr_codegen(struct expr *e, FILE *outfil)
{
// if there's no expression to generate code for then leave
if (!e) return;
// generate code based on type of expression
switch (e->kind)
{
// Interior node: generate children, then add them
case EXPR_ASSIGN: // 0
printf("assignment time\n");
// generate code for both sides of the assignment
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// store the resulting register (left) onto the stack
// fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->right->symbol));
if (e->left->kind == EXPR_ARRELEM)
{
int idx = e->left->right->literal_value;
printf("array elem: index %i\n",idx*8);
// load the array again cause I'm lazy
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tstr\t%s, [%s, %i]\n", scratch_name(e->right->reg), scratch_name(e->left->reg), idx*8);
}
else if (e->left->symbol->kind == SYMBOL_LOCAL)
{
printf("not an array element\n");
// fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->right->symbol));
fprintf(outfil, "\tstr\t%s, [sp, %s]\n", scratch_name(e->right->reg), symbol_codegen(e->left->symbol));
}
else // TODO check to see if global variable editing even works
{
printf("global variable storage: %s\n",e->left->name);
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tstr\t%s, [%s]\n", scratch_name(e->right->reg), scratch_name(e->left->reg));
}
e->reg = e->left->reg;
break;
case EXPR_ADD: // 1
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
fprintf(outfil, "\tadd\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_SUB: // 2
expr_codegen(e->left, outfil);
/*
int leftreg_ptr = e->left->reg;
if (e->right->kind == EXPR_FUNCCALL)
{
e->left->reg = 19;
}
*/
expr_codegen(e->right, outfil);
fprintf(outfil, "\tsub\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
/*
if (e->right->kind == EXPR_FUNCCALL)
{
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(leftreg_ptr), scratch_name(e->left->reg));
e->left->reg = leftreg_ptr;
}
*/
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_MUL: // 3
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
fprintf(outfil, "\tmul\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_DIV: // 4
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
fprintf(outfil, "\tsdiv\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_MOD: // 5
expr_codegen(e->left, outfil); // left side of modulo operator (a)
expr_codegen(e->right, outfil); // right side of modulo operator (n)
// perform modulus operation - a mod n = a - [n * int(a/n)]
int div_reg = scratch_alloc();
fprintf(outfil, "\tsdiv\t%s, %s, %s\n", scratch_name(div_reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
fprintf(outfil, "\tmul\t%s, %s, %s\n", scratch_name(e->right->reg), scratch_name(div_reg), scratch_name(e->right->reg));
fprintf(outfil, "\tsub\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
// free left and right registers
e->reg = e->left->reg;
scratch_free(div_reg);
scratch_free(e->right->reg);
break;
case EXPR_EXP: // 6
expr_codegen(e->left, outfil); // base
expr_codegen(e->right, outfil); // exponent
// let's just hope these registers are in x0 and x1 lol
int base_reg = 0;
int expo_reg = 1;
if (e->left->reg != base_reg)
{
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(base_reg), scratch_name(e->left->reg));
}
if (e->right->reg != expo_reg)
{
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(expo_reg), scratch_name(e->right->reg));
}
// branch to our integer power function
fprintf(outfil, "\tbl\tinteger_power\n");
e->reg = e->left->reg;
scratch_free(e->left->reg);
scratch_free(e->right->reg);
break;
case EXPR_LE: // 7
case EXPR_LT: // 8
case EXPR_GE: // 9
case EXPR_GT: // 10
case EXPR_EQ: // 11
case EXPR_NEQ: // 12
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// compare both sides of the expression
fprintf(outfil, "\tcmp\t%s, %s\n", scratch_name(e->left->reg), scratch_name(e->right->reg));
// conditional set a register based on one of the conditions
switch (e->kind)
{
case EXPR_LE: // 7
fprintf(outfil, "\tcset\t%s, le\n", scratch_name(e->left->reg));
break;
case EXPR_LT: // 8
fprintf(outfil, "\tcset\t%s, lt\n", scratch_name(e->left->reg));
break;
case EXPR_GE: // 9
fprintf(outfil, "\tcset\t%s, ge\n", scratch_name(e->left->reg));
break;
case EXPR_GT: // 10
fprintf(outfil, "\tcset\t%s, gt\n", scratch_name(e->left->reg));
break;
case EXPR_EQ: // 11
fprintf(outfil, "\tcset\t%s, eq\n", scratch_name(e->left->reg));
break;
case EXPR_NEQ: // 12
fprintf(outfil, "\tcset\t%s, ne\n", scratch_name(e->left->reg));
break;
}
// free unnecessary register and assign expression register
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_AND: // 13
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// create an AND function
fprintf(outfil, "\tand\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
// update expression register, maybe keep the unused register idk
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_OR: // 14
expr_codegen(e->left, outfil);
expr_codegen(e->right, outfil);
// create an AND function
fprintf(outfil, "\torr\t%s, %s, %s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), scratch_name(e->right->reg));
// update expression register, maybe keep the unused register idk
e->reg = e->left->reg;
scratch_free(e->right->reg);
break;
case EXPR_NOT: // 15
expr_codegen(e->right, outfil);
// do an equals comparison to 0
fprintf(outfil, "\tcmp\t%s, 0\n", scratch_name(e->right->reg));
fprintf(outfil, "\tcset\t%s, eq\n", scratch_name(e->right->reg));
// set new register of the expression
e->reg = e->right->reg;
break;
case EXPR_NEG: // 16
expr_codegen(e->right, outfil);
// use the negative instruction on the register
fprintf(outfil, "\tneg\t%s, %s\n", scratch_name(e->right->reg), scratch_name(e->right->reg));
// set new register of the expression
e->reg = e->right->reg;
break;
case EXPR_INCR: // 17
case EXPR_DECR: // 18
expr_codegen(e->left, outfil);
int temp_reg = scratch_alloc();
if (e->kind == EXPR_INCR)
fprintf(outfil, "\tadd\t%s, %s, 1\n", scratch_name(temp_reg), scratch_name(e->left->reg));
else if (e->kind == EXPR_DECR)
fprintf(outfil, "\tsub\t%s, %s, 1\n", scratch_name(temp_reg), scratch_name(e->left->reg));
else
{
printf("codegen error: how are you here in the incr/decr section.\n");
exit(1);
}
e->reg = e->left->reg;
// gotta also store this register into memory then free it
// check whether we're saving an array element, local, or global variable
if (e->left->kind == EXPR_ARRELEM)
{
int idx = e->left->right->literal_value;
// load the array again cause I'm lazy
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), e->left->left->name);
fprintf(outfil, "\tstr\t%s, [%s, %i]\n", scratch_name(temp_reg), scratch_name(e->left->reg), idx*8);
}
else if (e->left->symbol->kind == SYMBOL_LOCAL)
{
printf("not an array element\n");
fprintf(outfil, "\tstr\t%s, [sp, %s]\n", scratch_name(temp_reg), symbol_codegen(e->left->symbol));
}
else
{
printf("global variable storage: %s\n",e->left->name);
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->left->reg), scratch_name(e->left->reg), symbol_codegen(e->left->symbol));
fprintf(outfil, "\tstr\t%s, [%s]\n", scratch_name(temp_reg), scratch_name(e->left->reg));
// immediately load the value into x0 in case we wanna use it
fprintf(outfil, "\tldr\t%s, [%s]\n", scratch_name(e->left->reg), scratch_name(e->left->reg));
}
// free the registers afterward
scratch_free(temp_reg);
scratch_free(e->left->reg);
break;
case EXPR_GROUP: // 19
// expression grouping/precedence just doesn't work at all
expr_codegen(e->right,outfil);
e->reg = e->right->reg;
break;
case EXPR_ARRELEM: // 20
// TODO somehow implement the assignment of values to arrays which have not been declared yet
// TODO also assignment of new values to already declared arrays
printf("ARRAY ELEM INDEXING\n");
if (e->left) printf("name: %s\n",e->left->name);
if (e->right) printf("idx: %i\n",e->right->literal_value);
e->reg = scratch_alloc();
// instructions to deal with loading the array up
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->reg), e->left->name);
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->reg), scratch_name(e->reg), e->left->name);
// now we gotta load up the exact element based on where it's located on the stack
// expr_codegen(e->right, outfil);
e->right->reg = scratch_alloc();
int idx = e->right->literal_value;
if (idx == 0)
fprintf(outfil, "\tldr\t%s, [%s]\n",scratch_name(e->right->reg),scratch_name(e->reg));
else
fprintf(outfil, "\tldr\t%s, [%s, %i]\n",scratch_name(e->right->reg),scratch_name(e->reg),idx*8);
// to be annoying and give probably the laziest and probably specific fix ever, just move the right reg into the arrays reg
fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->reg), scratch_name(e->right->reg));
// scratch_free(e->right->reg);
scratch_free(e->right->reg);
// e->reg = e->right->reg;
break;
// Leaf node: allocate register and load value
case EXPR_INT_LITERAL: // 21
case EXPR_BOOLEAN_LITERAL: // 22
case EXPR_CHAR_LITERAL: // 23
e->reg = scratch_alloc();
fprintf(outfil, "\tmov\t%s, %d\n", scratch_name(e->reg), e->literal_value);
break;
case EXPR_STRING_LITERAL: // 24
e->reg = scratch_alloc();
// string label stuff here
int str_label = label_create();
// start up the data section once more
fprintf(outfil, "\t.data\n");
fprintf(outfil, "\t.section\t.rodata\n");
// allocate 2^3 = 8 bytes
fprintf(outfil, "\t.align\t3\n");
// string label
fprintf(outfil, "%s:\n", label_name(str_label));
// string value
fprintf(outfil, "\t.string\t%s\n", e->string_literal);
// go back to the text section
fprintf(outfil, "\t.text\n");
// now we need instructions to deal with this string
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->reg), label_name(str_label));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->reg), scratch_name(e->reg), label_name(str_label));
break;
case EXPR_NAME: // 25
e->reg = scratch_alloc();
if (e->symbol->kind != SYMBOL_GLOBAL)
{
printf("loading local variable/parameter %s\n",e->name);
// code to reference any parameter or local variable for anything
fprintf(outfil, "\tldr\t%s, [sp, %s]\n", scratch_name(e->reg), symbol_codegen(e->symbol));
// TODO maybe remove this line cause it might not be necessary (i think this is only for global vars)
// fprintf(outfil, "\tmov\t%s, %s\n", scratch_name(e->reg), symbol_codegen(e->symbol));
}
else
{
// code to reference a global variable within a function for anything
printf("loading global variable %s\n",e->name);
fprintf(outfil, "\tadrp\t%s, %s\n", scratch_name(e->reg), symbol_codegen(e->symbol));
fprintf(outfil, "\tadd\t%s, %s, :lo12:%s\n", scratch_name(e->reg), scratch_name(e->reg), symbol_codegen(e->symbol));
// TODO figure out if commenting this breaks things
// TODO this breaks only when we gotta store something to the global variable itself aka any assignment
// is there a way to find out if this name comes from an assignment?
fprintf(outfil, "\tldr\t%s, [%s]\n", scratch_name(e->reg), scratch_name(e->reg));
}
break;
case EXPR_FUNCCALL: // 26
{
struct expr *er = e->right; // parameters
struct expr *er_copy = e->right; // parameters copy
struct expr *el = e->left; // function identifier
// int i = 0;
// printf("funccall start\n");
// TODO somehow move other IR values into other registers before calling this
// let's try to at least
/*
int reg_move = 19;
for (int i=0;i<6;i++)
{
if (reg_table[i])
{
}
}
*/
// generate code for loading in those parameters
while (er)
{
// TODO fix this up, we gotta load the parameters into argument registers then branch to the function
// If i hardcode the parameters, have this loop a "mov" command
// generate code for parameter
expr_codegen(er, outfil);
// free register if possible
// scratch_free(er->reg);
// move to next pointer
er = er->next;
}
// scratch_print();
// printf("now we free\n");
// free up the registers we just used
while (er_copy)
{
scratch_free(er_copy->reg);
er_copy = er_copy->next;
}
// scratch_print();
// printf("argument end\n");
// branch to the function
fprintf(outfil, "\tbl\t%s\n",el->name);
/*
// TODO needs local variable storage for any return parameters, probably also needs a lot of fixes
if (expr_typecheck(el) != TYPE_VOID)
{
printf("returning for function %s\n", el->name);
e->reg = scratch_alloc();
fprintf(outfil, "\tstr\t%s, [sp, %i]\n", scratch_name(e->reg), STACK_SIZE-(el->symbol->which*8));
}
*/
// printf("done with return type\n");
/*
int funccall_result = scratch_alloc();
e->reg = funccall_result;
*/
break;
}
}
/*
// I'm just gonna try something
if (e->right)
{
if (e->right->kind == EXPR_FUNCCALL)
{
// save registers
// new register time
e->reg = 19;
}
}
*/
}
/* print an expression */
void expr_print(struct expr *e)
{
// return if the expression just does not exist
if (!e) return;
// print based on the kind of expression
switch (e->kind)
{
case EXPR_ASSIGN:
expr_print(e->left);
printf("=");
expr_print(e->right);
break;
case EXPR_ADD:
// printf("ADDLEFT KIND:%d ",e->left->kind);
expr_print(e->left);
printf("+");
// printf("ADDRIGHT KIND:%d ",e->right->kind);
expr_print(e->right);
break;
case EXPR_SUB:
// printf("SUBLEFT KIND:%d ",e->left->kind);
expr_print(e->left);
printf("-");
// printf("SUBRIGHT KIND:%d ",e->right->kind);
expr_print(e->right);
break;
case EXPR_MUL:
expr_print(e->left);
printf("*");
expr_print(e->right);
break;
case EXPR_DIV:
expr_print(e->left);
printf("/");
expr_print(e->right);
break;
case EXPR_MOD:
expr_print(e->left);
printf("%%");
expr_print(e->right);
break;
case EXPR_EXP:
expr_print(e->left);
printf("^");
expr_print(e->right);
break;
case EXPR_LE:
expr_print(e->left);
printf("<=");
expr_print(e->right);
break;
case EXPR_LT:
expr_print(e->left);
printf("<");
expr_print(e->right);
break;
case EXPR_GE:
expr_print(e->left);
printf(">=");
expr_print(e->right);
break;
case EXPR_GT:
expr_print(e->left);
printf(">");
expr_print(e->right);
break;
case EXPR_EQ:
expr_print(e->left);
printf("==");
expr_print(e->right);
break;
case EXPR_NEQ:
expr_print(e->left);
printf("!=");
expr_print(e->right);
break;
case EXPR_AND:
expr_print(e->left);
printf("&&");
expr_print(e->right);
break;
case EXPR_OR:
expr_print(e->left);
printf("||");
expr_print(e->right);
break;
case EXPR_NOT:
printf("!");
expr_print(e->right);
break;
case EXPR_NEG:
printf("-");
expr_print(e->right);
break;
case EXPR_INCR:
expr_print(e->left);
printf("++");
break;
case EXPR_DECR:
expr_print(e->left);
printf("--");
break;
case EXPR_GROUP:
printf("(");
expr_print(e->right);
printf(")");
break;
case EXPR_ARRELEM:
expr_print(e->left); // expr_create_name(ident) --> expr_create(EXPR_NAME,0,0) --> name
printf("[");
expr_print(e->right); // bracket --> [expr] --> [i] bracket --> expr->right = brackets --> bracket --> expr
printf("]");
e = e->right;
if (e->next)
{
while (e->next)
{
printf("[");
expr_print(e->next);
printf("]");
e = e->next;
}
}
break;
case EXPR_INT_LITERAL:
printf("%d",e->literal_value);
break;
case EXPR_BOOLEAN_LITERAL:
if (e->literal_value) printf("true");
else printf("false");
break;
case EXPR_CHAR_LITERAL:
printf("'%c'",e->literal_value);
break;
case EXPR_STRING_LITERAL:
printf("%s", e->string_literal);
break;
case EXPR_NAME:
printf("%s", e->name);
break;
case EXPR_FUNCCALL:
expr_print(e->left);
printf("(");
exprs_print(e->right);
printf(")");
break;
}
return;
}
/* print multiple expressions, for print, funccalls, arrayelems */
void exprs_print(struct expr *e)
{
/* print nothing if it doesn't exist */
if (!e) return;
expr_print(e);
if (e->next)
{
printf(", ");
}
exprs_print(e->next);
}
|
The Perception of Sound
By: Ken Humphreys
Speaker Engineer
After a sound wave reaches your eardrum, the real magic begins. When you’re aware of a sound, your ear and brain are working together on the difficult task of selecting which sound to pay attention to, what might be making it, where it’s located and much more. Here are a few of the important “processing” jobs you routinely but unconsciously accomplish:
Determining Loudness
You can hear a sound at 0 dB (but just barely) yet handle sounds with a trillion times the energy at 120 dB! The price you pay to be able pull off this remarkable feat is that you’re fairly insensitive to changes in sound energy levels. For example, a speaker receiving 100 watts of energy will sound only four times as loud as when it’s receiving 1 watt. One side-effect of this phenomenon is that you don’t need to concern yourself with amplifier power nearly as much as you might think. 70 watts—100 watts—what’s the difference? Only about 1½ dB. Not much, right?
This graph shows the sound intensity range that you’re able to make sense of. Each 10dB increase represents 10 times the energy, but only twice the loudness.
Another neat loudness related trick your ear performs is that it becomes increasingly sensitive to bass when the sound is loud and sensitive to the midrange when everything quiets down. The “loudness” button on your receiver is designed to compensate for this by boosting the bass at lower listening levels. This context-sensitivity was probably quite useful for cavemen by allowing them to derive useful bass information when encountering stampeding wooly mammoths — yet be able to tune into the slight rustle of a skulking saber-toothed tiger. Dinner is served!
Locating sound
When you hear a sound, you can immediately turn your head and face it. You probably take this for granted, but you might not if you knew the number of hard-to-believe calculations your brain just performed. Scientists are discovering that you construct a spatial model in your brain that updates constantly and uses sound as well as sight. Yes, very similar to bats.
To locate sounds in this model you constantly gather information from a variety of sources:
What kind of space are you in? When you hear a sound it has a “signature” that is unique. It arrives at your ear and gets “fingerprinted,” and a few milliseconds later a family of other sounds that bear the same signature arrive in the form of reflections. First, they are associated with the first arrival that created the signature so that the cacophony of other sounds around you can be ignored. Then, by calculating the direction of these delayed arrivals, how long they were delayed and the way that their signature has been “smeared” (whew!) you are able to tell a lot about what kind of environment you are in. For example, you may now know that you are in a small room with large, hard surfaces. In order to do this you had to determine the directions of the original sound and the way it echoed around the room. This was not simply done. Your brain just took into consideration at least three different kinds of information to calculate the direction. First, one ear heard the sound as louder simply because your head created a “sound shadow” and blocked the sound to the ear furthest away. Secondly, the part of your ear that sticks out from your head modified the sound in ways that clue you in regarding the direction the sound came from. And lastly, your brain calculated the phase thing: How much was the delay between the wave arriving at the left ear versus the right ear? Your brain then unconsciously applies this formula to what you just experienced.
And you thought you were bad at math! Your brain is a whiz.
For speaker designers, some of the important points are:
1. For familiar sounds, you are very sensitive to “tonal balance,” that is, are the treble, bass and midrange parts in the right proportion to one another? If a speaker’s frequency response graph is “flat”, that tells you that it’s reproducing the sound with the right balance (at least for the position of the measuring microphone). This has been shown to be the most important thing perceived as “accuracy” in the entire audio system.
2. How much of a time-delay does there need to be for an arriving sound to be identified as a reflection rather than part of the original sound’s signature? Jury’s out on this one, but if the “delayed arrival” is soon enough, say from reflections off of the grill frame or speakers that aren’t mounted flush, it is heard as part of the signature and you will hear it as a distortion to the tonal balance.
3. Your brain mostly ignores reflected signals when evaluating the balance of sound. Bass reflections get treated a little differently.
4. You cannot locate bass sounds unless you correctly associate a bass note’s overtones and then locate them in space. This allows for speakers that specialize in low bass—subwoofers—to be placed away from the main speakers and successfully fool you into believing that the bass is coming from the small speakers that reproduce the overtones.
5. Here is a neat little experiment you can try at home: Put your amp in “mono’ mode and notice that if you are just slightly off-center, the sound will appear to be coming completely from the speaker closest to you. This is because your brain is a detective, and the sound coming from this speaker gets “fingerprinted”, identified as the first arrival of sound and then used as the sole source of information as to the sound’s location. You are still hearing the other speaker, (try unplugging it) your brain just isn’t using it for location information.
In Conclusion
The study of how the brain processes sound – psychoacoustics — is a huge and very interesting body of information. If you’d like to read more, there’s a lot to dig into. You may want to bring a good shovel and start at this wikipedia article. Have fun exploring science!
Aperion Home Theater Gurus
Tags: Audio Technology, Guru Tips and Tricks
Leave a Reply
You must be logged in to post a comment.
|
Mastering the art of bidding; Auction! The Guide to Bidding, Buying, Bargaining, Selling, Exhibiting, and Making a Profit, by William C. Ketchum Jr. New York: Stirling Publishing Company. $10.95. Cashing in on the Auction Boom, by James Wagenvoord. New York: Rawson, Wade. $ 6.95.
Whether or not you return home with a Victorian sofa or a slightly used ironing board, an auction can make a good afternoon's or evening's worth of entertainment. Those who know the right way to attend an auction, who have mastered the art of bidding and not bidding, will get good buys as well as entertainment. Those who don't may end up wishing they'd gone to a movie instead.
Recognizing that auctions are loaded with both pleasures and perils, William C. Ketchum Jr. has written a useful guide to making sure there are more of the former than the latter.
You begin, he says, by making wise use of the auction preview, the time period in which the public can examine the goods to be sold. Anything that interests you should be examined thoroughly. Does that dropleaf table have both its leaves intact? Does that quilt have too many moth holes to make it a worthwhile investment? Never, he advises, bid on anything you haven't seen before it goes up for bid.
Other chapters deal with the sale itself, including such crucial matters as where to sit and how to bid intelligently. He also tackles the thorny subject of how to protect yourself against a dishonest auctioneer. How do you know if the auctioneer is using a "shill," someone planted in the audience to bid in order to get the price up? Or what about those "phantom bidders" who aren't really there at all?
A lawyer as well as an avid auction-goer, Mr. Ketchum gives the reader a good idea of the rules and regulations governing most auctions. Just how binding a bid can be and the circumstances under which a customer can return an object are well-outlined. He also includes a chapter on how to use auctions as a seller rather than as a buyer, pointing out that certain auctions can yield particularly high prices for your own merchandise.
In addition there is some useful background on the types of antiques auctions that are available. They range from the elite city galleries such as Sotheby Parke Bernet and Christie's, where millions of dollars can be spent during a single sale, to the small country auctions that dispense everything from Chippendale highboys to boxes of bottle caps. Each, as Mr. Ketchum illustrates, requires a certain amount of know-how to obtain both profit and enjoyment.
James Wagenvoord's book is less of a how-to on auction attendance and more of a compendium of the many different types of auctions available today. While Mr. Ketchum deals with just those offering antiques and fine arts, Mr. Wagenvoord introduces the reader to everything from post office a uctions to those resulting from business liquidations.
|
This database of images for the study and teaching of art, design, and visual culture at Illinois State University, is produced as a collaboration between the School of Art and Milner Library. The images come from many sources, including publications, original photography, and the Visual Resources Collection of the School of Art.
The slides of Sverre "Bex" Braathen combine a "Passion for Circus" with the skills and artistry of photography at its finest.
Images were captured in the saturated colors of Kodachrome slides and date from the early 1940s to the late 1950s as well as black and white film in the 1930s. Set within the context of the entire Braathen …
Illinois State University History is a growing collection that currently includes campus history books, proceedings of the first university governing board, and nearly 400 photographs.
Support for this collection is provided by the Friends of Milner Library and the Illinois State Library, a division of the Office of the Secretary of …
Welcome to Milner Library's International Collection of Child Art digital image collection! This resource holds images of art created by children and adolescents representing more than fifty countries and cultures from Argentina to New Zealand. The artworks are two dimensional and use varied media. The work in this collection …
Voices of Extremism: Conflicting Ideologies in United States Politics in the Decades Following WWII is a unique audio documentation of the individuals and movements that characterized the Extremist politics in the United States in the decades following the Second World War from 1946 to 1980. The collection also includes a documentary on …
Cultivated in the spirit of teaching, learning and research, Milner Library's digital collections provide a variety of resources. They reflect the rich cultural heritage at Illinois State University, and include audio recordings, historic documents, photos, and images of art and visual culture.
Discover all collections
Art & Culture
Circus & Allied Arts
Illinois State University History
International Collection of Child Art
Voices of Extremism
Native American Collection
Normal Editions Workshop (N.E.W.)
Towanda Area History
World War I Women
|
tag:www.econsultancy.com,2008:/topics/email Latest Email content from Econsultancy 2017-05-02T14:01:00+01:00 tag:www.econsultancy.com,2008:BlogPost/69035 2017-05-02T14:01:00+01:00 2017-05-02T14:01:00+01:00 How Lenny Letter used email newsletters to cultivate an online community Nikki Gilliland <p>With 500,000 subscribers and a reported 70% open rate, it has rapidly grown in popularity since its launch in 2015. So, what makes readers race to read it? </p> <p>Here’s a bit more on how Lenny has evolved so far.</p> <h3>Email as an intimate medium</h3> <p>Lena Dunham has famously championed the discussion of feminist topics, including friendship, health, sex and money – previously using the mediums of TV and books to do so. With the realisation that there was an appetite for more in-depth feminist content, she launched Lenny Letter to deliver it direct to women’s inboxes.</p> <p>Lenny takes the form of two emails per week – Tuesdays is for personal essays and short stories, while Fridays is reserved for interviews. Both are lengthy and usually feature illustrations by up-and-coming artists. </p> <p><img src="https://assets.econsultancy.com/images/0008/5694/Lenny_2.JPG" alt="" width="500" height="820"></p> <p>So, why did Dunham choose to steer clear of the standard website-format, used by the likes of <a href="https://econsultancy.com/blog/68121-why-i-love-the-pool-and-its-refreshing-approach-to-publishing/" target="_blank">The Pool</a> and Jezebel?</p> <p>According to editor Jessica Grose, it is so that writers can directly speak to the audience, shining a spotlight on important messages rather than distracting them with a broad selection of articles. </p> <p>What’s more, it is built on the notion that email is a much more intimate and personal medium, with users deliberately opting in to receive content rather than absent-mindedly browsing on a public forum. </p> <h3>Encourages social community</h3> <p>Lenny does have an accompanying website, however, content is published with a delay of 24 hours or so to incentivise subscriptions to the newsletter. This is also done to give the design of the newsletter due attention, with illustrations and composition deliberately aligning with the medium.</p> <p>Like a lot of other publications, Lenny <a href="https://econsultancy.com/blog/68663-why-online-publications-are-ditching-comments-sections-for-social/" target="_blank">does not allow comments</a>, instead encouraging readers to use social media to start positive conversations about topics featured. In turn, Lenny employees are highly responsive, typically replying to Instagram or Twitter comments within the same day.</p> <p>Combined, this has helped the publisher to create a receptive online audience, which has in no doubt contributed to high open rates and loyal readership. </p> <h3>Advertising business model</h3> <p>The main reason for the existence of the Lenny website is to provide a permanent space for display and <a href="https://econsultancy.com/blog/67083-is-native-advertising-sustainable/" target="_blank">native ads</a> – the result of a partnership with Hearst Media. The deal involves Hearst selling space for advertising and branded content on the site, as well as promoting Lenny across titles like Marie Claire and <a href="https://econsultancy.com/blog/68384-how-cosmopolitan-reinvented-itself-became-the-number-one-women-s-magazine-in-the-uk/" target="_blank">Cosmopolitan</a> magazine.</p> <p>Lenny also stresses that its branded content is just as authentic as its regular features, collaborating closely with brands to ensure the publication’s tone of voice remains strong.</p> <p>For instance, an interview with writer Helen Ellis focuses on what it’s like to be in a stressful situation – and it also happens to be sponsored by Secret Deodorant. Examples like these show how sponsored content can blend seamlessly in with the over-arching brand. Of course, it also relies on the audience’s trust in its reputation and dedication to quality journalism.</p> <p><img src="https://assets.econsultancy.com/images/0008/5695/Helen_Ellis.JPG" alt="" width="760" height="637"></p> <h3>Branching into other areas of business</h3> <p>Alongside the newsletter, Lenny also has an online shop selling branded clothing and accessories. </p> <p>Described as a place that ‘would rep grassroots feminist businesses’, it’s more of an extension of the brand’s values than a real money-making venture. Likewise, it also builds on the community element, with readers keen to wear subtly branded items like the ‘Dismantle the Patriarchy’ patch set.</p> <p><img src="https://assets.econsultancy.com/images/0008/5696/Lenny_shop.JPG" alt="" width="760" height="467"></p> <p>Lenny is not averse to expanding its presence in other areas, too. Last year, it began a <a href="https://econsultancy.com/blog/68348-three-reasons-brands-are-using-podcasts-as-part-of-their-content-marketing-strategy/" target="_blank">podcast series</a> called ‘Women of the Hour’ and it currently has a video series in the works for HBO Now.</p> <p>Naturally, it will need to tread carefully. While expansion could help to increase new subscribers, even more brand involvement or corporate sponsorship could potentially alienate existing readers invested in the core premise. </p> <p>That being said, as long as it keeps its focus firmly on what women really want to read about, I can’t see it going too far wrong.</p> <blockquote class="twitter-tweet"> <p lang="en" dir="ltr">Just read <a href="https://twitter.com/lennyletter">@lennyletter</a> interview by <a href="https://twitter.com/oliviaclement_">@oliviaclement_</a> with <a href="https://twitter.com/AnnaDeavereS">@AnnaDeavereS</a> . Lots of gems, but these really stuck with me. 1st on education.</p> — meghan (@meghafon) <a href="https://twitter.com/meghafon/status/852904569432571909">April 14, 2017</a> </blockquote> <p><strong><em>For more on the topic of email, you can download Econsultancy's <a href="https://econsultancy.com/reports/email-census/" target="_blank">Email Marketing Industry Census 2017</a></em></strong></p> tag:www.econsultancy.com,2008:TrainingDate/3230 2017-03-21T16:49:38+00:00 2017-03-21T16:49:38+00:00 Email Marketing - Advanced <p>Give your email campaigns an injection of fresh thinking in this fantastic email marketing workshop.</p> <p>You’ll gain advanced, strategic email marketing training and get the opportunity to have your email campaigns reviewed by an industry expert who will provide practical tips for improvement.</p> <p>Strictly limited to 10 places, the workshop allows for plenty of interaction and you’ll be able to bounce ideas off other experienced marketers.</p> tag:www.econsultancy.com,2008:TrainingDate/3229 2017-03-21T16:48:41+00:00 2017-03-21T16:48:41+00:00 Email Marketing - Advanced <p>Give your email campaigns an injection of fresh thinking in this fantastic email marketing workshop.</p> <p>You’ll gain advanced, strategic email marketing training and get the opportunity to have your email campaigns reviewed by an industry expert who will provide practical tips for improvement.</p> <p>Strictly limited to 10 places, the workshop allows for plenty of interaction and you’ll be able to bounce ideas off other experienced marketers.</p> tag:www.econsultancy.com,2008:TrainingDate/3178 2017-03-21T11:39:19+00:00 2017-03-21T11:39:19+00:00 Intensive: Mastering eCRM <p>Implementing a robust CRM strategy delivers vastly improved effectiveness in your marketing programmes. This three day course will help you understand how CRM can help your business and give you the practical skills to apply and assess CRM techniques in the real world.</p> <p>Econsultancy’s intensives are three-day programmes offering you a deep dive into specific digital disciplines. With content drawn from our academically accredited digital certificates, the intensives offer the practical training without the need for long term commitment.</p> <p>Intensives:</p> <ul> <li>Are led by practitioner trainers</li> <li>Include access to resources to support the training</li> <li>Allow delegates to implement and evaluate what they’ve learnt through ‘homework’ and trainer feedback after training</li> <li>Lead to an Econsultancy certificate of completion</li> </ul> tag:www.econsultancy.com,2008:TrainingDate/3162 2017-03-21T11:14:13+00:00 2017-03-21T11:14:13+00:00 eCRM <p>The principles of traditional, offline-focussed, Customer Relationship Management are not up to the challenge of new web channels, social media and mobile engagements. This course will take you through the essentials of the new approach to eCRM - enabling you to execute a high performance CRM solution that drives revenue.</p> tag:www.econsultancy.com,2008:BlogPost/68573 2016-11-30T11:01:07+00:00 2016-11-30T11:01:07+00:00 Seven examples of Black Friday email marketing from retailers Nikki Gilliland <p>Following on from our article on <a href="https://econsultancy.com/blog/68557-how-uk-retailers-are-promoting-black-friday-online" target="_blank">how UK brands promoted the event online</a>, here’s how seven retailers executed their email marketing campaigns.</p> <h3>ASOS</h3> <p>Let's kick off with one of the best of the bunch.</p> <p>ASOS executed a pretty heavy email campaign, first mentioning the event nearly an entire week beforehand.</p> <p>While this might sound a little excessive, the emails are still quite subtle, designed to build excitement and get customers in the mood.</p> <p><img src="https://assets.econsultancy.com/images/0008/1844/Black_Friday_warm_up.JPG" alt="" width="450" height="424"></p> <p>When the real event finally kicked off, ASOS used a discount code with the promise of 20% off all items.</p> <p>Just imagine the regret if you forgot to enter the code at the checkout...</p> <p><img src="https://assets.econsultancy.com/images/0008/1845/ASOS_code.JPG" alt="" width="450" height="436"></p> <p>It also promoted the Black Friday offer on top of an existing sale of 'up to 70%'.</p> <p>It's not clear whether the items here were any good, but the email copy sure does makes you want to go and have a look.</p> <p><img src="https://assets.econsultancy.com/images/0008/1849/ASOS_extra.JPG" alt="" width="450" height="199"></p> <p>Likewise, ASOS's subject lines were nicely done, reinforcing the brand's young and conversational tone of voice.</p> <p><img src="https://assets.econsultancy.com/images/0008/1846/Asos_subject_lines.JPG" alt="" width="500" height="139"></p> <p><em>For more on ASOS, read our post on <a href="https://econsultancy.com/blog/67950-eight-ecommerce-checkout-design-features-that-make-asos-great/" target="_blank">eight checkout design features that make its site great.</a></em></p> <h3>House of Fraser</h3> <p>Unlike ASOS's strong but subtle approach, House of Fraser went overboard on the emails this year, as shown in the screenshot of my inbox below.</p> <p><img src="https://assets.econsultancy.com/images/0008/1850/House_of_Fraser_emails.JPG" alt="" width="300" height="508"></p> <p>The actual emails were fine - they nicely promoted the array of discounts on offer.</p> <p>It's just a shame they were sent every day for a week, which could be enough to put off even the most loyal customers.</p> <p><img src="https://assets.econsultancy.com/images/0008/1851/HoF_email.JPG" alt="" width="450" height="595"></p> <p>On the plus side, despite going down to 30% off, the emails become get more targeted as the week wore one.</p> <p>The one below obviously takes into account my previous interest in womenswear.</p> <p><img src="https://assets.econsultancy.com/images/0008/1852/HoF_30_.JPG" alt="" width="450" height="544"></p> <h3>Zara</h3> <p>In contrast to the aforementioned example, Zara took a very restrained approach, only sending out two emails in total.</p> <p><img src="https://assets.econsultancy.com/images/0008/1853/Zara_black_friday.JPG" alt="" width="450" height="613"></p> <p>As well as being underwhelming (in terms of the discount and the creative) - the subject lines were pretty boring to say the least.</p> <p>With no indication of how big the offer or how long it'd be on for, I'd be surprised if it received many click-throughs.</p> <p><img src="https://assets.econsultancy.com/images/0008/1854/Zara_subject_lines.JPG" alt="" width="430" height="139"></p> <p><em>For more on Zara, read <a href="https://econsultancy.com/blog/67581-six-reasons-i-love-zara-com-and-a-few-reasons-i-don-t/" target="_blank">'Six reasons I love Zara.com (and a few reasons I don't)'</a></em></p> <h3>John Lewis</h3> <p>Surprisingly, John Lewis wasn't very impressive either.</p> <p>Again, with no indication of the amount of money customers might save, it doesn't give much incentive to click through.</p> <p><img src="https://assets.econsultancy.com/images/0008/1855/John_Lewis_black_friday.JPG" alt="" width="450" height="563"></p> <p>Another thing I found interesting was that its Sunday email - sent when the weekend event was still running - used an entirely unrelated subject line.</p> <p>This was despite the fact that the email itself was Black Friday related.</p> <p>Maybe the retailer was trying to be subtle? It just felt a bit misjudged to me,</p> <p><img src="https://assets.econsultancy.com/images/0008/1857/John_Lewis_subject_lines.JPG" alt="" width="450" height="121"></p> <p>However, with John Lewis <a href="https://econsultancy.com/blog/68512-john-lewis-combines-tv-ad-with-snapchat-lens-and-email/" target="_blank">traditionally more focused on Christmas</a>, perhaps Black Friday was deliberately underplayed.</p> <p><img src="https://assets.econsultancy.com/images/0008/1856/John_Lewis_black_friday_2.JPG" alt="" width="430" height="528"></p> <h3>H&M</h3> <p>H&M's emails on and around Black Friday were strong.</p> <p>With a bold and concise message of 20% off plus free delivery - customers were left in no doubt as to what they could expect.</p> <p><img src="https://assets.econsultancy.com/images/0008/1858/H_M_black_friday.JPG" alt="" width="450" height="546"></p> <p>Furthermore, I also like the fact that its emails included editorial-inspired content, motivating customers with how they could style their bargains rather than just promoting the sale.</p> <p><img src="https://assets.econsultancy.com/images/0008/1859/H_M_2.JPG" alt="" width="450" height="569"></p> <p>The only factor that let H&M down was its slightly dull subject lines.</p> <p>Not bad - just a bit lacklustre. Still, at least they're concise.</p> <p><img src="https://assets.econsultancy.com/images/0008/1861/H_M_subject_line.JPG" alt="" width="450" height="114"></p> <h3>Debenhams</h3> <p>On to Debenhams, and it demonstrated a good amount of variety in its emails.</p> <p><img src="https://assets.econsultancy.com/images/0008/1862/Debehams_black_friday.JPG" alt="" width="400" height="559"></p> <p>As well as giving customers a heads up on what was to come, it also included original content, such as a 'Top 10' deal countdown and editorial-inspired imagery.</p> <p><img src="https://assets.econsultancy.com/images/0008/1863/Debenhams_2.JPG" alt="" width="380" height="287"></p> <p>By incorporating more variety into its messaging, it feels less salesy, meaning customers are less likely to dismiss it as Black Friday noise.</p> <p><img src="https://assets.econsultancy.com/images/0008/1864/Debenhams_3.JPG" alt="" width="400" height="550"></p> <p>You can read how Debenhams' site redesign led to ecommerce sales growth <a href="https://econsultancy.com/blog/66644-how-debenhams-site-redesign-led-to-ecommerce-sales-growth/" target="_blank">in this article</a>.</p> <h3>Threadless</h3> <p>Finally, an interesting approach from US retailer Threadless.</p> <p>On the Wednesday before the event, it sent out this email offering an exclusive 40% off code that expired before the Black Friday deals began.</p> <p>While this might sound like it'd have limited impact as people would just hold out for Black Friday, it's obviously an attempt to foster customer loyalty for the long-term.</p> <p><img src="https://assets.econsultancy.com/images/0008/1869/Personal_email_threadless.JPG" alt="" width="500" height="454"></p> <p>By using a personal tone - even sending it from the Founder of the company - it is designed to make customers feel valued.</p> <p>A refreshing surprise just before Black Friday hit, it made for one of the most memorable emails of the week.</p> <p><img src="https://assets.econsultancy.com/images/0008/1871/Threadless_email.JPG" alt="" width="370" height="147"></p> <p>On to the actual Black Friday emails, and Threadless promoted it with a Christmas-themed creative.</p> <p>This could also prove effective for getting customers to think about the festive period (and why they might want to come back again soon).</p> <p><img src="https://assets.econsultancy.com/images/0008/1868/Threadless_creative_2.JPG" alt="" width="450" height="487"></p> <p>Finally, hats off to the brand for including an original and humourous subject line in its Cyber Monday email.</p> <p><img src="https://assets.econsultancy.com/images/0008/1866/Threadless_subject_line_2.JPG" alt="" width="450" height="123"></p> tag:www.econsultancy.com,2008:BlogPost/68507 2016-11-15T14:36:49+00:00 2016-11-15T14:36:49+00:00 Which vertical sector is the king of the hill for email marketing? Henry Hyder-Smith <p>In addition, 10 years of increased integration between the technologies and channels used now means better segmentation, increasingly sophisticated personalisation and customer-driven marketing.</p> <p>However, in order to make such a tactics and strategy analysis more useful for marketers it’s important to drill down until we reach the sector level.</p> <p>This way marketers can learn from each other and even cherry pick (and test) good ideas that already work in other sectors.</p> <p>Using data collected for the Adestra/Econsultancy Email Marketing Industry Census 2016 – a survey of over 1,100 digital marketers around the world - we looked at the top six sectors: Retail/Mail Order, Print/Publishing & Media, Charities/Government & Non-profits, Financial Services & Insurance, Travel & Hospitality and Technology & Telecoms.</p> <p>We analysed each sector to see which are producing the best return for the budget they spend on email, the tactics and strategies they use, the time spent on them, how they focus on mobile and implement automation, and finally their outlook on the future.</p> <p>I’ve picked three sectors from the report which are notable for being best performing, most improved and showing most growth potential.</p> <h4><strong>Print, publishing & media</strong></h4> <p>Yet again, the Print, Publishing & Media industry has produced consistent results across the board. Publishers have seen email performance shoot up since last year (see fig.1), and they top the chart for total sales attributable to the email channel.</p> <p>They make use of the broadest number of ESP services and lead the pack in optimising email for mobile. It’s not surprising then that there is no other sector that feels more love for their ESP.</p> <p><em>Fig.1 How do you rate the performance of your company’s email campaigns? (Results show Excellent or Good)</em></p> <p><img src="https://assets.econsultancy.com/images/resized/0008/1327/2016_email_performance_sector_census-blog-flyer.png" alt="Email performance 2016 Sector Census" width="470" height="376"></p> <h4><strong>Charities, Government & Not-for-Profits</strong></h4> <p>From mediocre results last year, the sector with the biggest turnaround has to be Charities, Government & NFP. Their ROI is consistently higher (and now tops the chart at 84%, excellent/good ROI – see Fig.2), email performance has skyrocketed and more time is now spent on strategic activities.</p> <p><em>Fig.2 How do you rate the email channel in terms of return on investment? (Results show Excellent or Good)</em></p> <p><em><img src="https://assets.econsultancy.com/images/resized/0008/1329/2016_roi_sector_census-blog-flyer.png" alt="Email ROI 2016 Sector Census" width="470" height="329"></em></p> <h4><strong>Retail/ Mail Order</strong></h4> <p>ROI has grown considerably from last year for the Retail/Mail Order sector, and email performance is just keeping above the overall email industry average.</p> <p>Retailers also score above the industry average for mobile optimisation strategy. While they are keeping time spent on tactical activities down, they have however lost a little focus on strategy.</p> <p>Their use of tactics overall has dropped back since last year, however firms have seen modest improvements in success when implementing automated email programmes. With an eye on the future, retailers are the most innovative sector (see Fig.3), and feel most strongly about innovating with creative behavioural triggers.</p> <p><em>Fig.3 How do you intend to innovate with email in 2016?</em></p> <p><em><img src="https://assets.econsultancy.com/images/resized/0008/1328/2016_innovation_sector_census-blog-flyer.png" alt="Email Innovation 2016 Sector Census" width="470" height="339"></em></p> <h4><strong>And the king of the hill is…?</strong></h4> <p>Publishers have produced the most consistent results across the board, while charities have shown a huge upswing in both return and performance as they get to grips with more email tactics and strategies. Travel firms too have upped their game as they adopt more email tactics, data services and mobile optimisation techniques.</p> <p>Retail performance is largely middle of the road, however the sector has a great future potential if it can focus its efforts. While finance firms have experienced a rise in email performance, they are let down by not embracing email tactics or ESP services, and have low email optimisation strategies.</p> <p>Similarly, with few highpoints, tech companies are often trailing the pack in terms of how they use email and (predictably) the return it produces.</p> <p>While we can still highlight individual improvements across the board, some sectors need to use the experience and successes of their peers and look at the opportunities, services and tactics available to really make the email channel work harder for them.</p> <p>It might seem an uphill battle, but experimentation and testing are the name of the game.</p> <p><em>Subscribers can download the full <a href="https://econsultancy.com/reports/email-census/">Email Marketing Census 2016</a>.</em></p> tag:www.econsultancy.com,2008:BlogPost/68391 2016-10-13T01:00:00+01:00 2016-10-13T01:00:00+01:00 Ten ways to freshen-up your email marketing Jeff Rajeck <p>So, though it seems like email is working well, companies are not increasing investment in the channel.</p> <p> <img src="https://assets.econsultancy.com/images/0008/0002/1.png" alt="" width="701" height="340"></p> <p>One potential reason for this is that email is a legacy technology and many marketers have become comfortable with how it fits into their organisations.</p> <p><img src="https://assets.econsultancy.com/images/0008/0003/2.png" alt="" width="616" height="379"></p> <p>To others, though, email marketing is still evolving and<strong> there are a number of new best practices which can help even the most jaded email marketer.</strong></p> <p>To find out more about these, we spoke to a number of marketers about email at our recent Digital Cream Sydney and asked for ways to 'freshen-up' a stale email marketing programme.</p> <p>Here are ten tips provided by client-side marketers on the day.</p> <h3>1. Email marketing is a value exchange</h3> <p>One of the first things participants pointed out is that consumers are becoming much more savvy in managing their emails. Often, they pointed out, people have multiple email accounts to manage and ignore commercial emails.</p> <p>Because of this, email marketers should no longer send emails with a simple call-to-action and hope for the best. </p> <p>Instead, marketers should treat an email as a 'value exchange'. This means that every email sent should answer the customer's unspoken question, 'what's in it for me'. </p> <p>Special offers, exclusive content, and event invites all provide this, according to attendees.</p> <p><img src="https://assets.econsultancy.com/images/0008/0004/email-2.jpg" alt="" width="800" height="533"></p> <h3>2. Email content must be engaging</h3> <p>In addition to providing value to get clicks and opens, marketers must also provide engaging content in order to be read.</p> <p>According to a <a href="https://litmus.com/blog/mobile-friendly-email-september-2016-email-market-share">recent report by Litmus</a>, <strong>email is most often opened on a mobile device.</strong></p> <p>Because of this, noted one participant, <strong>emails are not only in competition with other emails but with everything else available on mobile.</strong></p> <p>So, when writing emails, keep your user's short attention span in mind and make sure that the content is sharp, relevant, and to the point.</p> <h3>3. Use social media to build email lists</h3> <p>Attendees said that organisations still struggle to get email addresses from potential customers.</p> <p>While buying email addresses is now completely out of the question, many are wondering what to do to increase the size of their list.</p> <p>One participant said that social media can help. </p> <p>First off, educational advertising on social media helps drive high-quality traffic to the site. Then offering a free service or valuable information in exchange for an email address can help increase the list size.</p> <p>Also, <strong>if users need to login to your site for any reason</strong><strong>, use a social login.</strong> Then you should be able to get their email address as well as some demographic information.</p> <p>In either case, another noted, the organisation should still use an opt-in email in order to ensure that the customer is okay receiving promotional emails in the future.</p> <p><img src="https://assets.econsultancy.com/images/0008/0005/email-3.jpg" alt="" width="800" height="533"></p> <h3>4. Marketers need to get email data under control</h3> <p>Another way companies can improve their email marketing programmes is to look at the data that they use to measure effectiveness.</p> <p>With so many departments having access to email, <strong>there is often no visibility in an organisation about how many times a customer has been emailed.</strong> </p> <p>This means that marketers have no way to gauge 'email fatigue', one of the most common reasons for unsubscribes.</p> <p>Also, another participant pointed out, <strong>most organisations do not have clarity on what click, open, and unsubscribe rates they should aim for.</strong> </p> <p>Some do use industry benchmarks, but attendees felt that these were too general.</p> <p>Email marketers should lead the way on the benchmarks and ensure that everyone who uses email knows what data and targets they should aim for and how they can help to avoid over-emailing customers.</p> <h3>5. A/B testing makes a big difference</h3> <p>Delegates were all enthusiastic about the positive effects of using A/B testing in their email marketing programmes.</p> <p>Things marketers test include: </p> <ul> <li>Email receiver's name.</li> <li>Subject line.</li> <li>Amount of content.</li> <li>CTAs.</li> <li>Frequency. </li> </ul> <p>Out of all those, participants felt that subject line was probably the most important and encouraged others to make testing that a general practice.</p> <h3>6. Use responsive design and video in emails</h3> <p>Emails have changed a lot in the past few years. Now that many people view them on mobile email clients which support rich media, they can include HTML5 design, graphics, and even video.</p> <p><strong>Participants agreed that better-looking emails tend to perform better,</strong> but urged marketers to test emails on multiple platforms.</p> <p>One attendee noted that many email platforms still do not use responsive design as standard and so emails may not render correctly.</p> <p>Another delegate said that video has worked very well for their company, but added that <strong>all video in emails should have subtitles as well as audio.</strong></p> <p> <img src="https://assets.econsultancy.com/images/0008/0006/email-4.jpg" alt="" width="800" height="533"></p> <h3>7. Use preference centres, but be careful</h3> <p>Participants said that email marketers should use web pages where customers can update their preferences, also known as 'preference centres'.</p> <p>They can help brands keep subscribers who were about to unsubscribe and get feedback from those who do.</p> <p>Poorly-designed preference centres, however, can cause customer frustration. </p> <p>Delegates warned that <strong>requiring customers to login to make changes or offering overwhelming options can turn what should delight customers into something which destroys brand loyalty.</strong></p> <h3>8. All employees who use email marketing should be trained</h3> <p>As email marketing has become more widely-understood in organisations, the use of the channel has become more widespread.</p> <p>What this means is that in many organisations, people who are not familiar with marketing principles often send out campaigns without abiding to the principles of good data management and integrity.</p> <p>At best this means that customers will get too many irrelevant emails and at worst, one participant warned, the organisation may be blocked by major email providers for spam.</p> <p>Because the stakes are so high, <strong>anyone who has permission to launch a campaign should be trained in email marketing</strong>. </p> <p>At the very least they should understand email design, copywriting, audience management, and relevant spam laws.</p> <p><img src="https://assets.econsultancy.com/images/0008/0007/email-1.jpg" alt="" width="800" height="533"></p> <h3>9. Enterprise-grade email systems are becoming standard</h3> <p>Most participants on the day said that they use, or are in the process of buying, enterprise-grade email systems.</p> <p>Products mentioned included Salesforce, Oracle, and Adobe all of whom include email within their marketing clouds. </p> <p>Mailchimp was mentioned as a high-quality product for those companies who do not send massive amounts of emails.</p> <p>Along with buying these systens though, attendees said that <strong>marketing teams need to allocate resources to learn and use the system properly.</strong></p> <p>Without proper training, one warned, the advantages of having an enterprise-grade email system will not be realised.</p> <h3>10. Email is not the future</h3> <p>Interestingly, many delegates were keen to point out that email is a legacy technology and will probably not grow in influence.</p> <p>This is because consumers now have so many other ways to find information out about brands and keep in touch with customer service.</p> <p>This means that <strong>email marketers should start to see what other services they can integrate with emails</strong>, such as <a href="https://econsultancy.com/blog/64255-why-do-online-retailers-need-live-chat/">online chat</a>, in order to keep their skills current.</p> <p>That said, another participant pointed out that email will probably never go away completely.</p> <p>To back that up, they pointed out that we still receive physical, direct mail from brands to this day.</p> <h3>A word of thanks</h3> <p>Econsultancy would like to thank all of the marketers who participated on the day and especially the moderator at the Email Marketing table, <strong>Monica Villate Escobar, Marketing Manager at Ventura Health</strong>.</p> <p>We hope to see you all at future Sydney Econsultancy events!</p> <p><img src="https://assets.econsultancy.com/images/0007/9893/hosts.jpg" alt="" width="800" height="533"></p> tag:www.econsultancy.com,2008:BlogPost/67395 2016-01-13T02:09:00+00:00 2016-01-13T02:09:00+00:00 Three things email marketing leaders do regularly [APAC case studies] Jeff Rajeck <p>In our recent <a href="https://econsultancy.com/reports/email-census">Email Marketing Industry Census 2015</a>, we discovered that email marketing is still a very popular strategy for brands globally.</p> <p>One reason for this is that email marketing offers great return on investment (ROI). </p> <p>Two-thirds (66%) of marketers felt that their email marketing ROI was better than average, and less than one in ten (7%) of those surveyed felt it was 'poor'.</p> <p><img src="https://assets.econsultancy.com/images/resized/0007/0595/roi_from_channels-blog-flyer.png" alt="" width="470" height="414"></p> <p>The same group also felt very positive about email marketing's future. The vast majority (78%) disagreed with the statement 'Email marketing will be redundant in five years' and only 9% agreed.</p> <p>So as email marketing is maintaining its popularity, it's useful to review the state of the art occasionally for some best practices.</p> <p>And though it's interesting just to see what everyone else is doing, it's also good to use these best practices to review your own email marketing and see if it is up to scratch.</p> <p>So, for your review and reflection, here are three things which Asia-Pacific email marketing leaders do regularly, each with a relevant case study.</p> <h3>1. They come up with a strategy first, then tactics</h3> <p>When thinking about all the things that you can do with email, it's easy to focus on the tactics. Tactics, after all, are where you provide value to the customer and get metrics to report upwards.</p> <p>And there are plenty of guides to help you with tactics. You can find dozens of blog posts telling you <a href="https://econsultancy.com/blog/64878-45-words-to-avoid-in-your-email-marketing-subject-lines/">how to write a better subject line</a> or about <a href="https://econsultancy.com/blog/62688-six-case-studies-and-infographics-on-the-optimal-time-to-send-emails/">the optimal time to send emails</a>.</p> <p>But without a good strategy, it's hard to know which tactics to use.</p> <p>And once your campaign is finished, it's much harder to analyse the effectiveness without referring to the original strategy.</p> <h4>OK, but what is an email marketing strategy?</h4> <p>There are many types of marketing strategies, but for email marketing one of the best is the segmenting, targeting, and positioning (or STP) approach.</p> <p>For a full explanation of STP, there are excellent resources available (<a href="http://www.slideshare.net/crisanthony/plenus-stp">here's one</a>), but here is a short description of how STP relates to email marketing.</p> <p>There are three steps to this approach: </p> <ol> <li> <strong>Segment</strong>: Divide your email list into exhaustive and mutually exclusive segments.</li> <li> <strong>Target</strong>: Decide which of your offers is most appropriate for each segment.</li> <li> <strong>Position</strong>: Then plan to communicate the value your offer provides to the targeted segment.</li> </ol> <p>How you execute on the strategy, the tactics, should be geared towards capturing the information you need to segment and delivering your offer to the intended target.</p> <p>It's fairly simple, but too often marketing departments lose sight of their original strategy and execute tactics without knowing why they are doing it.</p> <h4>Thai Airways: Strategy in practice</h4> <p>A good example of a company that had a <a href="https://www.marketingmag.com.au/hubs-c/jetting-towards-brand-loyalty/">clear strategic vision ahead of a tactical email marketing campaign</a> is Thai Airways.</p> <p>In order to re-activate its Australian customer base, Thai Airways sent an email to its Australian customers about a contest to win a free trip. </p> <p>To enter the contest, though, participants had to tell Thai Airways when they were available to travel.</p> <p>But instead of just using this data for the contest, Thai airways then segmented its customer base using the customers' preferred travel dates.</p> <p>Then, it sent targeted emails to each segment with an offer positioned to appeal to each customer's personal travel time frame.</p> <p>In short, Thai Airways </p> <ol> <li>Segmented its customers by travel date preference.</li> <li>Targeted those customers with a travel offer relevant to their preferences.</li> <li>Positioned the fare using a personalized email highlighting the offer and the travel dates.</li> </ol> <p> <img src="https://assets.econsultancy.com/images/0007/0596/Picture4.png" alt="" width="389" height="656"></p> <p>The results were great. Through using STP Thai Airways was able to increase the average open rate of its emails to 40%, well above the Australian industry standard of 16 to 24%.</p> <p>But more interesting than the results is how the team at Thai Airways: </p> <ul> <li>Thought about what product they wanted to position (time-sensitive travel deals),</li> <li>Worked out how to get the data they needed to segment their email list,</li> <li>And executed using a personalized email. </li> </ul> <p>Thai Airways truly executed a strategy-driven, tactical campaign.</p> <h3>2. They use customer behaviour to trigger emails</h3> <p>Brands gather customer data in other ways besides surveys though, too. Many companies are now using customer behaviour in order to better segment and target their customer base.</p> <p>For example, many businesses now send emails to customers who have 'abandoned' an online shopping cart on their site. </p> <p>Our email survey indicated that nearly two in five (37%) used this tactic in 2015, nearly twice as many who did so in 2013 (20%).</p> <p>But there are other behaviors which can used to trigger an email to improve customer experience. </p> <h4>Zuji's behavioural approach</h4> <p>Zuji, an Asian online travel site, <a href="http://www.experian.com.sg/resources/zuji-case-study-overview.html">sends emails which are triggered by browsing behaviour on its website</a>. </p> <p>That is, when someone registered at Zuji clicks on a link or conducts a flight search, Zuji records the behavior and associates it with the person's email.</p> <p>Then, should Zuji's algorithm determine that the customer needs more information or perhaps a special offer, Zuji's email systems sends a personalized message.</p> <p>According to a recent case study, using behavioural emails resulted in a 50-fold improvement on revenue per thousand emails.</p> <p><img src="https://assets.econsultancy.com/images/resized/0007/0597/capture-blog-flyer.png" alt="" width="470" height="467"></p> <p>But more than just increasing revenue, personalized emails are also a great way of improving the customer experience.</p> <p>Getting relevant, personalized information when you're in the research stage is almost always welcomed by customers. </p> <p>And it's not surprising that doing so led to more sales for Zuji.</p> <h3>3. They keep their email list clean</h3> <p>And finally, in order for these programs to work continuously, top brands put a lot of effort into keeping their mailing list clean.</p> <p>One big part of maintaining a clean email list is monitoring the bounces when you send a campaign. </p> <p>Just in case you weren't aware, every email campaign should have a 'bounce report' which tells you why an email couldn't be delivered to one of your customers.</p> <p>Sometimes, things happen out of your control. The customer may have closed their account or moved jobs. Or the company may have gone out of business and the domain is now invalid.</p> <p>But quite often you can fix the problem. The bounce may have been caused by a misspelling or the addition of an invalid character, such as a space. </p> <p>If you monitor your bounce report regularly, you can fix these manually and 'rescue' the email address quickly.</p> <p>But more serious problems can be identified from the bounce report, as well. </p> <p>Your domain may have been, unknowingly, blacklisted by a major email provider such as Hotmail or Gmail. This means that your emails will either be delivered to spam folders for people who use those services, or not at all.</p> <h4>Estée Lauder: Improving deliverability</h4> <p>Estée Lauder in Malaysia <a href="http://www.experian.com.my/assets/resources/case-studies/estee-lauder-malaysia-case-study.pdf">had a big problem</a>. Its emails had a bounce rate of 14.1% on average and ran as high as 21.6%. This meant that, at times, Estée Lauder was not able to deliver email to one in five people on its list!</p> <p>To improve deliverability, Estée Lauder implemented new email software (CheetahMail) and went to work on reducing bounces.</p> <p>First, the system validated its existing list and then deployed a bounce management scheme which removed emails which frequently bounced.</p> <p>But another problem it addressed was deliverability. This involved working with a high-quality email service provider (ESP) who had good relationships with major email providers and making sure that all of their anti-spam policies were being followed.</p> <p>Then, the emails it sent were far more likely to be delivered to recipients in their inbox, and not as spam.</p> <p>The results were that Estée Lauder reduced its email bounce rate from over 10% to under 1%.</p> <p><img src="https://assets.econsultancy.com/images/resized/0007/0598/picture2-blog-flyer.jpg" alt="" width="470" height="473"></p> <p>Now, it is easy see this and think you don't have a problem with a bounces. Most companies already have bounce rates under 1%. </p> <p>But maintaining focus on deliverability is still important as every email which bounces is a lost opportunity for better ROI. </p> <p>In fact, cleaning your email list is probably one of the most underrated and effective email marketing tactics for improving ROI.</p> <p>It's also a great place for to start looking for issues if you feel like your email campaigns aren't working as well as they used to.</p> <h3>So...</h3> <p>Brands that do email marketing well tend to have strategies before tactics, use multiple data sources when targeting emails, and use many tactics to keep their email list clean.</p> <p>If you could only do one of these, though, conducting strategic analysis of your email list before executing tactics is probably the most important. </p> <p>You can try all the tricks to improve open and click rates through A/B testing subject lines and body copy, but a good strategy is a much better way to spend your scarce time and resources.</p> <p>This means segmenting your list into meaningful groups, coming up with offers specifically for the segment, and then positioning it in a way which appeals to them.</p> <p>Doing so is the shortest path to improving email marketing ROI and boosting your email marketing program up with the best in the industry.</p> tag:www.econsultancy.com,2008:BlogPost/67306 2015-12-10T11:10:00+00:00 2015-12-10T11:10:00+00:00 Is Pinterest or Instagram better for driving ecommerce? Georges Berzgal <p>However, what hasn’t always been obvious is how to convert these followers into sales.</p> <p>Both platforms recently developed new tools to more easily facilitate commerce across the board.</p> <p>So what are the inherent benefits of services like Pinterest and Instagram, and which provides the best platform for commerce?</p> <h3>Target audiences</h3> <p>It’s no secret that brands looking to target female consumers see the benefits of embracing social media.</p> <p><a href="http://www.entrepreneur.com/article/231970">Women are 10% more</a> likely than men to show brand support and 17% more likely to access offers on social media, although <a href="http://digitalmarketingmagazine.co.uk/social-media-marketing/is-the-social-buy-button-poised-to-take-off/2766">research found</a> that men are slightly more interested in purchasing directly on social networks by using a social buy button than women (33 % vs. 30%).</p> <p>All social media networks, bar LinkedIn, have more female users than male, although women’s domination of social media is not equally spread across all networks.</p> <p>Figures suggest that <a href="http://www.conversedigital.com/digital-strategy/should-my-company-be-on-instagram-or-pinterest">Pinterest’s users are 70% and Instagram’s users are 55% female.</a></p> <h3>Buyable Pins</h3> <p>Pinterest launched <a href="https://econsultancy.com/blog/66529-pinterest-enables-ecommerce-with-buyable-pins/">Buyable Pins</a> earlier this year, allowing consumers to purchase items without leaving the platform, and to pay using Apple Pay or credit cards.</p> <p>With a <a href="http://expandedramblings.com/index.php/pinterest-stats/">user base of 70m</a> made-up largely of consumers who are the most active and engaged, it’s no surprise that Pinterest is often seen as the social network with the highest potential for ecommerce.</p> <p><img src="https://assets.econsultancy.com/images/0006/9879/buyable_pins.jpg" alt="" width="700" height="466"></p> <h3>Instagram's buy button</h3> <p>However, the truth, as unveiled by research from member-based business intelligence firm L2, is that Instagram actually <a href="http://business.financialpost.com/investing/trading-desk/how-instagram-is-becoming-a-must-have-for-retailers?__lsa=6904-3bfd">has the highest browser-to-shopper conversion rate</a> of the social media outlets it tracks.</p> <p>This is all the more impressive considering that Instagram only allows brands to link to their website from their profile page.</p> <p><img src="https://assets.econsultancy.com/images/0006/9878/instagram_ads.jpg" alt="" width="700"></p> <p>The introduction of the Instagram ‘buy button’ sounded like a shift for the network.</p> <p>It is not available on regular Instagram posts yet, but limited to <a href="https://econsultancy.com/blog/66689-how-brands-are-using-instagram-ads/">the recently-introduced ad platform</a>.</p> <p>So if consumers see an item on the brand’s Instagram page they would like to purchase, they still have to search for the item on the retailer’s website to be able to buy it.</p> <h3>So, why is Instagram better at converting browsers to shoppers?</h3> <p>The answer is two-fold. What Pinterest promises is a channel through which brands can speak to women in a way that they like being spoken to.</p> <p>From our experience with clients, marketing messages with gender specific content are five times more successful than unisex messages.</p> <p>Brands understand the need to target consumers by gender, what seems odd is that brands are excited to segregate their female-targeted messages onto an entirely separate platform. </p> <p>Instagram, on the other hand, has a much more level gender split, allowing brands to target both men and women through the same platform by separating their content through gender specific accounts.</p> <p>Apparel retailers like Nike and ASOS are amongst the pioneers of this approach to Instagram, and it makes total sense. Why would you split your product by gender in-store, but then present it all together online?</p> <p><img src="https://assets.econsultancy.com/images/0006/9880/Screen_Shot_2015-12-10_at_11.08.21.png" alt="" width="700"></p> <p>It is more difficult for retailers to push their products openly on Instagram, which is the second, counter-intuitive reason why the platform is better for driving commerce.</p> <p>Brands publish content on Instagram that describes the lifestyle and culture of the company; it is the social network where retailers can forge an emotional connection with consumers.</p> <p>With our own customers we often see marketing messages with an absence of product promotion bringing in the most revenue.</p> <p>Messages promoting the culture behind the brand – be it a tie in with another brand or a connection to the local community – have proven to be extremely effective at driving engagement and revenue.</p> <p>Pinterest has been under pressure to bring commerce to the front of its platform for some time.</p> <p>Buyable pins move Pinterest towards becoming an aggregator of ecommerce, something akin to a digital shopping centre.</p> <p>This is by no means a bad thing, either for brands or consumers, but this evolution also moves Pinterest away from its social origins.</p> <p>Brands looking to tap into Instagram for ecommerce must keep in mind that the logical benefits of a product are often outweighed by a decision based on emotion.</p> <p>Social media allows brands to share their brand story in a way that retail space and owned websites often cannot offer, and for this reason a targeted Instagram account looks to be the better choice for driving revenue now, and potentially in the future.</p>
|
new icn messageflickr-free-ic3d pan white
Iceland - Strokkur - Geysir's Smaller Brother | by Ben124.
Back to photostream
Iceland - Strokkur - Geysir's Smaller Brother
There is only one Icelandic word used in the English language: geyser. Though the word refers to all geysers in general, it comes from a single geyser (in fact, the geyser) located in the South West of Iceland. Unfortunately, the Great Geysir has been somewhat shy in recent decades, though on special occasions it can sometimes be coaxed into a performance with some soap. When Geysir does perform, it lives up to its name, spraying a jet of steaming water 200 feet skyward. Far more reliable, though less spectacular, is nearby Strokkur (“the churn”), which spouts a 60-100 foot jet about once every five minutes. The geyser area is also rich in walking paths that lead past steaming vents and colourful, mineral-rich mud formations. The whole area is a geothermal park sitting on top of a vast boiling cauldron. Belching sulphurous mud pots of unusual colours, hissing steam vents, hot and cold springs, warm streams, and primitive plants can all be found here.
We stopped at the geothermal area of Geysir, the geyser for which all geysers are named. The famous Geysir now only erupts after large earthquakes and last erupted in 2000. Its little brother, Strokkur, erupts much more frequently, about 6-8 minutes apart. . People gather around the geyser and stare at the mouth, watching the water boil, in full anticipation with cameras ready. If you turn away, you’ll miss it. When you take a photo of one there are not that many ways to come up with unique composition. You can try a longer exposure of 1sec to give it slightly softer feel. You have to be ready even if it means standing still waiting for the eruption for up to 20 min with the camera in the right position. The geyser spouts upward close to 30 meter high and then it’s done. Sometimes there is a smaller spurt immediately before the large eruption.
Why does a geyser erupt?
What will become of Geysir?
The water level in the Geysir has been artificially lowered, but recent volcanic activity has reactivated it, so Geysir has somewhat found it's renewed life. Unfortunately, Geysir now erupts to no specific timetable.
24 faves
Taken on October 23, 2009
|
// Exercise10.20.cpp
// Ad
// Use count_if to rewrite the portion of our program that counted how many words are greater than length 6.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
std::vector<std::string> svec{"a", "asdfghj", "123", "uoiwersss"};
size_t sz{6};
auto cnt{count_if(svec.begin(), svec.end(), [sz](const std::string &s) { return s.size() > sz; })};
std::cout << cnt << std::endl;
// pause
system("pause");
return 0;
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include <stout/os/mkdir.hpp>
#include "uri/fetchers/hadoop.hpp"
using std::vector;
using std::set;
using std::string;
using process::Failure;
using process::Future;
using process::Owned;
namespace mesos {
namespace uri {
HadoopFetcherPlugin::Flags::Flags()
{
add(&Flags::hadoop_client,
"hadoop_client",
"The path to the hadoop client\n");
add(&Flags::hadoop_client_supported_schemes,
"hadoop_client_supported_schemes",
"A comma-separated list of the schemes supported by the hadoop client.\n",
"hdfs,hftp,s3,s3n");
}
const char HadoopFetcherPlugin::NAME[] = "hadoop";
Try<Owned<Fetcher::Plugin>> HadoopFetcherPlugin::create(const Flags& flags)
{
Try<Owned<HDFS>> hdfs = HDFS::create(flags.hadoop_client);
if (hdfs.isError()) {
return Error("Failed to create HDFS client: " + hdfs.error());
}
vector<string> schemes = strings::tokenize(
flags.hadoop_client_supported_schemes, ",");
return Owned<Fetcher::Plugin>(new HadoopFetcherPlugin(
hdfs.get(),
set<string>(schemes.begin(), schemes.end())));
}
set<string> HadoopFetcherPlugin::schemes() const
{
return schemes_;
}
string HadoopFetcherPlugin::name() const
{
return NAME;
}
Future<Nothing> HadoopFetcherPlugin::fetch(
const URI& uri,
const string& directory,
const Option<string>& data,
const Option<string>& outputFileName) const
{
// TODO(jieyu): Validate the given URI.
if (!uri.has_path()) {
return Failure("URI path is not specified");
}
Try<Nothing> mkdir = os::mkdir(directory);
if (mkdir.isError()) {
return Failure(
"Failed to create directory '" +
directory + "': " + mkdir.error());
}
// NOTE: We ignore the scheme prefix if the host in URI is not
// specified. This is the case when the host is set using the hadoop
// configuration file.
//
// TODO(jieyu): Allow user to specify the name of the output file.
return hdfs->copyToLocal(
(uri.has_host() ? stringify(uri) : uri.path()),
path::join(directory, Path(uri.path()).basename()));
}
} // namespace uri {
} // namespace mesos {
|
Why are we there?
Glastonbury Festival enjoys a relatively crime-free existence and some parts still hark back to the early days of peace, love and free milk. However, there will be more than 200,000 people at the festival. This is bigger than plenty of towns across the United Kingdom and no-one would question why those towns had police officers stationed there.
In a gathering of such size, there are unfortunately one or two bad apples and the police would be remiss not to have a presence at the festival and make sure that the vast majority of people enjoy a happy festival, with crime the last thing on their minds.
Policing Team 5
In all seriousness, a policing presence at the festival is essential to the granting of the licence needed to hold the festival.
After historic problems including public order, overcrowding, crime and safety problems, the festival had questions to answer from the police before a licence would be granted for another festival.
The solid steel fence which now surrounds the whole site was a massive step forward in public order and safety of those inside and outside the festival and has done a lot to make policing the festival an easier task.
However, the need for policing is still there, unfortunately there still is crime at the festival. There needn’t be though – with your help, we can make Glastonbury Festival all about peace and love, and not about who might nick your iPhone. Keep it safe, keep it hidden, keep it.
• To report non emergencies call 101 or report online
|
#include "addon_editor_plugin.h"
#include "editor_node.h"
void EditorAssetLibraryItem::configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost) {
title->set_text(p_title);
asset_id=p_asset_id;
category->set_text(p_category);
category_id=p_category_id;
author->set_text(p_author);
author_id=p_author_id;
price->set_text(p_cost);
for(int i=0;i<5;i++) {
if (i>2)
stars[i]->set_texture(get_icon("RatingNoStar","EditorIcons"));
else
stars[i]->set_texture(get_icon("RatingStar","EditorIcons"));
}
}
void EditorAssetLibraryItem::set_image(int p_type,int p_index,const Ref<Texture>& p_image) {
ERR_FAIL_COND(p_type!=EditorAddonLibrary::IMAGE_QUEUE_ICON);
ERR_FAIL_COND(p_index!=0);
icon->set_normal_texture(p_image);
}
void EditorAssetLibraryItem::_notification(int p_what) {
if (p_what==NOTIFICATION_ENTER_TREE) {
icon->set_normal_texture(get_icon("GodotAssetDefault","EditorIcons"));
category->add_color_override("font_color", Color(0.5,0.5,0.5) );
author->add_color_override("font_color", Color(0.5,0.5,0.5) );
}
}
void EditorAssetLibraryItem::_asset_clicked() {
emit_signal("asset_selected",asset_id);
}
void EditorAssetLibraryItem::_category_clicked(){
emit_signal("category_selected",category_id);
}
void EditorAssetLibraryItem::_author_clicked(){
emit_signal("author_selected",author_id);
}
void EditorAssetLibraryItem::_bind_methods() {
ObjectTypeDB::bind_method("set_image",&EditorAssetLibraryItem::set_image);
ObjectTypeDB::bind_method("_asset_clicked",&EditorAssetLibraryItem::_asset_clicked);
ObjectTypeDB::bind_method("_category_clicked",&EditorAssetLibraryItem::_category_clicked);
ObjectTypeDB::bind_method("_author_clicked",&EditorAssetLibraryItem::_author_clicked);
ADD_SIGNAL( MethodInfo("asset_selected"));
ADD_SIGNAL( MethodInfo("category_selected"));
ADD_SIGNAL( MethodInfo("author_selected"));
}
EditorAssetLibraryItem::EditorAssetLibraryItem() {
Ref<StyleBoxEmpty> border;
border.instance();
/*border->set_default_margin(MARGIN_LEFT,5);
border->set_default_margin(MARGIN_RIGHT,5);
border->set_default_margin(MARGIN_BOTTOM,5);
border->set_default_margin(MARGIN_TOP,5);*/
add_style_override("panel",border);
HBoxContainer *hb = memnew( HBoxContainer );
add_child(hb);
icon = memnew( TextureButton );
icon->set_default_cursor_shape(CURSOR_POINTING_HAND);
icon->connect("pressed",this,"_asset_clicked");
hb->add_child(icon);
VBoxContainer *vb = memnew( VBoxContainer );
hb->add_child(vb);
vb->set_h_size_flags(SIZE_EXPAND_FILL);
title = memnew( LinkButton );
title->set_text("My Awesome Addon");
title->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
title->connect("pressed",this,"_asset_clicked");
vb->add_child(title);
category = memnew( LinkButton );
category->set_text("Editor Tools");
category->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
title->connect("pressed",this,"_category_clicked");
vb->add_child(category);
author = memnew( LinkButton );
author->set_text("Johny Tolengo");
author->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
title->connect("pressed",this,"_author_clicked");
vb->add_child(author);
HBoxContainer *rating_hb = memnew( HBoxContainer );
vb->add_child(rating_hb);
for(int i=0;i<5;i++) {
stars[i]=memnew(TextureFrame);
rating_hb->add_child(stars[i]);
}
price = memnew( Label );
price->set_text("Free");
vb->add_child(price);
set_custom_minimum_size(Size2(250,100));
set_h_size_flags(SIZE_EXPAND_FILL);
set_stop_mouse(false);
}
//////////////////////////////////////////////////////////////////////////////
void EditorAddonLibraryItemDescription::set_image(int p_type,int p_index,const Ref<Texture>& p_image) {
switch(p_type) {
case EditorAddonLibrary::IMAGE_QUEUE_ICON: {
item->call("set_image",p_type,p_index,p_image);
} break;
case EditorAddonLibrary::IMAGE_QUEUE_THUMBNAIL: {
for(int i=0;i<preview_images.size();i++) {
if (preview_images[i].id==p_index) {
preview_images[i].button->set_icon(p_image);
}
}
//item->call("set_image",p_type,p_index,p_image);
} break;
case EditorAddonLibrary::IMAGE_QUEUE_SCREENSHOT: {
for(int i=0;i<preview_images.size();i++) {
if (preview_images[i].id==p_index && preview_images[i].button->is_pressed()) {
preview->set_texture(p_image);
}
}
//item->call("set_image",p_type,p_index,p_image);
} break;
}
}
void EditorAddonLibraryItemDescription::_bind_methods() {
ObjectTypeDB::bind_method(_MD("set_image"),&EditorAddonLibraryItemDescription::set_image);
}
void EditorAddonLibraryItemDescription::configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost,const String& p_description) {
item->configure(p_title,p_asset_id,p_category,p_category_id,p_author,p_author_id,p_rating,p_cost);
description->parse_bbcode(p_description);
set_title(p_title);
}
void EditorAddonLibraryItemDescription::add_preview(int p_id, bool p_video,const String& p_url){
Preview preview;
preview.id=p_id;
preview.video_link=p_url;
preview.button = memnew( Button );
preview.button->set_flat(true);
preview.button->set_icon(get_icon("ThumbnailWait","EditorIcons"));
preview.button->set_toggle_mode(true);
preview_hb->add_child(preview.button);
if (preview_images.size()==0)
preview.button->set_pressed(true);
preview_images.push_back(preview);
}
EditorAddonLibraryItemDescription::EditorAddonLibraryItemDescription() {
VBoxContainer *vbox = memnew( VBoxContainer );
add_child(vbox);
set_child_rect(vbox);
HBoxContainer *hbox = memnew( HBoxContainer);
vbox->add_child(hbox);
vbox->add_constant_override("separation",15);
VBoxContainer *desc_vbox = memnew( VBoxContainer );
hbox->add_child(desc_vbox);
hbox->add_constant_override("separation",15);
item = memnew( EditorAssetLibraryItem );
desc_vbox->add_child(item);
desc_vbox->set_custom_minimum_size(Size2(300,0));
PanelContainer * desc_bg = memnew( PanelContainer );
desc_vbox->add_child(desc_bg);
desc_bg->set_v_size_flags(SIZE_EXPAND_FILL);
description = memnew( RichTextLabel );
//desc_vbox->add_child(description);
desc_bg->add_child(description);
desc_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
preview = memnew( TextureFrame );
preview->set_custom_minimum_size(Size2(640,345));
hbox->add_child(preview);
PanelContainer * previews_bg = memnew( PanelContainer );
vbox->add_child(previews_bg);
previews_bg->set_custom_minimum_size(Size2(0,85));
previews_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
previews = memnew( ScrollContainer );
previews_bg->add_child(previews);
previews->set_enable_v_scroll(false);
previews->set_enable_h_scroll(true);
preview_hb = memnew( HBoxContainer );
preview_hb->set_v_size_flags(SIZE_EXPAND_FILL);
previews->add_child(preview_hb);
get_ok()->set_text("Install");
get_cancel()->set_text("Close");
}
////////////////////////////////////////////////////////////////////////////////
void EditorAddonLibrary::_notification(int p_what) {
if (p_what==NOTIFICATION_READY) {
_api_request("api/configure");
}
if (p_what==NOTIFICATION_PROCESS) {
}
}
const char* EditorAddonLibrary::sort_key[SORT_MAX]={
"rating",
"downloads",
"name",
"cost",
"updated"
};
const char* EditorAddonLibrary::sort_text[SORT_MAX]={
"Rating",
"Downloads",
"Name",
"Cost",
"Updated"
};
void EditorAddonLibrary::_select_author(int p_id) {
//opemn author window
}
void EditorAddonLibrary::_select_category(int p_id){
for(int i=0;i<categories->get_item_count();i++) {
if (i==0)
continue;
int id = categories->get_item_metadata(i);
if (id==p_id) {
categories->select(i);
_search();
break;
}
}
}
void EditorAddonLibrary::_select_asset(int p_id){
_api_request("api/asset","?id="+itos(p_id));
/*
if (description) {
memdelete(description);
}
description = memnew( EditorAddonLibraryItemDescription );
add_child(description);
description->popup_centered_minsize();*/
}
void EditorAddonLibrary::_image_request_completed(int p_status, int p_code, const StringArray& headers, const ByteArray& p_data,int p_queue_id) {
ERR_FAIL_COND( !image_queue.has(p_queue_id) );
if (p_status==HTTPRequest::RESULT_SUCCESS) {
print_line("GOT IMAGE YAY!");
Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
if (obj) {
int len=p_data.size();
ByteArray::Read r=p_data.read();
Image image(r.ptr(),len);
if (!image.empty()) {
Ref<ImageTexture> tex;
tex.instance();
tex->create_from_image(image);
obj->call("set_image",image_queue[p_queue_id].image_type,image_queue[p_queue_id].image_index,tex);
}
}
} else {
WARN_PRINTS("Error getting PNG file for asset id "+itos(image_queue[p_queue_id].asset_id));
}
image_queue[p_queue_id].request->queue_delete();;
image_queue.erase(p_queue_id);
_update_image_queue();
}
void EditorAddonLibrary::_update_image_queue() {
int max_images=2;
int current_images=0;
List<int> to_delete;
for (Map<int,ImageQueue>::Element *E=image_queue.front();E;E=E->next()) {
if (!E->get().active && current_images<max_images) {
String api;
switch(E->get().image_type) {
case IMAGE_QUEUE_ICON: api="api/icon/icon.png"; break;
case IMAGE_QUEUE_SCREENSHOT: api="api/screenshot/screenshot.png"; break;
case IMAGE_QUEUE_THUMBNAIL: api="api/thumbnail/thumbnail.png"; break;
}
print_line("REQUEST ICON FOR: "+itos(E->get().asset_id));
Error err = E->get().request->request(host+"/"+api+"?asset_id="+itos(E->get().asset_id)+"&index="+itos(E->get().image_index));
if (err!=OK) {
to_delete.push_back(E->key());
} else {
E->get().active=true;
}
current_images++;
} else if (E->get().active) {
current_images++;
}
}
while(to_delete.size()) {
image_queue[to_delete.front()->get()].request->queue_delete();
image_queue.erase(to_delete.front()->get());
to_delete.pop_front();
}
}
void EditorAddonLibrary::_request_image(ObjectID p_for,int p_asset_id,ImageType p_type,int p_image_index) {
ImageQueue iq;
iq.asset_id=p_asset_id;
iq.image_index=p_image_index;
iq.image_type=p_type;
iq.request = memnew( HTTPRequest );
iq.target=p_for;
iq.queue_id=++last_queue_id;
iq.active=false;
iq.request->connect("request_completed",this,"_image_request_completed",varray(iq.queue_id));
image_queue[iq.queue_id]=iq;
add_child(iq.request);
_update_image_queue();
}
void EditorAddonLibrary::_search(int p_page) {
String args;
args=String()+"?sort="+sort_key[sort->get_selected()];
if (categories->get_selected()>0) {
args+="&category="+itos(categories->get_item_metadata(categories->get_selected()));
}
if (filter->get_text()!=String()) {
args+="&filter="+filter->get_text().http_escape();
}
if (p_page>0) {
args+="&page="+itos(p_page);
}
_api_request("api/search",args);
}
HBoxContainer* EditorAddonLibrary::_make_pages(int p_page,int p_max_page,int p_page_len,int p_total_items,int p_current_items) {
HBoxContainer * hbc = memnew( HBoxContainer );
//do the mario
int from = p_page-5;
if (from<0)
from=0;
int to = from+10;
if (to>p_max_page)
to=p_max_page;
Color gray = Color(0.65,0.65,0.65);
hbc->add_spacer();
hbc->add_constant_override("separation",10);
LinkButton *first = memnew( LinkButton );
first->set_text("first");
first->add_color_override("font_color", gray );
first->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
first->connect("pressed",this,"_search",varray(0));
hbc->add_child(first);
if (p_page>0) {
LinkButton *prev = memnew( LinkButton );
prev->set_text("prev");
prev->add_color_override("font_color", gray );
prev->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
prev->connect("pressed",this,"_search",varray(p_page-1));
hbc->add_child(prev);
}
for(int i=from;i<=to;i++) {
if (i==p_page) {
Label *current = memnew(Label);
current->set_text(itos(i));
hbc->add_child(current);
} else {
LinkButton *current = memnew( LinkButton );
current->add_color_override("font_color", gray );
current->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
current->set_text(itos(i));
current->connect("pressed",this,"_search",varray(i));
hbc->add_child(current);
}
}
if (p_page<p_max_page) {
LinkButton *next = memnew( LinkButton );
next->set_text("next");
next->add_color_override("font_color", gray );
next->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
next->connect("pressed",this,"_search",varray(p_page+1));
hbc->add_child(next);
}
LinkButton *last = memnew( LinkButton );
last->set_text("last");
last->add_color_override("font_color", gray );
last->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
hbc->add_child(last);
last->connect("pressed",this,"_search",varray(p_max_page));
Label *totals = memnew( Label );
totals->set_text("( "+itos(from*p_page_len)+" - "+itos(from*p_page_len+p_current_items-1)+" / "+itos(p_total_items)+" )");
hbc->add_child(totals);
hbc->add_spacer();
return hbc;
}
void EditorAddonLibrary::_api_request(const String& p_request,const String& p_arguments) {
if (requesting!=REQUESTING_NONE) {
request->cancel_request();
}
current_request=p_request;
request->request(host+"/"+p_request+p_arguments);
}
void EditorAddonLibrary::_http_request_completed(int p_status, int p_code, const StringArray& headers, const ByteArray& p_data) {
String str;
{
int datalen=p_data.size();
ByteArray::Read r = p_data.read();
str.parse_utf8((const char*)r.ptr(),datalen);
}
print_line("response: "+itos(p_status)+" code: "+itos(p_code));
Dictionary d;
d.parse_json(str);
print_line(Variant(d).get_construct_string());
if (current_request=="api/configure") {
categories->clear();
categories->add_item("All");
categories->set_item_metadata(0,0);
if (d.has("categories")) {
Array clist = d["categories"];
for(int i=0;i<clist.size();i++) {
Dictionary cat = clist[i];
if (!cat.has("name") || !cat.has("id"))
continue;
String name=cat["name"];
int id=cat["id"];
categories->add_item(name);
categories->set_item_metadata( categories->get_item_count() -1, id);
}
}
_search();
} else if (current_request=="api/search") {
if (asset_items) {
memdelete(asset_items);
}
if (asset_top_page) {
memdelete(asset_top_page);
}
if (asset_bottom_page) {
memdelete(asset_bottom_page);
}
int page=0;
int pages=1;
int page_len=10;
int total_items=1;
Array result;
if (d.has("page")) {
page=d["page"];
}
if (d.has("pages")) {
pages=d["pages"];
}
if (d.has("page_length")) {
page_len=d["page_length"];
}
if (d.has("total")) {
total_items=d["total"];
}
if (d.has("result")) {
result=d["result"];
}
asset_top_page = _make_pages(page,pages,page_len,total_items,result.size());
library_vb->add_child(asset_top_page);
asset_items = memnew( GridContainer );
asset_items->set_columns(2);
asset_items->add_constant_override("hseparation",10);
asset_items->add_constant_override("vseparation",10);
library_vb->add_child(asset_items);
asset_bottom_page = _make_pages(page,pages,page_len,total_items,result.size());
library_vb->add_child(asset_bottom_page);
for(int i=0;i<result.size();i++) {
Dictionary r = result[i];
ERR_CONTINUE(!r.has("title"));
ERR_CONTINUE(!r.has("asset_id"));
ERR_CONTINUE(!r.has("author"));
ERR_CONTINUE(!r.has("author_id"));
ERR_CONTINUE(!r.has("category"));
ERR_CONTINUE(!r.has("category_id"));
ERR_CONTINUE(!r.has("rating"));
ERR_CONTINUE(!r.has("cost"));
EditorAssetLibraryItem *item = memnew( EditorAssetLibraryItem );
asset_items->add_child(item);
item->configure(r["title"],r["asset_id"],r["category"],r["category_id"],r["author"],r["author_id"],r["rating"],r["cost"]);
item->connect("asset_selected",this,"_select_asset");
item->connect("author_selected",this,"_select_author");
item->connect("category_selected",this,"_category_selected");
_request_image(item->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_ICON,0);
}
} else if (current_request=="api/asset") {
ERR_FAIL_COND(!d.has("info"));
Dictionary r = d["info"];
ERR_FAIL_COND(!r.has("title"));
ERR_FAIL_COND(!r.has("asset_id"));
ERR_FAIL_COND(!r.has("author"));
ERR_FAIL_COND(!r.has("author_id"));
ERR_FAIL_COND(!r.has("category"));
ERR_FAIL_COND(!r.has("category_id"));
ERR_FAIL_COND(!r.has("rating"));
ERR_FAIL_COND(!r.has("cost"));
ERR_FAIL_COND(!r.has("description"));
if (description) {
memdelete(description);
}
description = memnew( EditorAddonLibraryItemDescription );
add_child(description);
description->popup_centered_minsize();
description->configure(r["title"],r["asset_id"],r["category"],r["category_id"],r["author"],r["author_id"],r["rating"],r["cost"],r["description"]);
/*item->connect("asset_selected",this,"_select_asset");
item->connect("author_selected",this,"_select_author");
item->connect("category_selected",this,"_category_selected");*/
_request_image(description->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_ICON,0);
if (d.has("previews")) {
Array previews = d["previews"];
for(int i=0;i<previews.size();i++) {
Dictionary p=previews[i];
ERR_CONTINUE(!p.has("id"));
bool is_video=p.has("type") && String(p["type"])=="video";
String video_url;
if (is_video && p.has("link")) {
video_url="link";
}
int id=p["id"];
description->add_preview(id,is_video,video_url);
_request_image(description->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_THUMBNAIL,id);
if (i==0) {
_request_image(description->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_SCREENSHOT,id);
}
}
}
}
}
void EditorAddonLibrary::_bind_methods() {
ObjectTypeDB::bind_method("_http_request_completed",&EditorAddonLibrary::_http_request_completed);
ObjectTypeDB::bind_method("_select_asset",&EditorAddonLibrary::_select_asset);
ObjectTypeDB::bind_method("_select_author",&EditorAddonLibrary::_select_author);
ObjectTypeDB::bind_method("_select_category",&EditorAddonLibrary::_select_category);
ObjectTypeDB::bind_method("_image_request_completed",&EditorAddonLibrary::_image_request_completed);
ObjectTypeDB::bind_method("_search",&EditorAddonLibrary::_search,DEFVAL(0));
}
EditorAddonLibrary::EditorAddonLibrary() {
tabs = memnew( TabContainer );
tabs->set_v_size_flags(SIZE_EXPAND_FILL);
add_child(tabs);
installed = memnew( EditorPluginSettings );
installed->set_name("Installed");
tabs->add_child(installed);
Ref<StyleBoxEmpty> border;
border.instance();
border->set_default_margin(MARGIN_LEFT,15);
border->set_default_margin(MARGIN_RIGHT,15);
border->set_default_margin(MARGIN_BOTTOM,15);
border->set_default_margin(MARGIN_TOP,15);
PanelContainer *margin_panel = memnew( PanelContainer );
margin_panel->set_name("Online");
margin_panel->add_style_override("panel",border);
tabs->add_child(margin_panel);
VBoxContainer *library_main = memnew( VBoxContainer );
margin_panel->add_child(library_main);
HBoxContainer *search_hb = memnew( HBoxContainer );
library_main->add_child(search_hb);
library_main->add_constant_override("separation",20);
search_hb->add_child( memnew( Label("Search: ")));
filter =memnew( LineEdit );
search_hb->add_child(filter);
filter->set_h_size_flags(SIZE_EXPAND_FILL);
filter->connect("text_entered",this,"_search");
search = memnew( Button("Search"));
search->connect("pressed",this,"_search");
search_hb->add_child(search);
library_vb->add_child(search_hb);
HBoxContainer *search_hb2 = memnew( HBoxContainer );
library_main->add_child(search_hb2);
search_hb2->add_child( memnew( Label("Sort: ")));
sort = memnew( OptionButton );
for(int i=0;i<SORT_MAX;i++) {
sort->add_item(sort_text[i]);
}
search_hb2->add_child(sort);
sort->set_h_size_flags(SIZE_EXPAND_FILL);
reverse = memnew( CheckBox);
reverse->set_text("Reverse");
search_hb2->add_child(reverse);
search_hb2->add_child(memnew(VSeparator));
//search_hb2->add_spacer();
search_hb2->add_child( memnew( Label("Category: ")));
categories = memnew( OptionButton );
categories->add_item("All");
search_hb2->add_child(categories);
categories->set_h_size_flags(SIZE_EXPAND_FILL);
//search_hb2->add_spacer();
search_hb2->add_child(memnew(VSeparator));
search_hb2->add_child( memnew( Label("Site: ")));
repository = memnew( OptionButton );
repository->add_item("Godot");
search_hb2->add_child(repository);
repository->set_h_size_flags(SIZE_EXPAND_FILL);
/////////
PanelContainer * library_scroll_bg = memnew( PanelContainer );
library_main->add_child(library_scroll_bg);
library_scroll_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
library_scroll_bg->set_v_size_flags(SIZE_EXPAND_FILL);
library_scroll = memnew( ScrollContainer );
library_scroll->set_enable_v_scroll(true);
library_scroll->set_enable_h_scroll(false);
library_scroll_bg->add_child(library_scroll);
Ref<StyleBoxEmpty> border2;
border2.instance();
border2->set_default_margin(MARGIN_LEFT,15);
border2->set_default_margin(MARGIN_RIGHT,35);
border2->set_default_margin(MARGIN_BOTTOM,15);
border2->set_default_margin(MARGIN_TOP,15);
PanelContainer * library_vb_border = memnew( PanelContainer );
library_scroll->add_child(library_vb_border);
library_vb_border->add_style_override("panel",border2);
library_vb_border->set_h_size_flags(SIZE_EXPAND_FILL);
library_vb_border->set_stop_mouse(false);
library_vb = memnew( VBoxContainer );
library_vb->set_h_size_flags(SIZE_EXPAND_FILL);
library_vb_border->add_child(library_vb);
// margin_panel->set_stop_mouse(false);
asset_top_page = memnew( HBoxContainer );
library_vb->add_child(asset_top_page);
asset_items = memnew( GridContainer );
asset_items->set_columns(2);
asset_items->add_constant_override("hseparation",10);
asset_items->add_constant_override("vseparation",10);
library_vb->add_child(asset_items);
asset_bottom_page = memnew( HBoxContainer );
library_vb->add_child(asset_bottom_page);
request = memnew( HTTPRequest );
add_child(request);
request->connect("request_completed",this,"_http_request_completed");
last_queue_id=0;
library_vb->add_constant_override("separation",20);
description = NULL;
host="http://localhost:8000";
}
///////
void AddonEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
addon_library->show();
} else {
addon_library->hide();
}
}
AddonEditorPlugin::AddonEditorPlugin(EditorNode *p_node) {
editor=p_node;
addon_library = memnew( EditorAddonLibrary );
addon_library->set_v_size_flags(Control::SIZE_EXPAND_FILL);
editor->get_viewport()->add_child(addon_library);
addon_library->set_area_as_parent_rect();
addon_library->hide();
}
AddonEditorPlugin::~AddonEditorPlugin() {
}
|
/*
utils - utility library
Copyright (c) 2021-2022 on-keyday (https://github.com/on-keyday)
Released under the MIT license
https://opensource.org/licenses/mit-license.php
*/
// tokenizer - custom tokenizer for syntax
#pragma once
#include "../../tokenize/tokenizer.h"
#include "../../tokenize/merge.h"
#include "keyword.h"
#include "attribute.h"
namespace utils {
namespace syntax {
namespace tknz = tokenize;
namespace internal {
template <class String, template <class...> class Vec = wrap::vector>
tknz::Tokenizer<String, Vec> make_internal_tokenizer() {
tknz::Tokenizer<String, Vec> ret;
auto cvt_push = [&](auto base, auto& predef) {
String converted;
utf::convert(base, converted);
predef.push_back(std::move(converted));
};
for (size_t i = 0; i < sizeof(keyword_str) / sizeof(keyword_str[0]); i++) {
cvt_push(keyword_str[i], ret.keyword.predef);
}
cvt_push(":=", ret.symbol.predef);
cvt_push("[", ret.symbol.predef);
cvt_push("]", ret.symbol.predef);
cvt_push("|", ret.symbol.predef);
cvt_push("#", ret.symbol.predef);
cvt_push("\"", ret.symbol.predef);
cvt_push("\\", ret.symbol.predef);
cvt_push(attribute(Attribute::adjacent), ret.symbol.predef);
cvt_push(attribute(Attribute::fatal), ret.symbol.predef);
cvt_push(attribute(Attribute::ifexists), ret.symbol.predef);
cvt_push(attribute(Attribute::repeat), ret.symbol.predef);
return ret;
}
template <class T, class String, template <class...> class Vec = wrap::vector>
bool tokenize_and_merge(Sequencer<T>& input, wrap::shared_ptr<tknz::Token<String>>& output, const char** errmsg = nullptr) {
auto tokenizer = internal::make_internal_tokenizer<String, Vec>();
auto result = tokenizer.tokenize(input, output);
assert(result && "expect true but tokenize failed");
const char* err = nullptr;
auto res = tknz::merge(err, output, tknz::escaped_comment<String>("\"", "\\"),
tknz::line_comment<String>("#"));
if (errmsg) {
*errmsg = err;
}
return res;
}
} // namespace internal
} // namespace syntax
} // namespace utils
|
Date: August 2010
Creator: Allen, Evette L.
Description: Family communication has the potential to affect a variety of youth behavioral outcomes including adolescent sexual risk behavior. Within chapter 1, I present past literature on adolescent sexual risk behaviors, family communication patterns, and the gaps associated with those areas. In chapter 2, I review previous literature on adolescent sexual risk behavior, parent-child communication and family communication patterns. In chapter 3, I present the method which includes a description of the participants, procedures, measures, and data analysis used. In Chapter 4, I present the results of the study. According to the results of the study, father-child communication is not a better predictor of adolescent sexual risk behavior. A higher quantity of parent-child communication does not lead to less adolescent sexual risk behavior. Participants with a pluralistic family type do significantly differ from laissez-faire and protective family types in regards to levels of parent-child communication. Participants with a consensual family type do have significantly higher levels of parent-child communication in comparison to laissez-faire family types, but not protective family types. Finally, in chapter 5, I present the discussion with a review of previous research (consistent or inconsistent with the current findings), limitations and conclusions for the current study.
Contributing Partner: UNT Libraries
|
Born in 1940, Wangari Maathai is a Kenyan ecologist and environmental activist who founded the Green Belt Movement in 1977, causing the media to depict her as a latter-day Johnny Appleseed who has planted millions of trees in Africa. (The Green Belt Movement has been responsible for the planting of more than 10 million trees to prevent soil erosion and provide a source of firewood.)
As a member of the Green Belt Movement, Maathai has led sub-Saharan African women in provoking sometimes-violent clashes with police. Though casting herself as a hero of the downtrodden, she has demonstrated against peasants’ economic interests. When Kenyan autocratic leader Daniel arap Moi wanted to revive the nation’s dead economy by building the world’s largest skyscraper in the capital, her riotous actions dried up investment. Later, she led a protest to prevent “small-scale farming” on African forestland and called farmers “invaders” who were guilty of “rape.” In 1992, she and the women in her Green Belt Movement foreshadowed contemporary Western antiwar demonstrators by staging a public strip-in.
In 2004 she won the Nobel Peace Prize for her work in “human rights” and “reversing deforestation across Africa.”
When Maathai was awarded her Nobel Prize, United Nations Secretary-General Kofi Annan paid her a glowing tribute:
Maathai is also an anti-white, anti-Western crusader for international socialism. She charges that “some sadistic [white] scientists” created the AIDS virus “to punish blacks” and, ultimately, “to wipe out the black race.” Maathai continues:
“Renowned and admired throughout her native Kenya and across Africa for her pioneering struggle against deforestation and for women’s rights and democracy, Ms. Maathai has also played an important role at UN conferences such as the Earth Summit, making an imprint on the global quest for sustainable development.... Selfless and steadfast, Ms. Maathai has been a champion of the environment, of women, of Africa, and of anyone concerned about our future security.”
“Some say that AIDS came from the monkeys, and I doubt that, because we have been living with monkeys [since] time immemorial; others say it was a curse from God, but I say it cannot be that.... Us black people are dying more than any other people in this planet. It’s true that there are some people who create agents to wipe out other people.”
“Why is the rest of the world just watching,” Maathai asks, “doing nothing while Africans are being wiped out? The rest of the world has abandoned us.”
There is, of course, a very real genocide throughout sub-Saharan Africa, as Muslim Arabs murder indigenous black Christians and animists, 100,000 in Darfur alone. The repeated rape of young black boys by Arabs is now commonplace. These scenes first played out during the genocide in Rwanda, which began early in the Clinton administration, and have been seen all over the sub-continent for a decade. Maathai addressed this brutality at the World Women’s Conference in Beijing in 1995, where she blamed it on Western capitalists. She claims that Western governments laid the groundwork for present slaughter during the Cold War. “The carnage goes on in Somalia, Rwanda, Liberia and in the streets of many cities,” she says. “People of Africa continue to be sacrificed so that some factories may stay open, earn capital and save jobs.”
Thus in Maathai’s view, Arab genocide is the fault of wealthy whites.
Maathai has courted global socialism through her long association with the United Nations’ environmentalist agenda. She was a member of the Commission on Global Governance (CGG), founded in 1992 at the suggestion of former West German Chancellor and socialist Willy Brandt. Maathai worked on the CGG alongside Maurice Strong, Jimmy Carter, and Robert McNamara. The group’s manifesto, “Our Global Neighborhood,” calls for a dramatic reordering of the world’s political power – and redistribution of the world’s wealth.
Most importantly, the CGG’s proposals would phase out America’s veto in the Security Council. At the same time, the CGG would increase UN authority over member nations, declaring, “All member-states of the UN that have not already done so should accept the compulsory jurisdiction of the World Court.” It asks the UN to prevail upon member governments to enact proposals made by wide NGOs – such as the Green Belt Movement. “Our Global Neighborhood” also suggested creating a 10,000-man “UN Volunteer Force” to be deployed at the UN’s approval on infinite peacekeeping missions everywhere (except Iraq).
Maathai currently acts as a commissioner for the Earth Charter, along with the aforementioned Maurice Strong, Mikhail Gorbachev and Steven Rockefeller. She is also on the Earth Charter’s Steering Committee. In addition to calling for sharing the “benefits of development . . . equitably,” the Earth Charter calls on international bodies to “Promote the equitable distribution of wealth within nations and among nations.” Another Charter provision would disarm the entire world and use the money previously allocated for national defense to restore the environment. Additionally, the Earth Charter worries about the “unprecedented rise in human population,” and demands “universal access to health care.”
Maathai earned her biology degree from Mount St. Scholastica College in Kansas and a Master’s degree at the University of Pittsburgh. She later returned to Kenya and worked in veterinary medical research at the University of Nairobi, eventually earning a Ph.D. there and becoming head of the veterinary medicine faculty.
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/wisdom/ConnectWisdomService_EXPORTS.h>
#include <aws/wisdom/model/FilterField.h>
#include <aws/wisdom/model/FilterOperator.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ConnectWisdomService
{
namespace Model
{
/**
* <p>A search filter.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/wisdom-2020-10-19/Filter">AWS API
* Reference</a></p>
*/
class AWS_CONNECTWISDOMSERVICE_API Filter
{
public:
Filter();
Filter(Aws::Utils::Json::JsonView jsonValue);
Filter& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The field on which to filter.</p>
*/
inline const FilterField& GetField() const{ return m_field; }
/**
* <p>The field on which to filter.</p>
*/
inline bool FieldHasBeenSet() const { return m_fieldHasBeenSet; }
/**
* <p>The field on which to filter.</p>
*/
inline void SetField(const FilterField& value) { m_fieldHasBeenSet = true; m_field = value; }
/**
* <p>The field on which to filter.</p>
*/
inline void SetField(FilterField&& value) { m_fieldHasBeenSet = true; m_field = std::move(value); }
/**
* <p>The field on which to filter.</p>
*/
inline Filter& WithField(const FilterField& value) { SetField(value); return *this;}
/**
* <p>The field on which to filter.</p>
*/
inline Filter& WithField(FilterField&& value) { SetField(std::move(value)); return *this;}
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline const FilterOperator& GetOperator() const{ return m_operator; }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline bool OperatorHasBeenSet() const { return m_operatorHasBeenSet; }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline void SetOperator(const FilterOperator& value) { m_operatorHasBeenSet = true; m_operator = value; }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline void SetOperator(FilterOperator&& value) { m_operatorHasBeenSet = true; m_operator = std::move(value); }
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline Filter& WithOperator(const FilterOperator& value) { SetOperator(value); return *this;}
/**
* <p>The operator to use for comparing the field’s value with the provided
* value.</p>
*/
inline Filter& WithOperator(FilterOperator&& value) { SetOperator(std::move(value)); return *this;}
/**
* <p>The desired field value on which to filter.</p>
*/
inline const Aws::String& GetValue() const{ return m_value; }
/**
* <p>The desired field value on which to filter.</p>
*/
inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; }
/**
* <p>The desired field value on which to filter.</p>
*/
inline void SetValue(const Aws::String& value) { m_valueHasBeenSet = true; m_value = value; }
/**
* <p>The desired field value on which to filter.</p>
*/
inline void SetValue(Aws::String&& value) { m_valueHasBeenSet = true; m_value = std::move(value); }
/**
* <p>The desired field value on which to filter.</p>
*/
inline void SetValue(const char* value) { m_valueHasBeenSet = true; m_value.assign(value); }
/**
* <p>The desired field value on which to filter.</p>
*/
inline Filter& WithValue(const Aws::String& value) { SetValue(value); return *this;}
/**
* <p>The desired field value on which to filter.</p>
*/
inline Filter& WithValue(Aws::String&& value) { SetValue(std::move(value)); return *this;}
/**
* <p>The desired field value on which to filter.</p>
*/
inline Filter& WithValue(const char* value) { SetValue(value); return *this;}
private:
FilterField m_field;
bool m_fieldHasBeenSet;
FilterOperator m_operator;
bool m_operatorHasBeenSet;
Aws::String m_value;
bool m_valueHasBeenSet;
};
} // namespace Model
} // namespace ConnectWisdomService
} // namespace Aws
|
The postpartum risk that many moms don’t know about
Special to The Globe and Mail
When you give birth you are expecting a baby to come out, and then the placenta. Not many moms are expecting their bladder or uterus to come out – most don’t even know this is possible.
Pregnancy and childbirth are risk factors for a condition known as pelvic organ prolapse. Studies show that 50 per cent of women who have given birth one or more times will have some degree of prolapse but it is likely even higher given the low reporting rate and lack of awareness. In simple terms a prolapse is the progressive descent of the internal organs (the bladder, the uterus or the rectum) into and eventually out of the vagina.
It occurs in stages, with the first and second stages often being asymptomatic, so many women don’t even know they have a problem until it progresses to stage 3, when the organ is at the vaginal opening and may even bulge out periodically on exertion, or stage 4, when the organ is bulging right out of the vaginal opening.
Early stage prolapse is sometimes reversible and is very manageable. But once the prolapse progresses to stage 3 or 4, it becomes life altering and may require surgery – surgery that can in turn cause other challenges and potentially lead to more operations. Prevention and early detection are key when it comes to pelvic organ prolapse.
Here are some possible symptoms to look for:
• low back pain
• a feeling of heaviness in the lower abdomen
• discomfort with sex
• difficulty starting the flow of urine
• difficulty emptying the bladder
• inability to completely empty the rectum.
As the descent of the organs continues, symptoms may progress to:
• feeling like you are sitting on a golf ball
• feeling like something is falling out
• heaviness that gets worse as the day progresses
• tampons getting pushed out
• difficulty inserting a tampon.
The best thing a woman can do to prevent prolapse (and any pelvic floor dysfunction for that matter) is to see a pelvic floor physiotherapist, ideally prior to conception, then during pregnancy, then at six weeks postpartum and then annually. Visit www.pelviennewellness.com for a list of pelvic floor physiotherapists across Canada. They assess the pelvic floor muscles for function and the internal organs to see if they are where they should be.
If a prolapse is found, a number of lifestyle management options would be presented.
Stand, sit and move with a neutral pelvis
If your posture is such that your pelvis is not aligned with your breathing diaphragm, then you will be given tips on how to stand, move and sit properly which in turn will make the pelvic floor exercises more effective. Most baby carriers encourage poor posture, so ensure your physiotherapist shows you the proper form while you are holding and carrying your baby as well.
Avoid heavy lifting
Heavy lifting causes an increase in intra-abdominal pressure and if your core (pelvic floor) can’t manage that pressure, then your organs will continue to move down and eventually out. Generally anything over 15 pounds may be too strenuous for some, and most moms are “heavy lifting” many times a day. Work with your pelvic floor physiotherapist to develop strategies for proper core activation to make lifting safer.
Explore a pessary
A pessary is a device inserted high into the vagina that supports the its walls and the organs. There are many different sizes and shapes, and it may take a few tries to find the right one, but once you do, it can allow the muscles to function better and provide relief from the discomfort of prolapse.
Avoid crunches
Crunches are the standard “go to” exercise for losing the mummy tummy but they increase intra-abdominal pressure pushing the abdomen outward and the pelvic organs downward. With each crunch, the bulging bladder or uterus is pushed further south.
Having a prolapse does not mean all exercise should be halted, it just needs to be modified. Some great options for prolapse-friendly exercise are:
The hypopresive method
A series of hypopresive postures (meaning “without pressure”) done with rhythmic breathing and apneas (pauses in breathing) that improve resting tone in the abdomen and pelvic floor and may even reverse early stage prolapse. Visit www.metodohipopresivo.com.
The buoyancy from water is a welcome relief from the downward draw of being upright against gravity all day. The water also provides resistance, making it a great way to train your muscles without the heavy lifting.
Yoga in general is thought of as gentle but there are some styles that may be too strenuous for unsupported organs. Opt for yin yoga, restorative yoga or gentle hatha when living with prolapse.
|
//
// This file is AUTOMATICALLY GENERATED, and should not be edited unless you are certain
// that it will not be re-generated anytime in the future. As generated code, the
// copyright owner(s) of the generating program do NOT claim any copyright on the code
// generated.
//
// Run Length Encoded (RLE) bitmaps. Each run is encoded as either one or two bytes,
// with NO PADDING. Thus, the data for each line of the bitmap is VARIABLE LENGTH, and
// there is no way of determining where any line other than the first starts without
// walking though the data.
//
// Note that one byte encoding ONLY occurs if the total number of colors is 16 or less,
// and in that case the 'flags' member of the 'RLEBitmapInfo' will have the first bit
// (0x01) set.
//
// In that case, if the high 4 bits of the first byte are ZERO, then this is a 2 byte
// run. The first byte is the index of the color in the color palette, and the second
// byte is the length.
//
// Else, the lower 4 bits are the color index, and the upper 4 bits are the run length.
//
// If the 'flags' member first bit is zero, then ALL runs are 2 byte runs. The first
// byte is the palette index, and the second is the run length.
//
// In order to save PROGMEM for other uses, the bitmap data is placed in a section that
// occurs near the END of the used FLASH. So, this data should only be accessed using
// the 'far' versions of the progmem functions - the usual versions are limited to the
// first 64K of FLASH.
//
// Data is from file 'images\240\mask_29_240.bmp'.
//
const byte mask_29_240_RLEBM_data[] PROGMEM_LATE =
{
0x00, 0x6d, 0xc1, 0x00, 0x77,
0x00, 0x65, 0xb1, 0x00, 0x80,
0x00, 0x60, 0x91, 0x00, 0x87,
0x00, 0x5b, 0x91, 0x00, 0x8c,
0x00, 0x58, 0x91, 0x00, 0x8f,
0x00, 0x54, 0x91, 0x00, 0x93,
0x00, 0x51, 0xa1, 0x00, 0x95,
0x00, 0x4f, 0x91, 0x00, 0x98,
0x00, 0x4c, 0xa1, 0x00, 0x9a,
0x00, 0x4a, 0x91, 0x00, 0x9d,
0x00, 0x47, 0xa1, 0x00, 0x9f,
0x00, 0x45, 0xa1, 0x00, 0xa1,
0x00, 0x43, 0xb1, 0x00, 0xa2,
0x00, 0x41, 0xb1, 0x00, 0xa4,
0x00, 0x3f, 0xb1, 0x00, 0xa6,
0x00, 0x3d, 0xc1, 0x00, 0xa7,
0x00, 0x3c, 0xb1, 0x00, 0xa9,
0x00, 0x3a, 0xc1, 0x00, 0xaa,
0x00, 0x38, 0xc1, 0x00, 0xac,
0x00, 0x37, 0xc1, 0x00, 0xad,
0x00, 0x35, 0xd1, 0x00, 0xae,
0x00, 0x34, 0xc1, 0x00, 0xb0,
0x00, 0x32, 0xd1, 0x00, 0xb1,
0x00, 0x31, 0xd1, 0x00, 0xb2,
0x00, 0x30, 0xd1, 0x00, 0xb3,
0x00, 0x2e, 0xe1, 0x00, 0xb4,
0x00, 0x2d, 0xe1, 0x00, 0xb5,
0x00, 0x2c, 0xe1, 0x00, 0xb6,
0x00, 0x2b, 0xe1, 0x00, 0xb7,
0x00, 0x2a, 0xe1, 0x00, 0xb8,
0x00, 0x29, 0xe1, 0x00, 0xb9,
0x00, 0x27, 0xf1, 0x00, 0xba,
0x00, 0x26, 0xf1, 0x00, 0xbb,
0x00, 0x25, 0xf1, 0x00, 0xbc,
0x00, 0x24, 0xf1, 0x00, 0xbd,
0x00, 0x23, 0xf1, 0x00, 0xbe,
0x00, 0x22, 0xf1, 0x00, 0xbf,
0x00, 0x21, 0x01, 0x10, 0x00, 0xbf,
0x00, 0x20, 0x01, 0x10, 0x00, 0xc0,
0x00, 0x1f, 0x01, 0x10, 0x00, 0xc1,
0x00, 0x1f, 0xf1, 0x00, 0xc2,
0x00, 0x1e, 0xf1, 0x00, 0xc3,
0x00, 0x1d, 0x01, 0x10, 0x00, 0xc3,
0x00, 0x1c, 0x01, 0x10, 0x00, 0xc4,
0x00, 0x1b, 0x01, 0x10, 0x00, 0xc5,
0x00, 0x1a, 0x01, 0x11, 0x00, 0xc5,
0x00, 0x1a, 0x01, 0x10, 0x00, 0xc6,
0x00, 0x19, 0x01, 0x10, 0x00, 0xc7,
0x00, 0x18, 0x01, 0x11, 0x00, 0xc7,
0x00, 0x17, 0x01, 0x11, 0x00, 0xc8,
0x00, 0x17, 0x01, 0x10, 0x00, 0xc9,
0x00, 0x16, 0x01, 0x11, 0x00, 0xc9,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x14, 0x01, 0x11, 0x00, 0xcb,
0x00, 0x13, 0x01, 0x12, 0x00, 0xcb,
0x00, 0x13, 0x01, 0x11, 0x00, 0xcc,
0x00, 0x12, 0x01, 0x12, 0x00, 0xcc,
0x00, 0x11, 0x01, 0x12, 0x00, 0xcd,
0x00, 0x11, 0x01, 0x11, 0x00, 0xce,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xb0, 0x01, 0x13, 0x00, 0xd2,
0xb0, 0x01, 0x12, 0x00, 0xd3,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x70, 0x01, 0x14, 0x00, 0xd5,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x60, 0x01, 0x14, 0x00, 0xd6,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x13, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x13, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x01, 0x15, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x10, 0x01, 0x14, 0x00, 0xdb,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x20, 0x01, 0x14, 0x00, 0xda,
0x30, 0x01, 0x13, 0x00, 0xda,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x30, 0x01, 0x14, 0x00, 0xd9,
0x40, 0x01, 0x13, 0x00, 0xd9,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x40, 0x01, 0x14, 0x00, 0xd8,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x50, 0x01, 0x13, 0x00, 0xd8,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x50, 0x01, 0x14, 0x00, 0xd7,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x60, 0x01, 0x13, 0x00, 0xd7,
0x60, 0x01, 0x14, 0x00, 0xd6,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x70, 0x01, 0x13, 0x00, 0xd6,
0x70, 0x01, 0x14, 0x00, 0xd5,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x80, 0x01, 0x13, 0x00, 0xd5,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0x90, 0x01, 0x13, 0x00, 0xd4,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0xa0, 0x01, 0x13, 0x00, 0xd3,
0xb0, 0x01, 0x12, 0x00, 0xd3,
0xb0, 0x01, 0x13, 0x00, 0xd2,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xc0, 0x01, 0x12, 0x00, 0xd2,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xd0, 0x01, 0x12, 0x00, 0xd1,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xe0, 0x01, 0x12, 0x00, 0xd0,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0xf0, 0x01, 0x12, 0x00, 0xcf,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0x00, 0x10, 0x01, 0x12, 0x00, 0xce,
0x00, 0x11, 0x01, 0x11, 0x00, 0xce,
0x00, 0x11, 0x01, 0x12, 0x00, 0xcd,
0x00, 0x12, 0x01, 0x12, 0x00, 0xcc,
0x00, 0x13, 0x01, 0x11, 0x00, 0xcc,
0x00, 0x13, 0x01, 0x12, 0x00, 0xcb,
0x00, 0x14, 0x01, 0x11, 0x00, 0xcb,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x15, 0x01, 0x11, 0x00, 0xca,
0x00, 0x16, 0x01, 0x11, 0x00, 0xc9,
0x00, 0x17, 0x01, 0x10, 0x00, 0xc9,
0x00, 0x17, 0x01, 0x11, 0x00, 0xc8,
0x00, 0x18, 0x01, 0x11, 0x00, 0xc7,
0x00, 0x19, 0x01, 0x10, 0x00, 0xc7,
0x00, 0x1a, 0x01, 0x10, 0x00, 0xc6,
0x00, 0x1a, 0x01, 0x11, 0x00, 0xc5,
0x00, 0x1b, 0x01, 0x10, 0x00, 0xc5,
0x00, 0x1c, 0x01, 0x10, 0x00, 0xc4,
0x00, 0x1d, 0x01, 0x10, 0x00, 0xc3,
0x00, 0x1e, 0xf1, 0x00, 0xc3,
0x00, 0x1f, 0xf1, 0x00, 0xc2,
0x00, 0x1f, 0x01, 0x10, 0x00, 0xc1,
0x00, 0x20, 0x01, 0x10, 0x00, 0xc0,
0x00, 0x21, 0x01, 0x10, 0x00, 0xbf,
0x00, 0x22, 0xf1, 0x00, 0xbf,
0x00, 0x23, 0xf1, 0x00, 0xbe,
0x00, 0x24, 0xf1, 0x00, 0xbd,
0x00, 0x25, 0xf1, 0x00, 0xbc,
0x00, 0x26, 0xf1, 0x00, 0xbb,
0x00, 0x27, 0xf1, 0x00, 0xba,
0x00, 0x29, 0xe1, 0x00, 0xb9,
0x00, 0x2a, 0xe1, 0x00, 0xb8,
0x00, 0x2b, 0xe1, 0x00, 0xb7,
0x00, 0x2c, 0xe1, 0x00, 0xb6,
0x00, 0x2d, 0xe1, 0x00, 0xb5,
0x00, 0x2e, 0xe1, 0x00, 0xb4,
0x00, 0x30, 0xd1, 0x00, 0xb3,
0x00, 0x31, 0xd1, 0x00, 0xb2,
0x00, 0x32, 0xd1, 0x00, 0xb1,
0x00, 0x34, 0xc1, 0x00, 0xb0,
0x00, 0x35, 0xd1, 0x00, 0xae,
0x00, 0x37, 0xc1, 0x00, 0xad,
0x00, 0x38, 0xc1, 0x00, 0xac,
0x00, 0x3a, 0xc1, 0x00, 0xaa,
0x00, 0x3c, 0xb1, 0x00, 0xa9,
0x00, 0x3d, 0xc1, 0x00, 0xa7,
0x00, 0x3f, 0xb1, 0x00, 0xa6,
0x00, 0x41, 0xb1, 0x00, 0xa4,
0x00, 0x43, 0xb1, 0x00, 0xa2,
0x00, 0x45, 0xa1, 0x00, 0xa1,
0x00, 0x47, 0xa1, 0x00, 0x9f,
0x00, 0x4a, 0x91, 0x00, 0x9d,
0x00, 0x4c, 0xa1, 0x00, 0x9a,
0x00, 0x4f, 0x91, 0x00, 0x98,
0x00, 0x51, 0xa1, 0x00, 0x95,
0x00, 0x54, 0x91, 0x00, 0x93,
0x00, 0x58, 0x91, 0x00, 0x8f,
0x00, 0x5b, 0x91, 0x00, 0x8c,
0x00, 0x60, 0x91, 0x00, 0x87,
0x00, 0x65, 0xb1, 0x00, 0x80,
0x00, 0x6d, 0xc1, 0x00, 0x77,
}; // 240x240 Bitmap (57600 pixels) in 1240 bytes
const uint16_t mask_29_240_RLEBM_palette[] PROGMEM_LATE =
{
// Palette has 2 entries
0x0000, 0xffff,
};
// Some platforms don't fully implement the pgmspace.h interface. Assume ordinary
// addresses will do.
#if not defined pgm_get_far_address
#define pgm_get_far_address(x) ((uint32_t)(&(x)))
#endif
// Returns the info needed to render the bitmap.
inline void get_mask_29_240_RLEBM(
RLEBitmapInfo &bmInfo)
{
bmInfo.pRLEBM_data_far = pgm_get_far_address(mask_29_240_RLEBM_data);
bmInfo.pRLEBM_palette_far = pgm_get_far_address(mask_29_240_RLEBM_palette);
bmInfo.width = 240;
bmInfo.height = 240;
bmInfo.flags = 0x01;
}
|
Dismiss Notice
Join Physics Forums Today!
Double Pendulum with motor between segments
1. Apr 8, 2009 #1
Hello everyone,
First, I must apologize in advance as I am no physicist, and am unable to be of any help in physics to anyone else at a high level. I have a general knowledge of a wide range of subjects, and I have a problem that I need to understand better. So, with that said, here is my question.
I'm interested in the concept of momentum transfer between segments of a double pendulum system. Essentially conservation of momentum.. right? One segment decelerates while the other accelerates.
First question. Does one segment give up it's momentum to the next, or does one segment draw momentum from the other. Is this just semantics?
Second question. Both segments are interacting with one another through a pivot point. One segment slows down while the next segment speeds up. Let's change the scenario though. What would happen if there was a motor between the links at the pivot point forcefully causing the angle of the joint to change. In this case how would the transfer of momentum be affected between the segments? Would it just speed up?
I know i've most likely done a hatchet job to some physics terms in writing this out, so I hope you get the gist of what i'm trying to ask, But any help would be much appreciated.
Thank You
2. jcsd
3. Apr 8, 2009 #2
Andy Resnick
User Avatar
Science Advisor
Education Advisor
2016 Award
What you are describing is a fairly complicated system- complicated because the range of possible motions and behaviors of such a system is quite vast: stable oscillations, unstable, chaotic oscillations... to name three.
To answer question 1, I don't think it's correct to divide up the system like that- the two segments do not act independently of the other (except, perhaps, as a limiting case). Rather, the total momentum is the only well-defined measure. How it is partitioned among the internal degrees of freedom, and how that varies in time, can probably be written down (most easily by working in terms of Lagrangian or Hamiltonian mechanics).
For question 2, what you describe is a phenomenon that can be modeled by 'negative friction' (Froude's pendulum). The dynamics are incredibly complex.
Does that help?
4. Apr 9, 2009 #3
soceric, perhaps you are thinking of the energy rather than momentum? If one bob is oscillating more rapidly, and then over time the other is, then could we say that the kinetic energy is transferring from one to the other?
One thing to keep in mind is that pendulums are difficult to model by conservation of momentum because there are net external forces on the pendulum. Strictly speaking, when a bob reverses direction because it's reached its peak height, the entire Earth moves (imperceptibly) to compensate.
Similar Discussions: Double Pendulum with motor between segments
1. Double pendulum (Replies: 2)
2. Double Pendulum (Replies: 1)
3. Double Pendulum (Replies: 1)
|
/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/core/kernels/range_sampler.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/env.h"
namespace tensorflow {
namespace {
using gtl::ArraySlice;
using gtl::MutableArraySlice;
class RangeSamplerTest : public ::testing::Test {
protected:
void CheckProbabilitiesSumToOne() {
double sum = 0;
for (int i = 0; i < sampler_->range(); i++) {
sum += sampler_->Probability(i);
}
EXPECT_NEAR(sum, 1.0, 1e-4);
}
void CheckHistogram(int num_samples, float tolerance) {
const int range = sampler_->range();
std::vector<int> h(range);
std::vector<int64> a(num_samples);
// Using a fixed random seed to make the test deterministic.
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
sampler_->SampleBatch(&rnd, false, &a);
for (int i = 0; i < num_samples; i++) {
int64 val = a[i];
ASSERT_GE(val, 0);
ASSERT_LT(val, range);
h[val]++;
}
for (int val = 0; val < range; val++) {
EXPECT_NEAR((h[val] + 0.0) / num_samples, sampler_->Probability(val),
tolerance);
}
}
void Update1() {
// Add the value 3 ten times.
std::vector<int64> a(10);
for (int i = 0; i < 10; i++) {
a[i] = 3;
}
sampler_->Update(a);
}
void Update2() {
// Add the value n n times.
int64 a[10];
for (int i = 0; i < 10; i++) {
a[i] = i;
}
for (int64 i = 1; i < 10; i++) {
sampler_->Update(ArraySlice<int64>(a + i, 10 - i));
}
}
std::unique_ptr<RangeSampler> sampler_;
};
TEST_F(RangeSamplerTest, UniformProbabilities) {
sampler_.reset(new UniformSampler(10));
for (int i = 0; i < 10; i++) {
CHECK_EQ(sampler_->Probability(i), sampler_->Probability(0));
}
}
TEST_F(RangeSamplerTest, UniformChecksum) {
sampler_.reset(new UniformSampler(10));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, UniformHistogram) {
sampler_.reset(new UniformSampler(10));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, LogUniformProbabilities) {
int range = 1000000;
sampler_.reset(new LogUniformSampler(range));
for (int i = 100; i < range; i *= 2) {
float ratio = sampler_->Probability(i) / sampler_->Probability(i / 2);
EXPECT_NEAR(ratio, 0.5, 0.1);
}
}
TEST_F(RangeSamplerTest, LogUniformChecksum) {
sampler_.reset(new LogUniformSampler(10));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, LogUniformHistogram) {
sampler_.reset(new LogUniformSampler(10));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, UnigramProbabilities1) {
sampler_.reset(new UnigramSampler(10));
Update1();
EXPECT_NEAR(sampler_->Probability(3), 0.55, 1e-4);
for (int i = 0; i < 10; i++) {
if (i != 3) {
ASSERT_NEAR(sampler_->Probability(i), 0.05, 1e-4);
}
}
}
TEST_F(RangeSamplerTest, UnigramProbabilities2) {
sampler_.reset(new UnigramSampler(10));
Update2();
for (int i = 0; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), (i + 1) / 55.0, 1e-4);
}
}
TEST_F(RangeSamplerTest, UnigramChecksum) {
sampler_.reset(new UnigramSampler(10));
Update1();
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, UnigramHistogram) {
sampler_.reset(new UnigramSampler(10));
Update1();
CheckHistogram(1000, 0.05);
}
static const char kVocabContent[] =
"w1,1\n"
"w2,2\n"
"w3,4\n"
"w4,8\n"
"w5,16\n"
"w6,32\n"
"w7,64\n"
"w8,128\n"
"w9,256";
TEST_F(RangeSamplerTest, FixedUnigramProbabilities) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 9, fname, 0.8, 0, 1, 0));
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 0; i < 9; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, i * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramChecksum) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 9, fname, 0.8, 0, 1, 0));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, FixedUnigramHistogram) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 9, fname, 0.8, 0, 1, 0));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve1) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 10, fname, 0.8, 1, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 1; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 1) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve2) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 11, fname, 0.8, 2, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
ASSERT_NEAR(sampler_->Probability(1), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 2; i < 11; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 2) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(9, weights, 0.8, 0, 1, 0));
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 0; i < 9; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, i * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramChecksumFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(9, weights, 0.8, 0, 1, 0));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, FixedUnigramHistogramFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(9, weights, 0.8, 0, 1, 0));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve1FromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(10, weights, 0.8, 1, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 1; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 1) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve2FromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(11, weights, 0.8, 2, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
ASSERT_NEAR(sampler_->Probability(1), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 2; i < 11; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 2) * 0.8) / 197.05, 1e-4);
}
}
// AllSampler cannot call Sample or Probability directly.
// We will test SampleBatchGetExpectedCount instead.
TEST_F(RangeSamplerTest, All) {
int batch_size = 10;
sampler_.reset(new AllSampler(10));
std::vector<int64> batch(batch_size);
std::vector<float> batch_expected(batch_size);
std::vector<int64> extras(2);
std::vector<float> extras_expected(2);
extras[0] = 0;
extras[1] = batch_size - 1;
sampler_->SampleBatchGetExpectedCount(nullptr, // no random numbers needed
false, &batch, &batch_expected, extras,
&extras_expected);
for (int i = 0; i < batch_size; i++) {
EXPECT_EQ(i, batch[i]);
EXPECT_EQ(1, batch_expected[i]);
}
EXPECT_EQ(1, extras_expected[0]);
EXPECT_EQ(1, extras_expected[1]);
}
TEST_F(RangeSamplerTest, Unique) {
// We sample num_batches batches, each without replacement.
//
// We check that the returned expected counts roughly agree with each other
// and with the average observed frequencies over the set of batches.
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
const int range = 100;
const int batch_size = 50;
const int num_batches = 100;
sampler_.reset(new LogUniformSampler(range));
std::vector<int> histogram(range);
std::vector<int64> batch(batch_size);
std::vector<int64> all_values(range);
for (int i = 0; i < range; i++) {
all_values[i] = i;
}
std::vector<float> expected(range);
// Sample one batch and get the expected counts of all values
sampler_->SampleBatchGetExpectedCount(
&rnd, true, &batch, MutableArraySlice<float>(), all_values, &expected);
// Check that all elements are unique
std::set<int64> s(batch.begin(), batch.end());
CHECK_EQ(batch_size, s.size());
for (int trial = 0; trial < num_batches; trial++) {
std::vector<float> trial_expected(range);
sampler_->SampleBatchGetExpectedCount(&rnd, true, &batch,
MutableArraySlice<float>(),
all_values, &trial_expected);
for (int i = 0; i < range; i++) {
EXPECT_NEAR(expected[i], trial_expected[i], expected[i] * 0.5);
}
for (int i = 0; i < batch_size; i++) {
histogram[batch[i]]++;
}
}
for (int i = 0; i < range; i++) {
// Check that the computed expected count agrees with the average observed
// count.
const float average_count = static_cast<float>(histogram[i]) / num_batches;
EXPECT_NEAR(expected[i], average_count, 0.2);
}
}
TEST_F(RangeSamplerTest, Avoid) {
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
sampler_.reset(new LogUniformSampler(100));
std::vector<int64> avoided(2);
avoided[0] = 17;
avoided[1] = 23;
std::vector<int64> batch(98);
// We expect to pick all elements of [0, 100) except the avoided two.
sampler_->SampleBatchGetExpectedCountAvoid(
&rnd, true, &batch, MutableArraySlice<float>(), ArraySlice<int64>(),
MutableArraySlice<float>(), avoided);
int sum = 0;
for (auto val : batch) {
sum += val;
}
const int expected_sum = 100 * 99 / 2 - avoided[0] - avoided[1];
EXPECT_EQ(expected_sum, sum);
}
} // namespace
} // namespace tensorflow
|
Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
Friction on an incline
1. Feb 22, 2016 #1
A block is sliding with an initial velocity of 7.3 m/s along a frictionless horizontal surface when it then goes up an incline of 51.5 degrees that does have friction. If the kinetic friction coefficient is 0.1 then how far along the incline (hypotenuse) will the object travel before it stops?
Θ = 51.5°
µ(k) = 0.1
v(initial) = 7.3 m/s
v(final) = 0 ...because the question asks at what point will it stop, meaning there is no more speed.
g = 9.81
d = ?
m = ?
a = ? ...i do not know if i even need acceleration
F = ?
W = ?
2. Relevant equations
KE = W = 1/2mv(final) - 1/2mv(initial)
F = mg
W = Fd
Force up ramp... F = mg sinΘ
Normal Force against ramp... Fnormal = mg cosΘ
Force of friction between block and ramp... F(f) = µ Fnormal
3. The attempt at a solution
Honestly i have no clue where to even begin, i am so lost on this problem :(
Also, my equations could be wrong. Could somebody please give me a detailed walkthrough on how to solve this?
2. jcsd
3. Feb 22, 2016 #2
User Avatar
Staff: Mentor
Alas, we cannot do that; it's against forum rules. You'll need to make some attempt at a solution before help can be given.
That said, I suggest that you consider how energy is traded and lost along the block's path.
4. Feb 22, 2016 #3
User Avatar
Science Advisor
Homework Helper
Gold Member
2016 Award
There is a flaw in this question. The way the diagram is drawn, the transition from horizontal to inclined motion is sudden, implying a non-conservative impact. But my guess is that you should suppose there is a small radius allowing for a smooth transition.
Have something to add?
Draft saved Draft deleted
Similar Discussions: Friction on an incline
1. Friction and Incline (Replies: 2)
2. Friction on an incline (Replies: 9)
3. Friction on an incline (Replies: 6)
4. Inclines and friction (Replies: 1)
5. Friction on an incline (Replies: 3)
|
There are many ways to effectively teach a dog.
Not so long ago, most of the accepted methods for training were forceful or aversive. Unfortunately, some of these methods still are in use among the abusive and uneducated.
One of the pioneers of gentle training techniques was Barbara Woodhouse. This English dog trainer was instrumental in paving the way for today’s nonaversive and positive methods of training. She was a genius at molding behaviors with lures and gently “modeling” a dog into positions without force. But even Woodhouse used some techniques that can be considered rough by today’s standards.
If you have researched dog-training methodologies at all, you probably have noticed that a percentage of the available training books advocate the use of a “choke chain” (otherwise called the training collar). When used properly, this training device relies on aversion to get the dog’s attention or to make a correction when your dog doesn’t respond to a command correctly. A sharp snap of the leash tightens the collar around the dog’s neck, startling the dog with a momentary, low-level pain.
The choke chain is not a training device for leash pullers, as is commonly thought, and when used incorrectly can, at the least, cause misalignment of the spine and trachea damage. At worst, it can cause brain damage and even death. Because there is such a high risk for misuse of this device (you may not realize that the choke chain should be worn with the free ring up, for instance), the training world probably would be much better off without it.
Your efforts to train your dog should focus on building a bond and nurturing trust. This bond becomes the motivator that drives your dog to learn, focus and respond.
Why would anyone want to use force or violence when positive reinforcement works so well? Why should your dog trust you if he knows that you are likely to hit him when he is unfocused or confused? That’s like your supervisor yelling at you when you have problems with a difficult task. Stress won’t help you concentrate or focus better. Abusive treatment of dogs in the name of training, just as abusive handling of employees in the name of supervision, doesn’t work. It does, however, tell us a lot about the trainer.
For any method of dog training to be successful, it must be:
Effective – If it’s not effective, what’s the point?
Efficient – Both you and your dog will become frustrated if training takes too long.
Enjoyable – Fun is an important ingredient in motivating both you and your dog.
The proper execution of any training program is dependent on these three ingredients.
But, ultimately, the most important ingredient in your training program is you, the owner. The trust you nurture in your dog will be evident in his willingness to look to you for leadership and his motivation to work with you in any and all situations. Those qualities are in your dog right now but cannot be developed through the use of harsh training methods.
Dog training can be whatever you want it to be. If you rely on anger and force, the relationship and trust will suffer. If you rely on motivation and reward, while providing appropriate consequences for misdeeds, training just gets better and better.
Julie Winkelman is a certified pet dog trainer and a certified dog trainer. Reach her at www.alphacanineacademy.com.
|
A 2012 survey conducted by the Association for Pet Obesity Prevention found 52.5 percent of dogs and 58.3 percent of cats to be overweight or obese by their veterinarian. This translates to nearly 80 million dogs and cats in America with a weight problem. Dr. George Banta, chair of the Veterinary Technology department at Brown Mackie College - Akron and Dr. Mary Jo Wagner, attending veterinarian at Argosy University, Twin Cities, offer useful information for pet owners.
How can you tell if your pet is overweight? “It’s not the number of pounds, it’s how the animal carries the weight,” says Banta. “The number on the Body Condition Score is more important than pounds.” The Body Condition Score offers a way to assess the condition of an animal, usually on a scale from one to five, taking into account height, weight, and relative proportions of muscle and fat.
With a little knowledge, you can use sight and touch to figure your pet’s general condition. “When looking down on a dog or cat from above,” says Banta, “the body should slim to a discernable waist. An animal is too thin if you can see the spine or ribs; however, you should be able to feel them beneath the fur.” An animal of ideal weight will also display a pelvic tuck when viewed from the side.
“Just like humans, when animals overeat, they face increased risk for health problems like diabetes, heart disease, gastrointestinal problems and cancer,” continues Banta. In fact, these risks also include a shortened life expectancy.
Many owners feed pets according to the manufacturer’s suggested amounts; however, this instruction may not be right for your pet. “These guidelines are meant to cover all animals of a certain weight range,” says Wagner. “An owner must consider the age and activity level of each pet. The more active they are, the more calories they will burn in a day.”
Metabolism rates vary in animals the same way they do in people. Metabolism is the body process in which food is broken down for energy; another factor that affects the amount of food a pet needs. Wagner advises owners to keep an eye on body condition to judge whether a pet is eating properly. “If your pet shows signs of being overweight, simply cut back the amount of food given at each meal. Then weigh the pet in two or three weeks to see if it has made a difference,” she says.
Choosing the right food for your pet is important as well. Different brands of pet food contain varying amounts of protein, fat, carbohydrates and calories. “As a general rule, young, active dogs need high protein food,” says Wagner. “Older dogs need higher fiber to keep the gastrointestinal (GI) tract moving.” Ingredients listed on the package appear in descending order of volume; the first item on the list is most abundant in the food.
Most of us love to give treats, but many of us don’t realize how many we offer each day. “A 40-pound dog is one quarter the size of a 160-pound person,” Wagner says. “They have smaller stomachs. Look at calories in everything your pet eats. After that, it’s simple math.”
“Table scraps are a definite no. Zip, zilch, nada,” says Banta. “They are not good for two reasons. First, foods like chocolate, caffeine, grapes and raisins can be toxic to dogs. Second, the high fat content associated with table scraps, especially holiday trimmings, can lead to the onset of acute pancreatitis, which can be fatal.”
He recommends offering a kibble of food or a carrot instead of a cookie. If you must give cookies, try breaking them in half. “Pets do enjoy treats as a reward; however, attention from you is also a reward. It’s important to praise animals. In some ways, spending time with them is better than a treat,” Wagner says.
|
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file MSTransportableDevice_Routing.h
/// @author Michael Behrisch
/// @author Daniel Krajzewicz
/// @author Jakob Erdmann
/// @date Tue, 04 Dec 2007
///
// A device that performs vehicle rerouting based on current edge speeds
/****************************************************************************/
#pragma once
#include <config.h>
#include "MSTransportableDevice.h"
// ===========================================================================
// class declarations
// ===========================================================================
class MSLane;
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class MSTransportableDevice_Routing
* @brief A device that performs person rerouting based on current edge speeds
*
* The routing-device system consists of in-vehicle devices that perform the routing
* and simulation-wide static methods for collecting edge weights and
* parallelizing in MSRoutingEngine.
*
* A device is assigned using the common explicit/probability - procedure.
*
* A device computes a new route for a person as soon as a personTrip appears in the plan.
*/
class MSTransportableDevice_Routing : public MSTransportableDevice {
public:
/** @brief Inserts MSTransportableDevice_Routing-options
* @param[filled] oc The options container to add the options to
*/
static void insertOptions(OptionsCont& oc);
/** @brief checks MSTransportableDevice_Routing-options
* @param[filled] oc The options container with the user-defined options
*/
static bool checkOptions(OptionsCont& oc);
/** @brief Build devices for the given person, if needed
*
* The options are read and evaluated whether rerouting-devices shall be built
* for the given person.
*
* When the first device is built, the static container of edge weights
* used for routing is initialised with the mean speed the edges allow.
* In addition, an event is generated which updates these weights is
* built and added to the list of events to execute at a simulation end.
*
* The built device is stored in the given vector.
*
* @param[in] p The person for which a device may be built
* @param[filled] into The vector to store the built device in
*/
static void buildDevices(MSTransportable& p, std::vector<MSTransportableDevice*>& into);
/// @brief Destructor.
~MSTransportableDevice_Routing();
/// @brief return the name for this type of device
const std::string deviceName() const {
return "rerouting";
}
/** @brief Saves the state of the device
*
* @param[in] out The OutputDevice to write the information into
*/
void saveState(OutputDevice& out) const;
/** @brief Loads the state of the device from the given description
*
* @param[in] attrs XML attributes describing the current state
*/
void loadState(const SUMOSAXAttributes& attrs);
/// @brief initiate the rerouting, create router / thread pool on first use
void reroute(const SUMOTime currentTime, const bool onInit = false);
/// @brief try to retrieve the given parameter from this device. Throw exception for unsupported key
std::string getParameter(const std::string& key) const;
/// @brief try to set the given parameter for this device. Throw exception for unsupported key
void setParameter(const std::string& key, const std::string& value);
private:
/** @brief Constructor
*
* @param[in] holder The vehicle that holds this device
* @param[in] id The ID of the device
* @param[in] period The period with which a new route shall be searched
*/
MSTransportableDevice_Routing(MSTransportable& holder, const std::string& id, SUMOTime period);
/** @brief Performs rerouting after a period
*
* A new route is computed by calling the vehicle's "reroute" method, supplying
* "getEffort" as the edge effort retrieval method.
*
* This method is called from the event handler at the begin of a simulation
* step after the rerouting period is over. The reroute period is returned.
*
* @param[in] currentTime The current simulation time
* @return The offset to the next call (the rerouting period "myPeriod")
* @see MSVehicle::reroute
* @see MSEventHandler
* @see WrappingCommand
*/
SUMOTime wrappedRerouteCommandExecute(SUMOTime currentTime);
private:
/// @brief The period with which a vehicle shall be rerouted
SUMOTime myPeriod;
/// @brief The last time a routing took place
SUMOTime myLastRouting;
/// @brief The (optional) command responsible for rerouting
WrappingCommand< MSTransportableDevice_Routing >* myRerouteCommand;
private:
/// @brief Invalidated copy constructor.
MSTransportableDevice_Routing(const MSTransportableDevice_Routing&);
/// @brief Invalidated assignment operator.
MSTransportableDevice_Routing& operator=(const MSTransportableDevice_Routing&);
};
|
Fewer rare sea turtles will die on the swordfish industry's longlines in Hawaii under an agreement between environmental groups and the government. The agreement settles a lawsuit challenging the federal government's plans that would have dramatically increase the number of turtles that could be killed. The Turtle Island Restoration Network, Center for Biological Diversity and KAHEA sued the National Marine Fisheries Service for allowing 46 imperiled Pacific loggerhead turtles to be hooked last year. The new court-ordered settlement caps the number at 17 per year. Meanwhile the National Marine Fisheries Service is weighing whether loggerheads need more protection under the Endangered Species Act.
"It made absolutely no sense to have one arm of the National Marine Fisheries Service increasing the lethal capture of loggerheads, while the other arm is in the process of determining whether loggerheads should be uplisted from threatened to endangered," said Todd Steiner, biologist and executive director of Turtle Island Restoration Network. "With extinction looming, these animals need more protection, not less."
"With this decision, Hawaii's public-trust ocean resources can be better managed for our collective best interest, and not just the interests of this commercial fishery," said KAHEA program director Marti Townsend. "This is a victory not just for the turtles, but for Hawaii's people who rely on a healthy, functioning ocean ecosystem."
Conservation groups represented by Earthjustice filed a federal lawsuit challenging a 2009 rule allowing the swordfish fleet to catch nearly three times as many loggerhead sea turtles as previously permitted. This settlement freezes the number at the previous cap of 17 while the government conducts additional environmental studies and decides whether or not to classify the loggerhead as endangered, rather than its current, less-protective status of threatened. For leatherback turtles, the bycatch limit remains at 16 per year. In 2010, eight Pacific leatherbacks and seven loggerheads were caught in the longline fishery, according to the National Marine Fisheries Service. There have already been 4 loggerheads captured in 2011, which has sea turtle conservationists concerned.
"Sea turtles have been swimming the oceans since the time of dinosaurs. But without a change in management, they won't survive our voracious quest for swordfish and tuna," said Miyoko Sakashita, oceans director at the Center for Biological Diversity. "If loggerheads are going to survive in the North Pacific, we need to stop killing them in our fisheries."
"Pacific loggerhead sea turtles are nearly extinct, so this bycatch rollback helps right a serious wrong," said Teri Shore, program director at Turtle Island Restoration Network. "We can't allow these rare sea turtles to disappear for a plate of swordfish. It's tragic that it took a lawsuit to correct this fishery problem."
Swordfish longline vessels trail up to 60 miles of fishing line suspended in the water with floats, with as many as 1,000 baited hooks deployed at regular intervals. Sea turtles become hooked while trying to take bait or become entangled while swimming through the nearly invisible lines. These encounters can drown the turtles or leave them with serious injuries. Sea birds such as albatross dive for the bait and become hooked; marine mammals, including endangered humpback whales and false killer whales, also sometimes become hooked when they swim through the floating lines.
|
/** \file locify_main.cpp
*
* Defines the "vg locify" subcommand
*/
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <iostream>
#include "subcommand.hpp"
#include "../vg.hpp"
#include "../xg.hpp"
#include "../index.hpp"
#include "../convert.hpp"
#include <vg/io/stream.hpp>
#include <vg/io/vpkg.hpp>
#include <bdsg/overlay_helper.hpp>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_locify(char** argv){
cerr << "usage: " << argv[0] << " locify [options] " << endl
<< " -l, --loci FILE input loci over which to locify the alignments" << endl
<< " -a, --aln-idx DIR use this rocksdb alignment index (from vg index -N)" << endl
<< " -x, --xg-idx FILE use this xg index or graph" << endl
<< " -n, --name-alleles generate names for each allele rather than using full Paths" << endl
<< " -f, --forwardize flip alignments on the reverse strand to the forward" << endl
<< " -s, --sorted-loci FILE write the non-nested loci out in their sorted order" << endl
<< " -b, --n-best N keep only the N-best alleles by alignment support" << endl
<< " -o, --out-loci FILE rewrite the loci with only N-best alleles kept" << endl;
// TODO -- add some basic filters that are useful downstream in whatshap
}
int main_locify(int argc, char** argv){
string gam_idx_name;
string loci_file;
Index gam_idx;
string xg_idx_name;
bool name_alleles = false;
bool forwardize = false;
string loci_out, sorted_loci;
int n_best = 0;
if (argc <= 2){
help_locify(argv);
exit(1);
}
int c;
optind = 2; // force optind past command positional argument
while (true) {
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"gam-idx", required_argument, 0, 'g'},
{"loci", required_argument, 0, 'l'},
{"xg-idx", required_argument, 0, 'x'},
{"name-alleles", no_argument, 0, 'n'},
{"forwardize", no_argument, 0, 'f'},
{"sorted-loci", required_argument, 0, 's'},
{"loci-out", required_argument, 0, 'o'},
{"n-best", required_argument, 0, 'b'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hl:x:g:nfo:b:s:",
long_options, &option_index);
// Detect the end of the options.
if (c == -1)
break;
switch (c)
{
case 'g':
gam_idx_name = optarg;
break;
case 'l':
loci_file = optarg;
break;
case 'x':
xg_idx_name = optarg;
break;
case 'n':
name_alleles = true;
break;
case 'f':
forwardize = true;
break;
case 'o':
loci_out = optarg;
break;
case 's':
sorted_loci = optarg;
break;
case 'b':
n_best = parse<int>(optarg);
name_alleles = true;
break;
case 'h':
case '?':
help_locify(argv);
exit(1);
break;
default:
abort ();
}
}
if (!gam_idx_name.empty()) {
gam_idx.open_read_only(gam_idx_name);
}
if (xg_idx_name.empty()) {
cerr << "[vg locify] Error: no xg index provided" << endl;
return 1;
}
ifstream xgstream(xg_idx_name);
unique_ptr<PathHandleGraph> path_handle_graph = vg::io::VPKG::load_one<PathHandleGraph>(xgstream);
bdsg::PathPositionOverlayHelper overlay_helper;
PathPositionHandleGraph* xgidx = overlay_helper.apply(path_handle_graph.get());
std::function<vector<string>(string, char)> strsplit = [&](string x, char delim){
vector<string> ret;
stringstream ss;
std::string tok;
while (getline(ss, tok, delim)){
ret.push_back(tok);
}
return ret;
};
vector<string> locus_names;
map<string, map<string, int > > locus_allele_names;
map<string, Alignment> alignments_with_loci;
map<pos_t, set<string> > pos_to_loci;
map<string, set<pos_t> > locus_to_pos;
map<string, map<int, int> > locus_allele_support;
map<string, vector<int> > locus_to_best_n_alleles;
map<string, set<int> > locus_to_keep;
int count = 0;
std::function<void(Locus&)> lambda = [&](Locus& l){
locus_names.push_back(l.name());
set<vg::id_t> nodes_in_locus;
for (int i = 0; i < l.allele_size(); ++i) {
auto& allele = l.allele(i);
for (int j = 0; j < allele.mapping_size(); ++j) {
auto& position = allele.mapping(j).position();
nodes_in_locus.insert(position.node_id());
}
// for position in mapping
map<pos_t, int> ref_positions;
map<pos_t, Edit> edits;
decompose(allele, ref_positions, edits);
// warning: uses only reference positions!!!
for (auto& pos : ref_positions) {
pos_to_loci[pos.first].insert(l.name());
locus_to_pos[l.name()].insert(pos.first);
}
}
// void for_alignment_in_range(int64_t id1, int64_t id2, std::function<void(const Alignment&)> lambda);
std::function<void(const Alignment&)> fill_alns = [&](const Alignment& a){
// TODO reverse complementing alleles ?
// overlap is stranded
//matching
// find the most-matching allele
map<double, vector<int> > matches;
for (int i = 0; i < l.allele_size(); ++i) {
auto& allele = l.allele(i);
matches[overlap(a.path(), allele)].push_back(i);
}
assert(l.allele_size());
int best = matches.rbegin()->second.front();
Locus matching;
matching.set_name(l.name());
if (name_alleles) {
//map<string, map<string, int > > locus_allele_names;
auto& allele = l.allele(best);
string s;
allele.SerializeToString(&s);
auto& l_names = locus_allele_names[l.name()];
auto f = l_names.find(s);
int name_int = 0;
if (f == l_names.end()) {
int next_id = l_names.size() + 1;
l_names[s] = next_id;
name_int = next_id;
} else {
name_int = f->second;
}
string allele_name = vg::convert(name_int);
Path p;
p.set_name(allele_name);
*matching.add_allele() = p;
if (n_best) {
// record support for this allele
// we'll use to filter the locus records later
locus_allele_support[l.name()][name_int]++;
}
} else {
*matching.add_allele() = l.allele(best);
// TODO get quality score relative to this specific allele / alignment
// record in the alignment we'll save
}
if (alignments_with_loci.find(a.name()) == alignments_with_loci.end()) {
alignments_with_loci[a.name()] = a;
}
Alignment& aln = alignments_with_loci[a.name()];
*aln.add_locus() = matching;
};
vector<vg::id_t> nodes_vec;
for (auto& id : nodes_in_locus) nodes_vec.push_back(id);
gam_idx.for_alignment_to_nodes(nodes_vec, fill_alns);
};
if (!loci_file.empty()){
ifstream ifi(loci_file);
vg::io::for_each(ifi, lambda);
} else {
cerr << "[vg locify] Warning: empty locus file given, could not annotate alignments with loci." << endl;
}
// find the non-nested loci
vector<string> non_nested_loci;
for (auto& name : locus_names) {
// is it nested?
auto& positions = locus_to_pos[name];
int min_loci = 0;
for (auto& pos : positions) {
auto& loci = pos_to_loci[pos];
min_loci = (min_loci == 0 ? (int)loci.size() : min(min_loci, (int)loci.size()));
}
if (min_loci == 1) {
// not fully contained in any other locus
non_nested_loci.push_back(name);
}
}
// filter out the non-best alleles
if (n_best) {
// find the n-best
for (auto& supp : locus_allele_support) {
auto& name = supp.first;
auto& alleles = supp.second;
map<int, int> ranked;
for (auto& allele : alleles) {
ranked[allele.second] = allele.first;
}
auto& to_keep = locus_to_keep[name];
for (auto r = ranked.rbegin(); r != ranked.rend(); ++r) {
to_keep.insert(r->second);
if (to_keep.size() == n_best) {
break;
}
}
}
// filter out non-n-best from the alignments
for (auto& a : alignments_with_loci) {
auto& aln = a.second;
vector<Locus> kept;
for (int i = 0; i < aln.locus_size(); ++i) {
auto& allele = aln.locus(i).allele(0);
if (locus_to_keep[aln.locus(i).name()].count(atoi(allele.name().c_str()))) {
kept.push_back(aln.locus(i));
}
}
aln.clear_locus();
for (auto& l : kept) {
*aln.add_locus() = l;
}
}
}
if (n_best && !loci_out.empty()) {
// filter out non-n-best from the loci
if (!loci_file.empty()){
ofstream outloci(loci_out);
vector<Locus> buffer;
std::function<void(Locus&)> lambda = [&](Locus& l){
// remove the alleles which are to filter
//map<string, map<string, int > > locus_allele_names;
auto& allele_names = locus_allele_names[l.name()];
auto& to_keep = locus_to_keep[l.name()];
vector<Path> alleles_to_keep;
for (int i = 0; i < l.allele_size(); ++i) {
auto allele = l.allele(i);
string s; allele.SerializeToString(&s);
auto& name = allele_names[s];
if (to_keep.count(name)) {
allele.set_name(vg::convert(name));
alleles_to_keep.push_back(allele);
}
}
l.clear_allele();
for (auto& allele : alleles_to_keep) {
*l.add_allele() = allele;
}
buffer.push_back(l);
vg::io::write_buffered(outloci, buffer, 100);
};
ifstream ifi(loci_file);
vg::io::for_each(ifi, lambda);
vg::io::write_buffered(outloci, buffer, 0);
outloci.close();
} else {
cerr << "[vg locify] Warning: empty locus file given, could not update loci." << endl;
}
}
// sort them using... ? ids?
sort(non_nested_loci.begin(), non_nested_loci.end(),
[&locus_to_pos](const string& s1, const string& s2) {
return *locus_to_pos[s1].begin() < *locus_to_pos[s2].begin();
});
if (!sorted_loci.empty()) {
ofstream outsorted(sorted_loci);
for (auto& name : non_nested_loci) {
outsorted << name << endl;
}
outsorted.close();
}
vector<Alignment> output_buf;
for (auto& aln : alignments_with_loci) {
// TODO order the loci by their order in the alignments
if (forwardize) {
if (aln.second.path().mapping_size() && aln.second.path().mapping(0).position().is_reverse()) {
output_buf.push_back(reverse_complement_alignment(aln.second,
[&xgidx](int64_t id) { return xgidx->get_length(xgidx->get_handle(id)); }));
} else {
output_buf.push_back(aln.second);
}
} else {
output_buf.push_back(aln.second);
}
vg::io::write_buffered(cout, output_buf, 100);
}
vg::io::write_buffered(cout, output_buf, 0);
return 0;
}
// Register subcommand
static Subcommand vg_locify("locify", "find loci", main_locify);
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/rekognition/Rekognition_EXPORTS.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Rekognition
{
namespace Model
{
class AWS_REKOGNITION_API DeleteCollectionResult
{
public:
DeleteCollectionResult();
DeleteCollectionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DeleteCollectionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>HTTP status code that indicates the result of the operation.</p>
*/
inline int GetStatusCode() const{ return m_statusCode; }
/**
* <p>HTTP status code that indicates the result of the operation.</p>
*/
inline void SetStatusCode(int value) { m_statusCode = value; }
/**
* <p>HTTP status code that indicates the result of the operation.</p>
*/
inline DeleteCollectionResult& WithStatusCode(int value) { SetStatusCode(value); return *this;}
private:
int m_statusCode;
};
} // namespace Model
} // namespace Rekognition
} // namespace Aws
|
Dismiss Notice
Join Physics Forums Today!
Group axioms - Verify?
1. Sep 25, 2006 #1
It is known that "the integers under addition" form a group,
that is (Z,+).
I have always wondered how to actually proof that (Z,+) is a group?
Definitions for a group from wikipedia:
I'm especially interested in two things:
1) Why does the associative law hold for (Z,+), that is
a+(b+c) = (a+b)+c for a,b,c in Z.
And moreover:
2) Why is closure fulfilled?
That is, if a and b in Z, then a+b is also in Z.
2. jcsd
3. Sep 25, 2006 #2
In order to prove that addition on integers is commutative and that they are closed under addition, you need to use the definition of addition on the integers. However, in order to define addition you need to know how the integers are constructed.
You can construct the natural numbers as a sequence of sets, and define addition. You can then construct the integers from the natural numbers, and define addition on the integers using the addition you've already defined on the natural numbers. The wikipedia pages on natural numbers and integers have some of the details.
4. Sep 25, 2006 #3
User Avatar
Staff Emeritus
Science Advisor
Gold Member
Just to emphasize the importance of stating from which definition you're working -- in many contexts I would define the integers as "the free ring on zero generators"... in which case the additive group structure is trivial.
5. Sep 25, 2006 #4
How is that the case? Don't the integers have one generator? Either 1 or -1. Why isn't the ring with zero generators the trivial ring?
6. Sep 25, 2006 #5
User Avatar
Staff Emeritus
Science Advisor
Gold Member
Because it's not free -- it satisfies a nontrivial relation amongst its elements. (in particular, 0 = 1)
For a ring R to be freely generated by the empty set, that means:
For any ring S, any function {} --> S extends uniquely to a homomorphism R --> S.
(There is, of course, only one function {} --> S)
If you plug in R = Z, you'll find the above is satisfied. If you plug in R = 0, you'll find it's not satisfied. (In fact, if 0 --> S is a homomorphism, then S = 0)
7. Sep 25, 2006 #6
So is this equivalent to saying that R has a basis? That was what I thought a free ring was.
And how does Z have zero generators?
8. Sep 25, 2006 #7
User Avatar
Staff Emeritus
Science Advisor
Gold Member
Because it's generated by the empty set. ({1} is also a generating set for Z, of course, but Z is not the free ring on one object)
{} is clearly a subset of Z. What is the subring of Z generated by {}? Recall that it's the intersection of all subrings of Z that contain every element in {}. The only subring of Z is Z itself -- so {} generates Z.
9. Sep 25, 2006 #8
Okay, I think I see this. I was thinking of generating sets in terms of groups, and was trying to generate Z with addition. But that's not right. So the free ring on one generator would be Z[x], right?
On the level of groups, 1 or -1 generate Z, correct? So Z is the free group on one generator.
10. Sep 25, 2006 #9
User Avatar
Staff Emeritus
Science Advisor
Gold Member
Sounds right; I think things don't get annoying until you have two generators. (Unless you specify "free commutative ring" -- then everything remains nice. :smile:)
Similar Discussions: Group axioms - Verify?
1. Completeness Axiom (Replies: 4)
2. Axioms and Theorems (Replies: 10)
3. Field axiom (Replies: 5)
|
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void nextIndex(vector<int> &nums, int &index) {
for (; index < nums.size(); index++) {
if (nums[index] != 0)
break;
}
}
void moveZeroes(vector<int> &nums) {
int index = 1;
nextIndex(nums, index);
for (int zero = 0; zero < nums.size() && index < nums.size(); zero++) {
if (index < zero) {
index = zero;
nextIndex(nums, index);
}
if (nums[zero] == 0) {
swap(nums[index], nums[zero]);
nextIndex(nums, index);
}
}
}
};
int main() {
vector<int> nums = {4, 2, 4, 0, 0, 3, 0, 5, 1, 0};
Solution().moveZeroes(nums);
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << endl;
}
return 0;
}
|
Volume 4 Number 2
©The Author(s) 2002
The Continuity Framework: A Tool for Building Home, School, and Community Partnerships
AbstractWe will need to become savvy about how to build relationships, how to nurture growing, evolving things. All of us will need better skills in listening, communicating, and facilitating groups, because these are the talents that build strong relationships. (Wheatley, 1992, p. 38)
In the face of today's challenging social and family issues, many new efforts are underway to help children and families. One solution that many communities have adopted is the establishment of a collaborative partnership that involves all the relevant partners—home, school, and community—in the planning and monitoring of services for children. Unfortunately, achieving a strong partnership with meaningful participation can often be difficult and time-consuming. This article focuses on a set of training materials that has been developed to assist community partnerships in their efforts. These materials highlight eight elements of continuity and successful partnerships: (1) families as partners, (2) shared leadership, (3) comprehensive/responsive services, (4) culture and home language, (5) communication, (6) knowledge and skill development, (7) appropriate care and education, and (8) evaluation of partnership success. Results from a field study that included more than 200 reviewers and 8 pilot sites are summarized. Results indicate that a majority of reviewers found the training materials easy to understand, relevant to their work, and up-to-date. In addition, data gathered from the pilot sites indicate that the partnerships found the materials practical and useful for addressing a variety of issues, including time constraints, communication gaps, differences in professional training, and funding limitations.
Communities face a host of problems that threaten the health and well-being of their children and families. Poverty, unemployment, inadequate care/education, and poor health care are just a few of the difficult issues that communities must confront. What makes these issues particularly challenging is that children and families who experience one problem are often likely to experience other problems as well.
Compounding the problem is that delivery of services to help children and families is typically fragmented and scattered. Even efforts designed to increase the quality and supply of services to children and families have, at times, created greater fragmentation and discontinuity.
In previous years, those who sought to improve outcomes for children concentrated only on the child. Today, however, many service providers have come to understand that the best way to serve and preserve children is to serve and preserve the supportive networks that benefit children (Family Support America, 1996). An extensive body of research identifies the elements that contribute to children's well-being, beginning with those closest to the child and moving outward to encompass the family, early care/education, the neighborhood, the community, and beyond. This ecological perspective (Bronfenbrenner, 1979) has motivated a growing number of communities to focus more closely on the need for collaboration--engaging in a process that allows the community to address many problems at once rather than one at a time.
One solution that many communities have adopted is the establishment of a collaborative partnership involving all the relevant partners--home, school, and service providers--in the planning and monitoring of services for children (Kagan, 1992; Hoffman, 1991). The goal of most of these collaboration initiatives is to improve child outcomes, recognizing that many of the child's needs are closely linked to needs of the family and the community.
Challenges to Collaboration
Community collaboratives/partnerships represent one of the most challenging--yet one of the most effective--efforts for creating a flexible, comprehensive system that meets the needs of children and families. They involve new relationships among service providers and the children and families they serve. They require time, resources, and the willingness of collaborating agencies to learn about and establish trust with each other. In short, they require change (Bruner, Kunesh, & Knuth, 1992).
As a result of the new roles and responsibilities that service providers must assume, collaboratives/partnerships encounter many common difficulties, including (Melaville, Blank, & Asayesh, 1996):
- staff or agency representatives who are resistant to relinquishing power;
- policies and regulations within individual agencies that make it difficult to coordinate services, information, and resources;
- differences in prior knowledge, training, or experience that make it difficult for members to communicate and work together; and
- lack of time to meet and plan together.
Many factors contribute to the success or failure of a community collaborative, and no two collaboratives operate in exactly the same way. However, certain guidelines seem to help smooth the way for a more successful partnership, including (North Central Regional Educational Laboratory, 1993):
- involve all key stakeholders;
- establish a shared vision of how the partnership will operate and expected outcomes for the children and families served;
- build in ownership at all levels;
- establish communication and decision-making processes that are open and allow conflict to be addressed constructively;
- institutionalize changes through established policies, procedures, and program mandates;
- provide adequate time for partners to meet, plan, and carry out activities.
The process of establishing and maintaining a collaborative partnership is not easy, and in the end, each partnership must find a way to proceed that is consistent with its community and unique set of circumstances. However, a number of resources and tools are available to help communities get started creating an effective system for delivering services. In this article, we describe one such tool that assembles elements essential to building a successful collaborative partnership.
Development of Continuity Framework Materials
For the past eight years, the 10 Regional Educational Laboratories (RELs) serving each region of the country have studied effective strategies for strengthening collaboration and increasing continuity among programs for young children and their families. The RELs are overseen by the U.S. Department of Education's Office of Educational Research and Improvement [now the Institute of Education Sciences], and their primary purpose is ensuring that those involved in educational improvement have access to the best information from research and practice. During the contract period of 1995-2000, the RELs established a program called the Laboratory Network Program (LNP), which convened representatives from each Laboratory as a national network working on common issues.
In 1995, the Early Childhood LNP developed Continuity in Early Childhood: A Framework for Home, School, and Community Linkages (U.S. Department of Education, 1995), a document designed with two key purposes in mind: first, an emphasis on the need for children and families to receive comprehensive and responsive services, reflected in the eight elements of continuity outlined in the Framework (see Figure 1). Taken together, the elements are intended to promote a comprehensive understanding of continuity and transition during early childhood. Second, the Framework offered a set of guidelines that partnerships could use to compare and assess their current policies and practices, as well as identify areas in need of improvement.
Figure 1. Elements of Continuity
(U.S.Department of Education, 1995)
An extensive field review of the Framework indicated that although the document was helpful and informative, many community partnerships continued to have difficulty "getting started." As a result, a Trainer's Guide was developed to support the use of the Framework and assist community partnerships in the first stages. These materials were developed by the Early Childhood LNP in collaboration with the National Center for Early Development & Learning.
The Trainer's Guide provides an overview of the content and potential uses of the Framework and includes all activities and materials necessary to conduct training sessions. The Guide itself consists of four training sessions that are organized around the eight elements of continuity. The materials are designed so that a local partnership has everything needed to conduct the training: background information, scripts, handouts, transparencies, sample agendas, and checklists for additional equipment and supplies:
- The first session, Understanding Continuity, is designed to introduce participants to the Framework document and help participants develop a greater understanding and appreciation for continuity.
- The second session, Developing a Continuity Team, highlights the importance of broad representation and shared leadership among partnership members.
- The third session, Planning for Continuity, emphasizes the need for a comprehensive approach to service delivery and encourages participants to examine their current partnership practices and policies.
- The final session, Formalizing Continuity, focuses on the importance of effective communication among group members and provides participants with an opportunity to formulate action plans.
The Guide is designed to be a flexible training tool, adaptable to meet the needs of a particular audience. The intended audience includes local partnerships for children and families (including Smart Start partnerships in North Carolina), Head Start Program representatives, public schools, and communities. The overall objectives of the training are (1) to enhance the collaborative's knowledge and understanding of continuity, (2) to strengthen and support collaborative groups in their efforts to work as partners, and (3) to maximize the benefit they might receive from using the Framework.
What follows is a description of the field test that was designed to assess the use and effectiveness of the Trainer's Guide. The field test focused exclusively on the Framework materials--no other instructional sources were employed. We will present the major findings of the field test and summarize recommendations based on those findings. In addition, we will highlight the work of several collaborative partnerships that took part in the field study, and we will describe some of the problems they encountered, how they used the Framework materials to address those problems, and where they are today. Specifically, the evaluation will explore:
- To what extent is the information contained in the Framework and Trainer's Guide relevant and useful to community partnerships?
- What is the perceived impact of the training and Framework on partnership activities?
- How do partnerships incorporate elements of the Framework into their ongoing activities?
- Of the review sites that indicated interest in the training materials, what proportion actually conducted the training?
The overall usefulness and effectiveness of the Trainer's Guide was studied in two phases. Phase One consisted of document review and feedback from individuals working in the early childhood field. In Phase Two of field testing, the training was actually piloted in eight partnership sites.
Phase One: Document Review
Reviewers for the Trainer's Guide were solicited through the Laboratory Network Program (LNP) and at conferences related to early childhood issues. Three hundred thirteen individuals/organizations requested a set of the Framework materials (participant manual, Trainer's Guide, and a sample color transparency) and feedback form. Feedback questions centered on four areas: (1) information's relevancy and accuracy, (2) format and organization of the Trainer's Guide, (3) specific training needs, and (4) possible barriers to conducting training.
Of the 313 requesting materials, 215 (68.7%) reviewers returned feedback forms. Twenty-one percent (N = 45) of the respondents were members of a Smart Start partnership (North Carolina initiative), 19% (N = 40) worked in Head Start agencies, and 11% (N = 24) worked in family resource centers. Others included representatives from state agencies, school personnel, and university faculty. A majority (89%) of the respondents indicated that they are actively involved in a community partnership.
Final Follow-up with Select Reviewer Sites. Of the original 215 organizations/individuals who reviewed the Framework materials, 80 indicated an interest in conducting the training in its entirety and requested a complete set of transparencies. (The original materials included one sample color transparency, and the REL offered a complete set of Framework transparencies to all organizations making the request.) Approximately one year after receiving the materials, interviews were conducted with representatives who received transparencies. The purpose of these follow-up telephone calls was to determine if the materials had been used and the degree to which outside support or assistance might be needed to conduct the training.
Phase Two: Pilot Training
During the second phase of the field testing, the training was piloted in eight collaborative partnerships from across the nation (see Table 1). These sites were recruited through the LNP and selected based on their interest in the project. To assist with logistical details, a liaison, identified at each site, coordinated training dates and assisted with data collection. Sites varied according to demographics, partnership maturity, and sponsoring or lead agency.
|Site Location||Community Type||Sponsor/Lead Agency|
|Beaufort, SC||Rural||Success by 6|
|Dothan, AL||Urban||Family Resource Center|
|Walnut Cove, NC||Rural||Smart Start|
|Valdosta, GA||Rural||Family Connections/County Commission|
|Wheeling, WV||Rural||Head Start|
|Troy, NC||Rural||Smart Start|
|Concord, WV||Rural||Family Resource Center|
Five of the partnerships described themselves as existing collaboratives (two years or more), while the remaining three indicated that they were in the planning stages of building a collaborative partnership. Sponsors of the partnerships included Smart Start (2); Head Start, family resource centers (2); Success by 6; a public school system; and a county task force.
Across the eight sites, a total of 160 individuals participated in the training. Approximately 64% of the attendees were White, 27% were African American, and the remainder were either Hispanic, American Indian/Alaskan Native, or multiracial.
Several of the partnerships invited persons who were not part of the collaborative partnership to attend the training. As a result, slightly more than half (54%) of the participants reported that they were current members of the partnership. The majority of these had been members less than one year (53%). Early childhood specialists represented the largest group attending the training (29%), followed by program administrators (18%), teachers/caregivers (14%), and parents (10%). Other groups represented included policy makers, members of the business community, and university faculty.
Each of the sites conducted the entire training course in the fall; however, there was some variability in delivery of training. For example, some partnerships conducted the training as described in the Trainer's Guide--two complete, consecutive days of training. Other partnerships modified the training schedule to meet the needs of its members and used other formats such as one day of training followed two weeks later by a second day of training.
At the conclusion of training, participants were asked to provide feedback on specific elements of the training, including organization, training content, and materials/resources. In addition, participants were asked to comment on their satisfaction with the training and the overall usefulness of the training materials. This information, along with information gathered from the review sites, was used to revise the Trainer's Guide.
In the six months following the training, partnership activities were studied to determine the degree to which the collaboratives incorporated content from the Framework into their regular activities. Materials studied included a record of stakeholder attendance and meeting minutes documenting partnership activities. At the end of this period, a follow-up survey was sent to participants at each pilot site. Survey questions focused on three major areas: (1) impact of the training, (2) impact of the Framework materials, and (3) overall familiarity with Framework materials.
In addition to the final survey with individuals who participated in the training, a final interview was conducted with seven site liaisons (one liaison was unavailable for interview). Interview questions focused on the original goal of the partnership, reasons for participating in the field study, and impact of the training and Framework materials.
The data were analyzed to determine general response patterns and to identify logical changes or improvements to the Trainer's Guide. Both quantitative and qualitative techniques were used to analyze data from the review sites and the pilot sites.
Phase One: Document Review
Analyses of data from reviewer sites were conducted on 215 surveys. Table 2 summarizes Trainer's Guide as easy to understand, relevant to their work, accurate, and up-to-date.
|Survey Statement||Agreed or Strongly Agreed with Statement|
|Information is accurate and up to date.||94.9% (4.54)|
|Format is easy to understand and follow.||93.9% (4.49)|
|Training materials were easy to understand and follow.||92.5% (4.46)|
|Information is relevant to my work.||89.3% (4.41)|
|I would be comfortable using the materials.||83.3% (4.29)|
|*Note: According to the scale, 1 = strongly disagree and 5 = strongly agree. Mean scores are presented in parentheses.|
A series of open-ended questions provided respondents with an opportunity to provide more specific information and feedback. When asked what parts of the training were most useful, of those who responded, approximately 30% reported that the materials were the most useful part of the training. Reviewers specifically mentioned handouts, transparencies, and checklists. Another 22% reported that the information focusing on the need to include families and share leadership responsibilities was most useful.
Reviewers also were asked to identify the greatest training need within their partnerships. Of those who responded, more than one-third (34%) reported that they often need assistance identifying and including community stakeholders. Reviewers cited family members and members of the business community as groups that often are poorly represented at partnership meetings. Other topics representing challenges to partnerships included developing the team, sharing leadership responsibilities, and involving families in meaningful ways.
In terms of barriers or factors that would influence the use of training, most of the respondents (75%) cited time as the greatest barrier to conducting training. This factor was followed by a lack of funding (68%), the unavailability of a trainer (45%), and lack of interest of collaborative partners (39%).
Final Follow-up with Select Reviewer Sites. Of the 80 individuals/organizations who requested a complete set of transparencies, 68 were located for follow-up interviews (85%). For the remaining 12, attempts to contact the site were unsuccessful; either the person requesting the transparencies was no longer there, or the materials were never received.
Interviews revealed that 23 of the respondents had conducted training using the Framework and accompanying materials. Of those who stated that they had conducted the training, only two (less than 10%) had used the training in its entirety. Most had conducted at least one part of the training, selecting the portions most useful for their work. "Families as Partners," "Shared Leadership," and "Comprehensive and Responsive Services" were the elements from the Framework most often used for training.
An additional 17% said that although they had not conducted the training as designed, they had adapted the materials or used them in other circumstances. Examples of how they had adapted the materials included using the exercises, overheads, major concepts, and other information in training activities.
Head Start agencies were the primary sponsors for half of the training events. Public schools, area education associations, state departments of education, local partnerships, child development centers, and related-type centers were listed as sponsors or lead agencies for the remaining training activities.
Training participants included staff and administrators at Head Start agencies, preschool and child care providers, local education agencies, schools, school improvement teams, state departments of education staff, local family service agencies and boards of directors, and parents.
All who said they had used the training materials were asked to comment on the usefulness of the training. The majority of respondents rated the training as "very useful" or "useful," and all said they would recommend the training to others. Particular aspects of the training that respondents liked included:
- professional quality, clarity of materials, and sequencing of content of the Framework;
- handouts, activities, and overheads;
- content and the ability to present the material at multiple skill levels; and
- ease of use of the Framework.
There were suggestions for improving the training. Four respondents said the course was "too long," especially if used in school systems or with parents. Others maintained a need for greater emphasis on action planning and implementation, "more written support materials (research, position support, background), and additional copies of key pieces of materials that helped shape the Framework."
Phase Two: Pilot Training
In terms of the training quality and overall effectiveness, most of the participants rated the training sessions as either "good" or "excellent." Participants tended to rate the second day of training as higher in quality and more effective than the first day of training (M = 4.392 and M = 4.17, respectively, based on a 5-point scale).
Participants also evaluated the effects of the training and estimated its impact on future partnership practices. Using a four-point Likert-type scale, participants rated the extent to which they agreed with each statement. Table 3 summarizes participants' appraisal of the training and reinforces the focus of the original training objectives.
Objective 1: To enhance the collaborative's knowledge and understanding of continuity
|As a result of the training, I believe that I am motivated to build and strengthen continuity efforts in my community.||3.44||.65|
|As a result of the training, I believe that I have a better understanding of continuity and why it is important.||3.41||.65|
|I believe that this training will have an impact on increasing awareness of new skills and knowledge for our team.||3.31||63|
Objective 2: To strengthen and support collaborative groups in their efforts to works as partners
|As a result of the training, I believe that I am better able to participate as a member of a home, school, and community partnership.||3.40||.65|
|I believe that this training will have an impact on how decisions are made and the planning we do for services.||3.25||.59|
|I believe that this training will have an impact on changing/enhancing the quality of community practices.||3.23||.58|
Objective 3: To maximize the benefit the collaborative might receive from using the Framework
|As a result of the training, I believe that I am better able to use the Framework as a tool for exploring continuity and transition||3.26||.63|
|I believe that this training will have an impact on positively affecting outcomes for children and families.||3.31||.63|
|*Note: According to the scale, 1 = strongly disagree and 4 = strongly agree.|
In addition to participant ratings immediately following the training, data were collected on regular partnership activities after the training. Analysis of materials such as meeting minutes revealed that during the six months following completion of the training, five of the eight sites reported that they continued to use the Framework materials. Exactly how the materials were used varied from site to site. Two of the sites selected specific elements of the Framework as their priority concerns for the coming year. They then organized subcommittees to review the partnerships' practices with respect to those elements and make recommendations for improving existing services. Another partnership used the materials to provide training to other agencies and organizations not directly involved with the partnership. The remaining two partnerships used the Framework as a resource for improving transition practices with their communities.
At the end of the six months, a final survey was distributed to participants at the last partnership meeting of the year, and surveys were mailed to those not in attendance at the final meeting. Approximately half of the individuals who participated in the training (81 of 160) responded to the survey. Participants were asked to rate the extent to which the Framework materials had had an impact on partnership practices. On a four-point scale (4 = "a great deal," 3 = "some," 2 = "very little," and 1 = "not at all"), the majority of respondents (88.6%) reported that the training had "impacted" their knowledge and skill development "some" or a "great deal." Respondents also thought that the Framework had at least "some" impact on the knowledge and skills development of their partnership (83%) and community (72%). The majority (97.4%) speculated that the Framework would have at least some future impact.
Finally, participants were asked to indicate the single greatest impact they experienced as a result of the training. Approximately 41% reported that as a result of the training they felt more motivated to build or strengthen efforts to support continuity of services for children in their communities. Thirty-five percent of the respondents said they had a better understanding of continuity and its importance; 17% felt that the training prepared them to be better members of their partnership; and 7% said that the training gave them a greater understanding of the Framework as a tool.
Stokes County Partnership for Children, King, NC
An ongoing goal of the Stokes County Partnership for Children is to create a system that encourages service providers to work together and promotes continuity for children and their families. Members of the partnership began by using the Framework to build their own knowledge and skills about continuity; however, they soon recognized the need to inform others of the importance of continuity in children's lives. As a result, the Partnership conducted a series of focus groups and meetings among parents and family members within the community. They used information from Elements 3 (Comprehensive/Responsive Services) and 7 (Developmentally Appropriate Care/Education) to explain what was needed to support continuity and its potential benefits for children. These meetings were also an opportunity to inform families of the various resources and supports available within the community. Later, the focus groups were expanded to include all stakeholders (e.g., child care, kindergarten, Head Start, school administrators, special needs coordinators, etc). The information gathered from these meetings has been used to guide the development and implementation of policies and practices that promote continuity.
Final Interview with Liaisons. In the final interview conducted with site liaisons, five of the seven liaisons reported that the overall goal of their partnership is to improve services for children and their families by connecting agencies and strengthening the collaborative bonds between those agencies. Three of the liaisons specifically mentioned the need to improve transitions and create a system of responsive and comprehensive services.
In addition, liaisons were asked to talk about their reasons for participating in the field-test process. At least three of the liaisons cited low levels of collaboration across agencies and indicated that partnership meetings were used primarily as a time for sharing information. Others saw the training as an opportunity to invite additional partners to the table and begin a discussion of how they could better work together.
Finally, liaisons were asked to rate the extent to which the Framework materials had been helpful in accomplishing their overall partnership goal. Using a five-point scale, five of the liaisons rated the Framework materials as either "helpful" (4) or "very helpful" (5). The remaining two liaisons rated the Framework materials as at least "somewhat helpful" (3).
Developing and maintaining a community collaborative is hard work, and it is a challenge that requires a great deal of commitment and cooperation from those involved. Training and resource materials available to help community partnerships build a more responsive system must address such issues as time constraints, communication gaps, differences in professional training, and funding limitations. Given these challenges, the Continuity Framework and its Trainer's Guide seem to be important and useful tools for helping partnerships increase collaboration and involvement.
Data gathered from participant ratings and key-informant interviews indicated that the training was helpful in a number of ways. A feature of the training mentioned by many of the participants was the fact that the experience helped "level the playing field." That is, it provided stakeholders with a common language to use as they worked together. As illustrated in the following example, stakeholders often come from a variety of agencies and backgrounds, which can be a major impediment when a community must begin to work together and coordinate its efforts.
The case studies in the sidebars highlight the work of four collaborative partnerships that took part in the field study. These case studies discuss some of the problems they encountered, how they used the Framework materials to address those problems, and where they are today.
Bovill, Idaho, Collaborative
Bovill is a small town (population 310) located in the north central part of the state. Bovill has no resident doctor or dentist. At the time, there also was no child care center or preschool available to children. (The closest one was 35 miles away.)
In 1998, various members of the community decided that they wanted to do something to help improve the situation for children. This group of citizens brought together parents and virtually every local organization to work on a plan that would support the learning needs of children and their families. Part of this effort was a proposal submitted to the J.A. and Kathryn Albertson Foundation that would help fund an early learning center. In 1999, they were awarded a grant, and they began the work to open the Bovill Early Childhood Community Learning Center.
However, once the work began, members of the partnership found that they did not have a common vocabulary to talk about the issues of early childhood education. There were also difficulties associated with establishing a partnership, such as "Who else should be included?" and "How do you get started?" In an effort to "get started" and begin the planning process, the partnership elected to participate in the field testing of the Framework materials.
Framework training was provided over two consecutive days and built into the inservice training schedule of the elementary school. In addition to staff and faculty from the elementary school, representatives from other agencies and organizations participated, including the health department, the Idaho Department of Disabilities, news media, schools, early childhood education, Even Start, parents, university students, attorneys, community leaders, and businesses.
According the site liaison, the Framework materials were used:
- To improve awareness of key issues in providing high-quality services. The Framework provides direction to help develop a program that really works.
- To provide a common language and for internal communication enhancement. Now everyone "speaks the same language."
- As an external communication tool. According to the liaison, "it is so much easier to talk with funding sources when you use the structure of the elements as a base."
- To validate their progress toward providing the best practices in early childhood education.
- As a piece of the Bovill Elementary School improvement plan.
Positive impact on individual partnership members was cited as another basis for success of the training. Many indicated they had a better understanding of continuity and were more motivated to continue to work on the difficult issues that often arise as part of the collaborative process. An added value of the training was the opportunity to spend time together and develop relationships with persons from other agencies. Often, these individual relationships help form the basis for collaborative work within the partnership.
Based on the sites that continued to use the materials, the Continuity Framework and its Trainer's Guide seem to be equally useful to both existing and newly established partnerships. A common experience in the maturation of partnerships is that they are prone to lose initial momentum, often stagnating into "easy" roles such as simple information sharing. A serendipitous discovery of this study is that such partnerships evidenced rejuvenation of their efforts after participating in the training (see the Valdosta, Georgia, example).
Valdosta, Georgia, Collaborative
The Lowndes County/Valdosta Commission for Children and Youth has been in existence for more than a decade, and during this time, the partnership has experienced various "ups and downs." According to site liaison Vickie Elliott, cycles are a normal part of the collaborative process, "They may be the result of staff turnover or changes in the board chair and/or board members." She reports that participation in the training provided members with practical, research-based information. This information served as a reminder to members that they were doing good work and that their work was important.
Since the training, the partnership has continued to use Framework materials as a reference and resource. For example, during a recent meeting, members began a discussion regarding the evaluation of partnership activities. They used Element 8: Evaluation of Partnership Success to help shape and guide this discussion. In addition, the partnership has applied for and received a 21st Century Learning Community grant. Because of the knowledge and understanding they gained during the training, members requested funds for a case manager position to be based at each school and conducting home visits. It is hoped that this strategy will facilitate communication and create greater continuity of services for students and families.
Finally, the data indicate that change takes place slowly. Participants reported that the training had had some impact on their community but felt that the greatest impact was yet to come. Bringing everyone to the table is not enough. True collaboration that produces continuity in services for children takes place over a long period of time, as agencies that have not previously worked together begin to get to know each other and slowly modify procedures and practices.
Marshall County Tadpole Team, Wheeling, WV
Efforts to collaborate are often driven by the realization that single agencies cannot solve problems alone. Partners must be willing to jointly plan and implement new ventures, as well as pool resources such as money and personnel. Nowhere is this need to collaborate and pool resources more crucial than in Marshall County, WV. Located in the northern part of West Virginia, Marshall County remains a predominantly rural county. With a population of approximately 36,000, Marshall County has seen a decline in the number of residents over the past two to three years, largely attributed to the economic hardships of the area. This part of West Virginia relies heavily on the coal and steel industries, and as these industries have fallen on hard times, so too have many families. As a result, many families have moved away to find other employment; however, many others have sought support from social services agencies within the community. In order to make the most of the limited resources and support available within the county, many of the local agencies (e.g., Northern Panhandle Head Start, Starting Points Center, Tadpoles Team) came together to form a community collaborative. Although their collaborative meetings began more as a time for sharing information, members soon realized that to be a true "working group," they would need to broaden the meeting agendas and formalize the collaborative relationships. Using the Framework materials as an assessment tool, members worked through each element identifying the gaps in services and generating ideas for possible programs and procedures to address those gaps. This shift encouraged members to devote meeting times to discussing specific issues facing the community. Moreover, it encouraged members to formalize the partnership with written agreements. These agreements have allowed members to make a solid commitment to the collaborative, as well as clarify specific roles and responsibilities for services.
Beyond the content of the training and issues related to the collaborative process, the field study underscored the importance of training structure and design. Many study participants praised the Framework materials for flexibility and relevance to a variety of contexts. The training materials were designed so that particular attention was devoted to issues such as target audience attributes (e.g., varied educational and professional development backgrounds), which dictate the appropriate level of sophistication as well as the need for course module structure (i.e., overall organization and scripting) to be highly adaptable to local training needs.
The field studies indicate that community partnerships benefit from training and technical assistance that help with the process of getting started, as well as recapturing momentum and focus. Additional research is needed to document the ongoing efforts of these communities and explore whether the Framework materials continue to have an impact on community practices and outcomes, as many of the participants predicted. Further study also is needed to determine what other kinds of training or technical assistance might be useful to these partnerships as they work to build capacity and expand or grow new programs.
Bronfenbrenner, Urie. (1979). The ecology of human development. Cambridge, MA: Harvard University Press.
Bruner, Charles; Kunesh, Linda; & Knuth, Randy. (1992). What does research say about interagency collaboration? [Online]. Oak Brook, IL: North Central Regional Educational Laboratory. Available: http://www.ncrel.org/sdrs/areas/stw_esys/8agcycol.htm [2002, October 22].Editor's Note: this url is no longer active.
Family Support America. (1996). Making the case for family support [Online]. Chicago: Author. Available: http://www.familysupportamerica.org/content/pub_proddef.htm [2002, October 22]. Editor's Note: this url is no longer active.
Hoffman, Stevie (Ed.). (1991). Educational partnerships: Home-school-community [Special issue]. Elementary School Journal, 91(3).
Kagan, Sharon Lynn. (1992). The strategic importance of linkages and the transition between early childhood programs and early elementary school. In Sticking together: Strengthening linkages and the transition between early childhood education and early elementary school (Summary of a National Policy Forum). Washington, DC: U.S. Department of Education. ED 351 152.
Kunesh, Linda. (1994). Integrating community services for children, youth, and families. Oak Brook, IL: North Central Regional Educational Laboratory.
Melaville, Atelia; Blank, Martin; & Asayesh, Gelareh. (1996). Together we can: A guide for crafting a profamily system of education and human services (Rev. ed.). Washington, DC: U.S. Department of Education. Available: http://eric-web.tc.columbia.edu/families/TWC/ Editor's Note: this url is no longer active.[2002, October 22]. ED 443 164.
North Central Regional Educational Laboratory. (1993). NCREL's policy briefs: Integrating community services for young children and their families. Oak Brook, IL: Author. Available: http://www.ncrel.org/sdrs/areas/issues/envrnmnt/go/93-3toc.htm [2002, October 22].
U.S. Department of Education and U.S. Department of Health and Human Services. (1995). Continuity in early childhood: A framework for home, school, and community linkages [Online]. Washington, DC: Author. Available: http://www.sedl.org/prep/hsclinkages.pdf [2002, October 22]. ED 395 664.
Wheatley, Margaret J. (1992). Leadership and the new science. San Francisco: Berrett-Koehler.
Dr. Glyn Brown is a senior program specialist with SERVE Regional Educational Laboratory. She studied at the University of Alabama (B.S.), the University of Southern Mississippi (M.S.), and completed her Ph.D. in Family and Child Development at Auburn University. Prior to coming to SERVE, Dr. Brown worked as a children's therapist in a community mental health program. As a program specialist with SERVE, Dr. Brown provides training and direct consultation to school personnel, child care providers, and community partnerships.
SERVE Regional Educational Laboratory
1203 Governor's Square Blvd., Suite 400
Tallahassee, FL 32301
Carolynn Amwake, a program specialist at the SERVE Regional Educational Laboratory, has extensive experience working with families, child care providers, teachers, administrators, and community partners. She received her B.S. from Radford University in early childhood education and special education and has taught children with special needs in elementary schools, children's homes, and child care centers. Her experiences as an educator and parent led to an interest in improving the quality and continuity of early childhood transitions for both children and families.
SERVE Regional Educational Laboratory
1203 Governor's Square Blvd., Suite 400
Tallahassee, FL 32301
Timothy Speth is a research associate at Northwest Regional Educational Laboratory (NWREL). He received his B.S. in psychology from South Dakota State University and his M.A. from San Diego State University. He has extensive training and experience in research design, statistics, and program evaluation. Mr. Speth is currently involved with several research and evaluation projects throughout the Northwest, as a Research Associate of NWREL's Child and Family Program. He is the primary external evaluator for six Alaska schools participating in the Comprehensive School Reform Demonstration Project (CSRD) and assists in CSRD-related activities throughout the Northwest.
Northwest Regional Educational Laboratory
101 S.W. Main Street, Suite 500
Portland, OR 97204-3297
Catherine Scott-Little, Ph.D., is director of the Expanded Learning Opportunities Project for SERVE. Dr. Little completed her graduate work in human development at the University of Maryland, College Park. Her undergraduate degree in child development and family relations is from the University of North Carolina at Greensboro. Prior to joining SERVE, Dr. Little was deputy director of a large Head Start program in Fort Worth, Texas, and she has also served as director for a child development center serving homeless families in the Washington, DC, area.
SERVE Regional Educational Laboratory
P.O. Box 5367
Greensboro, NC 27435
|
Using the Moon as a High-Fidelity Analogue Environment to Study Biological and Behavioural Effects of Long-Duration Space Exploration
Goswami, Nandu and Roma, Peter G. and De Boever, Patrick and Clément, Gilles and Hargens, Alan R. and Loeppky, Jack A. and Evans, Joyce M. and Stein, T. Peter and Blaber, Andrew P. and Van Loon, Jack J.W.A. and Mano, Tadaaki and Iwase, Satoshi and Reitz, Guenther and Hinghofer-Szalkay, Helmut G. (2012) Using the Moon as a High-Fidelity Analogue Environment to Study Biological and Behavioural Effects of Long-Duration Space Exploration. Planetary and Space Science, Epub ahead of print (in press). Elsevier. DOI: 10.1016/j.pss.2012.07.030.
Full text not available from this repository.
Due to its proximity to Earth, the Moon is a promising candidate for the location of an extra-terrestrial human colony. In addition to being a high-fidelity platform for research on reduced gravity, radiation risk, and circadian disruption, the Moon qualifies as an isolated, confined, and extreme (ICE) environment suitable as an analogue for studying the psychosocial effects of long-duration human space exploration missions and understanding these processes. In contrast, the various Antarctic research outposts such as Concordia and McMurdo serve as valuable platforms for studying biobehavioral adaptations to ICE environments, but are still Earth-bound, and thus lack the low-gravity and radiation risks of space. The International Space Station (ISS), itself now considered an analogue environment for long-duration missions, better approximates the habitable infrastructure limitations of a lunar colony than most Antarctic settlements in an altered gravity setting. However, the ISS is still protected against cosmic radiation by the earth magnetic field, which prevents high exposures due to solar particle events and reduces exposures to galactic cosmic radiation. On Moon the ICE environments are strengthened, radiations of all energies are present capable of inducing performance degradation, as well as reduced gravity and lunar dust. The interaction of reduced gravity, radiation exposure, and ICE conditions may affect biology and behavior--and ultimately mission success--in ways the scientific and operational communities have yet to appreciate, therefore a long-term or permanent human presence on the Moon would ultimately provide invaluable high-fidelity opportunities for integrated multidisciplinary research and for preparations of a manned mission to Mars.
|Title:||Using the Moon as a High-Fidelity Analogue Environment to Study Biological and Behavioural Effects of Long-Duration Space Exploration|
|Journal or Publication Title:||Planetary and Space Science|
|In Open Access:||No|
|In ISI Web of Science:||Yes|
|Volume:||Epub ahead of print (in press)|
|Keywords:||Physiology, Orthostatic tolerance, Muscle deconditioning, Behavioural health, Psychosocial adaptation, Radiation, Lunar dust, Genes, Proteomics|
|HGF - Research field:||Aeronautics, Space and Transport, Aeronautics, Space and Transport|
|HGF - Program:||Space, Raumfahrt|
|HGF - Program Themes:||W EW - Erforschung des Weltraums, R EW - Erforschung des Weltraums|
|DLR - Research area:||Space, Raumfahrt|
|DLR - Program:||W EW - Erforschung des Weltraums, R EW - Erforschung des Weltraums|
|DLR - Research theme (Project):||W - Vorhaben MSL-Radiation (old), R - Vorhaben MSL-Radiation|
|Institutes and Institutions:||Institute of Aerospace Medicine > Radiation Biology|
|Deposited By:||Kerstin Kopp|
|Deposited On:||27 Aug 2012 08:05|
|Last Modified:||07 Feb 2013 20:40|
Repository Staff Only: item control page
|
/*
Copyright (C) 1997-2011 by Suntail.com AS, Tim Whelan
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <ofsys.h>
#include <storageblobbuffer.h>
#if defined(OFOPSYS_SOLARIS)
#include <strings.h>
#endif
StorageBlobBuffer::StorageBlobBuffer( ):
m_blob( NULL ), m_left( -1 ), m_ptr( NULL ), m_dyn( false )
{
}
StorageBlobBuffer::StorageBlobBuffer( unsigned char *aBlob,
int aSize,
bool dynFlag ):
m_blob( aBlob ),
m_left( aSize ),
m_ptr( aBlob ),
m_dyn( dynFlag )
{
}
StorageBlobBuffer::~StorageBlobBuffer( )
{
if ( m_dyn )
delete [] m_blob;
}
void
StorageBlobBuffer::makeEmpty()
{
if ( m_dyn )
delete [] m_blob;
m_blob = m_ptr = NULL;
m_left = -1;
m_dyn = false;
}
void
StorageBlobBuffer::bufferTaken( )
{
m_dyn = false;
}
void
StorageBlobBuffer::setupBlob( unsigned char *aBlob, int aSize )
{
m_ptr = m_blob = new unsigned char [ aSize ];
m_left = aSize;
m_dyn = true;
bcopy( aBlob, m_blob, aSize );
}
bool
StorageBlobBuffer::hasOverflowed( )
{
return m_left < 0;
}
void
StorageBlobBuffer::allocate( )
{
m_left = m_ptr - m_blob;
if ( m_dyn )
delete[] ( m_blob );
m_ptr = m_blob = new unsigned char[m_left];
m_dyn = true;
}
unsigned char *
StorageBlobBuffer::getBlob( )
{
return m_blob;
}
int
StorageBlobBuffer::getSize( )
{
return m_ptr - m_blob;
}
void
StorageBlobBuffer::writeBool( bool aBool )
{
if ( --m_left < 0 )
{
m_ptr++;
return;
}
*m_ptr++ = aBool ? 1 : 0;
}
void
StorageBlobBuffer::writeInt08( ofint32 anInt )
{
if ( ( m_left -- ) < 0 )
{
m_ptr ++;
return;
}
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeInt16( ofint32 anInt )
{
if ( ( m_left -= 2 ) < 0 )
{
m_ptr += 2;
return;
}
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeInt32( ofint32 anInt )
{
if ( ( m_left -= 4 ) < 0 )
{
m_ptr += 4;
return;
}
*m_ptr++ = static_cast < char >( anInt >> 24 );
*m_ptr++ = static_cast < char >( anInt >> 16 );
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeInt64( ofuint64 anInt )
{
if ( ( m_left -= 8 ) < 0 )
{
m_ptr += 8;
return;
}
*m_ptr++ = static_cast < char >( anInt >> 56 );
*m_ptr++ = static_cast < char >( anInt >> 48 );
*m_ptr++ = static_cast < char >( anInt >> 40 );
*m_ptr++ = static_cast < char >( anInt >> 32 );
*m_ptr++ = static_cast < char >( anInt >> 24 );
*m_ptr++ = static_cast < char >( anInt >> 16 );
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeString( const char *aString )
{
int i = strlen( aString ) + 1;
if ( ( m_left -= i ) >= 0 )
OFOS::strcpy( ( char * ) m_ptr, aString );
m_ptr += i;
}
void
StorageBlobBuffer::writeIdentity( const OFIDENTITY * anId )
{
writeInt32( anId->m_flags );
writeInt64( anId->m_id0 );
writeInt64( anId->m_id1 );
}
void
StorageBlobBuffer::readIdentity( OFIDENTITY * anId )
{
anId->m_flags = readInt32( );
anId->m_id0 = readInt64( );
anId->m_id1 = readInt64( );
}
void
StorageBlobBuffer::writeServerIdentity( const SRVIDENTITY * anId )
{
assert( anId );
writeInt64( anId->m_id );
}
void
StorageBlobBuffer::readServerIdentity( SRVIDENTITY * anId )
{
anId->m_id = readInt64( );
}
void
StorageBlobBuffer::writeIdentityList( vector < OFIDENTITY * >*list )
{
writeInt32( list->size( ) );
for ( vector < OFIDENTITY * >::iterator i = list->begin( ); i != list->end( ); i++ )
writeIdentity( *i );
}
void
StorageBlobBuffer::writeDouble( double aDouble )
{
if ( ( m_left -= 8 ) < 0 )
{
m_ptr += 8;
return;
}
ofint64 anInt = *( ofint64 * ) ( &aDouble );
*m_ptr++ = static_cast < char >( anInt >> 56 );
*m_ptr++ = static_cast < char >( anInt >> 48 );
*m_ptr++ = static_cast < char >( anInt >> 40 );
*m_ptr++ = static_cast < char >( anInt >> 32 );
*m_ptr++ = static_cast < char >( anInt >> 24 );
*m_ptr++ = static_cast < char >( anInt >> 16 );
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeBinary( void *data,
ofuint32 size )
{
if ( ( m_left -= size ) < 0 )
{
m_ptr += size;
return;
}
memcpy( m_ptr, data, size );
m_ptr += size;
}
bool
StorageBlobBuffer::readBool( )
{
return ( *m_ptr++ != 0 );
}
ofint32 StorageBlobBuffer::readInt08( )
{
ofuint32 anInt;
anInt = *m_ptr++;
return anInt;
}
ofint32 StorageBlobBuffer::readInt16( )
{
ofuint32 anInt;
anInt = *m_ptr++ << 8;
anInt |= *m_ptr++;
return anInt;
}
ofint32 StorageBlobBuffer::readInt32( )
{
ofint32 anInt;
anInt = *m_ptr++ << 24;
anInt |= *m_ptr++ << 16;
anInt |= *m_ptr++ << 8;
anInt |= *m_ptr++;
return anInt;
}
ofuint64 StorageBlobBuffer::readInt64( )
{
ofuint64 anInt;
anInt = ( ( ofuint64 ) * m_ptr++ ) << 56;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 48;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 40;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 32;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 24;
anInt |= *m_ptr++ << 16;
anInt |= *m_ptr++ << 8;
anInt |= *m_ptr++;
return anInt;
}
char *
StorageBlobBuffer::readString( )
{
ofint32 len = strlen( ( char * ) m_ptr ) + 1;
char *aString = new char[len];
OFOS::strcpy( aString, ( const char * ) m_ptr );
m_ptr += len;
return aString;
}
char *
StorageBlobBuffer::tempReadString( )
{
ofint32 len = strlen( ( char * ) m_ptr ) + 1;
char *aString = ( char * ) m_ptr;
m_ptr += len;
return aString;
}
void
StorageBlobBuffer::readString( char *aString )
{
OFOS::strcpy( aString, ( const char * ) m_ptr );
m_ptr += strlen( ( char * ) m_ptr ) + 1;
}
void
StorageBlobBuffer::readIdentityList( vector < OFIDENTITY * >*list )
{
ofuint32 count = readInt32( );
for ( ; count; count-- )
{
OFIDENTITY *id = new OFIDENTITY;
readIdentity( id );
list->push_back( id );
}
}
double
StorageBlobBuffer::readDouble( )
{
ofint64 anInt;
anInt = ( ( ofuint64 ) * m_ptr++ ) << 56;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 48;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 40;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 32;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 24;
anInt |= *m_ptr++ << 16;
anInt |= *m_ptr++ << 8;
anInt |= *m_ptr++;
return *( ( double * ) &anInt );
}
void
StorageBlobBuffer::readBinary( void *data,
ofuint32 size )
{
memcpy( data, m_ptr, size );
m_ptr += size;
}
void
StorageBlobBuffer::setReadPosition( ofuint32 pos )
{
m_ptr = m_blob + pos;
}
void
StorageBlobBuffer::setWritePosition( ofuint32 pos )
{
m_ptr = m_blob + pos;
m_left = 0x7fffffff;
}
ofuint32
StorageBlobBuffer::getCurrentPosition()
{
return m_ptr-m_blob;
}
|
German destroyer Z11 Bernd von Arnim
|Career (Nazi Germany)|
|Name:||Z11 Bernd von Arnim|
|Namesake:||Bernd von Arnim|
|Ordered:||9 January 1935|
|Laid down:||26 April 1935|
|Launched:||8 July 1936|
|Completed:||6 December 1938|
|Fate:||Scuttled, 13 April 1940|
|General characteristics as built|
|Class & type:||Type 1934A-class destroyer|
|Displacement:||2,171 long tons (2,206 t)|
|Length:||119 m (390 ft 5 in) o/a
114 m (374 ft 0 in) w/l
|Beam:||11.3 m (37 ft 1 in)|
|Draft:||4.23 m (13 ft 11 in)|
|Installed power:||70,000 shp (52,000 kW)|
|Propulsion:||2 shafts, 2 × Wagner geared steam turbines
6 × water-tube boilers
|Speed:||36 knots (67 km/h; 41 mph)|
|Range:||1,825 nmi (3,380 km; 2,100 mi) at 19 knots (35 km/h; 22 mph)|
|Armament:||5 × 1 - 12.7 cm (5 in) guns
2 × 2 - 3.7 cm (1.5 in) guns
6 × 1 - 2 cm (0.79 in) guns
2 × 4 - 53.3 cm (21 in) torpedo tubes
32–64 depth charges, 4 throwers and 6 individual racks
Z11 Bernd von Arnim was a Type 1934A-class destroyer built for the German Navy (Kriegsmarine) in the late 1930s. At the beginning of World War II, the ship was initially deployed to blockade the Polish coast, but she was quickly transferred to the German Bight to lay minefields in German waters. In late 1939 the ship made one successful minelaying sortie off the English coast that claimed one British warship and seven merchant ships. During the early stages of the Norwegian Campaign, Bernd von Arnim fought the British destroyer Glowworm while transporting troops to the Narvik area in early April 1940, but neither ship was damaged during the action. The ship fought in both naval Battles of Narvik several days later and had to be scuttled after she exhausted her ammunition.
Design and description
Bernd von Arnim had an overall length of 119 meters (390 ft 5 in) and was 114 meters (374 ft 0 in) long at the waterline. The ship had a beam of 11.3 meters (37 ft 1 in), and a maximum draft of 4.23 meters (13 ft 11 in). She displaced 2,171 long tons (2,206 t) at standard load and 3,190 long tons (3,240 t) at deep load. The Wagner geared steam turbines were designed to produce 70,000 shaft horsepower (52,199 kW) which would propel the ship at 36 knots (67 km/h; 41 mph). Steam was provided to the turbines by six high-pressure Benson boilers with superheaters. Bernd von Arnim carried a maximum of 752 metric tons (740 long tons) of fuel oil which was intended to give a range of 4,400 nautical miles (8,100 km; 5,100 mi) at 19 knots (35 km/h; 22 mph), but the ship proved top-heavy in service and 30% of the fuel had to be retained as ballast low in the ship. The effective range proved to be only 1,530 nmi (2,830 km; 1,760 mi) at 19 knots (35 km/h; 22 mph).
Bernd von Arnim carried five 12.7 cm SK C/34 guns in single mounts with gun shields, two each superimposed, fore and aft. The fifth gun was carried on top of the rear deckhouse. Her anti-aircraft armament consisted of four 3.7 cm SK C/30 guns in two twin mounts abreast the rear funnel and six 2 cm C/30 guns in single mounts. The ship carried eight above-water 53.3-centimeter (21.0 in) torpedo tubes in two power-operated mounts. Four depth charge throwers were mounted on the sides of the rear deckhouse and they were supplemented by six racks for individual depth charges on the sides of the stern. Enough depth charges were carried for either two or four patterns of 16 charges each. Mine rails could be fitted on the rear deck that had a maximum capacity of 60 mines. 'GHG' (Gruppenhorchgerät) passive hydrophones were fitted to detect submarines.
The ship was ordered on 4 August 1934 and laid down at Germania, Kiel on 26 March 1935 as yard number G537. She was launched on 8 July 1936 and completed on 6 July 1938. When World War II began in September 1939, Bernd von Arnim was initially deployed in the Baltic to operate against the Polish Navy and to enforce a blockade of Poland, but she was soon transferred to the German Bight where she joined her sisters in laying defensive minefields. The ship also patrolled the Skagerrak to inspect neutral shipping for contraband goods. Bernd von Arnim joined the other destroyers in laying minefields off the British coast in November, when Bernd von Arnim, Hermann Künne and Wilhelm Heidkamp laid about 180 magnetic mines in the middle of the Thames Estuary on the night of 17/18 November. The destroyer HMS Gipsy, one trawler, and seven other ships totalling 27,565 Gross Register Tons (GRT) were sunk by this minefield. Four days later, she was one of the destroyers escorting the battleships Gneisenau and Scharnhorst through the North Sea to break out into the North Atlantic. Together with her sisters Hans Lody and Erich Giese, Bernd von Arnim was to lay a minefield off Cromer during the night of 6/7 December, but she had trouble with two of her boilers and had to shut them down. The ship was ordered to return to port while the other two destroyers continued their mission.
Norwegian Campaign
Bernd von Arnim was allocated to Group 1 for the Norwegian portion of Operation Weserübung in April 1940. The group's task was to transport the 139th Mountain Infantry Regiment (139. Gebirgsjäger Regiment) and the headquarters of the 3rd Mountain Division (3. Gebirgs-Division) to seize Narvik. The ships began loading troops on 6 April and set sail the next day. Bernd von Arnim was spotted by the British destroyer Glowworm in a storm on the morning of 8 April and the ship turned away to the north-west at full speed after laying a smoke screen. The German ship was suffering damage from the heavy seas at 35 knots (65 km/h; 40 mph) and was forced to reduce speed to 27 knots (50 km/h; 31 mph) after she had lost two men overboard. The British destroyer was better suited for the conditions and began to close on Bernd von Arnim. Lieutenant Commander (Korvettenkapitän) Curt Rechel, captain of von Arnim, turned his ship to the north-east, closer to the heavy cruiser Admiral Hipper. The ships exchanged fire without effect for an hour until Hipper came within range and sank Glowworm shortly afterward.
The German destroyers reached the Ofotfjord on the morning of 9 April and Commodore Friedrich Bonte took his flagship Wilhelm Heidkamp, Bernd von Arnim and Georg Thiele down the fjord to Narvik. A heavy snowstorm allowed von Arnim and Thiele to enter the harbor without challenge and tie up at a pier. The mountain troops immediately began disembarking, but the ship was spotted by the coast defense ship Norge a few minutes later. The latter ship immediately opened fire and was able to fire approximately 13 shells at 600–800 meters (660–870 yd) range before von Arnim was able to fire seven torpedoes. Only two struck the Norwegian ship, but they detonated one or more of the ship's magazines and she immediately capsized and sank. None of the Norwegian shells hit either of the two German destroyers due to the darkness and falling snow, despite the short range. Von Arnim lowered boats to rescue the surviving Norwegian sailors and was able to pick up 96 men together with boats from the merchantmen in harbor.
Von Arnim and Thiele were the first to refuel from the single tanker that had made it safely to Narvik and later moved to the Ballangenfjord, a southern arm of the Ofotfjord, closer to the entrance. Shortly before dawn on 10 April, the five destroyers of the British 2nd Destroyer Flotilla surprised the five German destroyers in Narvik harbor. They torpedoed two destroyers and badly damaged the other three while suffering only minor damage themselves. As they were beginning to withdraw they encountered the three destroyers of the 4th Flotilla which had been alerted in the Herjansfjord when the British began their attack. The Germans opened fire first, but the gunnery for both sides was not effective due to the mist and the smoke screen laid by the British as they retreated down the Ofotfjord. The German ships had to turn away to avoid a salvo of three torpedoes fired by one of the destroyers in Narvik, but von Arnim and Thiele had also been alerted and were coming up to engage the British.
The two German destroyers crossed the T of the British flotilla and were able to fire full broadsides at a range of only 4,000 meters (13,000 ft). They first engaged the British flagship, HMS Hardy, and badly damaged her. Both of her forward guns were knocked out and the forward superstructure was set afire. Hardy was forced to beach herself lest she sink, and the German ships switched their fire to HMS Havock, the next ship in line. Their fire was relatively ineffective and both sides fired torpedoes without scoring any hits. Havock pulled out and dropped to the rear to fight off any pursuit by the ships of the 4th Flotilla. This placed HMS Hunter in the lead and she was quickly set on fire by the German ships. Thiele probably also hit her with a torpedo and she was rammed from behind by HMS Hotspur when the latter ship lost steering control. Hotspur was able to disengage, but Hunter capsized shortly afterward. The three remaining British ships were able to escape from the Germans under the cover of a smoke screen. Von Arnim had been hit by five British shells, which had knocked out one boiler. This was repaired by the morning of 13 April and she received six torpedoes from the badly damaged destroyers.
On the night of 12 April, Commander Erich Bey, the senior surviving German officer, received word to expect an attack the following day by British capital ships escorted by a large number of destroyers and supported by carrier aircraft. The battleship Warspite and nine destroyers duly appeared on 13 April, although earlier than Commander Bey had expected, and caught the Germans out of position. The five operable destroyers, including Bernd von Arnim, charged out of Narvik harbor and engaged the British ships. Although no hits were scored, they did inflict splinter damage on several of the destroyers. The ship was able to make a torpedo attack on the British destroyers before being driven off, but her torpedoes all missed. Lack of ammunition forced the German ships to retreat to the Rombaksfjorden (the easternmost branch of the Ofotfjord), east of Narvik, where they might attempt to ambush pursuing British destroyers. Von Arnim had exhausted her ammunition and she was beached at the head of the fjord. Her crew placed demolition charges and abandoned the ship. By the time the British reached the ship she had rolled over onto her side. The ship's crew joined the German troops ashore and participated in the campaign until the British evacuated the area in June.
- Groener, p. 199
- Whitley, p. 18
- Koop and Schmolke, p. 26
- Whitley, p. 215
- Whitley, pp. 71–72
- Whitley, p. 204
- Koop and Schmolke, p. 91
- Rohwer, pp. 2–3, 5, 7
- Rohwer, p. 9
- Whitley, p. 89
- Hervieux, p. 112
- Whitley, pp. 89–90
- Whitley, p. 96
- Haarr, pp. 91–93
- Haarr, p. 323
- Haarr, pp. 327
- Haarr, p. 334
- Whitley, p. 99
- Harr, pp. 339–43
- Haarr, pp. 344–47
- Whitley, p. 101
- Haarr, pp. 356–57, 362, 366
- Whitley, p. 103
- Haarr, pp. 368, 373–74
- Gröner, Erich (1990). German Warships: 1815–1945. Volume 1: Major Surface Warships. Annapolis, Maryland: Naval Institute Press. ISBN 0-87021-790-9.
- Hervieux, Pierre (1980). "German Destroyer Minelaying Operations Off the English Coast (1940–1941)". In Roberts, John. Warship IV. Greenwich, England: Conway Maritime Press. pp. 110–16. ISBN 0-87021-979-0.
- Haarr, Geirr H. (2009). The German Invasion of Norway, April 1940. Annapolis, Maryland: Naval Institute Press. ISBN 978-1-59114-310-9.
- Koop, Gerhard; Schmolke, Klaus-Peter (2003). German Destroyers of World War II. Annapolis, Maryland: Naval Institute Press. ISBN 1-59114-307-1.
- Rohwer, Jürgen (2005). Chronology of the War at Sea 1939-1945: The Naval History of World War Two (Third Revised ed.). Annapolis, Maryland: Naval Institute Press. ISBN 1-59114-119-2.
- Whitley, M. J. (1991). German Destroyers of World War Two. Annapolis, Maryland: Naval Institute Press. ISBN 1-55750-302-8.
|
#ifndef TM_KIT_BASIC_IN_MEMORY_WITH_LOCK_CHAIN_HPP_
#define TM_KIT_BASIC_IN_MEMORY_WITH_LOCK_CHAIN_HPP_
#include <tm_kit/basic/simple_shared_chain/ChainReader.hpp>
#include <tm_kit/basic/simple_shared_chain/ChainWriter.hpp>
#include <tm_kit/basic/ByteData.hpp>
#include <tm_kit/basic/SerializationHelperMacros.hpp>
namespace dev { namespace cd606 { namespace tm { namespace basic { namespace simple_shared_chain {
#define InMemoryWithLockChainItemFields \
((int64_t, revision)) \
((std::string, id)) \
((T, data)) \
((std::string, nextID))
#define InMemoryWithLockChainStorageFields \
((T, data)) \
((std::string, nextID))
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT(((typename, T)), InMemoryWithLockChainItem, InMemoryWithLockChainItemFields);
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT(((typename, T)), InMemoryWithLockChainStorage, InMemoryWithLockChainStorageFields);
}}}}}
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT_SERIALIZE_NO_FIELD_NAMES(((typename, T)), dev::cd606::tm::basic::simple_shared_chain::InMemoryWithLockChainItem, InMemoryWithLockChainItemFields);
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT_SERIALIZE_NO_FIELD_NAMES(((typename, T)), dev::cd606::tm::basic::simple_shared_chain::InMemoryWithLockChainStorage, InMemoryWithLockChainStorageFields);
namespace dev { namespace cd606 { namespace tm { namespace basic { namespace simple_shared_chain {
template <class T>
class InMemoryWithLockChain {
public:
using StorageIDType = std::string;
using DataType = T;
using MapData = InMemoryWithLockChainStorage<T>;
using TheMap = std::unordered_map<std::string, MapData>;
using ItemType = InMemoryWithLockChainItem<T>;
static constexpr bool SupportsExtraData = true;
private:
std::function<void()> updateTriggerFunc_;
TheMap theMap_;
std::unordered_map<std::string, std::string> extraData_;
std::mutex mutex_;
std::mutex chainActionMutex_;
public:
InMemoryWithLockChain() : updateTriggerFunc_(), theMap_({{"", MapData {}}}), extraData_(), mutex_(), chainActionMutex_() {
}
void setUpdateTriggerFunc(std::function<void()> f) {
if (updateTriggerFunc_) {
throw std::runtime_error("Duplicate attempt to set update trigger function for InMemoryWithLockChain");
}
updateTriggerFunc_ = f;
if (updateTriggerFunc_) {
updateTriggerFunc_();
}
}
ItemType head(void *) {
std::lock_guard<std::mutex> _(mutex_);
auto &x = theMap_[""];
return ItemType {0, "", x.data, x.nextID};
}
ItemType loadUntil(void *, StorageIDType const &id) {
std::lock_guard<std::mutex> _(mutex_);
auto &x = theMap_[id];
return ItemType {0, id, x.data, x.nextID};
}
std::optional<ItemType> fetchNext(ItemType const ¤t) {
std::lock_guard<std::mutex> _(mutex_);
auto iter = theMap_.find(current.id);
if (iter == theMap_.end()) {
return std::nullopt;
}
if (iter->second.nextID == "") {
return std::nullopt;
}
iter = theMap_.find(iter->second.nextID);
if (iter == theMap_.end()) {
return std::nullopt;
}
return ItemType {0, iter->first, iter->second.data, iter->second.nextID};
}
bool idIsAlreadyOnChain(std::string const &id) {
std::lock_guard<std::mutex> _(mutex_);
return (theMap_.find(id) != theMap_.end());
}
bool appendAfter(ItemType const ¤t, ItemType &&toBeWritten) {
std::lock_guard<std::mutex> _(mutex_);
if (theMap_.find(toBeWritten.id) != theMap_.end()) {
return false;
}
auto iter = theMap_.find(current.id);
if (iter == theMap_.end()) {
return false;
}
if (iter->second.nextID != "") {
return false;
}
iter->second.nextID = toBeWritten.id;
theMap_.insert({iter->second.nextID, MapData {std::move(toBeWritten.data), ""}}).first;
if (updateTriggerFunc_) {
updateTriggerFunc_();
}
return true;
}
bool appendAfter(ItemType const ¤t, std::vector<ItemType> &&toBeWritten) {
if (toBeWritten.empty()) {
return true;
}
if (toBeWritten.size() == 1) {
return appendAfter(current, std::move(toBeWritten[0]));
}
std::lock_guard<std::mutex> _(mutex_);
auto const &firstID = toBeWritten[0].id;
if (theMap_.find(firstID) != theMap_.end()) {
return false;
}
auto iter = theMap_.find(current.id);
if (iter == theMap_.end()) {
return false;
}
if (iter->second.nextID != "") {
return false;
}
iter->second.nextID = firstID;
for (auto &&x : toBeWritten) {
theMap_.insert({x.id, MapData {std::move(x.data), std::move(x.nextID)}});
}
if (updateTriggerFunc_) {
updateTriggerFunc_();
}
return true;
}
template <class ExtraData>
void saveExtraData(std::string const &key, ExtraData const &data) {
std::lock_guard<std::mutex> _(mutex_);
extraData_[key] = basic::bytedata_utils::RunSerializer<basic::CBOR<ExtraData>>::apply(
basic::CBOR<ExtraData> {data}
);
}
template <class ExtraData>
std::optional<ExtraData> loadExtraData(std::string const &key) {
std::lock_guard<std::mutex> _(mutex_);
auto iter = extraData_.find(key);
if (iter != extraData_.end()) {
auto d = basic::bytedata_utils::RunDeserializer<basic::CBOR<ExtraData>>::apply(
iter->second
);
if (d) {
return d->value;
} else {
return std::nullopt;
}
} else {
return std::nullopt;
}
}
template <class Env>
static StorageIDType newStorageID() {
return Env::id_to_string(Env::new_id());
}
template <class Env>
static std::string newStorageIDAsString() {
return newStorageID<Env>();
}
static ItemType formChainItem(StorageIDType const &itemID, T &&itemData) {
return ItemType {
0, itemID, std::move(itemData), ""
};
}
static std::vector<ItemType> formChainItems(std::vector<std::tuple<StorageIDType, T>> &&itemDatas) {
std::vector<ItemType> ret;
bool first = true;
for (auto &&x: itemDatas) {
auto *p = (first?nullptr:&(ret.back()));
if (p) {
p->nextID = std::get<0>(x);
}
ret.push_back(formChainItem(std::get<0>(x), std::move(std::get<1>(x))));
first = false;
}
return ret;
}
static StorageIDType extractStorageID(ItemType const &p) {
return p.id;
}
static T const *extractData(ItemType const &p) {
return &(p.data);
}
static std::string_view extractStorageIDStringView(ItemType const &p) {
return std::string_view {p.id};
}
void acquireLock() {
chainActionMutex_.lock();
}
void releaseLock() {
chainActionMutex_.unlock();
}
};
}}}}}
#endif
|
Is Frisian a Language or a Dialect?
Frisian (Frysk) is a Germanic language, spoken by an ethnic minority known as the Frisians in the northern regions of the Netherlands and Germany. It is similar to Dutch, German, Danish and most similar to English. In fact, Frisian is, along with Scottish, the closest living language to English. It especially bears a lot of resemblance to Old English.
In Germany, Frisian is confined to small pockets of the country, with relatively few speakers. The Netherlands has the most Frisian speakers, about 400,000, and almost all live in the Province of Friesland (Dutch for “Land of the Frisians”).
Language or Dialect?
The discussion of whether a language is instead a dialect is a difficult and often tricky one. There are two kinds of criteria that distinguish a language from dialect. The first is the political criterion; languages are official and written, whereas dialects are mostly spoken and unofficial. A language is a dialect with an army and a navy. Or, as my French teacher once said: “A dialect is the language of a people that lost the last war.”
Linguists, however, follow a different set of criteria: if two kinds of speech are so closely related that speakers can have a conversation and understand each other, they are considered dialects of a single language, but if mutual comprehension is difficult or impossible, they are distinct languages.
According to the latter critirion, Frisian is very much a language. Although a Dutchman or a German could be able to pick up on some words, it would be impossible to understand a conversation in Frisian. Conversely, a Frisian would have no trouble at all understanding a conversation in Dutch. This is because a Frisian would have been taught Dutch from a young age in school. In other words, he lost the last war.
When considering the first criterion, Frisian is still a language. Although Frisians “lost the last war” with the Dutch, the Frisian language has had a special, minority status within the Kingdom of the Netherlands ever since, and is stated in the Constitution of 1848. Within the borders of the Province of Friesland, anyone has the right to address both the local and the national administration in Frisian. It has an official written form, and Frisian courses are taught at some Dutch universities.
Three Dialects
Within the Frisian language, there are three varieties, or main dialects: West Frisian, Saterland Frisian and North Frisian. West Frisian is spoken in the Dutch Province of Friesland. Saterlands Frisian is spoken in Saterland, a small German city. North Frisian is spoken in the northernmost part of Germany, near the Danish border, and in small areas on islands closest to Denmark. Because these regions are geographicly isolated from each other, these Frisian dialects have steadily grown apart to such a degree that inhabitants of the different regions would not be able to understand each other today. According to the linguists’ critirion, these varieties should be considered languages on their own.
Frisian and the English Language
To understand Frisian’s influence on the English language, one must look at its history. When the Roman legions left Brittannia in the 5th century A.D., the local Celtic tribes were no longer able to stop Scots and Picts from invading the North. The Celts sought the aid of Germanic tribes on the other side of the North Sea; the Jutes, the Saxons and the Frisians. As payment for their military services, these tribes were offered land in Brittannia. Boats full of Frisian mercenaries set sail for Brittannia, where the promise of land and an escape from the floods and overpopulation of their homeland appealed to them. After fighting alongside the tribes of Brittannia, many Frisians became homesick and returned to their Fryslân, while others settled in Brittannia. Places in England with names like Friston are a reminder of that time.
The Future of the Frisian Language
Although the Frisian language is protected and has special legal status in all three of the regions where it is still spoken, the two regions in the north of Germany are so small and isolated that Frisian is likely to disappear in the future. West Frisian, spoken in the Kingdom of The Netherlands, only has around 400,000 speakers and is increasingly being influenced by Dutch words.
A language is never static: it is a living thing. Just like any living thing on Earth, it either evolves or it dies out. Whether the Frisian language spoken today will evolve into a Dutch dialect, or whether it will die out, remains to be seen. Whatever the future of the Frisian language, Frisian words like bûter (butter), tsiis (cheese), see (sea), boat (boat), stoarm (storm), rein (rain), frieze (freeze), froast (frost), and mist (mist) live on in today’s English, the lingua franca of the modern world.
About Sjouke S.
I am a native Dutch translator living in the Netherlands. I am also an expert in SEO and academic writing. I enjoy copywriting and blogging.
|
#include "Astar.h"
#include <iostream>
#include <random>
#define K_LMRKS 16
int Astar::run(node_t source, node_t target)
{
Timer _t;
Label f_solution(routing_infty,-1);
f_solution.f_score = routing_infty;
astar_f_heap queue;
map<node_t, Label> nodesLabeled;
set<node_t> is_settled;
Label lb(0,source);
lb.f_score = lb.cost + calc_lmrk_dist(
source,target
,&m_g->landmarks_holder_avoid
,make_pair(m_g->nodes_container.at(source).dist_to_lmrk_avoid.get(),m_g->nodes_container.at(source).dist_from_lmrk_avoid.get())
,make_pair(m_g->nodes_container.at(target).dist_to_lmrk_avoid.get(),m_g->nodes_container.at(target).dist_from_lmrk_avoid.get())
);
queue.push(lb);
nodesLabeled[source] = lb;
while (!queue.empty())
{
Label g_label(queue.top());
if (is_settled.find(g_label.currentNode)==is_settled.end()) {
const Vertex* v = &m_g->nodes_container.at(g_label.currentNode);
is_settled.insert(g_label.currentNode);
queue.pop();
if (g_label.currentNode == target)
{
if (f_solution.f_score > g_label.f_score) {
f_solution = g_label;
}
else {
// solved
std::cout << "\nShortest path found in \033[1;31m" << _t.diff() << "s\033[0m";
std::cout << " with cost \033[32m" << f_solution.cost << "\033[0m" << std::endl;
return 0;
}
}
for (auto it = v->out_edges.begin(); it != v->out_edges.end(); ++it)
{
Label new_label(g_label.cost+it->second.cost,it->first);
new_label.prevNode = g_label.currentNode;
new_label.f_score = new_label.cost + calc_lmrk_dist(
new_label.currentNode,target
,&m_g->landmarks_holder_avoid
,make_pair(
m_g->nodes_container.at(new_label.currentNode).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(new_label.currentNode).dist_from_lmrk_avoid.get())
,make_pair(
m_g->nodes_container.at(target).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(target).dist_from_lmrk_avoid.get())
);
add_in_queue(&new_label,nodesLabeled,queue);
}
}
else {
queue.pop();
}
}
if (f_solution.currentNode != -1) {
// solved
std::cout << "\nShortest path found in \033[1;31m" << _t.diff() << "s\033[0m";
std::cout << " with cost \033[32m" << f_solution.cost << "\033[0m" << std::endl;
return 0;
}
else {
cout << " couldn't find Shortest path for source: " << source << ", target: " << target;
cout << " in: " << _t.diff() << " s\n";
return -1;
}
}
cost_t Astar::calc_lmrk_dist(
node_t curr_node,node_t target
,const vector<node_t>* lmrk_holder
,pair<const map<node_t, cost_t>*,const map<node_t, cost_t>*> lmrk_dists_curr_node
,pair<const map<node_t, cost_t>*,const map<node_t, cost_t>*> lmrk_dists_target)
{
double distance = 0;
if (curr_node==target)
return 0;
for(auto lmrk_it=lmrk_holder->begin();lmrk_it!=lmrk_holder->end();++lmrk_it)
{
double tmp_dist = //abs(
lmrk_dists_target.first->at(*lmrk_it) -
lmrk_dists_curr_node.first->at(*lmrk_it)
// )
;
if ( distance < tmp_dist )
{
distance = tmp_dist;
}
tmp_dist = //abs(
lmrk_dists_curr_node.second->at(*lmrk_it) -
lmrk_dists_target.second->at(*lmrk_it)
// )
;
if(distance < tmp_dist)
{
distance = tmp_dist;
}
}
return distance;
}
void Astar::add_in_queue(const Label* l, map<node_t,Label>& labels, astar_f_heap& q)
{
auto it = labels.find(l->currentNode);
if (it != labels.end()) {
if (it->second.cost > l->cost) {
it->second = *l;
q.push(*l);
}
}
else {
labels[l->currentNode] = *l;
q.push(*l);
}
}
int Astar::avoid(int thres_dist)
{
Timer _t;
vector<node_t> v_gNodes;
for(auto it=m_g->nodes_container.begin();it!=m_g->nodes_container.end();++it)
{
v_gNodes.push_back(it->n);
}
std::random_device rd;
std::mt19937 generator(rd());
vector<double> probabilities(v_gNodes.size(),1);
node_t random_node;
int lmrk_inpath_counter = 0;
while(m_g->landmarks_holder_avoid.size() < K_LMRKS )
{
std::discrete_distribution<node_t> distribution(probabilities.begin(), probabilities.end());
random_node = distribution(generator);
node_t rootNode = v_gNodes.at(random_node);
map<node_t,double> node_weights{{rootNode,0}};
map<node_t,Label> sp_tree;
vector<node_t> leafs;
dijkstra(m_g,rootNode,-1,leafs,sp_tree);
for(auto& node:m_g->nodes_container)
{
if (m_g->landmarks_holder_avoid.size()>0) {
double max_lmrk_dist = calc_lmrk_dist(
rootNode,node.n,&m_g->landmarks_holder_avoid
,make_pair(
m_g->nodes_container.at(rootNode).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(rootNode).dist_to_lmrk_avoid.get())
,make_pair(
m_g->nodes_container.at(node.n).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(node.n).dist_from_lmrk_avoid.get())
);
node_weights[node.n] = sp_tree.at(node.n).cost-max_lmrk_dist;
}
else {
node_weights[node.n] = sp_tree.at(node.n).cost;
}
}
for (auto& node:m_g->landmarks_holder_avoid) {
node_weights[node] = 0;
}
pair<node_t,double> max_size_node{-1,0};
map<node_t,double> node_size;
for (auto& leaf:leafs) {
node_t curr_node = leaf;
if (max_size_node.second < node_weights.at(curr_node)) {
max_size_node = make_pair(leaf,node_weights.at(curr_node));
}
node_size[curr_node] = node_weights.at(curr_node);
while (curr_node!=rootNode) {
node_t p_node = sp_tree.at(curr_node).prevNode;
if (node_weights.at(curr_node)==0 || node_weights.at(p_node)==0) {
node_size[p_node] = 0;
}
else {
try {
node_size.at(p_node) += node_weights.at(curr_node);
}
catch (out_of_range) {
node_size[p_node] = node_weights.at(p_node) + node_weights.at(curr_node);
}
if (max_size_node.second<node_size.at(p_node)) {
max_size_node = make_pair(p_node,node_size.at(p_node));
}
}
curr_node = p_node;
}
}
if (max_size_node.first>-1) {
bool lmrk_found = false;
set<node_t> settled;
while(!lmrk_found) {
const Vertex* v = &(m_g->nodes_container.at(max_size_node.first));
settled.insert(v->n);
pair<node_t,double> next_node(-1,0);
for (auto it = v->out_edges.begin(); it != v->out_edges.end(); ++it)
{
try {
if (next_node.second<node_size.at(it->first) && settled.find(it->first)==settled.end()) {
next_node = make_pair(it->first,node_size.at(it->first));
}
}
catch (out_of_range) {}
}
if (next_node.first==-1) {
m_g->landmarks_holder_avoid.push_back(max_size_node.first);
lmrk_found = true;
}
else if (find(leafs.begin(),leafs.end(),next_node.first)!=leafs.end()) {
max_size_node = next_node;
m_g->landmarks_holder_avoid.push_back(max_size_node.first);
lmrk_found = true;
}
else {
max_size_node = next_node;
}
}
node_t lmrk = max_size_node.first;
lmrk_dijkstra_dists(lmrk,-1);
lmrk_dijkstra_dists(lmrk,-1,true);
auto v_it = find(v_gNodes.begin(),v_gNodes.end(),lmrk);
probabilities.at(distance(v_gNodes.begin(),v_it)) = 0;
double lmrk_lon = m_g->nodes_container.at(max_size_node.first).lon;
double lmrk_lat = m_g->nodes_container.at(max_size_node.first).lat;
for (auto it=m_g->nodes_container.begin(); it!=m_g->nodes_container.end(); ++it) {
double geodist_to_lmrk = geodist(it->lat,it->lon,lmrk_lat,lmrk_lon,'K');
if ( geodist_to_lmrk>thres_dist) {
auto v_it = find(v_gNodes.begin(),v_gNodes.end(),it->n);
probabilities.at(distance(v_gNodes.begin(),v_it)) = (int)(geodist_to_lmrk/thres_dist);
}
}
}
else {
++lmrk_inpath_counter;
}
}
std::cout << "landmarks found in the path: \033[31m" << lmrk_inpath_counter << "\033[0m times" << std::endl;
std::cout << K_LMRKS << " landmarks selected in \033[31m" << _t.diff() << "\033[0ms: " << std::endl;
return 0;
}
int Astar::lmrk_dijkstra_dists(node_t s, node_t t, bool reverse)
{
f_heap queue;
map<node_t, Label> nodesLabeled;
for (auto it = m_g->nodes_container.begin(); it != m_g->nodes_container.end(); ++it)
{
Label l(routing_infty,it->n);
l.handle = setup_handle(queue.push(l));
nodesLabeled[it->n]=l;
}
nodesLabeled.at(s).cost=0;
nodesLabeled.at(s).prevNode = -1;
*(nodesLabeled.at(s).handle) = nodesLabeled.at(s);
queue.decrease(nodesLabeled.at(s).handle);
while (!queue.empty())
{
Label global_label(queue.top());
const Vertex* v = &(m_g->nodes_container.at(global_label.currentNode));
if ((global_label.cost == routing_infty) || (global_label.currentNode == t))
{
// solved
return 0;
}
map<node_t,Edge>* edges;
if(reverse) {
// (*m_g->nodes_container.at(global_label.currentNode).dist_to_lmrk)[s] = global_label.cost;
m_g->nodes_container.at(global_label.currentNode).add_lmrk_cost(s,global_label.cost);
edges = &v->in_edges;
}
else {
// (*m_g->nodes_container.at(global_label.currentNode).dist_from_lmrk)[s] = global_label.cost;
m_g->nodes_container.at(global_label.currentNode).add_lmrk_cost(s,global_label.cost,true);
edges = &v->out_edges;
}
queue.pop();
for (auto it = edges->begin(); it != edges->end(); ++it)
{
Label* _label = &nodesLabeled.at(it->first);
if (global_label.cost < _label->cost - it->second.cost)
{
_label->cost = global_label.cost + it->second.cost;
_label->prevNode = global_label.currentNode;
*(_label->handle) = *_label;
queue.decrease(_label->handle);
}
}
}
return 1;
}
f_heap::handle_type Astar::setup_handle(f_heap::handle_type &&handle)
{
(*handle).handle = handle;
return handle;
}
int Astar::dijkstra(
const Graph* g, node_t source, node_t target,
vector<node_t>& leafs,map<node_t, Label>& labels
)
{
f_heap queue;
for (auto& node:g->nodes_container) {
Label l(routing_infty,node.n);
labels[node.n] = l;
labels.at(node.n).handle = setup_handle(queue.push(labels.at(node.n)));
}
labels.at(source).cost=0;
labels.at(source).prevNode = -1;
*(labels.at(source).handle) = labels.at(source);
queue.decrease(labels.at(source).handle);
while (!queue.empty())
{
Label global_label(queue.top());
const Vertex* v = &(g->nodes_container.at(global_label.currentNode));
queue.pop();
if (!(global_label.currentNode==target)) {
int edges_opened=0;
for (auto it = v->out_edges.begin(); it != v->out_edges.end(); ++it)
{
if (labels.at(it->first).cost - it->second.cost > global_label.cost ) {
labels.at(it->first).cost = global_label.cost + it->second.cost;
labels.at(it->first).prevNode = global_label.currentNode;
*(labels.at(it->first).handle) = labels.at(it->first);
queue.decrease(labels.at(it->first).handle);
++edges_opened;
}
}
if (edges_opened==0
&& global_label.cost < routing_infty
&& find(leafs.begin(),leafs.end(),global_label.currentNode)==leafs.end())
{
leafs.push_back(global_label.currentNode);
}
}
else {
return 0;
}
}
return 1;
}
#define pi 3.14159265358979323846
double Astar::geodist(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta, dist;
theta = lon1 - lon2;
dist = sin(deg2rad(lat1)) * sin(deg2rad(lat2)) + cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * cos(deg2rad(theta));
dist = acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
switch(unit) {
case 'M':
break;
case 'K':
dist = dist * 1.609344;
break;
case 'N':
dist = dist * 0.8684;
break;
}
return (dist);
}
double Astar::deg2rad(double deg) {
return (deg * pi / 180);
}
double Astar::rad2deg(double rad) {
return (rad * 180 / pi);
}
|
A jack-o'-lantern, one of the symbols of Halloween
|Also called||All Hallows' Eve
All Saints' Eve
|Observed by||Western Christians & many non-Christians around the world|
|Celebrations||Trick-or-treating/guising, costume parties, making jack-o'-lanterns, lighting bonfires, divination, apple bobbing, visiting haunted attractions, fireworks displays|
|Observances||Church services, prayer, fasting, and vigils|
|Related to||Samhain, Hop-tu-Naa, Calan Gaeaf, Kalan Gwav, Day of the Dead, All Saints' Day (cf. vigils)|
Halloween or Hallowe'en (a contraction of "All Hallows' Evening"), also known as All Hallows' Eve, is a yearly celebration observed in a number of countries on October 31, the eve of the Western Christian feast of All Hallows (or All Saints) and the day initiating the triduum of Hallowmas.
According to many scholars, All Hallows' Eve is a Christianised feast originally influenced by western European harvest festivals, and festivals of the dead with possible pagan roots, particularly the Celtic Samhain. Other scholars maintain that it originated independently of Samhain and has solely Christian roots.
Typical festive Halloween activities include trick-or-treating (also known as "guising"), attending costume parties, carving pumpkins into jack-o'-lanterns, lighting bonfires, apple bobbing, visiting haunted attractions, playing pranks, telling scary stories, and watching horror films.
The word Halloween was first used in the 16th century and represents a Scottish variant of the fuller All Hallows' Eve ('evening'), that is, the night before All Hallows' Day. Although the phrase All Hallows' is found in Old English (ealra hālgena mæssedæg, mass-day of all saints), All Hallows' Eve is itself not seen until 1556.
Celtic influences
Though the origin of the word Halloween is Christian, the holiday is commonly thought to have pagan roots. Historian Nicholas Rogers, exploring the origins of Halloween, notes that while "some folklorists have detected its origins in the Roman feast of Pomona, the goddess of fruits and seeds, or in the festival of the dead called Parentalia, it is more typically linked to the Celtic festival of Samhain", which comes from the Old Irish for "summer's end". Samhain (pronounced SAH-win or SOW-in) was the first and most important of the four quarter days in the medieval Gaelic (Irish, Scottish and Manx) calendar. It was held on or about October 31 – November 1 and kindred festivals were held at the same time of year in other Celtic lands; for example the Brythonic Calan Gaeaf (in Wales), Kalan Gwav (in Cornwall) and Kalan Goañv (in Brittany). Samhain is mentioned in some of the earliest Irish literature and many important events in Irish mythology happen or begin on Samhain. It marked the end of the harvest season and the beginning of winter or the 'darker half' of the year. This was a time for stock-taking and preparing for the cold winter ahead; cattle were brought back down from the summer pastures and livestock were slaughtered. In much of the Gaelic world, bonfires were lit and there were rituals involving them. Some of these rituals hint that they may once have involved human sacrifice. Divination games or rituals were also done at Samhain.
Samhain (like Beltane) was seen as a time when the 'door' to the Otherworld opened enough for the souls of the dead, and other beings such as fairies, to come into our world. The souls of the dead were said to revisit their homes on Samhain. Feasts were had, at which the souls of dead kin were beckoned to attend and a place set at the table for them. Lewis Spence described it as a "feast of the dead" and "festival of the fairies". However, harmful spirits and fairies were also thought to be active at Samhain. People took steps to allay or ward-off these harmful spirits/fairies, which is thought to have influenced today's Halloween customs. Before the 20th century, wearing costumes at Samhain was done in parts of Ireland, Mann, the Scottish Highlands and islands, and Wales. Wearing costumes may have originated as a means of disguising oneself from these harmful spirits/fairies, although some suggest that the custom comes from a Christian or Christianized belief (see below). In Ireland, people went about before nightfall collecting for Samhain feasts and sometimes wore costumes while doing so. In the 19th century on Ireland's southern coast, a man dressed as a white mare would lead youths door-to-door collecting food; by giving them food, the household could expect good fortune from the 'Muck Olla'. In Moray during the 18th century, boys called at each house in their village asking for fuel for the Samhain bonfire. The modern custom of trick-or-treating may have come from these practices. Alternatively, it may come from the Christian custom of souling (see below).
Making jack-o'-lanterns at Halloween may also have sprung from Samhain and Celtic beliefs. Turnip lanterns, sometimes with faces carved into them, were made on Samhain in the 19th century in parts of Ireland and the Scottish Highlands. As well as being used to light one's way while outside on Samhain night, they may also have been used to represent the spirits/fairies and/or to protect oneself and one's home from them. Another legend is that a trickster named Jack decided one day to trick the Devil. He trapped the Devil in a pumpkin and paraded him around town. Eventually, Jack let the Devil out and the Devil put a curse on Jack and forever made him a spirit in hell. On Halloween, Jack is released to terrorize the country all night. To protect themselves, the Irish would place a pumpkin with a face outside to scare Jack into believing it was the Devil. However, a Christian origin has also been proposed.
Christian influences
Halloween is also thought to have been influenced by the Christian holy days of All Saints' Day (also known as All Hallows, Hallowmas or Hallowtide) on November 1 and All Souls' Day on November 2. They are a time for honoring the saints and praying for the recently departed who had yet to reach Heaven. All Saints was introduced in the year 609, but was originally celebrated on May 13. In 835, it was switched to November 1 (the same date as Samhain) at the behest of Pope Gregory IV. Some have suggested this was due to Celtic influence, while others suggest it was a Germanic idea.
By the end of the 12th century they had become holy days of obligation across Europe and involved such traditions as ringing bells for the souls in purgatory. "Souling", the custom of baking and sharing soul cakes for "all crysten christened souls", has been suggested as the origin of trick-or-treating. Groups of poor people, often children, would go door-to-door on All Saints/All Souls collecting soul cakes, originally as a means of praying for souls in purgatory. Similar practices for the souls of the dead were found as far south as Italy. Shakespeare mentions the practice in his comedy The Two Gentlemen of Verona (1593), when Speed accuses his master of "puling [whimpering or whining] like a beggar at Hallowmas." The custom of wearing costumes has been linked to All Saints/All Souls by Prince Sorie Conteh, who wrote: "It was traditionally believed that the souls of the departed wandered the earth until All Saints' Day, and All Hallows' Eve provided one last chance for the dead to gain vengeance on their enemies before moving to the next world. In order to avoid being recognised by any soul that might be seeking such vengeance, people would don masks or costumes to disguise their identities". In Halloween: From Pagan Ritual to Party Night, Nicholas Rogers explained Halloween jack-o'-lanterns as originally being representations of souls in purgatory. In Brittany children would set candles in skulls in graveyards.
In Britain, these customs came under attack during the Reformation as Protestants berated purgatory as a "popish" doctrine incompatible with the notion of predestination. The rising popularity of Guy Fawkes Night (5 November) from 1605 onward, saw many Halloween traditions appropriated by that holiday instead, and Halloween's popularity waned in Britain, with the noteworthy exception of Scotland. There and in Ireland, the rebellious Guy Fawkes was not viewed with the same criminality as in England, and they had been celebrating Samhain and Halloween since at least the early Middle Ages, and the Scottish kirk took a more pragmatic approach to Halloween, seeing it as important to the life cycle and rites of passage of communities and thus ensuring its survival in the country.
Spread to North America
North American almanacs of the late 18th and early 19th century give no indication that Halloween was celebrated there. The Puritans of New England, for example, maintained strong opposition to Halloween and it was not until the mass Irish and Scottish immigration during the 19th century that it was brought to North America in earnest. Confined to the immigrant communities during the mid-19th century, it was gradually assimilated into mainstream society and by the first decade of the 20th century it was being celebrated coast to coast by people of all social, racial and religious backgrounds.
Development of artifacts and symbols associated with Halloween formed over time. The turnip has traditionally been used in Ireland and Scotland at Halloween, but immigrants to North America used the native pumpkin, which is both much softer and much larger – making it easier to carve than a turnip. Subsequently, the mass marketing of various size pumpkins in autumn, in both the corporate and local markets, has made pumpkins universally available for this purpose. The American tradition of carving pumpkins is recorded in 1837 and was originally associated with harvest time in general, not becoming specifically associated with Halloween until the mid-to-late 19th century.
The modern imagery of Halloween comes from many sources, including national customs, works of Gothic and horror literature (such as the novels Frankenstein and Dracula) and classic horror films (such as Frankenstein and The Mummy). One of the earliest works on the subject of Halloween is from Scottish poet John Mayne, who, in 1780, made note of pranks at Halloween; "What fearfu' pranks ensue!", as well as the supernatural associated with the night, "Bogies" (ghosts), influencing Robert Burns' Halloween 1785. Elements of the autumn season, such as pumpkins, corn husks and scarecrows, are also prevalent. Homes are often decorated with these types of symbols around Halloween.
Trick-or-treating and guising
Trick-or-treating is a customary celebration for children on Halloween. Children go in costume from house to house, asking for treats such as candy or sometimes money, with the question, "Trick or treat?" The word "trick" refers to "threat" to perform mischief on the homeowners or their property if no treat is given.
In Scotland and Ireland, guising – children disguised in costume going from door to door for food or coins – is a traditional Halloween custom, and is recorded in Scotland at Halloween in 1895 where masqueraders in disguise carrying lanterns made out of scooped out turnips, visit homes to be rewarded with cakes, fruit and money. The practice of Guising at Halloween in North America is first recorded in 1911, where a newspaper in Kingston, Ontario reported children going "guising" around the neighborhood.
American historian and author Ruth Edna Kelley of Massachusetts wrote the first book length history of Halloween in the US; The Book of Hallowe'en (1919), and references souling in the chapter "Hallowe'en in America":
The taste in Hallowe'en festivities now is to study old traditions, and hold a Scotch party, using Burn's poem Hallowe'en as a guide; or to go a-souling as the English used. In short, no custom that was once honored at Hallowe'en is out of fashion now.
In her book, Kelley touches on customs that arrived from across the Atlantic; "Americans have fostered them, and are making this an occasion something like what it must have been in its best days overseas. All Halloween customs in the United States are borrowed directly or adapted from those of other countries". While the first reference to "guising" in North America occurs in 1911, another reference to ritual begging on Halloween appears, place unknown, in 1915, with a third reference in Chicago in 1920.
The earliest known use in print of the term "trick or treat" appears in 1927, from Blackie, Alberta, Canada:
Hallowe'en provided an opportunity for real strenuous fun. No real damage was done except to the temper of some who had to hunt for wagon wheels, gates, wagons, barrels, etc., much of which decorated the front street. The youthful tormentors were at back door and front demanding edible plunder by the word “trick or treat” to which the inmates gladly responded and sent the robbers away rejoicing.
The thousands of Halloween postcards produced between the turn of the 20th century and the 1920s commonly show children but not trick-or-treating. The editor of a collection of over 3,000 vintage Halloween postcards writes, "There are cards which mention the custom [of trick-or-treating] or show children in costumes at the doors, but as far as we can tell they were printed later than the 1920s and more than likely even the 1930s. Tricksters of various sorts are shown on the early postcards, but not the means of appeasing them". Trick-or-treating does not seem to have become a widespread practice until the 1930s, with the first U.S. appearances of the term in 1934, and the first use in a national publication occurring in 1939.
Halloween costumes are traditionally modeled after supernatural figures such as monsters, ghosts, skeletons, witches, and devils. Over time, in the United States the costume selection extended to include popular characters from fiction, celebrities, and generic archetypes such as ninjas and princesses.
Dressing up in costumes and going "guising" was prevalent in Ireland and Scotland at Halloween by the late 19th century. Costuming became popular for Halloween parties in the US in the early 20th century, as often for adults as for children. The first mass-produced Halloween costumes appeared in stores in the 1930s when trick-or-treating was becoming popular in the United States.
Halloween costume parties generally fall on or around October 31, often on the Friday or Saturday before Halloween.
"Trick-or-Treat for UNICEF" is a fundraising program to support UNICEF, a United Nations Programme that provides humanitarian aid to children in developing countries. Started as a local event in a Northeast Philadelphia neighborhood in 1950 and expanded nationally in 1952, the program involves the distribution of small boxes by schools (or in modern times, corporate sponsors like Hallmark, at their licensed stores) to trick-or-treaters, in which they can solicit small-change donations from the houses they visit. It is estimated that children have collected more than $118 million for UNICEF since its inception. In Canada, in 2006, UNICEF decided to discontinue their Halloween collection boxes, citing safety and administrative concerns; after consultation with schools, they instead redesigned the program.
Games and other activities
There are several games traditionally associated with Halloween parties. One common game is dunking or apple bobbing, which may be called "dooking" in Scotland in which apples float in a tub or a large basin of water and the participants must use their teeth to remove an apple from the basin. The practice is thought by some to have derived from the Roman practices in celebration of Pomona. A variant of dunking involves kneeling on a chair, holding a fork between the teeth and trying to drop the fork into an apple. Another common game involves hanging up treacle or syrup-coated scones by strings; these must be eaten without using hands while they remain attached to the string, an activity that inevitably leads to a very sticky face.
Some games traditionally played at Halloween are forms of divination. A traditional Scottish form of divining one's future spouse is to carve an apple in one long strip, then toss the peel over one's shoulder. The peel is believed to land in the shape of the first letter of the future spouse's name. Unmarried women were told that if they sat in a darkened room and gazed into a mirror on Halloween night, the face of their future husband would appear in the mirror. However, if they were destined to die before marriage, a skull would appear. The custom was widespread enough to be commemorated on greeting cards from the late 19th century and early 20th century.
Another game/superstition that was enjoyed in the early 1900s involved walnut shells. People would write fortunes in milk on white paper. After drying, the paper was folded and placed in walnut shells. When the shell was warmed, milk would turn brown therefore the writing would appear on what looked like blank paper. Folks would also play fortune teller. In order to play this game, symbols were cut out of paper and placed on a platter. Someone would enter a dark room and was ordered to put her hand on a piece of ice then lay it on a platter. Her "fortune" would stick to the hand. Paper symbols included: dollar sign-wealth, button-bachelorhood, thimble-spinsterhood, clothespin- poverty, rice-wedding, umbrella- journey, caldron-trouble, 4-leaf clover- good luck, penny-fortune, ring-early marriage, and key-fame.
The telling of ghost stories and viewing of horror films are common fixtures of Halloween parties. Episodes of television series and Halloween-themed specials (with the specials usually aimed at children) are commonly aired on or before Halloween, while new horror films are often released theatrically before Halloween to take advantage of the atmosphere.
Haunted attractions
Haunted attractions are entertainment venues designed to thrill and scare patrons. Most attractions are seasonal Halloween businesses. Origins of these paid scare venues are difficult to pinpoint, but it is generally accepted that they were first commonly used by the Junior Chamber International (Jaycees) for fundraising. They include haunted houses, corn mazes, and hayrides, and the level of sophistication of the effects has risen as the industry has grown. Haunted attractions in the United States bring in an estimate $300–500 million each year, and draw some 400,000 customers, although press sources writing in 2005 speculated that the industry had reached its peak at that time. This maturing and growth within the industry has led to technically more advanced special effects and costuming, comparable with that of Hollywood films.
Because Halloween comes in the wake of the yearly apple harvest, candy apples (known as toffee apples outside North America), caramel or taffy apples are common Halloween treats made by rolling whole apples in a sticky sugar syrup, sometimes followed by rolling them in nuts.
At one time, candy apples were commonly given to children, but the practice rapidly waned in the wake of widespread rumors that some individuals were embedding items like pins and razor blades in the apples in the United States. While there is evidence of such incidents, they are quite rare and have never resulted in serious injury. Nonetheless, many parents assumed that such heinous practices were rampant because of the mass media. At the peak of the hysteria, some hospitals offered free X-rays of children's Halloween hauls in order to find evidence of tampering. Virtually all of the few known candy poisoning incidents involved parents who poisoned their own children's candy.
One custom that persists in modern-day Ireland is the baking (or more often nowadays, the purchase) of a barmbrack (Irish: báirín breac), which is a light fruitcake, into which a plain ring, a coin and other charms are placed before baking. It is said that those who get a ring will find their true love in the ensuing year. This is similar to the tradition of king cake at the festival of Epiphany.
List of foods associated with Halloween:
- Barmbrack (Ireland)
- Bonfire toffee (Great Britain)
- Candy apples/toffee apples (Great Britain & Ireland)
- Candy corn, candy pumpkins (North America)
- Caramel apples
- Caramel corn
- Colcannon (Ireland)
- Novelty candy shaped like skulls, pumpkins, bats, worms, etc.
- Pumpkin, pumpkin pie, pumpkin bread
- Roasted pumpkin seeds
- Roasted sweet corn
- Soul cakes
- Scary Faced Pizza
Religious observances
On Hallowe'en (All Hallows' Eve), in Poland, believers are taught to pray out loud as they walk through the forests in order that the souls of the dead might find comfort; in Spain, Christian priests toll their church bells in order to allow their congregants to remember the dead on All Hallows' Eve. The Christian Church traditionally observed Hallowe'en through a vigil "when worshippers would prepare themselves with prayers and fasting prior to the feast day itself." This church service is known as the Vigil of All Hallows or the Vigil of All Saints; an initiative known as Night of Light seeks to further spread the Vigil of All Hallows throughout Christendom. After the service, "suitable festivities and entertainments" often follow, as well as a visit to the graveyard or cemetery, where flowers and candles are often placed in preparation for All Hallows' Day.
Christian attitudes towards Halloween are diverse. In the Anglican Church, some dioceses have chosen to emphasize the Christian traditions associated with All Hallow's Eve. Some of these practises include praying, fasting and attending worship services.
Father, All-Powerful and Ever-Living God, today we rejoice in the holy men and women of every time and place. May their prayers bring us your forgiveness and love. We ask this through Christ our Lord. Amen. —All Hallow's Eve Prayer from the Liturgy of the Hours
Other Protestant Christians also celebrate All Hallows' Eve as Reformation Day, a day to remember the Protestant Reformation, alongside All Hallow's Eve or independently from it. Often, "Harvest Festivals" or "Reformation Festivals" are held as well, in which children dress up as Bible characters or Reformers.
Father Gabriele Amorth, an exorcist in Rome, has said, "if English and American children like to dress up as witches and devils on one night of the year that is not a problem. If it is just a game, there is no harm in that." In more recent years, the Roman Catholic Archdiocese of Boston has organized a "Saint Fest" on Halloween. Similarly, many contemporary Protestant churches view Halloween as a fun event for children, holding events in their churches where children and their parents can dress up, play games, and get candy for free. Many Christians ascribe no negative significance to Halloween, treating it as a fun event devoted to "imaginary spooks" and handing out candy. To these Christians, Halloween holds no threat to the spiritual lives of children: being taught about death and mortality, and the ways of the Celtic ancestors actually being a valuable life lesson and a part of many of their parishioners' heritage. In the Roman Catholic Church, Halloween's Christian connection is sometimes cited, and Halloween celebrations are common in Catholic parochial schools throughout North America and in Ireland.
Some Christians feel concerned about the modern celebration of Halloween, and reject it because they feel it trivializes – or celebrates – paganism, the occult, or other practices and cultural phenomena deemed incompatible with their beliefs. A response among some fundamentalist and conservative evangelical churches in recent years has been the use of "Hell houses", themed pamphlets, or comic-style tracts such as those created by Jack T. Chick in order to make use of Halloween's popularity as an opportunity for evangelism. Some consider Halloween to be completely incompatible with the Christian faith, believing it to have originated as a pagan "Festival of the Dead".
According to Alfred J. Kolatch in the Second Jewish Book of Why Halloween is not technically permitted by Jewish Halakha because it violate Leviticus 18:3 forbidding Jews from partaking in gentile customs. Nevertheless many American Jews celebrate it as a secular holiday, disconnected from its pagan and Christian origins. Reform Rabbi Jeffrey Goldwasser, of the Central Conference of American Rabbis has said that “There is no religious reason why contemporary Jews should not celebrate Halloween as it is commonly observed" while Orthodox Rabbi Michael Broyde has argued against Jews sending their children trick or treating or otherwise observing the holiday.
Around the world
The traditions and importance of Halloween vary greatly among countries that observe it. In Scotland and Ireland, traditional Halloween customs include children dressing up in costume going "guising", holding parties, while other practices in Ireland include lighting bonfires, and having firework displays. Mass transatlantic immigration in the 19th century popularized Halloween in North America, and celebration in the United States and Canada has had a significant impact on how the event is observed in other nations. This larger North American influence, particularly in iconic and commercial elements, has extended to places such as South America, Australia, New Zealand, (most) continental Europe, Japan, and other parts of East Asia.
See also
- "BBC – Religions – Christianity: All Hallows' Eve". British Broadcasting Corporation (BBC). 2010. Retrieved 1 November 2011. "All Hallows' Eve falls on 31st October each year, and is the day before All Hallows' Day, also known as All Saints' Day in the Christian calendar. The Church traditionally held a vigil on All Hallows' Eve when worshippers would prepare themselves with prayers and fasting prior to the feast day itself. The name derives from the Old English 'hallowed' meaning holy or sanctified and is now usually contracted to the more familiar word Hallowe'en."
- The Book of Occasional Services 2003. Church Publishing, Inc. 2004. Retrieved 31 October 2011. "Service for All Hallows' Eve: This service may be used on the evening of October 31, known as All Hallows' Eve. Suitable festivities and entertainments may take place before or after this service, and a visit may be made to a cemetery or burial place."
- Anne E. Kitch (2004). The Anglican Family Prayer Book. Church Publishing, Inc. Retrieved 31 October 2011. "All Hallow's Eve, which later became known as Halloween, is celebrated on the night before All Saints' Day, November 1. Use this simple prayer service in conjunction with Halloween festivities to mark the Christian roots of this festival."
- The Paulist Liturgy Planning Guide. Paulist Press. 2006. Retrieved 31 October 2011. "Rather than compete, liturgy planners would do well to consider ways of including children in the celebration of these vigil Masses. For example, children might be encouraged to wear Halloween costumes representing their patron saint or their favorite saint, clearly adding a new level of meaning to the Halloween celebrations and the celebration of All Saints' Day."
- Thomas Thomson, Charles Annandale (1896). A History of the Scottish People from the Earliest Times: From the Union of the kingdoms, 1706, to the present time. Blackie. Retrieved 31 October 2011. "Of the stated rustic festivals peculiar to Scotland the most important was Hallowe'en, a contraction for All-hallow Evening, or the evening of All-Saints Day, the annual return of which was a season for joy and festivity."
- Merriam-Webster's Encyclopædia of World Religions. Merriam-Webster. 1999. Retrieved 31 October 2011. "Halloween, also called All Hallows' Eve, holy or hallowed evening observed on October 31, the eve of All Saints' Day. The pre-Christian observances influenced the Christian festival of All Hallows' Eve, celebrated on the same date."
- "BBC – Religions – Christianity: All Hallows' Eve". British Broadcasting Corporation (BBC). 2010. Retrieved 1 November 2011. "It is widely believed that many Hallowe'en traditions have evolved from an ancient Celtic festival called Samhain which was Christianised by the early Church."
- Nicholas Rogers (2002). Halloween: From Pagan Ritual to Party Night. Oxford University Press. Retrieved 31 October 2011. "Halloween and the Day of the Dead share a common origin in the Christian commemoration of the dead on All Saints' and All Souls' Day. But both are thought to embody strong pre-Christian beliefs. In the case of Halloween, the Celtic celebration of Samhain is critical to its pagan legacy, a claim that has been foregrounded in recent years by both new-age enthusiasts and the evangelical Right."
- Austrian information. 1965. Retrieved 31 October 2011. "The feasts of Hallowe'en, or All Hallows Eve and the devotions to the dead on All Saints' and All Souls' Day are both mixtures of old Celtic, Druid and other heathen customs intertwined with Christian practice."
- "BBC – Religions – Christianity: All Hallows' Eve". British Broadcasting Corporation (BBC). 2010. Retrieved 1 November 2011. "The Oxford Dictionary of World Religions also claims that Hallowe'en "absorbed and adopted the Celtic new year festival, the eve and day of Samhain". However, there are supporters of the view that Hallowe'en, as the eve of All Saints' Day, originated entirely independently of Samhain and some question the existence of a specific pan-Celtic religious festival which took place on 31st October/1st November."
- The Oxford English Dictionary (2nd ed.). Oxford: Oxford Univ. Press. 1989. ISBN 0-19-861186-2.
- Rogers, Nicholas (2002). "Samhain and the Celtic Origins of Halloween". Halloween: From Pagan Ritual to Party Night, pp. 11–21. New York: Oxford Univ. Press. ISBN 0-19-516896-8.
- Hutton, Ronald. The Stations of the Sun: A History of the Ritual Year in Britain (Oxford: Oxford University Press, 1996)
- A Pocket Guide To Superstitions Of The British Isles (Publisher: Penguin Books Ltd; Reprint edition: 4 November 2004) ISBN 0-14-051549-6
- All Hallows' Eve BBC. Retrieved 31 October 2011.
- Monaghan, Patricia. The Encyclopedia of Celtic Mythology and Folklore. Infobase Publishing, 2004. p.407
- Frazer, Sir James George. The Golden Bough: A Study in Magic and Religion. Forgotten Books, 2008. pp.663–664
- Monaghan, p.41
- O'Halpin, Andy. Ireland: An Oxford Archaeological Guide. Oxford University Press, 2006. p.236
- "Halloween". Britannica Concise Encyclopedia. Chicago: Encyclopaedia Britannica, 2009. Credo Reference. Web. 21 September 2012.
- McNeill, F. Marian. The Silver Bough, Vol. 3. William MacLellan. pp.11–46
- Spence, Lewis (1945). The Magic Arts in Celtic Britain. p.88. ISBN 0-09-474300-2
- Hutton, pp.380–382
- MacLeod, Sharon. Celtic Myth and Religion. McFarland, 2011. pp.61, 175
- Hutton, pp.365–368
- Hutton, p.382
- Hill, Christopher. Holidays and Holy Nights. Quest Books, 2003. p.56
- Rogers, p.57
- Rogers, Nicholas (2002). Halloween: From Pagan Ritual to Party Night, pp. 22, 27. New York: Oxford Univ. Press. ISBN 0-19-516896-8.
- Hutton, p.364
- Rogers, Nicholas (2001). Halloween: From Pagan Ritual to Party Night. Oxford University Press. pp. 28–30. ISBN 0-19-514691-3.
- "Halloween". Britannica. Encyclopædia Britannica. Retrieved 25 October 2012.
- Hutton, pp.374–375
- "Ask Anne", Washington Post, 21 November 1948, p. S11.
- The Two Gentlemen of Verona Act 2, Scene 1.
- Prince Sorie Conteh (2009). Traditionalists, Muslims, and Christians in Africa: Interreligious Encounters and Dialogue. Cambria Press. Retrieved 31 October 2011.
- "Kalan -Goañv ha Marv". Tartanplace.com. 12 July 2001. Retrieved 1 November 2012.
- Rogers, Nicholas (2002). Halloween: From Pagan Ritual to Party Night, pp. 37–38. New York: Oxford Univ. Press. ISBN 0-19-516896-8.
- Rogers, Nicholas (2002). Halloween: From Pagan Ritual to Party Night, pp. 49–50. New York: Oxford Univ. Press. ISBN 0-19-516896-8.
- Rogers, Nicholas (2002). Halloween: From Pagan Ritual to Party Night, p. 74. New York: Oxford Univ. Press. ISBN 0-19-516896-8.
- The Oxford companion to American food and drink p.269. Oxford University Press, 2007. Retrieved 17 February 2011
- Frank Leslie's popular monthly, Volume 40, November 1895, p. 540-543. Books.google.com. 5 February 2009. Retrieved 23 October 2011.
- Nathaniel Hawthorne, "The Great Carbuncle," in "Twice-Told Tales", 1837: Hide it [the great carbuncle] under thy cloak, say'st thou? Why, it will gleam through the holes, and make thee look like a jack-o'-lantern!
- As late as 1900, an article on Thanksgiving entertaining recommended a lit jack-o'-lantern as part of the festivities. "The Day We Celebrate: Thanksgiving Treated Gastronomically and Socially," The New York Times, 24 November 1895, p. 27. "Odd Ornaments for Table," The New York Times, 21 October 1900, p. 12.
- Rogers, Nicholas (2002). "Halloween Goes to Hollywood". Halloween: From Pagan Ritual to Party Night, pp. 103–124. New York: Oxford University Press. ISBN 0-19-516896-8.
- Thomas Crawford Burns: a study of the poems and songs Stanford University Press, 1960
- Simpson, Jacqueline All Saints' Day in Encyclopedia of Death and Dying, Howarth, G. and Leeman, O. (2001)London Routledge ISBN 0-415-18825-3, p.14 Halloween is closely associated in folklore with death and the supernatural.
- Rogers, Nicholas. (2002) "Coming Over:Halloween in North America". Halloween: From Pagan Ritual to Party Night. p.76. Oxford University Press, 2002, ISBN 0-19-514691-3
- Ruth Edna Kelley, The Book of Hallowe'en, Boston: Lothrop, Lee and Shepard Co., 1919, chapter 15, p.127. "Hallowe'en in America."
- Kelley, Ruth Edna. "Hallowe'en in America".
- Theo. E. Wright, "A Halloween Story," St. Nicholas, October 1915, p. 1144. Mae McGuire Telford, "What Shall We Do Halloween?" Ladies Home Journal, October 1920, p. 135.
- "'Trick or Treat' Is Demand," Herald (Lethbridge, Alberta), November 4, 1927, p. 5, dateline Blackie, Alberta, Nov. 3.
- For examples, see the websites Postcard & Greeting Card Museum: Halloween Gallery, Antique Hallowe'en Postcards, Vintage Halloween Postcards, and Morticia's Morgue Antique Halloween Postcards[dead link].
- E-mail from Louise and Gary Carpentier, 29 May 2007, editors of Halloween Postcards Catalog (CD-ROM), G & L Postcards.
- "Halloween Pranks Keep Police on Hop," Oregon Journal (Portland, Oregon), 1 November 1934:
Other young goblins and ghosts, employing modern shakedown methods, successfully worked the "trick or treat" system in all parts of the city.
Pretty Boy John Doe rang the door bells and his gang waited his signal. It was his plan to proceed cautiously at first and give a citizen every opportunity to comply with his demands before pulling any rough stuff. "Madam, we are here for the usual purpose, 'trick or treat.'" This is the old demand of the little people who go out to have some innocent fun. Many women have some apples, cookies or doughnuts for them, but they call rather early and the "treat" is given out gladly.
- Doris Hudson Moss, "A Victim of the Window-Soaping Brigade?" The American Home, November 1939, p. 48. Moss was a California-based writer.
- Beauchemin, Genevieve; CTV.ca News Staff (31 May 2006). "UNICEF to end Halloween 'orange box' program". CTV. Archived from the original on 16 October 2007. Retrieved 29 October 2006.
- "History of the Trick-or-Treat for UNICEF Campaign". UNICEF Canada. 2008. Archived from the original on 4 June 2009. Retrieved 25 October 2009.
- Apple dookers make record attempt, BBC News, 2 October 2008
- McNeill, F. Marian (1961, 1990) The Silver Bough, Vol. 3. William MacLellan, Glasgow ISBN 0-948474-04-1 pp.11–46
- "Vintage Halloween Cards". Vintage Holiday Crafts. Retrieved 28 October 2009.
- Green Bay Press Gazette, 27 October 1916
- Associated Press (30 October 2005). "Haunted house business getting frightfully hard". MSNBC.com. MSNBC. Retrieved 18 November 2008.
- Greg Ryan (17 September 2008). "A Model of Mayhem". Hudson Valley Magazine. Retrieved 6 October 2008.
- Wilson, Craig (12 October 2006). "Haunted houses get really scary". USAToday.com.
- Rogers, Nicholas (2002). "Razor in the Apple: Struggle for Safe and Sane Halloween, c. 1920–1990," Halloween: From Pagan Ritual to Party Night, pp. 78–102. New York: Oxford University Press. ISBN 0-19-516896-8.
- "Urban Legends Reference Pages: Pins and Needles in Halloween Candy". Snopes.com. Retrieved 31 October 2008.
- Nixon, Robin (27 October 2010). "Poisoned Halloween Candy: Trick, Treat or Myth? – LiveScience". LiveScience.com. Retrieved 23 January 2011.
- "Halloween Food:Scary Faced Pizza".
- Bannatyne, Lesley Pratt (1 August 1998). Halloween: An American Holiday, an American History. Pelican Publishing. p. 12. ISBN 1565543467. Retrieved 1 November 2012. "Polish Catholics taught their children to pray out loud as they walked through the woods so that the souls of the dead could hear them and be comforted. Priests in tiny Spanish villages still ring their church bells to remind parishioners to honor the dead on All Hallows Eve."
- "BBC - Religions - Christianity: All Hallows' Eve". British Broadcasting Corporation (BBC). 2010. Retrieved 1 November 2011. "All Hallows' Eve falls on 31st October each year, and is the day before All Hallows' Day, also known as All Saints' Day in the Christian calendar. The Church traditionally held a vigil on All Hallows' Eve when worshippers would prepare themselves with prayers and fasting prior to the feast day itself."
- Dr. Andrew James Harvey (31 October 2012). "'All Hallows' Eve'". The Patriot Post. Retrieved 1 November 2011. ""The vigil of the hallows" refers to the prayer service the evening before the celebration of All Hallows or Saints Day. Or "Halloween" for short -- a fixture on the liturgical calendar of the Christian West since the seventh century."
- "Vigil of All Saints". Catholic News Agency. 31 October 2012. Retrieved 1 November 2011. "The Vigil is based on the monastic office of Vigils (or Matins), when the monks would arise in the middle of the night to pray. On major feast days, they would have an extended service of readings (scriptural, patristic, and from lives of the saints) in addition to chanting the psalms. This all would be done in the dark, of course, and was an opportunity to listen carefully to the Word of God as well as the words of the Church Fathers and great saints. The Vigil of All Saints is an adaptation of this ancient practice, using the canonical office of Compline at the end."
- "Night of Light Beginnings". Cor et Lumen Christi Community. Retrieved 2 November 2012. "In its first year - 2000 AD - over 1000 people participated from several countries. This included special All Saints Vigil masses, extended periods of Adoration of the Blessed Sacrament and parties for children. In our second year 10,000 participated. Since these modest beginnings, the Night of Light has been adopted in many countries around the world with vast numbers involved each year from a Cathedral in India to a convent in New Zealand; from Churches in the USA and Europe to Africa; in Schools, churches, homes and church halls all ages have got involved. Although it began in the Catholic Church it has been taken up be other Christians who while keeping it's essentials have adapted it to suit their own traditions."
- "Here's to the Soulcakers going about their mysterious mummery". The Telegraph. Retrieved 6 November 2012. "One that has grown over the past decade is the so-called Night of Light, on All Hallows’ Eve, October 31. It was invented in 2000, in leafy Chertsey, Surrey, when perhaps 1,000 people took part. Now it is a worldwide movement, popular in Africa and the United States. The heart of the Night of Light is an all-night vigil of prayer, but there is room for children’s fun too: sweets, perhaps a bonfire and dressing up as St George or St Lucy. The minimum gesture is to put a lighted candle in the window, which is in itself too exciting for some proponents of health and safety. The inventor of the Night of Light is Damian Stayne, the founder of a year-round religious community called Cor et Lumen Christi – heart and light of Christ. This new movement is Catholic, orthodox and charismatic – emphasising the work of the Holy Spirit."
- Armentrout, Donald S.; Slocum, Robert Boak (1999). An Episcopal Dictionary of the Church. Church Publishing, Inc. p. 7. ISBN 0898692113. Retrieved 1 November 2012. "The BOS notes that "suitable festivities and entertainments" may precede of follow the service, and there may be a visit to a cemetery or burial place."
- Infeld, Joanna (1 December 2008). In-Formation. D & J Holdings LLC. p. 150. ISBN 0976051249. Retrieved 1 November 2012. "My folks are Polish and they celebrate Halloween in a different way. It is time to remember your dead and visit the cemetery and graves of your loved ones."
- "Bishop Challenges Supermarkets to Lighten up Halloween". The Church of England. Retrieved 28 October 2009. "Christianity needs to make clear its positive message for young people. It's high time we reclaimed the Christian aspects of Halloween," says the Bishop, explaining the background to his letter."
- "Halloween and All Saints Day". newadvent.org. n.d. Retrieved 22 October 2006.
- "Halloween Prayers: Prayers and Collects for All Hallows Eve". Ancient and Future Catholics. 2001. Retrieved 31 October 2011. "Father, All-Powerful and Ever-Living God, today we rejoice in the holy men and women of every time and place. May their prayers bring us your forgiveness and love. We ask this through Christ our Lord. Amen."
- "Reformation Day". Retrieved 22 October 2009
- "Reformation Day: What, Why, and Resources for Worship". The General Board of Discipleship of The United Methodist Church. 21 October 2005. Archived from the original on 23 February 2007. Retrieved 22 October 2006.
- Travis Allen (2011). "Christians and Halloween". John F. MacArthur. Retrieved 31 October 2011. "Other Christians will opt for Halloween alternatives called "Harvest Festivals", "Hallelujah Night" or "Reformation Festivals"--the kids dress up as farmers, Bible characters, or Reformation heroes."
- Gyles Brandreth, "The Devil is gaining ground" Sunday Telegraph (London), 11 March 2000.
- "Salem 'Saint Fest' restores Christian message to Halloween". www.rcab.org. n.d. Archived from the original on 29 September 2006. Retrieved 22 October 2006.
- "Feast of Samhain/Celtic New Year/Celebration of All Celtic Saints 1 November". All Saints Parish. n.d. Retrieved 22 November 2006.
- Halloween's Christian Roots AmericanCatholic.org. Retrieved on 24 October 2007.
- Halloween: What's a Christian to Do? (1998) by Steve Russo.
- "'Trick?' or 'Treat?' – Unmasking Halloween". The Restored Church of God. n.d. Retrieved 21 September 2007.
- "Jews and Halloween". Jewishvirtuallibrary.org. Retrieved 2013-03-05.
- Name (required) (2011-10-30). "Halloween and Judaism: a contradiction or a coalition?". Haamnews.wordpress.com. Retrieved 2013-03-05.
- Halloween fire calls 'every 90 seconds' UTV News Retrieved 22 November 2010
- McCann, Chris (28 October 2010). "Halloween firework injuries are on the increase". Belfast Telegraph. Retrieved 22 November 2010.
- Paul Kent (27 October 2010). "Calls for Halloween holiday in Australia". The Herald Sun.
- Denton, Hannah (30 October 2010). "Safe treats for kids on year's scariest night". New Zealand Herald. Retrieved 22 November 2010.
- Rogers, Nicholas (2002). Halloween: From Pagan Ritual to Party Night, p.164. New York: Oxford University Press. ISBN 0-19-516896-8
Further reading
- Diane C. Arkins, Halloween: Romantic Art and Customs of Yesteryear, Pelican Publishing Company (2000). 96 pages. ISBN 1-56554-712-8
- Diane C. Arkins, Halloween Merrymaking: An Illustrated Celebration Of Fun, Food, And Frolics From Halloweens Past, Pelican Publishing Company (2004). 112 pages. ISBN 1-58980-113-X
- Lesley Bannatyne, Halloween: An American Holiday, An American History, Facts on File (1990, Pelican Publishing Company, 1998). 180 pages. ISBN 1-56554-346-7
- Lesley Bannatyne, A Halloween Reader. Stories, Poems and Plays from Halloweens Past, Pelican Publishing Company (2004). 272 pages. ISBN 1-58980-176-8
- Phyllis Galembo, Dressed for Thrills: 100 Years of Halloween Costumes and Masquerade, Harry N. Abrams, Inc. (2002). 128 pages. ISBN 0-8109-3291-1
- Editha Hörandner (ed.), Halloween in der Steiermark und anderswo, Volkskunde (Münster in Westfalen), LIT Verlag Münster (2005). 308 pages. ISBN 3-8258-8889-4
- Lisa Morton, The Halloween Encyclopedia, McFarland & Company (2003). 240 pages. ISBN 0-7864-1524-X
- Nicholas Rogers, Halloween: From Pagan Ritual to Party Night, Oxford University Press, USA (2002). ISBN 0-19-514691-3
- Jack Santino (ed.), Halloween and Other Festivals of Death and Life, University of Tennessee Press (1994). 280 pages. ISBN 0-87049-813-4
|Find more about Halloween at Wikipedia's sister projects|
|Definitions and translations from Wiktionary|
|Media from Commons|
|News stories from Wikinews|
|Source texts from Wikisource|
|Travel information from Wikivoyage|
|
/**
* Copyright 2015-2021 IQRF Tech s.r.o.
* Copyright 2019-2021 MICRORISC s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "IDpaTransactionResult2.h"
#include "JsDriverSolver.h"
#include "Dali.h"
#include "JsonUtils.h"
#include <vector>
namespace iqrf
{
// use as common functionality predecessor for JsDriverDali, JsDriverSensor
class JsDriverStandardFrcSolver : public JsDriverSolver
{
private:
std::string m_functionName;
DpaMessage m_frcRequest;
uint16_t m_hwpid;
DpaMessage m_frcExtraRequest;
DpaMessage m_frcResponse;
DpaMessage m_frcExtraResponse;
std::unique_ptr<IDpaTransactionResult2> m_frcDpaTransactionResult;
std::unique_ptr<IDpaTransactionResult2> m_frcExtraDpaTransactionResult;
rapidjson::Document m_frcRequestResult0Doc;
rapidjson::Document m_frcResponseResultDoc;
protected:
// used by sensor::JsDriverFrc, dali::JsDriverFrc
JsDriverStandardFrcSolver(IJsRenderService* iJsRenderService)
:JsDriverSolver(iJsRenderService)
, m_hwpid(0xFFFF)
{}
public:
JsDriverStandardFrcSolver(IJsRenderService* iJsRenderService, const std::string & functionName, const rapidjson::Value & val, uint16_t hwpid)
:JsDriverSolver(iJsRenderService)
, m_functionName(functionName)
, m_hwpid(hwpid)
{
setRequestParamDoc(val);
}
virtual ~JsDriverStandardFrcSolver() {}
const DpaMessage & getFrcRequest() const { return m_frcRequest; }
const DpaMessage & getFrcExtraRequest() const { return m_frcExtraRequest; }
const rapidjson::Document & getRequestResult0Doc() const { return m_frcRequestResult0Doc; }
const rapidjson::Document & getResponseResultDoc() const { return m_frcResponseResultDoc; }
void setFrcDpaTransactionResult(std::unique_ptr<IDpaTransactionResult2> res)
{
m_frcDpaTransactionResult = std::move(res);
if (!m_frcDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc response");
}
m_frcResponse = m_frcDpaTransactionResult->getResponse();
}
void setFrcExtraDpaTransactionResult(std::unique_ptr<IDpaTransactionResult2> res)
{
m_frcExtraDpaTransactionResult = std::move(res);
if (!m_frcExtraDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc Extra response");
}
m_frcExtraResponse = m_frcExtraDpaTransactionResult->getResponse();
}
std::unique_ptr<IDpaTransactionResult2> moveFrcDpaTransactionResult()
{
return std::move(m_frcDpaTransactionResult);
}
std::unique_ptr<IDpaTransactionResult2> moveFrcExtraDpaTransactionResult()
{
return std::move(m_frcExtraDpaTransactionResult);
}
const rapidjson::Document & getResponseResultDoc() { return m_responseResultDoc; }
// partial JSON parse to get nadrs of returned results
rapidjson::Document getExtFormat(const std::string & resultArrayKey, const std::string & resultItemKey)
{
using namespace rapidjson;
Document doc;
doc.SetArray();
// get nadrs from selectedNodes if applied
std::set<int> selectedNodesSet;
const Value *selectedNodesVal = Pointer("/selectedNodes").Get(getRequestParamDoc());
if (selectedNodesVal && selectedNodesVal->IsArray()) {
for (const Value *nadrVal = selectedNodesVal->Begin(); nadrVal != selectedNodesVal->End(); nadrVal++) {
if (nadrVal->IsInt()) {
selectedNodesSet.insert(nadrVal->GetInt());
}
else {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array of Int .../selectedNodes[]");
}
}
}
Value *arrayVal = Pointer(resultArrayKey).Get(m_frcResponseResultDoc);
if (!(arrayVal && arrayVal->IsArray())) {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array ..." << resultArrayKey << "[]");
}
if (arrayVal->Size() > 0) { // is there something in the array?
if (selectedNodesSet.size() > 0) {
// selective FRC
// check size
if ((selectedNodesSet.size() + 1) > arrayVal->Size()) {
THROW_EXC_TRC_WAR(std::logic_error, "Inconsistent .../selectedNodes[] and ..." << resultArrayKey << "[]");
}
// iterate via selected nodes
const Value *itemVal = arrayVal->Begin() + 1; //skip index 0 as driver returns first null as a result of general FRC
for (auto nadr : selectedNodesSet) {
Value sensorVal;
Pointer("/nAdr").Set(sensorVal, nadr, doc.GetAllocator());
Pointer(resultItemKey).Set(sensorVal, *itemVal++, doc.GetAllocator());
doc.PushBack(sensorVal, doc.GetAllocator());
}
}
else {
// non-selective FRC //TODO does FRC always starts from nadr=0?
int nadr = 0;
for (Value *itemVal = arrayVal->Begin(); itemVal != arrayVal->End(); itemVal++) {
Value sensorVal;
Pointer("/nAdr").Set(sensorVal, nadr++, doc.GetAllocator());
Pointer(resultItemKey).Set(sensorVal, *itemVal, doc.GetAllocator());
doc.PushBack(sensorVal, doc.GetAllocator());
}
}
}
return doc;
}
protected:
uint16_t getNadrDrv() const override
{
return (uint16_t)0; // coordinator
}
uint16_t getHwpidDrv() const
{
return m_hwpid;
}
std::string functionName() const override
{
return m_functionName;
}
void preRequest(rapidjson::Document& requestResultDoc) override
{
// set in ctor by setRequestParamDoc(val);
(void)requestResultDoc; //silence -Wunused-parameter
}
void postRequest(const rapidjson::Document& requestResultDoc) override
{
using namespace rapidjson;
if (const Value *val0 = Pointer("/retpars/0").Get(requestResultDoc)) {
uint8_t pnum, pcmd;
rawHdp2dpaRequest(m_frcRequest, getNadrDrv(), pnum, pcmd, getHwpidDrv(), *val0);
m_frcRequestResult0Doc.CopyFrom(*val0, m_frcRequestResult0Doc.GetAllocator());
}
else {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array .../retpars[0]");
}
if (const Value *val1 = Pointer("/retpars/1").Get(requestResultDoc)) {
uint8_t pnum, pcmd;
rawHdp2dpaRequest(m_frcExtraRequest, getNadrDrv(), pnum, pcmd, getHwpidDrv(), *val1);
}
else {
THROW_EXC_TRC_WAR(std::logic_error, "Expected: Json Array .../retpars[1]");
}
}
void preResponse(rapidjson::Document& responseParamDoc) override
{
using namespace rapidjson;
// some std FRC needs requestParam to parse response
responseParamDoc.CopyFrom(getRequestParamDoc(), responseParamDoc.GetAllocator());
if (!m_frcDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc response");
}
{
Value val;
dpa2rawHdpResponse(m_frcResponse, val, responseParamDoc.GetAllocator());
Pointer("/responseFrcSend").Set(responseParamDoc, val);
}
if (m_frcExtraDpaTransactionResult) {
// optional extra result
if (!m_frcExtraDpaTransactionResult->isResponded()) {
THROW_EXC_TRC_WAR(std::logic_error, "No Frc response");
}
{
Value val;
dpa2rawHdpResponse(m_frcExtraResponse, val, responseParamDoc.GetAllocator());
Pointer("/responseFrcExtraResult").Set(responseParamDoc, val);
}
}
Pointer("/frcSendRequest").Set(responseParamDoc, m_frcRequestResult0Doc);
}
void postResponse(const rapidjson::Document& responseResultDoc) override
{
m_frcResponseResultDoc.CopyFrom(responseResultDoc, m_frcResponseResultDoc.GetAllocator());
}
};
} //namespace iqrf
|
#pragma once
#include <vector>
#include <list>
#include <functional>
#include <pthread.h>
#include <memory>
#include <iostream>
#include <pthread.h>
#include <sys/prctl.h>
#include <csignal>
#include "utils/Uncopyable.h"
#include "thread/MutexLock.h"
#include "thread/Condition.h"
template<typename T>
struct ThreadTask {
std::function<void(std::shared_ptr<T>)> process; // 线程接受的函数
std::shared_ptr<T> arg; // 该函数接受的参数表指针(若为单参数,则可为参数指针)
ThreadTask() {}
ThreadTask(std::shared_ptr<T>& arg, std::function<void(std::shared_ptr<T>)>& process):
process(process), arg(arg) { }
};
template<typename T>
class ThreadPool {
// 互斥锁
MutexLock mutex;
Condition condition;
// 线程池属性
int thread_num;
int max_queue_size;
// 状态信息
int started;
int shutdown_;
// 资源池与请求队列
std::vector<pthread_t> threads;
std::list<ThreadTask<T>> request_queue;
static void *worker(void *args);
/**
* @brief EventLoop:执行执行等待队列内的任务。
*/
void run();
public:
enum {
Default_Thread_Num = 8,
Max_Thread_Num = 1024,
Max_Queue_Size = 16384
};
typedef enum {
immediate_mode = 1,
graceful_mode = 2
} ShutdownMode;
ThreadPool(int thread_num, int max_queue_size);
~ThreadPool();
bool append(std::shared_ptr<T> arg, std::function<void(std::shared_ptr<T>)> fun);
void shutdown(bool graceful);
};
using std::cout;
using std::cerr;
using std::endl;
template<typename T>
ThreadPool<T>::ThreadPool(int thread_num, int max_queue_size) :
thread_num(thread_num), max_queue_size(max_queue_size),
started(0), shutdown_(0) {
if (thread_num <= 0 || thread_num > Max_Thread_Num) {
// 不合法的线程数量
cout << "Invalid thread size: " << thread_num << ", " << endl
<< "will be set to default value: " << Default_Thread_Num << endl;
thread_num = Default_Thread_Num;
}
if (max_queue_size <= 0 || max_queue_size > Max_Queue_Size) {
// 不合法的最大任务数量
cout << "Invalid waiting queue size: " << max_queue_size << ", " << endl
<< "will be set to default value: " << Max_Queue_Size << "." << endl;
max_queue_size = Max_Queue_Size;
}
// 创建线程,并保存线程的 tid
threads.resize(thread_num);
for (int i = 0; i < thread_num; i++) {
if (pthread_create(&threads[i], NULL, worker, this) != 0) {
cerr << "Failed to create thread#" << i << "." << endl;
abort();
}
started++;
}
}
template<typename T>
ThreadPool<T>::~ThreadPool() {
if (!shutdown_)
shutdown(true);
}
template<typename T>
bool ThreadPool<T>::append(std::shared_ptr<T> arg, std::function<void(std::shared_ptr<T>)> fun) {
// 如果已经停机,则不接受更多的链接
if (shutdown_) {
cout << "Failed to append task: ThreadPool has been shutdown." << endl;
return false;
}
MutexLockGuard guard(this->mutex);
if (request_queue.size() >= max_queue_size) {
cout << "Failed to append task: waiting queue is full." << endl;
return false;
}
// 向等待队列添加新的任务
request_queue.push_back({arg, fun});
// 通知空闲的线程处理任务队列
condition.notify();
return true;
}
template<typename T>
void ThreadPool<T>::shutdown(bool graceful) {
{
MutexLockGuard guard(this->mutex);
// 如果已经在停机状态,不需额外操作
if (shutdown_) {
cout << "Fail to shutdown: server has been shutdown." << endl;
// 进程退出时自动释放持有的文件符,无需手动释放
return;
}
shutdown_ = graceful ? graceful_mode : immediate_mode;
condition.notifyAll();
}
// 等待所有 thread 执行完毕
for (int i = 0; i < thread_num; i++) {
if (pthread_join(threads[i], NULL) != 0) {
cerr << "Fail to end thread: pthread_join error for thread#" << i << endl
<< "-- TID: " << threads[i] << endl;
}
}
}
template<typename T>
void *ThreadPool<T>::worker(void *args) {
ThreadPool *pool = static_cast<ThreadPool *>(args);
// 若线程池指针无效,则立即停止执行
if (pool == nullptr)
return NULL;
// 设置线程名
prctl(PR_SET_NAME,"EventLoopThread");
sigset_t cur_set;
sigaddset(&cur_set, SIGPIPE);
sigaddset(&cur_set, SIGINT);
pthread_sigmask(SIG_BLOCK, &cur_set, nullptr);
// 执行 EventLoop
pool->run();
return NULL;
}
template<typename T>
void ThreadPool<T>::run() {
// EventLoop
while (true) {
ThreadTask<T> requestTask;
{
// 此作用域用来约束互斥锁范围
MutexLockGuard guard(this->mutex);
// 没有任务且没有停机的情况下,不断通过条件变量进行等待(自旋锁会不会更快?)
while (request_queue.empty() && !shutdown_) {
// 此处条件变量会解锁互斥锁,因而不会死锁
condition.wait(this->mutex);
}
// 处理停机的情况:如果立即停机,则不处理剩下任务
// 如果为优雅关闭模式,则继续处理剩下的任务,直到处理完停机
if ((shutdown_ == immediate_mode) || (shutdown_ == graceful_mode && request_queue.empty())) {
break;
}
// 处理等待队列中的任务
requestTask = request_queue.front();
request_queue.pop_front();
}
// 此时互斥锁已经释放,因而执行过程不会阻塞线程池
requestTask.process(requestTask.arg);
}
}
|
#include <numeric>
#include "demoloop.h"
#include "graphics/3d_primitives.h"
#include <glm/gtx/rotate_vector.hpp>
#include "hsl.h"
using namespace std;
using namespace demoloop;
static const uint16_t NUM_VERTS = 60;
const uint32_t CYCLE_LENGTH = 3;
static const float RADIUS = 0.3;
class Loop11 : public Demoloop {
public:
Loop11() : Demoloop(CYCLE_LENGTH, 150, 150, 150), mesh(icosahedron(0, 0, 0, RADIUS)) {
gl.getProjection() = glm::perspective((float)DEMOLOOP_M_PI / 4.0f, (float)width / (float)height, 0.1f, 100.0f);
iota(mesh.mIndices.begin(), mesh.mIndices.end(), 0);
}
void Update() {
const float cycle_ratio = getCycleRatio();
for (int i = 0; i < NUM_VERTS; ++i) {
const float t = i;
const float interval_cycle_ratio = fmod(t / NUM_VERTS + cycle_ratio, 1);
auto color = hsl2rgb(interval_cycle_ratio, 1, 0.5);
Vertex &v = mesh.mVertices[i];
v.r = color.r;
v.g = color.g;
v.b = color.b;
v.a = 255;
}
gl.pushTransform();
const float cameraX = 0;//sin(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
// const float cameraY = pow(sin(cycle_ratio * DEMOLOOP_M_PI * 2), 2);
const float cameraY = cos(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
const float cameraZ = 3;//cos(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
gl.getTransform() = glm::lookAt(glm::vec3(cameraX, cameraY, cameraZ), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
mesh.buffer();
mesh.draw();
glm::mat4 m;
m = glm::translate(m, {0, sinf(cycle_ratio * DEMOLOOP_M_PI * 2) * RADIUS * 4, 0});
m = glm::scale(m, {0.5, 0.5, 0.5});
mesh.draw(m);
gl.popTransform();
}
private:
Mesh mesh;
};
int main(int, char**){
Loop11 test;
test.Run();
return 0;
}
|
|Birth name||Norman Percevel Rockwell|
February 3, 1894|
New York City
|Died||November 8, 1978
|Training||National Academy of Design
Art Students League
Norman Percevel Rockwell (February 3, 1894 – November 8, 1978) was a 20th-century American painter and illustrator. His works enjoy a broad popular appeal in the United States for their reflection of American culture. Rockwell is most famous for the cover illustrations of everyday life scenarios he created for The Saturday Evening Post magazine for more than four decades. Among the best-known of Rockwell's works are the Willie Gillis series, Rosie the Riveter, Saying Grace (1951), The Problem We All Live With, and the Four Freedoms series. He is also noted for his work for the Boy Scouts of America (BSA); producing covers for their publication Boys' Life, calendars, and other illustrations.
Life and works
Early life
Norman Rockwell was born on February 3, 1894, in New York City to Jarvis Waring Rockwell and Anne Mary "Nancy" (born Hill) Rockwell. His earliest American ancestor was John Rockwell (1588–1662), from Somerset, England, who immigrated to America probably in 1635 aboard the ship Hopewell and became one of the first settlers of Windsor, Connecticut. He had one brother, Jarvis Waring Rockwell, Jr., older by a year and a half. Jarvis Waring, Sr., was the manager of the New York office of a Philadelphia textile firm, George Wood, Sons & Company, where he spent his entire career.
Norman transferred from high school to the Chase Art School at the age of 14. He then went on to the National Academy of Design and finally to the Art Students League. There, he was taught by Thomas Fogarty, George Bridgman, and Frank Vincent DuMond; his early works were produced for St. Nicholas Magazine, the Boy Scouts of America (BSA) publication Boys' Life and other juvenile publications. Joseph Csatari carried on his legacy and style for the BSA.
As a student, Rockwell was given smaller, less important jobs. His first major breakthrough came in 1912 at age eighteen with his first book illustration for Carl H. Claudy's Tell Me Why: Stories about Mother Nature.
In 1913, the nineteen-year-old Rockwell became the art editor for Boys' Life, published by the Boy Scouts of America, a post he held for three years (1913–1916). As part of that position, he painted several covers, beginning with his first published magazine cover, Scout at Ship's Wheel, appearing on the Boys' Life September 1913 edition.
World War I
During World War I, he tried to enlist into the U.S. Navy but was refused entry because, at 6 feet (1.8 m) tall and 140 pounds (64 kg) he was eight pounds underweight. To compensate, he spent one night gorging himself on bananas, liquids and doughnuts, and weighed enough to enlist the next day. However, he was given the role of a military artist and did not see any action during his tour of duty.
Rockwell's family moved to New Rochelle, New York when Norman was 21 years old and shared a studio with the cartoonist Clyde Forsythe, who worked for The Saturday Evening Post. With Forsythe's help, he submitted his first successful cover painting to the Post in 1916, Mother's Day Off (published on May 20). He followed that success with Circus Barker and Strongman (published on June 3), Gramps at the Plate (August 5), Redhead Loves Hatty Perkins (September 16), People in a Theatre Balcony (October 14) and Man Playing Santa (December 9). Rockwell was published eight times total on the Post cover within the first twelve months. Norman Rockwell published a total of 323 original covers for The Saturday Evening Post over 47 years. His Sharp Harmony appeared on the cover of the issue dated September 26, 1936; it depicts a barber and three clients, enjoying an a cappella song. The image was adopted by SPEBSQSA in its promotion of the art.
Rockwell's success on the cover of the Post led to covers for other magazines of the day, most notably The Literary Digest, The Country Gentleman, Leslie's Weekly, Judge, Peoples Popular Monthly and Life Magazine.
Personal life
Rockwell married his first wife, Irene O'Connor, in 1916. Irene was Rockwell's model in Mother Tucking Children into Bed, published on the cover of The Literary Digest on January 19, 1921. However, the couple were divorced in 1930. Depressed, he moved briefly to Alhambra, California as a guest of his old friend Clyde Forsythe. There he painted some of his best-known paintings including "The Doctor and the Doll". While there he met and married schoolteacher Mary Barstow. The couple returned to New York shortly after their marriage. They had three children: Jarvis Waring, Thomas Rhodes and Peter Barstow. The family lived at 24 Lord Kitchener Road in the Bonnie Crest neighborhood of New Rochelle, New York. Rockwell and his wife were not very religious, although they were members of St. John's Wilmot Church, an Episcopal church near their home, and had their sons baptized there as well. Rockwell moved to Arlington, Vermont, in 1939 where his work began to reflect small-town life.
In 1953, the Rockwell family moved to Stockbridge, Massachusetts, so that his wife could be treated at the Austen Riggs Center, a psychiatric hospital at 25 Main Street, down Main Street from where Rockwell set up his studio. Rockwell himself received psychiatric treatment from the analyst Erik Erikson, who was on staff at Riggs. Erikson is said to have told the artist that he painted his happiness, but did not live it. In 1959, Mary Barstow Rockwell died unexpectedly of a heart attack.
World War II
In 1943, during World War II, Rockwell painted the Four Freedoms series, which was completed in seven months and resulted in his losing 15 pounds. The series was inspired by a speech by Franklin D. Roosevelt, in which he described four principles for universal rights: Freedom from Want, Freedom of Speech, Freedom of Worship, and Freedom from Fear. The paintings were published in 1943 by The Saturday Evening Post. The United States Department of the Treasury later promoted war bonds by exhibiting the originals in 16 cities. Rockwell himself considered "Freedom of Speech" to be the best of the four. That same year, a fire in his studio destroyed numerous original paintings, costumes, and props.
Shortly after the war, Rockwell was contacted by writer Elliott Caplin, brother of cartoonist Al Capp, with the suggestion that the three of them should make a daily comic strip together, with Caplin and his brother writing and Rockwell drawing. King Features Syndicate is reported to have promised a $1,000/week deal, knowing that a Capp-Rockwell collaboration would gain strong public interest. However, the project was ultimately aborted as it turned out that Rockwell, known for his perfectionism as an artist, could not deliver material as fast as required of him for a daily comic strip.
During the late 1940s, Norman Rockwell spent the winter months as artist-in-residence at Otis College of Art and Design. Students occasionally were models for his Saturday Evening Post covers. In 1949, Rockwell donated an original Post cover, "April Fool", to be raffled off in a library fund raiser.
In 1959, his wife Mary died unexpectedly from a heart attack, and Rockwell took time off from his work to grieve. It was during that break that he and his son Thomas produced his autobiography, My Adventures as an Illustrator, which was published in 1960. The Post printed excerpts from this book in eight consecutive issues, the first containing Rockwell's famous Triple Self-Portrait.
Later career
Rockwell married his third wife, retired Milton Academy English teacher Mary Leete "Molly" Punderson, on October 25, 1961. His last painting for the Post was published in 1963, marking the end of a publishing relationship that had included 321 cover paintings. He spent the next ten years painting for Look magazine, where his work depicted his interests in civil rights, poverty and space exploration. In 1968, Rockwell was commissioned to do an album cover portrait of Mike Bloomfield and Al Kooper for their record The Live Adventures of Mike Bloomfield and Al Kooper. During his long career, he was commissioned to paint the portraits for Presidents Eisenhower, Kennedy, Johnson, and Nixon, as well as those of foreign figures, including Gamal Abdel Nasser and Jawaharlal Nehru. One of his last works was a portrait of Judy Garland in 1969.
A custodianship of his original paintings and drawings was established with Rockwell's help near his home in Stockbridge, Massachusetts, and the Norman Rockwell Museum is still open today year round. Norman Rockwell Museum is the authoritative source for all things Norman Rockwell. The museum's collection is the world's largest, including more than 700 original Rockwell paintings, drawings, and studies. The Rockwell Center for American Visual Studies at the Norman Rockwell Museum is a national research institute dedicated to American illustration art.
When he began suffering poor health, he placed his studio and the contents with the Norman Rockwell Museum, which was formerly known as the Stockbridge Historical Society and even more formerly known as the Old Corner house, in a trust.
For "vivid and affectionate portraits of our country," Rockwell received the Presidential Medal of Freedom, the United States of America's highest civilian honor, in 1977.
Body of work
Norman Rockwell was a prolific artist, producing over 4,000 original works in his lifetime. Most of his works are either in public collections, or have been destroyed in fire or other misfortunes. Rockwell was also commissioned to illustrate over 40 books including Tom Sawyer and Huckleberry Finn. His annual contributions for the Boy Scouts' calendars between 1925 and 1976 (Rockwell was a 1939 recipient of the Silver Buffalo Award, the highest adult award given by the Boy Scouts of America), were only slightly overshadowed by his most popular of calendar works: the "Four Seasons" illustrations for Brown & Bigelow that were published for 17 years beginning in 1947 and reproduced in various styles and sizes since 1964. Illustrations for booklets, catalogs, posters (particularly movie promotions), sheet music, stamps, playing cards, and murals (including "Yankee Doodle Dandy" and "God Bless the Hills", which was completed in 1936 for the Nassau Inn in Princeton, New Jersey) rounded out Rockwell's œuvre as an illustrator.
In 1969, as a tribute to Rockwell's 75th-year birthday, officials of Brown & Bigelow and the Boy Scouts of America asked Rockwell to pose in Beyond the Easel, the calendar illustration that year.
Rockwell's work was dismissed by serious art critics in his lifetime. Many of his works appear overly sweet in modern critics' eyes, especially the Saturday Evening Post covers, which tend toward idealistic or sentimentalized portrayals of American life – this has led to the often-deprecatory adjective "Rockwellesque". Consequently, Rockwell is not considered a "serious painter" by some contemporary artists, who often regard his work as bourgeois and kitsch. Writer Vladimir Nabokov sneered that Rockwell's brilliant technique was put to "banal" use, and wrote in his book Pnin: "That Dalí is really Norman Rockwell's twin brother kidnapped by Gypsies in babyhood". He is called an "illustrator" instead of an artist by some critics, a designation he did not mind, as it was what he called himself.
However, in his later years, Rockwell began receiving more attention as a painter when he chose more serious subjects such as the series on racism for Look magazine. One example of this more serious work is The Problem We All Live With, which dealt with the issue of school racial integration. The painting depicts a young African American girl, Ruby Bridges, flanked by white federal marshals, walking to school past a wall defaced by racist graffiti.
Rockwell's work was exhibited at the Solomon R. Guggenheim Museum in 2001. Rockwell's Breaking Home Ties sold for $15.4 million at a 2006 Sotheby's auction. A twelve-city U.S. tour of Rockwell's works took place in 2008. In 2008, Rockwell was named the official state artist of the Commonwealth of Massachusetts.
- In the film Empire of the Sun, a young boy (played by Christian Bale) is put to bed by his loving parents in a scene also inspired by a Rockwell painting—a reproduction of which is later kept by the young boy during his captivity in a prison camp ("Freedom from Fear", 1943).
- The 1994 film Forrest Gump includes a shot in a school that re-creates Rockwell's "Girl with Black Eye" with young Forrest in place of the girl. Much of the film drew heavy visual inspiration from Rockwell's art.
- Film director George Lucas owns Rockwell's original of "The Peach Crop", and his colleague Steven Spielberg owns a sketch of Rockwell's Triple Self-Portrait. Each of the artworks hangs in the respective filmmaker's workspace. Rockwell is a major character in an episode of Lucas’ Young Indiana Jones Chronicles, “Passion for Life.”
- In 2005, Target Co. sold Marshall Field's to Federated Department Stores and the Federated discovered a reproduction of Rockwell's The Clock Mender, which depicted the great clocks of the Marshall Field and Company Building on display. Rockwell had donated the painting depicted on the cover of the November 3, 1945 Saturday Evening Post to the store in 1948.
- On Norman Rockwell's birthday, February 3, 2010, Google featured Rockwell's iconic image of young love "Boy and Girl Gazing at the Moon", which is also known as "Puppy Love", on its home page. The response was so great that day that the Norman Rockwell museum's servers went down under the onslaught.
- "Dreamland", a track from Canadian alternative rock band Our Lady Peace's 2009 album Burn Burn, was inspired by Rockwell's paintings.
Major works
- Scout at Ship's Wheel (first published magazine cover illustration, Boys' Life, September 1913)
- Santa and Scouts in Snow (1913)
- Boy and Baby Carriage (1916; first Saturday Evening Post cover)
- Circus Barker and Strongman (1916)
- Gramps at the Plate (1916)
- Redhead Loves Hatty Perkins (1916)
- People in a Theatre Balcony (1916)
- Tain't You (1917; first Life magazine cover)
- Cousin Reginald Goes to the Country (1917; first Country Gentleman cover)
- Santa and Expense Book (1920)
- Mother Tucking Children into Bed (1921; first wife Irene is the model)
- No Swimming (1921)
- Santa with Elves (1922)
- Doctor and Doll (1929)
- Deadline (1938)
- The Four Freedoms (1943)
- Rosie the Riveter (1943)
- Going and Coming (1947)
- Bottom of the Sixth (or The Three Umpires; 1949)
- The New Television Set (1949)
- Saying Grace (1951)
- The Young Lady with the Shiner (1953)
- Girl at Mirror (1954)
- Breaking Home Ties (1954)
- The Marriage License (1955)
- The Scoutmaster (1956)
- The Runaway (1958)
- A Family Tree (1959)
- Triple Self-Portrait (1960)
- Golden Rule (1961)
- The Problem We All Live With (1964)
- Southern Justice (Murder in Mississippi) (1965)
- New Kids in the Neighborhood (1967)
- Russian Schoolroom (1967)
- The Rookie
- Spirit of 76 (1976) (stolen in 1978 but recovered in 2001 by the FBI's Robert King Wittman)
Other collections
- Norman Rockwell World War II posters, hosted by the University of North Texas Libraries Digital Collections
- Rockwell Collection at the National Museum of American Illustration
- Norman Rockwell and the Art of Scouting at the National Scouting Museum, Irving, TX
See also
- James K. Van Brunt, a frequent model for Rockwell
- William Obanhein, another one of Rockwell's models who would later become famous elsewhere
- Norman Rockwell's World... An American Dream, a 1972 short documentary film
- "Alex Ross Biography". alexrossart.com. Retrieved February 13, 2012.
- About the Saturday Evening Post[dead link]
- Boughton, James (1903). Genealogy of the families of John Rockwell, of Stamford, Connecticut 1641, and Ralph Keeler, of Hartford, Connecticut 1939. W.F. Jones. p. 441.
- Roberts, Gary Boyd, and David Curtis Dearborn (1998). Notable Kin: An Anthology of Columns First Published in the NEHGS Nexus, 1986–1995. Boston, Massachusetts: Carl Boyer in cooperation with the New England Historic Genealogical Society. p. 28. ISBN 978-0-936124-20-9.
- Claridge, Laura P. (2001). Norman Rockwell: A Life. New York, New York: Random House. p. 20,29. ISBN 978-0-375-50453-2.
- Rockwell, Margaret (1998). Norman Rockwell's Growing Up in America. Metro Books. pp. 10–11. ISBN 978-1-56799-598-5.
- SSDI. – SS#: 177-01-3581.
- Claridge. – p.30,47,150.
- Rockwell, Norman, and Thomas Rockwell (1988). Norman Rockwell, My Adventures as an Illustrator. Abrams. p. 27. ISBN 978-0-8109-1563-3.
- "Rockwell and Csatari: A tour de force". Scouting magazine: 6. March–April, 2008.
- "A personal recollection". City of Alhambra. Retrieved April 28, 2012.
- Kamp, David (November 2009). "Norman Rockwell’s American Dream". Vanityfair.com. Retrieved April 28, 2012.
- "A portrait of Norman Rockwell - Berkshire Eagle Online". Berkshireeagle.com. July 3, 2009. Retrieved April 28, 2012.
- Elliott Caplin: Al Capp Remembered (1994)
- Gherman, Beverly (2000) "Norman Rockwell Storyteller with a brush"
- Claridge, p. 581
- Kamp, David. "Erratum: Norman Rockwell Actually Did Rock Well". Vanity Fair. Retrieved February 24, 2011.
- Official List of Silver Buffalo award Recipients (Retrieved July 17, 2007)
- William Hillcourt (1977). Norman Rockwell's World of Scouting. New York: Harry N. Abrams. ISBN 0-8109-1582-0.
- Jim Windolf (February 2008). "Keys to the Kingdom". Vanityfair.com. Retrieved April 28, 2012.
- "Solomon, Deborah, In Praise of Bad Art". New York Times. January 24, 1999. Retrieved April 28, 2012.
- "Art of Illustration". Norman Rockwell Museum. Retrieved April 28, 2012.
- "Norman Rockwell Wins Medal of Freedom". Massmoments.org. Retrieved April 28, 2012.
- Miller, Michelle (November 12, 2010). "Ruby Bridges, Rockwell Muse, Goes Back to School". CBS Evening News with Katie Couric (CBS Interactive Inc.). Retrieved November 13, 2010.
- Norman Rockwell at the Solomon R. Guggenheim Museum.[dead link]
- Gates, Anita (November 24, 1999). "Looking Beyond the Myth-Making Easel of Mr. Thanksgiving". New York Times. Retrieved April 28, 2012.
- RICHARD CORLISS (June 24, 2001). "The World According to Gump". Time.com. Retrieved April 28, 2012.
- Aronovich, Hannah (April 20, 2006). "Field's, Federated and More Feuds". Gothamist. Retrieved April 4, 2008.
- "Norman Rockwell Of Field's Store Goes Missing". NBC5.com. April 21, 2006. Retrieved April 4, 2008.
- Aronovich, Hannah (April 20, 2006). "Field's, Federated and More Feuds". Gothamist. Retrieved September 21, 2009.
- "Dreamland". Songfacts.com. Retrieved May 5, 2010.
- "Rosie the Riveter". Rosie the Riveter. Retrieved April 28, 2012.
- NRM, p. 109
- "The norman rockwell collection". Web.me.com. Retrieved April 28, 2012.
- "Norman Rockwell: Southern Justice (Murder in Mississippi)". Artchive.com. Retrieved April 28, 2012.
- "Museum > Exhibitions - Norman Rockwell and the Art of Scouting". Irving, Texas, USA: National Scouting Museum. Retrieved 16 August 2012.
Further reading
- Buechner, Thomas S (1992). The Norman Rockwell Treasury. Galahad. ISBN 0-88365-411-3.
- Finch, Christopher (1990). Norman Rockwell: 332 Magazine Covers. Abbeville Publishing Group. ISBN 0-89660-000-9.
- Christopher, Finch (1985). Norman Rockwell's America. Harry N. Abrams, Inc. ISBN 0-8109-8071-1.
- Gherman, Beverly (2000). Norman Rockwell: Storyteller with a Brush. ISBN 0-689-82001-1.
- Hennessey, Maureen Hart; Larson, Judy L. (1999). Norman Rockwell: Pictures for the American People. Harry N. Abrams. ISBN 0-8109-6392-2.
- Rockwell, Tom (2005). Best of Norman Rockwell. Courage Books. ISBN 0-7624-2415-X.
- Schick, Ron (2009). Norman Rockwell: Behind the Camera. Little, Brown & Co. ISBN 978-0-316-00693-4.
|Wikimedia Commons has media related to: Norman Rockwell|
|Wikiquote has a collection of quotations related to: Norman Rockwell|
- Booknotes interview with Laura Claridge on Norman Rockwell: A Life, December 2, 2001.
- Gallery of classic graphic design featuring the illustrations of Norman Rockwell.
- Art Directors Club biography, portrait and images of work
- Norman Rockwell at Find a Grave
- Footage of Norman Rockwell sketching a couple
- America, Illustrated – by The New York Times
- Norman Rockwell: Once upon a time there Was the American Dream by Tiziano Thomas Dossena, Bridge Puglia USA, April 2011
|
Sabermetrics is the specialized analysis of baseball through objective evidence, especially baseball statistics that measure in-game activity. The term is derived from the acronym SABR, which stands for the Society for American Baseball Research. It was coined by Bill James, who is one of its pioneers and is often considered its most prominent advocate and public face.
General principles
The Sabermetric Manifesto by David Grabiner (1994) begins:
Bill James defined sabermetrics as "the search for objective knowledge about baseball." Thus, sabermetrics attempts to answer objective questions about baseball, such as "which player on the Red Sox contributed the most to the team's offense?" or "How many home runs will Ken Griffey hit next year?" It cannot deal with the subjective judgments which are also important to the game, such as "Who is your favorite player?" or "That was a great game."
It may, however, attempt to settle questions such as "Was Willie Mays faster than Mickey Mantle?" by establishing several possible parameters for examining speed in objective studies (how many triples each man hit, how many bases each man stole, how many times he was caught stealing) and then reaching a tentative conclusion on the basis of these individual studies.
Sabermetricians frequently question traditional measures of baseball skill. For instance, they doubt that batting average is as useful as conventional wisdom says it is because team batting average provides a relatively poor fit for team runs scored. Sabermetric reasoning would say that runs win ballgames, and that a good measure of a player's worth is his ability to help his team score more runs than the opposing team. This may imply that the traditional RBI (runs batted in) is an effective metric; however, sabermetricians also reject RBI, for a number of reasons. Rather, sabermetric measures are usually phrased in terms of either runs or team wins. For example, a player might be described as being worth 54 offensive runs more than a replacement-level player at the same position over the course of a full season, as the sabermetric statistic VORP can indicate.
Sabermetrics is concerned both with determining the value of a player or team in current or past seasons and with attempting to predict the value of a player or team in the future. Many areas of study are still in development, specifically in the area of performance measurement.
Early history
Sabermetrics research began in the middle of the 20th century. Earnshaw Cook was one of the earliest researchers of sabermetrics. Cook gathered the majority of his research in his 1964 book, Percentage Baseball. The book was the first of its kind to gain national media attention, although it was widely criticized and not accepted by most baseball organizations.
- Base runs (BsR)
- Batting average on balls in play (BABIP)
- Defense independent pitching statistics (DIPS)
- Defensive Runs Saved (DRS)
- Equivalent average (EQA)
- Fantasy batter value (FBV)
- Late-inning pressure situations (LIPS)
- On-base plus slugging (OPS)
- PECOTA (Player empirical comparison and optimization test algorithm)
- Peripheral ERA (PERA)
- Pythagorean expectation
- Range factor
- Runs created
- Secondary average
- Similarity score
- Speed Score
- Super linear weights
- Total player rating, or Batter-Fielder Wins (TPR, BFW); Total Pitcher Index, or Pitcher Wins (TPI, PW)
- Ultimate zone rating (UZR)
- Value over replacement player (VORP)
- Win shares
- Wins above replacement (WAR)
Notable proponents
- Russ Brandon: Team President and CEO of the Buffalo Bills is going to incorporate Sabermetrics to contracts, and use in conjunction with scouting and player analysis beginning in 2013.
- Sandy Alderson: Former General Manager of the Oakland Athletics, Alderson began focusing on sabermetric principles toward obtaining relatively undervalued players in 1995. He became GM of the New York Mets in late 2010.
- Billy Beane: Athletics' General Manager since 1997. Although not a public proponent of sabermetrics, it has been widely noted that Beane has steered the team during his tenure according to sabermetric principles. In 2003, Michael Lewis published Moneyball about Billy Beane's use of a more quantitative approach. In 2011, a film based on Lewis' book which dramatised Beane's use of sabermetrics was released, starring Brad Pitt in the role of Beane.
- Carson Cistulli: Senior editor of FanGraphs, member of the BBWAA
- Earnshaw Cook: Early researcher and proponent of statistical baseball research. His 1964 book Percentage Baseball was the first book of baseball statistics studies to gain national media attention.
- Paul DePodesta: A key figure in Michael Lewis' book Moneyball: The Art of Winning an Unfair Game as Beane's assistant in Oakland.
- Theo Epstein: President of Baseball Operations for the Chicago Cubs. As GM of the Red Sox, Epstein hired sabermetrician Bill James.
- Bill James: Widely considered the father of sabermetrics due to his extensive series of books, although a number of less well known SABR researchers in the early 1970s provided a foundation for his work. He began publishing his Baseball Abstracts in 1977 to study some questions about baseball he found interesting, and their eclectic mix of essays based on new kinds of statistics soon became popular with a generation of thinking baseball fans. He discontinued the Abstracts after the 1988 edition, but continued to be active in the field. His two Historical Baseball Abstract editions and Win Shares book have continued to advance the field of sabermetrics, 25 years after he began. In 2002 James was hired as a special advisor to the Boston Red Sox.
- Christina Kahrl: Co-founder of Baseball Prospectus and current ESPN columnist, Kahrl puts an emphasis on advanced baseball analytics.
- Sean Lahman: Created a database of baseball statistics from existing sources and in the mid-1990s made it available for free download on the Internet, providing access to statistical data in electronic form for the first time.
- Voros McCracken: Developed a system called Defense Independent Pitching Statistics (DIPS) to evaluate a pitcher based purely on his ability.
- Rob Neyer: Senior writer at ESPN.com and national baseball editor of SBNation and former assistant to Bill James, he has worked to popularize sabermetrics since the mid-1980s. Neyer has authored or co-authored several books about baseball, and his journalistic writing focuses on sabermetric methods for looking at baseball players' and teams' performance.
- Joe Posnanski: A popular baseball writer and a proponent of sabermetrics.
- Nate Silver: Writer and former managing partner of Baseball Prospectus, inventor of PECOTA. Later applied sabermetric statistical models to the study of politics, particularly elections, and published the results on his blog FiveThirtyEight (later affiliated with The New York Times).
- David Smith: Founded Retrosheet in 1989, with the objective of computerizing the box score of every major league baseball game ever played, in order to more accurately collect and compare the statistics of the game.
- Tom Tango: Runs the Tango on Baseball sabermetrics website. In particular, he has worked in the area of defense independent pitching statistics.
- Eric Walker: Former aerospace engineer turned baseball writer, who played an important part in the early acceptance of sabermetrics within the Oakland Athletics organization. GM Sandy Alderson hired Walker in order to get "some Bill James-like stuff that was proprietary to us."
- Keith Woolner: Creator of VORP, or Value over Replacement Player, is a former writer for sabermetric group/website Baseball Prospectus. He was hired in 2007 by the Cleveland Indians as their Manager of Baseball Research & Analytics.
- Craig R. Wright: A statistician for the Texas Rangers, was the first front office employee in Major League Baseball to work under the title "Sabermetrician."
- Baseball Prospectus is an annual publication and web site produced by a group of sabermetricians who originally met over the Internet. Several Baseball Prospectus authors have invented or improved upon widely relied upon sabermetric measures and techniques. The website publishes analytical articles as well as advanced statistics and projections for individuals and teams. This group also publishes other books that use and seek to popularize sabermetric techniques, including Baseball Between the Numbers and It Ain't Over 'til It's Over.
- The Hardball Times is a website as well as an annual volume that evaluates the preceding major league season and presents original research articles on various sabermetric topics. The website also publishes original research on baseball.
- FanGraphs is a website that publishes advanced baseball statistics as well as graphics that evaluate and track the performance of players and teams. The site also favors the analysis of play-by-play data and PITCHf/x. It draws on some of the advanced baseball metrics developed by well-known sabermetricians such as Tom Tango and Mitchel Lichtman.
- Beyond the Boxscore is a part of SB Nation and specializes in sabermetric analysis and research. It has also launched the careers of many successful sabermetricians.
- SABR is the Society for American Baseball Research, founded in 1971, and the root of the term sabermetrics. Statistical study, however, is only a small component of SABR members' research, which also focuses on diverse issues including ballparks, the Negro Leagues, rules changes, and the desegregation of baseball as a mirror of American culture.
- Fielding Bible Awards are voted on by a panel of sabermetically inclined writers to recognize the best defensive player for each fielding position. It provides an alternative to the Gold Glove Awards, the traditional measurement of fielding excellence.
- Baseball Think Factory is a web forum that includes extensive coverage of and commentary on baseball, usually from the perspective of sabermetrics.
Popular culture
- Moneyball, the 2011 film about Billy Beane's use of sabermetrics to build the Oakland Athletics. The film is based on Michael Lewis' book of the same name.
- The season 3 Numb3rs episode "Hardball" focuses on sabermetrics, and the season 1 episode "Sacrifice" also covers the subject.
- "MoneyBART", the third episode of The Simpsons' 22nd season, in which Lisa utilizes sabermetrics to coach Bart's Little League Baseball team.
See also
- Fielding Bible Award
- Win Shares by Bill James
- Whatever Happened to the Hall of Fame? by Bill James
- Total Baseball by John Thorn and Pete Palmer
- The Bill James Historical Baseball Abstract
- Moneyball, by Michael Lewis
- APBRmetrics, the basketball equivalent
- Lewis, Michael M. (2003). Moneyball: The Art of Winning an Unfair Game. New York: W. W. Norton. ISBN 0-393-05765-8.
- Grabiner, David J. "The Sabermetric Manifesto". The Baseball Archive.
- Jarvis, J. (2003-09-29). "A Survey of Baseball Player Performance Evaluation Measures". Retrieved 2007-11-02.
- Albert, James; Jay M. Bennett (2001). Curve Ball: Baseball, Statistics, and the Role of Chance in the Game. Springer. pp. 170–171. ISBN 0-387-98816-5.
- Kipen, D. (June 1, 2003). "Billy Beane's brand-new ballgame". San Francisco Chronicle. Retrieved November 2, 2007.
- Neyer, Rob (November 5, 2002). "Red Sox hire James in advisory capacity". ESPN.com. Retrieved March 7, 2009.
- Shanahan, M. (May 23, 2005). Retrieved November 2, 2007 His numbers are in the ballpark The Boston Globe
- "Bill James, Beyond Baseball". Think Tank with Ben Wattenberg. PBS. June 28, 2005. Retrieved November 2, 2007.
- Ackman, D. (May 20, 2007). "Sultan of Stats". The Wall Street Journal. Retrieved November 2, 2007.
- Jaffe, C. (October 22, 2007). "Rob Neyer Interview". The Hardball Times. Retrieved November 2, 2007.
- Lewis, M. Moneyball. pp. 58–63.
- "Baseball Prospectus". Retrieved 2012-03-04.
- Baseball Between the Numbers. 2006. ISBN 0-465-00596-9.
- Goldman, Steven (2007). It Ain't Over 'til It's Over. ISBN 0-465-00285-4.
|
|Regions with significant populations|
|New York, Massachusetts, Michigan, Louisiana, Ohio, Iowa, Texas|
|Related ethnic groups|
Syrian Americans are residents of the United States of Syrian ancestry or nationality. This group includes Americans of Syrian ancestry, Syrian first generation immigrants, or descendants of Syrians who emigrated to the United States. Syrian Americans may be members of a number of differing ethnicities, including Arabs, Assyrians/Syriacs, Antiochian Greeks, Kurds, Armenians and Circassians. It is believed that the first significant wave of Syrian immigrants to arrive in the United States was in 1880. Many of the earliest Syrian Americans settled in New York, Boston, and Detroit. Immigration from Syria to the United States suffered a long hiatus after the United States Congress passed the Immigration Act of 1924, which restricted immigration. More than 40 years later, the Immigration Act of 1965, abolished the quotas and immigration from Syria to the United States saw a surge. An estimated 64,600 Syrians emigrated to the United States between 1961 and 2000.
The overwhelming majority of Syrian immigrants to the US from 1880 to 1960 were Christian, a minority were Jewish, whereas Muslim Syrians arrived in the United States chiefly after 1965. According to the United States 2000 Census, there were 142,897 Americans of Syrian ancestry, about 12% of the Arab population in the United States.
The first Syrian immigrants arrived in the United States from Ottoman Syria. Most of them came from Christian villages around Mount Lebanon, while around 5-10% were Muslims of different sects. A small number were also Palestinians. According to historian Philip Hitti, approximately 90,000 "Syrians" arrived in the United States between 1899 and 1919. An estimated 1,000 official entries per year came from the governorates of Damascus and Aleppo, which are governorates in modern-day Syria, in the period between 1900 and 1916. Early immigrants settled mainly in Eastern United States, in the cities of New York, Boston and Detroit and the Paterson, New Jersey area. In the 1920s, the majority of immigrants from Mount Lebanon began to refer themselves as "Lebanese" instead of "Syrians".
Syrians, like most immigrants to the United States, were motivated to immigrate to the United States to pursue the American Dream of economic success. Many Christian Syrians had immigrated to the United States seeking religious freedom and an escape from Ottoman hegemony. Thousands of immigrants returned to Syria after making money in the United States; these immigrants told tales which inspired further waves of immigrants. Many settlers also sent for their relatives.
Although the number of Syrian immigrants was not sizable, the Ottoman government set constraints on emigration in order to maintain its populace in Greater Syria. The United States Congress passed the Immigration Act of 1924, which greatly reduced Syrian immigration to the United States. However, the quotas were annulled by the Immigration Act of 1965, which opened the doors again to Syrian immigrants. 4,600 Syrians immigrated to the United States in the mid-1960s. Due to the Arab-Israeli and religious conflicts in Syria during this period, many Syrians immigrated to the United States seeking a democratic haven, where they could live in freedom without political suppression. An estimated 64,600 Syrians immigrated to the United States in the period between 1961 and 2000, of which ten percent have been admitted under the refugee acts.
According to the United States 2000 Census, there are 142,897 Americans of Syrian ancestry living in the United States. New York City has the biggest concentration of Syrian Americans in the United States. Other urban areas, including Boston, Dearborn, New Orleans, Toledo, Cedar Rapids, and Houston have large Syrian populations. Syrian Americans are also numerous in Southern California (i.e. the Los Angeles and San Diego areas) and Arizona, many are descendants of farm laborers invited with their farm skills to irrigate the deserts in the early 20th century.. Many recent Syrian immigrants are medical doctors who studied at Damascus and Aleppo Universities and pursued their residencies and fellowships in the United States.
The traditional clothing of the first Syrian immigrants in the United States, along with their occupation as peddlers, led to some xenophobia. Dr. A. J. McLaughlin, the United States health officer at Marine Hospital, described Syrians as "parasites in their peddling habits." However, Syrians reacted quickly to assimilate fully into their new culture. Immigrants Anglicized their names, adopted the English language and common Christian denominations. Syrians did not congregate in urban enclaves; many of the immigrants who had worked as peddlers were able to interact with Americans on a daily basis. This helped them to absorb and learn the language and customs of their new homeland. Additionally, military service during World War I and World War II helped accelerate assimilation. Assimilation of early Syrian immigrants was so successful that it has become difficult to recognize the ancestors of many families which have become completely Americanized.
Post 1965 Immigration was mostly Muslim, and unlike their Christian counterparts they faced a somewhat greater difficulty in assimilating because of their Islamic faith and the "back to the roots" trend that gripped America in the 1960s and 1970s. Generally, they are not overly desirous of giving up their identity as Arabs, which might be a result of the bloom in multiculturalism to respect their Islamic religious customs and traditions in the United States.
Christian Syrian Americans arrived in the United States in the late 19th century. Most Christian Syrian Americans are Greek Orthodox. There are also many Catholic Syrian Americans; most branches of Catholicism are of the Eastern rite, such as Maronite Catholics, Melkite Greek Catholics, Armenian Catholics, Syrian Catholics, and Assyrian Chaldean Catholics. There are only few minor differences between the different branches of Catholicism; such differences include the language/s church services are conducted, and the belief in papal infallibility. A few Christian Syrian Americans are Protestant. There are also members of the Assyrian Church of the East and Ancient Church of the East. The first Syrian American church was founded in Brooklyn, New York in 1895 by Saint Raphael of Brooklyn. There are currently hundreds of Eastern Orthodox churches and missions in the United States. Saint Nicholas and Saint George are popular saints for the Orthodox.
Muslim Syrian Americans arrived chiefly after 1965. The largest sect in Islam is the Sunni sect, forming 74% of the Muslim Syrian population. The second largest sect in Islam in Syria is the Alawite sect, a religious sect that originated in Shia Islam but separated from other Shiite Islam groups in the ninth and tenth centuries. Most, if not all, Alawi Syrians come from the rural areas of Latakia Governorate. Muslim Syrian Americans have often found it difficult practicing their religion in the United States; For example, some Muslims, who are required to pray five times a day as part of Muslim rite, argue that there aren't enough mosques in the United States.
Druzes form the third largest sect in Syria, which is a relatively small esoteric monotheistic religious sect. Early Syrian immigrants included Druze peddlers. Muslim Syrian Americans have often found it difficult practicing their religion in the United States;
Syrian Jews first immigrated to the United States around 1908 and settled mostly in New York. Initially they lived on the Lower East Side; later settlements were in Bensonhurst and Ocean Parkway in Flatbush, Brooklyn. The Syrian Jewish community estimates its population at around 50,000.
Early Syrian Americans were not involved politically. Business owners were usually Republican, meanwhile labor workers were usually Democrats. Second generation Syrian Americans were the first to be elected for political roles. In light of the Arab-Israeli conflict, many Syrian Americans tried to affect American foreign policy by joining Arab political groups in the United States. In the early 1970s, the National Association of Arab-Americans was formed to negate the stereotypes commonly associated with Arabs in American media. Syrian Americans were also part of the Arab American Institute, established in 1985, which supports and promotes Arab American candidates, or candidates commiserative with Arabs and Arab Americans, for office. Mitch Daniels, the current Governor of Indiana, is a descendant of Syrian immigrants with relatives in Homs.
The majority of the early Syrian immigrants arrived in the United States seeking better jobs; they usually engaged in basic commerce, especially peddling. Syrian American peddlers found their jobs comfortable since peddling required little training and mediocre vocabulary. Syrian American peddlers served as the distribution medium for the products of small manufacturers. Syrian peddlers traded mostly in dry goods, primarily clothing. Networks of Syrian traders and peddlers across the United States aided the distribution of Syrian settlements; by 1902, Syrians could be found working in Seattle, Washington. Most of these peddlers were successful, and, with time, and after raising enough capital, some became importers and wholesalers, recruiting newcomers and supplying them with merchandise. By 1908, there were 3,000 Syrian-owned businesses in the United States. By 1910, the first Syrian millionaires had emerged.
Syrian Americans gradually started to work in various métiers; many worked as physicians, lawyers, and engineers. Many Syrian Americans also worked in the bustling auto industry, bringing about large Syrian American gatherings in areas like Dearborn, Michigan. Later Syrian emigrants served in fields like banking, medicine, and computer science. Syrian Americans have a different occupational distribution than all Americans. According to the 2000 census, 42% of the Syrian Americans worked in management and professional occupations, compared with 34% of their counterparts in the total population; additionally, more Syrian Americans worked in sales than all American workers. However, Syrian Americans worked less in the other work domains like farming, transportation, construction, etc. than all American workers. According to the American Medical Association (AMA) and the Syrian American Medical Society (SAMS) which represents the American health care provoiders of Syrian descent www.sams-usa.net there are estimated 4000 Syrian physicians practicing in the United States representing 0.4% of the health workforce and 1.6% of international medical graduates. However the reported number of Syrian American phyicians does not include the second and third generation of Syrian descent, therefore it is estimated that there are 10,000 Syrian American physicians practice in the United States. Arabi M, Sankri-Tarbichi AG. The metrics of Syrian physicians' brain drain to the United States. Avicenna J Med [serial online] 2012 [cited 2012 Oct 27];2:1-2. Available from: http://www.avicennajmed.com/text.asp?2012/2/1/1/94802.
The median level of earnings for Syrian men and women is higher than the national earning median; employed Syrian men earned an average $46,058 per year, compared with $37,057 for all Americans and $41,687 for Arab Americans. Syrian American families also had a higher median income than all families and lower poverty rates than those of the general population.
Syrians value strong family ties. Unlike young Americans, young Syrians find leaving their family unnecessary to set up their independence; the reason being, is that Syrian society just like Southwest Asia, North Africa and the wider Eastern world, places great emphasis on the group rather than the individual. In the West the individual is key and the group is secondary. Respect and social status are important in Syrian societies. Men are respected for their financial success or their honesty and sincerity. Syrians are characterized by their magnanimity and graciousness, ethics which are integral to Syrian life." However, much of the Syrian traditions have diminished with time, mainly due to the fast pace of life in America which encourages individual independence.
Syrians consider eating an important aspect of social life. There are many Syrian dishes which have become popular in the United States. Unlike many Western foods, Syrian foods take more time to cook, are less expensive and usually more healthy. Pita bread (khubz), which is round flat bread, and hummus, a dip made of ground chickpeas, sesame tahini, lemon juice, and garlic, are two popular Syrian foods. Baba ghanoush, or eggplant spreads, is also a dish made by Syrians. Popular Syrian salads include tabbouleh and fattoush. The Syrian cuisine includes other dishes like stuffed zucchini (mahshe), dolma, kebab, kibbeh, kibbeh nayyeh, mujaddara, shawarma, and shanklish. Syrians often serve selections of appetizers, known as meze, before the main course. Za'atar, minced beef, and cheese manakish are popular hors d'œuvre. Syrians are also well known for their cheese. A popular Syrian drink is the arak beverage. One of the popular desserts made by Syrians is the baklava, which is made of filo pastry filled with chopped nuts and soaked in honey.
Syrian music includes several genres and styles of music ranging from Arab classical to Arabic pop music and from secular to sacred music. Syrian music is characterized by an emphasis on melody and rhythm, as opposed to harmony. There are some genres of Syrian music that are polyphonic, but typically, most Syrian and Arabic music is homophonic. Syrian music is also characterized by the predominance of vocal music. The prototypical Arabic music ensemble in Egypt and Syria is known as the takht, and relies on a number of musical instruments that represent a standardized tone system, and are played with generally standardized performance techniques, thus displaying similar details in construction and design. Such musical instruments include the oud, kanun, rabab, ney, violin, riq and tableh. The Jews of Syria sang pizmonim.
Modern Syrian music has incorporated instruments from the West, including the electric guitar, cello, double bass and oboe, and incorporated influences from jazz and other foreign musical styles.
Traditional clothing
Traditional dress is not very common with Syrian Americans, and even native Syrians; modern Western clothing is conventional in both Syria and the United States. Ethnic dance performers wear a shirwal, which are loose, baggy pants with an elastic waist. Some Muslim Syrian women wear a hijab, which is a headscarf worn by Muslim women to cover their hair. There are various styles of hijab.
Syrian Americans celebrate many religious holidays. Christian Syrian Americans celebrate most Christian holidays usually celebrated in the United States. They celebrate Christmas and Easter, but since most Syrians are Eastern Orthodox, they celebrate Easter on a different Sunday than most other Americans. Some Christians celebrate various Saints' days. Syrian American Jews celebrate the Jewish holidays, such as Rosh Hashanah, Yom Kippur, Sukkot, Purim, Passover and Shavuot. Few Syrians celebrate Syria's independence day, April 17. As American citizens, many Syrians celebrate American holidays like Memorial Day, Independence Day, and Thanksgiving Day.
Muslim Syrian Americans celebrate three main Muslim holidays: Ramadan, Eid ul-Fitr (Lesser Bairam), and Eid ul-Adha (Greater Bairam). Ramadan is the ninth month of the Islamic year, during which Muslims fast from dawn to sunset; Muslims resort to self-discipline to cleanse themselves spiritually. After Ramadan is over, Muslims celebrate Eid ul-Fitr, when Muslims break their fasting and revel exuberantly. Muslims also celebrate Eid ul-Adha (which means The Festival of Sacrifice) 70 days after at the end of the Islamic year, a holiday which is held along with the annual pilgrimage to Mecca, Hajj.
Dating and marriage
Syrian Americans prefer traditional relationships and disfavor casual dating. Muslims can only date after completing their marriage contact, kitabt al-kitab (Arabic: كتابة الكتاب, which means "writing the book"), a period that ranges from a few months to a year or more to get used to living with one another. After this time period, a wedding takes place and fulfills the marriage. Muslims tend to marry other Muslims only. Unable to find other suitable Muslim Syrian Americans, many Muslim Syrian American have married other Muslim Americans.
Syrian American marriages are usually very strong; this is reflected by the low divorce rates among Syrian Americans, which are below the average rates in the United States. Generally, Syrian American partners tend to have more children than average American partners; Syrian American partners also tend to have children at early stages of their marriages. According to the United States 2000 Census, almost 62% of Syrian American households were married-couple households.
Syrian Americans, including the earliest immigrants, have always placed a high premium on education. Like many other Americans, Syrian Americans view education as a necessity. Generally, Syrian and other Arab Americans are more highly educated than the average American. In the 2000 census it was reported that the proportion of Syrian Americans to achieve a bachelor's degree or higher is one and a half times that of the total American population. Many Syrian Americans now work as engineers, scientists, pharmacists, and physicians.
Syrians are mainly Arabic speakers. While some may speak the formal literary Arabic, many Syrians speak Syrian Arabic, a dialect which belongs to the Levantine Arabic family of dialects. There are also sub-dialects in Syrian Arabic; for example, people from Aleppo have a distinct and distinguishable accent, one that differs considerably from that of people from Homs or Al-Hasakah. Syrians can usually comprehend and understand the dialects of most Arabs, especially those who speak any form of Levantine Arabic.
Many old Syrian American families have lost their linguistic traditions because many parents do not teach their children Arabic. Newer immigrants, however, maintain their language traditions. The 2000 census shows that 79.9% of Syrian Americans speak English "very well". Throughout the United States, there are schools which offer Arabic language classes; there are also some Eastern Orthodox churches which hold Arabic services.
Notable people and contributions
Sometimes some confusion occurs between Greater Syria and the modern Syria when determining the place of origin of the earliest Syrian Americans. However, the following list comprises notable Americans who are originally people of modern Syrian heritage.
- Paula Abdul (born June 19, 1962), is a television personality, jewelry designer, multi-platinum Grammy-winning singer, and Emmy Award-winning choreographer. According to Abdul, she has sold over 53 million records to date. Abdul found renewed fame as a judge on the highly rated television series American Idol.
- F. Murray Abraham (born October 24, 1939), is an actor who won the Academy Award for Best Actor for his role as Antonio Salieri in the 1984 film Amadeus. His career after Amadeus inspired the name of the phenomenon dubbed "F. Murray Abraham syndrome", attributed to actors who, after winning an Oscar, have difficulty obtaining comparable success and recognition despite having recognizable talent.
- Moustapha Akkad (July 1, 1930 – November 11, 2005), was a film director and producer originally from Aleppo; Akkad is best known for producing the series of Halloween films, and for directing the Lion of the Desert and Mohammad, Messenger of God films.
- Malek Jandali (born December 25, 1972), is an award-winning composer and pianist originally from Homs; Jandali is best known for arranging the oldest music notation in the world of Ugarit in his album Echoes from Ugarit.
- Tige Andrews (March 19, 1920 – January 27, 2007), was an Emmy-nominated character actor who was best known for his role as "Captain Adam Greer" on the television series The Mod Squad.
- Paul Anka (born July 30, 1941), is a singer and song writer. Anka rose to fame after many successful 1950s songs, earning him the status of a teen idol. (Some sources, such as The Canadian Encyclopedia and Time magazine, suggest that Anka is of Syrian descent, while other sources, including Anka's official website, suggest that he is of Lebanese descent.)
- Michael Ansara (born April 15, 1922), is a stage, screen and voice actor.
- Rosemary Barkett (born 1939), was the first woman to serve on the Florida Supreme Court, and the first woman Chief Justice of that court. She currently serves as a federal judge on the United States Court of Appeals for the Eleventh Circuit.
- Mitch Daniels (born April 7, 1949), is the current Governor of the U.S. state of Indiana.
- Hala Gorani (born March 1, 1970), is a news anchor and correspondent for CNN International.
- Dan Hedaya (born July 24, 1940), is a prolific character actor notable for his many Italian American film roles.
- Robert M. Isaac (born January 27, 1928), is the former Republican Mayor of Colorado Springs, Colorado. Elected in 1979, he was the first elected Mayor of the history of Colorado Springs, serving through 1997.
- Alan Jabbour (born 1942), is a folklorist and a musician.
- Steve Jobs (February 24, 1955 – October 5, 2011), was the co-founder and former CEO of Apple, the largest Disney shareholder, and a member of Disney's Board of Directors. Jobs is considered a leading figure in both the computer and entertainment industries.
- Mohja Kahf (born 1967), poet and author
- Peter Lupus (born June 17, 1932), is a bodybuilder and actor, known primarily for "Mission: Impossible".
- Kurtis Mantronik (born September 4, 1965), is a hip-hop, electro funk, and dance music artist, DJ, remixer, and producer. Mantronik was the leader of the old-school band Mantronix.
- Jack Marshall (born 1936), is an author and poet.
- Louay M. Safi (born September 15, 1955), is a scholar and Human Rights activist, and a vocal critic of the Far Right. Author of numerous books and articles, Safi is active in the debate on nuclear race, social and political development, and Islam-West issues. He is the chairman of the Syrian American Congress.
- Jerry Seinfeld (born April 29, 1954), is a comedian, actor, and writer, best known for playing a semi-fictional version of himself in the long-running sitcom Seinfeld, which he co-created and executively produced.
- Teri Hatcher (born December 8, 1964), is an actress known for her television roles as Susan Mayer on the ABC comedy-drama series Desperate Housewives, and Lois Lane on Lois & Clark: The New Adventures of Superman. Hatcher is Syrian from her mother's side.
- Yasser Seirawan (born March 24, 1960), is a chess grandmaster and 4-time US-champion. Seirawan is the 69th best chess player in the world and the 2nd in the United States.
- Mona Simpson (born June 14, 1957), is a novelist and essayist; Simpson is also a sister of Steve Jobs.
- Kelly Slater (born February 11, 1972), is a successful professional surfer and an 11 time world champion.
- Wafa Sultan (born 1958), is a well-known secular activist and vocal critic of Islam. In 2006, Sultan was chosen by Time Magazine to be on the Time 100 list of the 100 most influential people in 2006.
- Vic Tayback (January 6, 1930 – May 25, 1990), was an actor who won two Golden Globe Awards for his role in the television series Alice.
- Fawwaz Ulaby, is the R. Jamieson and Betty Williams Professor of Electrical Engineering and Computer Science at the University of Michigan, and the former vice president for research.
- M.Safwan Badr, is a Professor of Internal Medicine and Chief of Pulmonary/Critical Care and Sleep Medicine at the Wayne State University, and the president elect of the American Academy of Sleep Medicine (AASM).
See also
- U.S. Census Bureau: Population by Selected Ancestry Group and Region: 2005[dead link]
- "Lebanese and Syrian Americans". Utica College. Retrieved 2007-05-06.
- "Immigrants, by Country of Birth: 1961 to 2005". United States Census. Archived from the original on 2007-04-03. Retrieved 2007-04-29.
- A Community of Many Worlds: Arab Americans in New York City, Museum of the City of New York/Syracuse University Press, 2002
- Naff (1993), p. 3
- Ernest McCarus (1992). The Development of Arab-American Identity (Hardcoover ed.). University of Michigan Press. pp. 24, 25. ISBN 0-472-10439-X.
- Hitti, Philip (2005) . The Syrians in America. Gorgias Press. ISBN 1-59333-176-2.
- "Syrian Americans". Everyculture.com. Retrieved 2007-05-21.
- Samovar & Porter (1994), p. 83
- Suleiman (1999), pp. 1-21
- McCarus, Ernest (1994). The Development of Arab-American Identity. University of Michigan Press. p. 26. ISBN 0-472-10439-X.
- Samovar & Porter (1994), p. 84
- "Religion in Syria - Christianity". About.com. Retrieved 2007-05-22.
- "St. Raphael of Brooklyn". Antiochian Orthodox Christian Archdiocese of North America. Retrieved 2007-05-22.
- "Orthodox Churches (Parishes)". The Antiochian Orthodox Church. Retrieved 2007-05-30.
- Williams, Raymond (1996). Christian Pluralism in the United States: The Indian Experience. Cambridge University Press. p. 11. ISBN 0-521-57016-6.
- "Syria". The World Factbook. 2007.
- "Religion in Syria - Alawi Islam". About.com. Retrieved 2007-05-22.
- Zenner, Walter (2000). A Global Community: The Jews from Aleppo, Syria. Wayne State University Press. p. 127. ISBN 0-8143-2791-5.
- Kornfeld, Alana B. Elias. "Syrian Jews mark 100 years in U.S.". Jewish News of Greater Phoenix. Retrieved 2007-05-20.
- Samovar & Porter (1994), p. 85
- The Arab Americans: a history by Gregory Orfalea, pg 224
- Naff, Alixa (1993). Becoming American: The Early Arab Immigrant Experience. Carbondale, Southern Illinois University Press. ISBN 978-0-585-10809-4.
- Levinson, David; Ember, Melvin (1997). American Immigrant Cultures: Builders of a Nation. Simon & Schuster Macmillan. p. 580. ISBN 0-02-897213-9.
- Giggie, John; Winston, Diane (2002). Faith in the Market: Religion and the Rise of Urban Commercial Culture. Rutgers University Press. p. 204. ISBN 0-8135-3099-7.
- "We the People of Arab Ancestry in the United States". United States Census. Retrieved 2007-05-20.
- Davis, Scott (2002). The Road from Damascus: A Journey Through Syria. Cune Press. ISBN 978-1-885942-84-5.
- Mahdi, Ali Akbar (2003). Teen Life in the Middle East. Greenwood Press. pp. 189–191. ISBN 0-313-31893-X.
- Toumar, Habib Hassan (2003). The Music of the Arabs. Amadeus. ISBN 1-57467-081-6.
- "Holidays". US Embassy in Damascus. Retrieved 2007-05-24.
- Eichner, Itamar (2006-11-17). "Israeli minister, American Idol". YNetNew.com. Retrieved 2006-05-20.
- Rocchio, Christopher (2007-03-14). "Paula Abdul dishes on Antonella Barba, 'Idol,' and her media portrayal". RealityTVWorld.com. Retrieved 2006-05-20.
- Zeidler, Sue. "Is winning an Oscar a curse or a blessing?". Film.com. Retrieved 2007-05-20.
- "Moustapaha Akkad". The Daily Telegraph (London). 2005-11-12. Retrieved 2007-05-20.
- "Malek Jandali". National Public Radio (Houston). 2010-10-08. Retrieved 2010-10-08.
- "'Mod Squad' actor Tige Andrews, 86, dies". USA Today. 2006-02-05. Retrieved 2006-05-20.
- "Paul Anka". Historyofrock.com. Retrieved 2007-05-20.
- "Anka, Paul". The Canadian Encyclopedia. Retrieved 2007-03-26.
- "Paul the Comforter". Time. 1961-11-03. Retrieved 2007-03-26.
- Leiby, Richard (2005-04-05). "Paul Anka's Deutsch Treat". The Washington Post. Retrieved 2007-03-26.
- "FAQ". PaulAnka.com. Retrieved 2007-03-26.
- "Indiana Governor Mitch Daniels". Official Indiana state site. Retrieved 2006-05-20.
- Abbas, Faisal (2006-01-17). "Q&A with CNN’s Hala Gorani". Asharq Al-Awsat. Retrieved 2006-05-20.
- "Dan Hedaya". Internet Movie Database. Retrieved 2007-05-20.
- "Steve Jobs' Magic Kingdom". BusinessWeek. 2006-01-06. Retrieved 2006-09-20.
- Burrows, Peter (2004-11-04). "Steve Jobs: He Thinks Different". BusinessWeek. Retrieved 2006-09-20.
- "Jerry Seinfeld". Vividseats.com. Retrieved 2006-05-20.
- "Yasser Seirawan". Chessgames.com. Retrieved 2006-05-20.
- Abinader, Elmaz. "Children of al-Mahjar: Arab American Literature Spans a Century". USINFO. Archived from the original on 2008-01-01. Retrieved 2007-05-20.
- Campbell, Duncan (2004-06-18). "Steve Jobs". The Guardian (London). Retrieved 2006-05-20.
- "Surf for Peace". Surfer Magazine. Retrieved 2009-06-17.
- Nomani, Asra (2006-04-30). "Wafa Sultan". Time. Retrieved 2006-05-20.
- "The TIME 100, 2006". Time. Retrieved 2006-05-20.
- Maslin, Janet. "Vic Tayback". The New York Times. Retrieved 2007-05-20.
- Abu-Laban, Baha; Suleiman, Michael (1989). Arab Americans: Continuity and Change. AAUG monograph series. Belmont, Massachusetts: Association of Arab-American University Graduates. ISBN 978-0-937694-82-4.
- Kayal, Philip; Kayal, Joseph (1975). The Syrian Lebanese in America: A Study in Religion and Assimilation. The Immigrant Heritage of America series. [New York], Twayne Publishers. ISBN 978-0-8057-8412-1.
- Naff, Alixa (1985). Becoming American: The Early Arab Immigrant Experience. Carbondale, Southern Illinois University Press. ISBN 978-0-585-10809-4.
- Saliba, Najib (1992). Emigration from Syria and the Syrian-Lebanese Community of Worcester, MA. Ligonier, Pennsylvania: Antakya Press. ISBN 0-9624190-1-X.
- Saliba Jerry Seinfeld Ticketsinventory.com Retrieved 2006-05-20. Missing or empty
- Samovar, L. A.; Porter, R. E. (1994). Intercultural Communication: A Reader. Thomson Wadsworth. ISBN 0-534-64440-6.
- Suleiman, Michael (1999). Arabs in America: Building a New Future. NetLibrary. ISBN 0-585-36553-9.
- Younis, Adele L. (1989). The Coming of the Arabic-Speaking People to the United States. Staten Island, New York: Center for Migration Studies. ISBN 978-0-934733-40-3. OCLC 31516579.
|
United Nations Special Commission
United Nations Special Commission (UNSCOM) was an inspection regime created by the United Nations to ensure Iraq's compliance with policies concerning Iraqi production and use of weapons of mass destruction after the Gulf War. Between 1991 and 1997 its director was Rolf Ekéus; from 1997 to 1999 its director was Richard Butler.
United Nations Special Commission (UNSCOM) was an inspection regime created with the adoption of United Nations Security Council Resolution 687 in April 1991 to oversee Iraq's compliance with the destruction of Iraqi chemical, biological, and missile weapons facilities and to cooperate with the International Atomic Energy Agency’s efforts to eliminate nuclear weapon facilities all in the aftermath of the Gulf War. The UNSCOM inspection regime was packaged with several other UN Security Council requirements, namely, that Iraq’s ruling regime formally recognize Kuwait as an independent state and pay out war reparations for the destruction inflicted in the Gulf War, including the firing of Kuwaiti oil supplies and destruction of public infrastructure. Until the UN Security Council saw that Iraq’s weapons programs had been aborted and Iraqi leaders had allowed monitoring systems to be installed, the UN’s aforementioned sanctions would continue to be imposed on Iraq.
The commission found corroborating evidence that Rihab Rashid Taha, an Iraqi microbiologist educated in England, had produced biological weapons for Iraq in the 1980s. The destruction of proscribed weapons and the associated facilities was carried out mainly by Iraq, under constant supervision by UNSCOM.
Inspectors withdrew in 1998, and disbanded the following year amid allegations that the United States had used the commission's resources to spy on the Iraqi military. Weapons inspector Scott Ritter later stated that Operation Rockingham had cherry-picked evidence found by the United Nations Special Commission; evidence, he says, that was later used as part of the casus belli for the 2003 invasion of Iraq.
The successor of the United Nations Special Commission was the United Nations Monitoring, Verification and Inspection Commission.
The United Nations Special Commission (UNSCOM) was headed by Rolf Ekéus and later Richard Butler. During several visits to Iraq by the United Nations Special Committee (UNSCOM), set up after the 1990 invasion of Kuwait to inspect Iraqi weapons facilities, weapons inspectors were told by Rihab Rashid Taha that the al-Hakam germ warfare center was a chicken-feed plant. "There were a few things that were peculiar about this animal-feed production plant," Charles Duelfer, UNSCOM's deputy executive chairman, later told reporters, "beginning with the extensive air defenses surrounding it."
The powers given to UNSCOM inspectors in Iraq were: “unrestricted freedom of movement without advance notice in Iraq”; the “right to unimpeded access to any site or facility for the purpose of the on-site inspection...whether such site or facility be above or below ground”; “the right to request, receive, examine, and copy any record data, or information...relevant to” UNSCOM’s activities; and the “right to take and analyze samples of any kind as well as to remove and export samples for off-site analysis.
Acceptance of the intrusion of the UNSCOM’s inspectors on the part of the Iraqi regime was slow coming. But with the threat of punitive military action looming from the international community, and particularly the U.S., Saddam Husain begrudgingly allowed UNSCOM’s inspectors into the country to begin their work.
Between 1991 and 1995, UN inspectors uncovered a massive program to develop biological and nuclear weapons. A large amount of equipment was confiscated and destroyed. Iraq by and large refused to cooperate with UNSCOM and its inspections as mandated by UN SC Res. 687 until June 1992, ten months after deadline, at which time the Iraqi government submitted “full, final and complete reports” on all of its weapons of mass destruction programs. These reports, however, were found to be incomplete and deficient, and at the same time UN inspectors were subjected to harassment and threats on the part of the Iraqi regime.
United Nations Security Council Resolution 699 was also passed in 1991, declaring that Iraq was responsible for all funding of UNSCOM’s inspections in Iraq.
In 1995, UNSCOM's principal weapons inspector Dr. Rod Barton showed Taha documents obtained by UNSCOM from Israel that showed the Iraqi government had just purchased 10 tons of growth media from a British company called Oxoid. Growth media is a mixture of sugar, proteins and minerals that allows microscopic life to grow. It is used in hospitals, where swabs from patients are placed in dishes containing growth media for diagnostic purposes. Iraq's hospital consumption of growth media was just 200 kg a year; yet in 1988, Iraq imported 39 tons of it.
Shown this evidence by UNSCOM, Taha admitted to inspectors that she had grown 19,000 litres of botulism toxin; 8,000 litres of anthrax; 2,000 litres of aflatoxins, which can cause liver cancer; clostridium perfringens, a bacterium that can cause gas gangrene; and ricin, a castor bean derivative which can kill by inhibiting protein synthesis. She also admitted conducting research into cholera, salmonella, foot and mouth disease, and camel pox, a disease that uses the same growth techniques as smallpox, but which is safer for researchers to work with. It was because of the discovery of Taha's work with camel pox that the US and British intelligence services feared Saddam Hussein may have been planning to weaponize the smallpox virus. Iraq had a smallpox outbreak in the 1970s and UNSCOM scientists believe the government would have retained contaminated material.
UNSCOM learned that, in August 1990, after Iraq's invasion of Kuwait, Taha's team was ordered to set up a program to weaponize the biological agents. By January 1991, a team of 100 scientists and support staff had filled 157 bombs and 16 missile warheads with botulin toxin, and 50 bombs and five missile warheads with anthrax. In an interview with the BBC, Taha denied the Iraqi government had weaponized the bacteria. "We never intended to use it," she told journalist Jane Corbin of the BBC's Panorama program. "We never wanted to cause harm or damage to anybody." UNSCOM found the munitions dumped in a river near al-Hakam. UNSCOM also discovered that Taha's team had conducted inhalation experiments on donkeys from England and on beagles from Germany. The inspectors seized photographs showing beagles having convulsions inside sealed containers.
The al-Hakam germ warfare center, headed by the British-educated Iraqi biologist Dr. Rihab Rashid Taha, was blown up by UNSCOM in 1996. According to a 1999 report from the U.S. Defense Intelligence Agency, the normally mild-mannered Taha exploded into violent rages whenever UNSCOM questioned her about al-Hakam, shouting, screaming and, on one occasion, smashing a chair, while insisting that al-Hakam was a chicken-feed plant.
Iraq charged that the commission was a cover for US espionage and refused UNSCOM access to certain sites, such as Baath Party headquarters. Although Ekéus has said that he resisted attempts at such espionage, many allegations have since been made against the agency commission under Butler, charges which Butler has denied. Within the UN establishment in Iraq, UNSCOM was not without its critics, with the UN's humanitarian staff informally calling the inspectors 'UN-Scum'. In return, the UN's humanitarian staff were called "bunny-huggers".
Also in 1996, the Iraqi ruling regime agreed to the terms of United Security Council Resolution 986, an oil-for-supplies agreement in which Iraq was allowed to sell $2 billion worth of oil every six months as a ways to purchase supplies for its increasingly impoverished and malnourished population. This agreement also allowed the UN to oversee the use and management of oil revenues, and to see that some of the funds went to pay war reparations and for the work of UNSCOM in Iraq during this period. The distribution of supplies purchased with oil revenues was also to be supervised by UN inspectors to ensure fair and equal distribution throughout the Iraqi population.
1998 Airstrikes
Security Council Meeting On the evening of 15 December 1998 the Security Council convened to consider two letters from weapons inspectors. The IAEA report by Mohamed El Baradei stated that Iraq "has provided the necessary level of cooperation to enable... [our] activities to be completed efficiently and effectively". The UNSCOM report, authored by Richard Butler, deplored the restrictions, lack of disclosure, and concealment. While conceding that "[i]n statistical terms, the majority of the inspections of facilities and sites under the ongoing monitoring system were carried out with Iraq's cooperation," his letter listed a number of instances where unspecificed "undeclared dual-capable items" had been discovered, and where inspections had been held up so that buildings could be cleared of sensitive material.
Since Operation Desert Fox had already begun at the time of the meeting (just hours after the inspectors had been evacuated), the Security Council debated about who was to blame for the military action, rather than whether they should authorize it. The Iraqi representative said:
|“||I speak to you now while rockets and bombs are falling on the cities and the villages of Iraq... At a time when the Security Council... was discussing [the] reports..., and before the Council reached any conclusion on this subject, the United States and Britain launched their attack against Iraq. The two Powers requested a suspension of the informal meeting of the Security Council and their pretext for aggression was that one of the two reports -- the UNSCOM report -- emphasized the lack of full cooperation by Iraq with UNSCOM... Time and again we have warned against the partiality and lack of objectivity of the United Nations Special Commission... The UNSCOM Executive Chairman singled out in his report yesterday five incidents out of a total of 300 inspection operations... The exaggerated uproar about Iraqi weapons of mass destruction is nothing but a great lie.||”|
The Russian ambassador added:
|“||We believe that although there are certain problems..., the current crisis was created artificially... On the night of 15 December this year, [Butler] presented a report that gave a distorted picture of the real state of affairs and concluded that there was a lack of full cooperation on the part of Iraq. That conclusion was not borne out by the facts. Without any consultations with the Security Council, Richard Butler then evacuated the entire Special Commission staff from Iraq. At the same time, there was an absolutely unacceptable leak of the report to the communications media, which received the text before the members of the Security Council themselves... It is symbolic that precisely at the time when Richard Butler... was attempting to defend the conclusions reached in his report, we were informed about the strike against Iraq, and the justification for that unilateral act was precisely the report which had been presented by the Executive Chairman of the Special Commission.||”|
The view of the Council was split, with several countries placing the responsibility on Iraq. The United States declared that "Iraq's policy of unremitting defiance and non-compliance necessitated the resort to military force". The United Kingdom stated that the objectives of the action were "to degrade Iraq's capability to build and use weapons of mass destruction, and to diminish the military threat Iraq poses to its neighbours. The targets chosen, therefore, are targets connected with his military capability, his weapons of mass destruction and his ability to threaten his neighbours."
1999: End of UNSCOM
In December 1999, the UN Security Council passed Resolution 1284, replacing UNSCOM with the United Nations Monitoring, Verification and Inspection Commission. Four countries — among them Russia, France and China — abstained from voting on Res. 1284, which led the Iraqi regime to reject the resolution because they saw the resolution as a way for the UN to claim Iraq as a “protectorate.”
UNSCOM’s intention of identifying and eliminating Iraqi weapons programs resulted in numerous successes, illustrating the “value of a system approach to biological arms verification,” as former UNSCOM Historian Stephen Black has written. But the overall effect of the UN sanctions on Iraqi in the 1990s proved devastating to an already crumbling country. Malnutrition rates among Iraqis increased and infant mortality rates soared, exacting a heavy toll on the people of Iraq not part of the ruling regime’s patrimonial “shadow state.”
Allegations of CIA infiltration of UNSCOM
Evidence that UNSCOM had been used by US intelligence to penetrate Iraqi security and track President Saddam Hussein's movements emerged in January 1999. An investigation by the Washington Post claimed that CIA engineers, working as UN technicians, installed equipment to spy on Iraqi sites without Butler's knowledge, and that this explained the unidentified "burst transmissions" that had been noted by the inspectors.
Former UN weapons inspector Scott Ritter later accused some UNSCOM personnel of spying, and also alleged that the purpose of the spying was to target Saddam in the bombing. Butler, on the other hand, denied allegations that foreign intelligence agencies "piggybacked" UNSCOM and questioned the factual accuracy of several of Ritter's statements.
On 31 August 1998, Ritter said: "Iraq still has proscribed weapons capability. There needs to be a careful distinction here. Iraq today is challenging the special commission to come up with a weapon and say where is the weapon in Iraq, and yet part of their efforts to conceal their capabilities, I believe, have been to disassemble weapons into various components and to hide these components throughout Iraq. I think the danger right now is that without effective inspections, without effective monitoring, Iraq can in a very short period of time measure the months, reconstitute chemical biological weapons, long-range ballistic missiles to deliver these weapons, and even certain aspects of their nuclear weaponization program."
Almost a year later, in June 1999, Ritter responded to an interviewer saying: "When you ask the question, 'Does Iraq possess militarily viable biological or chemical weapons?' the answer is no! It is a resounding NO. Can Iraq produce today chemical weapons on a meaningful scale? No! Can Iraq produce biological weapons on a meaningful scale? No! Ballistic missiles? No! It is 'no' across the board. So from a qualitative standpoint, Iraq has been disarmed. Iraq today possesses no meaningful weapons of mass destruction capability.
Butler resigned from UNSCOM on 30 June 1999.
See also
- In Shifting Sands: The Truth About Unscom and the Disarming of Iraq - documentary film directed by Scott Ritter
- Iraq disarmament crisis and Iraq disarmament timeline 1990–2003
- UNSCOM personnel: Rolf Ekéus, Richard Butler (diplomat), Charles A. Duelfer, Scott Ritter, Corinne Heraud, Alexander Coker
- United Nations Security Council Resolution 687 S-RES-687(1991) page 3 on 3 April 1991 (retrieved 2008-04-10)
- Zilinskas, Raymond A., “UNSCOM and the UNSCOM Experience in Iraq,” Politics and the Life Sciences, Vol. 14, No. 2 (Aug., 1995), 230-231
- Tripp, Charles, “A History of Iraq,” (New York: Cambridge University Press, 2008), 250
- What Happened to Saddam's WMD? Arms Control Today September, 2003
- Chief U.N. weapons inspector rejects spying allegations CNN January 6, 1999
- US silence on new Iraq spying allegations BBC News January 7, 1999
- Black, Stephen, “UNSCOM and the Iraqi Biological Weapons Program: Implications for Arms Control,” Politics and the Life Sciences,” Vol. 18, No. 1 (Mar., 1999), pp. 62-63
- Tripp, 250-251
- Zilinskas, 230
- "The Inspections Maze". Christian Science Monitor. 2002. Retrieved 2006-04-28.[dead link]
- "Baghdad prevents inspections at Baath party headquarters". Arabic News.com. 12/11/1998. Retrieved 2006-04-28.
- Wright, Susan (2002). Biological Warfare and Disarmament. Lanham: Rowman & Littlefield. p. 272. ISBN 0-7425-2469-8.
- Varadarajan, Siddharth (26 February 1998). "'UNSCUM' versus 'Bunny-huggers' in Iraq". The Times of India.
- Tripp, 252
- United Nations Security Council PV S-PV-3955 on 1998-12-16 (retrieved 2007-04-04)
- "LETTER DATED 15 DECEMBER 1998 FROM THE SECRETARY-GENERAL ADDRESSED TO THE PRESIDENT OF THE SECURITY COUNCIL". Un.org. Retrieved 2011-06-19.
- United Nations Security Council S-1998-1172 on 1998-12-15 (retrieved 2007-04-04)
- Julian Borger (17 December 1998). "Missile blitz on Iraq". The Guardian.
- United Nations Security Council PV S-PV-3955 page 2 on 1998-12-16 (retrieved 2007-04-04)
- United Nations Security Council PV S-PV-3955 page 3 on 1998-12-16 (retrieved 2007-04-04)
- United Nations Security Council PV S-PV-3955 page 8 on 1998-12-16 (retrieved 2007-04-04)
- United Nations Security Council PV S-PV-3955 page 5 on 1998-12-16 (retrieved 2007-04-04)
- Tripp, 269
- Black, 68
- Graham-Brown, Sarah, “Sanctioning Iraq: A Failed Policy, Middle East Report, No. 215 (Summer, 2000), pp. 8-10
- Halliday, Denis J., “The Impact of the UN Sanctions on the People of Iraq,” Journal of Palestine Studies, Vol. 28, No. 2 (Winter, 1999), pp. 29-33
- Mark Tran (7 January 1999). "UN 'spied on Iraq'". The Guardian.
- Barton Gellman (2 March 1999). "U.S. Spied On Iraq Via U.N". Washington Post.
- Julian Borger (3 March 1999). "UN 'kept in dark' about US spying in Iraq". The Guardian.
- "Unscom 'infiltrated by spies'". BBC News. March 23, 1999. Retrieved 2006-04-28.
- "The Lessons and Legacy of UNSCOM, an Interview with Ambassador Richard Butler". Arms Control Today. June 1999.
- Arons, Nicholas (June 24, 1999). "Interview with Scot Ritter". Federation of American Scientists, June 24, 1999. Retrieved 2008-09-06.
|
The names chiseled onto city tenement building entrances are often pretty puzzling.
The typical tenement is more than 100 years old. With the original builders long-gone, who can explain where some of these names come from, and why they were chosen?
Like Novelty Court, on Driggs Avenue in Williamsburg. Actually, a little research turned up an explanation: this used to be the site of the Novelty Theater, according to Cinema Treasures, which disappeared from city directories by the 1920s.
A. Segal’s (Secal’s?) Apartments are also in Williamsburg. But who was A. Segal, and why did he put his first initial and last name on his building?
Blennerhasset sounds like Manhasset, a town in Long Island. I’ve never seen the name anywhere else but on this tenement near Columbia University.
Who was Frances, and how would she feel about the terrible shape the building named for her is in, on Lexington Avenue in East Harlem?
|
The Best Time to Start Learning Anything During the Year
Home/Lifestyle/Education/The Best Time to Start Learning Anything During the Year
The Best Time to Start Learning Anything During the Year
Never stop learning; because life never stops teaching – Anonymous
All seasons have something to offer – Jeannette Walls
Was there a time in your school days that you faced challenge studying and understanding new lessons of the curriculum of any subject?
Science bets, that you must have had.
Since social media platforms have gained prominence, knowledge is equally shared by one and all. In every platform where article links are shared, definitely you will find quotes as to how seasons can affect learning moods and it is true. Let us imagine, you have done Masters in English Literature and wants to study digital marketing while working as a writing intern. Do you feel that you should have a plan where seasons play one of the major factors?
Well, you have to.
It has been proved by medical science that the time from winter to spring is the best to learn any new knowledge as you find an upsurge in moods and enhancement in energy levels.
Learning any new skills calls for the understanding of concepts and memory. Surveys have indicated that in the duration from winter to spring, students learn new skills and chapters easily. In fact, the more of sunlight, uplift of moods, energy, and well-being.
The component assisting you in learning new knowledge is called as dopamine. Its number increases on more exposure to sunlight and it enhances confidence, motivation, pleasure, and memory.
Since you know your learning abilities, why don’t you make the best use of seasons?
In spring, another factor also rules the roost. Your curiosity levels are triggered, and your learning gets easy since you can cross over borders and can do work independently.
However, too much of sunlight can lead to reduced sleeping hours and unless you have a proper work-to-do schedule, you can face a reduction in concentration, memory, and metabolism. In such cases, never wither away from the time schedule, and a sleep of six to eight hours on any day is vital for memorizing new concepts.
There is another simple way to learn new skills and concepts. Before you shut-eye, remember the concepts and skills you have acquired during the day. This will keep you not only focused but also store valuable data in the brain. Do not force your brain to retrieve more on the first day. Within a week, you can condense the concepts of the day within ten minutes.
Now, Do You Know Why Schools Announce Leave For The Summer Holidays?
When the sun is too hot, the brains switch off. If you have to learn a new way of digital marketing, for example, Amazon Web Services at Learning Technologies then do it in a way so that it is easy to you. If you are a creative guy, learn it the simple way of means of drawing images and charts. If you are a normal guy, ensure that you retain your passion for learning and try to revise the lessons every day or seek the assistance of a friend for a group study.
The Belgian study, Proceedings of the National Academy of Sciences journal, states that the resources are used by the brain differently for performing the same function according to the season.
In winter, you might feel a little laid back in learning. The easy way to understand, your body needs to use energy to withstand the cold temperature and unless you consume proper food, you may feel the lack of motivation.
Forget the seasons, even in a normal day; you could have understood the major productivity hours of the day. The morning hours are the most productive, in the afternoon after the lunch, there may be the lull in productivity. When the body recovers, after 4 pm, once again the scrambling of finishing the target before winding up for the day – These patterns may differ according to your body.
What is stronger? Mother Nature or the human mind?
The Human Mind.
Case Study One
You have performed well in your company and in the process of getting promoted as the International Manager. However, one of the new clients is a millionaire from the UAE and he insists on communicating only in Arabic.
You are given three months duration by the company to learn Arabic from experienced Arabic tutors. The time luckily is spring and so you find the learning easy. You pass the first part of the exam with flying colors and although, not proficient, can understand the words said by the man from the other part of the world.
The time is full winter and because of your tight schedule, you cannot attend the classroom based session. So you opt for taking classes on the internet. Your family stands by you; even your team members, seniors and you pass the certification.
Does your success in the exam mean that instead of winter, there was summer or spring? No, they came, will come and go. The fact is how focused you are in attaining your study goals regardless of the circumstances.
Learning new skills is not an impossible task. However, you need to have a little knowledge about gaining the skill in a smart way. The brain needs to be given information in the way as you understand its ability by which it will retain for a long time.
Case Study Two
You are a team leader and are about to get promoted as Operations Manager which was your dream goal. But there is one hitch: you have to pass the first part of Digital Certification program for application of the post.
Before learning a new task, schedule a plan on how to master it easily. Ask your friends, seniors or search on the internet for information. If needed, ask for some help from a family member, or a friend. Group discussion always benefits learning. Test your knowledge at least once a weekend. You may be a multi-tasker, but first, narrow down your strengths and focus while learning a new skill. After going via the basics, you can become your normal self.
If you are on your own, you might receive a few brickbats, do not feel afraid or fall into depression.
By |July 1st, 2017|Education|0 Comments
About the Author:
Leave A Comment
|
#include "TransferFunctionEditor.h"
#include <kvs/DebugNew>
#include <kvs/MouseEvent>
#include <kvs/Math>
#include <kvs/HSVColor>
#include <kvs/RGBColor>
#include <kvs/Date>
#include <kvs/Time>
#include <kvs/glut/GLUT>
#include <kvs/IgnoreUnusedVariable>
#include <kvs/Background>
#include <SupportGLUT/Viewer/KVSKey.h>
#include <SupportGLUT/Viewer/KVSMouseButton.h>
namespace
{
class ResetButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
ResetButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->reset();
}
};
class ApplyButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
ApplyButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->apply();
}
};
class SaveButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
SaveButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->save();
}
};
class UndoButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
UndoButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->undo();
}
};
class RedoButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
RedoButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->redo();
}
};
} // end of namespace
namespace kvs
{
namespace glut
{
TransferFunctionEditor::TransferFunctionEditor( kvs::ScreenBase* parent ):
m_screen( parent ),
m_color_palette( NULL ),
m_color_map_palette( NULL ),
m_opacity_map_palette( NULL ),
m_histogram( NULL ),
m_reset_button( NULL ),
m_undo_button( NULL ),
m_redo_button( NULL ),
m_save_button( NULL ),
m_apply_button( NULL ),
m_min_value( 0.0f ),
m_max_value( 0.0f )
{
const std::string title = "Transfer Function Editor";
const int x = ( parent != 0 ) ? parent->x() + parent->width() + 5 : 0;
const int y = ( parent != 0 ) ? parent->y() : 0;
const int width = 350;
const int height = 512;
const int margin = 10;
const kvs::RGBColor base_color( 50, 50, 50 );
kvs::Font caption_font;
caption_font.setStyleToBold();
caption_font.setColor( kvs::RGBColor( 180, 180, 180 ) );
SuperClass::setBackgroundColor( base_color );
SuperClass::setTitle( title );
SuperClass::setPosition( x, y );
SuperClass::setSize( width, height );
SuperClass::create();
const size_t resolution = 256;
m_initial_transfer_function.create( resolution );
m_undo_stack.push_front( m_initial_transfer_function );
m_stack_event = new StackEvent( this );
SuperClass::addEvent( m_stack_event );
m_max_stack_size = 10;
m_color_palette = new kvs::ColorPalette( this );
m_color_palette->setCaption( "Color palette" );
m_color_palette->setFont( caption_font );
m_color_palette->setY( -7 );
m_color_palette->setHeight( 170 );
m_color_palette->show();
m_color_map_palette = new kvs::ColorMapPalette( this );
m_color_map_palette->setCaption( "Color map" );
m_color_map_palette->setFont( caption_font );
m_color_map_palette->setColorMap( m_initial_transfer_function.colorMap() );
m_color_map_palette->setX( m_color_palette->x0() );
m_color_map_palette->setY( m_color_palette->y1() - m_color_palette->margin() );
m_color_map_palette->attachColorPalette( m_color_palette );
m_color_map_palette->show();
m_opacity_map_palette = new kvs::OpacityMapPalette( this );
m_opacity_map_palette->setCaption( "Opacity map" );
m_opacity_map_palette->setFont( caption_font );
m_opacity_map_palette->setOpacityMap( m_initial_transfer_function.opacityMap() );
m_opacity_map_palette->setX( m_color_map_palette->x0() );
m_opacity_map_palette->setY( m_color_map_palette->y1() - m_color_map_palette->margin() );
m_opacity_map_palette->show();
m_histogram = new kvs::HistogramBar( this );
m_histogram->setCaption( "Histogram" );
m_histogram->setFont( caption_font );
m_histogram->setX( m_opacity_map_palette->x0() );
m_histogram->setY( m_opacity_map_palette->y1() - m_opacity_map_palette->margin() );
m_histogram->setHeight( 100 );
m_histogram->setGraphColor( kvs::RGBAColor( 100, 100, 100, 1.0f ) );
m_histogram->show();
const size_t button_margin = 5;
const size_t button_width = ( width - 2 * margin - button_margin ) / 2;
m_reset_button = new ::ResetButton( this );
m_reset_button->setCaption( "Reset" );
m_reset_button->setFont( caption_font );
m_reset_button->setX( m_histogram->x0() + m_histogram->margin() );
m_reset_button->setY( m_histogram->y1() + 10 );
m_reset_button->setWidth( button_width );
m_reset_button->setButtonColor( base_color * 1.5 );
m_reset_button->show();
m_undo_button = new ::UndoButton( this );
m_undo_button->setCaption( "Undo" );
m_undo_button->setFont( caption_font );
m_undo_button->setX( m_reset_button->x1() + button_margin );
m_undo_button->setY( m_reset_button->y() );
m_undo_button->setWidth( ( button_width - button_margin ) / 2 );
m_undo_button->setButtonColor( base_color * 1.5 );
m_undo_button->show();
m_redo_button = new ::RedoButton( this );
m_redo_button->setCaption( "Redo" );
m_redo_button->setFont( caption_font );
m_redo_button->setX( m_undo_button->x1() + button_margin );
m_redo_button->setY( m_undo_button->y() );
m_redo_button->setWidth( ( button_width - button_margin ) / 2 );
m_redo_button->setButtonColor( base_color * 1.5 );
m_redo_button->show();
m_save_button = new ::SaveButton( this );
m_save_button->setCaption( "Save" );
m_save_button->setFont( caption_font );
m_save_button->setX( m_reset_button->x0() );
m_save_button->setY( m_reset_button->y1() + button_margin );
m_save_button->setWidth( button_width );
m_save_button->setButtonColor( base_color * 1.5 );
m_save_button->show();
m_apply_button = new ::ApplyButton( this );
m_apply_button->setCaption( "Apply" );
m_apply_button->setFont( caption_font );
m_apply_button->setX( m_save_button->x1() + button_margin );
m_apply_button->setY( m_save_button->y0() );
m_apply_button->setWidth( ( width -margin ) / 2 - m_opacity_map_palette->margin() );
m_apply_button->setButtonColor( base_color * 1.5 );
m_apply_button->show();
}
TransferFunctionEditor::~TransferFunctionEditor()
{
if ( m_stack_event ) { delete m_stack_event; m_stack_event = NULL; }
if ( m_color_palette ) { delete m_color_palette; m_color_palette = NULL; }
if ( m_color_map_palette ) { delete m_color_map_palette; m_color_map_palette = NULL; }
if ( m_opacity_map_palette ) { delete m_opacity_map_palette; m_opacity_map_palette = NULL; }
if ( m_histogram ) { delete m_histogram; m_histogram = NULL; }
if ( m_reset_button ) { delete m_reset_button; m_reset_button = NULL; }
if ( m_undo_button ) { delete m_undo_button; m_undo_button = NULL; }
if ( m_redo_button ) { delete m_redo_button; m_redo_button = NULL; }
if ( m_apply_button ) { delete m_apply_button; m_apply_button = NULL; }
if ( m_save_button ) { delete m_save_button; m_save_button = NULL; }
}
const kvs::TransferFunction TransferFunctionEditor::transferFunction() const
{
kvs::TransferFunction transfer_function( this->colorMap(), this->opacityMap() );
transfer_function.setRange( m_min_value, m_max_value );
return transfer_function;
}
void TransferFunctionEditor::setTransferFunction( const kvs::TransferFunction& transfer_function )
{
const kvs::ColorMap& cmap = transfer_function.colorMap();
const kvs::OpacityMap& omap = transfer_function.opacityMap();
// Deep copy for the initial transfer function.
kvs::ColorMap::Table color_map_table( cmap.table().data(), cmap.table().size() );
kvs::OpacityMap::Table opacity_map_table( omap.table().data(), omap.table().size() );
kvs::ColorMap color_map( color_map_table );
kvs::OpacityMap opacity_map( opacity_map_table );
m_initial_transfer_function.setColorMap( color_map );
m_initial_transfer_function.setOpacityMap( opacity_map );
if ( transfer_function.hasRange() )
{
m_min_value = transfer_function.colorMap().minValue();
m_max_value = transfer_function.colorMap().maxValue();
m_initial_transfer_function.setRange( m_min_value, m_max_value );
}
m_color_map_palette->setColorMap( color_map );
m_opacity_map_palette->setOpacityMap( opacity_map );
m_undo_stack.clear();
m_undo_stack.push_front( m_initial_transfer_function );
}
void TransferFunctionEditor::setVolumeObject( const kvs::VolumeObjectBase* object )
{
if ( !m_initial_transfer_function.hasRange() )
{
m_min_value = object->minValue();
m_max_value = object->maxValue();
}
m_histogram->create( object );
}
void TransferFunctionEditor::reset()
{
m_color_map_palette->setColorMap( m_initial_transfer_function.colorMap() );
m_opacity_map_palette->setOpacityMap( m_initial_transfer_function.opacityMap() );
m_color_map_palette->update();
m_opacity_map_palette->update();
this->redraw();
}
void TransferFunctionEditor::save()
{
const std::string date = kvs::Date().toString("");
const std::string time = kvs::Time().toString("");
const std::string filename = "tfunc_" + date + "_" + time + ".kvsml";
kvs::TransferFunction transfer_function = this->transferFunction();
transfer_function.write( filename );
}
void TransferFunctionEditor::undo()
{
if ( m_undo_stack.size() > 1 )
{
if ( m_redo_stack.size() > m_max_stack_size ) m_redo_stack.pop_back();
m_redo_stack.push_front( m_undo_stack.front() );
m_undo_stack.pop_front();
kvs::TransferFunction& transfer_function = m_undo_stack.front();
m_color_map_palette->setColorMap( transfer_function.colorMap() );
m_opacity_map_palette->setOpacityMap( transfer_function.opacityMap() );
m_color_map_palette->update();
m_opacity_map_palette->update();
this->redraw();
}
}
void TransferFunctionEditor::redo()
{
if ( m_redo_stack.size() > 1 )
{
kvs::TransferFunction& transfer_function = m_redo_stack.front();
m_color_map_palette->setColorMap( transfer_function.colorMap() );
m_opacity_map_palette->setOpacityMap( transfer_function.opacityMap() );
if ( m_undo_stack.size() > m_max_stack_size ) m_undo_stack.pop_back();
m_undo_stack.push_front( m_redo_stack.front() );
m_redo_stack.pop_front();
m_color_map_palette->update();
m_opacity_map_palette->update();
this->redraw();
}
}
TransferFunctionEditor::StackEvent::StackEvent(
kvs::glut::TransferFunctionEditor* editor ):
m_editor( editor )
{
}
void TransferFunctionEditor::StackEvent::update( kvs::MouseEvent* event )
{
if ( m_editor->opacityMapPalette()->palette().isActive() ||
m_editor->colorMapPalette()->palette().isActive() )
{
if ( m_editor->m_undo_stack.size() > m_editor->m_max_stack_size )
{
m_editor->m_undo_stack.pop_back();
}
m_editor->m_undo_stack.push_front( m_editor->transferFunction() );
m_editor->redraw();
}
}
} // end of namespace glut
} // end of namespace kvs
|
Rodrigues, A.S.L., Andelman, S.J., Bakarr, M.I., Boitani, L., Brooks, T.M., Cowling, R.M., Fishpool, L.D.C., da Fonseca, G.A.B., Gaston, K.J., Hoffmann, M., Long, J.S., Marquet, P.A., Pilgrim, J.D., Pressey, R.L., Schipper, J., Sechrest, W., Stuart, S.N., Underhill, L.G., Waller, R.W., Watts, M.E.J. and Yan, X. (2004) Effectiveness of the global protected area network in representing species diversity. Nature, 428 (6983). pp. 640-643. ISSN 0028-0836Full text available as:
The Fifth World Parks Congress in Durban, South Africa, announced in September 2003 that the global network of protected areas now covers 11.5% of the planet's land surface. This surpasses the 10% target proposed a decade earlier, at the Caracas Congress, for 9 out of 14 major terrestrial biomes. Such uniform targets based on percentage of area have become deeply embedded into national and international conservation planning. Although politically expedient, the scientific basis and conservation value of these targets have been questioned. In practice, however, little is known of how to set appropriate targets, or of the extent to which the current global protected area network fulfils its goal of protecting biodiversity. Here, we combine five global data sets on the distribution of species and protected areas to provide the first global gap analysis assessing the effectiveness of protected areas in representing species diversity. We show that the global network is far from complete, and demonstrate the inadequacy of uniform—that is, 'one size fits all'—conservation targets.
|Copyright, Publisher and Additional Information:||© 2004 Nature Publishing Group|
|Academic Units:||The University of Sheffield > Faculty of Science (Sheffield) > School of Biological Sciences (Sheffield) > Department of Animal and Plant Sciences (Sheffield)|
|Depositing User:||Repository Officer|
|Date Deposited:||12 Jan 2005|
|Last Modified:||08 Feb 2013 16:47|
Actions (login required)
|
TGC Graphic Design Web Design Animation Multimedia Courses Training Institute
Taking a FCP Course
Taking_a_FCP_Course-01Starting a career in Video Editing and cinematography involves taking up a video editing course. Video Editing courses would provide the opportunity to understand video making terminologies, hands on learning of non –linear editing through computer editing software. There are several computer software used for video editing and mixing among them are Adobe Premiere pro, Avid Composer and Final cut pro. Final cut Pro also known as FCP is a Video Editing software owned by apple that is being extensively used in the film industry for video editing. It has enabled top professional video editors in the world get Oscar awards for using them for their editing job, an example is the editing of Girl with the Dragon tattoo released in 2011. The editing job was done by Angus Wall and Kirk Baxter. This has contributed to the increased use and demand for FCP in the film industry and the resultant demand for FCP courses in the education Industry. FCP course fees range from INR 10.000 to INR 35000 in Delhi depending on the level of expertise required and the FCP training Institute .
FCP course fees are however higher than fees for other video editing software training like Adobe premiere pro for instance. This is due to the high cost of fcp software and all other apple accessories associated with the FCP Software. Most FCP courses deal with the latest version of the final cut pro software known as the FCPX, released in 2011 with a more advanced and speedy interface.
FCP courses last between 1- 3 months and FCP course fees are usually demanded in full at the start of the course or a lump sum with subsequent monthly installment payments until the course is done.
What does a FCP course offer?
1. A FCP course would teach an intending video editor the basics and rules of video editing and how to get them done in final cut pro interface using the Magnetic Timeline for an exceptionally fast, fluid new way to edit. It would also help an intending video editor manage his files by creating Smart Collections to organize media based on metadata and keywords. Depending on the FCP course fees, advanced metadata techniques for organizing projects may be taught or omitted.
2. A FCP course would teach the student how to combine multiple elements into a single compound clip, finetuning clips in the timeline with the precision editor and how to compare alternate shots from a collection of clips using auditions as well as working with compound clips
3. A FCP course would help the student understand the process and methods of applying video and audio effects, applying transitions and re timing clips. It would also teach the student the art of color correction using FCP both for entire clips and target specific areas using shape and color masks
4. A FCP course would also help the student learn how to create custom effects and transitions and apply a cinematic glow to clips, it would also teach the student how to export and import video files from other video editing software.
TGC India is a Multimedia Institute with affordable FCP course fees.
0 Responses on Taking a FCP Course"
Leave a Message
Call us at: 1800 3070 2228
Request a Call Back
|
#include <iostream>
#include <iomanip>
#include <chrono>
#include <memory>
#include <cstdint>
#include <random>
#include <vector>
#include "libalgebra.h" // pospopcnt
// force flagstats to define all implementations
#define STORM_HAVE_AVX2
#define STORM_HAVE_AVX512
#define STORM_HAVE_SSE42
#include "../libflagstats.h" // flagstats
using Clock = std::chrono::high_resolution_clock;
template <typename UNIT = std::chrono::microseconds>
Clock::time_point::rep elapsed(const Clock::time_point& t1, const Clock::time_point& t2) {
return std::chrono::duration_cast<UNIT>(t2 - t1).count();
}
class Application {
private:
const size_t size;
std::unique_ptr<uint16_t[]> flags;
std::ostream& out;
public:
Application(size_t size)
: size(size)
, flags(new uint16_t[size])
, out(std::cout) {
initialize_input();
}
void run() {
#if defined(STORM_HAVE_CPUID)
#if defined(__cplusplus)
/* C++11 thread-safe singleton */
static const int cpuid = STORM_get_cpuid();
#else
static int cpuid_ = -1;
int cpuid = cpuid_;
if (cpuid == -1) {
cpuid = STORM_get_cpuid();
#if defined(_MSC_VER)
_InterlockedCompareExchange(&cpuid_, cpuid, -1);
#else
__sync_val_compare_and_swap(&cpuid_, -1, cpuid);
#endif
}
#endif
#endif
uint32_t scalar[32];
run("scalar", FLAGSTAT_scalar, scalar);
#if defined(STORM_HAVE_SSE42)
if (cpuid & STORM_CPUID_runtime_bit_SSE42) {
uint32_t sse4[32];
const uint64_t time_sse4 = run("SSE4", FLAGSTAT_sse4, sse4);
uint32_t sse4_improved[32];
run("SSE4 improved", FLAGSTAT_sse4_improved, sse4_improved, sse4, time_sse4);
}
#endif
#if defined(STORM_HAVE_AVX2)
if (cpuid & STORM_CPUID_runtime_bit_AVX2) {
uint32_t avx2[32];
const uint64_t time_avx2 = run("AVX2", FLAGSTAT_avx2, avx2);
uint32_t avx2_improved[32];
run("AVX2 improved", FLAGSTAT_avx2_improved, avx2_improved, avx2, time_avx2);
}
#endif
#if defined(STORM_HAVE_AVX512)
if (cpuid & STORM_CPUID_runtime_bit_AVX512BW) {
uint32_t avx512[32];
const uint64_t time_avx512 = run("AVX512", FLAGSTAT_avx512, avx512, scalar);
uint32_t avx512_improved[32];
const uint64_t time_avx512_improved = run("AVX512 improved", FLAGSTAT_avx512_improved, avx512_improved, scalar, time_avx512);
uint32_t avx512_improved2[32];
const uint64_t time_avx512_improved2 = run("AVX512 improved 2", FLAGSTAT_avx512_improved2, avx512_improved2, scalar, time_avx512_improved);
uint32_t avx512_improved3[32];
const uint64_t time_avx512_improved3 = run("AVX512 improved 3", FLAGSTAT_avx512_improved3, avx512_improved3, scalar);
uint32_t avx512_improved4[32];
const uint64_t time_avx512_improved4 = run("AVX512 improved 4", FLAGSTAT_avx512_improved4, avx512_improved4, scalar);
}
#endif
}
private:
void initialize_input() {
std::random_device rd;
std::mt19937 eng(rd());
eng.seed(0); // make the results repeatable
std::uniform_int_distribution<uint16_t> flag(0, 4096 - 1);
for (size_t i=0; i < size; i++)
flags[i] = flag(eng);
}
template <typename FUN>
uint64_t run(const char* name,
FUN function,
uint32_t* stats,
uint32_t* stats_ref = nullptr,
uint64_t time_ref = 0)
{
out << "Running function " << name << ": ";
out << std::flush;
for (int i=0; i < 32; i++) stats[i] = 0;
const auto t1 = Clock::now();
function(flags.get(), size, stats);
const auto t2 = Clock::now();
const uint16_t time_us = elapsed(t1, t2);
out << "time " << time_us << " us";
if (time_ref != 0)
out << " (speedup: " << double(time_ref)/time_us << ")";
out << '\n';
dump_stats(stats);
if (stats_ref != nullptr) {
const bool has_error = compare(stats_ref, stats);
}
return time_us;
}
void dump_array(uint32_t* arr, int size) {
out << '[';
for (int i=0; i < size; i++) {
if (i != 0)
out << ", ";
out << std::setw(6);
out << arr[i];
}
out << ']';
}
void dump_stats(uint32_t* stats) {
out << "statistics are: ";
out << '\n';
for (int i=0; i < 32; i += 8) {
out << " ";
dump_array(stats + i, 8);
out << '\n';
}
}
bool compare(uint32_t* reference, uint32_t* stats) {
bool has_error = false;
// test only the counters actually written by FLAGSTAT_scalar_update
static const std::vector<int> tested_counters{
FLAGSTAT_FQCFAIL_OFF,
FLAGSTAT_FSECONDARY_OFF,
FLAGSTAT_FSUPPLEMENTARY_OFF,
FLAGSTAT_BIT12_OFF,
FLAGSTAT_FREAD1_OFF,
FLAGSTAT_FREAD2_OFF,
FLAGSTAT_BIT13_OFF,
FLAGSTAT_BIT14_OFF,
FLAGSTAT_FUNMAP_OFF,
FLAGSTAT_FDUP_OFF,
FLAGSTAT_FQCFAIL_OFF + 16,
FLAGSTAT_FSECONDARY_OFF + 16,
FLAGSTAT_FSUPPLEMENTARY_OFF + 16,
FLAGSTAT_BIT12_OFF + 16,
FLAGSTAT_FREAD1_OFF + 16,
FLAGSTAT_FREAD2_OFF + 16,
FLAGSTAT_BIT13_OFF + 16,
FLAGSTAT_BIT14_OFF + 16,
FLAGSTAT_FUNMAP_OFF + 16,
FLAGSTAT_FDUP_OFF + 16,
};
for (const int index: tested_counters) {
const uint32_t expected = reference[index];
const uint32_t actual = stats[index];
if (expected != actual) {
out << "Difference at " << index << ": expected = " << expected << ", actual = " << actual << '\n';
has_error = true;
}
}
return has_error;
}
};
int main(int argc, char* argv[]) {
const size_t default_size = 1024 * 100;
size_t size = default_size;
if (argc > 1)
size = atoi(argv[1]);
Application app(size);
app.run();
}
|
#pragma once
template <typename Type>
tensor<Type>& tensor<Type>::transpose()
{
auto const copy = *this;
for (int64_t n = 0; n < shape_.first * shape_.second; ++n)
{
auto i = n / shape_.first;
auto j = n % shape_.first;
data_[n] = copy.data_[j * shape_.second + i];
}
std::swap(shape_.first, shape_.second);
return *this;
}
template <typename Type>
tensor<Type> transpose(tensor<Type> tensor)
{
return tensor.transpose();
}
template <typename Type>
tensor<Type>& tensor<Type>::dot(tensor<Type> const& other)
{
if (shape_.second != other.shape_.first)
throw std::runtime_error("Invalid shapes - " + to_string(shape_) + " and " + to_string(other.shape_) + "!");
auto const n = shape_.first;
auto const m = shape_.second;
auto const p = other.shape_.second;
auto const other_transposed = std::move(simple_blas::transpose(other));
tensor<Type> result;
result.shape_ = { n, p };
result.data_ = std::make_unique<Type[]>(n * p);
#pragma omp parallel for
for (int64_t i = 0; i < n; ++i)
{
for (int64_t j = 0; j < p; ++j)
{
Type dot = 0;
for (int64_t k = 0; k < m; ++k)
dot += data_[i * m + k] * other_transposed.data_[j * m + k];
result.data_[i * p + j] = dot;
}
}
return (*this = std::move(result));
}
template <typename Type>
tensor<Type> dot(tensor<Type> lhs, tensor<Type> const& rhs)
{
auto result = lhs.dot(rhs);
return result;
}
template <typename Type>
template<uint_fast8_t Axis>
tensor<Type> tensor<Type>::sum() const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[j] += data_[i * shape_.second + j];
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[i] += data_[i * shape_.second + j];
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
Type tensor<Type>::sum() const
{
Type sum = 0;
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
sum += data_[i * shape_.second + j];
return sum;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<Type> tensor<Type>::max() const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result.data_[j] = data_[j];
for (int64_t i = 0; i < shape_.first; ++i)
result.data_[j] = std::max(data_[i * shape_.second + j], result.data_[j]);
}
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result.data_[i] = data_[i];
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[i] = std::max(data_[i * shape_.second + j], result.data_[i]);
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
Type tensor<Type>::max() const
{
Type max = data_[0];
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
max = std::max(data_[i * shape_.second + j], max);
return max;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<Type> tensor<Type>::min() const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result.data_[j] = data_[j];
for (int64_t i = 0; i < shape_.first; ++i)
result.data_[j] = std::min(data_[i * shape_.second + j], result.data_[j]);
}
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result.data_[i] = data_[i];
for (int64_t j = 0; j < shape_.second; ++j)
result.data_[i] = std::min(data_[i * shape_.second + j], result.data_[i]);
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
Type tensor<Type>::min() const
{
Type min = data_[0];
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
min = std::min(data_[i * shape_.second + j], min);
return min;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<size_t> tensor<Type>::argmax() const
{
if constexpr (Axis == 0)
{
tensor<size_t> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result[{0, j}] = 0;
for (int64_t i = 0; i < shape_.first; ++i)
{
auto const current = result[{0, j}];
result[{0, j}] = data_[i * shape_.second + j] > data_[current * shape_.second + j] ? i : current;
}
}
return result;
}
if constexpr (Axis == 1)
{
tensor<size_t> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result[{i, 0}] = 0;
for (int64_t j = 0; j < shape_.second; ++j)
{
auto const current = result[{i, 0}];
result[{i, 0}] = data_[i * shape_.second + j] > data_[i * shape_.second + current] ? j : current;
}
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
tensor_index tensor<Type>::argmax() const
{
tensor_index max = { 0,0 };
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
if ((data_[i * shape_.second + j] > data_[max.first * shape_.second + max.second])) max = tensor_index{ i, j };
return max;
}
template <typename Type>
template <uint_fast8_t Axis>
tensor<size_t> tensor<Type>::argmin() const
{
if constexpr (Axis == 0)
{
tensor<size_t> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result[{0, j}] = 0;
for (int64_t i = 0; i < shape_.first; ++i)
{
auto const current = result[{0, j}];
result[{0, j}] = data_[i * shape_.second + j] < data_[current * shape_.second + j] ? i : current;
}
}
return result;
}
if constexpr (Axis == 1)
{
tensor<size_t> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result[{i, 0}] = data_[i];
for (int64_t j = 0; j < shape_.second; ++j)
{
auto const current = result[{i, 0}];
result[{i, 0}] = data_[i * shape_.second + j] < data_[i * shape_.second + current] ? j : current;
}
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
tensor_index tensor<Type>::argmin() const
{
tensor_index min = { 0,0 };
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
if ((data_[i * shape_.second + j] < data_[min.first * shape_.second + min.second])) min = tensor_index{ i, j };
return min;
}
template <typename Type>
template <typename Reduction, uint_fast8_t Axis>
tensor<Type> tensor<Type>::reduce(Reduction reduction) const
{
if constexpr (Axis == 0)
{
tensor<Type> result({ 1, shape_.second });
for (int64_t j = 0; j < shape_.second; ++j)
{
result.data_[j] = data_[j];
for (int64_t i = 1; i < shape_.first; ++i)
result.data_[j] = reduction(data_[i * shape_.second + j], result.data_[j]);
}
return result;
}
if constexpr (Axis == 1)
{
tensor<Type> result({ shape_.first, 1 });
for (int64_t i = 0; i < shape_.first; ++i)
{
result.data_[i] = data_[i * shape_.second];
for (int64_t j = 1; j < shape_.second; ++j)
result.data_[i] = reduction(data_[i * shape_.second + j], result.data_[i]);
}
return result;
}
throw std::runtime_error("Invalid axis template parameter!");
}
template <typename Type>
template <typename Reduction>
Type tensor<Type>::reduce(Reduction reduction) const
{
Type r = data_[0];
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = i == 0 ? 1 : 0; j < shape_.second; ++j)
r = reduction(data_[i * shape_.second + j], r);
return r;
}
template <typename Type>
tensor<Type>& tensor<Type>::log()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::log(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> log(tensor<Type> tensor)
{
return tensor.log();
}
template <typename Type>
tensor<Type>& tensor<Type>::exp()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::exp(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> exp(tensor<Type> tensor)
{
return tensor.exp();
}
template <typename Type>
tensor<Type>& tensor<Type>::abs()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::fabs(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> abs(tensor<Type> tensor)
{
return tensor.abs();
}
template <typename Type>
tensor<Type>& tensor<Type>::sqrt()
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::sqrt(static_cast<double>(data_[i * shape_.second + j]));
return *this;
}
template <typename Type>
tensor<Type> sqrt(tensor<Type> tensor)
{
return tensor.sqrt();
}
template <typename Type>
tensor<Type>& tensor<Type>::maximum(Type max)
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::max(data_[i * shape_.second + j], max);
return *this;
}
template <typename Type>
tensor<Type> maximum(tensor<Type> tensor, Type max)
{
return tensor.maximum(max);
}
template <typename Type>
tensor<Type>& tensor<Type>::minimum(Type max)
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = std::min(data_[i * shape_.second + j], max);
return *this;
}
template <typename Type>
tensor<Type> minimum(tensor<Type> tensor, Type max)
{
return tensor.minimum(max);
}
template <typename Type>
template <typename Function>
tensor<Type> tensor<Type>::apply(Function func)
{
#pragma omp parallel for
for (int64_t i = 0; i < shape_.first; ++i)
for (int64_t j = 0; j < shape_.second; ++j)
data_[i * shape_.second + j] = func(data_[i * shape_.second + j]);
return *this;
}
template <typename Type, typename Function>
tensor<Type> apply(tensor<Type> tensor, Function func)
{
return tensor.apply(func);
}
template<typename Type, typename Function>
tensor<Type> produce(tensor<Type> lhs, tensor<Type> const& rhs, Function function)
{
if (lhs.shape().first == rhs.shape().first && rhs.shape().second == 1)
{
#pragma omp parallel for
for (int64_t i = 0; i < lhs.shape().first; ++i)
{
auto const elem = rhs[{i, 0}];
for (int64_t j = 0; j < lhs.shape().second; ++j)
lhs[{ i, j }] = Type(function(lhs[{ i, j }], elem));
}
}
else if (lhs.shape().second == rhs.shape().second && rhs.shape().first == 1)
{
#pragma omp parallel for
for (int64_t j = 0; j < lhs.shape().second; ++j)
{
auto const elem = rhs[{0, j}];
for (int64_t i = 0; i < lhs.shape().first; ++i)
lhs[{ i, j }] = Type(function(lhs[{ i, j }], elem));
}
}
else if (lhs.shape().first == rhs.shape().first && lhs.shape().second == rhs.shape().second)
{
#pragma omp parallel for
for (int64_t i = 0; i < lhs.shape().first; ++i)
for (int64_t j = 0; j < lhs.shape().second; ++j)
lhs[{ i, j }] = Type(function(lhs[{ i, j }], rhs[{i, j}]));
}
else
throw std::runtime_error("Invalid shapes - " + to_string(lhs.shape()) + " and " + to_string(rhs.shape()) + "!");
return lhs;
}
|
- Year Published: 1866
- Language: English
- Country of Origin: Russia
- Source: Dostoyevsky, F. (1866). Crime and Punishment. Moscow, Russia: The Russian Messenger.
- Flesch–Kincaid Level: 7.2
- Word Count: 7,803
Dostoyevsky, F. (1866). Part 3, Chapter 5. Crime and Punishment (Lit2Go Edition). Retrieved May 18, 2013, from
Dostoyevsky, Fyodor. "Part 3, Chapter 5." Crime and Punishment. Lit2Go Edition. 1866. Web. <>. May 18, 2013.
Fyodor Dostoyevsky, "Part 3, Chapter 5," Crime and Punishment, Lit2Go Edition, (1866), accessed May 18, 2013,.
Raskolnikov was already entering the room. He came in looking as though he had the utmost difficulty not to burst out laughing again. Behind him Razumihin strode in gawky and awkward, shamefaced and red as a peony, with an utterly crestfallen and ferocious expression. His face and whole figure really were ridiculous at that moment and amply justified Raskolnikov’s laughter. Raskolnikov, not waiting for an introduction, bowed to Porfiry Petrovitch, who stood in the middle of the room looking inquiringly at them. He held out his hand and shook hands, still apparently making desperate efforts to subdue his mirth and utter a few words to introduce himself. But he had no sooner succeeded in assuming a serious air and muttering something when he suddenly glanced again as though accidentally at Razumihin, and could no longer control himself: his stifled laughter broke out the more irresistibly the more he tried to restrain it. The extraordinary ferocity with which Razumihin received this “spontaneous” mirth gave the whole scene the appearance of most genuine fun and naturalness. Razumihin strengthened this impression as though on purpose.
“Fool! You fiend,” he roared, waving his arm which at once struck a little round table with an empty tea-glass on it. Everything was sent flying and crashing.
“But why break chairs, gentlemen? You know it’s a loss to the Crown,” Porfiry Petrovitch quoted gaily.
Raskolnikov was still laughing, with his hand in Porfiry Petrovitch’s, but anxious not to overdo it, awaited the right moment to put a natural end to it. Razumihin, completely put to confusion by upsetting the table and smashing the glass, gazed gloomily at the fragments, cursed and turned sharply to the window where he stood looking out with his back to the company with a fiercely scowling countenance, seeing nothing. Porfiry Petrovitch laughed and was ready to go on laughing, but obviously looked for explanations. Zametov had been sitting in the corner, but he rose at the visitors’ entrance and was standing in expectation with a smile on his lips, though he looked with surprise and even it seemed incredulity at the whole scene and at Raskolnikov with a certain embarrassment. Zametov’s unexpected presence struck Raskolnikov unpleasantly.
“I’ve got to think of that,” he thought. “Excuse me, please,” he began, affecting extreme embarrassment. “Raskolnikov.”
“Not at all, very pleasant to see you… and how pleasantly you’ve come in…. Why, won’t he even say good-morning?” Porfiry Petrovitch nodded at Razumihin.
“Upon my honour I don’t know why he is in such a rage with me. I only told him as we came along that he was like Romeo… and proved it. And that was all, I think!”
“Pig!” ejaculated Razumihin, without turning round.
“There must have been very grave grounds for it, if he is so furious at the word,” Porfiry laughed.
“Oh, you sharp lawyer!... Damn you all!” snapped Razumihin, and suddenly bursting out laughing himself, he went up to Porfiry with a more cheerful face as though nothing had happened. “That’ll do! We are all fools. To come to business. This is my friend Rodion Romanovitch Raskolnikov; in the first place he has heard of you and wants to make your acquaintance, and secondly, he has a little matter of business with you. Bah! Zametov, what brought you here? Have you met before? Have you known each other long?”
“What does this mean?” thought Raskolnikov uneasily.
Zametov seemed taken aback, but not very much so.
“Why, it was at your rooms we met yesterday,” he said easily.
“Then I have been spared the trouble. All last week he was begging me to introduce him to you. Porfiry and you have sniffed each other out without me. Where is your tobacco?”
Porfiry Petrovitch was wearing a dressing-gown, very clean linen, and trodden-down slippers. He was a man of about five and thirty, short, stout even to corpulence, and clean shaven. He wore his hair cut short and had a large round head, particularly prominent at the back. His soft, round, rather snub-nosed face was of a sickly yellowish colour, but had a vigorous and rather ironical expression. It would have been good-natured except for a look in the eyes, which shone with a watery, mawkish light under almost white, blinking eyelashes. The expression of those eyes was strangely out of keeping with his somewhat womanish figure, and gave it something far more serious than could be guessed at first sight.
As soon as Porfiry Petrovitch heard that his visitor had a little matter of business with him, he begged him to sit down on the sofa and sat down himself on the other end, waiting for him to explain his business, with that careful and over-serious attention which is at once oppressive and embarrassing, especially to a stranger, and especially if what you are discussing is in your opinion of far too little importance for such exceptional solemnity. But in brief and coherent phrases Raskolnikov explained his business clearly and exactly, and was so well satisfied with himself that he even succeeded in taking a good look at Porfiry. Porfiry Petrovitch did not once take his eyes off him. Razumihin, sitting opposite at the same table, listened warmly and impatiently, looking from one to the other every moment with rather excessive interest.
“Fool,” Raskolnikov swore to himself.
“You have to give information to the police,” Porfiry replied, with a most businesslike air, “that having learnt of this incident, that is of the murder, you beg to inform the lawyer in charge of the case that such and such things belong to you, and that you desire to redeem them… or… but they will write to you.”
“That’s just the point, that at the present moment,” Raskolnikov tried his utmost to feign embarrassment, “I am not quite in funds… and even this trifling sum is beyond me… I only wanted, you see, for the present to declare that the things are mine, and that when I have money….”
“That’s no matter,” answered Porfiry Petrovitch, receiving his explanation of his pecuniary position coldly, “but you can, if you prefer, write straight to me, to say, that having been informed of the matter, and claiming such and such as your property, you beg…”
“On an ordinary sheet of paper?” Raskolnikov interrupted eagerly, again interested in the financial side of the question.
“Oh, the most ordinary,” and suddenly Porfiry Petrovitch looked with obvious irony at him, screwing up his eyes and, as it were, winking at him. But perhaps it was Raskolnikov’s fancy, for it all lasted but a moment. There was certainly something of the sort, Raskolnikov could have sworn he winked at him, goodness knows why.
“He knows,” flashed through his mind like lightning.
“Forgive my troubling you about such trifles,” he went on, a little disconcerted, “the things are only worth five roubles, but I prize them particularly for the sake of those from whom they came to me, and I must confess that I was alarmed when I heard…”
“That’s why you were so much struck when I mentioned to Zossimov that Porfiry was inquiring for everyone who had pledges!” Razumihin put in with obvious intention.
This was really unbearable. Raskolnikov could not help glancing at him with a flash of vindictive anger in his black eyes, but immediately recollected himself.
“You seem to be jeering at me, brother?” he said to him, with a well-feigned irritability. “I dare say I do seem to you absurdly anxious about such trash; but you mustn’t think me selfish or grasping for that, and these two things may be anything but trash in my eyes. I told you just now that the silver watch, though it’s not worth a cent, is the only thing left us of my father’s. You may laugh at me, but my mother is here,” he turned suddenly to Porfiry, “and if she knew,” he turned again hurriedly to Razumihin, carefully making his voice tremble, “that the watch was lost, she would be in despair! You know what women are!”
“Not a bit of it! I didn’t mean that at all! Quite the contrary!” shouted Razumihin distressed.
“Was it right? Was it natural? Did I overdo it?” Raskolnikov asked himself in a tremor. “Why did I say that about women?”
“Oh, your mother is with you?” Porfiry Petrovitch inquired.
“When did she come?”
Porfiry paused as though reflecting.
“Your things would not in any case be lost,” he went on calmly and coldly. “I have been expecting you here for some time.”
And as though that was a matter of no importance, he carefully offered the ash-tray to Razumihin, who was ruthlessly scattering cigarette ash over the carpet. Raskolnikov shuddered, but Porfiry did not seem to be looking at him, and was still concerned with Razumihin’s cigarette.
“What? Expecting him? Why, did you know that he had pledges there?” cried Razumihin.
Porfiry Petrovitch addressed himself to Raskolnikov.
“Your things, the ring and the watch, were wrapped up together, and on the paper your name was legibly written in pencil, together with the date on which you left them with her…”
“How observant you are!” Raskolnikov smiled awkwardly, doing his very utmost to look him straight in the face, but he failed, and suddenly added:
“I say that because I suppose there were a great many pledges… that it must be difficult to remember them all…. But you remember them all so clearly, and… and…”
“Stupid! Feeble!” he thought. “Why did I add that?”
“But we know all who had pledges, and you are the only one who hasn’t come forward,” Porfiry answered with hardly perceptible irony.
“I haven’t been quite well.”
“I heard that too. I heard, indeed, that you were in great distress about something. You look pale still.”
“I am not pale at all…. No, I am quite well,” Raskolnikov snapped out rudely and angrily, completely changing his tone. His anger was mounting, he could not repress it. “And in my anger I shall betray myself,” flashed through his mind again. “Why are they torturing me?”
“Not quite well!” Razumihin caught him up. “What next! He was unconscious and delirious all yesterday. Would you believe, Porfiry, as soon as our backs were turned, he dressed, though he could hardly stand, and gave us the slip and went off on a spree somewhere till midnight, delirious all the time! Would you believe it! Extraordinary!”
“Really delirious? You don’t say so!” Porfiry shook his head in a womanish way.
“Nonsense! Don’t you believe it! But you don’t believe it anyway,” Raskolnikov let slip in his anger. But Porfiry Petrovitch did not seem to catch those strange words.
“But how could you have gone out if you hadn’t been delirious?” Razumihin got hot suddenly. “What did you go out for? What was the object of it? And why on the sly? Were you in your senses when you did it? Now that all danger is over I can speak plainly.”
“I was awfully sick of them yesterday.” Raskolnikov addressed Porfiry suddenly with a smile of insolent defiance, “I ran away from them to take lodgings where they wouldn’t find me, and took a lot of money with me. Mr. Zametov there saw it. I say, Mr. Zametov, was I sensible or delirious yesterday; settle our dispute.”
He could have strangled Zametov at that moment, so hateful were his expression and his silence to him.
“In my opinion you talked sensibly and even artfully, but you were extremely irritable,” Zametov pronounced dryly.
“And Nikodim Fomitch was telling me to-day,” put in Porfiry Petrovitch, “that he met you very late last night in the lodging of a man who had been run over.”
“And there,” said Razumihin, “weren’t you mad then? You gave your last penny to the widow for the funeral. If you wanted to help, give fifteen or twenty even, but keep three roubles for yourself at least, but he flung away all the twenty-five at once!”
“Maybe I found a treasure somewhere and you know nothing of it? So that’s why I was liberal yesterday…. Mr. Zametov knows I’ve found a treasure! Excuse us, please, for disturbing you for half an hour with such trivialities,” he said, turning to Porfiry Petrovitch, with trembling lips. “We are boring you, aren’t we?”
“Oh no, quite the contrary, quite the contrary! If only you knew how you interest me! It’s interesting to look on and listen… and I am really glad you have come forward at last.”
“But you might give us some tea! My throat’s dry,” cried Razumihin.
“Capital idea! Perhaps we will all keep you company. Wouldn’t you like… something more essential before tea?”
“Get along with you!”
Porfiry Petrovitch went out to order tea.
Raskolnikov’s thoughts were in a whirl. He was in terrible exasperation.
“The worst of it is they don’t disguise it; they don’t care to stand on ceremony! And how if you didn’t know me at all, did you come to talk to Nikodim Fomitch about me? So they don’t care to hide that they are tracking me like a pack of dogs. They simply spit in my face.” He was shaking with rage. “Come, strike me openly, don’t play with me like a cat with a mouse. It’s hardly civil, Porfiry Petrovitch, but perhaps I won’t allow it! I shall get up and throw the whole truth in your ugly faces, and you’ll see how I despise you.” He could hardly breathe. “And what if it’s only my fancy? What if I am mistaken, and through inexperience I get angry and don’t keep up my nasty part? Perhaps it’s all unintentional. All their phrases are the usual ones, but there is something about them…. It all might be said, but there is something. Why did he say bluntly, ‘With her’? Why did Zametov add that I spoke artfully? Why do they speak in that tone? Yes, the tone…. Razumihin is sitting here, why does he see nothing? That innocent blockhead never does see anything! Feverish again! Did Porfiry wink at me just now? Of course it’s nonsense! What could he wink for? Are they trying to upset my nerves or are they teasing me? Either it’s ill fancy or they know! Even Zametov is rude…. Is Zametov rude? Zametov has changed his mind. I foresaw he would change his mind! He is at home here, while it’s my first visit. Porfiry does not consider him a visitor; sits with his back to him. They’re as thick as thieves, no doubt, over me! Not a doubt they were talking about me before we came. Do they know about the flat? If only they’d make haste! When I said that I ran away to take a flat he let it pass…. I put that in cleverly about a flat, it may be of use afterwards…. Delirious, indeed… ha-ha-ha! He knows all about last night! He didn’t know of my mother’s arrival! The hag had written the date on in pencil! You are wrong, you won’t catch me! There are no facts… it’s all supposition! You produce facts! The flat even isn’t a fact but delirium. I know what to say to them…. Do they know about the flat? I won’t go without finding out. What did I come for? But my being angry now, maybe is a fact! Fool, how irritable I am! Perhaps that’s right; to play the invalid…. He is feeling me. He will try to catch me. Why did I come?”
All this flashed like lightning through his mind.
Porfiry Petrovitch returned quickly. He became suddenly more jovial.
“Your party yesterday, brother, has left my head rather…. And I am out of sorts altogether,” he began in quite a different tone, laughing to Razumihin.
“Was it interesting? I left you yesterday at the most interesting point. Who got the best of it?”
“Oh, no one, of course. They got on to everlasting questions, floated off into space.”
“Only fancy, Rodya, what we got on to yesterday. Whether there is such a thing as crime. I told you that we talked our heads off.”
“What is there strange? It’s an everyday social question,” Raskolnikov answered casually.
“The question wasn’t put quite like that,” observed Porfiry.
“Not quite, that’s true,” Razumihin agreed at once, getting warm and hurried as usual. “Listen, Rodion, and tell us your opinion, I want to hear it. I was fighting tooth and nail with them and wanted you to help me. I told them you were coming…. It began with the socialist doctrine. You know their doctrine; crime is a protest against the abnormality of the social organisation and nothing more, and nothing more; no other causes admitted!...”
“You are wrong there,” cried Porfiry Petrovitch; he was noticeably animated and kept laughing as he looked at Razumihin, which made him more excited than ever.
“Nothing is admitted,” Razumihin interrupted with heat.
“I am not wrong. I’ll show you their pamphlets. Everything with them is ‘the influence of environment,’ and nothing else. Their favourite phrase! From which it follows that, if society is normally organised, all crime will cease at once, since there will be nothing to protest against and all men will become righteous in one instant. Human nature is not taken into account, it is excluded, it’s not supposed to exist! They don’t recognise that humanity, developing by a historical living process, will become at last a normal society, but they believe that a social system that has come out of some mathematical brain is going to organise all humanity at once and make it just and sinless in an instant, quicker than any living process! That’s why they instinctively dislike history, ‘nothing but ugliness and stupidity in it,’ and they explain it all as stupidity! That’s why they so dislike the living process of life; they don’t want a living soul! The living soul demands life, the soul won’t obey the rules of mechanics, the soul is an object of suspicion, the soul is retrograde! But what they want though it smells of death and can be made of India-rubber, at least is not alive, has no will, is servile and won’t revolt! And it comes in the end to their reducing everything to the building of walls and the planning of rooms and passages in a phalanstery! The phalanstery is ready, indeed, but your human nature is not ready for the phalanstery—it wants life, it hasn’t completed its vital process, it’s too soon for the graveyard! You can’t skip over nature by logic. Logic presupposes three possibilities, but there are millions! Cut away a million, and reduce it all to the question of comfort! That’s the easiest solution of the problem! It’s seductively clear and you musn’t think about it. That’s the great thing, you mustn’t think! The whole secret of life in two pages of print!”
“Now he is off, beating the drum! Catch hold of him, do!” laughed Porfiry. “Can you imagine,” he turned to Raskolnikov, “six people holding forth like that last night, in one room, with punch as a preliminary! No, brother, you are wrong, environment accounts for a great deal in crime; I can assure you of that.”
“Oh, I know it does, but just tell me: a man of forty violates a child of ten; was it environment drove him to it?”
“Well, strictly speaking, it did,” Porfiry observed with noteworthy gravity; “a crime of that nature may be very well ascribed to the influence of environment.”
Razumihin was almost in a frenzy. “Oh, if you like,” he roared. “I’ll prove to you that your white eyelashes may very well be ascribed to the Church of Ivan the Great’s being two hundred and fifty feet high, and I will prove it clearly, exactly, progressively, and even with a Liberal tendency! I undertake to! Will you bet on it?”
“Done! Let’s hear, please, how he will prove it!”
“He is always humbugging, confound him,” cried Razumihin, jumping up and gesticulating. “What’s the use of talking to you? He does all that on purpose; you don’t know him, Rodion! He took their side yesterday, simply to make fools of them. And the things he said yesterday! And they were delighted! He can keep it up for a fortnight together. Last year he persuaded us that he was going into a monastery: he stuck to it for two months. Not long ago he took it into his head to declare he was going to get married, that he had everything ready for the wedding. He ordered new clothes indeed. We all began to congratulate him. There was no bride, nothing, all pure fantasy!”
“Ah, you are wrong! I got the clothes before. It was the new clothes in fact that made me think of taking you in.”
“Are you such a good dissembler?” Raskolnikov asked carelessly.
“You wouldn’t have supposed it, eh? Wait a bit, I shall take you in, too. Ha-ha-ha! No, I’ll tell you the truth. All these questions about crime, environment, children, recall to my mind an article of yours which interested me at the time. ‘On Crime’... or something of the sort, I forget the title, I read it with pleasure two months ago in the Periodical Review.”
“My article? In the Periodical Review?” Raskolnikov asked in astonishment. “I certainly did write an article upon a book six months ago when I left the university, but I sent it to the Weekly Review.”
“But it came out in the Periodical.”
“And the Weekly Review ceased to exist, so that’s why it wasn’t printed at the time.”
“That’s true; but when it ceased to exist, the Weekly Review was amalgamated with the Periodical, and so your article appeared two months ago in the latter. Didn’t you know?”
Raskolnikov had not known.
“Why, you might get some money out of them for the article! What a strange person you are! You lead such a solitary life that you know nothing of matters that concern you directly. It’s a fact, I assure you.”
“Bravo, Rodya! I knew nothing about it either!” cried Razumihin. “I’ll run to-day to the reading-room and ask for the number. Two months ago? What was the date? It doesn’t matter though, I will find it. Think of not telling us!”
“How did you find out that the article was mine? It’s only signed with an initial.”
“I only learnt it by chance, the other day. Through the editor; I know him…. I was very much interested.”
“I analysed, if I remember, the psychology of a criminal before and after the crime.”
“Yes, and you maintained that the perpetration of a crime is always accompanied by illness. Very, very original, but… it was not that part of your article that interested me so much, but an idea at the end of the article which I regret to say you merely suggested without working it out clearly. There is, if you recollect, a suggestion that there are certain persons who can… that is, not precisely are able to, but have a perfect right to commit breaches of morality and crimes, and that the law is not for them.”
Raskolnikov smiled at the exaggerated and intentional distortion of his idea.
“What? What do you mean? A right to crime? But not because of the influence of environment?” Razumihin inquired with some alarm even.
“No, not exactly because of it,” answered Porfiry. “In his article all men are divided into ‘ordinary’ and ‘extraordinary.’ Ordinary men have to live in submission, have no right to transgress the law, because, don’t you see, they are ordinary. But extraordinary men have a right to commit any crime and to transgress the law in any way, just because they are extraordinary. That was your idea, if I am not mistaken?”
“What do you mean? That can’t be right?” Razumihin muttered in bewilderment.
Raskolnikov smiled again. He saw the point at once, and knew where they wanted to drive him. He decided to take up the challenge.
“That wasn’t quite my contention,” he began simply and modestly. “Yet I admit that you have stated it almost correctly; perhaps, if you like, perfectly so.” (It almost gave him pleasure to admit this.) “The only difference is that I don’t contend that extraordinary people are always bound to commit breaches of morals, as you call it. In fact, I doubt whether such an argument could be published. I simply hinted that an ‘extraordinary’ man has the right… that is not an official right, but an inner right to decide in his own conscience to overstep… certain obstacles, and only in case it is essential for the practical fulfilment of his idea (sometimes, perhaps, of benefit to the whole of humanity). You say that my article isn’t definite; I am ready to make it as clear as I can. Perhaps I am right in thinking you want me to; very well. I maintain that if the discoveries of Kepler and Newton could not have been made known except by sacrificing the lives of one, a dozen, a hundred, or more men, Newton would have had the right, would indeed have been in duty bound… to eliminate the dozen or the hundred men for the sake of making his discoveries known to the whole of humanity. But it does not follow from that that Newton had a right to murder people right and left and to steal every day in the market. Then, I remember, I maintain in my article that all… well, legislators and leaders of men, such as Lycurgus, Solon, Mahomet, Napoleon, and so on, were all without exception criminals, from the very fact that, making a new law, they transgressed the ancient one, handed down from their ancestors and held sacred by the people, and they did not stop short at bloodshed either, if that bloodshed—often of innocent persons fighting bravely in defence of ancient law—were of use to their cause. It’s remarkable, in fact, that the majority, indeed, of these benefactors and leaders of humanity were guilty of terrible carnage. In short, I maintain that all great men or even men a little out of the common, that is to say capable of giving some new word, must from their very nature be criminals—more or less, of course. Otherwise it’s hard for them to get out of the common rut; and to remain in the common rut is what they can’t submit to, from their very nature again, and to my mind they ought not, indeed, to submit to it. You see that there is nothing particularly new in all that. The same thing has been printed and read a thousand times before. As for my division of people into ordinary and extraordinary, I acknowledge that it’s somewhat arbitrary, but I don’t insist upon exact numbers. I only believe in my leading idea that men are in general divided by a law of nature into two categories, inferior (ordinary), that is, so to say, material that serves only to reproduce its kind, and men who have the gift or the talent to utter a new word. There are, of course, innumerable sub-divisions, but the distinguishing features of both categories are fairly well marked. The first category, generally speaking, are men conservative in temperament and law-abiding; they live under control and love to be controlled. To my thinking it is their duty to be controlled, because that’s their vocation, and there is nothing humiliating in it for them. The second category all transgress the law; they are destroyers or disposed to destruction according to their capacities. The crimes of these men are of course relative and varied; for the most part they seek in very varied ways the destruction of the present for the sake of the better. But if such a one is forced for the sake of his idea to step over a corpse or wade through blood, he can, I maintain, find within himself, in his conscience, a sanction for wading through blood—that depends on the idea and its dimensions, note that. It’s only in that sense I speak of their right to crime in my article (you remember it began with the legal question). There’s no need for such anxiety, however; the masses will scarcely ever admit this right, they punish them or hang them (more or less), and in doing so fulfil quite justly their conservative vocation. But the same masses set these criminals on a pedestal in the next generation and worship them (more or less). The first category is always the man of the present, the second the man of the future. The first preserve the world and people it, the second move the world and lead it to its goal. Each class has an equal right to exist. In fact, all have equal rights with me—and _vive la guerre éternelle_—till the New Jerusalem, of course!”
“Then you believe in the New Jerusalem, do you?”
“I do,” Raskolnikov answered firmly; as he said these words and during the whole preceding tirade he kept his eyes on one spot on the carpet.
“And… and do you believe in God? Excuse my curiosity.”
“I do,” repeated Raskolnikov, raising his eyes to Porfiry.
“And… do you believe in Lazarus’ rising from the dead?”
“I… I do. Why do you ask all this?”
“You believe it literally?”
“You don’t say so…. I asked from curiosity. Excuse me. But let us go back to the question; they are not always executed. Some, on the contrary…”
“Triumph in their lifetime? Oh, yes, some attain their ends in this life, and then…”
“They begin executing other people?”
“If it’s necessary; indeed, for the most part they do. Your remark is very witty.”
“Thank you. But tell me this: how do you distinguish those extraordinary people from the ordinary ones? Are there signs at their birth? I feel there ought to be more exactitude, more external definition. Excuse the natural anxiety of a practical law-abiding citizen, but couldn’t they adopt a special uniform, for instance, couldn’t they wear something, be branded in some way? For you know if confusion arises and a member of one category imagines that he belongs to the other, begins to ‘eliminate obstacles’ as you so happily expressed it, then…”
“Oh, that very often happens! That remark is wittier than the other.”
“No reason to; but take note that the mistake can only arise in the first category, that is among the ordinary people (as I perhaps unfortunately called them). In spite of their predisposition to obedience very many of them, through a playfulness of nature, sometimes vouchsafed even to the cow, like to imagine themselves advanced people, ‘destroyers,’ and to push themselves into the ‘new movement,’ and this quite sincerely. Meanwhile the really new people are very often unobserved by them, or even despised as reactionaries of grovelling tendencies. But I don’t think there is any considerable danger here, and you really need not be uneasy for they never go very far. Of course, they might have a thrashing sometimes for letting their fancy run away with them and to teach them their place, but no more; in fact, even this isn’t necessary as they castigate themselves, for they are very conscientious: some perform this service for one another and others chastise themselves with their own hands…. They will impose various public acts of penitence upon themselves with a beautiful and edifying effect; in fact you’ve nothing to be uneasy about…. It’s a law of nature.”
“Well, you have certainly set my mind more at rest on that score; but there’s another thing worries me. Tell me, please, are there many people who have the right to kill others, these extraordinary people? I am ready to bow down to them, of course, but you must admit it’s alarming if there are a great many of them, eh?”
“Oh, you needn’t worry about that either,” Raskolnikov went on in the same tone. “People with new ideas, people with the faintest capacity for saying something new, are extremely few in number, extraordinarily so in fact. One thing only is clear, that the appearance of all these grades and sub-divisions of men must follow with unfailing regularity some law of nature. That law, of course, is unknown at present, but I am convinced that it exists, and one day may become known. The vast mass of mankind is mere material, and only exists in order by some great effort, by some mysterious process, by means of some crossing of races and stocks, to bring into the world at last perhaps one man out of a thousand with a spark of independence. One in ten thousand perhaps—I speak roughly, approximately—is born with some independence, and with still greater independence one in a hundred thousand. The man of genius is one of millions, and the great geniuses, the crown of humanity, appear on earth perhaps one in many thousand millions. In fact I have not peeped into the retort in which all this takes place. But there certainly is and must be a definite law, it cannot be a matter of chance.”
“Why, are you both joking?” Razumihin cried at last. “There you sit, making fun of one another. Are you serious, Rodya?”
Raskolnikov raised his pale and almost mournful face and made no reply. And the unconcealed, persistent, nervous, and discourteous sarcasm of Porfiry seemed strange to Razumihin beside that quiet and mournful face.
“Well, brother, if you are really serious… You are right, of course, in saying that it’s not new, that it’s like what we’ve read and heard a thousand times already; but what is really original in all this, and is exclusively your own, to my horror, is that you sanction bloodshed in the name of conscience, and, excuse my saying so, with such fanaticism…. That, I take it, is the point of your article. But that sanction of bloodshed by conscience is to my mind… more terrible than the official, legal sanction of bloodshed….”
“You are quite right, it is more terrible,” Porfiry agreed.
“Yes, you must have exaggerated! There is some mistake, I shall read it. You can’t think that! I shall read it.”
“All that is not in the article, there’s only a hint of it,” said Raskolnikov.
“Yes, yes.” Porfiry couldn’t sit still. “Your attitude to crime is pretty clear to me now, but… excuse me for my impertinence (I am really ashamed to be worrying you like this), you see, you’ve removed my anxiety as to the two grades getting mixed, but… there are various practical possibilities that make me uneasy! What if some man or youth imagines that he is a Lycurgus or Mahomet—a future one of course—and suppose he begins to remove all obstacles…. He has some great enterprise before him and needs money for it… and tries to get it… do you see?”
Zametov gave a sudden guffaw in his corner. Raskolnikov did not even raise his eyes to him.
“I must admit,” he went on calmly, “that such cases certainly must arise. The vain and foolish are particularly apt to fall into that snare; young people especially.”
“Yes, you see. Well then?”
“What then?” Raskolnikov smiled in reply; “that’s not my fault. So it is and so it always will be. He said just now (he nodded at Razumihin) that I sanction bloodshed. Society is too well protected by prisons, banishment, criminal investigators, penal servitude. There’s no need to be uneasy. You have but to catch the thief.”
“And what if we do catch him?”
“Then he gets what he deserves.”
“You are certainly logical. But what of his conscience?”
“Why do you care about that?”
“Simply from humanity.”
“If he has a conscience he will suffer for his mistake. That will be his punishment—as well as the prison.”
“But the real geniuses,” asked Razumihin frowning, “those who have the right to murder? Oughtn’t they to suffer at all even for the blood they’ve shed?”
“Why the word ought? It’s not a matter of permission or prohibition. He will suffer if he is sorry for his victim. Pain and suffering are always inevitable for a large intelligence and a deep heart. The really great men must, I think, have great sadness on earth,” he added dreamily, not in the tone of the conversation.
He raised his eyes, looked earnestly at them all, smiled, and took his cap. He was too quiet by comparison with his manner at his entrance, and he felt this. Everyone got up.
“Well, you may abuse me, be angry with me if you like,” Porfiry Petrovitch began again, “but I can’t resist. Allow me one little question (I know I am troubling you). There is just one little notion I want to express, simply that I may not forget it.”
“Very good, tell me your little notion,” Raskolnikov stood waiting, pale and grave before him.
“Well, you see… I really don’t know how to express it properly…. It’s a playful, psychological idea…. When you were writing your article, surely you couldn’t have helped, he-he! fancying yourself… just a little, an ‘extraordinary’ man, uttering a new word in your sense…. That’s so, isn’t it?”
“Quite possibly,” Raskolnikov answered contemptuously.
Razumihin made a movement.
“And, if so, could you bring yourself in case of worldly difficulties and hardship or for some service to humanity—to overstep obstacles?... For instance, to rob and murder?”
And again he winked with his left eye, and laughed noiselessly just as before.
“If I did I certainly should not tell you,” Raskolnikov answered with defiant and haughty contempt.
“No, I was only interested on account of your article, from a literary point of view…”
“Foo! how obvious and insolent that is!” Raskolnikov thought with repulsion.
“Allow me to observe,” he answered dryly, “that I don’t consider myself a Mahomet or a Napoleon, nor any personage of that kind, and not being one of them I cannot tell you how I should act.”
“Oh, come, don’t we all think ourselves Napoleons now in Russia?” Porfiry Petrovitch said with alarming familiarity.
Something peculiar betrayed itself in the very intonation of his voice.
“Perhaps it was one of these future Napoleons who did for Alyona Ivanovna last week?” Zametov blurted out from the corner.
Raskolnikov did not speak, but looked firmly and intently at Porfiry. Razumihin was scowling gloomily. He seemed before this to be noticing something. He looked angrily around. There was a minute of gloomy silence. Raskolnikov turned to go.
“Are you going already?” Porfiry said amiably, holding out his hand with excessive politeness. “Very, very glad of your acquaintance. As for your request, have no uneasiness, write just as I told you, or, better still, come to me there yourself in a day or two… to-morrow, indeed. I shall be there at eleven o’clock for certain. We’ll arrange it all; we’ll have a talk. As one of the last to be there, you might perhaps be able to tell us something,” he added with a most good-natured expression.
“You want to cross-examine me officially in due form?” Raskolnikov asked sharply.
“Oh, why? That’s not necessary for the present. You misunderstand me. I lose no opportunity, you see, and… I’ve talked with all who had pledges…. I obtained evidence from some of them, and you are the last…. Yes, by the way,” he cried, seemingly suddenly delighted, “I just remember, what was I thinking of?” he turned to Razumihin, “you were talking my ears off about that Nikolay… of course, I know, I know very well,” he turned to Raskolnikov, “that the fellow is innocent, but what is one to do? We had to trouble Dmitri too…. This is the point, this is all: when you went up the stairs it was past seven, wasn’t it?”
“Yes,” answered Raskolnikov, with an unpleasant sensation at the very moment he spoke that he need not have said it.
“Then when you went upstairs between seven and eight, didn’t you see in a flat that stood open on a second storey, do you remember? two workmen or at least one of them? They were painting there, didn’t you notice them? It’s very, very important for them.”
“Painters? No, I didn’t see them,” Raskolnikov answered slowly, as though ransacking his memory, while at the same instant he was racking every nerve, almost swooning with anxiety to conjecture as quickly as possible where the trap lay and not to overlook anything. “No, I didn’t see them, and I don’t think I noticed a flat like that open…. But on the fourth storey” (he had mastered the trap now and was triumphant) “I remember now that someone was moving out of the flat opposite Alyona Ivanovna’s…. I remember… I remember it clearly. Some porters were carrying out a sofa and they squeezed me against the wall. But painters… no, I don’t remember that there were any painters, and I don’t think that there was a flat open anywhere, no, there wasn’t.”
“What do you mean?” Razumihin shouted suddenly, as though he had reflected and realised. “Why, it was on the day of the murder the painters were at work, and he was there three days before? What are you asking?”
“Foo! I have muddled it!” Porfiry slapped himself on the forehead. “Deuce take it! This business is turning my brain!” he addressed Raskolnikov somewhat apologetically. “It would be such a great thing for us to find out whether anyone had seen them between seven and eight at the flat, so I fancied you could perhaps have told us something…. I quite muddled it.”
“Then you should be more careful,” Razumihin observed grimly.
The last words were uttered in the passage. Porfiry Petrovitch saw them to the door with excessive politeness.
They went out into the street gloomy and sullen, and for some steps they did not say a word. Raskolnikov drew a deep breath.
|
#include<bits/stdc++.h>
#define REP(x,y,z) for(int x=y;x<=z;x++)
#define MSET(x,y) memset(x,y,sizeof(x))
#define M 500005
#define MX 1048576
#define MOD 1000000007
using namespace std;
using LL = long long;
int n,in[M];
LL pw[M];
vector<int> pos[MX];
int find_cnt(int p1,int p2,int num) {
auto it1 = upper_bound(pos[num].begin(), pos[num].end(), p1);
auto it2 = lower_bound(pos[num].begin(), pos[num].end(), p2) - 1;
if (it1<=it2) return it2-it1+1;
return 0;
}
int main()
{
pw[0] = 1;
REP(i,1,M-1) pw[i] = (pw[i-1]*2) % MOD;
while (~scanf("%d",&n)) {
REP(i,0,MX-1) pos[i].clear();
REP(i,1,n) scanf("%d", &in[i]);
REP(i,2,n) in[i] ^= in[i-1];
REP(i,1,n) pos[in[i]].push_back(i);
//REP(i,1,n) printf("%d ",in[i]); puts("");
LL ans = 0;
REP(i,1,MX-1) if (in[n]==0 || in[n]==i) {
LL frsum = 0;
LL frdp = 0;
LL dp = 0;
REP(j,0,(int)pos[i].size()-1) {
int fri = j==0 ? 0 : pos[i][j-1];
int c0 = find_cnt(fri, pos[i][j], 0);
frdp = (frdp + frsum * c0) % MOD;
dp = (frdp + 1) % MOD;
frsum = (frsum + dp) % MOD;
}
if (in[n]==0) {
ans += frsum;
ans %= MOD;
} else {
ans += dp;
ans %= MOD;
}
}
if (in[n]==0) {
int len = 0;
REP(i,1,n-1) if(in[i]==0) len++;
ans += pw[len];
ans %= MOD;
}
printf("%lld\n", ans);
}
return 0;
}
|
Photo Courtesy of Steve Dewey, Utah State University, bugwood.org
Thermopsis montana Nutt.
Scientific Name Synonyms:
Life Span: Perennial
Growth Characteristics: Mountain goldenpea is an erect forb, growing up to 2 feet in height and spreading by rhizomes. It blooms between May and August, depending on the elevations.
Flowers: Pea-like lemon-yellow colored flowers in a raceme. Flowers are ½ to ¾ inch long. There are five to fifty flowers which make up the inflorescence. The flower spikes arise from the leaf axils
Fruits/Seeds: The seedpods are long, thin, blue/green and covered with downy hairy. They project vertically from the stem. The pods grow quickly in the late spring and early summer, and mature in late summer. There are two to five seeds per pod.
Leaves: Leaves are alternate, palmate, with 3 leaflets, which are oval in shape.
Stems: Multiple stems up to 2 feet tall.
Mountain goldenpea is found in montane and subalpine zones. It is common in woodlands and meadows.
Soils: Sandy, well-drained soils.
Associated Species: Aspen, lupine, snowberry.
Uses and Management:
Mountain goldenpea is poisonous to cattle. The principle toxin has not been isolated, but is thought to be similar to quinolizidine alkaloids found in Lupines. The toxin causes acute muscle degeneration – cattle become weak, ataxic, and unable to stand. Animals die from hunger and thirst.
Mountain Glodenpea will remain toxic in hay, especially if seed pods are present.
|
#include "initializer.h"
#include "thts.h"
#include "utils/logger.h"
#include "utils/math_utils.h"
#include "utils/string_utils.h"
#include "utils/system_utils.h"
/******************************************************************
Search Engine Creation
******************************************************************/
Initializer* Initializer::fromString(std::string& desc, THTS* thts) {
StringUtils::trim(desc);
assert(desc[0] == '[' && desc[desc.size() - 1] == ']');
StringUtils::removeFirstAndLastCharacter(desc);
StringUtils::trim(desc);
Initializer* result = nullptr;
if (desc.find("Expand") == 0) {
desc = desc.substr(6, desc.size());
result = new ExpandNodeInitializer(thts);
} else if (desc.find("Single") == 0) {
desc = desc.substr(6, desc.size());
result = new SingleChildInitializer(thts);
} else {
SystemUtils::abort("Unknown Initializer: " + desc);
}
StringUtils::trim(desc);
while (!desc.empty()) {
std::string param;
std::string value;
StringUtils::nextParamValuePair(desc, param, value);
if (!result->setValueFromString(param, value)) {
SystemUtils::abort("Unused parameter value pair: " + param + " / " +
value);
}
}
return result;
}
bool Initializer::setValueFromString(std::string& param, std::string& value) {
if (param == "-h") {
setHeuristic(SearchEngine::fromString(value));
return true;
} else if (param == "-hw") {
setHeuristicWeight(atof(value.c_str()));
return true;
} else if (param == "-iv") {
setNumberOfInitialVisits(atoi(value.c_str()));
return true;
}
return false;
}
Initializer::~Initializer() {
assert(heuristic);
delete heuristic;
}
/******************************************************************
Search Engine Administration
******************************************************************/
void Initializer::disableCaching() {
assert(heuristic);
heuristic->disableCaching();
}
void Initializer::initSession() {
assert(heuristic);
heuristic->initSession();
}
void Initializer::initRound() {
assert(heuristic);
heuristic->initRound();
}
void Initializer::finishRound() {
assert(heuristic);
heuristic->finishRound();
}
void Initializer::initStep(State const& current) {
assert(heuristic);
heuristic->initStep(current);
}
void Initializer::finishStep() {
assert(heuristic);
heuristic->finishStep();
}
/******************************************************************
Parameter Setter
******************************************************************/
void Initializer::setHeuristic(SearchEngine* _heuristic) {
if (heuristic) {
delete heuristic;
}
heuristic = _heuristic;
heuristic->prependName("THTS heuristic ");
}
void Initializer::setMaxSearchDepth(int maxSearchDepth) {
assert(heuristic);
heuristic->setMaxSearchDepth(maxSearchDepth);
}
/******************************************************************
Print
******************************************************************/
void Initializer::printConfig(std::string indent) const {
Logger::logLine(indent + "Initializer: " + name, Verbosity::VERBOSE);
indent += " ";
Logger::logLine(indent + "Heuristic weight: " +
std::to_string(heuristicWeight), Verbosity::VERBOSE);
Logger::logLine(indent + "Number of initial visits: " +
std::to_string(numberOfInitialVisits), Verbosity::VERBOSE);
assert(heuristic);
heuristic->printConfig(indent);
}
void Initializer::printStepStatistics(std::string indent) const {
assert(heuristic);
heuristic->printStepStatistics(indent);
}
void Initializer::printRoundStatistics(std::string indent) const {
assert(heuristic);
heuristic->printRoundStatistics(indent);
}
/******************************************************************
ExpandNodeInitializer
******************************************************************/
void ExpandNodeInitializer::initialize(SearchNode* node, State const& current) {
// Logger::logLine("initializing state:", Verbosity::DEBUG);
// Logger::logLine(current.toString(), Verbosity::DEBUG);
assert(node->children.empty());
node->children.resize(SearchEngine::numberOfActions, nullptr);
std::vector<int> actionsToExpand = thts->getApplicableActions(current);
std::vector<double> initialQValues(SearchEngine::numberOfActions,
-std::numeric_limits<double>::max());
heuristic->estimateQValues(current, actionsToExpand, initialQValues);
for (unsigned int index = 0; index < node->children.size(); ++index) {
if (actionsToExpand[index] == index) {
node->children[index] = thts->createChanceNode(1.0);
node->children[index]->futureReward =
heuristicWeight * initialQValues[index];
node->children[index]->numberOfVisits = numberOfInitialVisits;
node->children[index]->initialized = true;
node->numberOfVisits += numberOfInitialVisits;
node->futureReward = std::max(node->futureReward,
node->children[index]->futureReward);
// Logger::logLine("Initialized child " +
// SearchEngine::actionStates[index].toCompactString(),
// Verbosity::DEBUG);
// Logger::logLine(node->children[index]->toString(), Verbosity::DEBUG);
}
}
//Logger::logLine("", Verbosity::DEBUG);
node->initialized = true;
}
/******************************************************************
ExpandNodeInitializer
******************************************************************/
void SingleChildInitializer::initialize(SearchNode* node,
State const& current) {
// Logger::logLine("initializing state: ", Verbosity::DEBUG);
// Logger::logLine(current.toString(), Verbosity::DEBUG);
std::vector<int> candidates;
if (node->children.empty()) {
node->children.resize(SearchEngine::numberOfActions, nullptr);
std::vector<int> actionsToExpand = thts->getApplicableActions(current);
for (unsigned int index = 0; index < node->children.size(); ++index) {
if (actionsToExpand[index] == index) {
node->children[index] = thts->createChanceNode(1.0);
candidates.push_back(index);
}
}
} else {
for (unsigned int index = 0; index < node->children.size(); ++index) {
if (node->children[index] &&
MathUtils::doubleIsMinusInfinity(
node->children[index]->futureReward)) {
candidates.push_back(index);
}
}
}
assert(!candidates.empty());
int actionIndex = MathUtils::rnd->randomElement(candidates);
double initialQValue = 0.0;
heuristic->estimateQValue(current, actionIndex, initialQValue);
node->children[actionIndex]->futureReward = heuristicWeight * initialQValue;
node->children[actionIndex]->numberOfVisits = numberOfInitialVisits;
node->children[actionIndex]->initialized = true;
node->numberOfVisits += numberOfInitialVisits;
node->futureReward =
std::max(node->futureReward, node->children[actionIndex]->futureReward);
node->initialized = (candidates.size() == 1);
// Logger::logLine("Initialized child " +
// SearchEngine::actionStates[actionIndex].toCompactString(),
// Verbosity::DEBUG);
// Logger::logLine(node->children[actionIndex]->toString(), Verbosity::DEBUG);
}
|
#ifndef _ID1_PARRALEL_POLICY_H_
#define _ID1_PARRALEL_POLICY_H_
#include <memory>
#include <vector>
#include "esp_log.h"
#include "../typed"
namespace DynamicIndication {
namespace DataPolicy {
template <typename T> struct ic7414ParralelPolicy {
using bus_type = T;
using data_type = typename bus_type::data_type;
static constexpr char TAG[] = "ic7414ParralelPolicy";
static constexpr uint32_t bits_pre_channel = 4;
using framebuffer_element_type = typename typed<bits_pre_channel>::type;
ic7414ParralelPolicy(bus_type &databus, const uint32_t group_count = 1)
: databus{databus}, channels_pre_data_bus{databus.width() /
bits_pre_channel},
group_count{group_count} {}
ic7414ParralelPolicy(const ic7414ParralelPolicy &) = delete;
void setData(const std::vector<data_type> &dataSrc, uint8_t group) {
uint32_t bus_val = 0;
for (uint ch = 0; ch < channels_pre_data_bus; ++ch) {
if (dataSrc.size() <= group + ch * group_count) {
ESP_LOGW(TAG,
"dataSrc.size()[%d] <= group[%d] + "
"ch[%d] * group_count[%d]",
dataSrc.size(), group, ch, group_count);
return;
}
auto d = dataSrc.at(group + ch * group_count);
bus_val |= d << (bits_pre_channel * ch);
}
databus.setData(bus_val);
}
size_t framebufferSize() const { return channels_pre_data_bus * group_count; }
private:
bus_type &databus;
const uint32_t channels_pre_data_bus;
const uint32_t group_count;
};
} // namespace DataPolicy
} // namespace DynamicIndication
#endif /* _ID1_PARRALEL_POLICY_H_ */
|
Uveitis is inflammation of the uvea, which is made up of the iris, ciliary body and choroid. Together, these form the middle layer of the eye between the retina and the sclera (white of the eye).
The eye is shaped like a tennis ball, with three different layers of tissue surrounding the central gel-filled cavity, which is called the vitreous. The innermost layer is the retina, which senses light and helps to send images to your brain. The outermost layer is the sclera, the strong white wall of the eye. The middle layer between the sclera and retina is called the uvea.
The uvea contains many blood vessels — the veins, arteries and capillaries — that carry blood to and from the eye. Because the uvea nourishes many important parts of the eye (such as the retina), inflammation of the uvea can damage your sight.
There are several types of uveitis, defined by the part of the eye where it occurs.
- Iritis affects the front of your eye. Also called anterior uveitis, this is the most common type of uveitis. Iritis usually develops suddenly and may last six to eight weeks. Some types of anterior uveitis can be chronic or recurrent.
- If the uvea is inflamed in the middle or intermediate region of the eye, it is called pars planitis (or intermediate uveitis). Episodes of pars planitis can last between a few weeks to years. The disease goes through cycles of getting better, then worse.
- Posterior uveitis affects the back parts of your eye. Posterior uveitis can develop slowly and often lasts for many years.
- Panuveitis occurs when all layers of the uvea are inflamed.
Next Page: Uveitis Causes
|
/*
Copyright <SWGEmu>
See file COPYING for copying conditions.*/
#ifndef TRANSFERITEMARMORCOMMAND_H_
#define TRANSFERITEMARMORCOMMAND_H_
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/managers/objectcontroller/ObjectController.h"
#include "server/zone/managers/player/PlayerManager.h"
#include "server/zone/objects/player/sessions/TradeSession.h"
class TransferItemArmorCommand : public QueueCommand {
public:
TransferItemArmorCommand(const String& name, ZoneProcessServer* server)
: QueueCommand(name, server) {
}
int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const {
if (!checkStateMask(creature))
return INVALIDSTATE;
if (!checkInvalidLocomotions(creature))
return INVALIDLOCOMOTION;
/*
creature->info("transfer item armor");
StringBuffer infoMsg;
infoMsg << "target: 0x" << hex << target << " arguments" << arguments.toString();
creature->info(infoMsg.toString());
*/
StringTokenizer tokenizer(arguments.toString());
uint64 destinationID = tokenizer.getLongToken();
int transferType = tokenizer.getIntToken(); // I've seen -1 usually.. 4 when equipping most clothes (I think -1 is remove)
float unknown1 = tokenizer.getFloatToken();
float unknown2 = tokenizer.getFloatToken();
float unknown3 = tokenizer.getFloatToken();
ManagedReference<TradeSession*> tradeContainer = creature->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>();
if (tradeContainer != nullptr) {
server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(creature);
}
ManagedReference<SceneObject*> objectToTransfer = server->getZoneServer()->getObject(target);
if (objectToTransfer == nullptr) {
creature->error("objectToTransfer nullptr in transferitemarmor command");
return GENERALERROR;
}
if (!objectToTransfer->checkContainerPermission(creature, ContainerPermissions::MOVECONTAINER))
return GENERALERROR;
ManagedReference<SceneObject*> objectsParent = objectToTransfer->getParent().get();
if (objectsParent == nullptr)
return GENERALERROR;
if (!objectsParent->checkContainerPermission(creature, ContainerPermissions::MOVEOUT))
return GENERALERROR;
if (!objectToTransfer->isWearableObject()) {
creature->error("objectToTransfer is not an armor object in transferitemarmor");
return GENERALERROR;
}
if (!objectToTransfer->isASubChildOf(creature))
return GENERALERROR;
ManagedReference<SceneObject*> destinationObject = server->getZoneServer()->getObject(destinationID);
if (destinationObject == nullptr) {
creature->error("destinationObject nullptr in transferitemarmor command");
return GENERALERROR;
}
if (destinationObject != creature) {
creature->error("destinationObject is not player in transferitemarmor command");
return GENERALERROR;
}
if (transferType == 4) {
ManagedReference<SceneObject*> parent = objectToTransfer->getParent().get();
if (parent == nullptr) {
creature->error("objectToTransfer parent is nullptr in transferitemarmor command");
return GENERALERROR;
}
ZoneServer* zoneServer = server->getZoneServer();
ObjectController* objectController = zoneServer->getObjectController();
String errorDescription;
int transferPreProcess = destinationObject->canAddObject(objectToTransfer, transferType, errorDescription);
if (transferPreProcess == TransferErrorCode::SLOTOCCUPIED) {
int arrangementSize = objectToTransfer->getArrangementDescriptorSize();
if (arrangementSize > 0) {
int arrangementGroupToUse = -1;
for (int i = 0; i < arrangementSize && arrangementGroupToUse == -1; ++i) {
const Vector<String>* descriptors = objectToTransfer->getArrangementDescriptor(i);
for (int j = 0; j < descriptors->size(); ++j) {
const String& descriptor = descriptors->get(j);
if (destinationObject->getSlottedObject(descriptor) == nullptr && arrangementGroupToUse == -1) {
arrangementGroupToUse = i;
} else if (arrangementGroupToUse != -1) {
arrangementGroupToUse = -1;
break;
}
}
}
if (arrangementGroupToUse != -1) {
transferType += arrangementGroupToUse;
} else {
const String& childArrangement = objectToTransfer->getArrangementDescriptor(0)->get(0);
ManagedReference<SceneObject*> objectToRemove = destinationObject->getSlottedObject(childArrangement);
if (objectToRemove == nullptr)
return GENERALERROR;
if (!objectController->transferObject(objectToRemove, parent, 0xFFFFFFFF, true))
return GENERALERROR;
}
}
} else if (transferPreProcess != 0) {
if (errorDescription.length() > 1)
creature->sendSystemMessage(errorDescription);
return GENERALERROR;
}
if (!objectController->transferObject(objectToTransfer, destinationObject, transferType, true))
return GENERALERROR;
} /*else if (transferType == 4) {
}*/ else {
creature->error("unknown transferType in transferitemarmor command");
}
/*
uint64 target = packet->parseLong();
TangibleObject* targetTanoObject;
targetTanoObject = cast<TangibleObject*>( player->getInventoryItem(target));
if (targetTanoObject != nullptr) {
Inventory* inventory = player->getInventory();
if (inventory != nullptr)
inventory->moveObjectToTopLevel(player, targetTanoObject);
player->changeArmor(target, false);
}*/
return SUCCESS;
}
};
#endif //TRANSFERITEMARMORCOMMAND_H_
|
#include "src/core/applications/circuit_preprocessor.h"
#include "gtest/gtest.h"
extern bool is_valgrind;
/*
TEST(Circuit_preprocessor_test, miami_2000)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/miami/miami_left.kml", true);
Xml_document coord_right_kml("./database/tracks/miami/miami_right.kml", true);
Circuit_preprocessor::Options opts;
opts.print_level = 5;
opts.eps_c *= 5.0;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, 2000);
circuit.xml()->save("miami_2000.xml");
Xml_document solution_saved("./database/tracks/miami/miami_1000.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,700);
EXPECT_EQ(circuit.r_centerline.size(),700);
EXPECT_EQ(circuit.theta.size(),700);
EXPECT_EQ(circuit.kappa.size(),700);
EXPECT_EQ(circuit.nl.size(),700);
EXPECT_EQ(circuit.nr.size(),700);
EXPECT_EQ(circuit.dkappa.size(),700);
EXPECT_EQ(circuit.dnl.size(),700);
EXPECT_EQ(circuit.dnr.size(),700);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
*/
TEST(Circuit_preprocessor_test, museo_closed)
{
Xml_document coord_left_kml("./database/tracks/fa_museo/Museo_short_left.kml", true);
Xml_document coord_right_kml("./database/tracks/fa_museo/Museo_short_right.kml", true);
Circuit_preprocessor::Options options;
options.eps_k *= 0.001;
options.eps_n *= 0.001;
options.eps_c *= 0.001;
options.eps_d *= 0.001;
options.maximum_kappa = 1.0;
options.maximum_dkappa = 1.0;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, options, 100);
// Call the xml() method, just to confirm there are no errors/valgrind issues
circuit.xml();
Xml_document solution_saved("./data/museo_short_discrete.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,100);
EXPECT_EQ(circuit.r_centerline.size(),100);
EXPECT_EQ(circuit.theta.size(),100);
EXPECT_EQ(circuit.kappa.size(),100);
EXPECT_EQ(circuit.nl.size(),100);
EXPECT_EQ(circuit.nr.size(),100);
EXPECT_EQ(circuit.dkappa.size(),100);
EXPECT_EQ(circuit.dnl.size(),100);
EXPECT_EQ(circuit.dnr.size(),100);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_chicane)
{
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
Circuit_preprocessor::Coordinates start = {2.261, 41.57455};
Circuit_preprocessor::Coordinates finish = {2.26325, 41.57385};
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, start, finish, 20);
circuit.xml();
Xml_document solution_saved("./data/catalunya_chicane_discrete.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,21);
EXPECT_EQ(circuit.r_centerline.size(),21);
EXPECT_EQ(circuit.theta.size(),21);
EXPECT_EQ(circuit.kappa.size(),21);
EXPECT_EQ(circuit.nl.size(),21);
EXPECT_EQ(circuit.nr.size(),21);
EXPECT_EQ(circuit.dkappa.size(),21);
EXPECT_EQ(circuit.dnl.size(),21);
EXPECT_EQ(circuit.dnr.size(),21);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
}
TEST(Circuit_preprocessor_test, melbourne_700)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/melbourne/melbourne_left.kml", true);
Xml_document coord_right_kml("./database/tracks/melbourne/melbourne_right.kml", true);
Circuit_preprocessor::Options opts;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, 700);
circuit.xml();
Xml_document solution_saved("./database/tracks/melbourne/melbourne_700.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,700);
EXPECT_EQ(circuit.r_centerline.size(),700);
EXPECT_EQ(circuit.theta.size(),700);
EXPECT_EQ(circuit.kappa.size(),700);
EXPECT_EQ(circuit.nl.size(),700);
EXPECT_EQ(circuit.nr.size(),700);
EXPECT_EQ(circuit.dkappa.size(),700);
EXPECT_EQ(circuit.dnl.size(),700);
EXPECT_EQ(circuit.dnr.size(),700);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, melbourne_adapted)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/melbourne/melbourne_left.kml", true);
Xml_document coord_right_kml("./database/tracks/melbourne/melbourne_right.kml", true);
std::vector<scalar> s_bkp = {0.0000000000000000, 215.6155437858050732, 225.6155437858050732, 426.1900513192233007, 436.1900513192233007, 930.0647657741851617, 940.0647657741851617, 1291.0496358314749159, 1301.0496358314749159, 1749.8012415292823789, 1759.8012415292823789, 1975.4167853150893279, 1985.4167853150893279, 3171.1791673798661577, 3181.1791673798661577, 3562.2461099419315360, 3572.2461099419315360, 3945.7925343778033493, 3955.7925343778033493, 4178.9285962898038633, 4188.9285962898038633, 4276.6953319303202079, 4286.6953319303202079, 4690.3238288709662811, 4700.3238288709662811 };
std::vector<scalar> ds_bkp = {14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000};
Circuit_preprocessor::Options opts;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, s_bkp, ds_bkp);
circuit.xml();
Xml_document solution_saved("./database/tracks/melbourne/melbourne_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,545);
EXPECT_EQ(circuit.r_centerline.size(),545);
EXPECT_EQ(circuit.theta.size(),545);
EXPECT_EQ(circuit.kappa.size(),545);
EXPECT_EQ(circuit.nl.size(),545);
EXPECT_EQ(circuit.nr.size(),545);
EXPECT_EQ(circuit.dkappa.size(),545);
EXPECT_EQ(circuit.dnl.size(),545);
EXPECT_EQ(circuit.dnr.size(),545);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_500)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, 500);
circuit.xml();
Xml_document solution_saved("./database/tracks/catalunya/catalunya_discrete.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,500);
EXPECT_EQ(circuit.r_centerline.size(),500);
EXPECT_EQ(circuit.theta.size(),500);
EXPECT_EQ(circuit.kappa.size(),500);
EXPECT_EQ(circuit.nl.size(),500);
EXPECT_EQ(circuit.nr.size(),500);
EXPECT_EQ(circuit.dkappa.size(),500);
EXPECT_EQ(circuit.dnl.size(),500);
EXPECT_EQ(circuit.dnr.size(),500);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_adapted_by_coords)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
std::vector<std::pair<Circuit_preprocessor::Coordinates,scalar>> ds_breakpoints =
{ {{0.0, 0.0 }, 20.0},
{{2.257193719176818,41.56522599658208}, 8.0},
{{2.254933238159729,41.56471245384411}, 10.0},
{{2.253853158059371,41.56800644695232}, 8.0},
{{2.2547819299335, 41.56663345239372}, 10.0},
{{2.261124403684718,41.57244119725051}, 5.0},
{{2.260173022232699,41.57444062293845}, 3.0},
{{2.263173649148178,41.57388038009333}, 10.0}
};
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, ds_breakpoints);
circuit.xml();
Xml_document solution_saved("./data/catalunya_adapted_by_coords.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,555);
EXPECT_EQ(circuit.r_centerline.size(),555);
EXPECT_EQ(circuit.theta.size(),555);
EXPECT_EQ(circuit.kappa.size(),555);
EXPECT_EQ(circuit.nl.size(),555);
EXPECT_EQ(circuit.nr.size(),555);
EXPECT_EQ(circuit.dkappa.size(),555);
EXPECT_EQ(circuit.dnl.size(),555);
EXPECT_EQ(circuit.dnr.size(),555);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_adapted_by_ds_distribution)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
std::vector<scalar> s_distr = {0.0};
while (s_distr.back() < 4633.0 )
s_distr.push_back(s_distr.back() + 4.5);
std::vector<scalar> ds_distr(s_distr.size());
for (size_t i = 0; i < s_distr.size(); ++i)
{
ds_distr[i] = 9.0;
if (s_distr[i] > 950.0 && s_distr[i] < 1200.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 1150.0 && s_distr[i] < 1418.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 3633.17 && s_distr[i] < 3850.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 4050.0 && s_distr[i] < 4430.0)
ds_distr[i] = 2.5;
}
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, s_distr, ds_distr);
circuit.xml();
Xml_document solution_saved("./database/tracks/catalunya/catalunya_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,697);
EXPECT_EQ(circuit.r_centerline.size(),697);
EXPECT_EQ(circuit.theta.size(),697);
EXPECT_EQ(circuit.kappa.size(),697);
EXPECT_EQ(circuit.nl.size(),697);
EXPECT_EQ(circuit.nr.size(),697);
EXPECT_EQ(circuit.dkappa.size(),697);
EXPECT_EQ(circuit.dnl.size(),697);
EXPECT_EQ(circuit.dnr.size(),697);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, vendrell)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/vendrell/vendrell_left.kml", true);
Xml_document coord_right_kml("./database/tracks/vendrell/vendrell_right.kml", true);
Circuit_preprocessor::Options options;
options.eps_k *= 0.0002;
options.eps_n *= 0.001;
options.eps_c *= 0.001;
options.eps_d *= 0.001;
options.maximum_distance_find = 70.0;
options.maximum_kappa = 4.0;
options.maximum_dkappa = 4.0;
options.maximum_dn = 2.0;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, options, 500);
// Call the xml() method, just to confirm there are no errors/valgrind issues
circuit.xml();
Xml_document solution_saved("./database/tracks/vendrell/vendrell.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,500);
EXPECT_EQ(circuit.r_centerline.size(),500);
EXPECT_EQ(circuit.theta.size(),500);
EXPECT_EQ(circuit.kappa.size(),500);
EXPECT_EQ(circuit.nl.size(),500);
EXPECT_EQ(circuit.nr.size(),500);
EXPECT_EQ(circuit.dkappa.size(),500);
EXPECT_EQ(circuit.dnl.size(),500);
EXPECT_EQ(circuit.dnr.size(),500);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, imola_adapted)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/imola/imola_left.kml", true);
Xml_document coord_right_kml("./database/tracks/imola/imola_right.kml", true);
std::vector<scalar> s_bkp = { 0.0, 2650.0, 2660.0, 2950.0, 2960.0, 3300.0, 3310.0, 3450.0, 3460.0, 7000.0};
std::vector<scalar> ds_bkp = { 8.0, 8.0, 6.0, 6.0, 8.0, 8.0, 4.0, 4.0, 8.0, 8.0};
Circuit_preprocessor::Options opts;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, s_bkp, ds_bkp);
circuit.xml();
Xml_document solution_saved("./database/tracks/imola/imola_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,643);
EXPECT_EQ(circuit.r_centerline.size(),643);
EXPECT_EQ(circuit.theta.size(),643);
EXPECT_EQ(circuit.kappa.size(),643);
EXPECT_EQ(circuit.nl.size(),643);
EXPECT_EQ(circuit.nr.size(),643);
EXPECT_EQ(circuit.dkappa.size(),643);
EXPECT_EQ(circuit.dnl.size(),643);
EXPECT_EQ(circuit.dnr.size(),643);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_2022_adapted)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya_2022/catalunya_2022_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya_2022/catalunya_2022_right.kml", true);
std::vector<scalar> s_distr = {0.0};
while (s_distr.back() < 5000.0 )
s_distr.push_back(s_distr.back() + 4.5);
std::vector<scalar> ds_distr(s_distr.size());
for (size_t i = 0; i < s_distr.size(); ++i)
{
ds_distr[i] = 9.0;
if (s_distr[i] > 950.0 && s_distr[i] < 1200.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 1150.0 && s_distr[i] < 1418.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 3633.17 && s_distr[i] < 3850.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 4050.0 && s_distr[i] < 4430.0)
ds_distr[i] = 2.5;
}
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, s_distr, ds_distr);
circuit.xml();
Xml_document solution_saved("./database/tracks/catalunya_2022/catalunya_2022_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,700);
EXPECT_EQ(circuit.r_centerline.size(),700);
EXPECT_EQ(circuit.theta.size(),700);
EXPECT_EQ(circuit.kappa.size(),700);
EXPECT_EQ(circuit.nl.size(),700);
EXPECT_EQ(circuit.nr.size(),700);
EXPECT_EQ(circuit.dkappa.size(),700);
EXPECT_EQ(circuit.dnl.size(),700);
EXPECT_EQ(circuit.dnr.size(),700);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
|
Do You Know Nutrition: Invasion of the genetically modified organisms
Oct. 11, 2011 at 5:11 a.m.
Phylis Canion
Phylis Canion
By Phylis Canion
Sometime back, you had a timeline about GMOs. Can you please explain more about what GMOs are, how they affect our food supply, and names of product ingredients that we need to be aware of?
GMOs are genetically modified organisms (also called GEs, genetically engineered) plants or animals created through the gene splicing techniques of biotechnology.
According to the Non GMO Project, this experimental technology merges DNA from different species, creating unstable combinations of plant, animal, bacterial and viral genes that cannot occur in nature or in traditional crossbreeding. Virtually all commercial GMOs are bred to withstand direct application of herbicides.
In more than 30 countries around the world, including all of the European countries and Japan, there are significant restrictions or outright bans on the production of GMOs because they do not consider them safe.
In the United States, however, the government has approved commercial production of GMOs based on studies conducted by companies who created them and profit from their sales.
The six major GMO crops are soy, corn, canola, cotton, sugar beets and alfalfa. Specific ingredients to look for on product labeling that should be avoided are the following: soy protein isolate, hydrolyzed soy protein, high fructose corn syrup, sucrose, monosodium glutamate, dextrose, modified food starch, corn syrup, sugar syrup, malt, mono and di-glycerides and rBGH(a recumbent growth hormone added to milk and butter), to name a few of the most prevalent.
One of the major issues concerning genetically modified organisms is that there is no labeling requirements that specifically states a product contains GMOs although they make up approximately 1/4 of our food supply.
Those manufacturers whose products do not contain GMOs gladly list on their packaging that the product is GMO free or that it is a NON-GMO product.
Because GMOs are relatively new and have not been in use long enough for the risk to be known, there is growing concerns about safety.
According to the American Academy of Environmental Medicine, several animal studies indicate serious health risks associated with genetically modified foods that include infertility, immune problems, accelerated aging, faulty insulin regulation and issues with the gastrointestinal system.
The World Health Organization has also taken an active role in the evaluation of genetically modified foods.
Powered By AdvocateDigitalMedia
|
Grain farmers could make more money be switching to organic grain crops according to a new study released at last week's American Agricultural Economics Association's annual meeting.
Records showed that organic crops fetched much more than conventional crops: soybeans, up to $14 more per bushel; corn, up to $3 more; and wheat, up to $5 more. Organic alfalfa hay is too new to have a track record, so researchers recorded it as selling for the same price as conventionally grown hay.
Over four years the study analyzed both economic risks and transition effects of switching to organic farming of the Agricultural Research Service's Swan Lake Research Farm near Morris, Minn. The 130-acre Swan Lake farm is representative of typical corn-soybean farms in Minnesota.
ARS economist David Archer and soil scientist Hillarius Kludze compared an organic corn-soybean rotation and an organic corn-soybean-spring wheat/alfalfa rotation - half grown with conventional tillage and half with strip tillage - with a corn-soybean rotation using conventional tillage. Strip tillage involves tilling only the middle of the seedbed. The scientists found that when strip tillage is used with organic farming, one of the transition risks is an increase in weeds until farmers learn to manage the system.
Computer simulations projected costs, yields and risks over a 20-year period, using yield and economic data from the four-year study, as well as crop price records of recent years.
Another computer model projected that farmers would net an average $50 to $60 more per acre a year by going organic, even with the highest transition costs. The premium price advantage would outweigh the initial higher costs and possibly lower yields, even if organic prices were to drop by half.
|
// This file implements the IRemoteDebugApplication Interface and Gateway for Python.
// Generated by makegw.py
#include "stdafx.h"
#include "PyIRemoteDebugApplication.h"
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation
PyIRemoteDebugApplication::PyIRemoteDebugApplication(IUnknown *pdisp) : PyIUnknown(pdisp) { ob_type = &type; }
PyIRemoteDebugApplication::~PyIRemoteDebugApplication() {}
/* static */ IRemoteDebugApplication *PyIRemoteDebugApplication::GetI(PyObject *self)
{
return (IRemoteDebugApplication *)PyIUnknown::GetI(self);
}
// @pymethod |PyIRemoteDebugApplication|ResumeFromBreakPoint|Continue an application which is currently in a breakpoint.
PyObject *PyIRemoteDebugApplication::ResumeFromBreakPoint(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
// @pyparm <o PyIRemoteDebugApplicationThread>|prptFocus||Description for prptFocus
// @pyparm int|bra||Break resume action
// @pyparm int|era||Error resume action
PyObject *obprptFocus;
BREAKRESUMEACTION bra;
ERRORRESUMEACTION era;
if (!PyArg_ParseTuple(args, "Oii:ResumeFromBreakPoint", &obprptFocus, &bra, &era))
return NULL;
IRemoteDebugApplicationThread *prptFocus;
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obprptFocus, IID_IRemoteDebugApplicationThread, (void **)&prptFocus,
FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->ResumeFromBreakPoint(prptFocus, bra, era);
prptFocus->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |PyIRemoteDebugApplication|CauseBreak|Causes the application to break into the debugger at the earliest
// opportunity.
PyObject *PyIRemoteDebugApplication::CauseBreak(PyObject *self, PyObject *args)
{
// @comm Note that a long time may elapse before the application actually breaks, particularly if
// the application is not currently executing script code.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":CauseBreak"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->CauseBreak();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |PyIRemoteDebugApplication|ConnectDebugger|Connects a debugger to the application.
PyObject *PyIRemoteDebugApplication::ConnectDebugger(PyObject *self, PyObject *args)
{
// @comm Only one debugger may be connected at a
// time; this method fails if there is already a debugger connected.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
// @pyparm <o PyIApplicationDebugger>|pad||Description for pad
PyObject *obpad;
if (!PyArg_ParseTuple(args, "O:ConnectDebugger", &obpad))
return NULL;
IApplicationDebugger *pad;
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obpad, IID_IApplicationDebugger, (void **)&pad, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->ConnectDebugger(pad);
pad->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |PyIRemoteDebugApplication|DisconnectDebugger|Disconnects the current debugger from the application.
PyObject *PyIRemoteDebugApplication::DisconnectDebugger(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":DisconnectDebugger"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->DisconnectDebugger();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyIApplicationDebugger>|PyIRemoteDebugApplication|GetDebugger|Returns the current debugger connected to
// the application.
PyObject *PyIRemoteDebugApplication::GetDebugger(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":GetDebugger"))
return NULL;
IApplicationDebugger *pad;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->GetDebugger(&pad);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(pad, IID_IApplicationDebugger, FALSE);
}
// @pymethod <o PyIUnknown>|PyIRemoteDebugApplication|CreateInstanceAtApplication|Create objects in the application
// process address space.
PyObject *PyIRemoteDebugApplication::CreateInstanceAtApplication(PyObject *self, PyObject *args)
{
// @comm Provides a mechanism for the debugger IDE, running out-of-process to the
// application, to create objects in the application process.
// This method simply delegates to CoCreateInstance.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
// @pyparm <o PyIID>|rclsid||Description for rclsid
// @pyparm <o PyIUnknown>|pUnkOuter||Description for pUnkOuter
// @pyparm int|dwClsContext||Description for dwClsContext
// @pyparm <o PyIID>|riid||Description for riid
PyObject *obrclsid;
PyObject *obpUnkOuter;
DWORD dwClsContext;
PyObject *obriid;
if (!PyArg_ParseTuple(args, "OOiO:CreateInstanceAtApplication", &obrclsid, &obpUnkOuter, &dwClsContext, &obriid))
return NULL;
IID rclsid;
IUnknown *pUnkOuter;
IID riid;
IUnknown *ppvObject;
BOOL bPythonIsHappy = TRUE;
if (!PyWinObject_AsIID(obrclsid, &rclsid))
bPythonIsHappy = FALSE;
if (!PyWinObject_AsIID(obriid, &riid))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
if (!PyCom_InterfaceFromPyInstanceOrObject(obpUnkOuter, IID_IUnknown, (void **)&pUnkOuter, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->CreateInstanceAtApplication(rclsid, pUnkOuter, dwClsContext, riid, &ppvObject);
pUnkOuter->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(ppvObject, IID_IUnknown, FALSE);
}
// @pymethod |PyIRemoteDebugApplication|QueryAlive|Returns True if alive, else False.
PyObject *PyIRemoteDebugApplication::QueryAlive(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":QueryAlive"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->QueryAlive();
PY_INTERFACE_POSTCALL;
return PyInt_FromLong(hr == S_OK);
}
// @pymethod <o PyIEnumRemoteDebugApplicationThreads>|PyIRemoteDebugApplication|EnumThreads|Enumerates all threads known
// to be associated with the application.
PyObject *PyIRemoteDebugApplication::EnumThreads(PyObject *self, PyObject *args)
{
// @comm New threads may be added at any time.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":EnumThreads"))
return NULL;
IEnumRemoteDebugApplicationThreads *perdat;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->EnumThreads(&perdat);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(perdat, IID_IEnumRemoteDebugApplicationThreads, FALSE);
}
// @pymethod |PyIRemoteDebugApplication|GetName|Description of GetName.
PyObject *PyIRemoteDebugApplication::GetName(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":GetName"))
return NULL;
BSTR pbstrName;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->GetName(&pbstrName);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
PyObject *obpbstrName = MakeBstrToObj(pbstrName);
PyObject *pyretval = Py_BuildValue("O", obpbstrName);
Py_XDECREF(obpbstrName);
SysFreeString(pbstrName);
return pyretval;
}
// @pymethod <o PyIDebugApplicationNode>|PyIRemoteDebugApplication|GetRootNode|Returns the application node under which
// all nodes associated with the application are added.
PyObject *PyIRemoteDebugApplication::GetRootNode(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":GetRootNode"))
return NULL;
IDebugApplicationNode *pNode;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->GetRootNode(&pNode);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(pNode, IID_IDebugApplicationNode, FALSE);
}
// @pymethod <o IEnumDebugExpressionContexts>|PyIRemoteDebugApplication|EnumGlobalExpressionContexts|Enumerates all
// global expression contexts
PyObject *PyIRemoteDebugApplication::EnumGlobalExpressionContexts(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":EnumGlobalExpressionContexts"))
return NULL;
IEnumDebugExpressionContexts *perdat;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->EnumGlobalExpressionContexts(&perdat);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(perdat, IID_IEnumDebugExpressionContexts, FALSE);
}
// @object PyIRemoteDebugApplication|Description of the interface
static struct PyMethodDef PyIRemoteDebugApplication_methods[] = {
{"ResumeFromBreakPoint", PyIRemoteDebugApplication::ResumeFromBreakPoint,
1}, // @pymeth ResumeFromBreakPoint|Continue an application which is currently in a breakpoint.
{"CauseBreak", PyIRemoteDebugApplication::CauseBreak,
1}, // @pymeth CauseBreak|Causes the application to break into the debugger at the earliest opportunity.
{"ConnectDebugger", PyIRemoteDebugApplication::ConnectDebugger,
1}, // @pymeth ConnectDebugger|Connects a debugger to the application.
{"DisconnectDebugger", PyIRemoteDebugApplication::DisconnectDebugger,
1}, // @pymeth DisconnectDebugger|Disconnects the current debugger from the application.
{"GetDebugger", PyIRemoteDebugApplication::GetDebugger,
1}, // @pymeth GetDebugger|Returns the current debugger connected to the application.
{"CreateInstanceAtApplication", PyIRemoteDebugApplication::CreateInstanceAtApplication,
1}, // @pymeth CreateInstanceAtApplication|Create objects in the application process address space.
{"QueryAlive", PyIRemoteDebugApplication::QueryAlive,
1}, // @pymeth QueryAlive|Indicates if the application is alive.
{"EnumThreads", PyIRemoteDebugApplication::EnumThreads,
1}, // @pymeth EnumThreads|Enumerates all threads known to be associated with the application.
{"GetName", PyIRemoteDebugApplication::GetName, 1}, // @pymeth GetName|Description of GetName
{"GetRootNode", PyIRemoteDebugApplication::GetRootNode,
1}, // @pymeth GetRootNode|Returns the application node under which all nodes associated with the application are
// added.
{"EnumGlobalExpressionContexts", PyIRemoteDebugApplication::EnumGlobalExpressionContexts,
1}, // @pymeth EnumGlobalExpressionContexts|Enumerates all global expression contexts.
{NULL}};
PyComTypeObject PyIRemoteDebugApplication::type("PyIRemoteDebugApplication", &PyIUnknown::type,
sizeof(PyIRemoteDebugApplication), PyIRemoteDebugApplication_methods,
GET_PYCOM_CTOR(PyIRemoteDebugApplication));
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGRemoteDebugApplication::ResumeFromBreakPoint(
/* [in] */ IRemoteDebugApplicationThread __RPC_FAR *prptFocus,
/* [in] */ BREAKRESUMEACTION bra,
/* [in] */ ERRORRESUMEACTION era)
{
PY_GATEWAY_METHOD;
PyObject *obprptFocus = PyCom_PyObjectFromIUnknown(prptFocus, IID_IRemoteDebugApplicationThread, TRUE);
HRESULT hr = InvokeViaPolicy("ResumeFromBreakPoint", NULL, "Oii", obprptFocus, bra, era);
Py_XDECREF(obprptFocus);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::CauseBreak(void)
{
PY_GATEWAY_METHOD;
HRESULT hr = InvokeViaPolicy("CauseBreak", NULL);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::ConnectDebugger(
/* [in] */ IApplicationDebugger __RPC_FAR *pad)
{
PY_GATEWAY_METHOD;
PyObject *obpad = PyCom_PyObjectFromIUnknown(pad, IID_IApplicationDebugger, TRUE);
HRESULT hr = InvokeViaPolicy("ConnectDebugger", NULL, "O", obpad);
Py_XDECREF(obpad);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::DisconnectDebugger(void)
{
PY_GATEWAY_METHOD;
HRESULT hr = InvokeViaPolicy("DisconnectDebugger", NULL);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::GetDebugger(
/* [out] */ IApplicationDebugger __RPC_FAR *__RPC_FAR *pad)
{
PY_GATEWAY_METHOD;
if (pad == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetDebugger", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obpad;
if (!PyArg_Parse(result, "O", &obpad))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obpad, IID_IApplicationDebugger, (void **)pad, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::CreateInstanceAtApplication(
/* [in] */ REFCLSID rclsid,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DWORD dwClsContext,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppvObject)
{
PY_GATEWAY_METHOD;
if (ppvObject == NULL)
return E_POINTER;
PyObject *obrclsid = PyWinObject_FromIID(rclsid);
PyObject *obpUnkOuter = PyCom_PyObjectFromIUnknown(pUnkOuter, IID_IUnknown, TRUE);
PyObject *obriid = PyWinObject_FromIID(riid);
PyObject *result;
HRESULT hr =
InvokeViaPolicy("CreateInstanceAtApplication", &result, "OOiO", obrclsid, obpUnkOuter, dwClsContext, obriid);
Py_XDECREF(obrclsid);
Py_XDECREF(obpUnkOuter);
Py_XDECREF(obriid);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obppvObject;
if (!PyArg_Parse(result, "O", &obppvObject))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obppvObject, IID_IUnknown, (void **)ppvObject, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::EnumThreads(IEnumRemoteDebugApplicationThreads __RPC_FAR *__RPC_FAR *pperdat)
{
PY_GATEWAY_METHOD;
if (pperdat == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("EnumThreads", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *oberdat;
if (!PyArg_Parse(result, "O", &oberdat))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(oberdat, IID_IEnumRemoteDebugApplicationThreads, (void **)pperdat,
FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::QueryAlive(void)
{
PY_GATEWAY_METHOD;
HRESULT hr = InvokeViaPolicy("QueryAlive", NULL);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::GetName(
/* [out] */ BSTR __RPC_FAR *pbstrName)
{
PY_GATEWAY_METHOD;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetName", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obpbstrName;
if (!PyArg_Parse(result, "O", &obpbstrName))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_BstrFromPyObject(obpbstrName, pbstrName))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::GetRootNode(IDebugApplicationNode __RPC_FAR *__RPC_FAR *ppdanRoot)
{
PY_GATEWAY_METHOD;
if (ppdanRoot == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetRootNode", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obnode;
if (!PyArg_Parse(result, "O", &obnode))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obnode, IID_IDebugApplicationNode, (void **)ppdanRoot,
FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::EnumGlobalExpressionContexts(
IEnumDebugExpressionContexts __RPC_FAR *__RPC_FAR *ppedec)
{
PY_GATEWAY_METHOD;
if (ppedec == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("EnumGlobalExpressionContexts", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *oberdat;
if (!PyArg_Parse(result, "O", &oberdat))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(oberdat, IID_IEnumDebugExpressionContexts, (void **)ppedec,
TRUE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
|
#include <wiringPiI2C.h>
#include <wiringPi.h>
#include <time.h>
#include <string.h>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <wiringSerial.h>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <vector>
#include "../rover_util/utils.h"
#include "../sensor/nineaxis.h"
#include "accel_manager.h"
#include "accel_mangaer_constanth.h"
AccelManager gAccelManager;
bool AccelManager::onInit(const struct timespec& time)
{
gNineAxisSensor.setRunMode(true);
mLastUpdateTime = time;
isTryNineaxis = false;
mAccelSamples.clear();
return true;
}
void AccelManager::onClean()
{
}
void AccelManager::onUpdate(const timespec & time)
{
double dt = Time::dt(time, mLastUpdateTime);
if (dt < ACCELMANAGER_UPDATE_INTERVAL_TIME)return;
mLastUpdateTime = time;
if (!gNineAxisSensor.isActive())
{
if (isTryNineaxis)
{
setRunMode(false);
return;
}
gNineAxisSensor.setRunMode(true);
isTryNineaxis = true;
}
UpdateMadgwickQuaternion(dt, getAx(), getAy(), getAz(), getGx()*M_PI / 180.0f, getGy()*M_PI / 180.0f, getGz()*M_PI / 180.0f, getMx(), getMy(), getMz());
//UpdateMahonyQuaternion(dt, getAx(), getAy(), getAz(), getGx()*M_PI / 180.0f, getGy()*M_PI / 180.0f, getGz()*M_PI / 180.0f, getMx(), getMy(), getMz());
if (!isSensorView) return;
printInfo();
}
bool AccelManager::onCommand(const std::vector<std::string>& args)
{
if (args[0].compare(getName()) != 0) return true;
switch (args.size())
{
case 1:
Debug::print(LOG_PRINT,
"\r\n\
accel calibmagnet : calibrate magnet. Do 8 circle!\r\n\
accel view : sensor view \r\n\n\
");
printInfo();
printCalibInfo();
return true;
case 2:
if (args[1].compare("calibmagnet") == 0)
{
calibrationMagnet(MAGNET_CALIBRATION_SAMPLES);
Debug::print(LOG_PRINT, "Magnet OFFSET POS X:%f, Y:%f, Z:%f\r\n", mOffsetMagnetX, mOffsetMagnetY, mOffsetMagnetZ);
Debug::print(LOG_PRINT, "Magnet OFFSET SCALE X:%f, Y:%f, Z:%f\r\n", mScaleMagnetX, mScaleMagnetY, mScaleMagnetZ);
}
else if (args[1].compare("view") == 0)
{
isSensorView = !isSensorView;
}
return true;
default:
return true;
}
}
void AccelManager::printInfo()
{
Debug::print(LOG_PRINT, "Accel %3.3f %3.3f %3.3f\r\n", getAx(), getAy(), getAz());
Debug::print(LOG_PRINT, "Gyro %3.3f %3.3f %3.3f\r\n", getGx(), getGy(), getGz());
Debug::print(LOG_PRINT, "Magnet %3.3f %3.3f %3.3f\r\n", getMx(), getMy(), getMz());
Debug::print(LOG_PRINT, "Magnet Angle %3.3f %3.3f %3.3f\r\n", getMx(), getMy(), getMz());
Debug::print(LOG_PRINT, "Roll, Pitch, Yaw %3.3f %3.3f %3.3f\r\n", getRoll(), getPitch(), getYaw());
Debug::print(LOG_PRINT, "Azimuth(deg) %3.3f\r\n", getRawMagnetDirection());
//Debug::print(LOG_PRINT, "Sx, Sy, Sz %3.3f %3.3f %3.3f\r\n", getSx(), getSy(), getSz());
Debug::print(LOG_PRINT, "Turn Side, Turn Back %s %s \r\n", isTurnSide() ? "true" : "false", isTurnBack() ? "true" : "false");
}
void AccelManager::printCalibInfo()
{
Debug::print(LOG_PRINT, "Calibration Magnet POS X:%3.3f, Y:%3.3f, Z:%3.3f\r\n", mOffsetMagnetX, mOffsetMagnetY, mOffsetMagnetZ);
Debug::print(LOG_PRINT, "Calibration Magnet SCALE X:%3.3f, Y:%3.3f, Z:%3.3f\r\n", mScaleMagnetX, mScaleMagnetY, mScaleMagnetZ);
}
bool AccelManager::isTurnSide()
{
float roll = abs(getRoll());
return (roll > 90 - TURN_SIDE_THRESHOLD && roll < 90 + TURN_SIDE_THRESHOLD);
}
bool AccelManager::isTurnBack()
{
float roll = abs(getRoll());
return (roll > 180 - TURN_BACK_THRESHOLD && roll < 180 + TURN_BACK_THRESHOLD);
}
VECTOR3 AccelManager::getVectorAccel() const
{
return VECTOR3();
}
double AccelManager::getAx() const
{
return gNineAxisSensor.getAccel().x;
}
double AccelManager::getAy() const
{
return gNineAxisSensor.getAccel().y;
}
double AccelManager::getAz() const
{
return gNineAxisSensor.getAccel().z;
}
VECTOR3 AccelManager::getVectorGyro() const
{
return VECTOR3();
}
double AccelManager::getGx() const
{
return gNineAxisSensor.getGyro().x;
}
double AccelManager::getGy() const
{
return gNineAxisSensor.getGyro().y;
}
double AccelManager::getGz() const
{
return gNineAxisSensor.getGyro().z;
}
void AccelManager::calibrationMagnet(int calib_magnet_samples)
{
std::vector<VECTOR3> magnet_samples;
for (; magnet_samples.size() < calib_magnet_samples;)
{
magnet_samples.push_back(gNineAxisSensor.getMagnet());
Debug::print(LOG_SUMMARY, "Calib Progres %d / %d\r\n", magnet_samples.size(), calib_magnet_samples);
delay(10);
}
std::vector<double> magnet_vector_x;
std::vector<double> magnet_vector_y;
std::vector<double> magnet_vector_z;
for (VECTOR3 sample : magnet_samples)
{
magnet_vector_x.push_back(sample.x);
magnet_vector_y.push_back(sample.y);
magnet_vector_z.push_back(sample.z);
}
auto max_x = max_element(magnet_vector_x.begin(), magnet_vector_x.end());
auto max_y = max_element(magnet_vector_y.begin(), magnet_vector_y.end());
auto max_z = max_element(magnet_vector_z.begin(), magnet_vector_z.end());
auto min_x = min_element(magnet_vector_x.begin(), magnet_vector_x.end());
auto min_y = min_element(magnet_vector_y.begin(), magnet_vector_y.end());
auto min_z = min_element(magnet_vector_z.begin(), magnet_vector_z.end());
mOffsetMagnetX = (*max_x + *min_x) / 2;
mOffsetMagnetY = (*max_y + *min_y) / 2;
mOffsetMagnetZ = (*max_z + *min_z) / 2;
double avg_delta = (mOffsetMagnetX + mOffsetMagnetY + mOffsetMagnetZ) / 3;
mScaleMagnetX = avg_delta / mOffsetMagnetX;
mScaleMagnetY = avg_delta / mOffsetMagnetY;
mScaleMagnetZ = avg_delta / mOffsetMagnetZ;
}
VECTOR3 AccelManager::getVectorMagnet() const
{
return gNineAxisSensor.getMagnet();
}
double AccelManager::getMx() const
{
return (gNineAxisSensor.getMagnet().x - mOffsetMagnetX) * mScaleMagnetX;
}
double AccelManager::getMy() const
{
return (gNineAxisSensor.getMagnet().y - mOffsetMagnetY) * mScaleMagnetY;
}
double AccelManager::getMz() const
{
return (gNineAxisSensor.getMagnet().z - mOffsetMagnetZ) * mScaleMagnetZ;
}
double AccelManager::getRawMagnetDirection() const
{
double azimuth;
double mag_x = getMx();
double mag_y = getMy();
double mag_z = getMz();
azimuth = -(fmod(atan2(mag_y, mag_x) * (180.0 / M_PI) + 270.0 - 7, 360.0) - 360.0);
return azimuth;
}
VECTOR3 AccelManager::getVectorSpeed() const
{
return VECTOR3();
}
double AccelManager::getSx() const
{
/*std::deque<VECTOR3> accel_samples = gNineAxisSensor.getAccelSamples();
std::deque<VECTOR3>::iterator it = accel_samples.begin();
double speed;
double curr_accel = 0.0;
double pre_accel = 0.0;
while (it != accel_samples.end())
{
curr_accel = (*it).x;
speed += (curr_accel + pre_accel) / 2 * NINEAXIS_UPDATE_INTERVAL_TIME;
pre_accel = curr_accel;
++it;
}
return speed;*/
return 0.0;
}
double AccelManager::getSy() const
{
/*std::deque<VECTOR3> accel_samples = gNineAxisSensor.getAccelSamples();
std::deque<VECTOR3>::iterator it = accel_samples.begin();
double speed;
double curr_accel = 0.0;
double pre_accel = 0.0;
while (it != accel_samples.end())
{
curr_accel = (*it).y;
speed += (curr_accel + pre_accel) / 2 * NINEAXIS_UPDATE_INTERVAL_TIME;
pre_accel = curr_accel;
++it;
}
return speed;*/
return 0.0;
}
double AccelManager::getSz() const
{
/*std::deque<VECTOR3> accel_samples = gNineAxisSensor.getAccelSamples();
std::deque<VECTOR3>::iterator it = accel_samples.begin();
double speed;
double curr_accel = 0.0;
double pre_accel = 0.0;
while (it != accel_samples.end())
{
curr_accel = (*it).z;
speed += (curr_accel + pre_accel) / 2 * NINEAXIS_UPDATE_INTERVAL_TIME;
pre_accel = curr_accel;
++it;
}
return speed;*/
return 0.0;
}
VECTOR3 AccelManager::getVectorRolling() const
{
return VECTOR3();
}
float AccelManager::getRoll() const
{
double roll = atan2(2.0f * (mQuaternion[0] * mQuaternion[1] + mQuaternion[2] * mQuaternion[3]), mQuaternion[0] * mQuaternion[0] - mQuaternion[1] * mQuaternion[1] - mQuaternion[2] * mQuaternion[2] + mQuaternion[3] * mQuaternion[3]);
roll *= 180.0f / M_PI;
return roll;
}
float AccelManager::getPitch() const
{
double pitch = -asin(2.0f * (mQuaternion[1] * mQuaternion[3] - mQuaternion[0] * mQuaternion[2]));
pitch *= 180.0f / M_PI;
return pitch;
}
float AccelManager::getYaw() const
{
double yaw = atan2(2.0f * (mQuaternion[1] * mQuaternion[2] + mQuaternion[0] * mQuaternion[3]), mQuaternion[0] * mQuaternion[0] + mQuaternion[1] * mQuaternion[1] - mQuaternion[2] * mQuaternion[2] - mQuaternion[3] * mQuaternion[3]);
yaw *= 180.0f / M_PI;
yaw -= -DECLINATION_FOR_YAW;
return yaw;
}
double AccelManager::normalize(double pos)
{
while (pos >= 180 || pos < -180)pos += (pos > 0) ? -360 : 360;
return pos;
}
void AccelManager::UpdateMadgwickQuaternion(double dt, float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = mQuaternion[0], q2 = mQuaternion[1], q3 = mQuaternion[2], q4 = mQuaternion[3]; // short name local variable for readability
float norm;
float hx, hy, _2bx, _2bz;
float s1, s2, s3, s4;
float qDot1, qDot2, qDot3, qDot4;
// Auxiliary variables to avoid repeated arithmetic
float _2q1mx;
float _2q1my;
float _2q1mz;
float _2q2mx;
float _4bx;
float _4bz;
float _2q1 = 2.0f * q1;
float _2q2 = 2.0f * q2;
float _2q3 = 2.0f * q3;
float _2q4 = 2.0f * q4;
float _2q1q3 = 2.0f * q1 * q3;
float _2q3q4 = 2.0f * q3 * q4;
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Normalise accelerometer measurement
norm = sqrtf(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrtf(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
_2q1mx = 2.0f * q1 * mx;
_2q1my = 2.0f * q1 * my;
_2q1mz = 2.0f * q1 * mz;
_2q2mx = 2.0f * q2 * mx;
hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4;
hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4;
_2bx = sqrtf(hx * hx + hy * hy);
_2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4;
_4bx = 2.0f * _2bx;
_4bz = 2.0f * _2bz;
// Gradient decent algorithm corrective step
s1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 - ay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz * q2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 - _2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay) + (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
norm = sqrtf(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalise step magnitude
norm = 1.0f / norm;
s1 *= norm;
s2 *= norm;
s3 *= norm;
s4 *= norm;
// Compute rate of change of quaternion
qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;
qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;
qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;
qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;
// Integrate to yield quaternion
q1 += qDot1 * dt;
q2 += qDot2 * dt;
q3 += qDot3 * dt;
q4 += qDot4 * dt;
norm = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion
norm = 1.0f / norm;
mQuaternion[0] = q1 * norm;
mQuaternion[1] = q2 * norm;
mQuaternion[2] = q3 * norm;
mQuaternion[3] = q4 * norm;
}
void AccelManager::UpdateMahonyQuaternion(double dt, float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = mQuaternion[0], q2 = mQuaternion[1], q3 = mQuaternion[2], q4 = mQuaternion[3]; // short name local variable for readability
float norm;
float hx, hy, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
float pa, pb, pc;
// Auxiliary variables to avoid repeated arithmetic
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Normalise accelerometer measurement
norm = sqrtf(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrtf(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);
hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);
bx = sqrtf((hx * hx) + (hy * hy));
bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);
// Estimated direction of gravity and magnetic field
vx = 2.0f * (q2q4 - q1q3);
vy = 2.0f * (q1q2 + q3q4);
vz = q1q1 - q2q2 - q3q3 + q4q4;
wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);
wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);
wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);
// Error is cross product between estimated direction and measured direction of gravity
ex = (ay * vz - az * vy) + (my * wz - mz * wy);
ey = (az * vx - ax * vz) + (mz * wx - mx * wz);
ez = (ax * vy - ay * vx) + (mx * wy - my * wx);
if (Ki > 0.0f)
{
mErrorOfIntegral[0] += ex; // accumulate integral error
mErrorOfIntegral[1] += ey;
mErrorOfIntegral[2] += ez;
}
else
{
mErrorOfIntegral[0] = 0.0f; // prevent integral wind up
mErrorOfIntegral[1] = 0.0f;
mErrorOfIntegral[2] = 0.0f;
}
// Apply feedback terms
gx = gx + Kp * ex + Ki * mErrorOfIntegral[0];
gy = gy + Kp * ey + Ki * mErrorOfIntegral[1];
gz = gz + Kp * ez + Ki * mErrorOfIntegral[2];
// Integrate rate of change of quaternion
pa = q2;
pb = q3;
pc = q4;
q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * dt);
q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * dt);
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * dt);
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * dt);
// Normalise quaternion
norm = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);
norm = 1.0f / norm;
mQuaternion[0] = q1 * norm;
mQuaternion[1] = q2 * norm;
mQuaternion[2] = q3 * norm;
mQuaternion[3] = q4 * norm;
}
void AccelManager::normalize(VECTOR3& pos)
{
pos.x = normalize(pos.x);
pos.y = normalize(pos.y);
pos.z = normalize(pos.z);
}
AccelManager::AccelManager() :mOffsetMagnetX(MAGNET_POS_OFFSET_X), mOffsetMagnetY(MAGNET_POS_OFFSET_Y), mOffsetMagnetZ(MAGNET_POS_OFFSET_Z), mScaleMagnetX(MAGNET_SCALE_OFFSET_X), mScaleMagnetY(MAGNET_SCALE_OFFSET_Y), mScaleMagnetZ(MAGNET_SCALE_OFFSET_Z)
{
setName("accel");
setPriority(TASK_PRIORITY_SENSOR, TASK_INTERVAL_SENSOR);
mQuaternion[0] = 1;
mQuaternion[1] = 0;
mQuaternion[2] = 0;
mQuaternion[3] = 0;
mErrorOfIntegral[0] = 0;
mErrorOfIntegral[1] = 0;
mErrorOfIntegral[2] = 0;
isSensorView = false;
}
AccelManager::~AccelManager()
{
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.