text
stringlengths 121
672k
|
|---|
Basic Use To make a new number, a simple initialization suffices:
var foo = 0; // or whatever number you want
foo = 1; //foo = 1 foo += 2; //foo = 3 (the two gets added on) foo -= 2; //foo = 1 (the two gets removed)
Number literals define the number value. In particular: They appear as a set of digits of varying length. Negative literal numbers have a minus sign before the set of digits. Floating point literal numbers contain one decimal point, and may optionally use the E notation with the character e. An integer literal may be prepended with "0", to indicate that a number is in base-8. (8 and 9 are not octal digits, and if found, cause the integer to be read in the normal base-10). An integer literal may also be found with "0x", to indicate a hexadecimal number. The Math Object Unlike strings, arrays, and dates, the numbers aren't objects. The Math object provides numeric functions and constants as methods and properties. The methods and properties of the Math object are referenced using the dot operator in the usual way, for example:
var varOne = Math.ceil(8.5); var varPi = Math.PI; var sqrt3 = Math.sqrt(3);
Methods random() Generates a pseudo-random number.
var myInt = Math.random();
max(int1, int2) Returns the highest number from the two numbers passed as arguments.
var myInt = Math.max(8, 9); document.write(myInt); //9
min(int1, int2) Returns the lowest number from the two numbers passed as arguments.
var myInt = Math.min(8, 9); document.write(myInt); //8
floor(float) Returns the greatest integer less than the number passed as an argument.
var myInt = Math.floor(90.8); document.write(myInt); //90;
ceil(float) Returns the least integer greater than the number passed as an argument.
var myInt = Math.ceil(90.8); document.write(myInt); //91;
round(float) Returns the closest integer to the number passed as an argument.
var myInt = Math.round(90.8); document.write(myInt); //91;
|
by +Richard Holbrooke – Schwann cells boost and amplify nerve growth in animal models, but their clinical use has been held back because they are difficult, time-consuming and costly to culture.
A University of Sheffield team, led by Professor John Haycock, has developed a new technique with adult rat tissue which overcomes all these problems, producing Schwann cells in less than half the time and at much lower cost.
“The ability of Schwann cells to boost nerve growth was proved many years ago in animals, but if you want to use this technique with patients, the problem is: where do you get enough cells from?” said Professor Haycock, from the University’s Department of Materials Science and Engineering.
“To reduce immune rejection, the cells have to be grown from the patient’s own tissue. Of course, you want to take the smallest amount of tissue necessary, so the technique must be efficient. It must also be fast, so treatment can begin as soon as possible after injury. For clinical use, it must also provide pure Schwann cells. And finally, to make it viable, it has to be at a reasonable cost.”
Existing methods for growing Schwann cells from adult tissue promote the growth of another type of cell, called fibroblasts, which swamp the Schwann cells, reducing the speed they grow and their numbers. This means that large amounts of tissue are needed at the outset, to grow sufficient cells for therapeutic use. It also requires extra purification stages added to the process, making it slow and costly – taking up to 3 months to complete.
Professor Haycock and his team have come up with a very simple solution: feed the Schwann cells but starve the fibroblasts. The research, published today in Nature Protocols, uses an amino acid that only the Schwann cells can break down and feed off, and are able to produce a 97 per cent pure population of Schwann cells in a much shorter space of time – just 19 days – from a small sample of adult tissue.
Professor Haycock is confident the technique can be replicated in humans. His team are trialling the same method using human nerve tissue, with results expected within the next six months.
|
If you feel like Cortana just doesn't get you, improvements may be on the way.
We all want to know the person we're talking to is listening to us. We extend this expectation to our "non-human" AI companions as well. Having to repeat oneself, once we've mentally moved from "expression of thought" to "expectation of response" only to be volleyed back to "expression of thought" because the listener did't hear us is an exercise in frustration.
Talking to digital assistants can be frustrating.
This all-too-common pattern of exchange between humans and our AI digital assistants has caused many of us to default to more reliable "non-verbal" exchanges.
Ironically, speaking to our assistants is supposed to be a more natural and quicker way to get things done.
Perhaps science fiction has spoiled us. The ease with which Knight Rider's Michael Knight verbally interacted with his artificially intelligent Trans Am, KITT, (and other fictional AI-human interactions), painted a frictionless picture of verbal discourse. The bar has been set very high.
Microsoft may have gotten us a bit closer to that bar, and to a route out of the pattern of frustration talking to digital assistants often engenders.
Crystal clear
On Monday, October 17th, 2016 Microsoft announced that their latest automated system had reached human parity regarding speech recognition. In a nutshell, Microsoft's non-human system was just as accurate as professional human transcriptionists when hearing and transcribing conversational speech.
Microsoft's automated system performed as well as professional transcriptionists.
The tests included pairs of strangers discussing an assigned topic and open-ended conversations between family and friends. The automated system surpassed the respective 5.9%, and 11.3% word error rates of the professional transcriptionists for each test.
Microsoft's executive vice-president of Artificial Intelligence and Research Group, Harry Shum, praised this accomplishment:
This breakthrough, of course, is foundational to the realization of the more complex AI interactions we have come to believe are just around the corner. An assistant's ability to accurately hear us, like with human interactions, is a prerequisite to its understanding us. The journey to understanding is, of course, the next step. That may or may not take as long as our trek to human parity in "hearing" has taken us to achieve.
Competition is good
The road to human parity speech recognition began in the 1970's with a research division of the US Department of Defense, DARPA. Microsoft's subsequent decades-long investments led to artificial neural networks which are patterned after the biological neural networks of animals. The combination of convolutional and Long-Short-Term-Memory neural networks helped Redmond's system become "more human". Xuedong Huang, Microsoft's chief speech scientist exclaims:
This is an historic achievement.
And, of course, it is. Microsoft is not alone in its efforts to evolve AI understanding of human language, however. Google and Apple have invested in neural networks as well. The boost to Siri's performance is likely attributable to Cupertino's investments. Furthermore, Google's access to a massive repository of data through its search engine and ubiquitous Android OS has helped Mountain View's voice-recognition efforts make tremendous strides.
Apple is striving to catch up to Microsoft and Google.
Google's and Microsoft's industry leading progress with deep neural networks, AI, natural language processing and machine learning have likely spurred Apple's most recent investments in Siri.
Cupertino is looking to make its bounded assistant more competitive if recent job postings for the Siri team in Cambridge UK are any indication:
Join Apple's Siri team…and be part of revolutionizing human-machine interaction!"
"You will be joining a highly talented team of software engineers and machine learning scientists to develop the next generation of Siri. We use world class tools and software engineering practices and push the boundaries of artificial intelligence with a single aim: make a real difference to the lives of the hundreds of millions of Siri users.
This will undoubtedly increase Siri's reliability over time. Still, these advantages will be limited to Siri users within Apple's walled garden of 11.7% of all smartphone users and around 10% of all PC users.
Canvasing the competition
In a world where digital experiences are transient, the unbounded (cross-platform) nature of Cortana and Google Now, is arguably an advantage these assistants have over Siri. Combined with the Bing and Google search engine backbones respectively, Microsoft's and Google's investments in conversation as a canvas position these companies beyond the "iPhone-focused" Apple.
Speech recognition is key to Microsofts Conversations as a Platform plan.
Microsoft's forward-thinking platform focus is the backdrop which supports its accomplishments in human parity in speech recognition. This achievement is important to Nadella's Conversation as a Platform and human language (written/verbal) as a UI strategy. It's a critical piece to a complex puzzle of making AI and human interaction more natural. Nadella had this to say about Conversation as a Platform:
We're in the very early days of this…It's a simple concept, yet it's very powerful in its impact. It is about taking the power of human language and applying it more pervasively to all of our computing. ...we need to infuse into our computers and computing intelligence, intelligence about us and our context…by doing so…this can have as profound an impact as the previous platform shifts have had, whether it be GUI, whether it be the Web or touch on mobile.
Cortana on PC, Edge, Windows Mobile, iOS, Android and Xbox is a big part of this vision. Shum shared of Redmond's speech recognition achievement and Microsoft's AI assistant:
This will make Cortana more powerful, making a truly intelligent assistant possible.
Going Forward
Customizing Cortana to each region, like Korea, before her launch there, provides a tailored regional experience but slows her global expansion. This is a sore spot for many users but is an essential part of Microsoft's personal digital assistant vision. Still, it is a disadvantage Cortana has in relation to the more widely distributed Siri and Google Now.
Finally, the lack of a standalone unit such as Alexa and Google Home is an apparent hole in Microsoft's strategic positioning of Cortana. Perhaps Redmond's groundbreaking success in speech recognition will give such a future a device a strategic advantage over the competition. Fans are asking, I wonder if Microsoft can hear them.
|
/******************************************************************************
* IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. *
* *
* By downloading, copying, installing or using the software you agree to *
* this license.If you do not agree to this license, do not download, *
* install,copy or use the software. *
* *
* License Agreement *
* For AutoPilot-tool *
* *
* Copyright (C) 2020, Huang Jianyu, all rights reserved. *
* Third party copyrights are property of their respective owners. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification,are permitted provided that the following conditions are met: *
* *
* * Redistribution's of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* * Redistribution's in binary form must reproduce the above copyright *
* notice,this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* * The name of the copyright holders may not be used to endorse or promote *
* productsderived from this software without specific prior written *
* permission. *
* *
* This software is provided by the copyright holders and contributors "as is" *
* and any express or implied warranties, including, but not limited to, the *
* implied warranties of merchantability and fitness for a particular purpose *
* are disclaimed.In no event shall the Intel Corporation or contributors be *
* liable for any direct,indirect, incidental, special, exemplary, or *
* consequential damages(including, but not limited to, procurement of *
* substitute goods or services;loss of use, data, or profits; or business *
* interruption) however caused and on any theory of liability, whether in *
* contract, strict liability,or tort (including negligence or otherwise) *
* arising in any way out of the use of this software, even if advised of *
* the possibility of such damage. *
* *
*******************************************************************************
* Author: Huang Jianyu **
* Website: https://github.com/HjyTiger/AutoPilot-Tool **
* Date: 2020.12.24 **
* Version: 1.0.0 **
******************************************************************************/
#pragma once
#include "Model/Model_Config.h"
#include <string>
#include <atomic>
#include <QObject>
#include "qtpropertymanager.h"
#include "qteditorfactory.h"
#include "qttreepropertybrowser.h"
#include "qtbuttonpropertybrowser.h"
#include "qtgroupboxpropertybrowser.h"
enum PropertyOperation{
//common
THEME_CHANGE,
VIEW_CHANGE,
ENABLE_MOUSE,
ENABLE_KEYBOARD,
MOUSE_SENSITIVITY_CHANGE,
MOUSEWHEEL_SENSITIVITY_CHANGE,
KEYBOARD_SENSITIVITY_CHANGE,
//logger
CHANGE_PROJECT_NAME,
CHANGE_SW_VERSION,
CHANGE_VEHICLE_NO,
CHANGE_TESTER_NAME,
CHANGE_DATA_DISK,
CHANGE_LOG_CONS_TYPE,
CHANGE_LOG_CONS_VALUE,
CHANGE_RECORD_MODE,
CHANGE_RECORD_VALUE,
//player
ENABLE_PUBLISH_LCM,
CHANGE_PLAY_SPEED
};
struct PropertyOperationValue{
bool value_flag;
int value_enum;
int value_int;
float value_float;
double value_double;
std::string value_string;
};
Q_DECLARE_METATYPE(PropertyOperationValue)
enum LogConstrainType{
LOG_TIME_DURATION,
LOG_FILE_SIZE,
LOG_MESSAGE_COUNT
};
enum RecordMode{
RECORD_TIME_DURATION,
RECORD_FILE_SIZE,
RECORD_MESSAGE_COUNT
};
///
/// \brief The QTagTableWidget class
///
class QOptionPropertyBrowser: public QtTreePropertyBrowser
{
Q_OBJECT
public:
explicit QOptionPropertyBrowser(QWidget *parent = 0);
virtual ~QOptionPropertyBrowser();
public:
void Init();
void InitSignalAndSlot();
void InitCommonProperty();
void InitLoggerProperty();
void InitPlayerProperty();
void set_Config(tool::Option_Config * option_config);
void save_Config();
tool::Option_Config * get_Config(){
return config_;
}
private:
tool::Option_Config * config_;
QtStringPropertyManager * m_stringManager;
QtBoolPropertyManager * m_boolManager;
QtEnumPropertyManager * m_enumManager;
QtIntPropertyManager * m_intManager;
QtIntPropertyManager * m_intManager_slider;
QtDoublePropertyManager * m_doubleManager;
QtCheckBoxFactory * m_checkBoxFactory;
QtSpinBoxFactory * m_spinBoxFactory;
QtLineEditFactory * m_lineEditFactory;
QtEnumEditorFactory * m_comboBoxFactory;
QtDoubleSpinBoxFactory * m_doubleSpinBoxFactory;
QtSliderFactory * m_sliderFactory;
QtGroupPropertyManager * m_groupManager;
std::map<std::string,QtProperty *> m_Property_Map;
signals:
void updatePropertyOperation(int operation,PropertyOperationValue operValue);
void operationInformation(QString msgInfo,QColor strcolor);
public slots:
void OnStringChanged(QtProperty * property, QString val);
void OnBoolChanged(QtProperty * property, bool val);
void OnEnumChanged(QtProperty * property, int val);
void OnIntChanged(QtProperty * property, int val);
void OnIntSliderChanged(QtProperty * property, int val);
void OnDoubleChanged(QtProperty * property, double val);
};
|
/*
Copyright 2015 Alvaro Herrasti and Daniel Dovali
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.
*/
#ifndef GAME_LOOP_H
#define GAME_LOOP_H
#pragma once
#include <iostream>
#include <map>
#include <unordered_map>
#include <functional>
#include <cstdarg>
#include "GameSystem.h"
#include "SystemMessageSender.h"
template <typename KeyType>
class GameLoop
{
public:
// Constructs gameloop, recieves comparator function to order templated GameLoops, systemManager owning this gameloop,
// maxSubSteps maximum number of steps for simulation clamps when time since last render is big and loop runs multiple times with each fixed step,
// fixedTimeStep discrete timestep that will be passed to each system's update, if zero it passes delta time since last render
// priority of this gameloop with respect to others in SystemManager to which this is added
GameLoop(std::function<bool(const KeyType&, const KeyType&)> comparator, SystemMessageSender* sysManager,
double maxSubSteps = 1.0, double fixedTimeStep = 0.0, int priority = 0) :
mMaxSubSteps(maxSubSteps),
mFixedTimeStep(fixedTimeStep),
mSystemMap(comparator),
mComparator(comparator),
mSysManager(sysManager),
mTimeAccumulator(0.0),
mPriority(priority)
{
}
// lvalue copy constructor
GameLoop(GameLoop&& other) :
mMaxSubSteps(other.mMaxSubSteps),
mFixedTimeStep(other.mFixedTimeStep),
mSystemMap(std::move(other.mSystemMap)),
mComparator(other.mComparator),
mSysManager(other.mSysManager),
mTimeAccumulator(other.mTimeAccumulator),
mPriority(other.mPriority)
{
}
GameLoop() :
mMaxSubSteps(0),
mFixedTimeStep(0),
mSysManager(nullptr),
mTimeAccumulator(0.0),
mPriority(0)
{
}
// Adds new system to run, recieves priority key and object to copy
template <class T>
std::shared_ptr<GameSystem> addNewSystem(const KeyType& priorityKey, T&& newSystem) {
std::shared_ptr<GameSystem> system = std::shared_ptr<GameSystem>(new T(std::move(newSystem)));
this->mSystemMap[priorityKey] = system;
const std::type_info* type = &typeid(T);
mSysManager->addSystem(type, system);
return system;
}
// Adds new system to run, recieves priority and initializes new object with default constructor
template <class T>
std::shared_ptr<GameSystem> addNewSystem(const KeyType& priorityKey) {
std::shared_ptr<GameSystem> system = std::shared_ptr<GameSystem>(new T());
this->mSystemMap[priorityKey] = system;
const std::type_info* type = &typeid(T);
mSysManager->addSystem(type, system);
return system;
}
// removes system based on priority key
template <class T>
bool removeSystem(const KeyType& priorityKey) {
auto sysIt = this->ms
this->mSystemMap[priorityKey] = system;
const std::type_info* type = &typeid(T);
mSysManager->removeSystem(type);
return system;
}
// recieves deltaTime since last render
void run(double deltaTimeStep, SystemMessageSender* msgSender)
{
int loops = 0;
mTimeAccumulator += deltaTimeStep;
// runs systems in discrete fixed timesteps for deterministic behavior
// and clamps to max number of steps if simulation is runing too slow
while (mTimeAccumulator >= mFixedTimeStep && loops < mMaxSubSteps) {
// if mFixedTimeStep
double deltaTimeUpdate = mFixedTimeStep != 0.0 ? mFixedTimeStep : deltaTimeStep;
for (auto it = this->mSystemMap.begin(); it != this->mSystemMap.end(); it++)
{
it->second->update(deltaTimeUpdate, msgSender);
}
mTimeAccumulator -= deltaTimeUpdate;
loops++;
}
}
// Sets priority of this gameloop
void setPriority(int priority) {
this->mPriority = priority;
}
// gets priority of this gameloop, reference value used to look for inside a SystemManager
int getPriority() {
return this->mPriority;
}
~GameLoop()
{
}
private:
double mMaxSubSteps;
double mFixedTimeStep;
typedef std::map < KeyType, std::shared_ptr<GameSystem>, std::function<bool(const KeyType&, const KeyType&)> > SystemMap;
SystemMap mSystemMap;
typedef std::function<bool(const KeyType&, const KeyType&)> CompareFunc;
CompareFunc mComparator;
SystemMessageSender* mSysManager;
double mTimeAccumulator;
int mPriority;
};
#endif
|
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#include "libHh/Homogeneous.h"
using namespace hh;
int main() {
{
Point p(1.f, 2.f, 3.f), q(8.f, 7.f, 6.f);
Vector v(1.f, 2.f, 3.f), w(1.f, 0.f, 1.f), x(0.f, 1.f, 0.f), y = x;
SHOW(p, q, v, w, y);
SHOW(Homogeneous(p) + Homogeneous(q));
SHOW(to_Point((p + p * 2.f + p) / 4.f));
SHOW(to_Point((p + p) / 2.f));
SHOW(to_Point((p * 2.f) / 2.f));
SHOW(to_Point((p + q) / 2.f));
}
{
const Homogeneous h1(1.f, 2.f, 3.f, 4.f);
dummy_use(h1);
const Homogeneous h2(h1);
dummy_use(h2);
const Vec4<float> v(0.f, 0.f, 0.f, 0.f);
dummy_use(v);
const Homogeneous h3 = v;
dummy_use(h3);
const Homogeneous h4 = V(0.f, 0.f, 0.f, 0.f);
dummy_use(h4);
}
}
|
#ifndef CHESS_NEURAL_PHENOME_H_
#define CHESS_NEURAL_PHENOME_H_
#include <unordered_set>
#include <queue>
#include <algorithm>
#include <cassert>
#include "genome.h"
#include "quadtree.h"
namespace chess::neural {
struct NodePhenotype {
double bias;
NodeType type;
activation_t function;
double activation = 0;
};
class Phenome {
Genome &_genome;
PhenomeParameters _params;
int _node_count;
std::vector<Point> &_inputs;
std::vector<Point> &_outputs;
// Map 3D substrate points to node indexes
std::unordered_map<Point, int, PointHash> _pointset;
std::unordered_map<int, NodePhenotype> _nodes;
std::unordered_map<Edge, double, EdgeHash> _edges;
std::unordered_map<int, std::vector<int>> _adjacency;
std::vector<int> _sorted;
/**
* Checks if adding a new edge will create a cycle
*/
bool creates_cycle(Edge edge);
/**
* Query the CPPN (genome) to generate weight and bias values
*/
double calculate_weight(Point p0, Point p1);
/**
* Perform the division and initialization step of the evolving substrate
*/
Quadtree *division_initialization(Point point, bool outgoing);
/**
* Perform the prune and extract algorithm of the evolving substrate
*/
void prune_extract(Point point, Quadtree *quadtree, bool outgoing,
std::unordered_map<Edge, double, EdgeHash> &connections);
/**
* Check if a path exists between two nodes using BFS
*/
bool path_exists(int start, int end);
/**
* Remove nodes and connections that do not have a path to inputs or outputs
*/
void cleanup();
/**
* Generate the adjacency list
*/
void generate_adjacency();
/**
* Topologically sort the nodes for feed-forward evaluation
*/
void topological_sort(int node, std::unordered_set<int> &visited);
/**
* Update the internal graph structure of the neural network for evaluation
*/
void update_structure();
/**
* Check if all the output nodes are active
*/
bool active_output();
public:
/**
* A phenome is defined by the genome CPPN
*/
Phenome(Genome &genome, std::vector<Point> &inputs, std::vector<Point> &outputs, PhenomeParameters params);
Phenome &operator=(const Phenome &rhs);
/**
* Evaluate the neural network
*/
std::vector<double> forward(std::vector<double> input);
/**
* Get the fitness of this phenome's genome
*/
double get_fitness();
/**
* Set the fitness of this phenome's genome
*/
void set_fitness(double fitness);
/**
* Get this phenome's genome
*/
Genome &get_genome();
};
}
#endif
|
I recently read an interesting article by respected writer and analyst Walt Mossberg, who said the PC is being redefined. I agree. But ...
I've described the evolving personal computing landscape in the past. To communicate an accurate picture of the modern personal computing environment and the influencing factors that have shaped it, I've acknowledged that it's impossible to ignore the impact of the iPhone.
Though smartphones existed before the iPhone, those business-focused devices were not relevant to the masses. The iPhone, with its "massive" touch screen merged the iPod, a phone and an internet device, and redefined the smartphone. Consumers loved it as much as they loved the popular iPod that primed them for a pocketable consumer-focused smartphone from Apple.
Eventually, the iPhone and the "there's-an-app-for-that" model, which made it a veritable "swiss-army mobile computing device," evolved into much more than the phone-iPod-internet device introduced by former Apple CEO Steve Jobs in 2007.
In time, Apple's introduction of the iPhone had a profound effect on the personal computing landscape. The iPhone, Android phones and to a lesser extent Windows phones — all with their supporting app ecosystems, integrated services, always-connected nature and pocketability — supplanted the traditional PC as the most used personal computers. Yes, smartphones are personal computing devices.
Microsoft, not Apple, is more instrumental to the evolution of the PC.
I agree with Mossberg that the mobile computing environment and ecosystems that shape personal computing today are influencers on what the PC will ultimately be. However, I disagree with his assessment that a significant shift to the new type of ARM-based PC that runs mobile apps will be determined by Apple.
Millions of consumers already buy laptops that use "mobile apps"
Microsoft's Universal Windows Platform (UWP) and Windows 10 laptops and 2-in-1s have already begun the process of bringing consumers to a laptop form factor that runs mobile apps, as well as traditional apps. This computing environment will be brought to ARM processors, as ARM-based Windows 10 PCs begin rolling out in several months. The change to an ARM-based system will be largely transparent to users.
What won't be transparent are the advantages of ARM-based cellular Windows 10 PCs. Among other advantages, consumers will reap the benefits of lower costs, and lighter, fan-less and more power-efficient Windows 10 PCs.
Mossberg said the following of a shift to ARM in relation to this problem:
But the signs of a shift to ARM only set the stage for a bigger development: The migration of the most important modern software platforms, Android and iOS, to laptops and other traditional hardware that once defined the old kind of PC.
... I believe it won't matter much until Apple builds an ARM-based laptop running iOS. Here's why.
Microsoft ... does have a modern breed of multi-touch apps that work properly on a tablet or clamshell screen, and some are included on every Windows tablet and laptop. Unfortunately, partly because Microsoft has no smartphone business to speak of, it also lacks a critical mass of these new-style apps and, even on its tablets, relies instead on classic Windows apps.
Apple, by contrast, boasts 1.3 million tablet-optimized apps for the iPad, and these could presumably easily run on a small laptop with a built-in keyboard and touchscreen. This is more than a small advantage; it's the reason people might buy this type of device instead of a traditional laptop.
I agree with the general assessments Mossberg puts forth. I also see the value in his conclusion that Apple, because of its vast and appealing app ecosystem, occupies an influential position. Consumer love for iOS apps may be a sufficient motivating factor for the masses to consciously and deliberately choose to use a laptop running those same mobile apps. That's if Apple can deliver a good mouse-and-keyboard productivity experience.
Can Apple generate interest in a laptop that runs only mobile apps?
I put forth a similar analysis in relation to Google's position if it ever decided to merge Chrome and Android. Google's 80 percent dominance of the mobile market would be a real threat to Microsoft's 90 percent dominance in PCs if Google brought a viable desktop experience to a desktop environment.
Microsoft already invented the universal app 'wheel' Apple needs
iOS apps are optimized for a slate consumption-based experience, not a peripheral-enhanced productivity setting. Mossberg stated the following in relation to this problem:
The definition of a PC, a personal computer, is already undergoing a profound change. A great laptop running the new kinds of user interfaces and apps that people now love on phones and tablets would be a big, exciting event that would help seal the deal. But there hasn't yet been a product that emphatically suggests the era of the traditional PC is fading. And it feels like an opportunity only Apple can seize.
Microsoft's Windows 10 and Universal Platform with Continuum are driving the evolution of the PC while also keeping the traditional PC around. Rather than just a clamshell laptop that runs mobile apps, which is Mossberg's vision for an evolved PC, Microsoft's strategy is more comprehensive.
Microsoft's PC vision is more comprehensive than mobile apps on a laptop.
Redmond saw the coming shift and created a device form factor with the Surface, a context-sensitive OS in Windows 10 and a Universal Platform that provides a common core for all device types and app development.
The research firm IDC said the following, confirming the success and adoption of Windows laptops and 2-in-1s in a recent report:
Consumers are just starting to graduate from old, consumption-based, slate tablets to a more productive detachable tablet. At the same time, the benefits of having a thin, touch-sensitive, productivity-based machine is [sic] shining light on the traditional PC category, causing vendors and consumers to focus on more premium devices in the Convertible and Ultraslim space.
As we watch the unfolding of Microsoft's strategy with the industry's embrace of 2-in-1s, Windows 10 laptops and PCs and Windows Mixed Reality (formerly Windows Holographic), Microsoft's impact on the evolution of the PC, in all of its forms, obviously exceeds Apple's.
Technologically, Microsoft is where Mossberg hopes Apple will get
Mossberg states, "Apple … boasts 1.3 million tablet-optimized apps for the iPad, and these could presumably easily run on a small laptop with a built-in keyboard and touchscreen." He supplies the caveat "presumably" in acknowledgment of his (and all of our) uncertainty as to the viability of iOS apps running on a small laptop with a built-in keyboard (and mouse).
iOS apps are not yet optimized for a laptop environment.
By contrast, we know with full certainty that Microsoft's unique UWP allows Windows Store apps to run on phones, laptops, 2-in-1s, HoloLens, Xbox, desktop PCs and any as yet to be created Windows devices. Most Windows 10 devices also run Win32 apps in conjunction with Store apps, and Windows 10 on ARM may bring that ability to phones.
What Mossberg speculates would be a technological advancement for the Apple ecosystem already exists in far greater depth and breadth as part of Microsoft's UWP. Mossberg's vision of an evolved PC is a laptop with iOS apps and only iOS apps.
Microsoft's personal computer vision is far broader than that.
Windows 10 is key to the modern PC
Though Windows 10 is only running on 400 million devices, Windows is a desktop and mobile platform. In less than two years, though far below it's one billion devices target, 400 million devices is impressive. iOS and Android have had roughly a decade to reach the billion mark those OSes achieved.
Windows 10 is an evolution of the OS that embraces mobile computing.
Some may argue that Windows 10 is merely an upgrade to the Windows OS that has a billion installed base. It is actually more of an evolution toward a new type of OS that retains the legacy strengths of the traditional desktop while adopting the necessary attributes of the modern, mobile personal computing environment. Universal Windows Apps, along with the coming full Windows on ARM and CShell on all types of mobile devices, help us visualize this reality.
When viewing it from that proper perspective, the unique unified desktop and mobile OS that is Windows 10 has already begun to achieve in a very real way what Mossberg anticipates will be achieved with Android and iOS: bringing a relevant "mobile" OS to a desktop clamshell form factor.
The market is buying, but may not "buy into" Microsoft's vision
The PC's transformation, based on Windows 10 2-in-1s and even laptops, has already been accepted in the market by OEMs and consumers. Mossberg's vision awaits a move from Apple to create wide acceptance for what the success of Windows 2-in-1s is already achieving: market-wide acceptance of a laptop (or 2-in-1) OS that runs mobile apps. The Windows Store on a Windows 10 desktop has thousands of universal apps that work across various form factors, including mobile.
I concede that the success of the Windows Store is not on par with Microsoft's goals. Moreover, the implementation of a Windows-based smartphone has not met commercial success. Consequently, though there are thousands of universal apps that are compatible beyond the mobility of a laptop or 2-in-1 form factor, and that work on a phone, the number is dwarfed by the number of iOS apps in the App Store.
So yes, the popularity of iOS apps, if somehow made to work as efficiently in a mouse-and-keyboard laptop form factor, would produce more of a "conscious" decision by consumers to seek out or inquire about such a device. These consumers may be motivated by a desire to use the mobile apps they're familiar with from their iPhones, on a laptop-like device.
PC consumers are likely not motivated by an opportunity to experience Store apps.
By contrast, the universal apps that are part of Microsoft's proliferating "evolving PC" vision and that are also available to users who buy Windows 10 2-in-1s and laptops are in many cases likely just "along for the ride." Candidly speaking, these user purchases are likely less motivated by the opportunity to experience universal apps and their benefits than by the productivity legacy of Window PCs, even as manifest in modern touch-enabled laptops and 2-in-1s.
The Windows Store's underperformance is likely one of the motivating factors in Microsoft's increasingly aggressive advertising efforts in Windows 10. It needs to get users that have embraced the new OS and evolving PC form-factors to also embrace the ecosystem that they exist within. Apple, with the popularity of iOS apps, but the lack of a truly universal platform akin to the UWP, and the efficient productivity environment that Windows 10 PCs bring mobile apps, would have the exact opposite challenge.
Microsoft's impact on PC evolution is both deep and broad
Ultimately, I agree with Mossberg's conclusion from a consumer perspective. That is, if Microsoft cannot draw developers and consumers to its modern app ecosystem, Apple may be more successful in drawing consumer "attention" to the concept of a mobile-app-focused laptop. That's if Apple invests in and successfully creates an iOS-based laptop, which the famously secretive company has made no indication of doing.
I do, however, believe that Mossberg may be underestimating the industry impact Microsoft's Windows 10 and UWP has had, and is currently having, on the evolution of the PC, in the form of touch-sensitive laptops, 2-in-1s and other devices like HoloLens that run universal apps.
Mossberg may be underestimating Microsoft's impact on the PC's evolution.
OEM's, consumers, businesses, and various industries have greatly embraced these "modern," evolved PCs.
As Microsoft's partners begin bringing ARM-based cellular PCs to market in several months, that impact will be even more evident than it is now. In truth, Apple's mimicry of the Surface with the iPad Pro is indicative of its reactive, or follower's role, in the PC's evolution.
The evolution is well underway. Microsoft is driving it, and its plan goes even further than Mossberg's vision of mobile apps on a laptop form factor.
Related reading:
The truth about the new iPad ads, Microsoft Surface and Windows
How the Surface changed Microsoft forever
|
/*
* mesh_gatt_cfg.c
*
* Created on: 2018��8��2��
* Author: huichen
*/
/*
* INCLUDE FILES
****************************************************************************************
*/
#include "osapp_config.h"
#ifdef OSAPP_MESH
#include "mesh_gatt_cfg.h"
///**
// ****************************************************************************************
// * @brief The Mesh Gatt att_mtu max size to peer device.
// *
// * @param[in] conn_index gatt connect index.
// *
// * @return The max gatt mtu size.
// *
// ****************************************************************************************
// */
//uint16_t mesh_gatt_get_att_mtu_size(uint16_t conn_index)
//{
//
//}
//
//
#endif /* OSAPP_MESH */
|
Friday, 7 June 2013
Avanti Polar Lipids - Super G Balance
Avanti Polar Lipids - Super G Balance
Great balance for measuring lipid stocks before doing a monolayer experiment.
Surface Tension Droplets at 2500fps - The Slow Mo Guys
Just water (with its amazing properties), a slow motion camera and two Englishmen. See what happens...
Droplet Collisions at 5000fps - The Slow Mo Guys
I love the Slow Mo guys. Showing that surface tension can be sexy!
Wednesday, 5 June 2013
Quantum model helps solve mysteries of water
Quantum model helps solve mysteries of water
These guys from the University of Edinburgh and IBM's TJ Watson Research Center are made a new model to understand the properties of water. Since there is no ultimate model but models that can reproduce certain aspects of water these scientists made a bottom up approach.
Their approach shows how a single charged particle called a 'quantum Drude oscillator' can mimic that way electrons of real water respond to their environment and fluctuate.
This simplification allows the network of hydrogen bonds and other properties like surface tension to be observed.
Tuesday, 4 June 2013
Study led by George Washington University Professor May Help Understand Freezing Bulk Water
Study led by George Washington University professor provides better understanding of water's freezing behavior at nanoscale
Bulk water verses the water at the surface. Is there a difference? And where is the boundary of this difference. These guys show that ice nucleation at the nanoscale is smaller than that of the bulk water. Water at the small scale can no longer be considered bulk water.
This has important research in climate. Clouds largely contain a lot of water. This research may answer the question of whether ice nucleation occurs within the cloud or right at the surface. Engineering may be able to control this nucleation by tuning the surface tension if the nucleation occurs on the surface of the cloud (it reminds me of Storm controlling the weather in X-Men).
Saturday, 1 June 2013
Bill Nye Teaches About Surface Tension
I remember watching Bill Nye when I was younger and learning about science. From this post from Mashable I learned that Rush Limbaugh said, '"Bill Nye is not a scientist. Bill Nye can explain to kids things like surface tension, why you can fill a glass above the rim and it won't fall over if it's just the right amount. He explains things like that, surface tension. He's not a scientist. He knows it, and everybody else knows it. Doesn't matter." Well teaching kids anything about science and having passion about it is far better than whatever bullshit Rush Limbaugh spews out of his mouth.
Personally, I would love to see Bill Nye work with Tesla or Elon Musk on the Hyperloop. Bill Nye has a degree in hydraulic engineering and works with cool space stuff. Well that is what I would say during an interview to build something called a Hyperloop.
‘Lotus effect’ paper repels oil and water
‘Lotus effect’ paper repels oil and water
Lotus leaf effect from paper can help make sustainable materials....
|
Oliviero Toscani Photographer
Every picture is a piece of the inside of ourselves”. That may be the reason why Oliviero Toscani‘s shoots strike so much the international public. The philosophy followed by the famous Italian photographer brings him to stand out, to be exceptional and totally different from an ordinary fashion photographer. The images Oliviero Toscani has signed for many fashion maisons (Benetton above all) or fashion magazines, the social campaigns he has promoted and the works he has been realising in the over 50 years of his career have made the tour around the world, bringing a piece of made-in-Italy talent to the most remote countries.
Photography was in his veins. His father was the first photo-journalist for the famous Italian newspaper “Il corriere della sera”, and Oliviero Toscani began to play with his first cameras at a very young age, soon showing the talent inherited from his father. After studying in Milan, he moved to Zurich were he attended photography and design courses at the Hochschule fur Gestaltung from 1961 to 1965.
In 1968, while Italy (like the rest of the world) was hit by the waves of the social revolution, the Italian photographer began to move his first important steps on the world of photographic films. Soon enough, Oliviero Toscani became a renowed synonim of original portraits of the contemporary social trends and movements, his camera becaming an artistic eye through which people can watch the world they lived in from an unusual perspective.
His talent caught the eye first of many important fashion magazines. From Vogue to Elle, from the Harper’s Bazaar to G.Q., the Italian photographer’s signature became to appear under more and more images printed on the glossy paper of the most famous international reviews. The popularity brought by these publications allowed Oliviero Toscani to reach the most important Italian (and international) fashion houses. Brands like Prenatal, Valentino, Fiorucci or Esprit choosed the Italian photographer as creative head for their promotional campaigns, and Toscani began to stand out for its strong and scandalous images.
The portrait of the supermodel Donna Jordan’s backside in a pair of Jesus Jeans hot pants, with the biblical phrase “Those who love me will follow me”, was just one of the first shocking advertisment campaigns realised by the Italian photographer. Many others followed, bringing the name of Oliviero Toscani to ever greater success, but the turning point came in 1982, when the Italian fashion group Benetton put its total trust on the new talent of Italian photography, leaving to him the reins of the creative division of the company.
Almost twenty years of collaboration which saw the Benetton group communication policy reach levels that any fashion maison could have reached before. Besides the simple promotion of the brand, Oliviero Toscani’s images were explicit and daring messages on problems and issues of the modern society; peace, tolerance and fight against social plagues were his main purpose, hidden behind the Benetton’s signature. Two nuns kissing, children from different ethnic groups holding hands, a Vietnam war’s victim cemetery, a boy dying from AIDS or a man killed by mafia. These were just a few of the most famous images that brough the Italian photographer, as well as the Italian fashion brand, to reach popularity and fame also through their social commitment.
Even after leaving the Benetton brand, Oliviero Toscani continued to shock the world with his works. One popular example is the anti-anorexia campaign that saw the too-thin model Isabelle Carol pose totally naked showing her body worn out by the disease, which history was documented in the film “Anorexia, storia di un’immagine”. The giant posters spreaded all over Milan and the other main Italian cities did not only conquered the favours of the anti-anorexia movements, but were also condemned by some people who didn’t appreciate the Italian photographer’s strong images. For that same reason, sometimes Oliviero Toscani has had to face critics and censorship, for the rawness of his images, printed as well as in TV spots.
The Italian photographer indeed has worked not only with his camera, but also using the other promotional medias, from TV to the internet. He helped realising many TV spots, ever so strong as his photos, and the Benetton group website’s birth saw his precious collaboration. The signature of Oliviero Toscani was so present in the fashion group that he even realised sportswear lines for Playlife, one the brands under the Benetton label.
In 1990, Oliviero Toscani, with the collaboration of the American graphic designer Tibor Kalman, co-founded the magazine Colors, owned partly by Benetton. “A magazine about the rest of the world”, this was the tagline of the magazine, which perfectly describes the multicultural publication. Under the supervision of the Italian fashion group, he also set up Fabrica, the Benetton Group Communications research center, in 1994. Not an academy nor a simple school, Fabrica is defined as a laboratory of creativity, where new and winning ideas come to life, changing the communication and media’s world.
The collaboration with the Italian maison, as well as the many and many other works that have marked his long career, have gained Oliviero Toscani many prizes, among which we can find the Grand Prix d’Affichage, or the Grand Prix Unesco, and even the Leone d’Oro, the award given at the Festival of Cannes, in 1989. His works were shown in the most important location, from the Biennale of Venezia, to the Triennale Museum of Milan, or even in exhibitions held all over the globe, from Brazil to Europe. The world of Italian photography even recognised him a professorship in the Roman University of La Sapienza, where he taught communication strategies to young and curious students.
His life has changed a lot, but his passion for photography has never abandoned him. Nowadays, besides portraiting the Appaloosa horses he breeds in his Tuscany’s estate, where he lives with his wife and three children producing wine and olive oil, he keeps on surprising the whole world with his innovative idead that have changed and revolutioned the concept of photography. (via)
|
Tuesday, May 11, 2010
A discussion thread had to do with why we pantheists call ourselves pantheists. My reply follows:
The consciousness that rides along within and is generated by the activities of the brain that calls itself I, since it is the slave of biology and physiology, interacts strangely with these attempts or any institution's attempts to use the language of consciousness to define what consciousness, carried along by the body's activities, finds itself being and thinking from day to day.
I call myself pantheist because the brain that calls itself I and that carries the I of me along with it is deeply enmeshed in the biology and physiology of the airy reality into which it found itself swimming (existing). The collective brains who make up the category "scientist" have physically interacted with the Cosmos in such a way as to give other brains, through the senses of their eyes (reading) and ears (hearing), a new kind of information about that reality. The brain that calls itself I has learned from this set of scientific brains (who form opinions, expressed mathematically, only after by materially testing the physical Universe) that it is not enough to trust language, the creator of consciousness, and, thus, does not accept any reality that exists solely within the language and which is not physically present (so as to be sensed) in the material Cosmos. Thus concepts like "god" which exist only in the realm of the untrustworthy consciousness and which can't be smelt, touched, sensed by the physical body are foreign to it (the brain that calls itself I). The brain that calls itself I and finds itself afloat in air like a fish in water knows itself as a part of the physical Universe and not part of the conscious Cosmos.
If "MY" speechless physical body has any relationship with the physical Universe, it is much like a zygote to a mother's body than it is a consciousness to a higher consciousness which language has made up totally and completely. Since it is my speechless body that exists in the Cosmos and "I" am the language it is hearing as thought, it/I am completely and totally dependent on the physical Cosmos for my continued existence. And since a speechless zygote can't worship it's source, so my body can't worship the Cosmos, except through hearing itself in the thoughts that are generated within its synaptic patterns by its daily efforts to procreate, win friends, have sex with the opposite sex, surround itself with comfort and surplus, et cetera.
Sometimes the body that experiences its own self in consciousness as I will sense itself so safe for a moment in the Cosmos that a wonderful feeling of well-being (i.e. flood of dopamine or other chemical) fills it and that feeling will generate a thought to explain to itself what it's feeling and that thought is "worship".
The previous philosophical notations have made me understand something very interesting to me—the human robot (i.e. animal) through consciousness (the naming with words of the outer reality) has been returning from the naming of the outer world back to the naming of itself, to its physical reality as a robot that is experiencing and responding to the physical Cosmos. The namer is discovering the silent source of its naming function and, perhaps, someday the namer and the named will become as one.
Anyway, that's why I (or the brain that names itself I) name myself "pantheist" for this moment in time. It's purely an emotional thing, separate from all the conscious quibbling that goes on in the insubstantial world of consciousness where disagreements about naming are common.
No comments:
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include "IECore/Group.h"
#include "IECore/Renderer.h"
#include "IECore/AttributeBlock.h"
#include "IECore/AttributeState.h"
#include "IECore/MurmurHash.h"
#include "OpenEXR/ImathBoxAlgo.h"
#include "boost/format.hpp"
#include "boost/lexical_cast.hpp"
using namespace IECore;
using namespace std;
using namespace Imath;
static IndexedIO::EntryID g_transformEntry("transform");
static IndexedIO::EntryID g_stateEntry("state");
static IndexedIO::EntryID g_childrenEntry("children");
const unsigned int Group::m_ioVersion = 0;
IE_CORE_DEFINEOBJECTTYPEDESCRIPTION( Group );
Group::Group()
: m_transform( 0 ), m_parent( 0 )
{
}
Group::~Group()
{
clearChildren();
}
Transform *Group::getTransform()
{
return m_transform.get();
}
const Transform *Group::getTransform() const
{
return m_transform.get();
}
void Group::setTransform( TransformPtr transform )
{
m_transform = transform;
}
Imath::M44f Group::transformMatrix( float time ) const
{
ConstTransformPtr t = getTransform();
if( t )
{
return t->transform( time );
}
return Imath::M44f(); // identity
}
Imath::M44f Group::globalTransformMatrix( float time ) const
{
if( m_parent )
{
return transformMatrix( time ) * m_parent->globalTransformMatrix( time );
}
return transformMatrix( time );
}
void Group::addState( StateRenderablePtr state )
{
if( !state )
{
throw InvalidArgumentException( "Cannot add null state object." );
}
if( state->isInstanceOf( Transform::staticTypeId() ) )
{
throw Exception( "Transforms cannot be added as state." );
}
m_state.push_back( state );
}
void Group::removeState( StateRenderablePtr state )
{
StateContainer::iterator it = find( m_state.begin(), m_state.end(), state );
if( it==m_state.end() )
{
throw Exception( "State not present in Group" );
}
m_state.erase( it );
}
void Group::clearState()
{
m_state.clear();
}
const Group::StateContainer &Group::state() const
{
return m_state;
}
const Data *Group::getAttribute( const std::string &name ) const
{
StateContainer::const_reverse_iterator it = m_state.rbegin();
for( ; it != m_state.rend(); ++it )
{
if( ConstAttributeStatePtr attr = runTimeCast< const AttributeState >( *it ) )
{
CompoundDataMap::const_iterator attrIt = attr->attributes().find( name );
if( attrIt != attr->attributes().end() )
{
return attrIt->second.get();
}
}
}
if( m_parent )
{
return m_parent->getAttribute( name );
}
return 0;
}
void Group::setAttribute( const std::string &name, ConstDataPtr value )
{
// find existing attribute/override it ?
StateContainer::iterator it = m_state.begin();
AttributeStatePtr attrFound;
for( ; it != m_state.end(); ++it )
{
if( AttributeStatePtr attr = runTimeCast< AttributeState >( *it ) )
{
attrFound = attr;
CompoundDataMap::iterator attrIt = attr->attributes().find( name );
if( attrIt != attr->attributes().end() )
{
attr->attributes()[ name ] = value->copy();
return;
}
}
}
if( !attrFound )
{
attrFound = new AttributeState;
addState( attrFound );
}
attrFound->attributes()[ name ] = value->copy();
}
void Group::addChild( VisibleRenderablePtr child )
{
if( !child )
{
throw InvalidArgumentException( "Cannot add null child object." );
}
GroupPtr gChild = runTimeCast<Group>( child );
if( gChild )
{
GroupPtr gChildParent = gChild->parent();
if( gChildParent )
{
gChildParent->removeChild( gChild );
}
gChild->m_parent = this;
}
m_children.push_back( child );
}
void Group::removeChild( VisibleRenderablePtr child )
{
ChildContainer::iterator it = find( m_children.begin(), m_children.end(), child );
if( it==m_children.end() )
{
throw Exception( "Child is not a member of Group" );
}
GroupPtr gChild = runTimeCast<Group>( child );
if( gChild )
{
gChild->m_parent = 0;
}
m_children.erase( it );
}
void Group::clearChildren()
{
while( m_children.size() )
{
removeChild( m_children[0] );
}
}
const Group::ChildContainer &Group::children() const
{
return m_children;
}
Group *Group::parent()
{
return m_parent;
}
const Group *Group::parent() const
{
return m_parent;
}
void Group::copyFrom( const Object *other, CopyContext *context )
{
VisibleRenderable::copyFrom( other, context );
const Group *tOther = static_cast<const Group *>( other );
if( tOther->m_transform )
{
m_transform = context->copy<Transform>( tOther->m_transform.get() );
}
else
{
m_transform = 0;
}
clearState();
for( StateContainer::const_iterator it=tOther->state().begin(); it!=tOther->state().end(); it++ )
{
addState( context->copy<StateRenderable>( it->get() ) );
}
clearChildren();
for( ChildContainer::const_iterator it=tOther->children().begin(); it!=tOther->children().end(); it++ )
{
addChild( context->copy<VisibleRenderable>( it->get() ) );
}
}
void Group::save( SaveContext *context ) const
{
VisibleRenderable::save( context );
IndexedIOPtr container = context->container( staticTypeName(), m_ioVersion );
if( m_transform )
{
context->save( m_transform.get(), container.get(), g_transformEntry );
}
IndexedIOPtr stateContainer = container->subdirectory( g_stateEntry, IndexedIO::CreateIfMissing );
int i = 0;
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
string name = str( boost::format( "%d" ) % i );
context->save( it->get(), stateContainer.get(), name );
i++;
}
IndexedIOPtr childrenContainer = container->subdirectory( g_childrenEntry, IndexedIO::CreateIfMissing );
i = 0;
for( ChildContainer::const_iterator it = children().begin(); it!=children().end(); it++ )
{
string name = str( boost::format( "%d" ) % i );
context->save( it->get(), childrenContainer.get(), name );
i++;
}
}
bool Group::entryListCompare( const IndexedIO::EntryID& a, const IndexedIO::EntryID& b )
{
int a_idx( 0 );
int b_idx( 0 );
try
{
a_idx = boost::lexical_cast<int>( a.value() );
}
catch (...)
{
}
try
{
b_idx = boost::lexical_cast<int>( b.value() );
}
catch (...)
{
}
return a_idx < b_idx;
}
void Group::load( LoadContextPtr context )
{
VisibleRenderable::load( context );
unsigned int v = m_ioVersion;
ConstIndexedIOPtr container = context->container( staticTypeName(), v );
m_transform = 0;
try
{
m_transform = context->load<Transform>( container.get(), g_transformEntry );
}
catch( ... )
{
}
clearState();
ConstIndexedIOPtr stateContainer = container->subdirectory( g_stateEntry );
IndexedIO::EntryIDList l;
stateContainer->entryIds( l );
sort( l.begin(), l.end(), entryListCompare );
for( IndexedIO::EntryIDList::const_iterator it=l.begin(); it!=l.end(); it++ )
{
addState( context->load<StateRenderable>( stateContainer.get(), *it ) );
}
clearChildren();
ConstIndexedIOPtr childrenContainer = container->subdirectory( g_childrenEntry );
childrenContainer->entryIds( l );
sort( l.begin(), l.end(), entryListCompare );
for( IndexedIO::EntryIDList::const_iterator it=l.begin(); it!=l.end(); it++ )
{
addChild( context->load<VisibleRenderable>( childrenContainer.get(), *it ) );
}
}
bool Group::isEqualTo( const Object *other ) const
{
if( !VisibleRenderable::isEqualTo( other ) )
{
return false;
}
const Group *tOther = static_cast<const Group *>( other );
// check transform
if( (bool)m_transform != (bool)tOther->m_transform )
{
return false;
}
if( m_transform && !tOther->m_transform->isEqualTo( m_transform.get() ) )
{
return false;
}
// check state
if( m_state.size()!=tOther->m_state.size() )
{
return false;
}
for( size_t i=0; i<m_state.size(); i++ )
{
if( !m_state[i]->isEqualTo( tOther->m_state[i].get() ) )
{
return false;
}
}
// check children
if( m_children.size()!=tOther->m_children.size() )
{
return false;
}
for( size_t i=0; i<m_children.size(); i++ )
{
if( !m_children[i]->isEqualTo( tOther->m_children[i].get() ) )
{
return false;
}
}
return true;
}
void Group::memoryUsage( Object::MemoryAccumulator &a ) const
{
VisibleRenderable::memoryUsage( a );
if( m_transform )
{
a.accumulate( m_transform.get() );
}
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
a.accumulate( it->get() );
}
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
a.accumulate( it->get() );
}
}
void Group::hash( MurmurHash &h ) const
{
VisibleRenderable::hash( h );
if( m_transform )
{
m_transform->hash( h );
}
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
(*it)->hash( h );
}
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
(*it)->hash( h );
}
}
void Group::render( Renderer *renderer ) const
{
render( renderer, true );
}
void Group::render( Renderer *renderer, bool inAttributeBlock ) const
{
/// \todo I wonder if this should just use a transform block if
/// the Group doesn't have any state?
AttributeBlock attributeBlock( renderer, inAttributeBlock );
if( m_transform )
{
m_transform->render( renderer );
}
renderState( renderer );
renderChildren( renderer );
}
void Group::renderState( Renderer *renderer ) const
{
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
(*it)->render( renderer );
}
}
void Group::renderChildren( Renderer *renderer ) const
{
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
(*it)->render( renderer );
}
}
Imath::Box3f Group::bound() const
{
Box3f result;
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
result.extendBy( (*it)->bound() );
}
return transform( result, transformMatrix() );
}
|
LANs to WANs(c) The Complete Management Guide
Authors: Muller N.J.
Published year: 2003
|< Day Day Up >|
Depending on the situation facing network managers, bridges can be used to either extend or segment LANs. At one level, bridges can be used for segmenting LANs into smaller subnets to improve performance, control access, and facilitate fault isolation and testing without impacting the overall user population. At another level, they are used to create an extended network that greatly expands the number of devices that can be supported and the services available to each user . Bridges may even offer additional features such as data compression, which has the effect of providing greater throughput over low-speed lines. Compression ratios of 2:1 all the way down to 6:1 may be selected by the network manager, depending on what the vendor offers with a specific product.
As noted, bridging occurs at the data link layer (see Figure 5.1), which provides physical addressing, manages access to the physical medium, controls data flow, and handles transmission errors. Bridges analyze incoming frames, make forwarding decisions based on the source and destination addresses of those frames, and then forward the frames to their destinations. Sometimes, as in source-route bridging, the frame contains the entire path to the destination. In other cases, as in transparent bridging, frames are forwarded one hop at a time toward the destination.
Figure 5.1: Bridge functionality in reference to the OSI model.
Bridges can be either local or remote. Local bridges provide direct connections between many LAN segments in the same area. Remote bridges connect LAN segments in different areas, usually over telecommunication lines. There are several kinds of bridging and all may be supported in the same device:
Transparent bridging —used mostly in Ethernet environments that have the same media types, these bridges keep a table of destination addresses and outbound interfaces.
Source-route bridging —used mostly in token-ring environments, these bridges only forward frames based on the routing indicator contained in the frame. End stations are responsible for determining and maintaining the table of destination addresses and routing indicators.
Translation bridging —used to bridge data between different media types, these devices typically go between Ethernet and FDDI or token ring to Ethernet.
Source-route translation bridging —this is a combination of source-route bridging and transparent bridging that allows communication in mixed Ethernet and token-ring environments. (Translation bridging without routing indicators between token ring and Ethernet is also called source-route transparent bridging.)
The engine for transparent bridging is the spanning tree algorithm (STA), which dynamically discovers a loop-free subset of the network’s topology. The STA accomplishes this by placing active bridge ports that create loops into a standby or blocked condition. A blocked port can provide redundancy in that if the primary port fails, it can be activated to take the traffic load.
The spanning tree calculation is triggered when the bridge is powered up and whenever a change in topology is detected . A topology change might occur when a forwarding port is going down (blocking) or when a port transitions to forwarding and the bridge has a designated port, which also indicates that the bridge is not standalone. Configuration messages known as bridge protocol data units (BPDUs) actually trigger the spanning tree calculation. These messages are exchanged between bridges at regular intervals set by the network manager, usually 1 to 4 seconds.
Once a change in topology is detected, this information must be shared with all bridges on the network. This is a two-step process that starts when a bridge notifies the root bridge of the spanning tree by sending it a special BPDU known as a topology change notification (TCN). The bridge sends the TCN out over its root port. The root bridge acknowledges the message by sending back a normal configuration BPDU with the topology change acknowledgment (TCA) bit set. The second step in the topology update process entails the root bridge sending out configuration BPDUs with the topology change (TC) bit set. These BPDUs are relayed by every bridge, so they can become aware of the changed topology.
There are some problems associated with spanning tree. The more hosts on the network, the higher the probability of topology changes. For example, a directly attached host, such as a client or server, will trigger a topology change when powered off, then go on to clear an operating system problem. In a large, flat network, the point can be reached when it is continually in topology change status. The resulting high level of flooding can lead to an unstable STP environment. To deal with this problem, vendors have come up with ways to avoid TCN generation for certain events. For example, the network manager can configure the bridge so that it issues a TCN when a server is power cycled, but not when client devices are power cycled. If a bridge port going up or down is not deemed an important event, this event too can be programmed not to issue a TCN.
Source-route bridging (SRB) is used in the token-ring environment as the method by which a station establishes a route through a multiple-ring network to its destination. The first step for a station to reach another is to create a packet called an explorer. This packet is copied by all bridges in the network, with each of them adding information about itself before passing it on. The explorer packet’s routing information field (RIF) contains the information of where it has traversed through the network and within the RIF; a route descriptor stores the path it has taken through the network.
As the explorer packet is constructed on its way through the network, the destination station will start receiving data packets from the originating station. Based on the contents of the explorer packet, the destination station will then decide which route to use to send data packets back to the originating station. Or it will send its own explorer packet so that the originating station can determine its own route.
The explorer packet is limited in terms of how many rings it can hold in the routing information field. Although the RIF can hold a total of 14 rings, IBM long ago limited this to seven. Other vendors also adopted this limitation. Consequently, an explorer packet that has traversed seven rings will be dropped in the network. To control traffic in the network with more precision, parameters can be set in the bridge to decrease this number even further, so that packets that reach X number of rings (any number below seven) will be dropped.
While explorers are limited to traversing only seven rings, in a meshed ring environment, one explorer can finish being copied by many bridges, which can cause too many explorers. Explorer storms can be prevented in redundant network topologies by setting the bridge to filter out explorers that have already been forwarded once. Since explorer traffic can be distinguished from regular source route traffic, the network manager can issue commands that check the bridge for various parameters, such as the number of explorers that were dropped outbound on that interface.
While Ethernet has become the network of choice for new installations, there is still a good amount of token ring in use, making it necessary to mix the two environments for data exchange. Doing so is complicated because some very fundamental differences between Ethernet and token ring must be reconciled. Token ring has functional addresses, while Ethernet primarily relies on broadcasts.
Furthermore, MAC addresses on the Ethernet are different from MAC addresses on the token ring. Ethernet does not have a source-route bridging capability and token ring has a routing information field. Finally, token ring and Ethernet use different methods to read the bits into their adapters.
To unify the two environments, vendors have come up with various methods such as translation bridging. This is a type of bridging that is implemented on networks that use different MAC sublayer protocols, providing a method of resolving differences in header formats and protocol specifications. Since there are no real standards in how communication between two media types should occur, however, no single translation implementation can be called correct. The only consideration for network managers is to select a method of translation and implement it uniformly throughout the network.
Essentially, the bridges reorder source and destination address bits when translating between Ethernet and token-ring frame formats. The problem of embedded MAC-addresses can be resolved by programming the bridge to look for various types of MAC addresses. Some translation-bridges simply check for the most popular embedded addresses. If others are used, the bridge must be programmed to look for them as well. But if translation-bridging software runs in a multi-protocol router, which is very common today, these protocols can be routed and the problem avoided entirely.
Token ring’s RIF field has a component that indicates the largest frame size that can be accepted by a particular source-route bridging implementation. Translation bridges that send frames from the transparent-bridging domain to the SRB domain usually set the maximum transfer unit (MTU) field to 1,500 bytes to limit the size of token-ring frames entering the transparent-bridging domain, because this is the maximum size of Ethernet frames. Some hosts cannot process this field correctly, in which case translation bridges are forced to drop the frames that exceed Ethernet’s MTU size.
Bits representing token-ring functions that are absent in Ethernet are discarded by translation bridges. For example, token ring’s priority, reservation, and monitor bits are discarded during translation. And token ring’s frame status bits are treated differently, depending on the bridge manufacturer; the products of some manufacturers may even ignore these bits.
Sometimes, the bridge will have the C bit set, indicating that the frame has been copied, but not the A bit set, indicating that the destination station recognizes the address. In the former case, a token-ring source node determines if the frame it sent has become lost. Advocates of this approach claim that reliability mechanisms, such as the tracking of lost frames, are better left for implementation in Layer 4 of the OSI model. Advocates of setting the C bit argue that this bit must be set to track lost frames, but that the A bit cannot be set because the bridge is not the final destination.
Translation bridges also can be used to create a software gateway between the token ring and Ethernet domains. To the SRB end stations, the translation bridge has a ring number and a bridge number associated with it, so it looks like a standard source-route bridge. In this case, the ring number reflects the entire transparent-bridging domain. To the transparent-bridging domain, the translation bridge is just another transparent bridge.
When bridging from the SRB domain to the transparent-bridging domain, SRB information is removed. Token ring’s routing information fields usually are cached for use by any subsequent return traffic. When bridging from the transparent bridging to the SRB domain, the translation bridge checks the frame to see if it has a multicast or unicast destination. If the frame has a multicast or broadcast destination, it is sent into the SRB domain as a spanning-tree explorer. If the frame has a unicast address, the translation bridge looks up the destination in the RIF cache. If a path is found, it is used and the RIF information is added to the frame; otherwise , the frame is sent as a spanning-tree explorer.
Another solution to unify the Ethernet and token-ring environments is source-route translation bridging (SRTLB). This entails the addition of bridge groups to the interfaces of both the token ring and Ethernet bridges to create a transparent bridge domain between the two environments. The bridges at each end are responsible for establishing the path through the network. When a bridge on a token ring receives a packet from an Ethernet, for example, path establishment is handled as follows (see Figure 5.2):
Figure 5.2: Source-route translation bridging, from token ring to Ethernet.
Bridge-1 receives a packet from the Ethernet. This is from PC-1 to the host.
Bridge-1 needs a RIF to reach the host, so it creates an explorer to learn the path to reach the host.
After Bridge-1 receives the response, it sends the response (without a RIF) to the Ethernet station.
PC-1 sends an exchange identifier (XID) to the host MAC address.
Bridge-1 gets the Ethernet packet, attaches the RIF to the host, and sends the packet on its way.
As far as the host is concerned , the Ethernet is sitting on a pseudo ring. This is configured with the source-bridge transparent command on the bridge. The pseudo ring makes the host treat the Ethernet as if it were a token ring.
|< Day Day Up >|
LANs to WANs(c) The Complete Management Guide
Authors: Muller N.J.
Published year: 2003
|
Skip to content Skip to navigation
Lesbian Historic Motif Project: #110e Borris 2004 - Same-Sex Desire in the English Renaissance (Chapter 5)
Full citation:
Publication summary:
Chapter 5: Physiognomics
Anyone who has participated in a palm-reading has taken part in the pseudo-science of physiognomy. For that matter, statistical studies attributing a wide variety of psychological and behavioral traits (including sexual orientation) to the ratio of lengths of the index and ring fingers are operating within the realm of physiognomy. The two excerpts below that specifically mention sexual desire between women touch on only a few aspects of the field. It is interesting to note how fuzzy the line is between supposed cause and effect. In the description of Fracassa, her "manly" personality is considered to be signaled by the shape of her head and her lower limbs, but are behavioral traits (such as gait and posture) or activities (such as jousting in armor) considered to be a further consequence of that "manly personality" or are they, too, simply outward signifiers by which one may determine her "nature"? That is, does she joust because she's manly, or is she manly because she jousts?
* * *
We have not entirely managed to shed the idea that an individual’s habitual predispositions are reflected in their physical features. The Greek pseudo-Aristotelian Physiognomics is one of the foundational treatises that systematized this view. References to female homoeroticism (as opposed to male references) in the context of physiognomy are rare and primarily appear in texts derived from an anonymous Latin treatise of the 4th century.
Bartolommeo della Rocca (1467-1504) in a section on chiromancy (interpreting the hands) discusses how to interpret “signs of morally offensive lust on the hands of a woman”. The discussion groups together a wide variety of sexual behaviors, from incest, to women taking an active role with men, to any sexual activity by nuns, to masturbation, to bestiality. But the discussion specifically notes, “Note also that in women ‘morally offensive lust’ can be understood when women come together vulva to vulva and rub one another, of which Juvenal writes in this verse: ‘They ride one another, turn and turn about, and disport themselves for the Moon to witness.’ And such women are called by the ancient term tribades. It is said that Sappho, the Lesbian lass and poet, amused herself with this kind of lust.”
In a section primarily discussing characteristics of hair, della Rocca provides a detailed description of a “manly woman” both in terms of physical appearance and behavior (though sexual activity is not specifically mentioned). “By many outward signs may a man find out the qualities of the mind and courage. As when a woman is apparelled and decked in man’s apparel, which doth then declare her nature to draw near to man’s. As the like did that woman of courage named Fracassa, who commonly used to wear (by the report of the Physiognomer [i.e., Rocca himself]) man’s apparel, and would upon a bravery many times arm herself at all points to joust and run sundry times so armed at the ring. The form of which woman...was on this wise: she had a small head, and Pineaple-like, a neck comely formed, large breasted, seemly arms, answering to the body. But in her other parts, as in the hips, buttocks, thighs, and legs, near agreeing to man’s. This manly woman also walked upright in body, treading light on the ground, and bearing her head playing like to the Hart. The other notes of this woman did the Physiognomer for brevity sake here omit. Yet he thus concludeth that by the sundry notes which he viewed, she was prone to come to a violent death...”
Time period:
Add new comment
|
Cancer Fighting Foods/Spices
The National Cancer Institute estimates that roughly one-third of all cancer deaths may be diet related. What you eat can hurt you, but it can also help you. Many of the common foods found in grocery stores or organic markets contain cancer-fighting properties, from the antioxidants that neutralize the damage caused by free radicals to the powerful phytochemicals that scientists are just beginning to explore. There isn’t a single element in a particular food that does all the work: The best thing to do is eat a variety of foods.
The following foods have the ability to help stave off cancer and some can even help inhibit cancer cell growth or reduce tumor size.
Avocados are rich in glutathione, a powerful antioxidant that attacks free radicals in the body by blocking intestinal absorption of certain fats. They also supply even more potassium than bananas and are a strong source of beta-carotene. Scientists also believe that avocados may also be useful in treating viral hepatitis (a cause of liver cancer), as well as other sources of liver damage.
Broccoli, cabbage, and cauliflower have a chemical component called indole-3-carbinol that can combat breast cancer by converting a cancer-promoting estrogen into a more protective variety. Broccoli, especially sprouts, also have the phytochemical sulforaphane, a product of glucoraphanin – believed to aid in preventing some types of cancer, like colon and rectal cancer. Sulforaphane induces the production of certain enzymes that can deactivate free radicals and carcinogens. The enzymes have been shown to inhibit the growth of tumors in laboratory animals. However, be aware that the Agriculture Department studied 71 types of broccoli plants and found a 30-fold difference in the amounts of glucoraphanin. It appears that the more bitter the broccoli is, the more glucoraphanin it has. Broccoli sprouts have been developed under the trade name BroccoSprouts that have a consistent level of sulforaphane – as much as 20 times higher than the levels found in mature heads of broccoli.
Carrots contain a lot of beta carotene, which may help reduce a wide range of cancers including lung, mouth, throat, stomach, intestine, bladder, prostate and breast. Some research indicated beta carotene may actually cause cancer, but this has not proven that eating carrots, unless in very large quantities – 2 to 3 kilos a day, can cause cancer. In fact, a substance called falcarinol that is found in carrots has been found to reduce the risk of cancer, according to researchers at Danish Institute of Agricultural Sciences (DIAS). Kirsten Brandt, head of the research department, explained that isolated cancer cells grow more slowly when exposed to falcarinol. This substance is a polyacethylen, however, so it is important not to cook the carrots.
Chili peppers and jalapenos contain a chemical, capsaicin, which may neutralize certain cancer-causing substances (nitrosamines) and may help prevent cancers such as stomach cancer.
November 20, 2008 at 3:27 pm
Maybe you should be eating more beets, left, or chopped cabbage. (Credit: Evan Sung for The New York Times, left
Nutritionist and author Jonny Bowden has created several lists of healthful foods people should be eating but aren’t. But some of his favorites, like purslane, guava and goji berries, aren’t always available at regular grocery stores. I asked Dr. Bowden, author of “The 150 Healthiest Foods on Earth,” to update his list with some favorite foods that are easy to find but don’t always find their way into our shopping carts. Here’s his advice.
- Beets: Think of beets as red spinach, Dr. Bowden said, because they are a rich source of folate as well as natural red pigments that may be cancer fighters.
How to eat: Fresh, raw and grated to make a salad. Heating decreases the antioxidant power.
- Cabbage: Loaded with nutrients like sulforaphane, a chemical said to boost cancer-fighting enzymes.
How to eat: Asian-style slaw or as a crunchy topping on burgers and sandwiches.
- Swiss chard: A leafy green vegetable packed with carotenoids that protect aging eyes.
How to eat it: Chop and saute in olive oil.
- Cinnamon: Helps control blood sugar and cholesterol.
How to eat it: Sprinkle on coffee or oatmeal.
- Pomegranate juice: Appears to lower blood pressure and loaded with antioxidants.
How to eat: Just drink it.
- Dried plums: Okay, so they are really prunes, but packed with cancer-fighting antioxidants.
How to eat: Wrapped in prosciutto and baked.
- Pumpkin seeds: The most nutritious part of the pumpkin and packed with magnesium; high levels of the mineral are associated with lower risk for early death.
How to eat: Roasted as a snack, or sprinkled on salad.
- Sardines: Dr. Bowden calls them “health food in a can.’’ They are high in omega-3’s, contain virtually no mercury and are loaded with calcium. They also contain iron, magnesium, phosphorus, potassium, zinc, copper and manganese as well as a full complement of B vitamins.
How to eat: Choose sardines packed in olive or sardine oil. Eat plain, mixed with salad, on toast, or mashed with dijon mustard and onions as a spread.
- Turmeric: The “superstar of spices,’’ it has anti-inflammatory and anti-cancer properties.
How to eat: Mix with scrambled eggs or in any vegetable dish.
- Frozen blueberries: Even though freezing can degrade some of the nutrients in fruits and vegetables, frozen blueberries are available year-round and don’t spoil; associated with better memory in animal studies.
How to eat: Blended with yogurt or chocolate soy milk and sprinkled with crushed almonds.
- Canned pumpkin: A low-calorie vegetable that is high in fiber and immune-stimulating vitamin A; fills you up on very few calories.
How to eat: Mix with a little butter, cinnamon and nutmeg.
You can find more details and recipes on the Men’s Health Web site, which published the original version of the list last year.
In my own house, I only have two of these items — pumpkin seeds, which I often roast and put on salads, and frozen blueberries, which I mix with milk, yogurt and other fruits for morning smoothies. How about you? Have any of these foods found their way into your shopping cart?
Courtesy: New York Times
July 1, 2008 at 9:06 am
|
//
// MDNotification.h
// Medable
//
// Copyright (c) 2014 Medable. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MDNotificationManager.h"
#import "MDBaseInstance.h"
@class MDObjectId;
@class MDReference;
NS_ASSUME_NONNULL_BEGIN
/**
* Notifications are created as a result of modifications to contexts, posts and comment begin created or edited,
* invitations to connect and context ownership transfer requests.
* An Organization can setup an app for Apple Push Notification Service (APNs), and users can set preferences for
* how to receive notifications, through APNs or via email.
*
* Notifications are automatically cleared for posts and comments when they are retrieved using the API. Otherwise,
* clients should manually clear them using the notifications API.
*/
@interface MDNotification : MDBaseInstance
/**
* The context for which the notification was created.
*/
@property (nonatomic, readonly) MDReference* context;
/**
* Enumeration of the context the notification belongs to. Should only be used for default classes and not custom ones.
*/
@property (nonatomic, readonly) MDNotificationContext contextEnumerated;
/**
* Type-specific metadata
*/
@property (nonatomic, readonly) NSDictionary* meta;
/**
* Notification Type.
*/
@property (nonatomic, readonly) MDObjectId* type;
/**
* Type enumeration.
*
* @see MDNotificationType
*/
@property (nonatomic, readonly) MDNotificationType typeEnumerated;
/**
* Returns the ObjectId representing the type of notification.
*
* @param type type of notification
*
* @return MDObjectId representing the type of notification.
*/
+ (MDObjectId*)typeIdWithType:(MDNotificationType)type;
// unavailable
+ (instancetype)new NS_UNAVAILABLE;
// unavailable init
- (instancetype)init NS_UNAVAILABLE;
/**
* Create a new notification object from a received notification.
*
* @param attributes Notification information, as received.
*
* @return Instance representing the received notification.
*/
- (instancetype)initWithAttributes:(nonnull NSDictionary*)attributes;
@end
NS_ASSUME_NONNULL_END
|
/* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#ifndef _PIIPISOOPERATION_H
#define _PIIPISOOPERATION_H
#include <PiiDefaultOperation.h>
#include <QVector>
/**
* A parallel-to-serial converter. In the default non-grouped state,
* PiiPisoOperation outputs whatever it receives in any of its inputs
* to its single output. If [groupSize] is one, a PISO works like a
* multiplexer. A PISO is commonly useful in situations where multiple
* data sources feed data into one processing pipeline. The operation
* allows flexible control of input groups to redirect many
* synchronized input streams at once.
*
* If [groupSize] is greater than one, inputs are divided into
* synchronized groups. Input sockets from zero to `groupSize` - 1
* will form the first group, sockets from `groupSize` to 2 *
* `groupSize` - 1 the second one and so on. Every socket in a group
* must contain an object before it is processed. Whenever this
* happens, all objects will be simultaneously sent to the
* corresponding outputs. The first input in a group will be sent to
* `output0` and so on. If an input socket in a group has not been
* connected, there must be a [default value](defaultValues) for
* it.
*
*
* Configuring default values
* --------------------------
*
* A list of PiiVariant objects that will be used if a socket in a
* group is not connected. The first element in the list is the
* default value for the first input, or the first input in each
* group, depending on the value of [defaultValueMode]. The second
* element is the value for the second input and so on. An invalid
* PiiVariant means no default value. Input sockets with a valid
* default value will be marked optional. Default values have no
* effect if [groupSize] is one.
*
* ~~~(c++)
* PiiOperation* op = engine.createOperation("PiiPisoOperation");
* op->setProperty("groupSize", 2);
* op->setProperty("inputCount", 4);
* // No default value for first input in each group.
* // The default value for the second input is int(0)
* op->setProperty("defaultValues", PiiVariantList() << PiiVariant() << PiiVariant(0));
* ~~~
*
* You can configure also the one default value with property map
* (QVariantMap). Recognized property values are:
*
* - `index` - the index of the input to configure. (int, default
* value 0)
*
* - `defaultValue` - a PiiVariant object that will be used if the
* corresponding input is not connected.
*
* ~~~(c++)
* // Create a new piso
* PiiOperation* piso = engine.createOperation("PiiPisoOperation");
* piso->setProperty("groupSize", 2);
* piso->setProperty("dynamicInputCount", 4);
*
* QVariantMap props;
* props["index"] = 1;
* props["defaultValue"] = Pii::createQVariant(0);
* piso->setProperty("defaultValue", props);
* ~~~
*
* The default number of inputs is two.
*
* Inputs
* ------
*
* @in inputX - any number of input sockets that accept any object
* type. X ranges from 0 to `inputCount` - 1.
*
* @in groupX inputY - alias for input number X * [groupSize] + Y. If
* [groupSize] is 3, `group1` `input1` is an alias for `input4`.
*
* At least one of the inputs must be connected. If any of the inputs
* in a synchronous input group are connected, then all of them must
* either be connected or have a default value assigned.
*
* Outputs
* -------
*
* @out index - the index of the input group the object was or objects
* were received in. If [groupSize] is one (the default), the group
* index equals the index of the input socket.
*
* @out output - alias for output0. Emits the object received from any
* of the inputs. Objects are emitted in the order they are received.
*
* @out outputX - synchronous outputs, if [groupSize] is greater than
* one. X ranges from 0 to [groupSize]-1. Whenever all sockets in a
* synchronous group contain an object, the objects will be
* simultaneously sent to the corresponding outputs. That is,
* `groupX` `input0` will be redirected to `output0`, `groupX`
* `input1` to `input` 1 etc.
*
*/
class PiiPisoOperation : public PiiDefaultOperation
{
Q_OBJECT
/**
* The number of input sockets. Default is 2.
*/
Q_PROPERTY(int dynamicInputCount READ dynamicInputCount WRITE setDynamicInputCount);
/**
* The number of sockets in each synchronized group. It is usually a
* clever idea to make [dynamicInputCount] divisible by this value. If it is
* not, the last group will not have corresponding inputs for all
* outputs. In such a case there must be a [defaultValues]
* "default value" for each orphaned output. The default value is
* one.
*/
Q_PROPERTY(int groupSize READ groupSize WRITE setGroupSize);
/**
* A list of PiiVariant objects that will be used if a socket in
* a group is not connected. The first element in the list is the
* default value for the first input, or the first input in each
* group, depending on the value of [defaultValueMode]. The second
* element is the value for the second input and so on. An invalid
* PiiVariant means no default value. Input sockets with a valid
* default value will be marked optional. Default values have no
* effect if [groupSize] is one.
*
* ~~~(c++)
* PiiOperation* op = engine.createOperation("PiiPisoOperation");
* op->setProperty("groupSize", 2);
* op->setProperty("dynamicInputCount", 4);
* // No default value for first input in each group.
* // The default value for the second input is int(0)
* op->setProperty("defaultValues", PiiVariantList() << PiiVariant() << PiiVariant(0));
* ~~~
*/
Q_PROPERTY(PiiVariantList defaultValues READ defaultValues WRITE setDefaultValues);
/**
* Configure a single input. The `index` property in the
* `defaultValue` map specifies the input to configure.
*
* ~~~(c++)
* QVariantMap props;
* props["defaultValue"] = Pii::createQVariant("name");
* props["index"] = 0;
* piso->setProperty("defaultValue", props);
* ~~~
*/
Q_PROPERTY(QVariantMap defaultValue WRITE setDefaultValue STORED false);
/**
* Treatment of the [defaultValues] list. The default value is
* `SameDefaultsForAllGroups`.
*/
Q_PROPERTY(DefaultValueMode defaultValueMode READ defaultValueMode WRITE setDefaultValueMode);
Q_ENUMS(DefaultValueMode);
/**
* Operation mode. Default is `AsynchronousMode`.
*/
Q_PROPERTY(OperationMode operationMode READ operationMode WRITE setOperationMode);
Q_ENUMS(OperationMode);
PII_OPERATION_SERIALIZATION_FUNCTION
public:
/**
* Default value handling.
*
* - `SameDefaultsForAllGroups` - the [defaultValues] list is
* repeated for each group of synchronized inputs. The same default
* value applies to the corresponding sockets in each group. If the
* length of the [defaultValues] list is larger than [groupSize], the
* extra entries will be ignored.
*
* - `IndividualDefaults` - each input socket has its own default
* value. If the length of the [defaultValues] list is smaller than
* the number of input sockets, the rest of the input sockets will
* not have default values. If the length of the [defaultValues] list
* is larger than [dynamicInputCount], the extra entries will be ignored.
*/
enum DefaultValueMode { SameDefaultsForAllGroups, IndividualDefaults };
/**
* Operation modes.
*
* - `AsynchronousMode` - the operation passed data from any input
* group as soon as the group is full. Some groups may be handled
* more often than others. Synchronization information will be
* passed only once it is received in all groups.
*
* - `SynchronousMode` - the operation waits until all input groups
* are full before passing data. Input objects will then be emitted
* serially starting from group zero. The objects are sent between
* synchronization tags. (See PiiOutputSocket::startMany() and
* PiiOutputSocket::endMany().)
*/
enum OperationMode { AsynchronousMode, SynchronousMode };
PiiPisoOperation();
PiiInputSocket* input(const QString& name) const;
PiiOutputSocket* output(const QString& name) const;
void check(bool reset);
void setDefaultValue(const QVariantMap& defaultValue);
void setGroupSize(int groupSize);
int groupSize() const;
void setDefaultValues(const PiiVariantList& defaultValues);
PiiVariantList defaultValues() const;
void setDefaultValueMode(const DefaultValueMode& defaultValueMode);
DefaultValueMode defaultValueMode() const;
void setDynamicInputCount(int count);
int dynamicInputCount() const;
void setOperationMode(const OperationMode& operationMode);
OperationMode operationMode() const;
protected:
void process();
PiiFlowController* createFlowController();
private:
bool hasDefaultValue(int inputIndex);
void passObjectsInGroup(int groupId);
/// @internal
class Data : public PiiDefaultOperation::Data
{
public:
Data();
int iGroupSize;
int iGroupCount;
PiiVariantList lstDefaultValues;
QVector<bool> vecConnectedInputs;
DefaultValueMode defaultValueMode;
OperationMode operationMode;
};
PII_D_FUNC;
};
#endif //_PIIPISOOPERATION_H
|
Data structures for manipulating (biological) sequences.
Generally supports both nucleotide and protein sequences, some functions,
like revcompl, only makes sense for nucleotides.
|A sequence is a header, sequence data itself, and optional quality data.
Sequences are type-tagged to identify them as nucleotide, amino acids,
or unknown type.
All items are lazy bytestrings. The Offset type can be used for indexing.
|A sequence consists of a header, the sequence data itself, and optional quality data.
The type parameter is a phantom type to separate nucleotide and amino acid sequences
|An offset, index, or length of a SeqData
|The basic data type used in Sequences
|Quality data is normally associated with nucleotide sequences
|Basic type for quality data. Range 0..255. Typical Phred output is in
the range 6..50, with 20 as the line in the sand separating good from bad.
|Quality data is a Qual vector, currently implemented as a ByteString.
|Read the character at the specified position in the sequence.
|Return sequence length.
|Return sequence label (first word of header)
|Return full header.
|Return the sequence data.
|Check whether the sequence has associated quality data.
|Return the quality data, or error if none exist. Use hasqual if in doubt.
|Adding information to header
|Modify the header by appending text, or by replacing
all but the sequence label (i.e. first word).
|Converting to and from [Char]
|Convert a String to SeqData
|Convert a SeqData to a String
Returns a sequence with all internal storage freshly copied and
with sequence and quality data present as a single chunk.
By freshly copying internal storage, defragSeq allows garbage
collection of the original data source whence the sequence was
read; otherwise, use of just a short sequence name can cause an
entire sequence file buffer to be retained.
By compacting sequence data into a single chunk, defragSeq avoids
linear-time traversal of sequence chunks during random access into
|map over sequences, treating them as a sequence of (char,word8) pairs.
This will work on sequences without quality, as long as the function doesn't
try to examine it.
The current implementation is not very efficient.
|Phantom type functionality, unchecked conversion between sequence types
|Nucleotide sequences contain the alphabet [A,C,G,T].
IUPAC specifies an extended nucleotide alphabet with wildcards, but
it is not supported at this point.
|Complement a single character. I.e. identify the nucleotide it
can hybridize with. Note that for multiple nucleotides, you usually
want the reverse complement (see revcompl for that).
|Calculate the reverse complement.
This is only relevant for the nucleotide alphabet,
and it leaves other characters unmodified.
|Calculate the reverse complent for SeqData only.
|For type tagging sequences (protein sequences use Amino below)
|Proteins are chains of amino acids, represented by the IUPAC alphabet.
|Translate a nucleotide sequence into the corresponding protein
sequence. This works rather blindly, with no attempt to identify ORFs
or otherwise QA the result.
|Convert a sequence in IUPAC format to a list of amino acids.
|Convert a list of amino acids to a sequence in IUPAC format.
|Display a nicely formated sequence.
|A simple function to display a sequence: we generate the sequence string and
| call putStrLn
|Returns a properly formatted and probably highlighted string
| representation of a sequence. Highlighting is done using ANSI-Escape
|Default type for sequences
|Produced by Haddock version 2.6.1|
|
#pragma once
#include <string>
#include "vector4.hpp"
#include "vector3.hpp"
#include "vector2.hpp"
#include "rect.hpp"
namespace Prova
{
void Log(float number);
void Log(Vector2 vector);
void Log(Vector3 vector);
void Log(Vector4 vector);
void Log(Rect rect);
void Log(std::string message);
}
|
#include "tools.hh"
#include <iostream>
std::vector<std::string> nolang::applyToVector(std::vector<std::string> &dst, const std::vector<std::string> &src) {
dst.insert(dst.end(), src.begin(), src.end());
return dst;
}
void nolang::iterateTree(mpc_ast_t *tree, std::function<void(mpc_ast_t *)> closure) {
for (int c = 0; c < tree->children_num; ++c)
closure(tree->children[c]);
}
bool nolang::expect(mpc_ast_t *tree, std::string key, std::string val)
{
std::string tag = tree->tag;
if (tag.find(key) == std::string::npos) return false;
if (!val.empty() && tree->contents != val) return false;
return true;
}
void nolang::printError(std::string message, mpc_ast_t *item)
{
std::cerr << "** ERROR: " << message << ": " << item->tag << ": '" << item->contents << "'\n";
}
void nolang::printError(std::string message, const Statement *s)
{
std::cerr << "** ERROR: " << message << ": " << s->type() << ": '" << s->code() << "'\n";
}
void nolang::throwError(std::string message, mpc_ast_t *item)
{
throw message + ": " + item->tag + ": '" + item->contents;
}
void nolang::throwError(std::string message)
{
throw message;
}
void nolang::throwError(std::string message, std::string a)
{
throw message + " " + a;
}
void nolang::throwError(std::string message, std::string a, std::string b)
{
throw message + " " + a + " '" + b +"'";
}
mpc_ast_t *nolang::findFirstItemFromTree(mpc_ast_t *tree, std::string name)
{
for (int c = 0; c < tree->children_num; ++c) {
mpc_ast_t *item = tree->children[c];
if (std::string(item->tag).find(name) != std::string::npos) return item;
item = findFirstItemFromTree(item, name);
if (item != nullptr) return item;
};
return nullptr;
}
std::string nolang::combineStringList(const std::vector<std::string> &l, const std::string sep)
{
std::string res;
bool first = true;
for (auto v : l) {
if (first) first = false;
else res += sep;
res += v;
}
return res;
}
|
Theodore Roosevelt, Jr.
Timeline: Cherry, Plum, and Chrysanthemum
Portrait of Theodore Roosevelt, Jr.
26th President of the United States
March 4, 1913 – March 4, 1921
Predecessor: William Howard Taft
Successor: Charles Evans Hughes
Vice-President: Hiram Johnson (1913-17)
Henry Cabot Lodge (1917-21)
24th President of the United States
September 14, 1901 – March 4, 1909
Predecessor: William McKinley, Jr.
Successor: William Howard Taft
Vice-President: None (1901-05)
Charles Warren Fairbanks (1905-09)
24th Vice-President of the United States
March 4, 1901 – September 14, 1901
Predecessor: Garret Augustus Hobart
Successor: Charles Warren Fairbanks
President: William McKinley, Jr.
33rd Governor of New York
January 1, 1899 – December 31, 1900
Predecessor: Frank Swett Black
Successor: Benjamin Barker Odell, Jr.
Born: October 27, 1858
New York City, New York, United States of America
Died: March 4, 1929 (aged 70)
Cove Neck, New York, United States of America
Spouse: Alice Hathaway Lee (1880–84)
Edith Kermit Carow (1886–1929)
Political Party: Progressive (1912-29)
Republican (1882-1912)
Religion: Dutch Reformed
Profession: Politician; Author; Historian; Explorer; Conservationist
Theodore "T.R." Roosevelt, Jr. (October 27, 1858 – March 4, 1929) was an American author, naturalist, explorer, historian, and politician who served as the 24th and 26th President of the United States. He is the only U.S. president to serve four non-consecutive terms (1901–1909 and 1913–1921) and the second to be counted twice in the numbering of the presidents (the other is Ulysses S. Grant). With total of sixteen years in office, he remains the longest-serving President in the history of the United States.
Roosevelt was the co-founder and initial leader of the Progressive Party. He is noted for his colorful personality, range of interests and achievements, and his leadership of the Progressive Movement in early 20th century, as well as his "cowboy" persona and robust masculinity. Roosevelt is consistently rated by scholars as one of the top three U.S. Presidents, along with George Washington and Ulysses S. Grant. His face adorns Mount Rushmore alongside Benjamin Franklin, George Washington, and Ulysses S. Grant.
Roosevelt's eldest son, Theodore Roosevelt, Jr., was also became the 30th President of the United States (1941–1945).
Early life
Theodore Roosevelt, Jr. was born on October 27, 1858 in the modern-day Gramercy section of New York City to businessman Theodore "Thee" Roosevelt, Sr. and Dixie-born socialite Martha Stewart "Mittie" Bulloch. Theodore Roosevelt had Dutch, English, Irish, and Welsh ancestry from his father, and Scottish, English, and French ancestry from his mother.
TR Age 11 Paris
Theodore Roosevelt at age 11
Young Roosevelt suffered heavily from asthma attacks and spent much of his time in bed. Roosevelt used this time to study and develop an interest on natural history. Nevertheless, he was energetic and mischievously inquisitive. To compensate for his physical weakness, he embraced a strenuous life. With encouragement from his father, he then began a heavy regime of exercise.
Roosevelt made quick work of his political introduction to the membership in the Republican Party ("GOP") and was soon put forth as the party's candidate for the District's House seat in Albany. He was elected to the New York State Assembly in 1882, 1883, and 1884. In 1883, he was the GOP minority candidate for Speaker. In 1884, he lost the nomination for Speaker to Titus Sheard by a vote of 41 to 29 in the GOP caucus.
On October 27, 1880, Roosevelt married socialite Alice Hathaway Lee, daughter of banker George Cabot Lee and Caroline Watts Haskell. Their daughter Alice Lee Roosevelt was born on February 12, 1884. Alice died two days after their daughter was born from an undiagnosed case of kidney failure. His mother Mittie died of typhoid fever on the same day, in the same house. Seeking solace from personal tragedies, he left politics and went to the frontier, spent much of the next two years on his ranch in the Dakota Territory.
Political career
Harsh winters wiped out Roosevelt cattle ranch, leading him to bankruptcy
After his cattle was wiped out by the severe winters, Roosevelt decided to return to the East. On December 2, 1886, he married his childhood sweetheart, Edith Kermit Carow in London, England. Soon after, he resumed his political career. Despite a Republican and supported re-election of George F. Edmunds, Roosevelt re-entered the public life after being appointed to the United States Civil Service Commission by a Liberal president, Grover Cleveland, where he served until 1895. He vigorously fought the spoilsmen and demanded enforcement of civil service laws.
Roosevelt became president of the board of New York City Police Commissioners in 1895 for two years and radically reformed the police force. With his strictly disciplined style of leadership, Roosevelt implemented regular inspections of firearms and annual physical exams; he appointed 1,600 recruits based on their physical and mental qualifications, regardless of political affiliation, established Meritorious Service Medals and closed corrupt police hostelries.
Tr - nyc police commissioner 1894 - jacob riis bio - the making of an american - illustration named one was sitting asleep on a buttertub crop
Known for his deep interest on naval history, President William McKinley, urged by Roosevelt's close friend Congressman Henry Cabot Lodge, appointed Roosevelt as Assistant Secretary of the Navy in 1897. Roosevelt seized the opportunity and began pressing on the president his national security views regarding the Pacific and the Caribbean. Roosevelt was particularly adamant that Spain be ejected from Cuba, to foster the latter's independence and demonstrate U.S. resolve to re-enforce the Monroe Doctrine.
When the Spanish-American War finally broke out in 1898, Roosevelt promptly resigned as assistant secretary of the Navy and volunteered as commander of the 1st U.S. Volunteer Cavalry, known as the Rough Riders, an elite company comprised of Ivy League gentlemen, western cowboys, sheriffs, prospectors, police officers, and Native Americans. Under his leadership, the Rough Riders became famous for dual charges up Kettle Hill and San Juan Hill on July 1, 1898. The victories came at a cost of 200 killed and 1000 wounded.
Theodore Rooseveltnewtry
Col. Theodore Roosevelt
Roosevelt and the Rough Riders returned to the United States as war heroes. Roosevelt's war achievements caught the eye of New York Republican leaders who were looking for a gubernatorial candidate after their current governor was tainted by scandal and would probably lose. Just shortly after he was elected Governor of New York, Roosevelt began to exhibit an independence from the party bosses' influence that upset the state's political machine.
To stop Roosevelt's reforms, party bosses "kicked him upstairs" to the vice presidency under William McKinley, a powerless and merely ceremonial post at that time. Roosevelt's energetic campaigns helped ensure McKinley's re-election as president. However, the party bosses' efforts to keep him away from active politics soon vain; President McKinley was assassinated by an anarchist on September 6, 1901, making Roosevelt the nation's twenty-fourth President. At the age of 42 years old, he was the youngest person ever to serve in that capacity. Neither the nation nor the presidency would ever be the same again.
First Presidency, 1901–1909
659206249 orig
A cartoon depicting Roosevelt's policy of "trust-busting"
Ascending to the presidency, Roosevelt kept McKinley's Cabinet and promised to continue McKinley's policies. While he still endorsed the policies of gold standard, protective tariffs and lower taxes from his predecessor, Roosevelt called for a "Square Deal", and initiated a policy of increased Federal supervision that aggressively curbed the power of large corporations called "trusts". For his aggressive use of United States antitrust law he became known as the "trust-buster." Roosevelt then won the presidency in his own right in a landslide victory against Alton Brooks Parker in 1904.
Forty antitrust suits was brought by Roosevelt and major combinations such as the Standard Oil, the largest oil company, were broke-up. A new Department of Commerce and Labor was created in 1903. Conservation of the nation's natural resources and beautiful places was also a very high priority for Roosevelt. He placed 230 million acres under federal protection for preservation and parks and began systematic efforts to prevent forest fires and to retimber denuded tracts.
The United States emerged as a world economic and military power in late 1890s. Roosevelt worked to build and to strengthen the Army and the Navy into the forces that would able to protect U.S. interests corresponding with his "Speak softly and carry a big stick" policy. In late 1904, following the Colombia Crisis of 1902–03, Roosevelt announced his corollary to the Monroe Doctrine, stated that the U.S. would exercise an international police power over its Caribbean and Central American neighbors against European interventions.
Roosevelt monroe Doctrine cartoon
A cartoon depicting Roosevelt Corollary of Monroe Doctrine
The most spectacular of Roosevelt's foreign policy initiatives was the establishment of the Panama Canal. In 1899, Colombia negotiated with the United States and the United Kingdom for the support of a joint controlled canal that would be constructed in the Isthmus of Panama. Despite initial reluctance from his predecessors, Roosevelt was quite enthusiastic regarding the plan. After the U.S. concluded a negotiation with Colombia in 1903, the construction that believed to be one of the world's greatest engineering feats was finally started in 1904. In November 1906, Roosevelt inspected the canal's progress. This was the first trip outside the United States by a sitting President.
In 1905, Roosevelt offered to mediate a treaty to end the Russo-Japanese War. Although Russia and Japan initially refused his offer, they finally agreed to meet in Portsmouth, New Hampshire and ironed out a final conflict over division of Sakhalin and Korea in the Treaty of Portsmouth: Russia took the northern half and Japan the south, and Japan dropped its demand for an indemnity. For his role as a peace mediator, Roosevelt earned enough prestige to be awarded the Nobel Prize for Peace, the first U.S. President to do so.
Return to private life
"Teddy" Roosevelt and "Big Bill" Taft
Roosevelt's popularity was at its peak as the campaign of 1908 neared, but he declined to be nominated by Republicans for the third term. Instead, he supported his Secretary of War, William Howard Taft, for the presidential ticket. Taft was easily elected to the office, defeated three-time candidate William Jennings Bryan. Roosevelt had attempted to refashion Taft into a younger version of himself, but as soon as Taft began to display his individuality, Roosevelt unveiled his disenchantment. Roosevelt was further alienated when Taft did not consult him about cabinet appointments.
In March 1909, shortly after the end of his presidency, Roosevelt left New York for the safari in east and central Africa outfitted by the Smithsonian Institution. His decision was based on his desire to leave the political stage to Taft and on his natural need for action. With his son Kermit, he acquired more than 3,000 animal trophies, including eight elephants, seven hippos, nine lions, and thirteen rhinos. The expedition consumed 262 of the animals. Tons of salted animals and their skins were shipped to Mayflower, D.C.; the quantity was so large that it took years to mount them all, and the Smithsonian shared many duplicate animals with other museums.
Roosevelt and his son, Kermit, sitting on the top of the buffalo they shot on safari
After the year-long hunt, the safari was ended in Khartoum. There Roosevelt reunited with his wife Edith and family and took a vacation in Europe. He then proceeded to England for the funeral of King Edward VII and then on to Scandinavia to accept the Nobel Peace Prize for his part in ending the Russo-Japanese War. When he returned to New York in June 1910, he was greeted by one of the largest mass receptions ever given in New York City.
1912 Presidential election
Briefly after his return, Roosevelt found the crisis on Republican Party. Unlike Roosevelt, Taft never attacked business or businessmen in his rhetoric. However, he was attentive to the law, so he launched 90 antitrust suits, including one against the largest corporation, U.S. Steel, for an acquisition that Roosevelt had personally approved. Consequently, Taft lost the support of antitrust reformers (who disliked his conservative rhetoric), of big business (which disliked his actions), and of Roosevelt, who felt humiliated by his protege. In August 1910, Roosevelt gave his famous speech at Osawatomie, Kansas, which was the most radical of his career and openly initiated his break with the Taft administration and the conservative Republicans.
1912 national progressive convention
First National Progressive Convention, 1912, in the Chicago Coliseum
Pressured by the progressive wing of the Republican Party to challenge Taft, Roosevelt decided to run in the presidential election against his former protege in January 1912. The Republicans met in Detroit in June 1912, hopelessly split between the Roosevelt progressives and the supporters of President Taft. Roosevelt came to the convention having won a series of preferential primaries that put him ahead of the President in the race for party delegates. Taft, however, controlled the convention floor, and his backers managed to exclude most of the Roosevelt delegates by not recognizing their credentials. These tactics enraged Roosevelt, who then refused to allow himself to be nominated, paving the way for Taft to win on the first ballot.
Roosevelt and the Republican progressives reconvened in Chicago two weeks later to form the Progressive Party. When formally launched later that summer, the new Progressive Party chose Roosevelt as its presidential nominee and Hiram Johnson of California as his running mate. Declaring to the reporters that he felt "as strong as a Bull Moose," Roosevelt gave the new party its popular name, the "Bull Moose Party." In a famous acceptance speech, Roosevelt electrified the convention by cried out that "we stand at Armageddon, and we battle for the Lord."
While campaigning in Milwaukee, Roosevelt was shot in the chest by a fanatic. Fortunately, the bullet had been slowed down by the steel eyeglass case and the pages of a thick speech he had in his coat pocket. He declined suggestions to go to the hospital immediately. Instead, he delivered his scheduled speech with blood seeping into his shirt. The bullet in his chest had found to be more dangerous if it removed. Roosevelt carried it with him for the rest of his life. However, the bullet exacerbated his rheumatoid arthritis and prevented him from doing his daily stint of exercises; Roosevelt would soon become obese as well.
Second Presidency, 1913–1921
Despite running as a third-party candidate and have been expected the split between the Republicans would have assured a landslide victory for the Liberals, Roosevelt showed his popularity still strong enough on the 1912 election by took 62.8% of the popular vote and won 290 electoral votes from 26 states, defeated Taft and the Liberal candidate, Champ Clark. He was the second U.S. president that ever elected to third term after Ulysses S. Grant in 1881.
Roosevelt now adopted the "New Nationalism" that more radical in tone, emphasized the priority of labor over capital interests, a need to more effectively control corporate creation and combination and proposed a ban on corporate political contributions. The Federal Reserve System was created in 1913. The National Health Service and the Federal Insurance System were following in 1914. Roosevelt also approved a legislation that secured a maximum eight-hour workday and 40-hour work week for industrial workers in 1915. His most important move was the passage of the Antitrust Act of 1914 that ended the long battles over the trusts by spelling out the specific unfair practices that business were not allowed to engage in.
With Henry Cabot Lodge as his new running-mate, Roosevelt was narrowly re-elected in 1916, having faced strong performances from other candidates, Republican Elihu Root and Liberal William Gibbs McAdoo. He is the first and only U.S. president that ever elected to the fourth term (albeit not a full one). Roosevelt's re-election in 1916 later brought both the Republicans and the Liberals to put forward a proposal for constitutional amendment that would sets term limit for election to the office of U.S. President. Later in 1924, the Twentieth Amendment to the U.S. Constitution was passed. It sets a term limit for election to the office of President of the United States where a person cannot be elected president more than two terms.
Retirement and death
Ad blocker interference detected!
|
Tuesday, January 24, 2017
China is Building a Navy to Displace, Not Defeat the US in Asia
January 24, 2017 (Joseph Thomas - NEO) - In many ways, China's socioeconomic and military influence in Asia has already balanced a long-lopsided equation of geopolitical power in the region. The social and economic stability brought by the rise of China along with the rest of Asia has helped eliminate many of the "dark alleys" the US and its European allies have often used to create division, destruction and opportunities to then intervene, even overturn entire governments.
China's naval ambitions in particular have been disparaged by Western political and military analysts who believe (correctly) China's growing naval capabilities will never be on par with the United States' global-spanning naval forces.
But that is precisely the point.
China's naval capabilities are not meant to take and hold global hegemony by defeating the United States as a nation, but rather in displacing the United States as a regional hegemon in Asia where the US presence and its decades of influence have chaffed at, and at times trampled, Westphalian sovereignty.
Western analysts have pointed out that China's blue ocean naval capabilities fall far behind America's, and that it will be many years if and when China is able to compete on equal terms. For instance, analysts point out China's single operational aircraft carrier, Liaoning, faces America's 10 aircraft carriers.
However, if China's ambitions are not to overwhelm or compete with America's global fleet, and merely deter and ultimately displace America's presence in Asia Pacific, its current fleet is already adequate. Analysts point out that when China's naval assets are operated near Chinese shores, land-based weapon systems including land-based aircraft significantly tip the balance of military power in Beijing's favour.
China's decision to establish what are essentially unsinkable aircraft carriers in the South China Sea amid its island-building frenzy have angered waning Western hegemons specifically for this same reason. From these islands, should China choose or be forced to, military power can be exerted against Western naval assets in ways even the West's formidable military would struggle to counter.
And while analysts, politicians and demagogues alike attempt to accuse China of building up its forces in what will result in full-scale war between Beijing and the West, the reality is that war will only unfold if the West fails to gracefully concede the end of its "age of empires," and its unwarranted influence it has maintained quite literally an ocean away from its shores, in Asia Pacific.
Beyond America's waning military presence in the region, many of what Washington has called its "allies" have recently shown signs of shifting economically and even militarily toward Beijing. This is the result of not China's growing military might, but its expanding economic influence, as well as its differing style of diplomacy relative to Washington's.
China brings its neighbours trains and other infrastructure and investment opportunities, the US brings NGOs and colour revolutions.
Where the US has pursued a foreign policy in Asia Pacific based on "nation building" either through direct military intervention and occupation, various methods of coercion or through the use of its immense number of nongovernmental organisations used to build parallel institutions within allied nations to then displace existing governments and replace them with more pliant regimes, Beijing has focused more on cutting economic and immense infrastructure deals, regardless of who is in power.
China does not operate media organisations propagating political agitation within neighbouring states as the US does throughout Asia Pacific, nor does it play a role in supporting or opposing political parties in neighbouring states as the US does. In other words, no matter how beneficial a relationship with the US may seem to Asian Pacific states, the spectre of subversion always looms overhead, where with dealings with Beijing, it does not.
It is ironic then, that despite America's military might, it is its own, fundamentally backwards methods of diplomacy, a throwback to European colonialism, that has undone its power and influence in Asia Pacific. But then again, had the US not pursued a foreign policy based on extraterritorial expansion throughout Asia Pacific, it wouldn't need power and influence in Asia Pacific beyond the boundaries of Westphalian sovereignty to begin with.
China's naval forces then, are not intended to sail across the Pacific and project Beijing's influence upon the people of North and South America. It is intended to deter and eventually displace American forces in Asia. In many ways, China's strategy is already working and in time, it will inevitably succeed.
America's presence in Asia Pacific, like all imperial powers before it attempting to project influence thousands of kilometres from their own shores, finds itself in an untenable, unsustainable position. Even without a push, this precarious balancing act must eventually come to an end. China's burgeoning naval fleet, however, will provide a sufficient push to ensure it does sooner than later, and on Beijing's terms.
|
Contemporary world politics make it necessary for nations to integrate into international unions in the interest of their own national security and economy. In these international unions, which are usually based upon geographic location, such factors as natural resources, trading blocs, and even cultural values play an important role. Many neighboring countries combine their resources under the auspices of such organizations, create defensive alliances, and cooperate on a wide array of issues. The goal of such unions is to preserve peace, control the arms race, resolve disputes through diplomacy, promote socioeconomic development, and protect fundamental human rights and democracy. At the present time, NATO, the OSCE, the EU, NAFTA, OPEC, ASEAN, the G-8, the D-8, and APEC are the foremost international political, military, and economic unions.
These institutions are subject to organizational reforms because of new members or a widening of scope. All of these organizations, formed in the aftermath of the Second World War, have contributed to creating stability and order in the world and have played a major role in global socioeconomic development. Member nations protect their economic and military interests, and also acquire a stronger regional and international position. Even the developed world perceives the necessity of such partnerships. The creation of free trade zones, regional trade agreements, abolished customs controls, and even a common currency (as in the EU) safeguard the future of member states. Defensive pacts enable member states to reduce military expenditures and to divert those resources to cultural and educational fields.
A similar organization will provide considerable benefits to Muslim nations. For those that are desperate for technological as well as economic development, the foremost step toward stability is the creation of a central organization or, in other words, a unified Islamic world under the auspices of the Islamic Union.
Economic Development and Increasing Prosperity
Economic cooperation is necessary on two counts: stability and development. Muslim nations must bring stability and solidity to their economies. Developing industries and making the required investments is vital, as is the need for a comprehensive development plan and the simultaneous development of education, economy, culture, science, and technology. While various sectors are developed technologically, the labor force's educational levels and standards must be raised accordingly. Society must be motivated to become more productive, and the resulting economic cooperation will play a major role in eradicating poverty, illiteracy, the unjust distribution of wealth, and other socioeconomic problems rampant in Muslim countries. This partnership can be formed only by the creation of free trade zones, customs unions, and common economic areas.
Most Muslim countries have geostrategic importance as well as rich natural resources (e.g., natural gas and crude oil). These resources and strategic opportunities, however, are not being used effectively. In the Islamic world, 86% of the population's living standards fall below $2,000, 76% under $1,000, and 67% under $500 per year. When the Islamic world's total resources are considered,(1) this is quite a paradox: Roughly half of the petrol consumed in the West is exported from the Islamic world, as is 40% of the world's agricultural production.(2) Many economists and strategists freely admit that the world economy depends upon the Islamic world's oil and gas exports, in particular those of the Persian Gulf.(3)
The Persian Gulf holds two-thirds of the planet's discovered crude oil reserves. Data obtained from research concludes that Saudi Arabia alone holds 25.4% of the world's oil reserves, or 262 billion barrels. A further 11% is found in Iraq, 9.6 % in the UAE, 9.2 % in Kuwait, 8.6 % in Iran, 13% in other OPEC member states. The rest is distributed across the remainder of the world.(4) Research commissioned by the U.S. Department of Energy shows that between 2000 and 2020, oil exports from the area will increase by 125%.(5) This means that the world will continue to meet most of its energy needs by imports from the Gulf region. Moreover, the Middle East has 40% of the global natural gas reserves; 35 % of these reserves are in the Gulf region.(6) Algeria, Libya, and other North African countries have 3.7 % of the world's reserves.
The Caucasus and Central Asia are also rich in oil, natural gas, and other natural resources. For instance, Kazakhstan has between 10-17.6 billion barrels of proven oil reserves, and its natural gas reserves are estimated at between 53 and 83 trillion cubic feet.
Turkmenistan hasbetween 98 and 155 trillion cubic feet of natural gas reserves, making it the fourth largest producer.(7) Some other Muslim countries have valuable mineral resources. For instance, Uzbekistan and Kyrgyzstan are two of the world's leading gold producers. Turkey has one of the world's richest boron reserves, only recently discovered to be very important, and Tajikistan has the world's largest aluminum producing facilities.
These advantages will become more important in the twenty-first century, which some have already christened the "energy century." Energy is an essential element of modern society in terms of the military, industry, urbanization, and transport. Given that economic activity and manufacturing depend primarily upon energy, nations will do their best to achieve control over these energy resources. The Islamic world is not using its resources effectively, for many of its members lack the infrastructure and technology to increase the production and use their natural resources to develop their industries. Therefore, the resources' contributions to the country's economy are limited to export earnings. These countries do not have the means to process their own crude oil, use it in their industrial complexes, or to develop their industries. Worse still, some Muslim nations do not even have the necessary means to explore and research their natural resources or to discover and extract them. Explorations undertaken by foreign companies reveal that other Muslim nations have oil and gas reserves, but they cannot benefit from their resources.
Naturally, the ineffective use of natural resources is not the Islamic world's only economic problem. However, solving this problem can begin the process of solving many other problems. The economies of Muslim nations contain differences in structure and functioning. Some nations' economies depend upon mineral resources, such as the members of OPEC, while other nations' depend upon agriculture. These differences are also reflected, to some extent, in their social structures, such as the widely varying degrees of rural and urban populations. Developing complementary relationships and helping each other in their respective areas of expertise can turn these differences into a source of riches. All of this will be possible with the Islamic Union.
Joint ventures and project partnerships will be an important step in the right direction, for they will enable countries to benefit from one another's experiences and the income earned from investment projects will benefit all of the participating countries. Such mutual financial support is compatible with Islamic morality, for helping the needy and having a sense of social responsibility are important characteristics that Muslims strive to acquire. Many verses in the Qur’an remind Muslims to watch over the needy.
Society's internal cohesion must be extended to international relations. As international cooperation within a partnership cannot be one-sided, employment and income levels will rise in both countries. For example, one country will produce oil and another one will process it, and agriculturally dependent countries will be able to import the food they need from agriculturally developed countries. A manpower-poor country’s need will be met by another Islamic country, while rich countries will be able to invest in and help out a manpower-rich country that does not have enough jobs for its people. This will be to the benefit of both. Sharing know-how and experience will increase prosperity, and all Muslims will benefit from technological developments.
Joint ventures that realize the Islamic world's unification of opportunities and means will enable Muslims to produce hi-tech products. The Islamic common market will enable Muslim-made products to be marketed in other Muslim countries without the hindrance of customs, quotas, and other cross-border obstacles. The marketplace will grow, the market share and exports of all Muslim nations will rise, industrialization will speed up, and economic development will bring progress in technology. The living standards and wealth of Muslim nations will increase, and their existing inequalities will disappear. Some free trade agreements are already in place between countries in the Gulf, the Pacific Rim, and North Africa. Trade agreements signed by Turkey are already operational in the Islamic world. Bilateral cooperation exists in some regions; however, their scope must be widened. Such cooperation will safeguard the rights and interests of all Muslim nations and lead to all of them becoming developed—a result from which all of them will derive a far greater benefit than if they do not cooperate with each other.
All of these can be realized only under a central authority's leadership and coordination. Achieving this will be possible if Muslim nations adopt the Qur'an's values and the Prophet's (May God bless him and grant him peace) Sunnah, or, in other words, if they adopt Islamic culture. The Islamic Union must lead the way to this cultural awakening, as well as the resulting political and economic cooperation.
Mutual cooperation among Muslims, part of the Islamic code, must be adhered to by all Muslims, for God commands people to refrain from avarice and to guard the needy and support one another. In fact, destitute people have a due share of the believers' wealth (Qur'an, 51:19). As the Qur'an proclaims:
Our Lord also reveals that believers are one another's guardians (Qur'an, 9:71). The word "guardian" conveys such meanings as friend, helper, mentor, and protector. It also expresses the importance of cooperation and solidarity between Muslim nations. The cooperation that will arise from this fraternal awareness between Muslim nations will bring prosperity and wealth to Muslims and eradicate poverty, an important problem of the Islamic world. Societies that follow the Qur'an's values will not experience famine, destitution, and poverty. Muslims will develop their nations by following rational and long-term policies, establishing good relations with other nations and people, valuing trade and development, and learning from other cultures' experiences. This was so in history and, God willing, under the Islamic Union's leadership it will be so once again.
1- Demetrios Yiokaris, Islamic Leage Study Guide-1997, United Nations: Study Guides. Online at: www.vaxxine.com/cowac/islmclg1.htm.
2- “Islamic Countries have the resources to match the west, scientist”, Arabic News.com, 28 May 2000. Online at: www.arabicnews.com/ansub/ Daily/Day/000628/2000062848.html.
3- Anthony H. Cordesman and Arleigh A. Burke, “The Gulf and Transition: Executive Summary and Major Policy Recommendations” (October 30, 2000).
4- Anthony H. Cordesman and Arleigh A. Burke, “The US Military and the Evolving Challenges in the Middle East” (March 9, 2002), 3.
5- Anthony H. Cordesman and Arleigh A. Burke, “The US Military and the Evolving Challenges in the Middle East” (March 9, 2002), 3.
6- Anthony H. Cordesman and Arleigh A. Burke, “The US Military and the Evolving Challenges in the Middle East” (March 9, 2002), 4.
7- Jim Nichol, “Central Asia’s New States: Political Developments and Implications for U.S. Interests,” CRS (Congressional Research Service) Issue Brief for Congress (June 13, 2003). Online at: www.ncseonline.org/NLE/CRS/abstract.cfm?NLEid=16833.
|
//C++ 11
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
void Method(vector <int> &v){
for(auto x : v)
cout<<x;
//Member Function
cout<<'\n'<<v.front();
cout<<'\n'<<v.back();
}
};
int main(){
int a[]={1,2,3,4,5};
vector <int> V(begin(a),end(a));
//Member Function
V.push_back(6);
V.insert(V.begin(),7);
V.pop_back();
Solution Obj;
Obj.Method(V);
//Sort
sort(V.begin(),V.end());
cout<<'\n';
Obj.Method(V);
//Binary Search
cout<<"\nSearch 5:"<<binary_search(V.begin(),V.end(),5);
//Merge
vector <int> M;
merge(V.begin(),V.end(),V.begin(),V.end(),back_inserter(M));
cout<<'\n';
Obj.Method(M);
//Swap
swap(V[0],V[1]);
cout<<'\n';
Obj.Method(V);
//Reverse
reverse(V.begin(),V.end());
cout<<'\n';
Obj.Method(V);
return 0;
}
|
There could be genetic reasons why some women succumb to pressure to be thin, while others maintain a positive body image, according to US researchers.
“We’re all bombarded daily with messages extoling the virtues of being thin, yet intriguingly only some women develop what we term thin ideal internalisation,” study author Jessica Suisman from Michigan State University said in a press release.
“This suggests that genetic factors may make some women more susceptible to this pressure than others.”
Suisman and her colleagues studied more than 300 female twins aged 12 to 22 to see whether genetic factors influenced how vulnerable women are to societal thin ideals.
They measured how much the participants wanted to look like people from TV, movies and magazines, then compared identical twins, who share exactly the same genes, with fraternal twins, who share 50 percent of their genes.
The researchers found identical twins had closer levels of thin idealisation, which suggested genetics plays a part in determining body image.
“We were surprised to find that shared environmental factors, such as exposure to the same media, did not have as big an impact as expected,” Suisman said.
“Instead, non-shared factors that make co-twins different from each other had the greatest impact. The broad cultural risk factors that we thought were most influential in the development of thin-ideal internalisation are not as important as genetic risk and environmental risk factors that are specific and unique to each twin."
Megan O'Connor, from Eating Disorders Victoria, told ninemsn that experts are becoming increasingly aware of the potential genetic link.
"There are often examples of a mother and two of her daughters having eating disorders –– anecdotally we are hearing of family traits," she said.
O'Connor said families need to be aware of the possible genetic link and put responsible measures in place.
"People can certainly modify the sorts of language they use in their family about weight, dieting and body shape," she said.
"There is evidence to suggest that eating family meals together and having a healthy and relaxed relationship with food helps protect against eating disorders."
The study was published in the International Journal of Eating Disorders.
|
/* laplace/engine/basic_impact.predef.h
*
* Impact declarations.
*
* Copyright (c) 2021 Mitya Selivanov
*
* This file is part of the Laplace project.
*
* Laplace is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the MIT License for more details.
*/
#ifndef laplace_engine_basic_impact_predef_h
#define laplace_engine_basic_impact_predef_h
#include <memory>
#include <vector>
namespace laplace::engine {
class basic_impact;
using ptr_impact = std::shared_ptr<basic_impact>;
using vptr_impact = std::vector<ptr_impact>;
}
#endif
|
Tuesday, August 2, 2016
Making Dromaeosaurids Nasty Again Part IV: New Hypotheses on Dromaeosaurid Feeding Technique & Role of Tail in Movement
Hey now... I really thought about splitting this post into two posts for both respective hypotheses, but for the sake of brevity and wrapping this series up I decided to combine them. Additionally, as I will elaborate on further, the two aspects I will focus in on here - biting & locomotion - are not mutually exclusive and one dovetails into the other. So I gave this article a really long title and hope you get something out of it!!
Readers of this series may have detected a slight yet pervasive diminution of the import of the famed "killing claw" over the course of these posts. In my first post I documented the shift in scientific thought on these claws from scythes that cut meter long slashes in prey to crampons that allowed hitching rides on the hides of dinosaurs to ultimately the prevalent modern interpretation of raptor prey restraint (RPR) model of Fowler et al. in which prey subequal in size is grasped by all four digits. I reiterated a point seldom mentioned from the Fowler et al. paper on the dromaeosaurid RPR hypothesis: relative to accipterids, the ungual grasping ability of dromaeosaurids was >not as strong< as these birds in that arena i.e. they were not simply scaled up hawks. Later in that post I suggested a role for the arm/wings for pummeling prey/combatants as the feet grasped and pinned the animal. In my next post focusing on aggressive/combative scavenging in these animals I focused in on digit II as a useful tool in pinning large carcasses down as the head, neck and teeth pulled back on flesh - an idea supported by the unique morphology of the denticles on these theropods and the presence of enlarged digit II claws in several birds that work in a similar fashion.
My contention is that the import of digit II - so highly regarded that it is referred to as the "killing claw" - has both culturally and scientifically influenced these animals to the point that other aspects have been enshrouded. But was the "killing claw" really the most pivotal aspect of these animals behavior and ecology? I think not, or at least >not always<.
If the use of the "killing claw" digit II was indeed the be all and end all of dromaeosaurid prey capture and feeding technique we should be able to make some predictions to test that assertion. That over the course of the 100 million year evolutionary trajectory of these animals an increasing reliance on ungual prey capture will 1) show a trend towards shorter and therefore stronger legs i.e. less cursorial adaptations 2) as firepower is concentrated in the feet for killing the robustness of the skull and teeth should hold steady or potentially diminish. In the early Cretaceous Deinonychus we have a relatively sub-cursorial but highly adept foot grasper - again there is a bit of an inverse relationship between foot grasping strength and cursorial ability as I discussed in the first post and which Fowler et al. highlighted in their paper. I will cut and paste the source of this observation from the Fowler et al. paper:
As evidence for the purported trend in increasing foot strength Fowler et al. cite Deinonychus (early Cretaceous), and Velociraptor & Saurornitholestes (late Cretaceous). While Deinonychus and Velciraptor have relatively short metatarsi I can't see how they interpret the leggy Saurornitholestes as an example of this trend. Additionally there are some notable omissions, most obviously the name sake for the whole family Dromaeosaurus!!
In Dromaeosaurus albertensis cursorial adaptations are highlighted, the killing claw is relatively atrophied, and the skull is relatively massive and robust (almost tyrannosaurid like as GSP has commented). I mean just check out the skull of this animal, there is nothing slight, superficial, or atrophied about it at all:
robust head of Dromaeosaurus albertensis. credit LadyofHats. public domain
relatively diminished claw size/strength D. albertensis. credit LadyofHats. public domain
On the other hand digit II is not especially robust in Dromaeosaurus and the remaining unguals look more adapted towards a cursorial lifestyle than grasping. A "ground hawk" this was not.
Several of these trends towards diminished ungual strength and/or increasing skull robustness also play out in Dakotaraptor (cursorial w/diminished foot grasping ability) and the very robust skulled Atrociraptor.
Atrociraptor credit Ferahgo the assassin (Emily Willoughby) CC3.0
What am I getting at here? If anything the trend is towards increasing tooth and skull reliance over time >not always< towards increasing foot grasping & "killing claw" importance. I say >not always< because there were and likely always were dromaeosaurids that highlighted foot grasping ability. Sometimes foot grasping became diminished, sometimes it was very important. But what was always important and what was always highlighted in these animals was the jaws and teeth. They are the feature that always stayed pat or, if anything, increased in prominence.
No dromaeosaurids were not evolving protobeaks or going edentulous despite the persistent artistic meme and no they were not diminishing emphasis on teeth and jaws.
It really is all about the teeth....
To drive home this contention I want to revisit a famed piece of data that has caused quite a stir in terms of whom and how it was done - the famed Tenontosaurus bite marks and the case for Deinonychus "bite strength". A technical paper by Gignac et al. (2010), a blog post by Mark Witton, a blog post by central coast paleontologist, and an internet article/summary from The World of Animals all highlight the attention and thought these remains have attracted.
That these bite marks have evolved into a bit of a paleontological "who done it" has always irked me. Not because of a lack of data or some systemic problem with the analysis - but because of the pervasive "explaining away" of data that most parsimoniously points to Deinonychus as the perpetrator. Several ideas have been bandied about in an attempt to account for these bite marks by Deinonychus, a predator that appears to not have an especially high bite force.
Let's unpack them:
1) An undescribed and undiscovered tyrannosauroid dinosaur did this damage.
We have seen this story before... tremendous damage to bone - no way a "blade toothed" theropod did it much less a puny dromie. Let's just imagine a stout toothed, bone crunching tyrannosauroid existed at a time when such animals were basically all blade toothed anyways, and make this essentially fictional animal the perpetrator. Made up tyrant lizards did it!! Pesky blade toothed theropods just stay in your lane - you guys can't bite through bone the way tyrant lizards can!!
As you can tell (snark alert) I am not so much a fan of this idea. We have evidence of Deinonychus being the most ubiquitous theropod in the area; the tooth arcade matches; broken teeth in the area; the well established Tentontosaurus - Deinonychus relationship - the whole tide of evidence points to Deinonychus. If a cryptic lineage of stout toothed, bony crunching tyrannosauroids existed at this time I will be happy to be proven wrong - as of now I know such evidence and of the tyrannosauroids from this time period they are blade toothed predators without expanded jaw musculature - although I have heard murmuring of tyrannosauroid teeth from the same formation (but blade toothed not lethal bananas).
2) Deinonychus could bite hard, but it did so extremely rarely.
I mean really? Remember when you kept hearing how humans only use 10% of their brain? Yeah, this explanation sounds a lot like that. Over designed with a bite force exceeding modern American alligators yet barely ever uses this strength? I can't really go with this thought.
3) Stronger bite than predicted from studies.
I don't think that this animal had much of a stronger bite than studies indicate. I believe that we have been a little bit more than led astray by always looking at static bite strength as opposed to other methods of cutting that highlight speed, friction, and getting those darn denticles to do the work for you. It really is all about the teeth and it really is all about getting the denticles to work in a way that maximizes cutting efficiency with minimal effort and wear & tear of the tooth.
Its high time we start looking at hypotheses that invoke Deinonychus as the prime perpetrator. I will put out a hypothesis that highlights an unorthodox feeding mechanism in these animals, that is consistent with the data, and offers much explanatory power for the observed data.
To prime you for it I want to look at birds a bit (as usual). To really confound the situation the obvious choice is flamingoes - because what better to compare dromaeosaurids to than flamingoes, amirite?!?
I mean, excuse the poor video quality, but just look at those tongues go!! It is the tongue just pumping back and forth causing the whole neck to just vibrate. I have no idea why these flamingoes engage in this lingual vibration? Anyone ever see wild flamingoes do this? I would have to assume that they pump their tongues back and forth to filter food but in my observations of these captive Chilean flamingoes they just do it while walking around... probably just bored.
No I am not suggesting that Deinonychus had some sort of lingual vibrational apparatus set up - just pointing out how one muscular organ - the tongue - can move with such speed and power in this bird that it vibrates the whole head and neck of these animals. I mean can your tongue move with such speed and power that it causes the whole body to hummm and vibrate... ummm never mind. The message I am trying to convey here is that when we look at avian feeding mechanics - and by extension many dinosaurs and especially paravaians/maniraptorans/dromaeosaurids - there is a lot of potential for quick twitch muscle, full body and/or neck movement involved in the feding apparatus. To drive home this point, literally, what would woodpeckers be without their exceptionally quick and rapid - fire neck movements? Yes, it is the skull of woodpeckers that is wonderfully equipped to handle the blows and stresses incurred but without the power and speed provided by the neck the woodpecker would, essentially, not peck. It would just be a bird with a strong skull.
An often overlooked aspect of feeding mechanics is elaborating on how parts of or the whole of the body is engaged in feeding mechanics - the head need not be looked at as an isolated aspect of the process. Regular readers should note that I have made this point before on antediluvian salad especially with regards to twist or torsional feeding (death rolls) in plesiosaurs and in my bonesaw shimmy hypothesis on Allosaurus in which it is rapid neck movement in both the fore and aft direction that allows the denticles on the front and back end of the tooth to saw right through tissue. Bite force was not especially important in that hypothesis, in fact tight clamping would work against free movement of the denticles over the tissue.
This hypothesis does take some inspiration from the bonesaw shimmy model but it does deviate from it in several ways.
I propose that fast twitch muscular contractions of the neck, torso, and even tail would pulse out vibrational waves of energy towards the head. As bipeds that do not have their front feet on the ground these pulses of vibrational energy would travel unhindered through the neck, head, teeth, and ultimately into the food item they are cutting into. As the vibrational energy literally vibrated the tooth back and forth into the food item the peculiar denticle pattern of dromaeosaurids comes into fruition as an optimized adaptation to literally bore and auger into tissue.
The most striking and unique feature about the denticles on Deinonychus is that they are fairly reduced on the front of the tooth but very pronounced on the rear. But even stranger is the manner in which they are curved on the rear side which is towards the tip of the tooth, referred to as apical hooking. Fowler et al. suggested that this unique denticle design would optimize cutting into tissue as the prey animal was held in the RPR model and the head of the dromaeosaurs was sub-vertical with the nose facing down and biting between the legs. However this suggestion by Fowler fails to address the issue that many other theropods likely held prey/food down with their feet and wrenched off bites in a sub-vertical manner yet these theropods did not evolve such weird denticles as seen in many dromaeosaurids.
But if we imagine each denticle as a "tooth" and each tooth having a respective duty in food processing a potentially new perspective emerges that could explain the unique bone damage ascribed to Deinonychus.
As the piece of food is grasped a strong bite is first established. The slight and reduced serrations on the front of the tooth are useful here in establishing a piercing bite - not very deep as their bite force was modest but merely a small indentation into the article of food. Once a purchase is made then the body commences vibrations - potentially a combination of head, neck, torso, and tail rapid fire twitches - which allow the tooth to bore and auger into the food particle i.e. bone. As the "bore hole" phase commences the utility of the weird apically hooked denticles comes into play as each denticle literally chips and shreds away at tissue like individual teeth. As the tooth works its way into the material it leaves a remarkably accurate impression of the tooth - a literal bore hole that for all intents and purpose can be read as a puncture. Once the integrity of the material is weakened substantially the item can be pinned with the arms and/or feet and the head and neck are pulled back strongly incurring further and more drastic damage as the tooth is dragged back through the (weakened) material literally leaving deep bone raking marks and furrows. It is also potentially possible that vibrations of the body were not emphasized or were in fact used in concert with multiple quick bites - essentially chattering of the jaw - in which micro - abrasions from the denticles work to carve into tissue.
This "vibrational feeding" hypothesis could potentially explain the two types of feeding traces recorded on the bones of Tentontosaurus which include longer gouges and simple punctures.
Above you see the type of "bone rakings" I mentioned earlier. An initial puncture is established and with the teeth embedded now the neck and body can pull back and rake through tissue.
What I suggest was occurring here is that these were investigative bites into bone. The theropods were gouging into the bones to see if there was ample nutritional value in them to justify the effort and potential wear of teeth. There would always be a three-way tradeoff between nutritional value versus the effort and wear on the animals feeding apparatus all of which is tempered by the relative health of the animal i.e. how desperate for food is it. Ultimately it looks like the theropods abandoned the bone consumption in this case.
That dromaeosaurid teeth occasionally show extreme wear - especially on the tips as should be predicted in this model - is very interesting.
worn tooth "Dromaoesauroides" wiki
Private "dromaeosaur" tooth Montana .84"
Judith River "dromaeosaur" tooth
Clearly these animals were putting some heavy wear on their chompers, especially when we account for the fact that they were not keeping their teeth for life. An interesting test would be to see if komodo dragon teeth ever show equal levels of wear. But again, not the best test because theropod teeth were actually superbly designed to withstand stress more than any other ziphodont predators (Brink, 2015) (including komodos), yet they were still showing drastic wear... these animals were not getting this type of wear from just eating small animals and delicately nipping carcasses I'll tell you that much.
Of course it is worth mentioning that there is a lot of room for deviation in this model and we need not assume that all dromies employed vibrational feeding to the same extent. Indeed Dromaeosaurus could have employed a lot more emphasis on traditional "power chomps" than what I suggested for Deinonychus.
In theropods, being both ziphodont toothed and bipedal, there is no go to analogy among modern tetrapods - birds don't quite tell the whole story and neither do monitor lizards. So maybe we should expect some unothodox feeding mechanics.
Lifestyles of not only the quick and cursorial but the slow and persistent as well...
And now for the tail. Probably the aspect >least likely< to be assumed to be involved in "making dromaeosaurids nasty again". But it is the tail that is the most important aspect of these animals I will argue. The tail is what really pulls together all the disparate attributes of these animals and makes them what they were. And what they were was quite literally the most successful in tenure small to medium sized terrestrial hunter - scavengers that have ever existed. A unique blend; of accipterid "raptor"; combative scavenging vulture; bone chomping hyena ; a dash of felid; and, yes, highly efficient cursors similar to kangaroos, hyenas, humans, wolverines, and Arctodus.
One of the persistent ideas that has gained popular recognition in recent years is that dromaeosaurids were sub-cursorial - that they were slow. A chief argument put forth to support this notion is that the ankle bones - the metarsii - were rather short. And this is true for many species - Deinonychus and Velociraptor in particular - that were gaining mechanical advantage of foot claw strength at the expense of speed. But this was not so true in several other species - Dakotaraptor and Dromaeosaurus for instance - that were leggy to an exceptional degree. I am just not at ease with suggestions that species at the lower end of the spectrum were heavy footed clunkers - they could probably all put on a decent burst of speed if need be. Ursids (da' bears) have all the hallmarks of real clunkers but put on good speed with their short ankles. Keep in mind that dromies were competing with larger - and in the case of tyrannosaurids likely larger and quicker - theropods as well as azhdarchids. It is not always about being the fastest - but about being more agile when fleeing a larger threat. With their arm - wings and long tails doubtless many dromies frustrated an angry tyrannosaurid back in the day with their superior agility.
The dromie tail, just like the dromie "killing claw" has gone through a twisted and convoluted history of interpretations and revisions. A brief recap. Ostrom interpreted the tail as an intricate balancing rod that facilitated use of the "killing claw" for kicking and hanging onto prey. Each subsequent interpretation of dromie killing technique from hanging onto the side of prey and biting to the RPR method invoked the tail as intricate balancing organ for their respective prime foraging technique.
To add further context to the strange saga of dromie tails I want to revisit a post from Pterosaur.net Blog (remember that great site?) Dragon Tails: What Pterosaurs Teach Us About Velociraptor that made the strange and startling comparison between dromaeosaurid tails and rhamphorynchid tails... wtf? Well there is a comparison to be made there and it is not soooo strange when we work from the starting point that dromaeosaurids likely had flighted ancestors... so that they inherited a tail that - presumably - shared a convergence in form and function with rhamphorynchid pterosaurs.
credit Scott Hartman used w/permission . blog Scott Hartman's Skeletal Drawing
So if dromaeosaurids inherited the weird morphology of their tails from flighted ancestors - full of chevrons, diminished musculature, partially ossified dual tendons (i.e. caudal rods) there becomes two rather interesting questions: 1) what adaptive benefit did these features incur in flighted dromaeosaurids and tailed pterosaurs? and 2) how was this morphology coopted into terrestrial based dromaeosaurids? Question number #1 I am going to leave alone but I think it is a long overdue question that needs analysis but question number #2 is what I am going to approach here.
credit Scott Persons
What I am going to suggest is that dromaeosaurids across all ranges of absolute speed and leg length - were highly efficient long distance pacers. They could and did just keep going for miles at a time at a relatively moderate pace. The whole lot of 'em could just run you to death. And the key to this long distance efficiency was the tail. The tail - the whole organ - served as an elastic recoil that allowed these animals to store, redistribute, and recoup energy for efficient, long distance traveling. I have seen scant attention to the tail as an aide in terrestrial efficiency in dromies. Despite the fact that these animals were terrestrial and the tail of dinosaurs is intimately linked with movement - especially per the caudemofemoralis muscle. Darren Naish raised the question of dromie tails back in 2008 (What the hell is going on with dromaeosaur tails?) in light of Norell & Makovicky (1999) describing an articulated and sinuous Velociraptor tail. The comment section is interesting. I do note in it a pervasive sentiment of trying to "explain away" the sinuous tail - the presupposition being that stiff tails is the better supported null in dromies to start with. But is a stiff tail the better supported null or is it just how we grew up expecting dromie tails to behave? In either case lateral flexibility shown in both Velociraptor and Bambiraptor seems to have prevailed. But there is one comment by Alan #19 that I believe was very prescient and which received literally no attention in the discussion.
I think Alan was on the right track as goes energy efficiency although I doubt the hopping dromie scenario has much merit - indeed trackways have proven otherwise.
I will be working from the assumption that dromaeosaurids - whatever abilities they had for arboreal behavior or even some amount of gliding or even "flight" in small ones - that they were basically terrestrial animals and that the tide of evolutionary impetus should create a better and more efficient terrestrially adapted animal. Not an evolutionary experiment, and not a maladapted kinda-climber, kinda-jumper, kinda-walker but a reasonably well equipped and efficient animal that could do all the things that we should expect a small to medium sized hunter - scavenger to do in a highly competitive ecosystem. In short they could climb, they could potentially even swoop, they could swim, but what they did the most was walk and run around. Namely that means that they could move fairly quickly and efficiently to highly localized food sources - carcasses, hatching dinosaurs, large concentrations of prey. Especially given their long tenure, efficient terrestrial movement should almost be expected. Contra the "ground hawk" image we need not assume that these animals were >always< sit and wait ambushers or would swoop down from a perch. Indeed sit and wait ambushing is more of an ectothermic strategy and even when warm blooded predators do ambush from trees or from cover they choose spots that have a high degree of certainty that prey will be there fairly regularly. Dromies possibly could have utilized this tactic to some degree but I hardly think it was their dominant foraging strategy given that several species developed obvious cursorial adaptations and that some species lived in areas with little tree cover or sparse vegetation in general (i.e. dune fields).
From my own experimental paleontology in which I strapped on a huge tail to my butt at SVP Los Angeles and commenced to simultaneously entertain and annoy attendees I noted several patterns. What was really interesting to me is how much that darned tail moved around. Literally the smallest movement I made would thoroughly send the tail in motion. And what was most notable was the dramatic up and down oscillations that the tail went through as I walked. Each foot fall would create a simultaneous rise and fall of the tail - even the smallest and daintiest step. Don't believe me strap one on yourself and be a dinosaur for a day - you'll see what I am talking about.
These up and down movements of the tail that occurred simultaneously with each footfall likely occurred in all dinosaurs to some degree. What is interesting is that dromaeosaurid tails - because of their "caudal rods" - were designed to diminish this up and down movement of the tail as thoroughly explained by Scott Persons on his post on dromie/rhamphorynchus tail convergence. Note in the pic below how the caudal rods are neatly stacked against one another on the vertical plane to limit movement dorso - ventrally.
Caudal rods in Deinonychus prevent up and down movement of tail
credit Scott Persons
As has recently been illuminated by discoveries of articulated tails of Velociraptor and Bambiraptor these tails could still bend quite sinuously in the lateral realm.
Bambiraptor tail credit Scott Persons
So if the caudal rods of Deinonychus and other dromies diminish the up and down movement of the tails - which is a natural consequence of bipedal movement - we have some missing kinetic energy to account for. Energy is neither created nor destroyed. Something has happened to the energy otherwise absorbed and dissipated by the tail through up and down movement with each footfall in dromaeosaurids... where does it go? I suspect that this energy is recouped into the legs and aides in giving these animals just a little extra "bounce" to their step. The tail may work as a wonderful elastic rebound organ. We should potentially imagine dromies being very bouncy and springy as they paced along.
This model of locomotory efficiency is not without parallel in animals that have to move across vast expanses to find and locate rare and ephemeral food resources. A leading hypothesis concerning Arctodus is that it was a highly efficient long distance pacer that scavenged and usurped carcasses (Matheus, 2003) utilizing long legs and elastic recoil to travel at a moderate pace over long distances. Hyenas have long been noted for their efficient loping pace that allows large scale movements and carcass retrieval. Kangaroos and wallabies are well noted for their ability to travel long distance at an extremely energy efficient pace owing a lot to the elastic recoil in their leg tendons. Indeed a robotic kangaroo has been designed that utilizes such elastic recoil in the tail to recoup energy for movement.
I would be remiss not to mention the endurance running hypothesis has been invoked as a strategy for both scavenging and pursuit hunting in our own genus aided by the achilles tendon. To further quell the notion that short legs - such as in Deinonychus or Velociraptor - imply a suboptimal terrestrial movement capability let us not forget about wolverines which are notorious long range hunter -scavengers despite being very short limbed. I don't know if there have been any studies on the locomotory efficiency of these animals but I suspect there is something to 'em in those regards. There are at least loads of references to the marathon travels of these facultative scavengers.
"It is absolutely impossible for any human to keep up with a wolverine. What wolverine can do is just beyond human."
"A wolverine crosses a topo maps like we cross a street."
"They devour the landscape at a constant 4 mph regardless of terrain."
An energetic bundle of tooth, claw, and attitude? Switching from small game foraging to large carcass acquisition as the seasons dictate? Bone consumption? Able to outpace, outcompete, and outwork competitors that are several orders of magnitude larger in size? Thriving in areas and desolate habitats that other predators eschew (snowfields analogous to dune fields in these regards)? A little bit of the Gulo gulo in your dromie? You bet.
Making dromaeosaurids nasty again... Invoking the wolverine as a likely analogue for many dromies, it doesn't get much nastier than the demon of the north.
Ichnology: What Does It Tell Us?
Xing et. al. (2013) document a variety of dromaeosaurid trackways from the lower Cretaceouls Hekou group in China. The pace was not very high at about .75 meters/second which is about 1.7 mph or 2.7 km/hour. Average human walking speed is said to be about 3.1 mph or 5.0 km/hour. Let me just cut and paste the discussion:
So although these particular dromies seem to be moving along at slowish pace - perhaps they had full bellies or were just walking down for a drink. It is noteworthy that they mention several dromie ichno-species in the last paragraph that seem to be cruising along at quite brisk paces and one zipping along pretty good.
Dromaeosauripus from Korea at 4.86 m/s (Kim et al. 2008) which is 10.9 mph / 17.5 kmh
Paravipus (Murdoch et al. 2010) at 1.67 m/s and 3.61 m/s which is 3.6 mph / 5.8 kmh and 8.1 mph / 13.0 kmh
Dromaeopodus at 1.63 m/s (Li et al. 2007; Kim et al. 2008) which is 3.6 mph / 5.8 kmh
Considering that to document an actual predatory chase in the footprint record is exceptionally rare and that there is no evidence that a chase was in progress in any of these instances the ichnological data is very interesting. We see a range of speeds here from the more leisurely .75 m/s to a quite hectic 4.86 m/s. If we assume that these are reasonable cruising speeds then the small sample size we have does point to a relatively fast paced "cruiser" similar to humans, wolverines, coyotes, and hyenas that can cover vaste expanses of land at an efficient pace as the penultimate terrestrial hunter - scavengers of their time.
The Seldom Mentioned Fact of Dromie Toe & Heel Pads
The trackways from this study demonstrate that dromies had big ol' foot pads like two toed ostriches but also large heel pads! So pay attention to this aspect paleo-artists >at least some< dromies had big fat derpy looking foot/heel pads that are universally never depicted at all or large enough in paleo-art depictions (including my own). Why has this well documented aspect of dromaeosaur foot anatomy never penetrated into popular depictions? I mean no one - literally nobody - including world renowned paleoartists or more obscure/enthusiast artists depicts dromies with large heel pads. Yup the toes had big padding but the heel pad would have been very apparent in life. And this is from a peer reviewed paper with several notable authors including most notably to my western biased eyeballs, Phil Currie (who is btw the last author).
Such fleshy and large toe/heel pads would assist in stalking behavior by muffling sounds, stability, absorb stress from cursorial activity but I also have to wonder if such fleshy structures would diminish grasping effectiveness?
Also check out the base of digit II often reveals a bit of a fleshy toe pad. Dromaeosauripus yongjingensis represents a fairly large "Utahraptor" size dromie but other dromie footprints reveal fleshy toe pads and heel pads.
Kim et al. did a paper with reference to a speedy little dromie in the above discussion (Kim et al. 2008) from Korea of Dromaeosauripus moving along at about 4.86 meters per second (10.9 mph or 17.5 kmph).
The question is though does this represent a cruising speed or were we in fact lucky enough to document one of the rare instances that a theropod was actually "on the hunt"? Or neither? Could it be that dromies would normally walk at a fairly leisurely pace of less than 2 mph but when spurred into action (i.e. carcass or prey that have been detected via sensory cues but still require covering large terrain) that they then shift gears into a relatively higher pace 3 - 4 mph or even up to 8 - 10 mph / 16 -18 kmph? That is pretty fast but I hardly think it represent the top speed of these animals.
I also should give some space to the ichnological data pointing to at least six large dromies traveling in parallel and the special emphasis the authors give to the toe and heel pads in the footprints ( Li, 2007).
So when depicting the average large terrestrial dromie foot think more about ostrich feet than harpy eagle feet. Except that unlike ostriches dromies often had big ol' heel pads in addition to toe pads that would have further cushioned the foot and added a degree of stability normally not ascribed to these animals. The increased surface area would have facilitated greater efficacy and stability of movement in dubious terrain such as dune fields and mud flats.
ostrich foot credit Masteraah CC 2.0
Again it does beg the question that - at least among the dromies that sported such large heel & toe pads - how efficient a grip could have been enacted with the claws in the RPR model? I mean having such big, cushy organs between your claws and the animal you are gripping does pose some practical questions as goes the efficiency of such a grip.
A lot of questions to be answered but I do think that a fresh appraisal of these animals as primarily terrestrial long distance hunter - scavengers that have to cover a lot of ground efficiently is needed. Optimal walking versus optimal cruising speed can be addressed with larger sample size of ichnological data and computational methods... What I can say is that the anatomy of the tail likely has something to do with terrestrial locomotion and efficiency of gait is as good of a hypothesis to investigate as any...
These animals had to have been able to move and move well. They had to have traversed wide distances to secure meals in often times inhospitable terrain. They had to have competed against larger and aggressively hungry and growing youngsters of tyrannosauroids, carcharodontosaurids, and other theropods. They had to get to carcasses before large pterosaurs got all the good stuff. They had to have been at least reasonably competent in these realms to have persisted as... I don't know... the longest tenured group of small - medium sized tetrapod terrestrial hunter - scavengers that ever existed ( I know I said it before but it bears repeating). Speedy thieves indeed.
Earlier in this article I suggested that there was a link between the tail and biting apparatus in these animals - that their functions dovetail together. At the risk of piling one hypothesis on top of another let me put it out there that the diminished dorso-ventral movement of the tail as dictated by the caudal rods would have shunted more of the potential energy towards the anterior of the body - essentially towards the head, jaws, and teeth - during vibrational feeding.
credit Duane Nash Tsaagan & Velociraptor
Final Thoughts
Both a scientific and cultural emphasis on the "killing claw" in dromaesaurids has obscured a more nuanced, multifaceted, and holistic approach to these animals; that the "ground hawk" model has so embedded itself into our conscious; that the potential role of arm-wings as brutal spiked clobbering devices analogous to wing pummeling in modern aves has been overlooked; that the teeth were highly specialized and brutal weapons in their own right capable of extreme insults to carcass integrity (including bones) and perhaps full body "vibrational feeding"; that the importance of head and tooth weaponry did not diminish over the evolutionary history of this group but sometimes increased while emphasis on "killing claw" and foot grasping capability did in fact sometimes diminish; that cursorial ability did often times increase in capability and that all dromaeosaurids may have benefited from elastic rebound provided by caudal rods in the tail enhancing long distance, mid-paced terrestrial efficiency of movement as well as large fleshy toe & heel pads; that life appearance may have been more varied than simply "grounded hawks" with "dapper" haircuts but imbued with much of the panoply of life appearance we see in ratites, predatory and scavenging accipterids, cathartidae, bucerotidae, galliformes, and other large/terrestrial aves including but not limited to large exposed fleshy areas including caruncles, wattles, frills, dewlaps, and other tough - elastic - and fleshy skin derived outgrowths for thermorgulation and sexo-social signaling; that these attributes when generously applied to an outstanding and long lasted dynasty - in fact the longest tenure of small to medium sized tetrapod terrestrial hunter - scavengers to have ever existed - create a strikingly original, efficient and for lack of a better term "nasty" eco-morphological package that punched above their own weights in many categories.
They were above all else... awesome... bro.
And finally... can we please stop calling them raptors? That name is already taken!! You may have noticed through the course of these articles that I have bounced a lot between dromaeosaurid and dromie... I probably in retrospect should have used the term eudromaeosaurid through out as they are what I am principally talking about here not microraptorines or unenlagines.
I vote for calling these guys "dromies"and am fully favor of eschewing the befuddled term "raptor".
Scientific Reports 5, article no. 12338, July 2015
Gignac, P. M., Makovicky, P. J., Erickson, G. M., & Walsh, R. P. (2010). A description ofDeinonychus antirrhopus bite marks and estimates of bite force using tooth indentation simulations. Journal of Vertebrate Paleontology, 30(4), 1169-1177.
Kim, J.Y., Kim, K.S. and Lockley, M.G. 2008. New didactyl dinosaurs footprints (Dromaeosauripus hamanesnsi ichnogen. et ichnosp. nov.) from the Early Cretaceous Haman Formation, south coast of Korea. Palaeogeography, Paleoclimatology, Palaeoecology 262: 72-78
Li, Rihui., Lockley, M.G., Makovicky, P.J., Matsukawa, M., Norell, M.A., Harris. J.D., Liu, M., (2007) Behavioral and faunal implications of Early Cretaceous deinonychosaurian trackways from China. Naturwissenschaften (2008) 95: 185-191 online
Xing, L., Li, D., Harris, J.D., Bell, P.R., Azuma, Y., Fujita, M., Lee, Y.−N., and Currie, P.J. 2013. A new deinonycho−
Support me on Patreon.
Like antediluvian salad on facebook. Visit my other blog southlandbeaver.blogspot
D-man said...
Interesting hypotheses
Bk Jeong said...
I actually compared dromaeosaurs to large mustelids for a long time.
Nice to see that dromaeosaurs, despite the fact some of them were clearly not as fast, definitely were not sluggards. Speed isn't mobility.
Duane Nash said...
Right if those fossil trackways represent cruising speeds and they were not actively chasing something anything more than 4 mph is well above what most animals normally walk at. In one day they might cover 20-30 miles, that is getting around.
khalil beiting said...
An amazing "saga" of posts to sum up such amazing organisms. I don't have much else to say/ask about them seeing as how you covered nearly everything about their general behaviour, ecology, etc.
As I've talked to you about before, the large scale Dinosaur field guide I'm working on uses common names just like modern animals. I never wanted to use the word "raptor" for Dromaeosaurs since it's already taken by another group of highly carnivorous Theropod, so what are some good ideas that you (or anyone else in the comment section) have in mind that I could use? I thought of the name "Eagledrak" (literally Eagle Dragon) as a common name, but I have also thought of the name "Hell Hawk" to either replace or to accompany Eagledrak as a common name. Got any other suggestions?
Duane Nash said...
"Hell-pacer" "Running Bone Rattler" "Demon-scarf-hell-face" LOL
Thomas Holtz said...
A couple of notes:
There *IS* a Cloverly tyrannosauroid: http://www.tandfonline.com/doi/abs/10.1080/08912963.2010.543952#.V6SD4GUxu3c
In terms of metatarsal/tibia ratio, and scaled for size, even Saurornitholestes is actually fairly stumpy-footed.
Anonymous said...
I think the problem is more to do with:
Is the size and shape of the tooth resembles the scar made in tenontosaurus bone(Deinonychus does)? Even if it does, that means that Tyrannosaurs had a blade-tooth unlike later tyrannosaurs.
Anonymous said...
I think I may have sounded rude up there. What I was trying to say is that is there good reason to believe that Tyrannosaurs with classic blade tooth(that resembles Deinonychus tooth in size and shape) were capable of making significant bone damage via bite force.
khalil beiting said...
Duane I actually really love the names Hell-pacer and Bone Rattler. I'll be using these if that's fine with you ;).
Also, are there any other indications of other Dromies besides Deinonychus using this "bone rattling" technique? I'd be suprised if other well known genera weren't doing the same.
And speaking of bone rattling, do you think another common named for various Dromie taxa could be "Bonepeckers", in the same vain as modern Woodpeckers?
Duane Nash said...
@khalil any indictions of other dromies using this "bone rattling" technique? Not that I know of and it is far from proven or even adequately tested in Deinonychus. It's a hypothesis, one which may potentially explain the bone puncture marks, although I would not get too expectant in people jumping on board with it cuz skeptical scientist is skeptical.
Duane Nash said...
@Thomas Holtz Point taken regarding size correction for saurornitholestes and ref on the Cloverly turannosauroid. Anonymous iterated my concerns with simply ascribing the bone damage to a relatively rare and unknown tyrannosauroid.
I did in the post emphasis the long range loping ability of the wolverine - a stumpy footed carnivoran - which never the less travels staggering distances and has immense home ranges. I did make the analogy with that mustelid because dromie "cruising" foot print speed is often times not too shabby considering their stumpy footed design and the rarity of actual chases documented via footprints. Such high cruising speeds should stir interest in the use of the caudal rods as potential elastic rebound organs in facilitating such efficient paces over long distance as hunter - scavengers of often times marginal habitat (i.e. deserts/dunefields).
strangetruther said...
Hi Duane -
If you really are interested in understanding dromaeosaurs, you should be interested in my book where I ... SOLVED THESE QUESTIONS - not just questions to do with the tail. Far from my account being the only one that seems to be completely ignored, it is in fact the only one you need to read.
Would you like me to send you a free e-copy? I think it's about time you read it.
I'd actually put the tail explanation out on the internet several years before I published the book four years ago, but of course the "Ugly Sisters" complex amongst so many, made people want to pretend that I and my comments didn't exist. Energy storage is an interesting idea, which is why I noticed it and formed it into my theory. But seeing as many flying dromaeosaurs such as Microraptor gui had an extremely long stiff tail but clearly, from their feathered feet, could not have been long-distance foot predators, and since no predatory theropods without the special claw had the tail, it's unlikely energy saving in locomotion is the answer.
But energy utilisation by the tail is instead to do with the teeth. And I also explained why the back of the teeth had the larger denticles. And I also explained how the rear wings worked. And I also explained why it was the descendants of dromaeosaurs that won out in bird survival in the end.
Palaeontology usually seems to be played as a social game which pretends to be science, but if you choose you can actually follow the real science, Duane!
Anonymous said...
Although, I have to mention that Wolverine seems to be a plantigrade, so being efficient cruiser is not that strange. Same goes for human and bear.
Duane Nash said...
Hi Mr. jackson
Thanks for comments and my email is [email protected] if you want to send me an e-copy
(1) "seeing as many flying dromaeosaurs such as Microraptor gui had an extremely long stiff tail but clearly, from their feathered feet, could not have been long distance foot predators
(2) since no predatory theropods without the special claw had the tail, it's unlikely energy saving in locomotion is the answer"
First off in point (1) I am not so sold on the notion that just because Microraptor and other microraptorines had feathered hindlimbs that this in fact hindered or negated their terrestrial capability. Feathers can be especially tough and resilient and I don't see compelling reason why hindlimb feathers were so dainty and weak that brushing past vegetation or active movement would have been discouraged.
Point (2) I need to reiterate that dromie tails share remarkable similarity to rhamphorynchine tails. Why is this? Dromies were once flighted and it seems such a tail morphology had something to do with flight... did it aide in balance,,, did it store and recoup energy from the flight stroke?... I don't know. But what I am hedging to is that the caudal rod morphology inherited from flighted ancestors was exapted into a terrestrial capability in terrestrial dromies. The reason that other theropods did not evolve a similar caudal rod tail adaptation is quite simple - they did not have flighted ancestors to inherit the basic design. What they had - and other theropods/dinosaurs could have had parallel solutions to movement efficiency - was just good enough. Not perfect - but good enough.
I will have piece on microraptorines up soon so I will say more on them in the future...
I am interested in reading your book although I might disagree with some of your ideas/conclusions. But in this way I am treating you no different than many of the "luminaries" of the field which I also differ from on many points.
Dave said...
Interesting as always, Mr. Nash. I feel several comments are in order.
1. I feel that the Manning et al study has been too quickly accepted as dogma. Take a look at figure 9 in Kirkland's original description of Utahraptor: https://www.academia.edu/225747/A_large_dromaeosaurid_Theropoda_from_the_Lower_Cretaceous_of_Eastern_Utah
You'll notice that Utahraptor's killing claw is teardrop-shaped in cross section, and that it retains this shape very nearly all the way to the base. It practically screams "I had a sharp edge in life!" I'm not sure whether or not this is the case with Deinonychus and Velociraptor as well, but if it is, Manning et al's justification for testing a claw with a dull ventral surface on the basis of phylogenetic bracketing seems extremely weak - especially so given that similar arguments could be constructed demonstrating that dromaeosaurs probably didn't have those ossified ligaments in their tails, or that they probably didn't have serrated teeth! Why no one in the scientific community has pointed out this seemingly obvious shortcoming of Manning's test is beyond me. Suffice it to say that the slashing hypothesis is far from falsified. This isn't to say that the RPR model is totally wrong. After all, an entire clade of today's apex predators use ventral keeled claws for prey restraint. Whether slashing or prey capture was the primary use of the claw remains to be determined.
2. Re. Your "tooth boring" hypothesis:
a) given the orientation of the tooth in the mouth, it looks to me that it would be the anterior serrations that would be doing most of the work, not the posterior ones.
b) I'm somewhat confused as to the benefits of such a feeding style. The potential benefits of the bone saw shimmy you proposed for carnosaurs were fairly obvious. What purpose would this "bone-drill dougie" serve?
c) it seems to me that there's a simpler explanation for how a Deinonychus could have made such marks. Energy is force times distance, therefore force is energy divided by distance. Energy is conserved, so if you apply a force of 1000 Newtons to something (for example, a mandible full of teeth) for 20 cm, and then something else (for example, a dinosaur bone) decelerates the first thing for a distance of 5 cm, that something else will experience a force of some 4000 Newtons.
It's probably worth mentioning that, in a scrum of feeding dromaeosaurs, a lot of animals would be jostling to snap up a chunk of meat. It's probably also worth mentioning that some of these quick, hard, snapping bites might be poorly aimed, and could thus end up gouging marks in bones far deeper than would be expected from the sustainable force output of a dromaeosaur's jaws.
For whatever it's worth, to my (admittedly amateur) eyes, this explanation of the tooth marks seems to fit in better with the whole "dromaeosaurs as combative scavengers" model than your "bone-drill dougie" hypothesis does.
3. Regarding the use of the term "raptor," seeing as falcons, owls, accipitridae, and new-world vultures form a polyphyletic group, I see no reason why extinct clades of predatory/carnivorous bird - including at least dromaeosaurs and the terror birds - should not be subsumed under the term as well.
Duane Nash said...
†hanks for comment Dave
1) Interesting you mentioned a sharp edge likely in Utahraptor as I have came across this notion elsewhere in addition to new thought on the subject... well my thoughts have been evolving on the killing claw and I may have to eat some of my own words and come back around to the killing claw actually being a killing claw.
2) a) "looks to me the anterior serrations that would do most of the work" I think that they both had a function. The diminished anterior serrations allow piercing while the posterior serrations which are apically hooked do the excavation. I'm sure a computer simulation could be used to test this.
b) bone drilling would be useful not just for bone but more importantly getting into the thick hides of dinosaurs. Once the teeth get "drilled" into the carcass then the neck and body could pull back with better purchase. The "bone drilling" and "bonesaw" hypotheses might be better understood as ways to penetrate and get through the tough, often times osteoderm studded hides of dinosaurs. Of course "skinsaw" or "skin- drill" don't sound as cool ergo I use the bone terminology. Dinosaur skin and hide was a daunting task to get through and these speed & friction based biting methods provide hypotheses on how best to get through the skin of animals very similar to komodo dragon or crocodile skin.
c) yes but we still have the question of relatively weak bite force in Deinonychus - where is the energy coming from? If it is not coming from static jaw pressure maybe the body is generating the energy which gets transmitted through the teeth?
3. Little known fact: Jurassic Park made the term "raptor' popular because they followed the taxonomy of Gregory S. Paul. GSP sunk Deinonychus into the genus of Velociraptor an idea that pretty much no one follows except for Jurassic Park. JP really wanted more of a Deinonychus style villain - not a coyote sized Velociraptor - in their movie. They took Deinonychus (which they assumed as a type of Velociraptor per GSP taxonomy) and made it bigger, Incidentally Utahraptor discovered later that year!! The term "raptor" therefore came about and was popularized for a mistake!!
Dave said...
Thank you for taking the time to respond my comments, mr. Nash.
1. Not that I think you give a crap about my opinion, but it's nice to see a willingness to admit mistakes combined with a willingness to come up with out of the box hypotheses - especially when it comes to paleo-ecology, where we have such a dearth of empirical data.
2. I'm not going to continue with the further subdivision of this heading, as I wish to transition to a holistic discussion of tooth mechanics. In deinonychus, the teeth point backwards, and the denticles point towards the tip - in other words, backwards as well. If most theropods had teeth for slashing and sawing, dromaeosaurs had teeth for gripping and pulling. Of course, the anterior serrations mean that sawing is still viable, but their reduction could indicate that it was somewhat less important than the backwards yank. As for where the energy was coming from - it was coming from the weak jaws!
Deinonychus had a 40 cm skull. Conservatively, it could have had a gape of some 35 cm. Therrian et al calculated its sustainable bite force to be 1450 Newtons. That probably couldn't be sustained through the jaw's entire range of motion, as the jaw muscles would be further from perpendicular to the tooth row at wider gapes, so we'll go with a figure of 750 N. We'll subtract 5 cm from the gape to fit in the tenontosaur bone, and cut out an additional 2.5 cm to leave room for deceleration. So our 750 N will be applied for 27.5 cm. That means that the tooth row will have an energy of 206.25 J. If the bone decelerates the tooth row for a distance of 2.5 cm, it will be experiencing a force of some 8250 N - well in line with the experimental data. Needless to say, if the muscles of the neck and legs are recruited as well - say, if the animal violently thrusts its head into the scrum to snap a bite out of the carcass - the figure could be further inflated. In my opinion, this sort of suggestion has two advantages over yours: first, in my admittedly inexpert estimation, it seems less biomechanically questionable. Second, it fits in with your whole "combative scavenger" model somewhat more organically.
I hope that my contributions are helping you think through your ideas!
Duane Nash said...
Well no I do give a crap about other's opinions, in fact that was one of my main imperatives with this blog. Suggest new ideas, put them out there, and see how people respond to them either through valid critiques or other lines of evidence that I didn't think of. Sort of a group sourcing of paleo thought. A lot of my ideas of course need more rigorous and quantitative testing (math not my strong suit) and hopefully paleontologists with better experimental technology (FEA, actual models, computer simulations) will take up some of the hypotheses I have been suggesting.
We should not throw out unpolished gems just because they need a little work!!
Uggh it's been a long time since I did any physics but if your math holds up the scenario you put forth is much more reasonable than what I suggested. Which begs the question why didn't the pros think it through like you did? Admittedly using power and speed garnered from the legs and necks seems more reasonable from a biomechanical perspective but also from an evolutionary perspective - a problem with my idea is that I don't have an evolutionary mechanism - an exaptation - that would facilitate such a method as I proposed.
Don't worry I am not very wed to the idea of bone drilling teeth in dromies just kinda throwing shit at the wall to see what sticks!!
Thanks for your input Dave like I mentioned in the last post I did come across some rather novel and interesting thought on the dromie killing claw that infers a strong cutting edge and a rather bizarre use of the tail. Problem is that this idea comes from a man who is.... well he has a strong allegiance to an idea that is not very well liked in the dino-bird-paleocommunity. Unfortunately I fear this unyielding insistence on a particular idea has caused people to overlook - or not even read - his rather good idea on dromie killing claws. It's a tough needle for me to thread.
Dave said...
One weakness of my suggestion would be that such forces could only be delivered for a fraction of a second.if sustained pressure were required to produce such markings, my idea wouldn't work.
Would you be willing to direct me to this new thought on the killing claw?
Duane Nash said...
I found this old blog post basically laying it all out there: http://lefthandedcyclist.blogspot.com/2012/02/raptors-revisited.html
Interestingly this idea presented on the blog converges with pretty much the same idea developed by notorious Birds Came First advocate John Jackson in his self-published book The Secret Dino-Bird Story.
I don't agree with the BCF idea, nor with several of Jackson's other ideas. But I do suspect he is on to something with the hypothesis he developed. Unfortunately due to his reputation online and the lack of support and evidence for BCF I don't think many are aware of his ideas on the killing claw, However when his idea is decoupled from BCF no reason for it to not attract attention and further analysis.
I will probably blog on this "pierced from within" hypothesis eventually.
Dave said...
Very interesting... The dromaeosaur tail is such a curious adaptation.
Out of curiosity, does the Gignac study on Deinonychus bite force happen to mention how long force has to be applied in order to produce the observed indentations? In the interest of Scientific Progress (tm), I'm interested in finding out whether my suggestion really is plausible.
Duane Nash said...
to tell you the truth I don't know the ins and outs of the Gignac study just that it is referred to a lot in reference to bite force in Deinonychus.
Lam Luong said...
When I read in these dromies post about the heel pads that may impair grasping ability in the feet, as well as the diminished second toe claw in more cursorial species, I started thinking about cassowaries. They also have that enlarged talon on the second toe, and they can jump up to about 5 feet in the air. They don't have a need to grasp anything since they're ground-dwellers and mainly frugivorous, but they do charge and kick out at anything they feel threatened by, capable of leaving huge gashes in the offender/victim (I've heard of one report of a cassowary ripping down a car door and leaving it with a 6-inch gash). I was thinking that perhaps dromies (perhaps the cursorial species in particular) employed this tactic in prey capture along with, and possibly preceding, biting and wing-pummeling. Thoughts?
Duane Nash said...
Hi Lam Luoung thanks for comments. I tend to think that the cassowary/dromie comparison is taken too literally. The morphology of their claws are indeed very different. Indeed my thoughts on how the killing claw functioned has changed quite dramatically as of late, deviating from ideas I have expressed on these posts, as I have come across some alternative ideas on how the claw may have functioned. Stay tuned.
Related Posts Plugin for WordPress, Blogger...
|
Behind China's surge in patents
By Nin-Hai Tseng, reporter
FORTUNE -- China has won a few high-profile crowns lately: In January, the East Asian giant surpassed Germany as the world's largest exporter. Then in August, it trumped Japan to become the world's second largest economy.
And by next year, China is expected to surpass both Japan and the United States in patent filings, according to a Thomson Reuters report released this month.
Since patents often measure a country's inventive streak, it's reasonable to think that China is in line next year to become the world's top innovator. But the country, which is known for being lax on piracy and for its relatively uneven enforcement of intellectual property laws, has some ways to go before it catches up to the kind of innovation found in Japan and the U.S.
There's little doubt that China has made incredible advances since its first patent law went into effect in 1985 -- the country has been reforming its court system and administrative offices to better enforce laws. China's government has also encouraged innovation through subsidies and other incentives. More students are engineer graduates, and the country is known for some of the world's most innovative companies including Lenovo.
While patent applications across the world grew at their lowest rate in 2008 since the dot-com crisis in the early 2000s, growth of applications in China grew by 18.2%, according to the World International Property Organization. In fact, the country kept the worldwide total from spiraling to zero growth in 2008 as applications in Japan and Korea dropped, 1.3% and 1.1%, respectively. The U.S. saw zero growth.
In 2009, patent filings at most offices dropped again except in China, where they grew by 8.5%, even as public companies on average reduced R&D spending, according to WIPO. Spending at General Motors fell by 24.5%; Toyota (TM) by 19.8%; Caterpillar (CAT, Fortune 500) by 17.8% and Unilever (UL) by 3.9%, WIPO notes in a report released last month. Even information technology companies reduced spending, with the exception of a few, such as Apple (AAPL, Fortune 500) and Microsoft (MSFT, Fortune 500).
In many ways, the global recession gave China an unexpected edge over other economies leading innovation.
Growing pains
But the relevance of China's rise to the top isn't straightforward. It signals huge progress, and yet reminds the world that the country still has a host of issues to work out before its level of innovation reaches that of the United States, Europe or Japan. Just because the country may lead in patent volume doesn't necessarily mean it has yet become the world's top innovator.
For instance, look at China's quality of patents. Though experts say it's improving, Reuters notes that about half of all Chinese patents filed in 2009 were utility models -- a more affordable and less rigorous form of patent that provides a shorter term of protection of only 10 years versus 20 years for invention patents. What's more, despite the challenging economy in 2008, utility model applications surged with China leading the helm with a 24.4% increase in utility model patents, according to WIPO.
"If you're talking about Chinese companies using patents to exclude Americans or to gain a competitive advantage in the U.S. marketplace, the utility patents are meaningless," says Bruce Lehman, president of the International Intellectual Property Institute, a Washington DC-based think tank that promotes the idea that intellectual property can help drive economic growth, especially in developing countries.
Lehman adds that while the surge in utility model applications is a sign of progress given the Chinese economy's size and history, they are not recognized in the U.S. and most parts of the world.
And while China's intellectual property laws are strong, enforcement is still inconsistent. Even though the country has reformed its court system to better handle disputes, inefficiencies remain. Song Jung, attorney with McKenna Long & Aldridge, recalls his experience four years ago winning an intellectual property infringement case against a Chinese company. He says that while China's system has generally improved, one of the drawbacks is that compensation and royalties for intellectual property is very low compared with the U.S. This potentially creates a situation where companies that have grievances might not have an incentive to resolve intellectual property issues through the courts. Jung says it's not that compensation should be outrageously high either, as that could spark a frenzy of lawsuits and scare off companies from innovating.
"You have to strike a balance," he says.
Indeed, China is on its way to becoming the world's top innovator. It's not there yet, however. To top of page
|
//
// Created by Nicholas on 7 Jan 2021.
//
#pragma once
#include <cstddef>
#include <stdexcept>
#include <forward_list>
#include <memory>
#include <type_traits>
#include <vector>
#include <optional>
namespace wtl {
/**
* A directed edge in a flow network.
* @tparam CapacityType
*/
template<typename CapacityType>
struct FlowEdge {
std::size_t m_Source;
std::size_t m_Dest;
CapacityType m_Capacity;
CapacityType m_Flow = 0;
FlowEdge(std::size_t source, std::size_t dest, CapacityType capacity)
: m_Source(source), m_Dest(dest), m_Capacity(capacity) {}
[[nodiscard]] std::size_t source() const noexcept {
return m_Source;
}
[[nodiscard]] std::size_t dest() const noexcept {
return m_Dest;
}
[[nodiscard]] CapacityType getFlow() const noexcept {
return m_Flow;
}
[[nodiscard]] CapacityType getCapacity() const noexcept {
return m_Capacity;
}
[[nodiscard]] std::size_t other(std::size_t v) const {
if (v == m_Source)
return m_Dest;
else if (v == m_Dest) {
return m_Source;
} else {
throw std::invalid_argument("Invalid vertex");
}
}
/**
* Retrieve the residual capacity of the flow edge. Note that the residual capacity depends on
* which direction of the directed flow edge we are traversing.
* @param v
* @return
*/
[[nodiscard]] CapacityType getResidualCapacity(std::size_t v) const {
if (v == m_Dest) {
return m_Capacity - m_Flow;
} else if (v == m_Source) {
return m_Flow;
} else {
throw std::invalid_argument("Invalid vertex");
}
}
/**
* Add flow to the flow edge. If the flow is in the same direction as the directed edge,
* then the flow is added to the current flow, else it is subtracted.
* @param flow
* @param v
*/
void addFlowTo(std::size_t v, CapacityType flow) {
if (flow < 0 || getResidualCapacity(v) < flow) {
throw std::invalid_argument("Flow cannot be negative");
}
if (v == m_Dest) {
m_Flow += flow;
} else if (v == m_Source) {
m_Flow -= flow;
}
}
};
namespace impl {
template<typename CapacityType>
struct FlowNetwork_FlowEdge_Compare {
private:
using FlowEdge = FlowEdge<CapacityType>;
public:
bool operator()(const FlowEdge& lhs, const FlowEdge& rhs) const {
return (lhs.m_Source == rhs.m_Source && lhs.m_Dest == rhs.m_Dest)
|| (lhs.m_Source == rhs.m_Dest && lhs.m_Dest == rhs.m_Source);
}
};
}
/**
* A flow network is a directed graph where each edge has a capacity and flow value.
* The amount of flow on an edge cannot exceed the capacity of the edge.
* The vertices of the flow network are labelled from [0, number of vertices - 1].
* Flow Network does not allow for more than 1 edge between 2 vertices, regardless of edge direction.
* @tparam CapacityType
*/
template<typename CapacityType>
class FlowNetwork {
private:
using Edge = FlowEdge<CapacityType>;
using Edge_Ptr = Edge*;
using Compare = impl::FlowNetwork_FlowEdge_Compare<CapacityType>;
using Edges = std::forward_list<Edge>;
using Bucket = std::vector<Edge_Ptr>;
using AdjList = std::unique_ptr<Bucket[]>;
template<typename T>
friend
class FordFulkerson;
template<typename T>
friend
class EdmondsKarp;
template<typename T>
friend
class Dinic;
/// Number of vertices in the graph
const std::size_t m_VertexCount;
/// Keep track of number of edges.
std::size_t m_EdgeCount = 0;
/// Store all the edge objects
Edges m_Edges;
/// Graph represented as an adjacency list, which stores pointers to edges
AdjList m_Network;
/**
* Check if an vertex is invalid
* @param v
* @return True if invalid, false if valid
*/
[[nodiscard]] inline bool outOfBounds(std::size_t v) const noexcept {
return v < 0 || v >= m_VertexCount;
}
public:
/**
* Constructor
* @param vertexCount
*/
explicit FlowNetwork(std::size_t vertexCount)
: m_VertexCount(vertexCount) {
static_assert(std::is_arithmetic_v<CapacityType>, "CapacityType must be arithmetic type");
if (m_VertexCount < 1) {
throw std::invalid_argument("Flow network cannot have less than 1 vertex");
}
m_Network = std::make_unique<Bucket[]>(m_VertexCount);
}
/**
* Copy constructor
* @param other
* @return
*/
FlowNetwork(const FlowNetwork& other) = delete;
/**
* Copy assignment
* @param other
* @return
*/
FlowNetwork& operator=(const FlowNetwork& other) = delete;
/**
* Get the number of vertices in the flow network.
* @return
*/
[[nodiscard]] std::size_t vertex() const noexcept {
return m_VertexCount;
}
/**
* Get the number of edges in the flow network.
* @return
*/
[[nodiscard]] std::size_t edge() const noexcept {
return m_EdgeCount;
}
/**
* Get all edges adjacent to the specified vertex, which includes all edges pointing away
* and pointing towards the specified vertex.
* @param v
* @return vector of edge objects
*/
[[nodiscard]] std::vector<Edge> adjacent(std::size_t v) const {
if (outOfBounds(v)) {
throw std::invalid_argument("Invalid vertex");
}
std::vector<Edge> result;
for (const Edge_Ptr edgePtr : m_Network[v]) {
result.push_back(*edgePtr);
}
return result;
}
/**
* Get all edges in the flow network.
* @return vector of edge objects
*/
[[nodiscard]] std::vector<Edge> allEdges() const noexcept {
std::vector<Edge> result;
result.reserve(m_EdgeCount);
for (std::size_t i = 0; i < m_VertexCount; i++) {
for (const Edge_Ptr edgePtr : m_Network[i]) {
if (edgePtr->m_Source == i) {
result.push_back(*edgePtr);
}
}
}
return result;
}
/**
* Check there is an edge between vertex v and vertex w, regardless of the edge direction.
* @param v
* @param w
* @return true if there is an edge, false if not.
*/
[[nodiscard]] bool hasEdge(std::size_t v, std::size_t w) const {
if (outOfBounds(v) || outOfBounds(w)) {
throw std::invalid_argument("Invalid vertex");
}
Edge e(v, w, 1);
Compare compare;
for (const Edge_Ptr edgePtr : m_Network[v]) {
if (compare(e, *edgePtr)) {
return true;
}
}
return false;
}
/**
* Get the edge between vertex v and vertex w, regardless of the edge direction.
* @param v
* @param w
* @return const reference to the edge.
*/
[[nodiscard]] const Edge& getEdge(std::size_t v, std::size_t w) const {
if (outOfBounds(v) || outOfBounds(w)) {
throw std::invalid_argument("Invalid vertex");
}
Edge e(v, w, 1);
Compare compare;
for (const Edge_Ptr edgePtr : m_Network[v]) {
if (compare(e, *edgePtr)) {
return *edgePtr;
}
}
throw std::runtime_error("Edge does not exist");
}
/**
* Add an edge to the flow network. Since more than 1 edge cannot exist between 2 vertices, duplicate edges
* are not inserted.
* @param source
* @param dest
* @param capacity
* @return True if edge was inserted, false if not
*/
bool addEdge(std::size_t source, std::size_t dest, CapacityType capacity) {
if (outOfBounds(source) || outOfBounds(dest)) {
throw std::invalid_argument("Invalid vertices");
}
if (capacity < 0) {
throw std::invalid_argument("Capacity cannot be less than 0");
}
if (hasEdge(source, dest)) {
return false;
}
m_Edges.emplace_front(source, dest, capacity);
m_Network[source].push_back(&(*m_Edges.begin()));
m_Network[dest].push_back(&(*m_Edges.begin()));
return true;
}
};
}
|
/*
* Copyright (C) 2009 Citrix Ltd.
* Author Vincent Hanquez <[email protected]>
* Author Stefano Stabellini <[email protected]>
*
* This program 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; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
#include "libxl_osdeps.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h> /* for write, unlink and close */
#include <stdint.h>
#include <inttypes.h>
#include <assert.h>
#include "libxl.h"
#include "libxl_utils.h"
#include "libxl_internal.h"
#include "flexarray.h"
#define PAGE_TO_MEMKB(pages) ((pages) * 4)
#define BACKEND_STRING_SIZE 5
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
int libxl_ctx_init(libxl_ctx *ctx, int version, xentoollog_logger *lg)
{
struct stat stat_buf;
if (version != LIBXL_VERSION)
return ERROR_VERSION;
memset(ctx, 0, sizeof(libxl_ctx));
ctx->lg = lg;
memset(&ctx->version_info, 0, sizeof(libxl_version_info));
if ( stat(XENSTORE_PID_FILE, &stat_buf) != 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "Is xenstore daemon running?\n"
"failed to stat %s", XENSTORE_PID_FILE);
return ERROR_FAIL;
}
ctx->xch = xc_interface_open(lg,lg,0);
if (!ctx->xch) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno,
"cannot open libxc handle");
return ERROR_FAIL;
}
ctx->xsh = xs_daemon_open();
if (!ctx->xsh)
ctx->xsh = xs_domain_open();
if (!ctx->xsh) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno,
"cannot connect to xenstore");
xc_interface_close(ctx->xch);
return ERROR_FAIL;
}
return 0;
}
int libxl_ctx_free(libxl_ctx *ctx)
{
if (ctx->xch) xc_interface_close(ctx->xch);
libxl_version_info_destroy(&ctx->version_info);
if (ctx->xsh) xs_daemon_close(ctx->xsh);
return 0;
}
void libxl_string_list_destroy(libxl_string_list *psl)
{
int i;
libxl_string_list sl = *psl;
if (!sl)
return;
for (i = 0; sl[i] != NULL; i++)
free(sl[i]);
free(sl);
}
void libxl_key_value_list_destroy(libxl_key_value_list *pkvl)
{
int i;
libxl_key_value_list kvl = *pkvl;
if (!kvl)
return;
for (i = 0; kvl[i] != NULL; i += 2) {
free(kvl[i]);
if (kvl[i + 1])
free(kvl[i + 1]);
}
free(kvl);
}
/******************************************************************************/
int libxl_domain_rename(libxl_ctx *ctx, uint32_t domid,
const char *old_name, const char *new_name,
xs_transaction_t trans)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dom_path = 0;
const char *name_path;
char *got_old_name;
unsigned int got_old_len;
xs_transaction_t our_trans = 0;
int rc;
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) goto x_nomem;
name_path= libxl__sprintf(&gc, "%s/name", dom_path);
if (!name_path) goto x_nomem;
retry_transaction:
if (!trans) {
trans = our_trans = xs_transaction_start(ctx->xsh);
if (!our_trans) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno,
"create xs transaction for domain (re)name");
goto x_fail;
}
}
if (new_name[0]) {
/* nonempty names must be unique */
uint32_t domid_e;
rc = libxl_name_to_domid(ctx, new_name, &domid_e);
if (rc == ERROR_INVAL) {
/* no such domain, good */
} else if (rc != 0) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unexpected error"
"checking for existing domain");
goto x_rc;
} else if (domid_e == domid) {
/* domain already has this name, ok (but we do still
* need the rest of the code as we may need to check
* old_name, for example). */
} else {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "domain with name \"%s\""
" already exists.", new_name);
rc = ERROR_INVAL;
goto x_rc;
}
}
if (old_name) {
got_old_name = xs_read(ctx->xsh, trans, name_path, &got_old_len);
if (!got_old_name) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, errno, "check old name"
" for domain %"PRIu32" allegedly named `%s'",
domid, old_name);
goto x_fail;
}
if (strcmp(old_name, got_old_name)) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "domain %"PRIu32" allegedly named "
"`%s' is actually named `%s' - racing ?",
domid, old_name, got_old_name);
free(got_old_name);
goto x_fail;
}
free(got_old_name);
}
if (!xs_write(ctx->xsh, trans, name_path,
new_name, strlen(new_name))) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "failed to write new name `%s'"
" for domain %"PRIu32" previously named `%s'",
new_name, domid, old_name);
goto x_fail;
}
if (our_trans) {
if (!xs_transaction_end(ctx->xsh, our_trans, 0)) {
trans = our_trans = 0;
if (errno != EAGAIN) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "failed to commit new name `%s'"
" for domain %"PRIu32" previously named `%s'",
new_name, domid, old_name);
goto x_fail;
}
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "need to retry rename transaction"
" for domain %"PRIu32" (name_path=\"%s\", new_name=\"%s\")",
domid, name_path, new_name);
goto retry_transaction;
}
our_trans = 0;
}
rc = 0;
x_rc:
if (our_trans) xs_transaction_end(ctx->xsh, our_trans, 1);
libxl__free_all(&gc);
return rc;
x_fail: rc = ERROR_FAIL; goto x_rc;
x_nomem: rc = ERROR_NOMEM; goto x_rc;
}
int libxl_domain_resume(libxl_ctx *ctx, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc = 0;
if (libxl__domain_is_hvm(ctx, domid)) {
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "Called domain_resume on "
"non-cooperative hvm domain %u", domid);
rc = ERROR_NI;
goto out;
}
if (xc_domain_resume(ctx->xch, domid, 0)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xc_domain_resume failed for domain %u",
domid);
rc = ERROR_FAIL;
goto out;
}
if (!xs_resume_domain(ctx->xsh, domid)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xs_resume_domain failed for domain %u",
domid);
rc = ERROR_FAIL;
}
out:
libxl__free_all(&gc);
return 0;
}
/*
* Preserves a domain but rewrites xenstore etc to make it unique so
* that the domain can be restarted.
*
* Does not modify info so that it may be reused.
*/
int libxl_domain_preserve(libxl_ctx *ctx, uint32_t domid,
libxl_domain_create_info *info, const char *name_suffix, libxl_uuid new_uuid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
struct xs_permissions roperm[2];
xs_transaction_t t;
char *preserved_name;
char *uuid_string;
char *vm_path;
char *dom_path;
int rc;
preserved_name = libxl__sprintf(&gc, "%s%s", info->name, name_suffix);
if (!preserved_name) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
uuid_string = libxl__uuid2string(&gc, new_uuid);
if (!uuid_string) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
vm_path = libxl__sprintf(&gc, "/vm/%s", uuid_string);
if (!vm_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
roperm[0].id = 0;
roperm[0].perms = XS_PERM_NONE;
roperm[1].id = domid;
roperm[1].perms = XS_PERM_READ;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
xs_rm(ctx->xsh, t, vm_path);
xs_mkdir(ctx->xsh, t, vm_path);
xs_set_permissions(ctx->xsh, t, vm_path, roperm, ARRAY_SIZE(roperm));
xs_write(ctx->xsh, t, libxl__sprintf(&gc, "%s/vm", dom_path), vm_path, strlen(vm_path));
rc = libxl_domain_rename(ctx, domid, info->name, preserved_name, t);
if (rc) {
libxl__free_all(&gc);
return rc;
}
xs_write(ctx->xsh, t, libxl__sprintf(&gc, "%s/uuid", vm_path), uuid_string, strlen(uuid_string));
if (!xs_transaction_end(ctx->xsh, t, 0))
if (errno == EAGAIN)
goto retry_transaction;
libxl__free_all(&gc);
return 0;
}
static void xcinfo2xlinfo(const xc_domaininfo_t *xcinfo,
libxl_dominfo *xlinfo)
{
memcpy(&(xlinfo->uuid), xcinfo->handle, sizeof(xen_domain_handle_t));
xlinfo->domid = xcinfo->domain;
xlinfo->dying = !!(xcinfo->flags&XEN_DOMINF_dying);
xlinfo->shutdown = !!(xcinfo->flags&XEN_DOMINF_shutdown);
xlinfo->paused = !!(xcinfo->flags&XEN_DOMINF_paused);
xlinfo->blocked = !!(xcinfo->flags&XEN_DOMINF_blocked);
xlinfo->running = !!(xcinfo->flags&XEN_DOMINF_running);
if (xlinfo->shutdown || xlinfo->dying)
xlinfo->shutdown_reason = (xcinfo->flags>>XEN_DOMINF_shutdownshift) & XEN_DOMINF_shutdownmask;
else
xlinfo->shutdown_reason = ~0;
xlinfo->current_memkb = PAGE_TO_MEMKB(xcinfo->tot_pages);
xlinfo->max_memkb = PAGE_TO_MEMKB(xcinfo->max_pages);
xlinfo->cpu_time = xcinfo->cpu_time;
xlinfo->vcpu_max_id = xcinfo->max_vcpu_id;
xlinfo->vcpu_online = xcinfo->nr_online_vcpus;
}
libxl_dominfo * libxl_list_domain(libxl_ctx *ctx, int *nb_domain)
{
libxl_dominfo *ptr;
int i, ret;
xc_domaininfo_t info[1024];
int size = 1024;
ptr = calloc(size, sizeof(libxl_dominfo));
if (!ptr) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "allocating domain info");
return NULL;
}
ret = xc_domain_getinfolist(ctx->xch, 0, 1024, info);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "geting domain info list");
return NULL;
}
for (i = 0; i < ret; i++) {
xcinfo2xlinfo(&info[i], &ptr[i]);
}
*nb_domain = ret;
return ptr;
}
int libxl_domain_info(libxl_ctx *ctx, libxl_dominfo *info_r,
uint32_t domid) {
xc_domaininfo_t xcinfo;
int ret;
ret = xc_domain_getinfolist(ctx->xch, domid, 1, &xcinfo);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "geting domain info list");
return ERROR_FAIL;
}
if (ret==0 || xcinfo.domain != domid) return ERROR_INVAL;
xcinfo2xlinfo(&xcinfo, info_r);
return 0;
}
libxl_cpupoolinfo * libxl_list_cpupool(libxl_ctx *ctx, int *nb_pool)
{
libxl_cpupoolinfo *ptr, *tmp;
int i;
xc_cpupoolinfo_t *info;
uint32_t poolid;
ptr = NULL;
poolid = 0;
for (i = 0;; i++) {
info = xc_cpupool_getinfo(ctx->xch, poolid);
if (info == NULL)
break;
tmp = realloc(ptr, (i + 1) * sizeof(libxl_cpupoolinfo));
if (!tmp) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "allocating cpupool info");
free(ptr);
xc_cpupool_infofree(ctx->xch, info);
return NULL;
}
ptr = tmp;
ptr[i].poolid = info->cpupool_id;
ptr[i].sched_id = info->sched_id;
ptr[i].n_dom = info->n_dom;
if (libxl_cpumap_alloc(ctx, &ptr[i].cpumap)) {
xc_cpupool_infofree(ctx->xch, info);
break;
}
memcpy(ptr[i].cpumap.map, info->cpumap, ptr[i].cpumap.size);
poolid = info->cpupool_id + 1;
xc_cpupool_infofree(ctx->xch, info);
}
*nb_pool = i;
return ptr;
}
/* this API call only list VM running on this host. a VM can be an aggregate of multiple domains. */
libxl_vminfo * libxl_list_vm(libxl_ctx *ctx, int *nb_vm)
{
libxl_vminfo *ptr;
int index, i, ret;
xc_domaininfo_t info[1024];
int size = 1024;
ptr = calloc(size, sizeof(libxl_dominfo));
if (!ptr)
return NULL;
ret = xc_domain_getinfolist(ctx->xch, 1, 1024, info);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "geting domain info list");
return NULL;
}
for (index = i = 0; i < ret; i++) {
if (libxl_is_stubdom(ctx, info[i].domain, NULL))
continue;
memcpy(&(ptr[index].uuid), info[i].handle, sizeof(xen_domain_handle_t));
ptr[index].domid = info[i].domain;
index++;
}
*nb_vm = index;
return ptr;
}
int libxl_domain_suspend(libxl_ctx *ctx, libxl_domain_suspend_info *info,
uint32_t domid, int fd)
{
int hvm = libxl__domain_is_hvm(ctx, domid);
int live = info != NULL && info->flags & XL_SUSPEND_LIVE;
int debug = info != NULL && info->flags & XL_SUSPEND_DEBUG;
int rc = 0;
rc = libxl__domain_suspend_common(ctx, domid, fd, hvm, live, debug);
if (!rc && hvm)
rc = libxl__domain_save_device_model(ctx, domid, fd);
return rc;
}
int libxl_domain_pause(libxl_ctx *ctx, uint32_t domid)
{
int ret;
ret = xc_domain_pause(ctx->xch, domid);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "pausing domain %d", domid);
return ERROR_FAIL;
}
return 0;
}
int libxl_domain_core_dump(libxl_ctx *ctx, uint32_t domid,
const char *filename)
{
int ret;
ret = xc_domain_dumpcore(ctx->xch, domid, filename);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "core dumping domain %d to %s",
domid, filename);
return ERROR_FAIL;
}
return 0;
}
int libxl_domain_unpause(libxl_ctx *ctx, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *path;
char *state;
int ret, rc = 0;
if (libxl__domain_is_hvm(ctx, domid)) {
path = libxl__sprintf(&gc, "/local/domain/0/device-model/%d/state", domid);
state = libxl__xs_read(&gc, XBT_NULL, path);
if (state != NULL && !strcmp(state, "paused")) {
libxl__xs_write(&gc, XBT_NULL, libxl__sprintf(&gc, "/local/domain/0/device-model/%d/command", domid), "continue");
libxl__wait_for_device_model(ctx, domid, "running", NULL, NULL);
}
}
ret = xc_domain_unpause(ctx->xch, domid);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "unpausing domain %d", domid);
rc = ERROR_FAIL;
}
libxl__free_all(&gc);
return rc;
}
static char *req_table[] = {
[0] = "poweroff",
[1] = "reboot",
[2] = "suspend",
[3] = "crash",
[4] = "halt",
};
int libxl_domain_shutdown(libxl_ctx *ctx, uint32_t domid, int req)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *shutdown_path;
char *dom_path;
if (req > ARRAY_SIZE(req_table)) {
libxl__free_all(&gc);
return ERROR_INVAL;
}
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
if (libxl__domain_is_hvm(ctx,domid)) {
unsigned long pvdriver = 0;
int ret;
ret = xc_get_hvm_param(ctx->xch, domid, HVM_PARAM_CALLBACK_IRQ, &pvdriver);
if (ret<0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting HVM callback IRQ");
libxl__free_all(&gc);
return ERROR_FAIL;
}
if (!pvdriver) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "HVM domain without PV drivers:"
" graceful shutdown not possible, use destroy");
libxl__free_all(&gc);
return ERROR_FAIL;
}
}
shutdown_path = libxl__sprintf(&gc, "%s/control/shutdown", dom_path);
xs_write(ctx->xsh, XBT_NULL, shutdown_path, req_table[req], strlen(req_table[req]));
libxl__free_all(&gc);
return 0;
}
int libxl_get_wait_fd(libxl_ctx *ctx, int *fd)
{
*fd = xs_fileno(ctx->xsh);
return 0;
}
int libxl_wait_for_domain_death(libxl_ctx *ctx, uint32_t domid, libxl_waiter *waiter)
{
waiter->path = strdup("@releaseDomain");
if (asprintf(&(waiter->token), "%d", LIBXL_EVENT_DOMAIN_DEATH) < 0)
return -1;
if (!xs_watch(ctx->xsh, waiter->path, waiter->token))
return -1;
return 0;
}
int libxl_wait_for_disk_ejects(libxl_ctx *ctx, uint32_t guest_domid, libxl_device_disk *disks, int num_disks, libxl_waiter *waiter)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int i, rc = -1;
uint32_t domid = libxl_get_stubdom_id(ctx, guest_domid);
if (!domid)
domid = guest_domid;
for (i = 0; i < num_disks; i++) {
if (asprintf(&(waiter[i].path), "%s/device/vbd/%d/eject",
libxl__xs_get_dompath(&gc, domid),
libxl__device_disk_dev_number(disks[i].vdev)) < 0)
goto out;
if (asprintf(&(waiter[i].token), "%d", LIBXL_EVENT_DISK_EJECT) < 0)
goto out;
xs_watch(ctx->xsh, waiter[i].path, waiter[i].token);
}
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_get_event(libxl_ctx *ctx, libxl_event *event)
{
unsigned int num;
char **events = xs_read_watch(ctx->xsh, &num);
if (num != 2) {
free(events);
return ERROR_FAIL;
}
event->path = strdup(events[XS_WATCH_PATH]);
event->token = strdup(events[XS_WATCH_TOKEN]);
event->type = atoi(event->token);
free(events);
return 0;
}
int libxl_stop_waiting(libxl_ctx *ctx, libxl_waiter *waiter)
{
if (!xs_unwatch(ctx->xsh, waiter->path, waiter->token))
return ERROR_FAIL;
else
return 0;
}
int libxl_free_event(libxl_event *event)
{
free(event->path);
free(event->token);
return 0;
}
int libxl_free_waiter(libxl_waiter *waiter)
{
free(waiter->path);
free(waiter->token);
return 0;
}
int libxl_event_get_domain_death_info(libxl_ctx *ctx, uint32_t domid, libxl_event *event, libxl_dominfo *info)
{
if (libxl_domain_info(ctx, info, domid) < 0)
return 0;
if (info->running || (!info->shutdown && !info->dying))
return ERROR_INVAL;
return 1;
}
int libxl_event_get_disk_eject_info(libxl_ctx *ctx, uint32_t domid, libxl_event *event, libxl_device_disk *disk)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *path;
char *backend;
char *value;
char backend_type[BACKEND_STRING_SIZE+1];
value = libxl__xs_read(&gc, XBT_NULL, event->path);
if (!value || strcmp(value, "eject")) {
libxl__free_all(&gc);
return 0;
}
path = strdup(event->path);
path[strlen(path) - 6] = '\0';
backend = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend", path));
sscanf(backend,
"/local/domain/%d/backend/%" TOSTRING(BACKEND_STRING_SIZE) "[a-z]/%*d/%*d",
&disk->backend_domid, backend_type);
if (!strcmp(backend_type, "tap") || !strcmp(backend_type, "vbd")) {
disk->backend = DISK_BACKEND_TAP;
} else if (!strcmp(backend_type, "qdisk")) {
disk->backend = DISK_BACKEND_QDISK;
} else {
disk->backend = DISK_BACKEND_UNKNOWN;
}
disk->domid = domid;
disk->pdev_path = strdup("");
disk->format = DISK_FORMAT_EMPTY;
/* this value is returned to the user: do not free right away */
disk->vdev = xs_read(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "%s/dev", backend), NULL);
disk->unpluggable = 1;
disk->readwrite = 0;
disk->is_cdrom = 1;
free(path);
libxl__free_all(&gc);
return 1;
}
int libxl_domain_destroy(libxl_ctx *ctx, uint32_t domid, int force)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
libxl_dominfo dominfo;
char *dom_path;
char *vm_path;
int rc, dm_present;
rc = libxl_domain_info(ctx, &dominfo, domid);
switch(rc) {
case 0:
break;
case ERROR_INVAL:
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "non-existant domain %d", domid);
default:
return rc;
}
if (libxl__domain_is_hvm(ctx, domid)) {
dm_present = 1;
} else {
char *pid;
pid = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "/local/domain/%d/image/device-model-pid", domid));
dm_present = (pid != NULL);
}
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
rc = ERROR_FAIL;
goto out;
}
if (libxl_device_pci_shutdown(ctx, domid) < 0)
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "pci shutdown failed for domid %d", domid);
rc = xc_domain_pause(ctx->xch, domid);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc, "xc_domain_pause failed for %d", domid);
}
if (dm_present) {
if (libxl__destroy_device_model(ctx, domid) < 0)
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "libxl__destroy_device_model failed for %d", domid);
}
if (libxl__devices_destroy(ctx, domid, force) < 0)
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "libxl_destroy_devices failed for %d", domid);
vm_path = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/vm", dom_path));
if (vm_path)
if (!xs_rm(ctx->xsh, XBT_NULL, vm_path))
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "xs_rm failed for %s", vm_path);
if (!xs_rm(ctx->xsh, XBT_NULL, dom_path))
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "xs_rm failed for %s", dom_path);
libxl__userdata_destroyall(ctx, domid);
rc = xc_domain_destroy(ctx->xch, domid);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc, "xc_domain_destroy failed for %d", domid);
rc = ERROR_FAIL;
goto out;
}
rc = 0;
out:
libxl__free_all(&gc);
return 0;
}
int libxl_console_exec(libxl_ctx *ctx, uint32_t domid, int cons_num, libxl_console_constype type)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *p = libxl__sprintf(&gc, "%s/xenconsole", libxl_private_bindir_path());
char *domid_s = libxl__sprintf(&gc, "%d", domid);
char *cons_num_s = libxl__sprintf(&gc, "%d", cons_num);
char *cons_type_s;
switch (type) {
case LIBXL_CONSTYPE_PV:
cons_type_s = "pv";
break;
case LIBXL_CONSTYPE_SERIAL:
cons_type_s = "serial";
break;
default:
goto out;
}
execl(p, p, domid_s, "--num", cons_num_s, "--type", cons_type_s, (void *)NULL);
out:
libxl__free_all(&gc);
return ERROR_FAIL;
}
int libxl_primary_console_exec(libxl_ctx *ctx, uint32_t domid_vm)
{
uint32_t stubdomid = libxl_get_stubdom_id(ctx, domid_vm);
if (stubdomid)
return libxl_console_exec(ctx, stubdomid,
STUBDOM_CONSOLE_SERIAL, LIBXL_CONSTYPE_PV);
else {
if (libxl__domain_is_hvm(ctx, domid_vm))
return libxl_console_exec(ctx, domid_vm, 0, LIBXL_CONSTYPE_SERIAL);
else
return libxl_console_exec(ctx, domid_vm, 0, LIBXL_CONSTYPE_PV);
}
}
int libxl_vncviewer_exec(libxl_ctx *ctx, uint32_t domid, int autopass)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
const char *vnc_port;
const char *vnc_listen = NULL, *vnc_pass = NULL;
int port = 0, autopass_fd = -1;
char *vnc_bin, *args[] = {
"vncviewer",
NULL, /* hostname:display */
NULL, /* -autopass */
NULL,
};
vnc_port = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc,
"/local/domain/%d/console/vnc-port", domid));
if ( vnc_port )
port = atoi(vnc_port) - 5900;
vnc_listen = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc,
"/local/domain/%d/console/vnc-listen", domid));
if ( autopass )
vnc_pass = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc,
"/local/domain/%d/console/vnc-pass", domid));
if ( NULL == vnc_listen )
vnc_listen = "localhost";
if ( (vnc_bin = getenv("VNCVIEWER")) )
args[0] = vnc_bin;
args[1] = libxl__sprintf(&gc, "%s:%d", vnc_listen, port);
if ( vnc_pass ) {
char tmpname[] = "/tmp/vncautopass.XXXXXX";
autopass_fd = mkstemp(tmpname);
if ( autopass_fd < 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"mkstemp %s failed", tmpname);
goto x_fail;
}
if ( unlink(tmpname) ) {
/* should never happen */
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"unlink %s failed", tmpname);
goto x_fail;
}
if ( libxl_write_exactly(ctx, autopass_fd, vnc_pass, strlen(vnc_pass),
tmpname, "vnc password") )
goto x_fail;
if ( lseek(autopass_fd, SEEK_SET, 0) ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"rewind %s (autopass) failed", tmpname);
goto x_fail;
}
args[2] = "-autopass";
}
libxl__exec(autopass_fd, -1, -1, args[0], args);
abort();
x_fail:
libxl__free_all(&gc);
return ERROR_FAIL;
}
/******************************************************************************/
static int validate_virtual_disk(libxl_ctx *ctx, char *file_name,
libxl_device_disk *disk)
{
struct stat stat_buf;
char *delimiter;
if (disk->format == DISK_FORMAT_EMPTY)
return 0;
if (disk->format == DISK_FORMAT_PRESERVATION)
return 0;
if (disk->format == DISK_FORMAT_RAW) {
delimiter = strchr(file_name, ':');
if (delimiter) {
if (!strncmp(file_name, "vhd:", sizeof("vhd:")-1)) {
disk->format = DISK_FORMAT_VHD;
file_name = ++delimiter;
}
}
}
if ( stat(file_name, &stat_buf) != 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "failed to stat %s", file_name);
return ERROR_INVAL;
}
if (disk->backend == DISK_BACKEND_PHY) {
if ( !(S_ISBLK(stat_buf.st_mode)) ) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Virtual disk %s is not a block device!\n",
file_name);
return ERROR_INVAL;
}
} else if ( S_ISREG(stat_buf.st_mode) && stat_buf.st_size == 0 ) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Virtual disk %s size is 0!\n", file_name);
return ERROR_INVAL;
}
return 0;
}
int libxl_device_disk_add(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
char *backend_type;
int devid;
libxl__device device;
int major, minor, rc;
rc = validate_virtual_disk(ctx, disk->pdev_path, disk);
if (rc)
return rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
backend_type = libxl__device_disk_string_of_backend(disk->backend);
devid = libxl__device_disk_dev_number(disk->vdev);
if (devid==-1) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Invalid or unsupported"
" virtual disk identifier %s", disk->vdev);
rc = ERROR_INVAL;
goto out_free;
}
device.backend_devid = devid;
device.backend_domid = disk->backend_domid;
device.devid = devid;
device.domid = disk->domid;
device.kind = DEVICE_VBD;
switch (disk->backend) {
case DISK_BACKEND_PHY:
libxl__device_physdisk_major_minor(disk->pdev_path, &major, &minor);
flexarray_append(back, "physical-device");
flexarray_append(back, libxl__sprintf(&gc, "%x:%x", major, minor));
flexarray_append(back, "params");
flexarray_append(back, disk->pdev_path);
device.backend_kind = DEVICE_VBD;
break;
case DISK_BACKEND_TAP:
if (libxl__blktap_enabled(&gc) && disk->format != DISK_FORMAT_EMPTY) {
const char *dev = libxl__blktap_devpath(&gc,
disk->pdev_path, disk->format);
if (!dev) {
rc = ERROR_FAIL;
goto out_free;
}
flexarray_append(back, "tapdisk-params");
flexarray_append(back, libxl__sprintf(&gc, "%s:%s",
libxl__device_disk_string_of_format(disk->format),
disk->pdev_path));
flexarray_append(back, "params");
flexarray_append(back, libxl__strdup(&gc, dev));
backend_type = "phy";
libxl__device_physdisk_major_minor(dev, &major, &minor);
flexarray_append(back, "physical-device");
flexarray_append(back, libxl__sprintf(&gc, "%x:%x", major, minor));
device.backend_kind = DEVICE_VBD;
break;
}
case DISK_BACKEND_QDISK:
flexarray_append(back, "params");
flexarray_append(back, libxl__sprintf(&gc, "%s:%s",
libxl__device_disk_string_of_format(disk->format), disk->pdev_path));
if (libxl__blktap_enabled(&gc) &&
disk->backend != DISK_BACKEND_QDISK)
device.backend_kind = DEVICE_TAP;
else
device.backend_kind = DEVICE_QDISK;
break;
default:
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unrecognized disk backend type: %d\n", disk->backend);
rc = ERROR_INVAL;
goto out_free;
}
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", disk->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "removable");
flexarray_append(back, libxl__sprintf(&gc, "%d", (disk->unpluggable) ? 1 : 0));
flexarray_append(back, "bootable");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "dev");
flexarray_append(back, disk->vdev);
flexarray_append(back, "type");
flexarray_append(back, backend_type);
flexarray_append(back, "mode");
flexarray_append(back, disk->readwrite ? "w" : "r");
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", disk->backend_domid));
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
flexarray_append(front, "virtual-device");
flexarray_append(front, libxl__sprintf(&gc, "%d", devid));
flexarray_append(front, "device-type");
flexarray_append(front, disk->is_cdrom ? "cdrom" : "disk");
if (0 /* protocol != native*/) {
flexarray_append(front, "protocol");
flexarray_append(front, "x86_32-abi"); /* hardcoded ! */
}
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_disk_del(libxl_ctx *ctx,
libxl_device_disk *disk, int wait)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
libxl__device device;
int devid, rc;
devid = libxl__device_disk_dev_number(disk->vdev);
device.backend_domid = disk->backend_domid;
device.backend_devid = devid;
device.backend_kind =
(disk->backend == DISK_BACKEND_PHY) ? DEVICE_VBD : DEVICE_TAP;
device.domid = disk->domid;
device.devid = devid;
device.kind = DEVICE_VBD;
rc = libxl__device_del(ctx, &device, wait);
xs_rm(ctx->xsh, XBT_NULL, libxl__device_backend_path(&gc, &device));
xs_rm(ctx->xsh, XBT_NULL, libxl__device_frontend_path(&gc, &device));
libxl__free_all(&gc);
return rc;
}
char * libxl_device_disk_local_attach(libxl_ctx *ctx, libxl_device_disk *disk)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
const char *dev = NULL;
char *ret = NULL;
switch (disk->backend) {
case DISK_BACKEND_PHY:
if (disk->format != DISK_FORMAT_RAW) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "physical block device must"
" be raw");
break;
}
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "attaching PHY disk %s to domain 0",
disk->pdev_path);
dev = disk->pdev_path;
break;
case DISK_BACKEND_TAP:
if (disk->format == DISK_FORMAT_VHD || disk->format == DISK_FORMAT_RAW)
{
if (libxl__blktap_enabled(&gc))
dev = libxl__blktap_devpath(&gc, disk->pdev_path, disk->format);
else {
if (disk->format != DISK_FORMAT_RAW) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "tapdisk2 is required"
" to open a vhd disk");
break;
} else {
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "attaching tap disk %s to domain 0",
disk->pdev_path);
dev = disk->pdev_path;
break;
}
}
break;
} else if (disk->format == DISK_FORMAT_QCOW ||
disk->format == DISK_FORMAT_QCOW2) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "cannot locally attach a qcow or qcow2 disk image");
break;
} else {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unrecognized disk backend "
"type: %d", disk->backend);
break;
}
case DISK_BACKEND_QDISK:
if (disk->format != DISK_FORMAT_RAW) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "cannot locally attach a qdisk "
"image if the format is not raw");
break;
}
LIBXL__LOG(ctx, LIBXL__LOG_DEBUG, "attaching qdisk %s to domain 0\n",
disk->pdev_path);
dev = disk->pdev_path;
break;
case DISK_BACKEND_UNKNOWN:
default:
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "unrecognized disk backend "
"type: %d", disk->backend);
break;
}
if (dev != NULL)
ret = strdup(dev);
libxl__free_all(&gc);
return ret;
}
int libxl_device_disk_local_detach(libxl_ctx *ctx, libxl_device_disk *disk)
{
/* Nothing to do for PHYSTYPE_PHY. */
/*
* For other device types assume that the blktap2 process is
* needed by the soon to be started domain and do nothing.
*/
return 0;
}
/******************************************************************************/
int libxl_device_nic_init(libxl_device_nic *nic_info, int devnum)
{
const uint8_t *r;
libxl_uuid uuid;
libxl_uuid_generate(&uuid);
r = libxl_uuid_bytearray(&uuid);
memset(nic_info, '\0', sizeof(*nic_info));
nic_info->backend_domid = 0;
nic_info->domid = 0;
nic_info->devid = devnum;
nic_info->mtu = 1492;
nic_info->model = strdup("rtl8139");
nic_info->mac[0] = 0x00;
nic_info->mac[1] = 0x16;
nic_info->mac[2] = 0x3e;
nic_info->mac[3] = r[0] & 0x7f;
nic_info->mac[4] = r[1];
nic_info->mac[5] = r[2];
nic_info->ifname = NULL;
nic_info->bridge = strdup("xenbr0");
nic_info->ip = NULL;
if ( asprintf(&nic_info->script, "%s/vif-bridge",
libxl_xen_script_dir_path()) < 0 )
return ERROR_FAIL;
nic_info->nictype = NICTYPE_IOEMU;
return 0;
}
int libxl_device_nic_add(libxl_ctx *ctx, uint32_t domid, libxl_device_nic *nic)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
char *dompath, **l;
unsigned int nb, rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
if (nic->devid == -1) {
if (!(dompath = libxl__xs_get_dompath(&gc, domid))) {
rc = ERROR_FAIL;
goto out_free;
}
if (!(l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif", dompath), &nb))) {
nic->devid = 0;
} else {
nic->devid = strtoul(l[nb - 1], NULL, 10) + 1;
}
}
device.backend_devid = nic->devid;
device.backend_domid = nic->backend_domid;
device.backend_kind = DEVICE_VIF;
device.devid = nic->devid;
device.domid = nic->domid;
device.kind = DEVICE_VIF;
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", nic->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "script");
flexarray_append(back, nic->script);
flexarray_append(back, "mac");
flexarray_append(back, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
nic->mac[0], nic->mac[1], nic->mac[2],
nic->mac[3], nic->mac[4], nic->mac[5]));
if (nic->ip) {
flexarray_append(back, "ip");
flexarray_append(back, libxl__strdup(&gc, nic->ip));
}
flexarray_append(back, "bridge");
flexarray_append(back, libxl__strdup(&gc, nic->bridge));
flexarray_append(back, "handle");
flexarray_append(back, libxl__sprintf(&gc, "%d", nic->devid));
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", nic->backend_domid));
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
flexarray_append(front, "handle");
flexarray_append(front, libxl__sprintf(&gc, "%d", nic->devid));
flexarray_append(front, "mac");
flexarray_append(front, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
nic->mac[0], nic->mac[1], nic->mac[2],
nic->mac[3], nic->mac[4], nic->mac[5]));
if (0 /* protocol != native*/) {
flexarray_append(front, "protocol");
flexarray_append(front, "x86_32-abi"); /* hardcoded ! */
}
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
/* FIXME: wait for plug */
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_nic_del(libxl_ctx *ctx,
libxl_device_nic *nic, int wait)
{
libxl__device device;
device.backend_devid = nic->devid;
device.backend_domid = nic->backend_domid;
device.backend_kind = DEVICE_VIF;
device.devid = nic->devid;
device.domid = nic->domid;
device.kind = DEVICE_VIF;
return libxl__device_del(ctx, &device, wait);
}
libxl_nicinfo *libxl_list_nics(libxl_ctx *ctx, uint32_t domid, unsigned int *nb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath, *nic_path_fe;
char **l, **list;
char *val, *tok;
unsigned int nb_nics, i;
libxl_nicinfo *res, *nics;
dompath = libxl__xs_get_dompath(&gc, domid);
if (!dompath)
goto err;
list = l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif", dompath), &nb_nics);
if (!l)
goto err;
nics = res = calloc(nb_nics, sizeof (libxl_device_nic));
if (!res)
goto err;
for (*nb = nb_nics; nb_nics > 0; --nb_nics, ++l, ++nics) {
nic_path_fe = libxl__sprintf(&gc, "%s/device/vif/%s", dompath, *l);
nics->backend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/backend", nic_path_fe), NULL);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend-id", nic_path_fe));
nics->backend_id = val ? strtoul(val, NULL, 10) : -1;
nics->devid = strtoul(*l, NULL, 10);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/state", nic_path_fe));
nics->state = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/mac", nic_path_fe));
for (i = 0, tok = strtok(val, ":"); tok && (i < 6);
++i, tok = strtok(NULL, ":")) {
nics->mac[i] = strtoul(tok, NULL, 16);
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/event-channel", nic_path_fe));
nics->evtch = val ? strtol(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/tx-ring-ref", nic_path_fe));
nics->rref_tx = val ? strtol(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/rx-ring-ref", nic_path_fe));
nics->rref_rx = val ? strtol(val, NULL, 10) : -1;
nics->frontend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/frontend", nics->backend), NULL);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/frontend-id", nics->backend));
nics->frontend_id = val ? strtoul(val, NULL, 10) : -1;
nics->script = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/script", nics->backend), NULL);
}
libxl__free_all(&gc);
return res;
err:
libxl__free_all(&gc);
return NULL;
}
/******************************************************************************/
void libxl_device_net2_init(libxl_device_net2 *net2_info, int devnum)
{
const uint8_t *r;
libxl_uuid uuid;
libxl_uuid_generate(&uuid);
r = libxl_uuid_bytearray(&uuid);
memset(net2_info, '\0', sizeof(*net2_info));
net2_info->devid = devnum;
net2_info->front_mac[0] = 0x00;
net2_info->front_mac[1] = 0x16;
net2_info->front_mac[2] = 0x3e;;
net2_info->front_mac[3] = 0x7f & r[0];
net2_info->front_mac[4] = r[1];
net2_info->front_mac[5] = r[2];
net2_info->back_mac[0] = 0x00;
net2_info->back_mac[1] = 0x16;
net2_info->back_mac[2] = 0x3e;
net2_info->back_mac[3] = 0x7f & r[3];
net2_info->back_mac[4] = r[4];
net2_info->back_mac[5] = r[5];
net2_info->back_trusted = 1;
net2_info->filter_mac = 1;
net2_info->max_bypasses = 5;
net2_info->bridge = strdup("xenbr0");
}
int libxl_device_net2_add(libxl_ctx *ctx, uint32_t domid, libxl_device_net2 *net2)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front, *back;
libxl__device device;
char *dompath, *dom, **l;
unsigned int nb;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto err;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto err_free;
}
if (!(dompath = libxl__xs_get_dompath(&gc, domid))) {
rc = ERROR_FAIL;
goto err_free;
}
dom = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/name", dompath));
if (net2->devid == -1) {
if (!(l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif2", dompath), &nb))) {
net2->devid = 0;
} else {
net2->devid = strtoul(l[nb - 1], NULL, 10) + 1;
}
}
device.backend_devid = net2->devid;
device.backend_domid = net2->backend_domid;
device.backend_kind = DEVICE_VIF2;
device.devid = net2->devid;
device.domid = net2->domid;
device.kind = DEVICE_VIF2;
flexarray_append(back, "domain");
flexarray_append(back, dom);
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->domid));
flexarray_append(back, "local-trusted");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->back_trusted));
flexarray_append(back, "mac");
flexarray_append(back, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->back_mac[0], net2->back_mac[1],
net2->back_mac[2], net2->back_mac[3],
net2->back_mac[4], net2->back_mac[5]));
flexarray_append(back, "remote-trusted");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->trusted));
flexarray_append(back, "remote-mac");
flexarray_append(back, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->front_mac[0], net2->front_mac[1],
net2->front_mac[2], net2->front_mac[3],
net2->front_mac[4], net2->front_mac[5]));
flexarray_append(back, "max-bypasses");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->max_bypasses));
flexarray_append(back, "filter-mac");
flexarray_append(back, libxl__sprintf(&gc, "%d", !!(net2->filter_mac)));
flexarray_append(back, "handle");
flexarray_append(back, libxl__sprintf(&gc, "%d", net2->devid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, "1");
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", net2->backend_domid));
flexarray_append(front, "local-trusted");
flexarray_append(front, libxl__sprintf(&gc, "%d", net2->trusted));
flexarray_append(front, "mac");
flexarray_append(front, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->front_mac[0], net2->front_mac[1],
net2->front_mac[2], net2->front_mac[3],
net2->front_mac[4], net2->front_mac[5]));
flexarray_append(front, "remote-trusted");
flexarray_append(front, libxl__sprintf(&gc, "%d", net2->back_trusted));
flexarray_append(front, "remote-mac");
flexarray_append(front, libxl__sprintf(&gc, "%02x:%02x:%02x:%02x:%02x:%02x",
net2->back_mac[0], net2->back_mac[1],
net2->back_mac[2], net2->back_mac[3],
net2->back_mac[4], net2->back_mac[5]));
flexarray_append(front, "filter-mac");
flexarray_append(front, libxl__sprintf(&gc, "%d", !!(net2->filter_mac)));
flexarray_append(front, "state");
flexarray_append(front, "1");
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
/* FIXME: wait for plug */
rc = 0;
err_free:
flexarray_free(back);
flexarray_free(front);
err:
libxl__free_all(&gc);
return rc;
}
libxl_net2info *libxl_device_net2_list(libxl_ctx *ctx, uint32_t domid, unsigned int *nb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath, *net2_path_fe;
char **l;
char *val, *tok;
unsigned int nb_net2s, i;
libxl_net2info *res, *net2s;
dompath = libxl__xs_get_dompath(&gc, domid);
if (!dompath)
goto err;
l = libxl__xs_directory(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/device/vif2", dompath), &nb_net2s);
if (!l)
goto err;
res = calloc(nb_net2s, sizeof (libxl_net2info));
if (!res)
goto err;
net2s = res;
for (*nb = nb_net2s; nb_net2s > 0; --nb_net2s, ++l, ++net2s) {
net2_path_fe = libxl__sprintf(&gc, "%s/device/vif2/%s", dompath, *l);
net2s->backend = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/backend", net2_path_fe));
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend-id", net2_path_fe));
net2s->backend_id = val ? strtoul(val, NULL, 10) : -1;
net2s->devid = strtoul(*l, NULL, 10);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/state", net2_path_fe));
net2s->state = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/mac", net2_path_fe));
for (i = 0, tok = strtok(val, ":"); tok && (i < 6);
++i, tok = strtok(NULL, ":")) {
net2s->mac[i] = strtoul(tok, NULL, 16);
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/remote-trusted", net2_path_fe));
net2s->trusted = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/remote-mac", net2_path_fe));
for (i = 0, tok = strtok(val, ":"); tok && (i < 6);
++i, tok = strtok(NULL, ":")) {
net2s->back_mac[i] = strtoul(tok, NULL, 16);
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/filter-mac", net2_path_fe));
net2s->filter_mac = val ? strtoul(val, NULL, 10) : -1;
net2s->frontend = libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/frontend", net2s->backend));
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/frontend-id", net2s->backend));
net2s->frontend_id = val ? strtoul(val, NULL, 10) : -1;
}
libxl__free_all(&gc);
return res;
err:
libxl__free_all(&gc);
return NULL;
}
int libxl_device_net2_del(libxl_ctx *ctx, libxl_device_net2 *net2, int wait)
{
libxl__device device;
device.backend_devid = net2->devid;
device.backend_domid = net2->backend_domid;
device.backend_kind = DEVICE_VIF2;
device.devid = net2->devid;
device.domid = net2->domid;
device.kind = DEVICE_VIF2;
return libxl__device_del(ctx, &device, wait);
}
/******************************************************************************/
int libxl_device_console_add(libxl_ctx *ctx, uint32_t domid, libxl_device_console *console)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
device.backend_devid = console->devid;
device.backend_domid = console->backend_domid;
device.backend_kind = DEVICE_CONSOLE;
device.devid = console->devid;
device.domid = console->domid;
device.kind = DEVICE_CONSOLE;
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", console->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "domain");
flexarray_append(back, libxl__domid_to_name(&gc, domid));
flexarray_append(back, "protocol");
flexarray_append(back, LIBXL_XENCONSOLE_PROTOCOL);
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", console->backend_domid));
flexarray_append(front, "limit");
flexarray_append(front, libxl__sprintf(&gc, "%d", LIBXL_XENCONSOLE_LIMIT));
flexarray_append(front, "type");
if (console->consback == LIBXL_CONSBACK_XENCONSOLED)
flexarray_append(front, "xenconsoled");
else
flexarray_append(front, "ioemu");
flexarray_append(front, "output");
flexarray_append(front, console->output);
if (device.devid == 0) {
if (console->build_state == NULL) {
rc = ERROR_INVAL;
goto out_free;
}
flexarray_append(front, "port");
flexarray_append(front, libxl__sprintf(&gc, "%"PRIu32, console->build_state->console_port));
flexarray_append(front, "ring-ref");
flexarray_append(front, libxl__sprintf(&gc, "%lu", console->build_state->console_mfn));
} else {
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
flexarray_append(front, "protocol");
flexarray_append(front, LIBXL_XENCONSOLE_PROTOCOL);
}
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
/******************************************************************************/
void libxl_device_vkb_init(libxl_device_vkb *vkb, int dev_num)
{
memset(vkb, 0x00, sizeof(libxl_device_vkb));
vkb->devid = dev_num;
}
int libxl_device_vkb_add(libxl_ctx *ctx, uint32_t domid, libxl_device_vkb *vkb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
device.backend_devid = vkb->devid;
device.backend_domid = vkb->backend_domid;
device.backend_kind = DEVICE_VKBD;
device.devid = vkb->devid;
device.domid = vkb->domid;
device.kind = DEVICE_VKBD;
flexarray_append(back, "frontend-id");
flexarray_append(back, libxl__sprintf(&gc, "%d", vkb->domid));
flexarray_append(back, "online");
flexarray_append(back, "1");
flexarray_append(back, "state");
flexarray_append(back, libxl__sprintf(&gc, "%d", 1));
flexarray_append(back, "domain");
flexarray_append(back, libxl__domid_to_name(&gc, domid));
flexarray_append(front, "backend-id");
flexarray_append(front, libxl__sprintf(&gc, "%d", vkb->backend_domid));
flexarray_append(front, "state");
flexarray_append(front, libxl__sprintf(&gc, "%d", 1));
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(back);
flexarray_free(front);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_vkb_clean_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
int libxl_device_vkb_hard_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
static unsigned int libxl_append_disk_list_of_type(libxl_ctx *ctx,
uint32_t domid,
const char *type,
libxl_device_disk **disks,
unsigned int *ndisks)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *be_path = NULL;
char **dir = NULL;
unsigned int n = 0, len = 0;
libxl_device_disk *pdisk = NULL, *pdisk_end = NULL;
char *physpath_tmp = NULL;
be_path = libxl__sprintf(&gc, "%s/backend/%s/%d",
libxl__xs_get_dompath(&gc, 0), type, domid);
dir = libxl__xs_directory(&gc, XBT_NULL, be_path, &n);
if (dir) {
char *removable;
*disks = realloc(*disks, sizeof (libxl_device_disk) * (*ndisks + n));
pdisk = *disks + *ndisks;
*ndisks += n;
pdisk_end = *disks + *ndisks;
for (; pdisk < pdisk_end; pdisk++, dir++) {
pdisk->backend_domid = 0;
pdisk->domid = domid;
physpath_tmp = xs_read(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "%s/%s/params", be_path, *dir), &len);
if (physpath_tmp && strchr(physpath_tmp, ':')) {
pdisk->pdev_path = strdup(strchr(physpath_tmp, ':') + 1);
free(physpath_tmp);
} else {
pdisk->pdev_path = physpath_tmp;
}
libxl_string_to_backend(ctx, libxl__xs_read(&gc, XBT_NULL,
libxl__sprintf(&gc, "%s/%s/type", be_path, *dir)),
&(pdisk->backend));
pdisk->vdev = xs_read(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "%s/%s/dev", be_path, *dir), &len);
removable = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/%s/removable", be_path, *dir));
if (removable)
pdisk->unpluggable = atoi(removable);
else
pdisk->unpluggable = 0;
if (!strcmp(libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/%s/mode", be_path, *dir)), "w"))
pdisk->readwrite = 1;
else
pdisk->readwrite = 0;
type = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/device-type", libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/%s/frontend", be_path, *dir))));
pdisk->is_cdrom = !strcmp(type, "cdrom");
}
}
libxl__free_all(&gc);
return n;
}
libxl_device_disk *libxl_device_disk_list(libxl_ctx *ctx, uint32_t domid, int *num)
{
libxl_device_disk *disks = NULL;
unsigned int ndisks = 0;
*num = libxl_append_disk_list_of_type(ctx, domid, "vbd", &disks, &ndisks);
*num += libxl_append_disk_list_of_type(ctx, domid, "tap", &disks, &ndisks);
*num += libxl_append_disk_list_of_type(ctx, domid, "qdisk", &disks, &ndisks);
return disks;
}
int libxl_device_disk_getinfo(libxl_ctx *ctx, uint32_t domid,
libxl_device_disk *disk, libxl_diskinfo *diskinfo)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath, *diskpath;
char *val;
dompath = libxl__xs_get_dompath(&gc, domid);
diskinfo->devid = libxl__device_disk_dev_number(disk->vdev);
/* tap devices entries in xenstore are written as vbd devices. */
diskpath = libxl__sprintf(&gc, "%s/device/vbd/%d", dompath, diskinfo->devid);
diskinfo->backend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/backend", diskpath), NULL);
if (!diskinfo->backend) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/backend-id", diskpath));
diskinfo->backend_id = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/state", diskpath));
diskinfo->state = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/event-channel", diskpath));
diskinfo->evtch = val ? strtoul(val, NULL, 10) : -1;
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/ring-ref", diskpath));
diskinfo->rref = val ? strtoul(val, NULL, 10) : -1;
diskinfo->frontend = xs_read(ctx->xsh, XBT_NULL,
libxl__sprintf(&gc, "%s/frontend", diskinfo->backend), NULL);
val = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/frontend-id", diskinfo->backend));
diskinfo->frontend_id = val ? strtoul(val, NULL, 10) : -1;
libxl__free_all(&gc);
return 0;
}
int libxl_cdrom_insert(libxl_ctx *ctx, uint32_t domid, libxl_device_disk *disk)
{
int num, i;
uint32_t stubdomid;
libxl_device_disk *disks;
int ret = ERROR_FAIL;
if (!disk->pdev_path) {
disk->pdev_path = strdup("");
disk->format = DISK_FORMAT_EMPTY;
}
disks = libxl_device_disk_list(ctx, domid, &num);
for (i = 0; i < num; i++) {
if (disks[i].is_cdrom && !strcmp(disk->vdev, disks[i].vdev))
/* found */
break;
}
if (i == num) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR, "Virtual device not found");
goto out;
}
ret = 0;
libxl_device_disk_del(ctx, disks + i, 1);
libxl_device_disk_add(ctx, domid, disk);
stubdomid = libxl_get_stubdom_id(ctx, domid);
if (stubdomid) {
disks[i].domid = stubdomid;
libxl_device_disk_del(ctx, disks + i, 1);
disk->domid = stubdomid;
libxl_device_disk_add(ctx, stubdomid, disk);
disk->domid = domid;
}
out:
for (i = 0; i < num; i++)
libxl_device_disk_destroy(&disks[i]);
free(disks);
return ret;
}
/******************************************************************************/
void libxl_device_vfb_init(libxl_device_vfb *vfb, int dev_num)
{
memset(vfb, 0x00, sizeof(libxl_device_vfb));
vfb->devid = dev_num;
vfb->display = NULL;
vfb->xauthority = NULL;
vfb->vnc = 1;
vfb->vncpasswd = NULL;
vfb->vnclisten = strdup("127.0.0.1");
vfb->vncdisplay = 0;
vfb->vncunused = 1;
vfb->keymap = NULL;
vfb->sdl = 0;
vfb->opengl = 0;
}
int libxl_device_vfb_add(libxl_ctx *ctx, uint32_t domid, libxl_device_vfb *vfb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
flexarray_t *front;
flexarray_t *back;
libxl__device device;
int rc;
front = flexarray_make(16, 1);
if (!front) {
rc = ERROR_NOMEM;
goto out;
}
back = flexarray_make(16, 1);
if (!back) {
rc = ERROR_NOMEM;
goto out_free;
}
device.backend_devid = vfb->devid;
device.backend_domid = vfb->backend_domid;
device.backend_kind = DEVICE_VFB;
device.devid = vfb->devid;
device.domid = vfb->domid;
device.kind = DEVICE_VFB;
flexarray_append_pair(back, "frontend-id", libxl__sprintf(&gc, "%d", vfb->domid));
flexarray_append_pair(back, "online", "1");
flexarray_append_pair(back, "state", libxl__sprintf(&gc, "%d", 1));
flexarray_append_pair(back, "domain", libxl__domid_to_name(&gc, domid));
flexarray_append_pair(back, "vnc", libxl__sprintf(&gc, "%d", vfb->vnc));
flexarray_append_pair(back, "vnclisten", vfb->vnclisten);
flexarray_append_pair(back, "vncpasswd", vfb->vncpasswd);
flexarray_append_pair(back, "vncdisplay", libxl__sprintf(&gc, "%d", vfb->vncdisplay));
flexarray_append_pair(back, "vncunused", libxl__sprintf(&gc, "%d", vfb->vncunused));
flexarray_append_pair(back, "sdl", libxl__sprintf(&gc, "%d", vfb->sdl));
flexarray_append_pair(back, "opengl", libxl__sprintf(&gc, "%d", vfb->opengl));
if (vfb->xauthority) {
flexarray_append_pair(back, "xauthority", vfb->xauthority);
}
if (vfb->display) {
flexarray_append_pair(back, "display", vfb->display);
}
flexarray_append_pair(front, "backend-id", libxl__sprintf(&gc, "%d", vfb->backend_domid));
flexarray_append_pair(front, "state", libxl__sprintf(&gc, "%d", 1));
libxl__device_generic_add(ctx, &device,
libxl__xs_kvs_of_flexarray(&gc, back, back->count),
libxl__xs_kvs_of_flexarray(&gc, front, front->count));
rc = 0;
out_free:
flexarray_free(front);
flexarray_free(back);
out:
libxl__free_all(&gc);
return rc;
}
int libxl_device_vfb_clean_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
int libxl_device_vfb_hard_shutdown(libxl_ctx *ctx, uint32_t domid)
{
return ERROR_NI;
}
/******************************************************************************/
int libxl_domain_setmaxmem(libxl_ctx *ctx, uint32_t domid, uint32_t max_memkb)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *mem, *endptr;
uint32_t memorykb;
char *dompath = libxl__xs_get_dompath(&gc, domid);
int rc = 1;
mem = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/memory/target", dompath));
if (!mem) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot get memory info from %s/memory/target\n", dompath);
goto out;
}
memorykb = strtoul(mem, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "invalid memory %s from %s/memory/target\n", mem, dompath);
goto out;
}
if (max_memkb < memorykb) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "memory_static_max must be greater than or or equal to memory_dynamic_max\n");
goto out;
}
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
static int libxl__fill_dom0_memory_info(libxl__gc *gc, uint32_t *target_memkb)
{
int rc;
libxl_dominfo info;
libxl_physinfo physinfo;
char *target = NULL, *staticmax = NULL, *freememslack = NULL, *endptr = NULL;
char *target_path = "/local/domain/0/memory/target";
char *max_path = "/local/domain/0/memory/static-max";
char *free_mem_slack_path = "/local/domain/0/memory/freemem-slack";
xs_transaction_t t;
libxl_ctx *ctx = libxl__gc_owner(gc);
uint32_t free_mem_slack_kb = 0;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
target = libxl__xs_read(gc, t, target_path);
staticmax = libxl__xs_read(gc, t, max_path);
freememslack = libxl__xs_read(gc, t, free_mem_slack_path);
if (target && staticmax && freememslack) {
rc = 0;
goto out;
}
if (target) {
*target_memkb = strtoul(target, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid memory target %s from %s\n", target, target_path);
rc = ERROR_FAIL;
goto out;
}
}
rc = libxl_domain_info(ctx, &info, 0);
if (rc < 0)
goto out;
rc = libxl_get_physinfo(ctx, &physinfo);
if (rc < 0)
goto out;
if (target == NULL) {
libxl__xs_write(gc, t, target_path, "%"PRIu32,
(uint32_t) info.current_memkb);
*target_memkb = (uint32_t) info.current_memkb;
}
if (staticmax == NULL)
libxl__xs_write(gc, t, max_path, "%"PRIu32,
(uint32_t) info.max_memkb);
if (freememslack == NULL) {
free_mem_slack_kb = (uint32_t) (PAGE_TO_MEMKB(physinfo.total_pages) -
info.current_memkb);
/* From empirical measurements the free_mem_slack shouldn't be more
* than 15% of the total memory present on the system. */
if (free_mem_slack_kb > PAGE_TO_MEMKB(physinfo.total_pages) * 0.15)
free_mem_slack_kb = PAGE_TO_MEMKB(physinfo.total_pages) * 0.15;
libxl__xs_write(gc, t, free_mem_slack_path, "%"PRIu32, free_mem_slack_kb);
}
rc = 0;
out:
if (!xs_transaction_end(ctx->xsh, t, 0)) {
if (errno == EAGAIN)
goto retry_transaction;
else
rc = ERROR_FAIL;
}
return rc;
}
/* returns how much memory should be left free in the system */
static int libxl__get_free_memory_slack(libxl__gc *gc, uint32_t *free_mem_slack)
{
int rc;
char *free_mem_slack_path = "/local/domain/0/memory/freemem-slack";
char *free_mem_slack_s, *endptr;
uint32_t target_memkb;
retry:
free_mem_slack_s = libxl__xs_read(gc, XBT_NULL, free_mem_slack_path);
if (!free_mem_slack_s) {
rc = libxl__fill_dom0_memory_info(gc, &target_memkb);
if (rc < 0)
return rc;
goto retry;
} else {
*free_mem_slack = strtoul(free_mem_slack_s, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(gc->owner, LIBXL__LOG_ERROR,
"invalid free_mem_slack %s from %s\n",
free_mem_slack_s, free_mem_slack_path);
return ERROR_FAIL;
}
}
return 0;
}
int libxl_set_memory_target(libxl_ctx *ctx, uint32_t domid,
int32_t target_memkb, int relative, int enforce)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc = 1, abort = 0;
uint32_t memorykb = 0, videoram = 0;
uint32_t current_target_memkb = 0, new_target_memkb = 0;
char *memmax, *endptr, *videoram_s = NULL, *target = NULL;
char *dompath = libxl__xs_get_dompath(&gc, domid);
xc_domaininfo_t info;
libxl_dominfo ptr;
char *uuid;
xs_transaction_t t;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
target = libxl__xs_read(&gc, t, libxl__sprintf(&gc,
"%s/memory/target", dompath));
if (!target && !domid) {
xs_transaction_end(ctx->xsh, t, 1);
rc = libxl__fill_dom0_memory_info(&gc, ¤t_target_memkb);
if (rc < 0) {
abort = 1;
goto out;
}
goto retry_transaction;
} else if (!target) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"cannot get target memory info from %s/memory/target\n",
dompath);
abort = 1;
goto out;
} else {
current_target_memkb = strtoul(target, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid memory target %s from %s/memory/target\n",
target, dompath);
abort = 1;
goto out;
}
}
memmax = libxl__xs_read(&gc, t, libxl__sprintf(&gc,
"%s/memory/static-max", dompath));
if (!memmax) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"cannot get memory info from %s/memory/static-max\n",
dompath);
abort = 1;
goto out;
}
memorykb = strtoul(memmax, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid max memory %s from %s/memory/static-max\n",
memmax, dompath);
abort = 1;
goto out;
}
if (relative) {
if (target_memkb < 0 && abs(target_memkb) > current_target_memkb)
new_target_memkb = 0;
else
new_target_memkb = current_target_memkb + target_memkb;
} else
new_target_memkb = target_memkb;
if (new_target_memkb > memorykb) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR,
"memory_dynamic_max must be less than or equal to"
" memory_static_max\n");
abort = 1;
goto out;
}
if (!domid && new_target_memkb < LIBXL_MIN_DOM0_MEM) {
LIBXL__LOG(ctx, LIBXL__LOG_ERROR,
"new target %d for dom0 is below the minimum threshold\n",
new_target_memkb);
abort = 1;
goto out;
}
videoram_s = libxl__xs_read(&gc, t, libxl__sprintf(&gc,
"%s/memory/videoram", dompath));
videoram = videoram_s ? atoi(videoram_s) : 0;
if (enforce) {
memorykb = new_target_memkb;
rc = xc_domain_setmaxmem(ctx->xch, domid, memorykb +
LIBXL_MAXMEM_CONSTANT);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xc_domain_setmaxmem domid=%d memkb=%d failed "
"rc=%d\n", domid, memorykb + LIBXL_MAXMEM_CONSTANT, rc);
abort = 1;
goto out;
}
}
new_target_memkb -= videoram;
rc = xc_domain_set_pod_target(ctx->xch, domid,
new_target_memkb / 4, NULL, NULL, NULL);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"xc_domain_set_pod_target domid=%d, memkb=%d "
"failed rc=%d\n", domid, new_target_memkb / 4,
rc);
abort = 1;
goto out;
}
libxl__xs_write(&gc, t, libxl__sprintf(&gc, "%s/memory/target",
dompath), "%"PRIu32, new_target_memkb);
rc = xc_domain_getinfolist(ctx->xch, domid, 1, &info);
if (rc != 1 || info.domain != domid) {
abort = 1;
goto out;
}
xcinfo2xlinfo(&info, &ptr);
uuid = libxl__uuid2string(&gc, ptr.uuid);
libxl__xs_write(&gc, t, libxl__sprintf(&gc, "/vm/%s/memory", uuid),
"%"PRIu32, new_target_memkb / 1024);
out:
if (!xs_transaction_end(ctx->xsh, t, abort) && !abort)
if (errno == EAGAIN)
goto retry_transaction;
libxl__free_all(&gc);
return rc;
}
int libxl_get_memory_target(libxl_ctx *ctx, uint32_t domid, uint32_t *out_target)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc = 1;
char *target = NULL, *endptr = NULL;
char *dompath = libxl__xs_get_dompath(&gc, domid);
uint32_t target_memkb;
target = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc,
"%s/memory/target", dompath));
if (!target && !domid) {
rc = libxl__fill_dom0_memory_info(&gc, &target_memkb);
if (rc < 0)
goto out;
} else if (!target) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"cannot get target memory info from %s/memory/target\n",
dompath);
goto out;
} else {
target_memkb = strtoul(target, &endptr, 10);
if (*endptr != '\0') {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR,
"invalid memory target %s from %s/memory/target\n",
target, dompath);
goto out;
}
}
*out_target = target_memkb;
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_domain_need_memory(libxl_ctx *ctx, libxl_domain_build_info *b_info,
libxl_device_model_info *dm_info, uint32_t *need_memkb)
{
*need_memkb = b_info->target_memkb;
if (b_info->hvm) {
*need_memkb += b_info->shadow_memkb + LIBXL_HVM_EXTRA_MEMORY;
if (strstr(dm_info->device_model, "stubdom-dm"))
*need_memkb += 32 * 1024;
} else
*need_memkb += b_info->shadow_memkb + LIBXL_PV_EXTRA_MEMORY;
if (*need_memkb % (2 * 1024))
*need_memkb += (2 * 1024) - (*need_memkb % (2 * 1024));
return 0;
}
int libxl_get_free_memory(libxl_ctx *ctx, uint32_t *memkb)
{
int rc = 0;
libxl_physinfo info;
uint32_t freemem_slack;
libxl__gc gc = LIBXL_INIT_GC(ctx);
rc = libxl_get_physinfo(ctx, &info);
if (rc < 0)
goto out;
rc = libxl__get_free_memory_slack(&gc, &freemem_slack);
if (rc < 0)
goto out;
if ((info.free_pages + info.scrub_pages) * 4 > freemem_slack)
*memkb = (info.free_pages + info.scrub_pages) * 4 - freemem_slack;
else
*memkb = 0;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_wait_for_free_memory(libxl_ctx *ctx, uint32_t domid, uint32_t
memory_kb, int wait_secs)
{
int rc = 0;
libxl_physinfo info;
uint32_t freemem_slack;
libxl__gc gc = LIBXL_INIT_GC(ctx);
rc = libxl__get_free_memory_slack(&gc, &freemem_slack);
if (rc < 0)
goto out;
while (wait_secs > 0) {
rc = libxl_get_physinfo(ctx, &info);
if (rc < 0)
goto out;
if (info.free_pages * 4 - freemem_slack >= memory_kb) {
rc = 0;
goto out;
}
wait_secs--;
sleep(1);
}
rc = ERROR_NOMEM;
out:
libxl__free_all(&gc);
return rc;
}
int libxl_wait_for_memory_target(libxl_ctx *ctx, uint32_t domid, int wait_secs)
{
int rc = 0;
uint32_t target_memkb = 0;
libxl_dominfo info;
do {
wait_secs--;
sleep(1);
rc = libxl_get_memory_target(ctx, domid, &target_memkb);
if (rc < 0)
goto out;
rc = libxl_domain_info(ctx, &info, domid);
if (rc < 0)
return rc;
} while (wait_secs > 0 && info.current_memkb > target_memkb);
if (info.current_memkb <= target_memkb)
rc = 0;
else
rc = ERROR_FAIL;
out:
return 0;
}
int libxl_button_press(libxl_ctx *ctx, uint32_t domid, libxl_button button)
{
int rc = -1;
switch (button) {
case POWER_BUTTON:
rc = xc_domain_send_trigger(ctx->xch, domid, XEN_DOMCTL_SENDTRIGGER_POWER, 0);
break;
case SLEEP_BUTTON:
rc = xc_domain_send_trigger(ctx->xch, domid, XEN_DOMCTL_SENDTRIGGER_SLEEP, 0);
break;
default:
break;
}
return rc;
}
int libxl_get_physinfo(libxl_ctx *ctx, libxl_physinfo *physinfo)
{
xc_physinfo_t xcphysinfo = { 0 };
int rc;
rc = xc_physinfo(ctx->xch, &xcphysinfo);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting physinfo");
return ERROR_FAIL;
}
physinfo->threads_per_core = xcphysinfo.threads_per_core;
physinfo->cores_per_socket = xcphysinfo.cores_per_socket;
physinfo->max_cpu_id = xcphysinfo.max_cpu_id;
physinfo->nr_cpus = xcphysinfo.nr_cpus;
physinfo->cpu_khz = xcphysinfo.cpu_khz;
physinfo->total_pages = xcphysinfo.total_pages;
physinfo->free_pages = xcphysinfo.free_pages;
physinfo->scrub_pages = xcphysinfo.scrub_pages;
physinfo->nr_nodes = xcphysinfo.nr_nodes;
memcpy(physinfo->hw_cap,xcphysinfo.hw_cap, sizeof(physinfo->hw_cap));
physinfo->phys_cap = xcphysinfo.capabilities;
return 0;
}
int libxl_get_topologyinfo(libxl_ctx *ctx, libxl_topologyinfo *info)
{
xc_topologyinfo_t tinfo;
DECLARE_HYPERCALL_BUFFER(xc_cpu_to_core_t, coremap);
DECLARE_HYPERCALL_BUFFER(xc_cpu_to_socket_t, socketmap);
DECLARE_HYPERCALL_BUFFER(xc_cpu_to_node_t, nodemap);
int i;
int rc = 0;
rc += libxl_cpuarray_alloc(ctx, &info->coremap);
rc += libxl_cpuarray_alloc(ctx, &info->socketmap);
rc += libxl_cpuarray_alloc(ctx, &info->nodemap);
if (rc)
goto fail;
coremap = xc_hypercall_buffer_alloc(ctx->xch, coremap, sizeof(*coremap) * info->coremap.entries);
socketmap = xc_hypercall_buffer_alloc(ctx->xch, socketmap, sizeof(*socketmap) * info->socketmap.entries);
nodemap = xc_hypercall_buffer_alloc(ctx->xch, nodemap, sizeof(*nodemap) * info->nodemap.entries);
if ((coremap == NULL) || (socketmap == NULL) || (nodemap == NULL))
goto fail;
set_xen_guest_handle(tinfo.cpu_to_core, coremap);
set_xen_guest_handle(tinfo.cpu_to_socket, socketmap);
set_xen_guest_handle(tinfo.cpu_to_node, nodemap);
tinfo.max_cpu_index = info->coremap.entries - 1;
if (xc_topologyinfo(ctx->xch, &tinfo) != 0)
goto fail;
for (i = 0; i <= tinfo.max_cpu_index; i++) {
if (i < info->coremap.entries)
info->coremap.array[i] = (coremap[i] == INVALID_TOPOLOGY_ID) ?
LIBXL_CPUARRAY_INVALID_ENTRY : coremap[i];
if (i < info->socketmap.entries)
info->socketmap.array[i] = (socketmap[i] == INVALID_TOPOLOGY_ID) ?
LIBXL_CPUARRAY_INVALID_ENTRY : socketmap[i];
if (i < info->nodemap.entries)
info->nodemap.array[i] = (nodemap[i] == INVALID_TOPOLOGY_ID) ?
LIBXL_CPUARRAY_INVALID_ENTRY : nodemap[i];
}
xc_hypercall_buffer_free(ctx->xch, coremap);
xc_hypercall_buffer_free(ctx->xch, socketmap);
xc_hypercall_buffer_free(ctx->xch, nodemap);
return 0;
fail:
xc_hypercall_buffer_free(ctx->xch, coremap);
xc_hypercall_buffer_free(ctx->xch, socketmap);
xc_hypercall_buffer_free(ctx->xch, nodemap);
libxl_topologyinfo_destroy(info);
return ERROR_FAIL;
}
const libxl_version_info* libxl_get_version_info(libxl_ctx *ctx)
{
union {
xen_extraversion_t xen_extra;
xen_compile_info_t xen_cc;
xen_changeset_info_t xen_chgset;
xen_capabilities_info_t xen_caps;
xen_platform_parameters_t p_parms;
xen_commandline_t xen_commandline;
} u;
long xen_version;
libxl_version_info *info = &ctx->version_info;
if (info->xen_version_extra != NULL)
return info;
xen_version = xc_version(ctx->xch, XENVER_version, NULL);
info->xen_version_major = xen_version >> 16;
info->xen_version_minor = xen_version & 0xFF;
xc_version(ctx->xch, XENVER_extraversion, &u.xen_extra);
info->xen_version_extra = strdup(u.xen_extra);
xc_version(ctx->xch, XENVER_compile_info, &u.xen_cc);
info->compiler = strdup(u.xen_cc.compiler);
info->compile_by = strdup(u.xen_cc.compile_by);
info->compile_domain = strdup(u.xen_cc.compile_domain);
info->compile_date = strdup(u.xen_cc.compile_date);
xc_version(ctx->xch, XENVER_capabilities, &u.xen_caps);
info->capabilities = strdup(u.xen_caps);
xc_version(ctx->xch, XENVER_changeset, &u.xen_chgset);
info->changeset = strdup(u.xen_chgset);
xc_version(ctx->xch, XENVER_platform_parameters, &u.p_parms);
info->virt_start = u.p_parms.virt_start;
info->pagesize = xc_version(ctx->xch, XENVER_pagesize, NULL);
xc_version(ctx->xch, XENVER_commandline, &u.xen_commandline);
info->commandline = strdup(u.xen_commandline);
return info;
}
libxl_vcpuinfo *libxl_list_vcpu(libxl_ctx *ctx, uint32_t domid,
int *nb_vcpu, int *nrcpus)
{
libxl_vcpuinfo *ptr, *ret;
xc_domaininfo_t domaininfo;
xc_vcpuinfo_t vcpuinfo;
if (xc_domain_getinfolist(ctx->xch, domid, 1, &domaininfo) != 1) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting infolist");
return NULL;
}
*nrcpus = libxl_get_max_cpus(ctx);
ret = ptr = calloc(domaininfo.max_vcpu_id + 1, sizeof (libxl_vcpuinfo));
if (!ptr) {
return NULL;
}
for (*nb_vcpu = 0; *nb_vcpu <= domaininfo.max_vcpu_id; ++*nb_vcpu, ++ptr) {
if (libxl_cpumap_alloc(ctx, &ptr->cpumap)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "allocating cpumap");
return NULL;
}
if (xc_vcpu_getinfo(ctx->xch, domid, *nb_vcpu, &vcpuinfo) == -1) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting vcpu info");
return NULL;
}
if (xc_vcpu_getaffinity(ctx->xch, domid, *nb_vcpu, ptr->cpumap.map) == -1) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting vcpu affinity");
return NULL;
}
ptr->vcpuid = *nb_vcpu;
ptr->cpu = vcpuinfo.cpu;
ptr->online = !!vcpuinfo.online;
ptr->blocked = !!vcpuinfo.blocked;
ptr->running = !!vcpuinfo.running;
ptr->vcpu_time = vcpuinfo.cpu_time;
}
return ret;
}
int libxl_set_vcpuaffinity(libxl_ctx *ctx, uint32_t domid, uint32_t vcpuid,
libxl_cpumap *cpumap)
{
if (xc_vcpu_setaffinity(ctx->xch, domid, vcpuid, cpumap->map)) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "setting vcpu affinity");
return ERROR_FAIL;
}
return 0;
}
int libxl_set_vcpuonline(libxl_ctx *ctx, uint32_t domid, libxl_cpumap *cpumap)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
libxl_dominfo info;
char *dompath;
xs_transaction_t t;
int i, rc = ERROR_FAIL;
if (libxl_domain_info(ctx, &info, domid) < 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting domain info list");
goto out;
}
if (!(dompath = libxl__xs_get_dompath(&gc, domid)))
goto out;
retry_transaction:
t = xs_transaction_start(ctx->xsh);
for (i = 0; i <= info.vcpu_max_id; i++)
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "%s/cpu/%u/availability", dompath, i),
"%s", libxl_cpumap_test(cpumap, i) ? "online" : "offline");
if (!xs_transaction_end(ctx->xsh, t, 0)) {
if (errno == EAGAIN)
goto retry_transaction;
} else
rc = 0;
out:
libxl__free_all(&gc);
return rc;
}
/*
* returns one of the XEN_SCHEDULER_* constants from public/domctl.h
*/
int libxl_get_sched_id(libxl_ctx *ctx)
{
int sched, ret;
if ((ret = xc_sched_id(ctx->xch, &sched)) != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting domain info list");
return ERROR_FAIL;
}
return sched;
}
int libxl_sched_credit_domain_get(libxl_ctx *ctx, uint32_t domid, libxl_sched_credit *scinfo)
{
struct xen_domctl_sched_credit sdom;
int rc;
rc = xc_sched_credit_domain_get(ctx->xch, domid, &sdom);
if (rc != 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "setting domain sched credit");
return ERROR_FAIL;
}
scinfo->weight = sdom.weight;
scinfo->cap = sdom.cap;
return 0;
}
int libxl_sched_credit_domain_set(libxl_ctx *ctx, uint32_t domid, libxl_sched_credit *scinfo)
{
struct xen_domctl_sched_credit sdom;
xc_domaininfo_t domaininfo;
int rc;
rc = xc_domain_getinfolist(ctx->xch, domid, 1, &domaininfo);
if (rc < 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "getting domain info list");
return ERROR_FAIL;
}
if (rc != 1 || domaininfo.domain != domid)
return ERROR_INVAL;
if (scinfo->weight < 1 || scinfo->weight > 65535) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Cpu weight out of range, valid values are within range from 1 to 65535");
return ERROR_INVAL;
}
if (scinfo->cap < 0 || scinfo->cap > (domaininfo.max_vcpu_id + 1) * 100) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Cpu cap out of range, valid range is from 0 to %d for specified number of vcpus",
((domaininfo.max_vcpu_id + 1) * 100));
return ERROR_INVAL;
}
sdom.weight = scinfo->weight;
sdom.cap = scinfo->cap;
rc = xc_sched_credit_domain_set(ctx->xch, domid, &sdom);
if ( rc < 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "setting domain sched credit");
return ERROR_FAIL;
}
return 0;
}
static int trigger_type_from_string(char *trigger_name)
{
if (!strcmp(trigger_name, "nmi"))
return XEN_DOMCTL_SENDTRIGGER_NMI;
else if (!strcmp(trigger_name, "reset"))
return XEN_DOMCTL_SENDTRIGGER_RESET;
else if (!strcmp(trigger_name, "init"))
return XEN_DOMCTL_SENDTRIGGER_INIT;
else if (!strcmp(trigger_name, "power"))
return XEN_DOMCTL_SENDTRIGGER_POWER;
else if (!strcmp(trigger_name, "sleep"))
return XEN_DOMCTL_SENDTRIGGER_SLEEP;
else
return -1;
}
int libxl_send_trigger(libxl_ctx *ctx, uint32_t domid, char *trigger_name, uint32_t vcpuid)
{
int rc = -1;
int trigger_type = -1;
if (!strcmp(trigger_name, "s3resume")) {
xc_set_hvm_param(ctx->xch, domid, HVM_PARAM_ACPI_S_STATE, 0);
return 0;
}
trigger_type = trigger_type_from_string(trigger_name);
if (trigger_type == -1) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, -1,
"Invalid trigger, valid triggers are <nmi|reset|init|power|sleep>");
return ERROR_INVAL;
}
rc = xc_domain_send_trigger(ctx->xch, domid, trigger_type, vcpuid);
if (rc != 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Send trigger '%s' failed", trigger_name);
return ERROR_FAIL;
}
return 0;
}
int libxl_send_sysrq(libxl_ctx *ctx, uint32_t domid, char sysrq)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath = libxl__xs_get_dompath(&gc, domid);
libxl__xs_write(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/control/sysrq", dompath), "%c", sysrq);
libxl__free_all(&gc);
return 0;
}
int libxl_send_debug_keys(libxl_ctx *ctx, char *keys)
{
int ret;
ret = xc_send_debug_keys(ctx->xch, keys);
if ( ret < 0 ) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "sending debug keys");
return ERROR_FAIL;
}
return 0;
}
libxl_xen_console_reader *
libxl_xen_console_read_start(libxl_ctx *ctx, int clear)
{
libxl_xen_console_reader *cr;
unsigned int size = 16384;
char *buf = malloc(size);
if (!buf) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot malloc buffer for libxl_xen_console_reader,"
" size is %u", size);
return NULL;
}
cr = malloc(sizeof(libxl_xen_console_reader));
if (!cr) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot malloc libxl_xen_console_reader");
return NULL;
}
memset(cr, 0, sizeof(libxl_xen_console_reader));
cr->buffer = buf;
cr->size = size;
cr->count = size;
cr->clear = clear;
cr->incremental = 1;
return cr;
}
/* return values: *line_r
* 1 success, whole line obtained from buffer non-0
* 0 no more lines available right now 0
* negative error code ERROR_* 0
* On success *line_r is updated to point to a nul-terminated
* string which is valid until the next call on the same console
* reader. The libxl caller may overwrite parts of the string
* if it wishes. */
int libxl_xen_console_read_line(libxl_ctx *ctx,
libxl_xen_console_reader *cr,
char **line_r)
{
int ret;
memset(cr->buffer, 0, cr->size);
ret = xc_readconsolering(ctx->xch, cr->buffer, &cr->count,
cr->clear, cr->incremental, &cr->index);
if (ret < 0) {
LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "reading console ring buffer");
return ERROR_FAIL;
}
if (!ret) {
if (cr->count) {
*line_r = cr->buffer;
ret = 1;
} else {
*line_r = NULL;
ret = 0;
}
}
return ret;
}
void libxl_xen_console_read_finish(libxl_ctx *ctx,
libxl_xen_console_reader *cr)
{
free(cr->buffer);
free(cr);
}
uint32_t libxl_vm_get_start_time(libxl_ctx *ctx, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
char *dompath = libxl__xs_get_dompath(&gc, domid);
char *vm_path, *start_time;
uint32_t ret;
vm_path = libxl__xs_read(
&gc, XBT_NULL, libxl__sprintf(&gc, "%s/vm", dompath));
start_time = libxl__xs_read(
&gc, XBT_NULL, libxl__sprintf(&gc, "%s/start_time", vm_path));
if (start_time == NULL) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, -1,
"Can't get start time of domain '%d'", domid);
ret = -1;
}else{
ret = strtoul(start_time, NULL, 10);
}
libxl__free_all(&gc);
return ret;
}
char *libxl_tmem_list(libxl_ctx *ctx, uint32_t domid, int use_long)
{
int rc;
char _buf[32768];
rc = xc_tmem_control(ctx->xch, -1, TMEMC_LIST, domid, 32768, use_long,
0, _buf);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not get tmem list");
return NULL;
}
return strdup(_buf);
}
int libxl_tmem_freeze(libxl_ctx *ctx, uint32_t domid)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_FREEZE, domid, 0, 0,
0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not freeze tmem pools");
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_destroy(libxl_ctx *ctx, uint32_t domid)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_DESTROY, domid, 0, 0,
0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not destroy tmem pools");
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_thaw(libxl_ctx *ctx, uint32_t domid)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_THAW, domid, 0, 0,
0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not thaw tmem pools");
return ERROR_FAIL;
}
return rc;
}
static int32_t tmem_setop_from_string(char *set_name)
{
if (!strcmp(set_name, "weight"))
return TMEMC_SET_WEIGHT;
else if (!strcmp(set_name, "cap"))
return TMEMC_SET_CAP;
else if (!strcmp(set_name, "compress"))
return TMEMC_SET_COMPRESS;
else
return -1;
}
int libxl_tmem_set(libxl_ctx *ctx, uint32_t domid, char* name, uint32_t set)
{
int rc;
int32_t subop = tmem_setop_from_string(name);
if (subop == -1) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, -1,
"Invalid set, valid sets are <weight|cap|compress>");
return ERROR_INVAL;
}
rc = xc_tmem_control(ctx->xch, -1, subop, domid, set, 0, 0, NULL);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not set tmem %s", name);
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_shared_auth(libxl_ctx *ctx, uint32_t domid,
char* uuid, int auth)
{
int rc;
rc = xc_tmem_auth(ctx->xch, domid, uuid, auth);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not set tmem shared auth");
return ERROR_FAIL;
}
return rc;
}
int libxl_tmem_freeable(libxl_ctx *ctx)
{
int rc;
rc = xc_tmem_control(ctx->xch, -1, TMEMC_QUERY_FREEABLE_MB, -1, 0, 0, 0, 0);
if (rc < 0) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Can not get tmem freeable memory");
return ERROR_FAIL;
}
return rc;
}
void libxl_file_reference_destroy(libxl_file_reference *f)
{
libxl__file_reference_unmap(f);
free(f->path);
}
int libxl_get_freecpus(libxl_ctx *ctx, libxl_cpumap *cpumap)
{
int ncpus;
ncpus = libxl_get_max_cpus(ctx);
if (ncpus == 0)
return ERROR_FAIL;
cpumap->map = xc_cpupool_freeinfo(ctx->xch);
if (cpumap->map == NULL)
return ERROR_FAIL;
cpumap->size = (ncpus + 7) / 8;
return 0;
}
int libxl_create_cpupool(libxl_ctx *ctx, const char *name, int schedid,
libxl_cpumap cpumap, libxl_uuid *uuid,
uint32_t *poolid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc;
int i;
xs_transaction_t t;
char *uuid_string;
uuid_string = libxl__uuid2string(&gc, *uuid);
if (!uuid_string) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
rc = xc_cpupool_create(ctx->xch, poolid, schedid);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Could not create cpupool");
libxl__free_all(&gc);
return ERROR_FAIL;
}
libxl_for_each_cpu(i, cpumap)
if (libxl_cpumap_test(&cpumap, i)) {
rc = xc_cpupool_addcpu(ctx->xch, *poolid, i);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error moving cpu to cpupool");
libxl_destroy_cpupool(ctx, *poolid);
libxl__free_all(&gc);
return ERROR_FAIL;
}
}
for (;;) {
t = xs_transaction_start(ctx->xsh);
xs_mkdir(ctx->xsh, t, libxl__sprintf(&gc, "/local/pool/%d", *poolid));
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "/local/pool/%d/uuid", *poolid),
"%s", uuid_string);
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "/local/pool/%d/name", *poolid),
"%s", name);
if (xs_transaction_end(ctx->xsh, t, 0) || (errno != EAGAIN)) {
libxl__free_all(&gc);
return 0;
}
}
}
int libxl_destroy_cpupool(libxl_ctx *ctx, uint32_t poolid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc, i;
xc_cpupoolinfo_t *info;
xs_transaction_t t;
libxl_cpumap cpumap;
info = xc_cpupool_getinfo(ctx->xch, poolid);
if (info == NULL) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
rc = ERROR_INVAL;
if ((info->cpupool_id != poolid) || (info->n_dom))
goto out;
rc = ERROR_NOMEM;
if (libxl_cpumap_alloc(ctx, &cpumap))
goto out;
memcpy(cpumap.map, info->cpumap, cpumap.size);
libxl_for_each_cpu(i, cpumap)
if (libxl_cpumap_test(&cpumap, i)) {
rc = xc_cpupool_removecpu(ctx->xch, poolid, i);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error removing cpu from cpupool");
rc = ERROR_FAIL;
goto out1;
}
}
rc = xc_cpupool_destroy(ctx->xch, poolid);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc, "Could not destroy cpupool");
rc = ERROR_FAIL;
goto out1;
}
for (;;) {
t = xs_transaction_start(ctx->xsh);
xs_rm(ctx->xsh, XBT_NULL, libxl__sprintf(&gc, "/local/pool/%d", poolid));
if (xs_transaction_end(ctx->xsh, t, 0) || (errno != EAGAIN))
break;
}
rc = 0;
out1:
libxl_cpumap_destroy(&cpumap);
out:
xc_cpupool_infofree(ctx->xch, info);
libxl__free_all(&gc);
return rc;
}
int libxl_cpupool_rename(libxl_ctx *ctx, const char *name, uint32_t poolid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
xs_transaction_t t;
xc_cpupoolinfo_t *info;
int rc;
info = xc_cpupool_getinfo(ctx->xch, poolid);
if (info == NULL) {
libxl__free_all(&gc);
return ERROR_NOMEM;
}
rc = ERROR_INVAL;
if (info->cpupool_id != poolid)
goto out;
rc = 0;
for (;;) {
t = xs_transaction_start(ctx->xsh);
libxl__xs_write(&gc, t,
libxl__sprintf(&gc, "/local/pool/%d/name", poolid),
"%s", name);
if (xs_transaction_end(ctx->xsh, t, 0))
break;
if (errno == EAGAIN)
continue;
rc = ERROR_FAIL;
break;
}
out:
xc_cpupool_infofree(ctx->xch, info);
libxl__free_all(&gc);
return rc;
}
int libxl_cpupool_cpuadd(libxl_ctx *ctx, uint32_t poolid, int cpu)
{
int rc;
rc = xc_cpupool_addcpu(ctx->xch, poolid, cpu);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error moving cpu to cpupool");
return ERROR_FAIL;
}
return 0;
}
int libxl_cpupool_cpuadd_node(libxl_ctx *ctx, uint32_t poolid, int node, int *cpus)
{
int rc = 0;
int cpu;
libxl_cpumap freemap;
libxl_topologyinfo topology;
if (libxl_get_freecpus(ctx, &freemap)) {
return ERROR_FAIL;
}
if (libxl_get_topologyinfo(ctx, &topology)) {
rc = ERROR_FAIL;
goto out;
}
*cpus = 0;
for (cpu = 0; cpu < topology.nodemap.entries; cpu++) {
if (libxl_cpumap_test(&freemap, cpu) &&
(topology.nodemap.array[cpu] == node) &&
!libxl_cpupool_cpuadd(ctx, poolid, cpu)) {
(*cpus)++;
}
}
libxl_topologyinfo_destroy(&topology);
out:
libxl_cpumap_destroy(&freemap);
return rc;
}
int libxl_cpupool_cpuremove(libxl_ctx *ctx, uint32_t poolid, int cpu)
{
int rc;
rc = xc_cpupool_removecpu(ctx->xch, poolid, cpu);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error removing cpu from cpupool");
return ERROR_FAIL;
}
return 0;
}
int libxl_cpupool_cpuremove_node(libxl_ctx *ctx, uint32_t poolid, int node, int *cpus)
{
int ret = 0;
int n_pools;
int p;
int cpu;
libxl_topologyinfo topology;
libxl_cpupoolinfo *poolinfo;
poolinfo = libxl_list_cpupool(ctx, &n_pools);
if (!poolinfo) {
return ERROR_NOMEM;
}
if (libxl_get_topologyinfo(ctx, &topology)) {
ret = ERROR_FAIL;
goto out;
}
*cpus = 0;
for (p = 0; p < n_pools; p++) {
if (poolinfo[p].poolid == poolid) {
for (cpu = 0; cpu < topology.nodemap.entries; cpu++) {
if ((topology.nodemap.array[cpu] == node) &&
libxl_cpumap_test(&poolinfo[p].cpumap, cpu) &&
!libxl_cpupool_cpuremove(ctx, poolid, cpu)) {
(*cpus)++;
}
}
}
}
libxl_topologyinfo_destroy(&topology);
out:
for (p = 0; p < n_pools; p++) {
libxl_cpupoolinfo_destroy(poolinfo + p);
}
return ret;
}
int libxl_cpupool_movedomain(libxl_ctx *ctx, uint32_t poolid, uint32_t domid)
{
libxl__gc gc = LIBXL_INIT_GC(ctx);
int rc;
char *dom_path;
char *vm_path;
char *poolname;
xs_transaction_t t;
dom_path = libxl__xs_get_dompath(&gc, domid);
if (!dom_path) {
libxl__free_all(&gc);
return ERROR_FAIL;
}
rc = xc_cpupool_movedomain(ctx->xch, poolid, domid);
if (rc) {
LIBXL__LOG_ERRNOVAL(ctx, LIBXL__LOG_ERROR, rc,
"Error moving domain to cpupool");
libxl__free_all(&gc);
return ERROR_FAIL;
}
for (;;) {
t = xs_transaction_start(ctx->xsh);
poolname = libxl__cpupoolid_to_name(&gc, poolid);
vm_path = libxl__xs_read(&gc, XBT_NULL, libxl__sprintf(&gc, "%s/vm", dom_path));
if (!vm_path)
break;
libxl__xs_write(&gc, t, libxl__sprintf(&gc, "%s/pool_name", vm_path),
"%s", poolname);
if (xs_transaction_end(ctx->xsh, t, 0) || (errno != EAGAIN))
break;
}
libxl__free_all(&gc);
return 0;
}
|
/*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version 1.2.2) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 2017 (in review). #
# preprint DOI: 10.1101/088773 #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version 1.2.2) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 2017 (in review). #
# preprint DOI: 10.1101/088773 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2017, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <omp.h>
#include <fstream>
#include "./core/PhysiCell.h"
#include "./modules/PhysiCell_standard_modules.h"
// custom user modules
#include "./custom_modules/AMIGOS-invasion.h"
// #include "./custom_modules/ECM.h"
using namespace BioFVM;
using namespace PhysiCell;
// set number of threads for OpenMP (parallel computing)
void ecm_update(void);
int main( int argc, char* argv[] )
{
// load and parse settings file(s)
bool XML_status = false;
if( argc > 1 )
{ XML_status = load_PhysiCell_config_file( argv[1] ); }
else
{ XML_status = load_PhysiCell_config_file( "./config/PhysiCell_settings.xml" ); }
if( !XML_status )
{ exit(-1); }
// OpenMP setup
omp_set_num_threads(PhysiCell_settings.omp_num_threads);
// PNRG setup
// SeedRandom(0);
if( parameters.ints("unit_test_setup") == 1)
{SeedRandom(0);}
// time setup
std::string time_units = "min";
double t_max = PhysiCell_settings.max_time; // 1 days
/* Microenvironment setup */
setup_microenvironment();
/* PhysiCell setup */
// set mechanics voxel size, and match the data structure to BioFVM
double mechanics_voxel_size = 30;
Cell_Container* cell_container = create_cell_container_for_microenvironment( microenvironment, mechanics_voxel_size );
create_cell_types();
setup_tissue();
// ECM_setup(microenvironment.number_of_voxels());
/* Users typically start modifying here. START USERMODS */
/* Users typically stop modifying here. END USERMODS */
// set MultiCellDS save options
set_save_biofvm_mesh_as_matlab( true );
set_save_biofvm_data_as_matlab( true );
set_save_biofvm_cell_data( true );
set_save_biofvm_cell_data_as_custom_matlab( true );
// save a simulation snapshot
char filename[1024];
sprintf( filename , "%s/initial" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
// save a quick SVG cross section through z = 0, after setting its
// length bar to 200 microns
PhysiCell_SVG_options.length_bar = 200;
// for simplicity, set a pathology coloring function
std::vector<std::string> (*cell_coloring_function)(Cell*) = AMIGOS_invasion_coloring_function;
sprintf( filename , "%s/initial.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
display_citations();
run_biotransport( parameters.doubles("duration_of_uE_conditioning") );
if(parameters.bools("freeze_uE_profile")==true)
{
alter_cell_uptake_secretion_saturation();
}
if(parameters.ints("unit_test_setup")==1)
{
set_cell_motility_vectors();
}
// set the performance timers
BioFVM::RUNTIME_TIC();
BioFVM::TIC();
std::ofstream report_file;
//variables for March Project
double reset_Cells_interval = 980.0; // for a 1000 by 1000 um computational domain
bool enable_cell_resets = true;
// main loop
if( PhysiCell_settings.enable_legacy_saves == true )
{
sprintf( filename , "%s/simulation_report.txt" , PhysiCell_settings.folder.c_str() );
report_file.open(filename); // create the data log file
report_file<<"simulated time\tnum cells\tnum division\tnum death\twall time"<<std::endl;
}
try
{
while( PhysiCell_globals.current_time < t_max + 0.1*diffusion_dt )
{
// save data if it's time.
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_full_save_time ) < 0.01 * diffusion_dt )
{
display_simulation_status( std::cout );
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output( PhysiCell_globals.current_time , PhysiCell_globals.full_output_index, microenvironment, report_file);
}
if( PhysiCell_settings.enable_full_saves == true )
{
sprintf( filename , "%s/output%08u" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
}
if( parameters.bools("enable_ecm_outputs") == true)
{
sprintf( filename , "%s/output%08u_ECM.mat" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index);
write_ECM_Data_matlab( filename );
}
PhysiCell_globals.full_output_index++;
PhysiCell_globals.next_full_save_time += PhysiCell_settings.full_save_interval;
}
// save SVG plot if it's time
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_SVG_save_time ) < 0.01 * diffusion_dt )
{
if( PhysiCell_settings.enable_SVG_saves == true )
{
sprintf( filename , "%s/snapshot%08u.svg" , PhysiCell_settings.folder.c_str() , PhysiCell_globals.SVG_output_index );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
PhysiCell_globals.SVG_output_index++;
PhysiCell_globals.next_SVG_save_time += PhysiCell_settings.SVG_save_interval;
}
}
// Uncomment to run march test
if( fabs( PhysiCell_globals.current_time - reset_Cells_interval ) < 0.1 * diffusion_dt && parameters.ints("unit_test_setup") == 1 && parameters.ints("march_unit_test_setup") == 1)
{
if (enable_cell_resets == true )
{
reset_cell_position();
reset_Cells_interval += 980.0; // for a 1000 by 1000 um computational domain
}
}
// update the microenvironment
// if(parameters.bools("freeze_uE_profile")==true)
if( parameters.ints("unit_test_setup") == 0 && parameters.bools("freeze_uE_profile")==0 ) // Is there a way to set this only once??
{
microenvironment.simulate_diffusion_decay( diffusion_dt );
}
// run PhysiCell
((Cell_Container *)microenvironment.agent_container)->update_all_cells( PhysiCell_globals.current_time );
//add ECM update here!
// This changes the cell speed and bias as based on the ECM. It is the funciton that makes teh cells "see" the ECM and react to it with changes in their dynamics.
// In this current LS18 implementation, that means that only follower cells will see the ECM.
// May need something that specifics that only followers do this (fixed with test on cell type). Could perhaps put that into the custom stuff. Would need something similar for the ECM realignment. Would like to move this out of diffusion loop so we can specify how frequently it updates.
// cell_update_from_ecm();
PhysiCell_globals.current_time += diffusion_dt;
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output(PhysiCell_globals.current_time, PhysiCell_globals.full_output_index, microenvironment, report_file);
report_file.close();
}
}
}
catch( const std::exception& e )
{ // reference to the base of a polymorphic object
std::cout << e.what(); // information from length_error printed
}
// save a final simulation snapshot
sprintf( filename , "%s/final" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
sprintf( filename , "%s/final.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
// timer
std::cout << std::endl << "Total simulation runtime: " << std::endl;
BioFVM::display_stopwatch_value( std::cout , BioFVM::runtime_stopwatch_value() );
return 0;
}
|
Business Language Learning
From APEC HRDWG Wiki
As part of International Education Week 2010, APEC has expanded on several themes of the seminar on "Language Education: An Essential for a Global Economy," to provide a guide for students and instructors interested in the critical importance of business language for strengthening business relations in a global context. These themes include Business in the 21st Century; Cross Cultural Awareness for 21st Century Business; Language for 21st Century Business; Business Language Learning; and Business Language Policy.
In Business Language Instruction, we learn that different economies use different methodologies by which to teach and learn the subject of business. We find that conflict may arise when these differing methodologies come together in a single classroom.
Another application of advanced communications technologies may be found in the classroom, where traditional textbooks may be supplemented with electronic media such as video clips, as well as live information from Internet newsfeeds, essentially making textbook materials come alive. Students today may not learn history, geography, and science as it was taught a few years ago. They may actually view and experience events via the Internet as if they were present during the moment in which they took place. Video conferencing in the classroom may have other applications, such as providing students access to language teachers in foreign countries and to subject matter experts thousands of miles away, who can appear in the classroom and guest lecture as if they were actually there. These powerful new communications technologies have enhanced business language instruction in schools and universities, as evidenced from the scenario presented below.
- Technology provides web-based content to expand, complement, and supplement textbooks and teacher instruction.
- Online educational materials blend face-to-face learning with digital teaching and curricula.
- Technology such as virtual classroom fosters peer-to-peer and instructor-peer relationship building, collaboration, and social networking.
- When designing lesson plans for international students, educators must consider how cultural values affect the way students respond to specific assignments.
- Technology contributes to a green environment by saving paper and reducing travel.
In the fictional scenario below, teaching and learning methodologies from different economies clash as they are brought together into a single classroom, made possible only by advancements in telecommunications technologies.
A prestigious university located in collectivist Economy A invited a Marketing professor from a renowned university in individualistic Economy B teach a year-long course on the Fundamentals of Marketing to first-year business students. The professor had recently published a book on McBurger, the hamburger chain, and its success in Economy A. The students in Economy A viewed his book as a premier marketing book in the field of international business. Conducted virtually over Internet video stream, the course was the first [Ed Note: for which economy? Using a mix of traditional and technology-mediated instruction is not that new. It may be a stretch to say it was the first time for such a mix.] to integrate traditional methods of teaching with new technologies. The professor would present a traditional lecture from the university's video conferencing room in Economy B and the students in Economy A would view the lecture and participate in discussion as if the professor were in their classroom. Students would submit all assignments and exams to the professor through a "digital drop box," and the professor would return graded materials back to students via this medium. Using advanced technology in the classroom allowed students to learn from a renowned professor while enrolling in a "green course," one in which the professor did not need to travel to the economy and no paper would be used for assignments.
To prepare for the course, the professor chose various marketing, advertising, and strategy cases from around the world. On the first day of class, he presented a case study on Boca Rola, and its advent into Economy C. He gave the students 30 minutes to read the case study, and then encouraged the students to share their views about: (1) Boca Rola’s strategy to enter the market in Economy C, (2) the barriers Boca Rola faced in entering the market, (3) perceptions of foreign products previously unavailable in a particular economy, and (4) consumers' reaction to the new product. He found the students reluctant to share their individual views in the class. Thus, he presented his own views from the perspective of an outsider to Economy C, and shared his views about how Boca Rola’s business culture may be different than the culture of Economy C in which it was operating. At the end of class, the professor gave the students a list of questions about the case study. He asked the students to form small groups of 3-4 students and discuss the answers to the questions. After they discussed the questions, he asked each team to submit a 5-6 page summary of the responses in three days. Additionally, he assigned another case study for the students to read – one that focused on a large multinational company’s entry into the beauty care segment in Economy D for future discussion.
When the professor reviewed the students’ responses to the Boca Rola case study, he discovered that the 20 students had submitted 5 separate sets of case study responses, as required. However, each group provided the same responses to the same questions, with no variation. He knew that this could not be a blatant incidence of cheating. When the next class reconvened, he asked the students why they turned in identical sets of answers. The students looked surprised, believing that they had followed his instructions, but had perhaps misinterpreted them. Finally, one student raised his hand and stated that the class had formed groups of 3-4 students, but that each group tackled one question, and then shared the answers with the other groups. The students believed that it was not time efficient to discuss each question. Rather, they decided that each group would respond to just one question, and then share the response with the other groups, who would do the same. The professor smiled in exasperation, and, frustrated by his inability to engage the students in an open discussion, began discussing the beauty company’s entry into Economy D.
Points to Consider
- How has technology enhanced international educational opportunities for both students and instructors? Other than the examples cited, what other ways can technology facilitate international educational opportunities?
- To what extent did the professor understand the students’ motivation to learn, the context in which they learn, and their willingness to experiment and use different approaches to demonstrate what they can do and what they know?
- Why was the strategy of open classroom discussion widely popular in Economy B and a widely used strategy to introduce opposing views, and to encourage critical thinking?
- To what extent can strategies such as lesson study encourage students in Economy A to demonstrate problem solving skills, critical thinking, and creativity?
- What could the professor do to model how each group could engage in separate discussions to understand the various perceptions about Boca Rola’s strategy to enter the market in Economy C?
- Individualistic cultures are those cultures in which the opinion of the individual is greatly sought after and deeply valued, even though it may differ from the views of the group. These cultures believe that it is a variety of individual opinions that produce the best solutions to problems and that promote success, whether in social relationships or in the workplace.
- Collectivist cultures, on the other hand, value group consensus and harmony. These cultures believe that an environment conducive for business and personal success can only be created when members of the group align in sync with one another. Members of groups will first debate the merits of a question among themselves, and then choose the opinion that they deem most valuable before presenting it to a higher authority.
- The Professor from Economy B was used to receiving individual responses to his case discussion questions, responses that varied greatly from one another. Although not all responses he received were correct, he enjoyed reading the individual opinions present in them before discussing the correct answers with the class during the following lecture. Economy A students were, however, from a collectivist culture and valued sharing their responses with their group first before reaching a consensus on a particular answer choice.
- The professor noticed that, although he had received only one response per question, it was more or less correct, although there was not a way for him to ascertain which of his students had provided the response, how the learning had occurred, and what the viewpoints of those who disagreed might be.
- Teaching Tips for IEW 2010 provided by TESOL
- Teaching Tips for IEW 2009 submitted by teachers throughout the Asia-Pacific region
- Videos from the APEC-RELC International Language Seminar presentation "Creating Prosperity: Using the Internet to Revolutionize Language Learning"
- New paths of communication through:
- Technology providing access to content beyond books
- Video from the APEC-RELC International Language Seminar presentation "Changes in Our Field: Where are We Going?"
- E-Language Learning for Students - a collection of online language learning resources from various APEC members
- Related Tips for Teaching 21st Century Workplace Skills
More content from International Education Week 2010
|
Showing posts with label Antiquities; Looting; Smuggling; Collecting; Collections; iraq. Show all posts
July 8, 2017
Thou Shall Not Covet thy Neighbor's Cuneiform
Op/Ed By: Lynda Albertson
As the US press and social media came alive in condemnation as a result of the Hobby Lobby smuggling case, I couldn't help but notice that while the hashtag #HobbyLobbyisISIS is noticeably attention-grabbing, (as well as probably inaccurate), the more important facet of the "is-that-object-looted" puzzle was still being overlooked.
I asked myself, instead of simply rewording the press release announcement released by the government, why hadn't US news organizations dug deeper into the development of the Green Collection in ancient art. Especially since everyone now seems hellbent, (excuse the pun) on crucifying the fundamentalist Christian collector or finding some way to tie Hobby Lobby to Da'esh.
This is a case that has been widely publicized since 2015, and it's not the only time the Greens or their large collection have come under scrutiny or been accused of acquiring objects through untrustworthy channels with illicit ties.
In June 2014 Dr. David Trobisch, Director of Collections for the Museum of the Bible even attended ARCA’s annual art crime conference where he heard concerns made by Dr. Roberta Mazza, a papyrologist and ancient historian from the University of Manchester about the Green Collection's unprovenanced papyrus fragments. Those fragments however were not mentioned in this current civil complaint.
While this US civil forfeiture case underscores that illicit traffic in cultural objects contributes to the despoliation of a country's ancient heritage and causes irreparable loss to the world's heritage knowledge, why is it then that the public only wakes up and takes notice when ISIS ties are tangentially inferred?
Are trafficked Middle East artifacts only worthy of the world's indignation when they are looted to fund terrorism?
As the general public responded to the press coverage over the last two days most of the grumbling I've come across was either ISIS-funding related or centered on whether or not the punishment fit the crime. I use the word "crime" here loosely because no criminal charges were filed for the looting and theft of the 450 ancient cuneiform tablets and 3,000 ancient clay bullae which ultimately were the subject of this civil forfeiture.
In civil cases, the object of the law is the redress of wrongs by compelling compensation or restitution. As those following this case closely are painfully aware, civil law deals with the disputes between individuals, organizations, or between the two, in which compensation can be awarded to the victim. Criminal law is the body of law that deals with crime and the legal punishment of criminal offenses.
A civil fine is not a criminal punishment.
Civil case fines are primarily sought in federal investigations in order to compensate the state for harm done to it, rather than to punish a wrongful conduct, something many like myself would have liked to have seen happen given the Green's less than stellar record when it comes to vetting antiquities for inclusion in their collection. In this case, Hobby Lobby only suffers so much harm as is necessary to make good the wrong they have done (to the state).
Civil penalties, in this case a $3M fine, do not carry any jail time or other legal penalties. This fact illustrates why no one from Hobby Lobby was criminally charged, despite the large number of objects seized and subsequently forfeited.
This may also explain the absence of any noticeable public remorse on Hobby Lobby's part for their role in this antiquities smuggling affair. The lack of regret can also be seen in the unrepentant statement by Hobby Lobby President Steve Green, in his company's press release after the federal civil ruling was publicized.
Was new to the world of acquiring these items? Did not understand the correct way to document and ship these items?
Let's look at his statements more closely.
While Hobby Lobby, may be "new" to the world of acquiring antiquities, the fact that it has purchased more than 40,000 objects since November 2009 does not in any way make it a neophyte collector of ancient art.
In addition to the cuneiform tablets seized in this well publicized case, the Green Collection already had in its possession the third largest holding of cuneiform tablets in North America (over 10,000 pieces). This means Green and Hobby Lobby by proxy had ample prior opportunity to explore what could and should go on any customs declaration for objects that contain writing first developed by the ancient Sumerians of Mesopotamia between 3500-3000 BCE.
In 2010, a year before the seized cuneiform tablets arrived in Memphis, the Greens had also already consulted with Dr. Patty Gerstenblith, a cultural heritage law expert with DePaul University 's College of Law, about import restrictions for ancient antiquities who is reported to have advised them about their need for deeper due diligence in their collecting. Given Gerstenblith's impeccable familiarity with the cultural heritage law, it can be assumed that the Greens as collectors were not as ignorantly naive to the road they were embarking down as the firm's press statement this week seems to imply.
But setting aside the intricacies of import and customs documentation specifically related to ancient antiquities coming from Iraq, Hobby Lobby itself has some 32,000 employees, 750 stores in forty-seven states, and $4 billion in yearly revenue, much of it based on imported items.
It's corporate headquarters include a 9.2 million-square-foot manufacturing, distribution, and office complex in Oklahoma City. Its warehouse has an hourly employee base of 2500+ employees with 80+ members of management, headed by an Assistant Vice President of Warehouse Operations, who reports to the Senior Vice President of Distribution.
When importing merchandise from foreign countries Hobby Lobby is fully aware there are certain trade laws and regulations, and that U.S. Customs oversees the compliance of those laws. They even have an international department responsible for training and compliance to ensure the import process go smoothly, not to mention a manual outlining laws and regulations, valuation, assists, and country of origin requirements which can be downloaded here
So to imply to the public that Hobby Lobby "imprudently relied on dealers and shippers who, in hindsight, did not understand the correct way to document and ship these items" seems a bit unapologetic coming from an apologist.
Especially given Green's business thrives on supply-chain distribution members in its shipping department who would have to have, given the large scale operation of receiving imported cargo from across the globe in support of Hobby Lobby's national operations, sufficient knowledge of what the legal requirements are for import. If they didn't, they certainly knew who to ask.
As I have mentioned in a previous post, the estimated 40,000+ objects in the Green Collection equates to acquiring 6,666 objects per year or collecting a whopping 18 new objects per day. Compare that acquisition rate to the number of employees working on the Green's or the Museum of the Bible's payroll who are tasked with historic object provenance and one can easily surmise that an object's ethical collection history has never been either group's overriding priority.
Emphasis instead has been on filling the Museum of the Bible, Washington DC's about-to-be-opened 430,000-square-foot, eight story massive red brick museum located over the Federal Center SW Metro station. To put that into perspective, one NFL football field is 57,600 square feet. The Museum of the Bible has seven and a half football fields of space it needs to fill.
Given the scale of archaeological theft in biblical area source countries and the number of objects with questionable origins which have already been identified by various researchers following the Green Collection prior to this forfeiture, it's time for Hobby Lobby's founders to do more than just open their wallets, purchase, and if caught, pay civil fines and forfeit the objects in question.
Opening their wallets has been the crux of the problem, as the Green's appetite for unprovenanced antiquities, and the profits to be had from this appetite, have likely been a motivating factor for others to loot, thereby destroying whatever context the objects may have had.
It's time for the Greens to fulfill the promise previously made by their employee.
In 2014 the director of Collections at the Museum of the Bible, David Trobisch, informed Dr. Roberta Mazza that the Green Collection was going towards full digitisation and open access. This has yet to happen.
They should also make every effort, before making any further acquisitions, to ensure that the objects they are purchasing have been legally obtained and been legally exported from their country of origin.
If the Greens truly want to make amends, they should fill their future Museum of the Bible with acquisitions collected ethically, and make the details of their past purchases open to researchers and investigators so that they can start to set things right by restituting any objects previously purchased without sufficient moral and ethical consideration.
Exodus 20:15 and 17 King James Version (KJV):
“Thou shalt not steal."
I think that includes cuneiform tablets, clay bullae, incantation bowls and papyrus fragments.
July 6, 2017
By: Lynda Albertson
So much for remorse.
March 19, 2017
Lecture: Criminals without Borders - The many profiles of the (il)licit antiquities trade.
For those interested interested in the realm of illicit trafficking who will be in Rome, Italy April 21, 2017 Lynda Albertson, ARCA's Chief Executive Officer will be giving a talk on "Criminals without Borders."
This one hour lecture, at 6:00 pm at John Cabot University will provide a brief overview of the profile of actors in the illicit art trade, giving examples of how those in the trade avoid detection and prosecution.
This presentation will discuss the motives of trafficking in art and antiquities, highlighting cases from source and conflict countries emphasizing that the trade thrives on commercial opportunity i.e., a means of dealing in high value commodities that are often poorly protected, difficult to identify and easy to transport across national boundaries.
Her presentation will examine specific case examples and will underscoring response mechanisms that work to proactively counter the illegal trade.
The discussion will highlight
--the interchangeable participants in the illicit antiquities trade
--varying motives/opportunities
--how connections through single interactions can form loosely based networks
Lynda Albertson is the CEO of ARCA — The Association for Research into Crimes against Art, a nongovernmental organisation which works to promote research in the fields of art crime and cultural heritage protection. The Association seeks to identify emerging and under-examined trends related to the study of art crime and to develop strategies to advocate for the responsible stewardship of our collective artistic and archaeological heritage.
Ms. Albertson, through her role at ARCA seeks to influence policy makers, public opinion and other key stakeholders so that public policies are developed and based on apolitical evidence, and which addresses art crime prevention and the identification of art crimes in heritage preservation initiatives.
In furtherance of that, Ms. Albertson provides technical, scientific and regional expertise to national and international organizations such as UNESCO, CULTNET, ICOM, in furtherance of ARCA's heritage preservation mission. For the past five years, Lynda has focused part of her work on fighting the pillage of ancient sites and trafficking of artifacts, particularly in the Middle East and North Africa, conducting research on the illicit trade in antiquities in MENA countries.
Ms. Albertson also oversees ARCA's inter NGO - Governmental engagement and capacity building in MENA countries in recognition of UN Security Council Resolution 2199, which among other provisions, bans all trade in looted antiquities from Iraq and Syria and encourages steps to ensure such items are returned to their homelands.
Tuesday, March 21, 2017
6:00 PM - 8:00 PM (CET)
Guarini Campus
Via della Lungara, 233
March 18, 2017
For information please see the exhibition webpage here.
Exhibition Dates:
April 3 - May 13, 2017
Neubauer Collegium for Culture and Society
Exhibition takes place on the 1st floor gallery
5701 S. Woodlawn Avenue
Chicago, Illinois
11am-5pm, Monday-Friday
773-795-2329 (Front desk)
|
Education and health outcomes for social minorities in India: An analysis using SUR model
AbstractThe current study analyzes the health and education outcomes of fifteen year old children in India and investigates the question of inequality of such outcomes for socio-religious categories. To study the effect of health on education, SUR estimation has been undertaken. The comparison of SUR and OLS results shows that SUR estimates have smaller standard errors than the OLS estimates. Of the three categories analyzed in the data, STs have worst outcomes for both education and health and SCs lag behind in the health field. The results have important implications for policy regarding education and health of the socio-religious minorities.
Download InfoIf you experience problems downloading a file, check if you have the proper application to view it first. In case of further problems read the IDEAS help page. Note that these files are not on the IDEAS site. Please be patient as the files may be large.
Bibliographic InfoPaper provided by Agricultural and Applied Economics Association in its series 2012 Annual Meeting, August 12-14, 2012, Seattle, Washington with number 124840.
Date of creation: 2012
Date of revision:
Contact details of provider:
Postal: 555 East Wells Street, Suite 1100, Milwaukee, Wisconsin 53202
Phone: (414) 918-3190
Fax: (414) 276-3349
Web page: http://www.aaea.org
More information through EDIRC
Health Economics and Policy;
This paper has been announced in the following NEP Reports:
Please report citation or reference errors to , or , if you are the registered author of the cited work, log in to your RePEc Author Service profile, click on "citations" and make appropriate adjustments.:
- Sonalde Desai & Veena Kulkarni, 2008. "Changing educational inequalities in india in the context of affirmative action," Demography, Springer, vol. 45(2), pages 245-270, May.
- Vani Borooah & Sriya Iyer, 2005.
"Vidya, Veda, and Varna: The influence of religion and caste on education in rural India,"
The Journal of Development Studies,
Taylor and Francis Journals, vol. 41(8), pages 1369-1404.
- Vani K. Borooah & Sriya Iyer, 2002. "Vidya, Veda, and Varna: The Influence of Religion and Caste on Education in Rural India," ICER Working Papers 32-2002, ICER - International Centre for Economic Research.
- Behrman, Jere R, 1996. "The Impact of Health and Nutrition on Education," World Bank Research Observer, World Bank Group, vol. 11(1), pages 23-37, February.
- Dreze, Jean & Kingdon, Geeta Gandhi, 2001.
"School Participation in Rural India,"
Review of Development Economics,
Wiley Blackwell, vol. 5(1), pages 1-24, February.
- Jean Drèze & Geeta Gandhi Kingdon, 1999. "School Participation in Rural India," STICERD - Development Economics Papers - From 2008 this series has been superseded by Economic Organisation and Public Policy Discussion Papers 18, Suntory and Toyota International Centres for Economics and Related Disciplines, LSE.
- Jean Dreze & Geeta Gandhi Kingdon, 1999. "School Participation in Rural India," Working papers 69, Centre for Development Economics, Delhi School of Economics.
- Ashwini Deshpande, 2000. "Recasting Economic Inequality," Review of Social Economy, Taylor and Francis Journals, vol. 58(3), pages 381-399.
- Case, Anne & Fertig, Angela & Paxson, Christina, 2005. "The lasting impact of childhood health and circumstance," Journal of Health Economics, Elsevier, vol. 24(2), pages 365-389, March.
For technical questions regarding this item, or to correct its authors, title, abstract, bibliographic or download information, contact: (AgEcon Search).
If you have authored this item and are not yet registered with RePEc, we encourage you to do it here. This allows to link your profile to this item. It also allows you to accept potential citations to this item that we are uncertain about.
If references are entirely missing, you can add them using this form.
If the full references list an item that is present in RePEc, but the system did not link to it, you can help with this form.
If you know of missing items citing this one, you can help us creating those links by adding the relevant references in the same way as above, for each refering item. If you are a registered author of this item, you may also want to check the "citations" tab in your profile, as there may be some citations waiting for confirmation.
Please note that corrections may take a couple of weeks to filter through the various RePEc services.
|
Skip to Main Content
Machine learning methods are known to be inefficient when faced with many features that are unnecessary for rule discovery. In coping with this issue, many methods have been proposed for selecting important features. Among them is feature selection that selects a subset of discriminative features or attribute for model building due to its ability to avoid overfitting issue, improve model performance, provide faster and producing reliable model. This paper proposes a new method based on rough set algorithms, which is a rule-based data mining method to select the important features in bioinformatics datasets. Amino acid compositions are used as conditional features for the classification task. However, our results indicate that all amino acid composition features are equally important thus selecting the features are unnecessary. We do confirm the need of having a balance classes in classifying the protein function by demonstrating an increase of more than 15% in accuracy.
Electrical Engineering and Informatics, 2009. ICEEI '09. International Conference on (Volume:01 )
Date of Conference: 5-7 Aug. 2009
|
#include "cmrenderqueue.h"
#include "cmrenderworker.h"
#include <cstring>
#include <QThread>
CMRenderQueue::CMRenderQueue(QObject *parent)
: QObject{parent}
{
// set up worker in its thread
worker.moveToThread(&renderThread);
connect(&renderThread, &QThread::started, &worker, &CMRenderWorker::render);
connect(&worker, &CMRenderWorker::imageRendered, this, &CMRenderQueue::renderDone);
saveWorker.moveToThread(&saveThread);
connect(&saveThread, &QThread::started, &saveWorker, &CMSaveWorker::save);
connect(&saveWorker, &CMSaveWorker::imageSaved, this, &CMRenderQueue::saveDone);
qRegisterMetaType<CMRawImage>("CMRawImage");
}
CMRenderQueue::~CMRenderQueue() {
renderThread.quit();
renderThread.wait();
saveThread.quit();
saveThread.wait();
}
void CMRenderQueue::setImage(const CMRawImage &img)
{
if (rendering) {
this->nextRaw = img;
imageQueued = true;
renderQueued = true;
} else {
this->currentRaw = img;
this->startRender();
}
}
void CMRenderQueue::setParams(const ImagePipelineParams ¶ms)
{
this->plParams = params;
this->paramsSet = true;
if (rendering)
renderQueued = true;
else
this->startRender();
}
void CMRenderQueue::startRender()
{
if (!paramsSet)
return;
rendering = true;
// prepare and launch worker
worker.setImage(&this->currentRaw);
worker.setParams(this->plParams);
renderThread.start();
}
void CMRenderQueue::renderDone(const QImage &img)
{
emit imageRendered(img);
renderThread.quit();
renderThread.wait();
if (imageQueued) {
currentRaw = nextRaw;
imageQueued = false;
}
if (renderQueued) {
startRender();
renderQueued = false;
} else {
rendering = false;
}
}
bool CMRenderQueue::autoWhiteBalance(const CMAutoWhiteParams ¶ms, double *temp_K, double *tint)
{
if (this->currentRaw.isEmpty())
return false;
pipeline_auto_white_balance(this->currentRaw.getRaw(), &this->currentRaw.getCaptureInfo(),
¶ms, temp_K, tint);
return true;
}
bool CMRenderQueue::saveImage(const QString &fileName)
{
if (this->currentRaw.isEmpty() || !paramsSet || saving)
return false;
saving = true;
if (imageQueued)
saveWorker.setParams(fileName.toStdString(), this->nextRaw, this->plParams);
else
saveWorker.setParams(fileName.toStdString(), this->currentRaw, this->plParams);
saveThread.start();
return true;
}
void CMRenderQueue::saveDone(bool success)
{
saveThread.quit();
saveThread.wait();
saving = false;
emit imageSaved(success);
}
// Enqueues set image operation at end of signal queue
void CMRenderQueue::setImageLater(const CMRawImage &img)
{
QMetaObject::invokeMethod(this, "setImage", Qt::QueuedConnection, Q_ARG(CMRawImage, img));
}
bool CMRenderQueue::hasImage()
{
if (imageQueued)
return !this->nextRaw.isEmpty();
else
return !this->currentRaw.isEmpty();
}
|
In a countless number of movies and novels set in the British Regency and Victorian Era women are plagued by headaches; oftentimes as a way to show them as fragile, or as a joke. It is not a trope used with male characters, but if it were would they be taken seriously? Probably not. What if it was all viewed from a different angle and headaches were considered as something that legitimately affected their well-being? Maybe they were getting out of a carriage earlier in the week and bumped their head on the door frame causing a very mild head injury. What if in present day your head bumped against the driver’s side window in a small accident with no other injury? Could that genuinely affect anyone’s overall health?
A new study by Dr. Sylvia Lucas, coming out of the American Headache Society‘s Annual Meeting, states that those who experience milder head injuries tend to have more post-traumatic headaches as time progresses than those with severe injuries.
Out of the 598 participants in the study “about 70% [were] more likely than … their counterparts with moderate or severe injury to develop new headache or have a worsening of preexisting headache over the next year,” Dr Lucas was quoted as saying. The majority of headaches were classified as migraines, though a large chunk was unclassifiable using the International Classification of Headache Disorders, second edition.
They do not know why this occurs, but Dr. Lucas thinks it is related to the specific mechanics of the accident that caused the head injury.
Breaking down the participants: 220 had mild traumatic brain injuries (TBI) and began the study the same week of their accident; the other 378 had moderate to severe traumatic brain injury and were admitted to rehabilitation facilities. They found that migraines and tension headaches were most common, and that cervicogenic headaches were less common. This was unexpected considering most of the incidents that led to the TBI stemmed from motor vehicle accidents.
“Study results showed that the mild TBI group and the moderate or severe TBI group had an identical prevalence of headache before injury (17%). But the former had a higher incidence of new or worsened headache at baseline (56% vs. 40%), at 3 months (63% vs. 37%), at 6 months (69% vs. 33%), and at 12 months (58% vs. 34%).”
If you are wondering how this might severely affect somebody’s life, about a year ago a story came out that soldiers were sidelined more from headaches than from other types of wounds. Headaches. For the study Dr. Steven P. Cohen and his colleagues “reviewed the records of 985 soldiers who had been evacuated from the wars during 2004-2009 with a primary diagnosis of headache.” The causes of the headaches ranged from physical trauma, psychological or emotional, to environmental.
Only about a third of the patients in the study were able to return to duty.
So maybe headaches can cause a bigger imposition in life than originally thought. And the next time someone tells you “it’s just a headache” this will give them something to think about.
Check back again next week when we see what else is new on MD Consult.blog comments powered by Disqus
|
/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* 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; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/////////////////////////////////////////////////////////////////////////////
//
// IfFlattener class: takes all the shapes in the scene graph
// represented by a IfHolder and flattens it into a bunch of
// triangles. The coordinates, normals, texture coordinates, and
// material indices are stored in the SoIndexedTriangleStripSet in the
// IfHolder.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef _IF_FLATTENER_
#define _IF_FLATTENER_
#include <Inventor/SbLinear.h>
#include <Inventor/actions/SoCallbackAction.h>
class IfHolder;
class SoNode;
class SoShape;
class IfFlattener {
public:
IfFlattener();
~IfFlattener();
void flatten(IfHolder *_holder);
private:
IfHolder *holder; // Holds most important stuff
int numVerts; // Number of vertices stored
SbMatrix pointMatrix; // For transforming points
SbMatrix normalMatrix; // For transforming normals
SbMatrix textureMatrix; // For transforming texture coords
int numMtlIndices; // Number of material indices stored
int fieldSize; // Number of entries allocated for fields
// These hold pointers to the field value arrays (returned by
// startEditing()) to make additions much faster:
SbVec3f *coordVals;
SbVec3f *normalVals;
SbVec2f *texCoordVals;
int32_t *mtlIndexVals;
void expandFields();
void prepareForShape(SoCallbackAction *cba, const SoShape *shape);
void addTriangle(SoCallbackAction *cba,
const SoPrimitiveVertex *verts[3]);
void finishShape(SoCallbackAction *cba, const SoShape *shape);
void addCoordinate(const SbVec3f &point);
void addNormal(const SbVec3f &normal);
void addMaterialIndex(int materialIndex);
void addTextureCoordinate(const SbVec4f &texCoord);
void createGraph();
//////////////////////////////////////////////////////////////////
//
// Callbacks
static SoCallbackAction::Response preShapeCB(void *userData,
SoCallbackAction *cba,
const SoNode *shape)
{
((IfFlattener *) userData)->
prepareForShape(cba, (const SoShape *) shape);
return SoCallbackAction::CONTINUE;
}
static SoCallbackAction::Response postShapeCB(void *userData,
SoCallbackAction *cba,
const SoNode *shape)
{
((IfFlattener *) userData)->
finishShape(cba, (const SoShape *) shape);
return SoCallbackAction::CONTINUE;
}
static void triangleCB(void *userData, SoCallbackAction *cba,
const SoPrimitiveVertex *v1,
const SoPrimitiveVertex *v2,
const SoPrimitiveVertex *v3)
{
const SoPrimitiveVertex *v[3];
v[0] = v1;
v[1] = v2;
v[2] = v3;
((IfFlattener *) userData)->addTriangle(cba, v);
}
};
#endif /* _IF_FLATTENER_ */
|
// -*- C++ -*- <-- an Emacs control
// Copyright information is at the bottom of the file.
//=========================================================================
// XML-RPC C++ API
//=========================================================================
#ifndef _XMLRPCCPP_H_
#define _XMLRPCCPP_H_ 1
// The C++ standard says we should either include <string.h> (which gets
// us the wrong header), or say 'using namespace std;' (which doesn't
// work with our version of g++). So this header name is technically wrong.
// Tell me what your compiler does; I can provide some autoconf magic to the
// Right Thing on most platforms.
//
// 2004.12.22 Bryan: This looks like a problem with whatever g++ he was
// using, so if anything, the special case should be for that. In any case,
// we've already added using namespace std to other files, without knowing
// there was an issue, so I'm just going to do the "using namespace"
// unconditionally and see who complains. If there are complaints, we can
// improve the documentation here.
//
// Formerly, the "using namespace std" was under
// "#if defined(__GNUC__) && (__GNUC__ >= 3)".
#include <string>
using namespace std;
#include <xmlrpc_config.h>
#include <xmlrpc.h>
#include <xmlrpc_client.h>
#include <xmlrpc_server.h>
#define XMLRPC_NO_ASSIGNMENT \
XMLRPC_FATAL_ERROR("Assignment operator not available"); return *this;
//=========================================================================
// XmlRpcFault
//=========================================================================
// A C++ exception class representing an XML-RPC fault.
class XmlRpcFault {
private:
xmlrpc_env mFault;
XmlRpcFault& operator= (const XmlRpcFault& f)
{ (void) f; XMLRPC_NO_ASSIGNMENT }
public:
XmlRpcFault (const XmlRpcFault &fault);
XmlRpcFault (const int faultCode, const string faultString);
XmlRpcFault (const xmlrpc_env *env);
~XmlRpcFault (void);
int getFaultCode (void) const;
string getFaultString (void) const;
xmlrpc_env *getFaultEnv (void);
};
inline int XmlRpcFault::getFaultCode (void) const {
return mFault.fault_code;
}
inline xmlrpc_env *XmlRpcFault::getFaultEnv (void) {
return &mFault;
}
//=========================================================================
// XmlRpcEnv
//=========================================================================
// This class can be used to wrap xmlrpc_env object. Use it as follows:
//
// XmlRpcEnv env;
// xmlrpc_parse_value(env, v, "(i)", &i);
// env.throwIfFaultOccurred();
class XmlRpcEnv {
private:
xmlrpc_env mEnv;
void throwMe (void) const;
XmlRpcEnv& operator= (const XmlRpcEnv& e)
{ (void) e; XMLRPC_NO_ASSIGNMENT }
public:
XmlRpcEnv (const XmlRpcEnv &env);
XmlRpcEnv (void) { xmlrpc_env_init(&mEnv); }
~XmlRpcEnv (void) { xmlrpc_env_clean(&mEnv); }
bool faultOccurred (void) const { return mEnv.fault_occurred; };
bool hasFaultOccurred (void) const { return faultOccurred(); };
/* hasFaultOccurred() is for backward compatibility.
faultOccurred() is a superior name for this.
*/
XmlRpcFault getFault (void) const;
void throwIfFaultOccurred (void) const;
operator xmlrpc_env * (void) { return &mEnv; }
};
inline void XmlRpcEnv::throwIfFaultOccurred (void) const {
if (faultOccurred())
throwMe();
}
//=========================================================================
// XmlRpcValue
//=========================================================================
// An object in this class is an XML-RPC value.
//
// We have a complex structure to allow C code mixed in with C++ code
// which uses this class to refer to the same XML-RPC value object.
// This is especially important because there aren't proper C++ facilities
// for much of Xmlrpc-c; you have to use the C facilities even if you'd
// rather use proper C++.
//
// The XmlRpcValue object internally represents the value as an
// xmlrpc_value. It hold one reference to the xmlrpc_value. Users
// of XmlRpcValue never see that xmlrpc_value, but C code can. the
// C code might create the xmlrpc_value and then bind it to an XmlRpcValue,
// or it might get the xmlrpc_value handle from the XmlRpcValue. Finally,
// C code can simply use the XmlRpcValue where an xmlrpc_value handle is
// required and it gets converted automatically.
//
// So reference counting for the xmlrpc_value is quite a nightmare.
class XmlRpcValue {
private:
xmlrpc_value *mValue;
public:
enum ReferenceBehavior {
MAKE_REFERENCE,
CONSUME_REFERENCE
};
typedef xmlrpc_int32 int32;
XmlRpcValue (void);
XmlRpcValue (xmlrpc_value *value,
ReferenceBehavior behavior = MAKE_REFERENCE);
XmlRpcValue (const XmlRpcValue& value);
~XmlRpcValue (void);
XmlRpcValue& operator= (const XmlRpcValue& value);
// Accessing the value's type (think of this as lightweight RTTI).
xmlrpc_type getType(void) const;
// We don't supply an automatic conversion operator--you need to say
// whether you want to make or borrow this object's reference.
// XXX - Is it really OK for these to be const?
xmlrpc_value *makeReference (void) const;
xmlrpc_value *borrowReference (void) const;
// Some static "constructor" functions.
static XmlRpcValue makeInt (const XmlRpcValue::int32 i);
static XmlRpcValue makeBool (const bool b);
static XmlRpcValue makeDouble (const double d);
static XmlRpcValue makeDateTime (const string& dateTime);
static XmlRpcValue makeString (const string& str);
static XmlRpcValue makeString (const char *const str);
static XmlRpcValue makeString (const char *const str, size_t len);
static XmlRpcValue makeArray (void);
static XmlRpcValue makeStruct (void);
static XmlRpcValue makeBase64 (const unsigned char *const data,
size_t len);
/*
// An interface to xmlrpc_build_value.
static XmlRpcValue buildValue (const char *const format, ...);
*/
// Some functions to get the underlying data.
// These will throw an XmlRpcFault if the data is the wrong type.
XmlRpcValue::int32 getInt (void) const;
bool getBool (void) const;
double getDouble (void) const;
string getRawDateTime (void) const;
string getString (void) const;
XmlRpcValue getArray (void) const;
XmlRpcValue getStruct (void) const;
// This returns an internal pointer which will become invalid when
// all references to the underlying value are destroyed.
void getBase64 (const unsigned char *& out_data,
size_t& out_len) const;
/*
// An interface to xmlrpc_parse_value.
void parseValue (const char *const format, ...);
*/
// Array functions. These will throw an XmlRpcFault if the value
// isn't an array.
size_t arraySize (void) const;
void arrayAppendItem (const XmlRpcValue& value);
XmlRpcValue arrayGetItem (int index) const;
// Struct functions. These will throw an XmlRpcFault if the value
// isn't a struct.
size_t structSize (void) const;
bool structHasKey (const string& key) const;
XmlRpcValue structGetValue (const string& key) const;
void structSetValue (const string& key, const XmlRpcValue& value);
void structGetKeyAndValue (const int index,
string& out_key,
XmlRpcValue& out_value) const;
};
inline XmlRpcValue::XmlRpcValue (xmlrpc_value *value,
ReferenceBehavior behavior)
{
mValue = value;
if (behavior == MAKE_REFERENCE)
xmlrpc_INCREF(value);
}
inline XmlRpcValue::XmlRpcValue (const XmlRpcValue& value) {
mValue = value.mValue;
xmlrpc_INCREF(mValue);
}
inline XmlRpcValue::~XmlRpcValue (void) {
xmlrpc_DECREF(mValue);
}
inline XmlRpcValue& XmlRpcValue::operator= (const XmlRpcValue& value) {
// Must increment before we decrement, in case of assignment to self.
xmlrpc_INCREF(value.mValue);
xmlrpc_DECREF(mValue);
mValue = value.mValue;
return *this;
}
inline xmlrpc_type XmlRpcValue::getType (void) const {
return xmlrpc_value_type(mValue);
}
inline xmlrpc_value *XmlRpcValue::makeReference (void) const {
xmlrpc_INCREF(mValue);
return mValue;
}
inline xmlrpc_value *XmlRpcValue::borrowReference (void) const {
return mValue;
}
//=========================================================================
// XmlRpcClient
//=========================================================================
class XmlRpcClient {
private:
string mServerUrl;
public:
static void Initialize (string appname, string appversion);
static void Terminate (void);
XmlRpcClient (const string& server_url) : mServerUrl(server_url) {}
~XmlRpcClient (void) {}
XmlRpcClient (const XmlRpcClient& client);
XmlRpcClient& operator= (const XmlRpcClient& client);
XmlRpcValue call (string method_name, XmlRpcValue param_array);
void call_asynch (string method_name,
XmlRpcValue param_array,
xmlrpc_response_handler callback,
void* user_data);
void event_loop_asynch (unsigned long milliseconds);
};
inline void XmlRpcClient::call_asynch(string method_name,
XmlRpcValue param_array,
xmlrpc_response_handler callback,
void* user_data)
{
xmlrpc_client_call_asynch_params(
mServerUrl.c_str(),
method_name.c_str(),
callback,
user_data,
param_array.borrowReference());
}
inline void XmlRpcClient::event_loop_asynch(unsigned long milliseconds)
{
xmlrpc_client_event_loop_finish_asynch_timeout(milliseconds);
}
//=========================================================================
// XmlRpcClient Methods
//=========================================================================
// These are inline for now, so we don't need to screw with linker issues
// and build a separate client library.
inline XmlRpcClient::XmlRpcClient (const XmlRpcClient& client)
: mServerUrl(client.mServerUrl)
{
}
inline XmlRpcClient& XmlRpcClient::operator= (const XmlRpcClient& client) {
if (this != &client)
mServerUrl = client.mServerUrl;
return *this;
}
inline void XmlRpcClient::Initialize (string appname, string appversion) {
xmlrpc_client_init(XMLRPC_CLIENT_NO_FLAGS,
appname.c_str(),
appversion.c_str());
}
inline void XmlRpcClient::Terminate (void) {
xmlrpc_client_cleanup();
}
inline XmlRpcValue XmlRpcClient::call (string method_name,
XmlRpcValue param_array)
{
XmlRpcEnv env;
xmlrpc_value *result =
xmlrpc_client_call_params(env,
mServerUrl.c_str(),
method_name.c_str(),
param_array.borrowReference());
env.throwIfFaultOccurred();
return XmlRpcValue(result, XmlRpcValue::CONSUME_REFERENCE);
}
//=========================================================================
// XmlRpcGenSrv
//=========================================================================
class XmlRpcGenSrv {
private:
xmlrpc_registry* mRegistry;
xmlrpc_mem_block* alloc (XmlRpcEnv& env, const string& body) const;
public:
XmlRpcGenSrv (int flags);
~XmlRpcGenSrv (void);
xmlrpc_registry* getRegistry (void) const;
XmlRpcGenSrv& addMethod (const string& name,
xmlrpc_method method,
void *data);
XmlRpcGenSrv& addMethod (const string& name,
xmlrpc_method method,
void* data,
const string& signature,
const string& help);
string handle (const string& body) const;
};
inline XmlRpcGenSrv::XmlRpcGenSrv (int flags) {
XmlRpcEnv env;
if (flags == flags){};
mRegistry = xmlrpc_registry_new (env);
env.throwIfFaultOccurred();
}
inline XmlRpcGenSrv::~XmlRpcGenSrv (void) {
xmlrpc_registry_free (mRegistry);
}
inline xmlrpc_registry* XmlRpcGenSrv::getRegistry () const {
return mRegistry;
}
#undef XMLRPC_NO_ASSIGNMENT
// Copyright (C) 2001 by Eric Kidd. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#endif /* _XMLRPCCPP_H_ */
|
Hospitals across the country are diligently working to reduce infection rates. According to the World Health Organization, hospital-acquired infections affect as many as 1.7 million patients in the United States each year. These infections come at an annual cost of $6.5 billion and contribute to more than 90,000 deaths.
Proper hand hygiene is essential in helping to prevent hospital-acquired infections. A recent study performed by French researchers examined three types of healthcare workers. The first type spent a large amount of time with a discreet group of patients like a nurse would. The second group saw more patients but spent less time with each one - similar to doctors. Group three consisted of healthcare workers who interacted with every patient every day like therapists. The study found that if a healthcare worker in group three failed to wash their hands, the spread of disease was three times worse than if someone from group one or two didn't. The study was published online in Proceedings of the National Academy of Sciences. To read more about the study, continue here.
To read another take on hand hygiene and about the Joint Commission's national hand hygiene project, click here.
Photo Credit: Jessica Flavin
Almost two million patients hospitalized in the U.S. each year develop an infection. These infections occur in as many as one in every 10 patients, result in close to 100,000 deaths and cost upwards of $6 billion. The Wall Street Journal created a top 10 list of infection prevention strategies based on interviews with medical professionals, administrators a non profit company and the Association for Professionals in Infection Control and Epidemiology.
- Undercover Operations - Dr. Philip Carling, an epidemiologist at Caritas Carney Hospital in Dorchester, Mass. developed a solution to uncover how well patient rooms are cleaned. His invisible solution contains fluorescent markers which glow in black light. After spraying patient rooms with the solution, cleaning crews were brought in to perform their normal routine. Later, rooms were examined with a black light and areas missed by the cleaners glowed fluorescent. Sharing results with cleaners helped boost compliance with proper cleaning techniques.
- High-Tech Cleaning Systems - When hospital equipment is disinfected by hand, bacteria often remains. For more thorough disinfecting hospitals are utilizing machines such as Bioquell which sprays a disinfecting hydrogen-peroxide vapor.
- Data Mining - Many hospitals are tracking data to determine how to prevent infections. Lee Memorial Health System in Florida tracks infection rates by surgeon and reports on the results. Low ranking surgeons can then make adjustments to lower their infection rates and improve their ranking.
- Patient Hygiene - Research suggests a daily wash with mild antibacterial soap can dramatically reduce the rate of bloodstream infections. The recommended cleanser is chlorohexidine glutonate.
- Reporting Crackdown - Numerous states have passed laws which require hospitals to report on infection rates. In many cases the reports are publicly available. In addition, Medicare is limiting reimbursement for treatment of hospital-acquired infections.
- Clean hands - Hospitals that utilize strategically-placed dispensers of hand sanitizer have noticed an increase in hand hygiene compliance from less than 50% to more than 80%.
- Embracing the Checklist - Incorporating checklists into bedside medical charts can help reduce rates of infection by requiring shift nurses to answer questions such as: Does this patient have a catheter? If so, is it still necessary?
- Portable Kits - Utilizing all-inclusive kits for common procedures such as intravenous line insertions or dressing changes can limit the possibility for infection. Kits contain all the items needed for procedures and prevent the nurse from running in and out of the patient room during a procedure to find a forgotten item.
- Mouth Maintenance - Regularly cleaning patients' mouths, gums and teeth can help prevent ventilator-associated pneumonia, a common infection found in intensive care units.
- Infection ID - Quick diagnostic tests can identify infected patients in a matter of hours rather than days. This allows for a quick response when patients show symptoms, are tested and found to be infected.
To read the complete article with expanded descriptions of the top 10, click here.
Photo Credit: Presta
Hospitals in Michigan lowered the rate of bloodstream infections in their patients by following a five-step checklist. The study published in the New England Journal of Medicine
found that implementing the checklist reduced the rate of bloodstream infections related to catheter use by 66%. Despite this success, utilization of the checklist remains limited. The checklist itself isn't complicated:
- Wash hands
- Clean patient's skin with chlorohexidine
- Wear protective cap and gown and use a surgical drape during the procedure
- Avoid catheter insertion through the groin if possible
- Remove unnecessary catheters
Peter Pronovost, the patient-safety expert who led the study, spoke with The Wall Street Journal to share insights on why more hospitals haven't benefited from using the checklist. To read excerpts from his interview, click here.
Photo Credit: Adesigna
A recent study published in the American Journal of Infection Control examined the levels of bacteria on healthcare workers' lab coats. The study involved a cross section of medical and surgical grand rounds attendees at a large teaching hospital. Participants completed a survey and cultured their lab coat using a moistened swab on the lapels, pocket and cuffs. Of the 149 white coats in the study, 34 (23%) were contaminated with S aureus, of which 6 (18%) were methicillin-resistant S aureus (MRSA). Providers working with patients had higher contamination levels and the study suggests that white coats may contribute to patient-to-patient transmission of S aureus. Read the entire study in the March 2009 issue of the American Journal of Infection Control, the official journal of the Association for Professionals in Infection Control and Epidemiology (APIC).
Photo Credit: Estherase
Central venous catheters (CVC) are essential for treating children with cancer. They reduce the need for multiple needlesticks and the associated pain and anxiety. In addition, they can be used to deliver chemotherapy, parenteral fluids, blood products and analgesics. Despite the positives, children with CVCs are at increased risk for bloodstream infections. Complications associated with CVCs include pneumothorax, air embolism, nerve injury, catheter malposition, infection and occlusion.
A recent study had four objectives:
1. To decrease CVC-related bloodstream infection rates in children with cancer through a comprehensive educational intervention.
2. To determine if the frequency of catheter hub colonization of CVCs in children with cancer would decrease following the educational intervention.
3. To evaluate nurses' knowledge of CVC care.
4. To determine risk factors influencing CVC-related bloodstream infections in children with cancer.
The study was conducted in the cancer center of a large children's hospital and included patients ranging in age from infancy to 18 years. A 45 minute educational program on CDC guidelines, most frequent guideline violations and information on catheter-related infections was presented to all caregivers. Following the educational presentation, catheter-related bloodstream infections were tracked for six months in order to determine the rate of infection. Study findings showed that the educational program increased nurses' knowledge and instances of catheter-related bloodstream infections decreased. You can read the full article in the March 2009 issue of Oncology Nursing Forum or purchase it online here.
Photo Credit: Gulf Coast Regional Blood Center
According to a 2009 study, approximately 5 million central venous catheters are placed each year. Implantable ports provide reliable venous, arterial, epidural and peritoneal access and can be used to administer IV fluids, medications and to obtain blood samples. However complications including occlusion, infection, catheter migration and catheter separation from portal body can frequently occur.
A recent study conducted in a rural hematology-oncology clinic focused on infection. A port infection can present as local tenderness, pain, erythema, induration or edema at the insertion or exit site or over the port pocket. Patients may also have purulent or serous drainage, fever and chills. To prevent infection, aseptic technique should be utilized for dressing changes. In addition, clinicians should follow accessing and deaccessing procedures and keep the exit clear of potential sources of infection. The 62 patients included in the study were receiving a minimum of two complete cycles of chemotherapy after port insertion. Ports were accessed and deaccessed following outlined protocol.
*Steps for Accessing Ports:
- Wash hands. Assess the port site for erythema, warmth or drainage.
- Palpate the outline of the portal body.
- Wash hands.
- Apply nonsterile gloves. Cleanse port site with chlorohexidine swab in a circular motion for 30 seconds. Allow to dry for 30 seconds.
- Spray ethyl chloride.
- Stabilize portal body with one hand. Insert Huber needle (link to EZ Huber product page) into septum with other hand. Ensure patency by blood return. If no blood return, use interventions to assess port's patency.
- Stabilize port with gauze and tape or apply transparent dressing.
*Steps for Deaccessing Ports:
- Wash hands. Apply nonsterile gloves.
- Inspect exit site.
- Flush device with 20 ml normal saline followed by 5 ml heparin flush (100 units/ml). During final flush, clamp tubing to port.
- Stabilize port and remove needle.
- Apply bandage.
Six of the 62 patients in the study experienced a port infection, with four of the six ports requiring removal. The total number of catheter days for the implanted ports was 7,277. Patient catheter days ranged from 32-288. The study concluded that consistent, routine care is the best preventative measure against port complications. The entire study can be found in the October 2009 issue of the Clinical Journal of Oncology Nursing.
*The port access and de-access protocols are those that were used by the authors for this study. Please follow institutional policies and procedures regarding port access and de-access.
Although many infection headlines are related to hospitals, individual doctor's offices are facing similar challenges. Almost 30 cases of hepatitis B were recently tied to one doctor's office in New Jersey. When health inspectors visited the office they found blood on the floor of a room where chemotherapy was administered, blood in a bin where blood vials were stored, unsterile saline and gauze as well as open medication vials. Inspectors also noticed cross-contamination of pens, refrigerators and countertops, use of contaminated gloves and misuse of antiseptics.
Patients were sent a letter from state epidemiologist Dr. Christina Chan urging testing for hepatitis B. "Evidence gathered at this time suggests that since 2002, some clinic staff provided care in a manner that puts patients at risk for infection caused by bloodborne viruses, including hepatitis B," the letter told patients. "The investigation to date suggests that hepatitis B infections identified may be associated with the method by which medications were administered and procedures performed at the practice."
Numerous checklists and recommendations have been published around infection control. The American Academy of Pediatrics Committee on Infectious Diseases and Committee on Practice and Ambulatory Medicine offers these infection control musts:
- Hand washing
- Barrier precautions to prevent skin and mucous membrane exposure
- Proper handling of sharps and contaminated waste
- Appropriate cleaning and disinfecting of surfaces and equipment
- Aseptic technique for invasive procedures
For the full recommendation on infection control in physician's offices, click here.
To read more about the hepatitis B outbreak in New Jersey, continue reading here.
Photo Credit: Hollywood Pimp
The Joint Commission Center for Transforming Healthcare is working on its first improvement venture: The Hand Hygiene Project. According to the Centers for Disease Control and Prevention, an estimated 2 million patients get a hospital-related infection every year and 90,000 die from their infection.
Causes of Failure to Clean Hands
- Ineffective placement of dispensers or sinks
- Hand hygiene compliance data are not collected or reported accurately or frequently
- Lack of accountability and just-in-time coaching
- Safety culture does not stress hand hygiene at all levels
- Ineffective or insufficient education
- Hands full
- Wearing gloves interferes with process
- Perception that hand hygiene is not needed if wearing gloves
- Healthcare workers forget
Early results of the program found on average that caregivers washed their hands less than 50 percent of the time. "Demanding that healthcare workers try harder is not the answer. These healthcare organizations have the courage to step forward to tackle the problem of hand washing by digging deep to find out where the breakdowns take place so we can create targeted solutions that will work now and keep working in the future," said Mark R. Chassin, M.D., M.P.P, M.P.H., president, The Joint Commission.
By January, 2010, the Joint Commission Center for Transforming Healthcare plans to have data to demonstrate whether the proposed hand hygiene solutions can be sustained to achieve a 90+ percent compliance rate.
Eight hospitals are participating in this project:
- Cedars-Sinai Health System, Los Angeles, California
- Exempla Lutheran Medical Center, Wheat Ridge, Colorado
- Froedtert Hospital, Milwaukee, Wisconsin
- The Johns Hopkins Hospital and Health System, Baltimore, Maryland
- Memorial Hermann Health Care System, Houston, Texas
- Trinity Health, Novi, Michigan
- Virtua, Marlton, New Jersey
- Wake Forest University Baptist Medical Center, Winston-Salem, North Carolina
To read the full release from the Joint Commission for Transforming Healthcare, click here.
Photo Credit: Mag3737
Healthcare providers are on alert due to an increase in a new strain of hospital-acquired infections. A recent study released by Arlington Medical Resources (AMR) and Decision Resources, found that recurrent Clostridium difficile
is difficult to treat in a hospital setting.
Clostridium difficile is a bacterium that can cause symptoms as minor as diarrhea and as life threatening as severe inflammation of the colon. The elderly are most at risk and the Centers for Medicare and Medicaid services is considering adding Clostridium difficile to its list of "never events" or preventable hospital-acquired infections. Hospitals will receive reduced or no Medicare payments for infections on the "never events" list.
Read more about how the study was conducted as well as more information on Clostridium difficile here.
Photo Credit: Big Grey Mare
Jeanne Hahne was working as a nurse in a burn ward when inspiration struck. Because the patients were so vulnerable to infection, Hahne and other healthcare providers had to wear full protective gear including a cap to cover her hair and a mask that covered the majority of her face. Even though she worked with many of the burn patients every day, most couldn't recognize her.
Flash forward almost 30 years and Hahne has designed a face mask made of clear plastic so patients can see her smile. Hahne believes she can reassure patients with a smile and help decrease their anxiety. The masks also have utility for patients and healthcare providers with hearing loss since they allow for lip reading. In addition, the masks have helped improve communication between healthcare workers which can help decrease the chance for mistakes or misunderstanding. To read more and see pictures of the face mask, click here.
Photo Credit: Christiana Care
|
There are many aspects to learning the creation of interactive fiction. Here we mostly undertake to explain approaches to using Inform, and leave the larger questions of craft and design for elsewhere.
The two manuals
There are two interlinked manuals built into every copy of the Inform application: if you've downloaded Inform, you already have them. But they are also available to read or download separately from this website.
Writing with Inform is an overview of the language, beginning with the simplest kinds of construction (such as building a map of rooms, objects, and doors) and working its way up to more advanced tasks. It is meant to be read more or less sequentially, since later chapters build on the ideas in earlier ones; though some of the late chapters (such as those covering numbers, activities, or advanced text) might reasonably be read out of order.
The Recipe Book approaches the problem of authorship from a different perspective. Instead of trying to teach the language from start to finish, it is organized for the author who wants to accomplish something specific, such as asking the player's name at the start of play or implementing a system of measured liquids. It shares the same set of examples that are keyed to Writing with Inform, but organizes them into a new order and accompanies them with text about design problems in creating interactive fiction, rather than explanation of language features.
Following requests from partially sighted Inform users, we've also made two plain vanilla versions of the manual available - they have as little decoration or web design as possible, which means less clutter for screen-reading software to cope with. We offer a choice of:
Minimally tagged HTML provides an archive containing the pages of the manuals and examples as vanilla-flavoured HTML files.
Writing with Inform in plain text format is just what it claims to be - one single file containing only text, with no marking-up of any kind. This contains all of the examples, following the text in numerical order, but not the Recipe Book. (The whole idea of two interleaved manuals can't really be achieved in one flat text file.)
We receive occasional questions about publishing a printed form of the manuals. The answer is that we intend to do exactly that, in due course, but that we expect the current text will be revised wholesale once the system is more mature. (The same thing happened with Inform 6, with the appearance of the printed Designer's Manual in 2001 essentially marking the end of its design cycle.)
|
#ifndef _PARAMETER_HPP
#define _PARAMETER_HPP
#include <vector>
#include <map>
#include <list>
#include "aux.hpp" // Printable
#include "parprior.hpp"
#include "parse_params.hpp" // ParSpecs
// HACK 1: the first parameter is always the overdispersion of the noise
constexpr size_t IDX_SIGMA_OD = 0;
class Parameters : public Printable {
public:
Parameters() { /* empty */ }
Parameters(int n);
Parameters(const std::vector<size_t> & shape);
// TODO initilizer list
const ParPrior & operator[](int i) const; // retrieve a parameter by it's index (can use enum)
ParPrior & operator[](int i); // retrieve a parameter by it's index (can use enum)
const ParPrior & operator[](std::string name) const; // retrieve a parameter by it's name
ParPrior & operator[](std::string name); // retrieve a parameter by it's name
const ParPrior & operator()(size_t i) const; // retrieve i-th parameter, must be scalar
ParPrior & operator()(size_t i); // retrieve i-th parameter, must be scalar
const ParPrior & operator()(size_t i, size_t j) const; // retrieve (i,j)-th parameter according to shape
ParPrior & operator()(size_t i, size_t j); // retrieve (i,j)-th parameter according to shape
bool isScalar(size_t i) const; // is the i-th parameter a scalar according to shape?
size_t flat_size() const; // returns paramvec.size()
size_t size() const; // returns shape.size()
void mutate(Rng & rng, double rel_temp, double t);
void select(int r); // make sure that operator() returns the r-th element of vector-valued parameters
void deselect(); // remove selection
void lockAllBut(int r); // locks all parameter elements except the r-th if at least one element is NOT locked
void removeSingleLocks(); // removes all locks for random effects parameters if at least one element is NOT locked
void print(std::ostream & os) const override;
double loglike() const; // prior likelihood
// HACK 2: we have to disable some of the overdispersed noise terms
std::vector<double> select_od;
protected:
// aux methods for shape
std::pair<size_t, size_t> unflatten_index(size_t i) const;
size_t flatten_index(size_t i, size_t j) const;
// protected members
std::vector<ParPrior> paramvec;
std::vector<size_t> shape;
};
template <class T>
void load_param_specs(Parameters & par, const std::map<T, std::string> & parNameMap,
const std::list<ParSpecs> & parSpecsList) {
for ( auto & [symb, name] : parNameMap ) {
// find parameter in parSpecs
auto it = std::find_if(parSpecsList.begin(), parSpecsList.end(),
[name](const ParSpecs & psc) -> bool {return psc.name == name;});
if ( it == parSpecsList.end() ) {
throw std::runtime_error("parameter '" + name +
"' is not defined in the parameter specs list" + RIGHT_HERE);
} // else... parameter is defined
ParSpecs psc = *it;
// set value
par[symb] = psc.value;
// set name
par[symb].setName(name);
// if not locked, set bounds and sigma for the random walk
if ( !psc.is_locked ) {
par[symb].unlock();
par[symb].setPstd(psc.sigma_rw);
if ( psc.is_lbound ) {
par[symb].setLBound(psc.lbound);
}
if ( psc.is_ubound ) {
par[symb].setUBound(psc.ubound);
}
}
}
}
#endif
|
Serbs, Croats and unhealed wounds Serb recalls how his parents were killed by Croats.
October 01, 1991|By Carl Schoettler | Carl Schoettler,Evening Sun Staff
This man who is a Serbian Yugoslav recites his litany of the awful hurts of World War II as if they happened yesterday.
And as you listen, you realize that in the long history of animosity between Serbs and Croats, the 1940s were yesterday.
"I am born in Bosnia in a village called Blagaj," Vosjislav Velkjo says.
Velkjo owns a foundry in southwest Baltimore where he and his wife, Julia, and three Serbian friends have come to talk about the civil war now raging in Yugoslavia between Serbians and Croatians.
They fear the horrors of World War II are being re-enacted today. They see the Yugoslav army as the protector of Serbians in Croatia from radical Croat nationalists.
"The Croatians," says Velkjo, "who were calling themselves Ustashe, who are close to our village, living with us together like brothers before the Second War, after the war started, turned against us."
Velkjo was born in 1935. He's 56 now, a trim, black-haired, handsome man not given to smiling. He was about 7 when World War II came to his village. He speaks a slow, serviceable English, choosing his words carefully.
Julia, his wife, interrupts, comments, anticipates, moving Velkjo's narrative along like a member of the chorus in a tragedy.
Her brother, a professor who was dean of a university, is now a refugee from Croatia. He lived in Osijek, a city where heavy fighting has been reported.
"Together with Germans, Austrians and Italians," Velkjo says, picking up his story, "Croatians, who are called Ustashe, they catch our Serbs, the old people, children and other people and they put them down these big holes that are called jama."
Bogdan Miscevic, a painter of Yugoslav "primitives" who has lived in Baltimore for years, explains that a jama is a natural grotto common in Yugoslavia.
Miscevic worries about his sister, who lives in Zagreb, the capital of Croatia. He hasn't been able to get in touch with her.
"They put thousands and thousands of people in the same hole," Velkjo says. "Then they shoot into the hole. And they smile and drink and dance. They celebrate.
"So was the husband of my sister killed," Velkjo says.
Ustashe is described by the Encyclopaedia Britannia as a Fascist terrorist organization of radical nationalists that turned Croatia into a country modeled on "the most extremist [Nazi] formation, the SS."
To "purify" Croatia, the Britannia says, "the Ustashe persecuted and killed many thousands of Orthodox Serbs, Jews and Muslims."
Among them, Velkjo says, was his mother.
He describes women and children fleeing from his village into a forest during a battle between Yugoslavia partisan guerrillas and Nazi and Ustashe troops.
"Because she was an old woman she is going only into the woods close to the edge, at the first border, to cover herself, like hundreds of old women and the children they were carrying.
"Ustashe come and with knives kill my mother and one of the older girls." His sister, he says. Another sister was left alive to tell the tale.
"That girl lost her voice," Velkjo says. "From that time on she never talked again."
He and his father found his mother decapitated.
"She was there lying without her head," he says. "Her head on one side, her body on the other. Partisans bury her.
"Now I tell you how my father died."
His father, he says, was questioned and beaten by the Ustashe. They wanted to know where an older brother who had been in the Yugoslavian army was. His father didn't know.
"The last time they beat him," Velkjo says. "He came home and die after 24 hours from the beatings."
His father was 65 or 66. Velkjo was the youngest of nine children. His brother was, in fact, in a German concentration camp, a prisoner of war.
"Now," he says, "this time they're starting to work again the same thing they did in 1941, like they did with Nazis.
"I can't believe it that this happened again," he says. "Croatian politicians are working a long time on organizing what they call 'unfinished war,' what they call 1941 to 1945, fighting against the Serbs."
"Like an unfinished movie," Julia Velkjo says.
Roots of the division run all the way back to the Schism between the Roman and Eastern Orthodox religions in 1054. Serbs are primarily Orthodox, Croats Roman Catholic.
Conflicts between the Austro-Hungarian and the Ottoman Empire exacerbated the split. World War War I, of course, started after a Serb shot the Austrian Archduke Ferdinand at Sarajevo.
During World War II, various nationalist, Communist, monarchist, ethnic, pro-Allies and pro-Nazi groups fought one another. After the war, Josip Broz Tito, a Croat who led the Communist partisans, held the country together almost by sheer force of will -- and a fairly stiff police state -- until his death in 1980.
Franjo Tudjman, now president of the Croatian Republic, was one of Tito's generals. Becoming increasingly nationalist, he was tossed out of the Communist Party about 1967 and imprisoned for several years.
"For 46 years, we lived together to build a new Yugoslavia," Velkjo says. "We are all South Slavs living together. Building our houses, building together, building our hotels, building our factories. Living all together. And being proud for our work and lives together."
"The Serbs who live a long time in Croatia fight for their lands, their houses," Velkjo says. "They are a minority and the Yugoslavian army comes to help them, coming between the Serbs and Croats. They want to keep peace.
"The politicians are always sitting at the table and talking for something they can never achieve," he says. "How long we want to fight we don't know. We want peace for Yugoslavia because we know what peace means."
"But if we don't have army," Julia says, "we'll be killed overnight."
Baltimore Sun Articles
|
Bethlehem Plans To Open Zoning For Steel City Council Will Vote On The Proposal, Which Would Let Developers Convert The Dormant 160 Acres To Almost Any Legitimate Use. Old Blast Furnaces Could Become New Condominiums.
February 09, 1996|by THOMAS KUPPER, The Morning Call
Bethlehem Steel Corp. began easing the yoke of zoning regulations from its shoulders yesterday, as Bethlehem's Planning Commission went along with a plan to rezone 160 acres of the company's land to allow almost any use.
Steel Vice President Stephen Donches said the rezoning, which will go before City Council next, was essential to allow the company to negotiate with potential developers of the land, where steelmaking ended last fall.
"We would talk to developers or potential investors and there would always be three or four questions," Donches said, "and one of those questions was always zoning."
The commission gave its approval by a 3-1 vote, over the objection of member Barbara Flanagan. She said she wanted an idea of the company's intentions before giving executives carte blanche to redevelop the land as they see fit.
Under the plan, the city would rezone the land as an Industrial Redevelopment District. Unlike traditional zoning, which designates areas for specific uses, there would be no guidelines on what could go where.
The primary remaining requirement would be that new buildings would have to meet the requirements that apply to areas zoned for those buildings' uses. So, for instance, a commercial building would have to meet the requirements of a commercial zone.
Individual development plans would still be subject to review by the Planning Commission, but the commission would have no say in what types of buildings were allowed. The review would cover details such as the number of trees or parking spaces.
There would be no legal barrier to stop the company from, for example, putting condominiums next to its remaining steel operations.
City Business Administrator Robert Wilkins, a former Bethlehem Steel vice president, said the proposal had Mayor Ken Smith's strong support. He said Smith's administration knew some of the company's plans but had to keep them quiet to protect developers' confidentiality.
Bethlehem Steel has not divulged details of its plans for the riverfront land, where blast furnaces stand as central features of Bethlehem's skyline. Donches said the company would present a conceptual plan with possible uses for the land within about two months.
The rezoning proposal reflects an ordinance Bethlehem Steel submitted to the city with some modifications to meet the requirements of state law. One change will require the company to submit a report with its goals and possible uses for various sections.
City Council has scheduled a public hearing on the plan for March 5.
One man in the audience questioned whether there couldn't be some community control over the mix of uses on the property, for instance, setting aside a parcel for recreation. But city Solicitor Constantine Vasiliadis said that type of regulation would not be "appropriate."
Flanagan said the company ought to make its goals public before any rezoning.
"You're telling us, trust us, we're Bethlehem Steel," Flanagan said. "I'm saying we do trust you, but give us the public presentation first. Then I think we'll gladly give you the zoning."
Donches said the reason for the company's urgency was that potential developers might lose interest in the next two months. He said the company had put several developers on hold, and that cooperation from the city would help in the redevelopment.
Morning Call Articles
|
This is an old lecture by linguist and political activist Noam Chomsky (professor at MIT) given at UC Berkeley in 2003. For that evening in the Charles M. and Martha Hitchcock Lecture series, Chomsky examined biolinguistics - the study of relations between physiology and speech.
A second video of Chomsky is featured below, which is the second half of this talk. Fair warning - this is not easy material - Chomsky is speaking to people who are well-versed in this field.
Chomsky has been one the most influential scholars over the last three or four decades - between 1980 and 1992, he was cited as a source more than any other living scholar, and ranked eighth overall.
As background for this lecture, Wikipedia offers a good summary of his influence in linguistics (below the video).
Chomskyan LinguisticsChomskyan linguistics, beginning with his Syntactic Structures, a distillation of his Logical Structure of Linguistic Theory (1955, 75), challenges structural linguistics and introduces transformational grammar. This approach takes utterances (sequences of words) to have a syntax characterized by a formal grammar; in particular, a context-free grammar extended with transformational rules.
Perhaps his most influential and time-tested contribution to the field, is the claim that modeling knowledge of language using a formal grammar accounts for the "productivity" or "creativity" of language. In other words, a formal grammar of a language can explain the ability of a hearer-speaker to produce and interpret an infinite number of utterances, including novel ones, with a limited set of grammatical rules and a finite set of terms. He has always acknowledged his debt to Pāṇini for his modern notion of an explicit generative grammar although it is also related to rationalist ideas of a priori knowledge.
It is a popular misconception that Chomsky proved that language is entirely innate and discovered a "universal grammar" (UG). In fact, Chomsky simply observed that while a human baby and a kitten are both capable of inductive reasoning, if they are exposed to exactly the same linguistic data, the human child will always acquire the ability to understand and produce language, while the kitten will never acquire either ability. Chomsky labeled whatever the relevant capacity the human has which the cat lacks the "language acquisition device" (LAD) and suggested that one of the tasks for linguistics should be to figure out what the LAD is and what constraints it puts on the range of possible human languages. The universal features that would result from these constraints are often termed "universal grammar" or UG.
The Principles and Parameters approach (P&P)—developed in his Pisa 1979 Lectures, later published as Lectures on Government and Binding (LGB)—makes strong claims regarding universal grammar: that the grammatical principles underlying languages are innate and fixed, and the differences among the world's languages can be characterized in terms of parameter settings in the brain (such as the pro-drop parameter, which indicates whether an explicit subject is always required, as in English, or can be optionally dropped, as in Spanish), which are often likened to switches. (Hence the term principles and parameters, often given to this approach.) In this view, a child learning a language need only acquire the necessary lexical items (words, grammatical morphemes, and idioms), and determine the appropriate parameter settings, which can be done based on a few key examples.
Proponents of this view argue that the pace at which children learn languages is inexplicably rapid, unless children have an innate ability to learn languages. The similar steps followed by children all across the world when learning languages, and the fact that children make certain characteristic errors as they learn their first language, whereas other seemingly logical kinds of errors never occur (and, according to Chomsky, should be attested if a purely general, rather than language-specific, learning mechanism were being employed), are also pointed to as motivation for innateness.
More recently, in his Minimalist Program (1995), while retaining the core concept of "principles and parameters," Chomsky attempts a major overhaul of the linguistic machinery involved in the LGB model, stripping from it all but the barest necessary elements, while advocating a general approach to the architecture of the human language faculty that emphasizes principles of economy and optimal design, reverting to a derivational approach to generation, in contrast with the largely representational approach of classic P&P.
Chomsky's ideas have had a strong influence on researchers of the language acquisition in children, though many researchers in this area such as Elizabeth Bates and Michael Tomasello argue very strongly against Chomsky's theories, and instead advocate emergentist or connectionist theories, explaining language with a number of general processing mechanisms in the brain that interact with the extensive and complex social environment in which language is used and learned.
His best-known work in phonology is The Sound Pattern of English (1968), written with Morris Halle (and often known as simply SPE). This work has had a great significance for the development in the field. While phonological theory has since moved beyond "SPE phonology" in many important respects, the SPE system is considered the precursor of some of the most influential phonological theories today, including autosegmental phonology, lexical phonology and optimality theory. Chomsky no longer publishes on phonology.
|
White Cane Law
December 2, 1985
I USE A long white cane, and one of several that I own was bent into the shape of the letter L by a motorist who whizzed around a corner while I was trying to cross a street under a ''walk'' traffic signal. It was only luck that the shape of my body does not look like that cane.
Florida Statute 413.07 -- the white cane law -- requires drivers to come to a stop at an intersection where a person raising or using a white cane is trying to cross. This means a full stop and not a ''rolling stop,'' regardless of the fact that the motorist is making a turn or proceeding straight ahead.
The same rules apply where dog guides are used.
Any person who violated any portion of the law shall be guilty of a misdemeanor of the second degree.
George Curtis Mild
Florida Blinded Veterans Association
Orlando Sentinel Articles
|
/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file gameengine/Rasterizer/RAS_2DFilterManager.cpp
* \ingroup bgerast
*/
#include "BLI_utildefines.h"
#include "RAS_OpenGLFilters/RAS_Blur2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Sharpen2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Dilation2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Erosion2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Laplacian2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Sobel2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Prewitt2DFilter.h"
#include "RAS_OpenGLFilters/RAS_GrayScale2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Sepia2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Invert2DFilter.h"
#include "STR_String.h"
#include "RAS_ICanvas.h"
#include "RAS_Rect.h"
#include "RAS_2DFilterManager.h"
#include <iostream>
#include "GPU_glew.h"
#include <stdio.h>
#include "EXP_Value.h"
RAS_2DFilterManager::RAS_2DFilterManager():
texturewidth(-1), textureheight(-1),
/* numberoffilters(0), */ /* UNUSED */ need_tex_update(true)
{
isshadersupported = GLEW_ARB_shader_objects &&
GLEW_ARB_fragment_shader && GLEW_ARB_multitexture;
/* used to return before 2.49 but need to initialize values so don't */
if (!isshadersupported)
std::cout<<"shaders not supported!" << std::endl;
int passindex;
for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
{
m_filters[passindex] = 0;
m_enabled[passindex] = 0;
texflag[passindex] = 0;
m_gameObjects[passindex] = NULL;
}
texname[0] = texname[1] = texname[2] = -1;
errorprinted= false;
}
RAS_2DFilterManager::~RAS_2DFilterManager()
{
FreeTextures();
for (int passindex = 0; passindex < MAX_RENDER_PASS; passindex++) {
if (m_filters[passindex]) {
glDeleteObjectARB(m_filters[passindex]);
}
}
}
void RAS_2DFilterManager::PrintShaderErrors(unsigned int shader, const char *task, const char *code)
{
GLcharARB log[5000];
GLsizei length = 0;
const char *c, *pos, *end;
int line = 1;
if (errorprinted)
return;
errorprinted= true;
glGetInfoLogARB(shader, sizeof(log), &length, log);
end = code + strlen(code);
printf("2D Filter GLSL Shader: %s error:\n", task);
c = code;
while ((c < end) && (pos = strchr(c, '\n'))) {
printf("%2d ", line);
fwrite(c, (pos+1)-c, 1, stdout);
c = pos+1;
line++;
}
puts(c);
puts(log);
puts("\n");
}
unsigned int RAS_2DFilterManager::CreateShaderProgram(const char* shadersource)
{
GLuint program = 0;
GLuint fShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);
GLint success;
glShaderSourceARB(fShader, 1, (const char**)&shadersource, NULL);
glCompileShaderARB(fShader);
glGetObjectParameterivARB(fShader, GL_COMPILE_STATUS, &success);
if (!success) {
/*Shader Comile Error*/
PrintShaderErrors(fShader, "compile", shadersource);
goto fail;
}
program = glCreateProgramObjectARB();
glAttachObjectARB(program, fShader);
glLinkProgramARB(program);
glGetObjectParameterivARB(program, GL_LINK_STATUS, &success);
if (!success) {
/*Program Link Error*/
PrintShaderErrors(fShader, "link", shadersource);
goto fail;
}
glValidateProgramARB(program);
glGetObjectParameterivARB(program, GL_VALIDATE_STATUS, &success);
if (!success) {
/*Program Validation Error*/
PrintShaderErrors(fShader, "validate", shadersource);
goto fail;
}
/* owned by 'program' */
if (fShader) {
glDeleteObjectARB(fShader);
}
return program;
fail:
if (fShader) {
glDeleteObjectARB(fShader);
}
if (program) {
glDeleteObjectARB(program);
}
return 0;
}
unsigned int RAS_2DFilterManager::CreateShaderProgram(int filtermode)
{
switch (filtermode) {
case RAS_2DFILTER_BLUR:
return CreateShaderProgram(BlurFragmentShader);
case RAS_2DFILTER_SHARPEN:
return CreateShaderProgram(SharpenFragmentShader);
case RAS_2DFILTER_DILATION:
return CreateShaderProgram(DilationFragmentShader);
case RAS_2DFILTER_EROSION:
return CreateShaderProgram(ErosionFragmentShader);
case RAS_2DFILTER_LAPLACIAN:
return CreateShaderProgram(LaplacionFragmentShader);
case RAS_2DFILTER_SOBEL:
return CreateShaderProgram(SobelFragmentShader);
case RAS_2DFILTER_PREWITT:
return CreateShaderProgram(PrewittFragmentShader);
case RAS_2DFILTER_GRAYSCALE:
return CreateShaderProgram(GrayScaleFragmentShader);
case RAS_2DFILTER_SEPIA:
return CreateShaderProgram(SepiaFragmentShader);
case RAS_2DFILTER_INVERT:
return CreateShaderProgram(InvertFragmentShader);
}
return 0;
}
void RAS_2DFilterManager::AnalyseShader(int passindex, vector<STR_String>& propNames)
{
texflag[passindex] = 0;
if (glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture") != -1)
{
if (GLEW_ARB_depth_texture)
texflag[passindex] |= 0x1;
}
if (glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture") != -1)
{
texflag[passindex] |= 0x2;
}
if (m_gameObjects[passindex])
{
int objProperties = propNames.size();
int i;
for (i=0; i<objProperties; i++)
if (glGetUniformLocationARB(m_filters[passindex], propNames[i]) != -1)
m_properties[passindex].push_back(propNames[i]);
}
}
void RAS_2DFilterManager::StartShaderProgram(int passindex)
{
GLint uniformLoc;
glUseProgramObjectARB(m_filters[passindex]);
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTexture");
glActiveTextureARB(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texname[0]);
if (uniformLoc != -1)
{
glUniform1iARB(uniformLoc, 0);
}
/* send depth texture to glsl program if it needs */
if (texflag[passindex] & 0x1) {
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture");
glActiveTextureARB(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texname[1]);
if (uniformLoc != -1)
{
glUniform1iARB(uniformLoc, 1);
}
}
/* send luminance texture to glsl program if it needs */
if (texflag[passindex] & 0x2) {
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture");
glActiveTextureARB(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texname[2]);
if (uniformLoc != -1)
{
glUniform1iARB(uniformLoc, 2);
}
}
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_TextureCoordinateOffset");
if (uniformLoc != -1)
{
glUniform2fvARB(uniformLoc, 9, textureoffsets);
}
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureWidth");
if (uniformLoc != -1)
{
glUniform1fARB(uniformLoc,texturewidth);
}
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureHeight");
if (uniformLoc != -1)
{
glUniform1fARB(uniformLoc,textureheight);
}
int i, objProperties = m_properties[passindex].size();
for (i=0; i<objProperties; i++)
{
uniformLoc = glGetUniformLocationARB(m_filters[passindex], m_properties[passindex][i]);
if (uniformLoc == -1)
continue;
CValue *property = ((CValue *)m_gameObjects[passindex])->GetProperty(m_properties[passindex][i]);
if (!property)
continue;
switch (property->GetValueType()) {
case VALUE_INT_TYPE:
glUniform1iARB(uniformLoc, property->GetNumber());
break;
case VALUE_FLOAT_TYPE:
glUniform1fARB(uniformLoc, property->GetNumber());
break;
default:
break;
}
}
}
void RAS_2DFilterManager::EndShaderProgram()
{
glUseProgramObjectARB(0);
}
void RAS_2DFilterManager::FreeTextures()
{
if (texname[0]!=(unsigned int)-1)
glDeleteTextures(1, (GLuint*)&texname[0]);
if (texname[1]!=(unsigned int)-1)
glDeleteTextures(1, (GLuint*)&texname[1]);
if (texname[2]!=(unsigned int)-1)
glDeleteTextures(1, (GLuint*)&texname[2]);
}
void RAS_2DFilterManager::SetupTextures(bool depth, bool luminance)
{
FreeTextures();
glGenTextures(1, (GLuint*)&texname[0]);
glBindTexture(GL_TEXTURE_2D, texname[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texturewidth, textureheight, 0, GL_RGBA,
GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
if (depth) {
glGenTextures(1, (GLuint*)&texname[1]);
glBindTexture(GL_TEXTURE_2D, texname[1]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, texturewidth,textureheight,
0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE,NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
}
if (luminance) {
glGenTextures(1, (GLuint*)&texname[2]);
glBindTexture(GL_TEXTURE_2D, texname[2]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, texturewidth, textureheight,
0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
}
}
void RAS_2DFilterManager::UpdateOffsetMatrix(RAS_ICanvas* canvas)
{
/* RAS_Rect canvas_rect = canvas->GetWindowArea(); */ /* UNUSED */
texturewidth = canvas->GetWidth()+1;
textureheight = canvas->GetHeight()+1;
GLint i,j;
if (!GL_ARB_texture_non_power_of_two)
{
i = 0;
while ((1 << i) <= texturewidth)
i++;
texturewidth = (1 << (i));
// Now for height
i = 0;
while ((1 << i) <= textureheight)
i++;
textureheight = (1 << (i));
}
GLfloat xInc = 1.0f / (GLfloat)texturewidth;
GLfloat yInc = 1.0f / (GLfloat)textureheight;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
textureoffsets[(((i*3)+j)*2)+0] = (-1.0f * xInc) + ((GLfloat)i * xInc);
textureoffsets[(((i*3)+j)*2)+1] = (-1.0f * yInc) + ((GLfloat)j * yInc);
}
}
}
void RAS_2DFilterManager::UpdateCanvasTextureCoord(const int viewport[4])
{
/*
* This function update canvascoord[].
* These parameters are used to create texcoord[1]
* That way we can access the texcoord relative to the canvas:
* (0.0,0.0) bottom left, (1.0,1.0) top right, (0.5,0.5) center
*/
canvascoord[0] = (GLfloat) viewport[0] / -viewport[2];
canvascoord[1] = (GLfloat) (texturewidth - viewport[0]) / viewport[2];
canvascoord[2] = (GLfloat) viewport[1] / -viewport[3];
canvascoord[3] = (GLfloat)(textureheight - viewport[1]) / viewport[3];
}
void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
{
bool need_depth=false;
bool need_luminance=false;
int num_filters = 0;
int passindex;
if (!isshadersupported)
return;
for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
{
if (m_filters[passindex] && m_enabled[passindex]) {
num_filters ++;
if (texflag[passindex] & 0x1)
need_depth = true;
if (texflag[passindex] & 0x2)
need_luminance = true;
if (need_depth && need_luminance)
break;
}
}
if (num_filters <= 0)
return;
const int *viewport = canvas->GetViewPort();
if (texturewidth != viewport[2] || textureheight != viewport[3])
{
UpdateOffsetMatrix(canvas);
UpdateCanvasTextureCoord(viewport);
need_tex_update = true;
}
if (need_tex_update)
{
SetupTextures(need_depth, need_luminance);
need_tex_update = false;
}
if (need_depth) {
glActiveTextureARB(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texname[1]);
glCopyTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT, viewport[0], viewport[1], viewport[2], viewport[3], 0);
}
if (need_luminance) {
glActiveTextureARB(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texname[2]);
glCopyTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE16, viewport[0], viewport[1], viewport[2], viewport[3], 0);
}
// reverting to texunit 0, without this we get bug [#28462]
glActiveTextureARB(GL_TEXTURE0);
// We do this to make side-by-side stereo rendering work correctly with 2D filters. It would probably be nicer to just set the viewport,
// but it can be easier for writing shaders to have the coordinates for the whole screen instead of just part of the screen.
RAS_Rect scissor_rect = canvas->GetDisplayArea();
glScissor(scissor_rect.GetLeft() + viewport[0],
scissor_rect.GetBottom() + viewport[1],
scissor_rect.GetWidth() + 1,
scissor_rect.GetHeight() + 1);
glDisable(GL_DEPTH_TEST);
// in case the previous material was wire
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// if the last rendered face had alpha add it would messes with the color of the plane we apply 2DFilter to
glDisable(GL_BLEND);
// fix for [#34523] alpha buffer is now available for all OSs
glDisable(GL_ALPHA_TEST);
glPushMatrix(); //GL_MODELVIEW
glLoadIdentity(); // GL_MODELVIEW
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
{
if (m_filters[passindex] && m_enabled[passindex])
{
StartShaderProgram(passindex);
glActiveTextureARB(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texname[0]);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, viewport[0], viewport[1], viewport[2], viewport[3], 0); // Don't use texturewidth and textureheight in case we don't have NPOT support
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
glColor4f(1.f, 1.f, 1.f, 1.f);
glTexCoord2f(1.0f, 1.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[3]); glVertex2f(1.0f,1.0f);
glTexCoord2f(0.0f, 1.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[3]); glVertex2f(-1.0f,1.0f);
glTexCoord2f(0.0f, 0.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[2]); glVertex2f(-1.0f,-1.0f);
glTexCoord2f(1.0f, 0.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[2]); glVertex2f(1.0f,-1.0f);
glEnd();
}
}
glEnable(GL_DEPTH_TEST);
EndShaderProgram();
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
void RAS_2DFilterManager::EnableFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text)
{
if (!isshadersupported)
return;
if (pass<0 || pass>=MAX_RENDER_PASS)
return;
need_tex_update = true;
if (mode == RAS_2DFILTER_DISABLED)
{
m_enabled[pass] = 0;
return;
}
if (mode == RAS_2DFILTER_ENABLED)
{
m_enabled[pass] = 1;
return;
}
if (mode == RAS_2DFILTER_NOFILTER)
{
if (m_filters[pass])
glDeleteObjectARB(m_filters[pass]);
m_enabled[pass] = 0;
m_filters[pass] = 0;
m_gameObjects[pass] = NULL;
m_properties[pass].clear();
texflag[pass] = 0;
return;
}
if (mode == RAS_2DFILTER_CUSTOMFILTER)
{
if (m_filters[pass])
glDeleteObjectARB(m_filters[pass]);
m_filters[pass] = CreateShaderProgram(text.Ptr());
m_gameObjects[pass] = gameObj;
AnalyseShader(pass, propNames);
m_enabled[pass] = 1;
return;
}
// We've checked all other cases, which means we must be dealing with a builtin filter
if (m_filters[pass])
glDeleteObjectARB(m_filters[pass]);
m_filters[pass] = CreateShaderProgram(mode);
m_gameObjects[pass] = NULL;
AnalyseShader(pass, propNames);
m_enabled[pass] = 1;
}
|
#include "catch.hpp"
#include "../compiler/tinyparser.h"
// inline std::vector<tiny::st_c> _list(tiny::st_t* list[]) {
// std::vector<tiny::st_c> r;
// for (size_t i = 0; list[i]; ++i) {
// r.emplace_back(list[i]);
// }
// return r;
// }
// #define LIST(vals...) _list((tiny::st_t*[]){vals, nullptr})
#define RVAL(str, r) new tiny::value_t(tiny::tok_number, str, r)
#define VAL(str) RVAL(str, tiny::tok_undef)
#define VAR(name) new tiny::var_t(name)
#define BIN(op,a,b) new tiny::bin_t(op, a, b)
// #define CALL(fname, args) new tiny::call_t(fname, new tiny::list_t(LIST(args)))
// #define PCALL(r, args) new tiny::pcall_t(r, new tiny::list_t(LIST(args)))
#define PREG(args, seq) new tiny::func_t(args, seq)
#define SET(varname, val) new tiny::set_t(varname, val)
// #define SEQ(vals...) new tiny::sequence_t(LIST(vals))
TEST_CASE("Simple Treeify", "[treeify-simple]") {
SECTION("1 entry") {
const char* inputs[] = {
"0",
"1",
"arr",
"\"hello world\"",
"my_var",
"0x",
"0x1234",
"0b1011",
"aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899",
"aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889",
nullptr,
};
tiny::st_t* expected[] = {
VAL("0"),
VAL("1"),
VAR("arr"),
VAL("hello world"),
VAR("my_var"),
RVAL("", tiny::tok_hex),
RVAL("1234", tiny::tok_hex),
RVAL("1011", tiny::tok_bin),
VAR("aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"),
VAR("aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889"),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("2 tokens") {
const char* inputs[] = {
"(0)",
"(1)",
"(arr)",
"(\"hello world\")",
"(my_var)",
"(0x)",
"(0x1234)",
"(0b1011)",
"(aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899)",
"(aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889)",
"!1",
"!0",
nullptr,
};
tiny::st_t* expected[] = {
VAL("0"),
VAL("1"),
VAR("arr"),
VAL("hello world"),
VAR("my_var"),
RVAL("", tiny::tok_hex),
RVAL("1234", tiny::tok_hex),
RVAL("1011", tiny::tok_bin),
VAR("aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"),
VAR("aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889"),
new tiny::unary_t(tiny::tok_not, VAL("1")),
new tiny::unary_t(tiny::tok_not, VAL("0")),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("3 tokens") {
const char* inputs[] = {
"1 + 1",
"1 - 1",
"a * a",
"10 / 5",
"\"hello\" ++ \"world\"",
"0xab ++ 0xcd",
"function()",
nullptr,
};
tiny::st_t* expected[] = {
BIN(tiny::tok_plus, VAL("1"), VAL("1")),
BIN(tiny::tok_minus, VAL("1"), VAL("1")),
BIN(tiny::tok_mul, VAR("a"), VAR("a")),
BIN(tiny::tok_div, VAL("10"), VAL("5")),
BIN(tiny::tok_concat, VAL("hello"), VAL("world")),
BIN(tiny::tok_concat, RVAL("ab", tiny::tok_hex), RVAL("cd", tiny::tok_hex)),
new tiny::call_t("function", nullptr),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("4 tokens") {
const char* inputs[] = {
"a *= 5",
// "() {}",
"a ++= 11",
nullptr,
};
tiny::st_t* expected[] = {
SET("a", BIN(tiny::tok_mul, VAR("a"), VAL("5"))),
// PREG(std::vector<std::string>(), SEQ(nullptr)),
SET("a", BIN(tiny::tok_concat, VAR("a"), VAL("11"))),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("5 tokens") {
const char* inputs[] = {
"2 + 3 * 5",
"2 * 3 + 5",
"2 ++ 3 * 5",
"2 * 3 ++ 5",
// "() { 10 }",
"a = a * 5",
nullptr,
};
tiny::st_t* expected[] = {
BIN(tiny::tok_plus, VAL("2"), BIN(tiny::tok_mul, VAL("3"), VAL("5"))),
BIN(tiny::tok_plus, BIN(tiny::tok_mul, VAL("2"), VAL("3")), VAL("5")),
BIN(tiny::tok_concat, VAL("2"), BIN(tiny::tok_mul, VAL("3"), VAL("5"))),
BIN(tiny::tok_concat, BIN(tiny::tok_mul, VAL("2"), VAL("3")), VAL("5")),
// PREG(std::vector<std::string>(), SEQ(VAL("10"))),
SET("a", BIN(tiny::tok_mul, VAR("a"), VAL("5"))),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
}
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2018.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
namespace OpenMS
{
MzTabParameterList::~MzTabParameterList()
{
}
bool MzTabParameterList::isNull() const
{
return parameters_.empty();
}
void MzTabParameterList::setNull(bool b)
{
if (b)
{
parameters_.clear();
}
}
String MzTabParameterList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabParameter>::const_iterator it = parameters_.begin(); it != parameters_.end(); ++it)
{
if (it != parameters_.begin())
{
ret += "|";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabParameterList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split("|", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabParameter p;
lower = fields[i];
lower.toLower().trim();
if (lower == "null")
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("MzTabParameter in MzTabParameterList must not be null '") + s);
}
p.fromCellString(fields[i]);
parameters_.push_back(p);
}
}
}
std::vector<MzTabParameter> MzTabParameterList::get() const
{
return parameters_;
}
void MzTabParameterList::set(const std::vector<MzTabParameter>& parameters)
{
parameters_ = parameters;
}
MzTabStringList::MzTabStringList() :
sep_('|')
{
}
MzTabStringList::~MzTabStringList()
{
}
void MzTabStringList::setSeparator(char sep)
{
sep_ = sep;
}
bool MzTabStringList::isNull() const
{
return entries_.empty();
}
void MzTabStringList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabStringList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabString>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += sep_;
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabStringList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split(sep_, fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabString ts;
ts.fromCellString(fields[i]);
entries_.push_back(ts);
}
}
}
std::vector<MzTabString> MzTabStringList::get() const
{
return entries_;
}
void MzTabStringList::set(const std::vector<MzTabString>& entries)
{
entries_ = entries;
}
MzTabModification::MzTabModification()
{
}
MzTabModification::~MzTabModification()
{
}
bool MzTabModification::isNull() const
{
return pos_param_pairs_.empty() && mod_identifier_.isNull();
}
void MzTabModification::setNull(bool b)
{
if (b)
{
pos_param_pairs_.clear();
mod_identifier_.setNull(true);
}
}
void MzTabModification::setPositionsAndParameters(const std::vector<std::pair<Size, MzTabParameter> >& ppp)
{
pos_param_pairs_ = ppp;
}
std::vector<std::pair<Size, MzTabParameter> > MzTabModification::getPositionsAndParameters() const
{
return pos_param_pairs_;
}
void MzTabModification::setModificationIdentifier(const MzTabString& mod_id)
{
mod_identifier_ = mod_id;
}
MzTabString MzTabModification::getModOrSubstIdentifier() const
{
assert(!isNull());
return mod_identifier_;
}
String MzTabModification::toCellString() const
{
if (isNull())
{
return String("null");
}
else
{
String pos_param_string;
for (Size i = 0; i != pos_param_pairs_.size(); ++i)
{
pos_param_string += pos_param_pairs_[i].first;
// attach MzTabParameter if available
if (!pos_param_pairs_[i].second.isNull())
{
pos_param_string += pos_param_pairs_[i].second.toCellString();
}
// add | as separator (except for last one)
if (i < pos_param_pairs_.size() - 1)
{
pos_param_string += String("|");
}
}
// quick sanity check
if (mod_identifier_.isNull())
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Modification or Substitution identifier MUST NOT be null or empty in MzTabModification"));
}
String res;
// only add '-' if we have position information
if (!pos_param_string.empty())
{
res = pos_param_string + "-" + mod_identifier_.toCellString();
}
else
{
res = mod_identifier_.toCellString();
}
return res;
}
}
void MzTabModification::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
if (!lower.hasSubstring("-")) // no positions? simply use s as mod identifier
{
mod_identifier_.set(String(s).trim());
}
else
{
String ss = s;
ss.trim();
std::vector<String> fields;
ss.split("-", fields);
if (fields.size() != 2)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Can't convert to MzTabModification from '") + s);
}
mod_identifier_.fromCellString(fields[1].trim());
std::vector<String> position_fields;
fields[0].split("|", position_fields);
for (Size i = 0; i != position_fields.size(); ++i)
{
Size spos = position_fields[i].find_first_of("[");
if (spos == std::string::npos) // only position information and no parameter
{
pos_param_pairs_.push_back(std::make_pair(position_fields[i].toInt(), MzTabParameter()));
}
else
{
// extract position part
Int pos = String(position_fields[i].begin(), position_fields[i].begin() + spos).toInt();
// extract [,,,] part
MzTabParameter param;
param.fromCellString(position_fields[i].substr(spos));
pos_param_pairs_.push_back(std::make_pair(pos, param));
}
}
}
}
}
MzTabModificationList::~MzTabModificationList()
{
}
bool MzTabModificationList::isNull() const
{
return entries_.empty();
}
void MzTabModificationList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabModificationList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabModification>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += ",";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabModificationList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
if (!ss.hasSubstring("[")) // no parameters
{
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabModification ms;
ms.fromCellString(fields[i]);
entries_.push_back(ms);
}
}
else
{
// example string: 3|4[a,b,,v]|8[,,"blabla, [bla]",v],1|2|3[a,b,,v]-mod:123
// we don't want to split at the , inside of [ ] MzTabParameter brackets.
// Additionally, and we don't want to recognise quoted brackets inside the MzTabParameter where they can occur in quoted text (see example string)
bool in_param_bracket = false;
bool in_quotes = false;
for (Size pos = 0; pos != ss.size(); ++pos)
{
// param_bracket state
if (ss[pos] == '[' && !in_quotes)
{
in_param_bracket = true;
continue;
}
if (ss[pos] == ']' && !in_quotes)
{
in_param_bracket = false;
continue;
}
// quote state
if (ss[pos] == '\"')
{
in_quotes = !in_quotes;
continue;
}
// comma in param bracket
if (ss[pos] == ',' && !in_quotes && in_param_bracket)
{
ss[pos] = ((char)007); // use ASCII bell as temporary separator
continue;
}
}
// now the split at comma is save
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
fields[i].substitute(((char)007), ','); // resubstitute comma after split
MzTabModification ms;
ms.fromCellString(fields[i]);
entries_.push_back(ms);
}
}
}
}
std::vector<MzTabModification> MzTabModificationList::get() const
{
return entries_;
}
void MzTabModificationList::set(const std::vector<MzTabModification>& entries)
{
entries_ = entries;
}
MzTabSpectraRef::MzTabSpectraRef() :
ms_run_(0)
{
}
MzTabSpectraRef::~MzTabSpectraRef()
{
}
bool MzTabSpectraRef::isNull() const
{
return (ms_run_ < 1) || (spec_ref_.empty());
}
void MzTabSpectraRef::setNull(bool b)
{
if (b)
{
ms_run_ = 0;
spec_ref_.clear();
}
}
void MzTabSpectraRef::setMSFile(Size index)
{
assert(index >= 1);
if (index >= 1)
{
ms_run_ = index;
}
}
void MzTabSpectraRef::setSpecRef(String spec_ref)
{
assert(!spec_ref.empty());
if (!spec_ref.empty())
{
spec_ref_ = spec_ref;
}
}
String MzTabSpectraRef::getSpecRef() const
{
assert(!isNull());
return spec_ref_;
}
Size MzTabSpectraRef::getMSFile() const
{
assert(!isNull());
return ms_run_;
}
void MzTabSpectraRef::setSpecRefFile(const String& spec_ref)
{
assert(!spec_ref.empty());
if (!spec_ref.empty())
{
spec_ref_ = spec_ref;
}
}
String MzTabSpectraRef::toCellString() const
{
if (isNull())
{
return String("null");
}
else
{
return String("ms_run[") + String(ms_run_) + "]:" + spec_ref_;
}
}
void MzTabSpectraRef::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split(":", fields);
if (fields.size() != 2)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Can not convert to MzTabSpectraRef from '") + s);
}
spec_ref_ = fields[1];
ms_run_ = (Size)(fields[0].substitute("ms_run[", "").remove(']').toInt());
}
}
MzTabProteinSectionRow::MzTabProteinSectionRow()
{
// use "," as list separator because "|" can be used for go terms and protein accessions
go_terms.setSeparator(',');
ambiguity_members.setSeparator(',');
}
MzTabMetaData::MzTabMetaData()
{
mz_tab_version.fromCellString(String("1.0.0"));
}
MzTab::MzTab()
{
}
MzTab::~MzTab()
{
}
const MzTabMetaData& MzTab::getMetaData() const
{
return meta_data_;
}
void MzTab::setMetaData(const MzTabMetaData& md)
{
meta_data_ = md;
}
const MzTabProteinSectionRows& MzTab::getProteinSectionRows() const
{
return protein_data_;
}
void MzTab::setProteinSectionRows(const MzTabProteinSectionRows& psd)
{
protein_data_ = psd;
}
const MzTabPeptideSectionRows& MzTab::getPeptideSectionRows() const
{
return peptide_data_;
}
void MzTab::setPeptideSectionRows(const MzTabPeptideSectionRows& psd)
{
peptide_data_ = psd;
}
const MzTabPSMSectionRows& MzTab::getPSMSectionRows() const
{
return psm_data_;
}
void MzTab::setPSMSectionRows(const MzTabPSMSectionRows& psd)
{
psm_data_ = psd;
}
void MzTab::setCommentRows(const std::map<Size, String>& com)
{
comment_rows_ = com;
}
void MzTab::setEmptyRows(const std::vector<Size>& empty)
{
empty_rows_ = empty;
}
const std::vector<Size>& MzTab::getEmptyRows() const
{
return empty_rows_;
}
const std::map<Size, String>& MzTab::getCommentRows() const
{
return comment_rows_;
}
const MzTabSmallMoleculeSectionRows& MzTab::getSmallMoleculeSectionRows() const
{
return small_molecule_data_;
}
void MzTab::setSmallMoleculeSectionRows(const MzTabSmallMoleculeSectionRows& smsd)
{
small_molecule_data_ = smsd;
}
std::vector<String> MzTab::getProteinOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!protein_data_.empty())
{
for (MzTabProteinSectionRows::const_iterator it = protein_data_.begin(); it != protein_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
std::vector<String> MzTab::getPeptideOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!peptide_data_.empty())
{
for (MzTabPeptideSectionRows::const_iterator it = peptide_data_.begin(); it != peptide_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
std::vector<String> MzTab::getPSMOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!psm_data_.empty())
{
for (MzTabPSMSectionRows::const_iterator it = psm_data_.begin(); it != psm_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
std::vector<String> MzTab::getSmallMoleculeOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!small_molecule_data_.empty())
{
for (MzTabSmallMoleculeSectionRows::const_iterator it = small_molecule_data_.begin(); it != small_molecule_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
MzTabParameter::MzTabParameter()
: CV_label_(""),
accession_(""),
name_(""),
value_("")
{
}
MzTabParameter::~MzTabParameter()
{
}
bool MzTabParameter::isNull() const
{
return CV_label_.empty() && accession_.empty() && name_.empty() && value_.empty();
}
void MzTabParameter::setNull(bool b)
{
if (b)
{
CV_label_.clear();
accession_.clear();
name_.clear();
value_.clear();
}
}
void MzTabParameter::setCVLabel(const String& CV_label)
{
CV_label_ = CV_label;
}
void MzTabParameter::setAccession(const String& accession)
{
accession_ = accession;
}
void MzTabParameter::setName(const String& name)
{
name_ = name;
}
void MzTabParameter::setValue(const String& value)
{
value_ = value;
}
String MzTabParameter::getCVLabel() const
{
assert(!isNull());
return CV_label_;
}
String MzTabParameter::getAccession() const
{
assert(!isNull());
return accession_;
}
String MzTabParameter::getName() const
{
assert(!isNull());
return name_;
}
String MzTabParameter::getValue() const
{
assert(!isNull());
return value_;
}
String MzTabParameter::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret = "[";
ret += CV_label_ + ", ";
ret += accession_ + ", ";
if (name_.hasSubstring(", "))
{
ret += String("\"") + name_ + String("\""); // quote name if it contains a ","
}
else
{
ret += name_;
}
ret += String(", ");
if (value_.hasSubstring(", "))
{
ret += String("\"") + value_ + String("\""); // quote value if it contains a ","
}
else
{
ret += value_;
}
ret += "]";
return ret;
}
}
void MzTabParameter::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
StringList fields;
String field;
bool in_quotes = false;
for (String::const_iterator sit = s.begin(); sit != s.end(); ++sit)
{
if (*sit == '\"') // start or end of quotes
{
in_quotes = !in_quotes;
}
else if (*sit == ',') // , encountered
{
if (in_quotes) // case 1: , in quote
{
field += ','; // add , (no split)
}
else // split at , if not in quotes
{
fields.push_back(field.trim());
field.clear();
}
}
else if (*sit != '[' && *sit != ']')
{
// skip leading ws
if (*sit == ' ' && field.empty())
{
continue;
}
field += *sit;
}
}
fields.push_back(field.trim());
if (fields.size() != 4)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert String '") + s + "' to MzTabParameter");
}
CV_label_ = fields[0];
accession_ = fields[1];
name_ = fields[2];
value_ = fields[3];
}
}
MzTabString::MzTabString(const String& s)
{
set(s);
}
MzTabString::~MzTabString()
{
}
void MzTabString::set(const String& value)
{
String lower = value;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
value_ = value;
value_.trim();
}
}
String MzTabString::get() const
{
return value_;
}
bool MzTabString::isNull() const
{
return value_.empty();
}
void MzTabString::setNull(bool b)
{
if (b)
{
value_.clear();
}
}
MzTabString::MzTabString()
: value_()
{
}
String MzTabString::toCellString() const
{
if (isNull())
{
return String("null");
}
else
{
return value_;
}
}
void MzTabString::fromCellString(const String& s)
{
set(s);
}
MzTabBoolean::MzTabBoolean(bool v)
{
set(v);
}
MzTabBoolean::~MzTabBoolean()
{
}
MzTabBoolean::MzTabBoolean()
: value_(false)
{
}
void MzTabBoolean::set(const bool& value)
{
setNull(false);
value_ = value;
}
Int MzTabBoolean::get() const
{
return value_;
}
String MzTabBoolean::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
if (value_)
{
return "1";
}
else
{
return "0";
}
}
}
void MzTabBoolean::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
if (s == "0")
{
set(false);
}
else if (s == "1")
{
set(true);
}
else
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert String '") + s + "' to MzTabBoolean");
}
}
}
MzTabIntegerList::MzTabIntegerList()
{
}
bool MzTabIntegerList::isNull() const
{
return entries_.empty();
}
void MzTabIntegerList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabIntegerList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabInteger>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += ",";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabIntegerList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabInteger ds;
ds.fromCellString(fields[i]);
entries_.push_back(ds);
}
}
}
std::vector<MzTabInteger> MzTabIntegerList::get() const
{
return entries_;
}
void MzTabIntegerList::set(const std::vector<MzTabInteger>& entries)
{
entries_ = entries;
}
MzTabInteger::MzTabInteger(const int v)
{
set(v);
}
MzTabInteger::~MzTabInteger()
{
}
MzTabInteger::MzTabInteger()
: value_(0)
{
}
void MzTabInteger::set(const Int& value)
{
state_ = MZTAB_CELLSTATE_DEFAULT;
value_ = value;
}
Int MzTabInteger::get() const
{
if (state_ == MZTAB_CELLSTATE_DEFAULT)
{
return value_;
}
else
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Trying to extract MzTab Integer value from non-integer valued cell. Did you check the cell state before querying the value?"));
}
}
String MzTabInteger::toCellString() const
{
switch (state_)
{
case MZTAB_CELLSTATE_NULL:
return String("null");
case MZTAB_CELLSTATE_NAN:
return String("NaN");
case MZTAB_CELLSTATE_INF:
return String("Inf");
case MZTAB_CELLSTATE_DEFAULT:
default:
return String(value_);
}
}
void MzTabInteger::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else if (lower == "nan")
{
setNaN();
}
else if (lower == "inf")
{
setInf();
}
else // default case
{
set(lower.toInt());
}
}
MzTabNullAbleBase::MzTabNullAbleBase() :
null_(true)
{
}
MzTabNullAbleBase::~MzTabNullAbleBase()
{
}
bool MzTabNullAbleBase::isNull() const
{
return null_;
}
void MzTabNullAbleBase::setNull(bool b)
{
null_ = b;
}
MzTabNullNaNAndInfAbleBase::MzTabNullNaNAndInfAbleBase() :
state_(MZTAB_CELLSTATE_NULL)
{
}
MzTabNullNaNAndInfAbleBase::~MzTabNullNaNAndInfAbleBase()
{
}
bool MzTabNullNaNAndInfAbleBase::isNull() const
{
return state_ == MZTAB_CELLSTATE_NULL;
}
void MzTabNullNaNAndInfAbleBase::setNull(bool b)
{
state_ = b ? MZTAB_CELLSTATE_NULL : MZTAB_CELLSTATE_DEFAULT;
}
bool MzTabNullNaNAndInfAbleBase::isNaN() const
{
return state_ == MZTAB_CELLSTATE_NAN;
}
void MzTabNullNaNAndInfAbleBase::setNaN()
{
state_ = MZTAB_CELLSTATE_NAN;
}
bool MzTabNullNaNAndInfAbleBase::isInf() const
{
return state_ == MZTAB_CELLSTATE_INF;
}
void MzTabNullNaNAndInfAbleBase::setInf()
{
state_ = MZTAB_CELLSTATE_INF;
}
MzTabDouble::MzTabDouble()
: value_(0.0)
{
}
MzTabDouble::MzTabDouble(const double v)
{
set(v);
}
MzTabDouble::~MzTabDouble()
{
}
void MzTabDouble::set(const double& value)
{
state_ = MZTAB_CELLSTATE_DEFAULT;
value_ = value;
}
double MzTabDouble::get() const
{
if (state_ != MZTAB_CELLSTATE_DEFAULT)
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Trying to extract MzTab Double value from non-double valued cell. Did you check the cell state before querying the value?"));
}
return value_;
}
String MzTabDouble::toCellString() const
{
switch (state_)
{
case MZTAB_CELLSTATE_NULL:
return String("null");
case MZTAB_CELLSTATE_NAN:
return String("NaN");
case MZTAB_CELLSTATE_INF:
return String("Inf");
case MZTAB_CELLSTATE_DEFAULT:
default:
return String(value_);
}
}
void MzTabDouble::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else if (lower == "nan")
{
setNaN();
}
else if (lower == "inf")
{
setInf();
}
else // default case
{
set(lower.toDouble());
}
}
MzTabDoubleList::MzTabDoubleList()
{
}
MzTabDoubleList::~MzTabDoubleList()
{
}
bool MzTabDoubleList::isNull() const
{
return entries_.empty();
}
void MzTabDoubleList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabDoubleList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabDouble>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += "|";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabDoubleList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split("|", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabDouble ds;
ds.fromCellString(fields[i]);
entries_.push_back(ds);
}
}
}
std::vector<MzTabDouble> MzTabDoubleList::get() const
{
return entries_;
}
void MzTabDoubleList::set(const std::vector<MzTabDouble>& entries)
{
entries_ = entries;
}
MzTabNullAbleInterface::~MzTabNullAbleInterface()
{
}
MzTabNullNaNAndInfAbleInterface::~MzTabNullNaNAndInfAbleInterface()
{
}
}
|
Monday, October 30, 2006
The gentler sex?
Recently, reader Eriqua left a comment, asking:
"do we have any modern examples of women dictators? I just wonder if the gender gap has been bridged"
This is a fairly good question. The answer is, somewhat surprisingly, not really. Even though it's a man's world, there have certainly been some notable female tyrants, but nearly all of them have been monarchs from centuries past. From Queen Ravanalona I ("The Cruel") of Madagascar to Empress Catherine II of Russia, one would normally find a crown on the head of a woman crushing her people under her heel.
Given the relatively small list of female national leaders, the question remains: where are the dictators? It is curious that for communism's alleged penchant for gender equity, not one of the leaders of the former Soviet Union, nor any of its satellite states, was a woman. Similarly, there were no women among the military brasshats taking power in South America or post-colonial Africa. Lots of superfluous military decorations, yards of shiny patent leather, but no estrogen. Even when Pakistan's Benazir Bhutto took the top job in a nation notorious for its dictatorships, she either failed, or elected not to, follow in the footsteps of some of her infamous contemporaries.
So where has the modern age, so rife with dictators, found a woman's touch? Naturally, there have been a number of dictators whose wives have played a role behind the scenes, but only one of them, Argentina's Eva Perón, took a public role alongside her dictator husband (a role she eventually renounced). One supposes there are other reasons for a lack of women dictators, ranging from the traditional links between military service and dictatorial rule, to the overall lack of women in prominent leadership roles around the world, but even considering the diminished opportunities, few female rulers have sought to rule with an iron fist as male rulers have.
The best I can think of is a woman who, while not a dictator in the strict sense of the word, did at one point exercise dictatorial control over her country: the late Indira Gandhi of India (pictured above, manhandling a hapless koala).
Riding high after crushing Pakistan in the 1971 war of Bangladeshi Independence and India's equally successful entry to the nuclear age, Gandhi was riding high until the country found itself paralyzed by a political crisis in 1975. Without hesitating, Gandhi suspended India's democracy during the (now infamous) "emergency period", during which time, she adopted dictatorial powers, including the all important ability to rule by decree.
During the two year emergency period, Gandhi rode roughshod over her political enemies, sending tens of thousands of political opponents to jail on specious charges, imposed strict press censorship, dismissing state officials perceived to be hostile to her rule, while simultaneously grooming her sons Sanjay and Rajiv for a more political role.
Gandhi's confidence proved to be her undoing. Believing the economic progress made during the emergency period added to her political prestige, she called for new elections in 1977, and was soundly trounced by the opposing BJP party. She removed herself from office without a struggle, thus ending the brief and only dictatorship by a woman in the last century. Indira returned to power again, with disastrous results, before being assassinated by her Sikh bodyguards in 1984.
Wednesday, October 25, 2006
Top 10 Profile: Saparmurat Niazov
Name: Saparmurat Atayevich Niazov
Born: Aşgabat, TSSR (USSR) February 19, 1940
Length of rule: June 21, 1991 - present (15 years)
Means of ascent to power: Elected
Style: Cult of personality
Quick: what the first thing you think of when you hear the word "Turkmenistan"? For most Americans, the answer would be "What-where-i-stan?". For people fascinated by dictators, however, the sleepy Central Asian republic is white hot, thanks to its viciously ruthless yet lovably eccentric tyrant, Saparmurat "Turkmenbashi" Niazov. With rumors of his imminent demise coming from all angles, it behooves me to provide a quick outline of one of the strangest dictators of the past century.
After the catastrophic dissolution of the Soviet Union, the backwater chunk of Central Asia formerly known as the Turkmen Soviet Socialist Republic found itself, for better or worse, an indepent nation. Politics, like nature, abhors a vacuum, but nobody really took much notice when the leader of the Turkmen Communist Party, an undistinguished hack named Saparmurat Niazov, won newly independent Turkmenistan's first, and last, presidential election in 1992.
Taking a cue from Kemal Atatürk, Niazov found the role of "president" a bit too limiting, preferring shrewdly to announce that he had become the very personification, and even the very essence of the Turkmen people themselves. Very soon, Saparmurat Niazov, the colorless Soviet apparatchik, restyled himself as the dynamic Turkmenbashi, meaning, "leader of all Turkmen".
Taking a cue from Josef Stalin, Niazov isolated his nation from the rest of the world and began building a formidable personality cult. In case anyone might think he's a one trick pony, Niazov also borrowed something from Mao Zedong (more specifically, Mao's odious Little Red Book): the Ruhnama.
Written as a national epic in a quasi-religious, quasi-nationalistic style, Niazov's Little Green Book humbly purports to be the equal of lesser known works like the Bible and the Koran. Lest anyone attempt to diminish the importance of his book, Niazov has made study of Ruhnama compulsory. If there is anyone in Turkmenistan seeking employment (in the public or private sector), anyone seeking a driver's license, anyone looking to get married, and so on, he or she had better be able to recite large portions of Ruhnama by heart.
More ominously, failing to praise the book is a crime against the state, to say nothing of the punishments awaiting anyone who might dare to actually criticize the book as the rantings of a senile dictator. Niazov is so enamored of his epic, he's erected statues - even buildings - in its likeness. When prominent Muslims in Turkmenistan complained about being compelled to put his book next to the Koran, Niazov simply had them thrown in jail and ordered their mosques bulldozed. Perhaps these old fashioned Muslims can be appeased by Niazov's entirely straightfaced declaration that anyone who reads Ruhnama three times will "automatically" be admitted to heaven. That sure beats blowing yourself up on a bus in Tel Aviv, doesn't it?
While officially downplaying the extent of his personality cult, Niazov has seen fit to allow several golden statues of his likeness to remain standing, including a marvelous statue that rotates to face the direction of the sun. It is, perhaps, his crushing ubiquity in Turkmenistan that has provided him to pass some of the world's stupidest laws without his people raising an eyebrow in surprise. These laws include, but are by no means limited to:
• Outlawing gold teeth in favor of promoting "chewing bones"
• Banning female newscasters from wearing cosmetics
• Bans on karaoke and car stereos
• Replacing the Hippocratic Oath with an oath of allegience to Niazov
It's not known for sure if Niazov's bizarre presidental decrees are serious, or merely an effort to deflect attention from his country's appalling human rights record and lousy economy. Whatever the case may be, Turkmenistan is unencumbered by serious political opposition to his rule, much less military threats from at home or abroad. As long as he keeps pumping natural gas to Europe, the rest of the world will be content to paint him as the eccentric ruler of a charming backwater, more than happy to ignore the less amusing aspects of his totalitarian rule.
Still, one has to admire Niazov's sense of style, and his eagerness to set himself apart from the other grey stuffed Soviet suits that took over other former Soviet Republics. Ever seen anything about Heider Aliev, Islam Karimov, or Nursultan Nazarbayev in the insufferable "wacky news of the day" section of your local newspaper?
Didn't think so.
Monday, October 23, 2006
The Last King of Scotland
No, not James I, but the late, unlamented Idi Amin Dada of Uganda, is the focus of the new film The Last King of Scotland.
While the movie is clearly fiction, the real life and times of one of Africa's most notorious big men are brought to life in the movie, beginning with the overthrow of Uganda's previous dictator, to the economically disastrous expulsion of Uganda's "Asian" business class, to the militarily diastrous decision to provide assistance to Palestinian hijackers at Entebbe, the film reconstructs the timeline of Amin's bloody tyranny through the eyes of a Scottish doctor who manages to ingratiate himself to Amin.
Amin, of course, was no stranger to film during his lifetime, having appeared as himself in the bizarre documentary Idi Amin Dada, where he plays the accordion, mounts a mock invasion of the Golan Heights, and terrifies his subordinates, all while playing the role of a large, jolly man who feels wounded at being "misunderstood" at being portrayed as a bloodthirsty buffoon an unsympathetic Western press. Amin certainly didn't help his own cause, however, by murdering his political opponents, launching ill advised military actions against Uganda's neighbors. What's more, Amin's penchant for self-aggrandizing made him a popular target for Western reporters looking to portray him as an ignorant lout. Consider his modest, self-described title:
His service in the King's African Rifles notwithstanding, Idi Amin's chances of being awarded the Victoria Cross were roughly equivalent to my chances of being Miss Venezuela. It was Amin's bufoonish side and boyish charm that unnervingly contrasted with his explosive temper, total paranoia and bloodthirsty appetite for revenge, making him equal only to Mobutu Sese Seko as the most notorious of Africa's big men.
So what did I think of the movie? As a dictator-phile, I was pleasantly surprised by Forest Whitaker's portrayal of Amin, delighted that he paid such close attention to Amin's own mannerisms and body language from Idi Amin Dada. I was less enthralled with the Scottish doctor as narrative device, the romantic and espionage subplots, et al., and look forward to the day when Hollywood is ready to tackle the dictator biopic with the seriousness and breadth of vision it deserves.
|
Chinese researchers have turned to the light absorbing properties of butterfly wings to significantly increase the efficiency of solar hydrogen cells, using biomimetics to copy the nanostructure that allows for incredible light and heat absorption.
Butterflies are known to use heat from the sun to warm themselves beyond what their bodies can provide, and this new research takes a page from their evolution to improve hydrogen fuel generation. Analyzing the wings of Papilio helenus, the researchers found scales that are described as having:
[...] Ridges running the length of the scale with very small holes on either side that opened up onto an underlying layer. The steep walls of the ridges help funnel light into the holes. The walls absorb longer wavelengths of light while allowing shorter wavelengths to reach a membrane below the scales. Using the images of the scales, the researchers created computer models to confirm this filtering effect. The nano-hole arrays change from wave guides for short wavelengths to barriers and absorbers for longer wavelengths, which act just like a high-pass filtering layer.
So, what does this have to do with fuel cells? Splitting water into hydrogen and oxygen takes energy, and is a drain on the amount you can get out of a cell. To split the water, the process uses a catalyst, and certain catalysts — say, titanium dioxide — function by exposure to light. The researchers synthesized a titanium dioxide catalyst using the pattern from the butterfly's wings, and paired it with platinum nanoparticles to make it more efficient at splitting water. The result? A 230% uptick in the amount of hydrogen produced. The structure of the butterfly's wing means that it's better at absorbing light — so who knows, you might also see the same technique on solar panels, too.
|
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest.h>
#include <taskflow/taskflow.hpp>
// EmptyFuture
TEST_CASE("EmptyFuture" * doctest::timeout(300)) {
tf::Future<void> fu;
REQUIRE(fu.valid() == false);
REQUIRE(fu.cancel() == false);
}
// Future
TEST_CASE("Future" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
for(int i=0; i<100; i++) {
taskflow.emplace([&](){
counter.fetch_add(1, std::memory_order_relaxed);
});
}
auto fu = executor.run(taskflow);
fu.get();
REQUIRE(counter == 100);
}
// Cancel
TEST_CASE("Cancel" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<10000; i++) {
taskflow.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
// a new round
counter = 0;
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
// a new round
counter = 0;
fu = executor.run_n(taskflow, 100);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
}
// multiple cnacels
TEST_CASE("MultipleCancels" * doctest::timeout(300)) {
tf::Taskflow taskflow1, taskflow2, taskflow3, taskflow4;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<10000; i++) {
taskflow1.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
taskflow2.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
taskflow3.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
taskflow4.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
// a new round
counter = 0;
auto fu1 = executor.run(taskflow1);
auto fu2 = executor.run(taskflow2);
auto fu3 = executor.run(taskflow3);
auto fu4 = executor.run(taskflow4);
REQUIRE(fu1.cancel() == true);
REQUIRE(fu2.cancel() == true);
REQUIRE(fu3.cancel() == true);
REQUIRE(fu4.cancel() == true);
executor.wait_for_all();
REQUIRE(counter < 10000);
REQUIRE(fu1.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
REQUIRE(fu2.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
REQUIRE(fu3.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
REQUIRE(fu4.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
}
// cancel subflow
TEST_CASE("CancelSubflow" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<100; i++) {
taskflow.emplace([&, i](tf::Subflow& sf){
for(int j=0; j<100; j++) {
sf.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
if(i % 2) {
sf.join();
}
else {
sf.detach();
}
});
}
// a new round
counter = 0;
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
// a new round
counter = 0;
auto fu1 = executor.run(taskflow);
auto fu2 = executor.run(taskflow);
auto fu3 = executor.run(taskflow);
REQUIRE(fu1.cancel() == true);
REQUIRE(fu2.cancel() == true);
REQUIRE(fu3.cancel() == true);
fu1.get();
fu2.get();
fu3.get();
REQUIRE(counter < 10000);
}
// cancel asynchronous tasks in subflow
TEST_CASE("CancelSubflowAsyncTasks" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<100; i++) {
taskflow.emplace([&](tf::Subflow& sf){
for(int j=0; j<100; j++) {
auto a = sf.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
auto b = sf.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
a.precede(b);
sf.async([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
sf.silent_async([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
});
}
// a new round
counter = 0;
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
}
// cancel infinite loop
TEST_CASE("CancelInfiniteLoop" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
for(int i=0; i<100; i++) {
auto a = taskflow.emplace([](){});
auto b = taskflow.emplace([](){ return 0; });
a.precede(b);
b.precede(b);
}
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
}
// cancel from another
TEST_CASE("CancelFromAnother" * doctest::timeout(300)) {
tf::Taskflow taskflow, another;
tf::Executor executor(4);
// create a single inifnite loop
auto a = taskflow.emplace([](){});
auto b = taskflow.emplace([](){ return 0; });
a.precede(b);
b.precede(b);
auto fu = executor.run(taskflow);
REQUIRE(fu.wait_for(
std::chrono::milliseconds(100)) == std::future_status::timeout
);
// create a task to cancel another flow
another.emplace([&]() { REQUIRE(fu.cancel() == true); });
executor.run(another).wait();
}
// cancel from async task
TEST_CASE("CancelFromAsync" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
// create a single inifnite loop
auto a = taskflow.emplace([](){});
auto b = taskflow.emplace([&](){ return 0; });
a.precede(b);
b.precede(b);
executor.async([&](){
auto fu = executor.run_n(taskflow, 100);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
REQUIRE(fu.cancel() == true);
});
executor.wait_for_all();
}
// cancel async tasks
TEST_CASE("CancelAsync") {
tf::Executor executor(2);
std::vector<tf::Future<void>> futures;
for(int i=0; i<10000; i++) {
futures.push_back(executor.async([](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}));
}
size_t n_success = 0, n_failure = 0;
for(auto& fu : futures) {
if(fu.cancel() == true) n_success++;
else n_failure++;
}
executor.wait_for_all();
REQUIRE(n_success > n_failure);
for(auto& fu : futures) {
REQUIRE(fu.valid());
CHECK_NOTHROW(fu.get());
}
}
// cancel subflow async tasks
TEST_CASE("CancelSubflowAsync") {
tf::Taskflow taskflow;
tf::Executor executor(2);
std::atomic<bool> futures_ready {false};
std::vector<tf::Future<void>> futures;
taskflow.emplace([&](tf::Subflow& sf){
for(int i=0; i<10000; i++) {
futures.push_back(sf.async([](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}));
}
futures_ready = true;
});
executor.run(taskflow);
while(!futures_ready);
size_t n_success = 0, n_failure = 0;
for(auto& fu : futures) {
if(fu.cancel() == true) n_success++;
else n_failure++;
}
executor.wait_for_all();
REQUIRE(n_success > n_failure);
for(auto& fu : futures) {
REQUIRE(fu.valid());
CHECK_NOTHROW(fu.get());
}
}
// cancel composition tasks
TEST_CASE("CancelComposition") {
tf::Executor executor(4);
// f1 has two independent tasks
tf::Taskflow f1("F1");
auto f1A = f1.emplace([&](){ });
auto f1B = f1.emplace([&](){ });
f1A.name("f1A");
f1B.name("f1B");
// f2A ---
// |----> f2C
// f2B ---
//
// f1_module_task
tf::Taskflow f2("F2");
auto f2A = f2.emplace([&](){ });
auto f2B = f2.emplace([&](){ });
auto f2C = f2.emplace([&](){ });
f2A.name("f2A");
f2B.name("f2B");
f2C.name("f2C");
f2A.precede(f2C);
f2B.precede(f2C);
f2.composed_of(f1).name("module_of_f1");
// f3 has a module task (f2) and a regular task
tf::Taskflow f3("F3");
f3.composed_of(f2).name("module_of_f2");
f3.emplace([](){ }).name("f3A");
// f4: f3_module_task -> f2_module_task
tf::Taskflow f4;
f4.name("F4");
auto f3_module_task = f4.composed_of(f3).name("module_of_f3");
auto f2_module_task = f4.composed_of(f2).name("module_of_f2");
f3_module_task.precede(f2_module_task);
for(int r=0; r<100; r++) {
size_t N = 100;
size_t success = 0;
std::vector<tf::Future<void>> futures;
for(int i=0; i<100; i++) {
futures.emplace_back(executor.run(f4));
}
for(auto& fu: futures) {
success += (fu.cancel() ? 1 : 0);
}
executor.wait_for_all();
REQUIRE(success <= N);
}
}
|
#include <ros/ros.h>
#include <ros/rate.h>
#include <math.h>
#include <geometry_msgs/Pose.h>
#include <sensor_msgs/JointState.h>
#include <std_msgs/Float64.h>
bool received_state = false;
std::vector<double> q0;
void state_callback(const sensor_msgs::JointState& msg)
{
if(received_state) return;
q0.push_back(msg.position.at(0));
q0.push_back(msg.position.at(1));
q0.push_back(msg.position.at(6)); //NOTE: this is because e1 is at the end of the state vector
q0.push_back(msg.position.at(2));
q0.push_back(msg.position.at(3));
q0.push_back(msg.position.at(4));
q0.push_back(msg.position.at(5));
received_state=true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "single_lwr_homing");
ros::NodeHandle n_;
double rateHZ = 100;
std::vector<double> homing, homing_right;
homing.push_back(1.0); //a1
homing.push_back(1.0); //a2
homing.push_back(1.0); //e1
homing.push_back(1.0); //a3
homing.push_back(1.0); //a4
homing.push_back(1.0); //a5
homing.push_back(1.0); //a6
geometry_msgs::Pose command_msg;
ros::Subscriber sub = n_.subscribe("/joint_states",1,&state_callback);
ros::Publisher pub_command_l = n_.advertise<geometry_msgs::Pose>("/kuka_command", 10);
ros::Rate r(rateHZ);
bool active=false;
while(!received_state && ros::ok())
{
r.sleep();
ros::spinOnce();
}
double alpha=0.0;
while(ros::ok())
{
command_msg.position.x = alpha*homing.at(0) + (1-alpha)*q0.at(0);
command_msg.position.y = alpha*homing.at(1) + (1-alpha)*q0.at(1);
command_msg.position.z = alpha*homing.at(2) + (1-alpha)*q0.at(2);
command_msg.orientation.x = alpha*homing.at(3) + (1-alpha)*q0.at(3);
command_msg.orientation.y = alpha*homing.at(4) + (1-alpha)*q0.at(4);
command_msg.orientation.z = alpha*homing.at(5) + (1-alpha)*q0.at(5);
command_msg.orientation.w = alpha*homing.at(6) + (1-alpha)*q0.at(6);
pub_command_l.publish(command_msg);
r.sleep();
ros::spinOnce();
alpha+=0.0025;
if(alpha>1) break;
}
std::cout<<"Homing: DONE"<<std::endl;
return 0;
}
|
#include <cassert>
#include <array>
#include <vector>
#include <limits>
#include "islet_tables.hpp"
#include "islet_util.hpp"
#include "islet_isl.hpp"
#include "islet_xnodes_metrics.hpp"
#include "islet_npx.hpp"
extern "C" {
void dgemm_(const char* transa, const char* transb, const int* m,
const int* n, const int* k, const double* alpha, const double* a,
const int* lda, const double* b, const int* ldb,
const double* beta, double* c, const int* ldc);
void dpotrf_(const char* uplo, const int* n, double* a, const int* lda,
int* info);
void dpotrs_(const char* uplo, const int* n, const int* nrhs, const double* a,
const int* lda, double* b, const int* ldb, int* info);
void dtrsm_(const char* side, const char* uplo, const char* transa, const char* diag,
const int* n, const int* nrhs, const double* alpha, const double* a,
const int* lda, double* b, const int* ldb);
void dtrtrs_(const char* uplo, const char* trans, const char* diag,
const int* n, const int* nrhs, double* a, const int* lda,
double* b, const int* ldb, int* info);
void dgeqrf_(const int* m, const int* n, double* a, const int* lda,
double* tau, double* wrk, int* iwrk, int* info);
void dormqr_(const char* side, const char* trans,
const int* m, const int* n, const int* k,
double* a, const int* lda,
double* tau, double* c, const int* ldc,
double* wrk, const int* iwrk, int* info);
}
namespace islet {
// C = alpha op(A) op(B) + beta C
void dgemm (char transa, char transb, int m, int nrhs, int n, double alpha,
const double* a, int lda, const double* b, int ldb, double beta,
const double* c, int ldc) {
dgemm_(&transa, &transb, &m, &nrhs, &n, &alpha, const_cast<double*>(a), &lda,
const_cast<double*>(b), &ldb, &beta, const_cast<double*>(c), &ldc);
}
int dpotrf (char uplo, int n, double* a, int lda) {
int info;
dpotrf_(&uplo, &n, a, &lda, &info);
return info;
}
int dpotrs (char uplo, int n, int nrhs, const double* a, int lda, double* bx,
int ldb) {
int info;
dpotrs_(&uplo, &n, &nrhs, const_cast<double*>(a), &lda, bx, &ldb, &info);
return info;
}
void dtrsm (char side, char uplo, char transa, char diag, int n, int nrhs,
double alpha, const double* a, int lda, double* bx, int ldb) {
dtrsm_(&side, &uplo, &transa, &diag, &n, &nrhs, &alpha,
const_cast<double*>(a), &lda, bx, &ldb);
}
int dtrtrs (char uplo, char trans, char diag, int n, int nrhs,
double* a, int lda, double* b, int ldb) {
int info;
dtrtrs_(&uplo, &trans, &diag, &n, &nrhs, a, &lda, b, &ldb, &info);
return info;
}
// tau[min(m,n)], wrk[>= n]
int dgeqrf (int m, int n, double* a, int lda,
double* tau, double* wrk, int iwrk) {
int info;
dgeqrf_(&m, &n, a, &lda, tau, wrk, &iwrk, &info);
return info;
}
// tau[min(m,n)], wrk[>= max(m,n)]
int dormqr (char side, char trans, int m, int n, int k, double* a, int lda,
double* tau, double* c, int ldc, double* wrk, int iwrk) {
int info;
dormqr_(&side, &trans, &m, &n, &k, a, &lda, tau, c, &ldc, wrk, &iwrk, &info);
return info;
}
struct GllNatural : public Operator {
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
eval_lagrange_poly(get_xnodes(np), np, x, v);
}
};
struct GllOffsetNodalSubset : public Operator, public npxstab<Real> {
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
npxstab<Real>::eval(np, x, v);
}
};
void eval_offset_nodal_subset (
const Int np, const Int nreg, const Int* subnp, const Int* os, const Real* xnodes,
const Real& x, Real* const v)
{
if (x > 0) {
eval_offset_nodal_subset(np, nreg, subnp, os, xnodes, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
bool done = false;
for (Int i = 0; i < nreg; ++i)
if (x < xnodes[i+1]) {
std::fill(v, v + np, 0);
eval_lagrange_poly(xnodes + os[i], subnp[i], x, v + os[i]);
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(xnodes, np, x, v);
}
static void eval_offset (const Int& np, const Real* const xnodes,
const Int* const subnp, const Int* const offst,
const Real& x, Real* const v) {
if (x > 0) {
eval_offset(np, xnodes, subnp, offst, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
bool done = false;
for (Int i = 0; i < np/2; ++i)
if (x < xnodes[i+1]) {
std::fill(v, v + np, 0);
eval_lagrange_poly(xnodes + offst[i], subnp[i], x, v + offst[i]);
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(xnodes, np, x, v);
}
struct GllBest : public Operator {
static void eval_np4 (const Real* const xnodes, const Real& x, Real* const y) {
static const Real c1 = 0.306;
if (x < xnodes[1] || x > xnodes[2]) {
y[0] = y[3] = 0;
const Int os = x < xnodes[1] ? 0 : 1;
eval_lagrange_poly(xnodes + os, 3, x, y + os);
Real y4[4];
eval_lagrange_poly(xnodes, 4, x, y4);
const Real x0 = 2*(1 - std::abs(x))/(1 - xnodes[2]) - 1;
const Real a = (c1 + (0.5 - c1)*x0)*(x0 + 1);
for (int i = 0; i < 4; ++i)
y[i] = a*y[i] + (1 - a)*y4[i];
} else
eval_lagrange_poly(xnodes, 4, x, y);
}
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
const Real* xnodes = get_xnodes(np);
switch (np) {
case 4: eval_np4(xnodes, x, v); break; // 2
case 5: { // 2
const Int subnp[] = {3,4};
const Int offst[] = {0,0};
eval_offset(5, xnodes, subnp, offst, x, v);
} break;
case 6: { // 4
const Int subnp[] = {5,5,6};
const Int n0[] = { 0, 1, 2, 3, 4, };
const Int n1[] = { 0, 1, 2, 3, 5};
const Int n2[] = { 0, 1, 2, 3, 4, 5};
const Int* nodes[] = {n0,n1,n2};
::eval(6, true, xnodes, subnp, nodes, x, v);
} break;
case 7: { // 4
const Int subnp[] = {5,5,6};
const Int offst[] = {0,0,0};
eval_offset(7, xnodes, subnp, offst, x, v);
} break;
case 8: { // 5
const Int subnp[] = {6,6,7,6};
const Int offst[] = {0,0,0,1};
eval_offset(8, xnodes, subnp, offst, x, v);
} break;
case 9: { // 6
const Int subnp[] = {7,8,8,7};
const Int n0[] = { 0, 1, 2, 3, 4, 5, 8};
const Int n1[] = { 0, 1, 2, 3, 4, 5, 7, 8};
const Int n2[] = { 0, 1, 2, 3, 4, 5, 6, 8};
const Int n3[] = { 1, 2, 3, 4, 5, 6, 7 };
const Int* nodes[] = {n0,n1,n2,n3};
::eval(9, true, xnodes, subnp, nodes, x, v);
} break;
case 10: { // 6
const Int subnp[] = {7,7,7,8,8};
const Int offst[] = {0,0,0,0,1};
eval_offset(10, xnodes, subnp, offst, x, v);
} break;
case 11: { // 7
const Int subnp[] = {8,9,8,9,8};
const Int offst[] = {0,0,0,0,1};
eval_offset(11, xnodes, subnp, offst, x, v);
} break;
case 12: { // 8
const Int subnp[] = {9,9,10,10,9,10};
const Int offst[] = {0,0,0,0,1,1};
eval_offset(12, xnodes, subnp, offst, x, v);
} break;
case 13: { // 9
const Int subnp[] = {10,10,10,10,11,10};
const Int offst[] = {0,0,0,0,0,1};
eval_offset(13, xnodes, subnp, offst, x, v);
} break;
default: throw_if(true, "not impl'ed");
}
}
std::string get_basis_string (const Int& np) const override {
switch (np) {
case 5: return "5 1 | 0 3: 0 1 2 | 1 4: 0 1 2 3";
case 6: return "6 1 | 0 5: 0 1 2 3 4 | 1 5: 0 1 2 3 5 | 2 6: 0 1 2 3 4 5";
case 7: return "7 1 | 0 5: 0 1 2 3 4 | 1 5: 0 1 2 3 4 | 2 6: 0 1 2 3 4 5";
case 8: return "8 1 | 0 6: 0 1 2 3 4 5 | 1 6: 0 1 2 3 4 5 | 2 7: 0 1 2 3 4 5 6 | 3 6: 1 2 3 4 5 6";
case 9: return "9 1 | 0 7: 0 1 2 3 4 5 8 | 1 8: 0 1 2 3 4 5 7 8 | 2 8: 0 1 2 3 4 5 6 8 | 3 7: 1 2 3 4 5 6 7";
case 10: return "10 1 | 0 7: 0 1 2 3 4 5 6 | 1 7: 0 1 2 3 4 5 6 | 2 7: 0 1 2 3 4 5 6 | 3 8: 0 1 2 3 4 5 6 7 | 4 8: 1 2 3 4 5 6 7 8";
case 11: return "11 1 | 0 8: 0 1 2 3 4 5 6 7 | 1 9: 0 1 2 3 4 5 6 7 8 | 2 8: 0 1 2 3 4 5 6 7 | 3 9: 0 1 2 3 4 5 6 7 8 | 4 8: 1 2 3 4 5 6 7 8";
case 12: return "12 1 | 0 9: 0 1 2 3 4 5 6 7 8 | 1 9: 0 1 2 3 4 5 6 7 8 | 2 10: 0 1 2 3 4 5 6 7 8 9 | 3 10: 0 1 2 3 4 5 6 7 8 9 | 4 9: 1 2 3 4 5 6 7 8 9 | 5 10: 1 2 3 4 5 6 7 8 9 10";
case 13: return "13 1 | 0 10: 0 1 2 3 4 5 6 7 8 9 | 1 10: 0 1 2 3 4 5 6 7 8 9 | 2 10: 0 1 2 3 4 5 6 7 8 9 | 3 10: 0 1 2 3 4 5 6 7 8 9 | 4 11: 0 1 2 3 4 5 6 7 8 9 10 | 5 10: 1 2 3 4 5 6 7 8 9 10";
default: return "";
}
}
};
struct UniformOffsetNodalSubset : public Operator {
virtual const Real* get_xnodes (const Int& np) const override {
if (np < 2 || np > np_max+1) return nullptr;
static Real xnode[np_max+1][np_max+1] = {0};
if (xnode[np][0] == 0) {
for (Int i = 0; i < np; ++i)
xnode[np][i] = 2*(Real(i)/(np-1)) - 1;
}
return xnode[np];
}
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
const Real* xnodes = get_xnodes(np);
switch (np) {
case 2: {
const Int subnp[] = {2};
const Int offst[] = {0};
eval_offset(2, xnodes, subnp, offst, x, v);
} break;
case 3: {
const Int subnp[] = {3};
const Int offst[] = {0};
eval_offset(3, xnodes, subnp, offst, x, v);
} break;
case 4: {
const Int subnp[] = {3,4};
const Int offst[] = {0,0};
eval_offset(4, xnodes, subnp, offst, x, v);
} break;
case 5: {
const Int subnp[] = {3,4};
const Int offst[] = {0,0};
eval_offset(5, xnodes, subnp, offst, x, v);
} break;
case 6: {
const Int subnp[] = {3,4,6};
const Int offst[] = {0,0,0};
eval_offset(6, xnodes, subnp, offst, x, v);
} break;
case 7: {
const Int subnp[] = {3,4,4};
const Int offst[] = {0,0,1};
eval_offset(7, xnodes, subnp, offst, x, v);
} break;
case 8: {
const Int subnp[] = {4,4,4,4};
const Int offst[] = {0,0,1,2};
eval_offset(8, xnodes, subnp, offst, x, v);
} break;
case 9: {
const Int subnp[] = {4,4,4,4};
const Int offst[] = {0,0,1,2};
eval_offset(9, xnodes, subnp, offst, x, v);
} break;
case 10: {
const Int subnp[] = {4,4,4,4,4};
const Int offst[] = {0,0,1,2,3};
eval_offset(10, xnodes, subnp, offst, x, v);
} break;
case 11: {
const Int subnp[] = {4,4,4,4,4};
const Int offst[] = {0,0,1,2,3};
eval_offset(11, xnodes, subnp, offst, x, v);
} break;
case 12: {
const Int subnp[] = {4,4,4,4,4,4};
const Int offst[] = {0,0,1,2,3,4};
eval_offset(12, xnodes, subnp, offst, x, v);
} break;
case 13: {
const Int subnp[] = {4,4,4,4,4,4};
const Int offst[] = {0,0,1,2,3,4};
eval_offset(13, xnodes, subnp, offst, x, v);
} break;
default: throw_if(true, "not impl'ed");
}
}
};
Operator::ConstPtr Operator::create (Operator::Method m) {
switch (m) {
case gll_natural: return std::make_shared<GllNatural>();
case gll_offset_nodal_subset: return std::make_shared<GllOffsetNodalSubset>();
case gll_best: return std::make_shared<GllBest>();
case uniform_offset_nodal_subset: return std::make_shared<UniformOffsetNodalSubset>();
default: throw_if(true, "Operator::create: not a method: " << m);
}
return nullptr;
}
Int unittest_eval () {
Int nerr = 0;
{
GllOffsetNodalSubset o1;
GllBest o2;
for (const Int np : {5,7,8,10,11,12,13}) {
const Int n = 100;
Int ne = 0;
for (Int i = 0; i <= n; ++i) {
const Real x = 2*(Real(i)/n) - 1;
Real v1[np_max], v2[np_max];
o1.eval(np, x, v1);
o2.eval(np, x, v2);
for (Int j = 0; j < np; ++j) if (v1[j] != v2[j]) ++ne;
}
if (ne) printf("GllOffsetNodalSubset vs GllBest np %d failed\n", np);
nerr += ne;
}
}
return nerr;
}
} // namespace islet
using namespace islet;
extern "C" { // For python ctypes.
void get_xnodes (const Int method, const Int np, Real* xnodes) {
const auto op = Operator::create(static_cast<Operator::Method>(method));
const auto x = op->get_xnodes(np);
for (Int i = 0; i < np; ++i) xnodes[i] = x[i];
}
void eval_interpolant (const Int method, const Int np, const Int nx,
// y is np x nx, np the fast index.
const Real* const x, Real* const y) {
const auto op = Operator::create(static_cast<Operator::Method>(method));
for (Int ix = 0; ix < nx; ++ix)
op->eval(np, x[ix], y + np*ix);
}
} // extern "C"
|
Early Childhood Education
- The American Academy of Pediatrics is dedicated to the health of all children and committed to
the attainment of optimal physical, mental, and social health
and well-being for all infants, children, adolescents, and
- The Center for Early Childhood
Leadership is dedicated to enhancing the management skills,
professional orientation and leadership capacity of early
- The Child & Family
WebGuide describes and evaluates web sites that contain
research-based information about child development.
- An organization of regional Child
Care Resource and Referral (CCR&R) agencies serving
communities throughout the state of Illinois.
- The Children's Book Council is dedicated to encouraging literacy and the use and enjoyment
of children's books.
- Children's Literature offers information on authors and illustrators, recommended
books by theme, book award winners, etc.
- The Circle of Inclusion web site is for early childhood service providers and families
of young children. This web site offers demonstrations
of and information about the effective practices of inclusive
educational programs for children from birth through age eight.
- Civitas is a national
not-for-profit communication group that works to provide educational
tools to all adults who live and work with young children.
- The CLAS Early Childhood Research
Institute collects and describes early childhood/early
intervention resources that have been developed across the
United States for children with disabilities and their families
and the service providers who work with them. The materials
and resources available on this site reflect the intersection
of culture and language, disabilities and child development.
- The Division of Early Childhood (DEC) of the Council for Exceptional Children (CEC) is a nonprofit
organization advocating for individuals who work with or on
behalf of children with special needs, birth through age eight,
and their families. There is also an Illinois
Subdivision for the Division of Early Childhood (IDEC).
- The Early Childhood
Educators' and Family Web Corner contains articles, teacher
pages, family pages, etc.
- EdWorld.Resources covers a variety of areas of Early Childhood.
- ERIC provides research-based
information and articles in the field of early childhood.
- I Am Your Child is a national public awareness and engagement campaign to
make early childhood development a top priority of our nation.
- The Illinois Department of Children and Family Services web site for
information on day care licensing, etc.
- The Illinois
Department of Human Services Early Intervention site contains
information for parents and service providers, including Child
and Family Connections contacts. .
- The Illinois
Early Learning Web site provides evidence-based, reliable
information for parents, caregivers, and teachers of young
children in the State of Illinois.
- Illinois Head Start Association information.
- Lists of recommended children's books for birth to five and
Early Childhood Block Grant professional development opportunities
are available on the Early Childhood portion of the Illinois
Resource Center's web site.
- The Illinois
Secretary of State's literacy program site includes grant
applications and literacy resources.
- Meld offers education and
support for parents, trains family service providers to apply
best practices in their work with families and publishes a
broad range of resource materials for parents and the people
who work with them.
- The National Association for
the Education of Young Children has for its purpose, “leading
and consolidating the efforts of individuals and groups working
to achieve healthy development and constructive education
for all young children.”
- The National
Clearinghouse on Child Abuse and Neglect is a resource
for professionals and others seeking information on abuse
and neglect and child welfare.
- The National Early
Childhood Technical Assistance Center supports the implementation
of the early childhood provisions of the Individuals with
Disabilities Education Act (IDEA). Their mission is
to strengthen service systems to ensure that children with
disabilities (birth through five) and their families receive
and benefit from high quality, culturally appropriate, and
family-centered supports and services.
- The National Head Start Association is a private not-for-profit membership organization that provides
a national forum for the continued enhancement of Head Start
services for children ages 0 to 5 and their families.
- The National Institute for
Early Education Research supports early childhood education
initiatives by providing objective, nonpartisan information
based on research.
- Ongoing update about the National
Institute of Child Health and Human Development (NICHID)
study of Early Child Care and Youth Development.
- The Ounce of Prevention was established to promote the well-being of children and
adolescents by working with families, communities, and policy-makers.
- The Parents as Teachers National
Center is committed to seeing that “all children will
learn, grow, and develop to realize their full potential."
The information is geared to parents but helpful to all programs
in early childhood.
- The Partnership
for Reading continually creates resources and shares information
about how scientifically based research can inform the acquisition
of reading skills across the lifespan, from birth to adulthood.
Visit the Early
- Prevent Child
Abuse America provides leadership to promote the prevention
of child abuse and neglect at both the national and local
levels. Information is also available in Spanish.
- Reading Rockets,
"launching young readers", contains resources, book
lists, and tips on early reading.
- The Society for Research in
Child Development at the University of Michigan is a multidisciplinary,
not-for-profit, professional association of approximately
5,000 researchers, practitioners, and human development professionals.
- The U.S.
Department of Education's Early Reading First site contains
information on the status of Early Reading First grants.
- The U.S. Department
of Education main site includes information on No Child
- Voices for Illinois
Children works with families, communities, and policy-makers
to ensure that all children grow up healthy, nurtured, safe,
and well educated.
- Zero to Three is
a leading resource on the first three years of life.
Its goal is to strengthen and support families, practitioners
and communities to promote the healthy development of babies
|
World’s poorest on front line in climate change fight
24 July 2008 | News story
Climate change is already happening – and it hits poor people most. The effect of more frequent hurricanes, floods and droughts on developing countries is devastating, as this year’s cyclone Nagris proved again in southern Myanmar, leaving over 130,000 people dead or missing.
To protect the world’s poor against today’s more frequent extreme weather events, some US$ 2 billion is required according to the Internacional relief agency Oxfam. However, commitments so far only total US$173.
The need for innovative means to mitigate climate change impacts and help poor countries adapt is high on the agenda of the World Conservation Congress, held by IUCN, the International Union for Conservation of Nature from 5-14 October in Barcelona.
- In 2007, there were 950 natural catastrophes in 2007 compared with 850 in 2006, according to Munich Re, one of the world’s largest insurance companies. This is the highest number recorded since the company started compiling annual disaster reports in 1974.
- The burden of the disasters fall on the poor who are least to blame for climate change. Benin, and Bangladesh, for example, are at particularly high risk from rising sea-levels and storm surges, yet their per capita contribution to greenhouse gas output is one eightieth that of the United States, according to the British Institute of Development Studies.
- “What worries us the most is the impact on the poorest countries which have the least capacity to respond to the challenge,” said Yvo de Boer, secretary of the Convention on Climate Change.
- A healthy environment can help people survive. Healthy mangrove forests and coral reefs, for example, can serve as barriers and prevent coastal erosion; a solid forest cover prevents flooding in times of heavy rainfall.
- “There are positive examples of local level adaptation to the impacts of climate change, such as replanting mangrove forests that can serve as buffers against more frequent storms. But to implement these solutions on a larger scale, substantial financial support is required,” says Ninni Ikkala, Climate Change Officer at IUCN.
Upcoming media products:
6 August – International Press Release – Primates Red List update
12 August – International Press Release – Cetacean Red List update
Julia Marton-Lefèvre, IUCN’s Director General.
Ninni Ikkala, IUCN Climate Change Programme
Brian Thomson, IUCN Global Communications, m +417972182326, e [email protected].
Carolin Wahnbaeck, IUCN Global Communications, m +41 79 85 87 593, e [email protected]
World Conservation Congress, Barcelona (5-14 October)
The World Conservation Congress (WCC) brings together 8,000 leaders from the public sector, government, business and non-governmental organizations for what is the premier summit on sustainable development in 2008. Over ten days they debate the best ways to tackle environmental and development challenges. They share pragmatic solutions to pressing issues. And they commit to collaborative action.
|
//---------------------------------------------------------------------------
#ifndef FormMainH
#define FormMainH
//---------------------------------------------------------------------------
#include <FMX.ActnList.hpp>
#include <FMX.Controls.hpp>
#include <FMX.Controls.Presentation.hpp>
#include <FMX.Edit.hpp>
#include <FMX.Layouts.hpp>
#include <FMX.ListBox.hpp>
#include <FMX.Menus.hpp>
#include <FMX.Objects.hpp>
#include <FMX.StdCtrls.hpp>
#include <FMX.Types.hpp>
#include <System.Actions.hpp>
#include <System.Classes.hpp>
#include "FMXFormAppMain.h"
#include <vector>
#include "FormPanel.h"
//---------------------------------------------------------------------------
class TfrmMain : public TfrmPanelAppMain
{
__published: // IDE-managed Components
TTimer *tmrPolling;
TMenuItem *MenuItem1;
TMenuItem *MenuItem2;
TMenuItem *MenuItem3;
TMenuItem *MenuItem4;
TMenuItem *MenuItem5;
TMenuItem *MenuItem6;
TMenuItem *MenuItem7;
TMenuItem *MenuItem9;
TMenuItem *MenuItem10;
TMenuItem *MenuItem11;
TMenuItem *MenuItem12;
TMenuItem *MenuItem13;
TMenuItem *MenuItem16;
TMenuItem *MenuItem17;
TMenuItem *MenuItem18;
TMenuItem *MenuItem19;
TMenuItem *MenuItem34;
TLine *Line1;
TGridLayout *GridLayout1;
TAction *actPanelClear;
TButton *Button4;
TMenuBar *MenuBar1;
void __fastcall FormCloseQuery(TObject *Sender, bool &CanClose);
void __fastcall actPanelClearExecute(TObject *Sender);
void __fastcall actPanelClearUpdate(TObject *Sender);
private: // User declarations
using PanelType = TfrmPanel;
std::unique_ptr<TfrmPanel> panel_;
std::vector<std::unique_ptr<TButton>> btns_;
void BuildButtons();
void DestroyButtons();
void CreatePanel( FMXWinDisplayDev const * Display, bool Clipping,
bool Scaling, bool KeepAspectRatio );
void DestroyPanel();
void __fastcall NumButtonClick( TObject *Sender );
void __fastcall NumberChanged( TObject* Sender, int Num, bool Val );
protected:
virtual void RestoreProperties();
virtual void SaveProperties() const;
virtual void Start();
virtual void Stop();
virtual TfrmPanelBase* GetPanel() { return panel_.get(); }
virtual void Config();
public: // User declarations
using inherited = TfrmPanelAppMain;
__fastcall TfrmMain(TComponent* Owner);
__fastcall ~TfrmMain();
};
//---------------------------------------------------------------------------
extern PACKAGE TfrmMain *frmMain;
//---------------------------------------------------------------------------
#endif
|
#pragma once
#ifndef _SNAKE_H
#define _SNAKE_H
#include <vector>
#include "Texture.h"
#include "Globals.h"
#include "Timer.h"
#include "SnakePart.h"
class Snake {
public:
// Initialize snake
Snake();
// Deallocate memory
~Snake();
// Handle key presses
void handleEvent(const SDL_Event &e);
// Load texture
void loadHeadTexture(std::string path, SDL_Renderer *renderer);
void loadBodyTexture(std::string path, SDL_Renderer *renderer);
// Render snake
void render(SDL_Renderer *renderer) const;
// Move snake
bool move();
// Spawn head
void spawn(Loc spawnLoc);
// Snake's growth
void growth();
// Get entities
std::vector<SnakePart *> &getEntities();
private:
// Snake textures
Texture m_headTexture;
Texture m_bodyTexture;
// Snake parts
std::vector<SnakePart *> m_parts;
// Movement timer
Timer m_timer;
// Size of snake
int m_size;
};
#endif // !_SNAKE_H
|
Fixed Orthodontics
What are invisible braces?
In the event that you experience smile outlining utilizing Clear Path you can accomplish the smile you've generally needed. Smile design is an energizing new thought in dental treatment that we offer our patients. Whether you have screwy, chipped, split, stained, or misaligned teeth, our smile designing service will give you a chance to select your new smile.
Smile designing procedures are paramount for smiles that are defective, unappealing or ugly. The defects may lie in the color or state of the teeth. Smile outlining methods blanket a wide territory of treatment strategies running from essential nonessential dentistry techniques to profoundly intricate surgeries on the facial skeleton to redress jaw deformations. In the event that you search for a complete smile designing service our accomplished restorative dental practitioners are excited to offer assistance!
What are lingual braces?
Lingual braces are specially crafted fixed braces fortified to the once again of the teeth making them invisible to other peoples. In lingual braces the brackets are established onto the posterior of the teeth making them undetectable while in standard props the sections are solidified onto the front side of the teeth. Thus, lingual braces are a nonessential option to the individuals who don't wish the props to be noticeable.
What is fixed orthodontics?
Dental braces are gadgets utilized within orthodontics that adjust and straighten teeth and help to position them with respect to an individual's chomp, while likewise attempting to enhance dental wellbeing. They are frequently used to revise underbites, and malocclusions, overbites, cross nibbles, open chomps, profound nibbles, warped teeth, and different defects of the teeth and jaw. Props might be either nonessential or structural. Dental props are frequently utilized within conjunction with other orthodontic machines to help broaden the sense of taste or jaws and to generally support in forming the teeth and jaws.
Patients Photo
• Patient 1
|
#ifndef __FK_MODEL_HEADER__
#define __FK_MODEL_HEADER__
#ifndef FK_OLD_NONSUPPORT
//#define FK_OLD_NONSUPPORT
#endif
#include <FK/Boundary.h>
#include <FK/Palette.h>
#include <FK/RenderState.h>
#include <FK/Angle.h>
#include <FK/IndexFace.h>
#include <FK/Texture.h>
#include <FK/Tree.h>
#include <memory>
#include <functional>
namespace FK {
class fk_Material;
class fk_Shape;
class fk_TreeData;
class fk_Color;
class fk_ShaderBinder;
using fk_funcSet = std::tuple<unsigned int, std::function<void(void)> >;
//! 描画優先モードを表す列挙型
enum class fk_ElementMode {
NONE, //!< 描画しない
MODEL, //!< モデル設定優先
ELEMENT //!< 形状個別要素設定優先
};
//! シェーディングモードを表す列挙型
enum class fk_ShadingMode {
GOURAUD = 0, //!< グーローシェーディング
PHONG, //!< フォンシェーディング
NUM //!< シェーディングモード種類数
};
//! モデルを生成、管理するクラス
/*!
* このクラスは、「モデル」を制御する機能を提供します。
* FK における「モデル」とは、位置や方向を持ったオブジェクトのことを指します。
* 利用者は、
* このクラスを通じてカメラを含むオブジェクトの位置や姿勢を制御していきます。
* 従って、このクラスは FK システムにおいて最も中心的な存在であると言えます。
* 位置や姿勢を制御するための関数の多くは、
* fk_MatrixAdmin クラスから継承しています。
* (ただし、後述する「親子関係」に関連する機能は本クラス自体が持っています。)
* fk_MatrixAdmin クラスの説明も合わせて参照して下さい。
*
* FK において、モデルと形状は別の存在として扱います。
* 形状は別のクラスで作成しておき、
* モデルに対して形状をリンクするという考え方です。
* このような設計になっている利点は、
* まず第1に1つのモデルが複数の形状を使い分けられるということがあります。
* 第2に、1つの形状を複数のモデルで共有することでメモリ利用量を削減できます。
* 形状については fk_Shape クラスおよびその派生クラスを参照して下さい。
*
* 位置や姿勢の制御と共に、このクラスの重要な機能の1つが「親子関係」です。
* あるモデルを別のモデルに「子モデル」として登録したとします。
* 親モデルの位置や姿勢を制御すると、
* 子モデルの形状は親モデル内の形状と同じように追従するようになります。
* 例えば、車を車体モデルとタイヤモデルで別々に作成し、
* タイヤモデルを車体モデルの子モデルとして登録しておけば、
* 車体モデルの位置移動にあわせてタイヤモデルも位置関係を維持しながら
* 一緒に移動します。
* マテリアルや頂点色、稜線色については、
* 何も設定しない場合は親モデルの設定が用いられます。
* それぞれのモデルにマテリアルや色属性を設定した場合、
* そのモデルについては個々の設定が利用されるようになります。
*
* また、モデル同士の干渉判定や衝突判定を検出することができます。
* 干渉・衝突判定を行うには、
* まず「境界ボリューム」と呼ばれるモデルを覆う領域を設定します。
* その後、その境界ボリューム同士が干渉部分や衝突時間の検出を行うことで実現します。
* 本マニュアルにおいて、「干渉判定」と「衝突判定」は以下のような意味を持ちます。
* - 干渉判定: \n
* ある時点において、モデル同士に干渉部分があるかどうかを判定すること。
* - 衝突判定: \n
* 2つのモデルが時刻 t0 から t1 まで等速度直線運動をしていたと仮定した場合に、
* 途中で衝突が起こったかどうかを判定すること。
*
* 本クラスのメンバ関数では、以下のような機能を提供します。
* - setShape() にて形状を設定した後に自動的に境界ボリュームのサイズを設定する機能。
* - 干渉判定や衝突判定を行う機能。
* - 登録しておいたモデルと干渉した場合に自動的に停止する機能。
*
* 干渉判定は現在すべての種類の境界ボリュームで対応していますが、
* 同じ種類同士である必要があります。
* 衝突判定については、現在は境界球のみで対応しています。
* 境界ボリュームの種類に関する解説や、適用する境界ボリュームの選択については
* fk_Boundary クラスのリファレンスを参照して下さい。
*
* \sa fk_MatrixAdmin, fk_Boundary, fk_Shape, fk_Scene, fk_DisplayLink
*/
class fk_Model : public fk_Boundary {
#ifndef FK_DOXYGEN_USER_PROCESS
class Member {
public:
fk_Material material;
fk_Color pointColor;
fk_Color lineColor;
fk_Color curveColor;
fk_Shape *shape;
fk_Model *parentModel;
fk_TreeData *treeData;
fk_Draw drawMode;
fk_ElementMode elemMode;
fk_BlendMode blendMode;
fk_BlendFactor srcFactor;
fk_BlendFactor dstFactor;
fk_DepthMode depthMode;
double pointSize;
bool smoothFlag;
bool reverseFlag;
bool treeFlag;
unsigned int modelID;
bool treeDelMode;
fk_TexMode texMode;
fk_ShadingMode shadingMode;
std::unique_ptr<fk_HVector> snapPos;
std::unique_ptr<fk_HVector> snapInhPos;
std::unique_ptr<fk_Angle> snapAngle;
bool snapFlag;
bool interMode;
bool interStatus;
bool interStopMode;
std::list<fk_Model *> interList;
fk_ShaderBinder *shader;
bool shadowEffectMode;
bool shadowDrawMode;
bool fogMode;
Member(void);
};
#endif
public:
//! コンストラクタ
/*!
* \param[in] shape
* 形状インスタンスのポインタ。
* nullptr を代入した場合や引数を省略した場合は、
* 初期形状が無い状態になります。
*/
fk_Model(fk_Shape *shape = nullptr);
//! デストラクタ
virtual ~fk_Model();
//! ID参照関数
/*!
* モデルの固有IDを取得します。
* IDの最小値は 1 で、
* 同一プロセス中では同じ ID が別のモデルに割り振られることはありません。
*
* \return 固有モデルID
*/
unsigned int getID(void) const;
//! \name 回転制御関数
///@{
//! グローバル座標系座標軸回転関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、origin を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin
* グローバル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta
* 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Axis, double),
* loRotate(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Axis, double)
*/
bool glRotate(fk_Vector origin, fk_Axis axis, double theta);
//! グローバル座標系座標軸回転関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(orgX, orgY, orgZ) を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotate_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX グローバル座標系での回転軸上の点のx成分
* \param[in] orgY グローバル座標系での回転軸上の点のy成分
* \param[in] orgZ グローバル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotateWithVec(double, double, double, fk_Axis, double),
* loRotate(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::glRotate_(double, double, double, fk_Axis, double)
*/
bool glRotate(double orgX, double orgY, double orgZ, fk_Axis axis, double theta);
//! グローバル座標系任意軸回転関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A 回転軸上の1点。B と一致してはいけません。
* \param[in] B 回転軸上の1点。A と一致してはいけません。
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Vector, double),
* loRotate(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::glRotate_(fk_Vector &, fk_Vector &, double)
*/
bool glRotate(fk_Vector A, fk_Vector B, double theta);
//! グローバル座標系任意軸回転関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は glRotateWithVec() を利用して下さい。
* ローカル座標系で回転移動を行いたい場合は loRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotate_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax 回転軸上の1点 A の x 成分
* \param[in] Ay 回転軸上の1点 A の y 成分
* \param[in] Az 回転軸上の1点 A の z 成分
* \param[in] Bx 回転軸上の1点 B の x 成分
* \param[in] By 回転軸上の1点 B の y 成分
* \param[in] Bz 回転軸上の1点 B の z 成分
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(double, double, double, double, double, double, double),
* loRotate(double, double, double, double, double, double, double),
* fk_MatrixAdmin::glRotate_(double, double, double, double, double, double, double)
*/
bool glRotate(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
//! ローカル座標系座標軸回転関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) origin を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin
* ローカル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta
* 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(fk_Vector, fk_Axis, double),
* loRotateWithVec(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Axis, double)
*/
bool loRotate(fk_Vector origin, fk_Axis axis, double theta);
//! ローカル座標系座標軸回転関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) (orgX, orgY, orgZ) を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX ローカル座標系での回転軸上の点のx成分
* \param[in] orgY ローカル座標系での回転軸上の点のy成分
* \param[in] orgZ ローカル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(double, double, double, fk_Axis, double),
* loRotateWithVec(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::loRotate_(double, double, double, fk_Axis, double)
*/
bool loRotate(double orgX, double orgY, double orgZ, fk_Axis axis, double theta);
//! ローカル座標系任意軸回転関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における) A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A
* ローカル座標系における回転軸上の1点。B と一致してはいけません。
*
* \param[in] B
* ローカル座標系における回転軸上の1点。A と一致してはいけません。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Vector, double),
* loRotate(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::loRotate_(fk_Vector &, fk_Vector &, double)
*/
bool loRotate(fk_Vector A, fk_Vector B, double theta);
//! ローカル座標系任意軸回転関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における)
* (Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は位置のみを回転させるもので、姿勢は回転しません。
* 姿勢の回転も伴いたい場合は loRotateWithVec() を利用して下さい。
* グローバル座標系で回転移動を行いたい場合は glRotate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotate_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax
* ローカル座標系における回転軸上の1点 A の x 成分
*
* \param[in] Ay
* ローカル座標系における回転軸上の1点 A の y 成分
*
* \param[in] Az
* ローカル座標系における回転軸上の1点 A の z 成分
*
* \param[in] Bx
* ローカル座標系における回転軸上の1点 B の x 成分
*
* \param[in] By
* ローカル座標系における回転軸上の1点 B の y 成分
*
* \param[in] Bz
* ローカル座標系における回転軸上の1点 B の z 成分
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(double, double, double, double, double, double, double),
* loRotate(double, double, double, double, double, double, double),
* fk_MatrixAdmin::loRotate_(double, double, double, double, double, double, double)
*/
bool loRotate(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
//! グローバル座標系座標軸回転(姿勢付き)関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、origin を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin グローバル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(fk_Vector, fk_Axis, double),
* loRotateWithVec(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Axis, double)
*/
bool glRotateWithVec(fk_Vector origin, fk_Axis axis, double theta);
//! グローバル座標系座標軸回転(姿勢付き)関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(orgX, orgY, orgZ) を通り、
* axis で指定した座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX グローバル座標系での回転軸上の点のx成分
* \param[in] orgY グローバル座標系での回転軸上の点のy成分
* \param[in] orgZ グローバル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行な軸。fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa glRotate(double, double, double, fk_Axis, double),
* loRotateWithVec(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, fk_Axis, double)
*/
bool glRotateWithVec(double orgX, double orgY, double orgZ,
fk_Axis axis, double theta);
//! グローバル座標系任意軸回転(姿勢付き)関数1
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A 回転軸上の1点。B と一致してはいけません。
* \param[in] B 回転軸上の1点。A と一致してはいけません。
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotate(fk_Vector, fk_Vector, double),
* loRotateWithVec(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::glRotateWithVec_(fk_Vector &, fk_Vector &, double)
*/
bool glRotateWithVec(fk_Vector A, fk_Vector B, double theta);
//! グローバル座標系任意軸回転(姿勢付き)関数2
/*!
* モデルの位置を、グローバル座標系によって回転した場所に移動します。
* 回転軸は、(Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は glRotate() を利用して下さい。
* ローカル座標系で回転移動(姿勢付き)を行いたい場合は、
* loRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、同機能を持つ
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax 回転軸上の1点 A の x 成分
* \param[in] Ay 回転軸上の1点 A の y 成分
* \param[in] Az 回転軸上の1点 A の z 成分
* \param[in] Bx 回転軸上の1点 B の x 成分
* \param[in] By 回転軸上の1点 B の y 成分
* \param[in] Bz 回転軸上の1点 B の z 成分
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotate(double, double, double, double, double, double, double),
* loRotateWithVec(double, double, double, double, double, double, double),
* fk_MatrixAdmin::glRotateWithVec_(double, double, double, double, double, double, double)
*/
bool glRotateWithVec(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
//! ローカル座標系座標軸回転(姿勢付き)関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) origin を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] origin ローカル座標系での回転軸上の点
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa loRotate(fk_Vector, fk_Axis, double),
* glRotateWithVec(fk_Vector, fk_Axis, double),
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Axis, double)
*/
bool loRotateWithVec(fk_Vector origin, fk_Axis axis, double theta);
//! ローカル座標系座標軸回転(姿勢付き)関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は(ローカル座標系における) (orgX, orgY, orgZ) を通り、
* axis で指定した (ローカル座標系における) 座標軸に平行な直線となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, fk_Axis, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] orgX ローカル座標系での回転軸上の点のx成分
* \param[in] orgY ローカル座標系での回転軸上の点のy成分
* \param[in] orgZ ローカル座標系での回転軸上の点のz成分
*
* \param[in] axis
* 回転軸に平行なローカル座標系上の軸。
* fk_X, fk_Y, fk_Z のいずれかになります。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return この関数は常に true を返します。
*
* \sa loRotate(double, double, double, fk_Axis, double),
* glRotateWithVec(double, double, double, fk_Axis, double),
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, fk_Axis, double)
*/
bool loRotateWithVec(double orgX, double orgY, double orgZ,
fk_Axis axis, double theta);
//! ローカル座標系任意軸回転(姿勢付き)関数1
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における) A と B を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Vector &, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] A
* ローカル座標系における回転軸上の1点。B と一致してはいけません。
*
* \param[in] B
* ローカル座標系における回転軸上の1点。A と一致してはいけません。
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(fk_Vector, fk_Vector, double)
* loRotate(fk_Vector, fk_Vector, double),
* fk_MatrixAdmin::loRotateWithVec_(fk_Vector &, fk_Vector &, double)
*/
bool loRotateWithVec(fk_Vector A, fk_Vector B, double theta);
//! ローカル座標系任意軸回転(姿勢付き)関数2
/*!
* モデルの位置を、ローカル座標系によって回転した場所に移動します。
* 回転軸は、(ローカル座標系における)
* (Ax, Ay, Az) と (Bx, By, Bz) を通る軸となります。
* 回転角度は theta となります。単位は弧度法(ラジアン)です。
*
* この関数は、回転の際に姿勢も回転していきます。
* 位置のみの回転を行いたい場合は loRotate() を利用して下さい。
* グローバル座標系で回転移動(姿勢付き)を行いたい場合は、
* glRotateWithVec() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、同機能を持つ
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, double, double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] Ax
* ローカル座標系における回転軸上の1点 A の x 成分
*
* \param[in] Ay
* ローカル座標系における回転軸上の1点 A の y 成分
*
* \param[in] Az
* ローカル座標系における回転軸上の1点 A の z 成分
*
* \param[in] Bx
* ローカル座標系における回転軸上の1点 B の x 成分
*
* \param[in] By
* ローカル座標系における回転軸上の1点 B の y 成分
*
* \param[in] Bz
* ローカル座標系における回転軸上の1点 B の z 成分
*
* \param[in] theta 回転角度(ラジアン)
*
* \return
* 回転が成功した場合 true を返します。
* A と B が同一位置ベクトルであった場合、
* 回転せずに false を返します。
*
* \sa glRotateWithVec(double, double, double, double, double, double, double),
* loRotate(double, double, double, double, double, double, double),
* fk_MatrixAdmin::loRotateWithVec_(double, double, double, double, double, double, double)
*/
bool loRotateWithVec(double Ax, double Ay, double Az,
double Bx, double By, double Bz, double theta);
///@}
//! \name 位置制御関数
///@{
//! グローバル座標系平行移動関数1
/*!
* モデルを、クローバル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルで指定します。
*
* ローカル座標系による平行移動量の指定を行いたい場合は、
* loTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glTranslate_(fk_Vector &)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] v 平行移動量ベクトル
*
* \return この関数は常に true を返します。
*
* \sa loTranslate(fk_Vector), fk_MatrixAdmin::glTranslate_(fk_Vector &)
*/
bool glTranslate(fk_Vector v);
//! グローバル座標系平行移動関数2
/*!
* モデルを、クローバル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルの成分を意味する3個の実数で指定します。
*
* ローカル座標系による平行移動量の指定を行いたい場合は、
* loTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glTranslate_(double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] x 平行移動量ベクトルのx成分
* \param[in] y 平行移動量ベクトルのy成分
* \param[in] z 平行移動量ベクトルのz成分
*
* \return この関数は常に true を返します。
*
* \sa loTranslate(double, double, double),
* fk_MatrixAdmin::glTranslate_(double, double, double)
*/
bool glTranslate(double x, double y, double z);
//! ローカル座標系平行移動関数1
/*!
* モデルを、ローカル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルで指定します。
*
* グローバル座標系による平行移動量の指定を行いたい場合は、
* glTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loTranslate_(fk_Vector &)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] v 平行移動量ベクトル
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(fk_Vector), glMoveTo(fk_Vector),
* fk_MatrixAdmin::loTranslate_(fk_Vector &)
*/
bool loTranslate(fk_Vector v);
//! ローカル座標系平行移動関数2
/*!
* モデルを、ローカル座標系によって平行移動した位置に移動します。
* 平行移動量はベクトルの成分を意味する3個の実数で指定します。
*
* グローバル座標系による平行移動量の指定を行いたい場合は、
* glTranslate() を利用して下さい。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::loTranslate_(double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] x 平行移動量ベクトルのx成分
* \param[in] y 平行移動量ベクトルのy成分
* \param[in] z 平行移動量ベクトルのz成分
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(double, double, double), glMoveTo(double, double, double),
* fk_MatrixAdmin::loTranslate_(double, double, double)
*/
bool loTranslate(double x, double y, double z);
//! グローバル座標系位置指定関数1
/*!
* モデルの位置を、指定した位置ベクトルに移動します。
* 位置はベクトルで指定します。
*
* glMoveTo() 関数に対応するローカル座標系関数
* 「loMoveTo()」関数は存在しません。
* これは、loMoveTo() 関数はその意味的に
* loTranslate() とまったく同一の挙動となるためです。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glMoveTo_(fk_Vector &)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] p 移動先位置ベクトル
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(fk_Vector), loTranslate(fk_Vector),
* fk_MatrixAdmin::glMoveTo_(fk_Vector &)
*/
bool glMoveTo(fk_Vector p);
//! グローバル座標系位置指定関数2
/*!
* モデルの位置を、指定した位置ベクトルに移動します。
* 位置はベクトルの成分を意味する3個の実数で指定します。
*
* glMoveTo() 関数に対応するローカル座標系関数
* 「loMoveTo()」関数は存在しません。
* これは、loMoveTo() 関数はその意味的に
* loTranslate() とまったく同一の挙動となるためです。
*
* \note
* 「干渉自動停止モード」を利用しない場合は、
* 同機能を持つ
* fk_MatrixAdmin::glMoveTo_(double, double, double)
* を用いた方が、処理がわずかに速くなります。
*
* \param[in] x 移動先位置ベクトルのx成分
* \param[in] y 移動先位置ベクトルのy成分
* \param[in] z 移動先位置ベクトルのz成分
*
* \return この関数は常に true を返します。
*
* \sa glTranslate(double, double, double), loTranslate(double, double, double),
* fk_MatrixAdmin::glMoveTo_(double, double, double)
*/
bool glMoveTo(double x, double y, double z);
///@}
//! \name 形状データ制御関数
///@{
//! 形状設定関数
/*!
* モデルの形状を設定します。
* 形状は、 fk_Shape クラスの派生クラスであれば設定可能です。
* なお、呼ぶ前に形状が設定されていた場合、前の設定は破棄されます。
*
* 設定した形状インスタンスは、モデルに設定した状態で解放しないようにしてください。
* もし解放された場合、プログラムが誤動作を起こします。
*
* \param[in] shape 形状インスタンスのポインタ
*/
void setShape(fk_Shape *shape);
//! 形状参照関数
/*!
* 現在設定されている形状を取得します。
* 形状が設定されていない場合は nullptr を返します。
*
* \return 形状インスタンスのポインタ
*/
fk_Shape * getShape(void) const;
///@}
//! \name マテリアル属性設定関数
///@{
//! マテリアル設定関数
/*!
* モデルの基本マテリアルを設定します。
* マテリアルに関しての詳細は、
* fk_Material の説明およびユーザーズマニュアルを参照して下さい。
*
* \note
* 稜線の色は setLineColor(),
* 頂点の色は setPointColor(),
* 曲線の色は setCurveColor() を利用して設定して下さい。
* 個別位相要素のマテリアルとの制御については、
* setMaterialMode() を参照して下さい。
* テクスチャを描画する際には、テクスチャモードによって混合の仕方が異なりますので、
* fk_Texture::setTextureMode() を参照して下さい。
*
* \param[in] mat マテリアル
*
* \sa fk_Material, setLineColor(), setPointColor(), fk_Texture::setTextureMode()
*/
void setMaterial(const fk_Material &mat);
//! 頂点色設定関数1
/*!
* モデルの頂点色を設定します。
* 頂点は、光源による陰影の影響はなく、常に設定色で表示されます。
*
* \param[in] col 頂点色のポインタ
*
* \sa fk_Color
*/
void setPointColor(fk_Color *col);
//! 頂点色設定関数2
/*!
* モデルの頂点色を設定します。
* 頂点は、光源による陰影の影響はなく、常に設定色で表示されます。
* 各色要素は 0 から 1 までの値を取ります。
* それ以外の値が与えられた場合、0 以下なら 0 に、1 以上なら 1 に丸められます。
*
* \param[in] r 頂点色の赤要素
* \param[in] g 頂点色の緑要素
* \param[in] b 頂点色の青要素
*/
void setPointColor(float r, float g, float b);
//! 稜線色設定関数1
/*!
* モデルの稜線色を設定します。
* 稜線は、光源による陰影の影響はなく、常に設定色で表示されます。
*
* \param[in] col 稜線色のポインタ
*
* \sa fk_Color
*/
void setLineColor(fk_Color *col);
//! 稜線色設定関数2
/*!
* モデルの稜線色を設定します。
* 稜線は、光源による陰影の影響はなく、常に設定色で表示されます。
* 各色要素は 0 から 1 までの値を取ります。
* それ以外の値が与えられた場合、0 以下なら 0 に、1 以上なら 1 に丸められます。
*
* \param[in] r 稜線色の赤要素
* \param[in] g 稜線色の緑要素
* \param[in] b 稜線色の青要素
*/
void setLineColor(float r, float g, float b);
//! 曲線色設定関数1
/*!
* モデルの曲線色を設定します。
* 曲線は、光源による陰影の影響はなく、常に設定色で表示されます。
*
* \param[in] col 曲線色のポインタ
*
* \sa fk_Color
*/
void setCurveColor(fk_Color *col);
//! 曲線色設定関数2
/*!
* モデルの曲線色を設定します。
* 曲線は、光源による陰影の影響はなく、常に設定色で表示されます。
* 各色要素は 0 から 1 までの値を取ります。
* それ以外の値が与えられた場合、0 以下なら 0 に、1 以上なら 1 に丸められます。
*
* \param[in] r 曲線色の赤要素
* \param[in] g 曲線色の緑要素
* \param[in] b 曲線色の青要素
*/
void setCurveColor(float r, float g, float b);
///@}
//! \name マテリアル属性参照関数
///@{
//! マテリアル参照関数
/*!
* 現在モデルに設定されている基本マテリアルを参照します。
*
* \return 基本マテリアルのポインタ
*
* \sa fk_Material, setMaterial()
*/
fk_Material * getMaterial(void);
//! 頂点色参照関数
/*!
* 現在モデルに設定されている頂点色を参照します。
*
* \return 頂点色のポインタ
*
* \sa fk_Color, setPointColor()
*/
fk_Color * getPointColor(void);
//! 稜線色参照関数
/*!
* 現在モデルに設定されている稜線色を参照します。
*
* \return 稜線色のポインタ
*
* \sa fk_Color, setLineColor()
*/
fk_Color * getLineColor(void);
//! 曲線色参照関数
/*!
* 現在モデルに設定されている曲線色を参照します。
*
* \return 曲線色のポインタ
*
* \sa fk_Color, setCurveColor()
*/
fk_Color * getCurveColor(void);
///@}
//! \name 描画属性制御関数
///@{
//! 描画モード設定関数
/*!
* モデルの描画モードを設定します。
* 描画モードとは、
* 面、稜線、頂点のそれぞれを描画するかどうかを制御するものです。
* 描画モード種類は以下のとおりです。
* - fk_Draw::NONE: 何も描画しません。
* - fk_Draw::POINT: 頂点を描画します。
* 曲線・曲面の場合は制御点を描画します。
* - fk_Draw::LINE: 稜線を描画します。
* 曲線・曲面の場合は制御点を結ぶポリラインを描画します。
* - fk_Draw::FACE: 面の表を描画します。
* - fk_Draw::BACK_FACE: 面の裏を描画します。
* - fk_Draw::FRONTBACK_FACE: 面の表と裏を描画します。
* - fk_Draw::TEXTURE: テクスチャを描画します。
* - fk_Draw::GEOM_LINE: 曲線や、曲面グリッド線を描画します。
* - fk_Draw::GEOM_POINT: 曲線上や曲面上の分割点を描画します。
* - fk_Draw::GEOM_FACE: 曲面を描画します。
* .
* これらの描画モードは、
* ビット論理和を用いて複数のものを同時に指定することが可能です。
* 以下のコードは、頂点、稜線、面の表をすべて描画するように設定します。
*
* fk_Model model;
*
* model.setDrawMode(fk_Draw::POINT | fk_Draw::LINE | fk_Draw::FACE);
*
* \param[in] mode 描画モード
*/
void setDrawMode(const fk_Draw mode);
//! 描画モード参照関数
/*!
* 現在の描画モードを参照します。
*
* \return 描画モード
*
* \sa setDrawMode()
*/
fk_Draw getDrawMode(void) const;
//! 要素モード設定関数
/*!
* 形状表示の際、モデル設定と形状個別要素設定のどちらを採用するかを設定します。
* モードには以下のものがあります。
* - fk_ElementMode::NONE: 何も描画しません。
* - fk_ElementMode::MODEL: モデル設定を優先します。
* - fk_ElementMode::ELEMENT: 形状内の個別要素設定を優先します。
* .
*
* \param[in] mode 設定モード
*/
void setElementMode(const fk_ElementMode mode);
//! 要素モード設定関数
/*!
* 表示の際の優先モードを取得します。
*
* \return 設定モード
*
* \sa setElementMode()
*/
fk_ElementMode getElementMode(void) const;
//! シェーディングモード設定関数
/*!
* 面描画またはテクスチャ描画の際の、
* シェーディングアルゴリズムを設定します。
* グーローシェーディングは、各頂点ごとに発色輝度を計算し、
* 頂点以外の面内部は色値の線形補間によって発色輝度を決定します。
* フォンシェーディングでは、色値ではなく法線ベクトルを補間決定し、
* 面内部の発色は補間法線ベクトルに対し発色輝度を計算します。
* 一般的には、速度重視の場合はグーロー、質重視の場合はフォンを選択します。
* なお、本館数は面またはテクスチャの描画の際のみに関与するものであり、
* 線や点の描画の際には影響を及ぼしません。
*
* \param[in] mode モード
*/
void setShadingMode(fk_ShadingMode mode);
//! シェーディングモード取得関数
/*!
* 表示の差異のシェーディングモードを取得します。
*
* \return モード
*
* \sa setShadingMode()
*/
fk_ShadingMode getShadingMode(void) const;
//! ブレンドモード設定関数
/*!
* テクスチャ画像を伴うモデルを表示する場合、
* 表示色はテクスチャ画像の各画素色と、
* モデルに設定されているマテリアルの両方が関与します。
* この関数は、テクスチャ画像の画素色とモデルのマテリアル色に対し、
* どのような計算式で双方を混合(ブレンド)するかを設定します。
* ここでブレンドモードを設定しても、fk_Scene:setBlendStatus() で
* ブレンドを有効にしていないと実際の描画で有効になりません。
* ブレンドモードの設定は、一般的な設定をプリセットの中から選択するか、
* カスタムモードを選択した上で、入力ピクセルと出力ピクセルに対する係数を
* 個別に指定するかのどちらかによって行います。
*
* \param[in] mode
* ブレンドモードを設定します。与えられる値は以下の8種類です。
* - fk_BlendMode::ALPHA: 通常のアルファブレンドです。初期値です。
* - fk_BlendMode::NEGATIVE: 反転ブレンドです。
* - fk_BlendMode::ADDITION: 加算ブレンドです。
* - fk_BlendMode::SCREEN: アルファ付き加算ブレンドです。
* - fk_BlendMode::LIGHTEN: 入出力ピクセルのうち明るい方を採用するブレンドです。
* - fk_BlendMode::MULTIPLY: 乗算ブレンドです。
* - fk_BlendMode::NONE: ブレンドを行いません。
* fk_Scene 側の設定によらずブレンドを無効にします。
* - fk_BlendMode::CUSTOM: カスタムモードです。第 2,3 引数にて指定した
* 係数を用いた計算式でブレンドします。
*
* \param[in] srcFactor
* 入力ピクセルに対する係数を設定します。
* mode に fk_BlendMode::CUSTOM を指定した場合のみ有効です。
* それ以外のモードでは省略可能です。
* 本関数の仕様は OpenGL 関数の glBlendFunc() に準拠します。
* 詳細は glBlendFunc() の情報を参照して下さい。
* 与えられる値は以下の10種類で、
* それぞれの値に「GL」に置き換えた GLenum 型の値に対応します。
* - fk_BlendFactor::ZERO
* - fk_BlendFactor::ONE
* - fk_BlendFactor::SRC_COLOR
* - fk_BlendFactor::ONE_MINUS_SRC_COLOR
* - fk_BlendFactor::DST_COLOR
* - fk_BlendFactor::ONE_MINUS_DST_COLOR
* - fk_BlendFactor::SRC_ALPHA
* - fk_BlendFactor::ONE_MINUS_SRC_ALPHA
* - fk_BlendFactor::DST_ALPHA
* - fk_BlendFactor::ONE_MINUS_DST_ALPHA
*
* \param[in] dstFactor
* 出力ピクセルに対する係数を設定します。
* mode に fk_BlendFactor::CUSTOM を指定した場合のみ有効です。
* それ以外のモードでは省略可能です。与えられる値は srcFactor と同様です。
*
* \sa getBlendMode(), fk_Scene::setBlendStatus(), fk_Scene::getBlendStatus()
*/
void setBlendMode(const fk_BlendMode mode,
const fk_BlendFactor srcFactor = fk_BlendFactor::SRC_ALPHA,
const fk_BlendFactor dstFactor = fk_BlendFactor::ONE_MINUS_SRC_ALPHA);
//! ブレンドモード参照関数
/*!
* モデルのブレンドモードを取得します。
*
* \param[out] outSrc
* 入力ピクセルにかかる係数の種類を取得します。省略可能です。
* \param[out] outDst
* 出力ピクセルにかかる係数の種類を取得します。省略可能です。
* \return ブレンドモード
*
* \sa setBlendMode()
*/
fk_BlendMode getBlendMode(fk_BlendFactor *outSrc = nullptr,
fk_BlendFactor *outDst = nullptr) const;
//! スムースモード設定関数
/*!
* モデルのスムースモードを設定します。
* スムースモードを有効にすると、
* 形状の隣り合う面同士の法線ベクトルが補間され、
* 擬似的に滑らかな曲面として表示を行うようになります。
*
* \param[in] mode true である場合、スムースモードを有効とします。
* false である場合無効とします。
*/
void setSmoothMode(const bool mode);
//! スムースモード参照関数
/*!
* 現在のモデルのスムースモードを取得します。
*
* \return 有効である場合 true を、無効である場合 false を返します。
*
* \sa setSmoothMode()
*/
bool getSmoothMode(void) const;
//! 描画順序制御関数
/*!
* この関数では、モデルの持つ位相要素の描画順序を制御します。
* モデルの各位相要素が同一平面上にあり、描画順序を逆にしたい場合に用います。
*
* \param[in] mode
* true の場合、モデル内の描画が通常と逆順になります。
* false の場合、順序を通常の状態に戻します。
*/
void setReverseDrawMode(const bool mode);
//! 描画順序参照関数
/*!
* setReverseDrawMode() で設定した描画順序を取得します。
*
* \return 逆順である場合 true を、正順である場合 false を返します。
*
* \sa setReverseDrawMode()
*/
bool getReverseDrawMode(void) const;
//! 前後関係制御関数
/*!
* この関数では、モデルを描画する際の前後関係に関する設定を制御します。
* fk_Scene::entryOverlayModel()でも前後関係を無視した描画はできますが、
* 通常の描画中に前後関係を無視したり、
* 半透明物体が後続の描画の前後関係に作用しないようにするなど、
* 細かな調整を行いたい場合に用います。
*
* \param[in] mode
* 前後関係の処理モードを設定します。与えられる値は以下の4種類です。
* - fk_DepthMode::NO_USE: 前後関係の参照も更新も行わず、常に上書きします。
* - fk_DepthMode::READ: 前後関係を参照してチェックします。
* - fk_DepthMode::WRITE: 前後関係を更新して後続の描画に影響するようにします。
* - fk_DepthMode::READ_AND_WRITE: 前後関係を参照しつつ更新します。
* fk_DepthMode::READ | fk_DepthMode::WRITE と等価です。初期値です。
*/
void setDepthMode(const fk_DepthMode mode);
//! 前後関係参照関数
/*!
* setDepthMode() で設定した前後関係の設定を取得します。
*
* \return 前後関係処理モード
*
* \sa setDepthMode()
*/
fk_DepthMode getDepthMode(void) const;
//! テクスチャモード設定関数
/*!
* テクスチャの描画時における描画色処理モードを設定します。
* これは、ポリゴンに設定されているマテリアルによる発色と、
* テクスチャ画像の色をどのように混成するかを制御するものです。
* それぞれのモードの概要と厳密な計算式を以下に記載します。
* なお、数式中の \f$ C_f \f$ はポリゴン色、
* \f$ C_\alpha \f$ ポリゴンの透明度、
* \f$ T_f \f$ はテクスチャピクセル色、
* \f$ T_\alpha \f$ はテクスチャの透明度を表します。
*
* - fk_TexMode::MODULATE \n
* この設定では、ポリゴンの色とテクスチャの色を積算します。
* そのため、光源による陰影効果が生じます。
* 透明度に関しても積算となります。
* 数式として表すと、色と透明度はそれぞれ
* \f[
* (C_f T_f, \; C_\alpha T_\alpha)
* \f]
* となります。
*
* - fk_TexMode::REPLACE \n
* この設定では、ポリゴンの色は完全に無視され、
* テクスチャのピクセル色がそのまま表示されます。
* そのため、光源による陰影効果が生じません。
* また、テクスチャ画像の透明度はそのまま描画に反映されます。
* 数式として表すと、色と透明度はそれぞれ
* \f[
* (T_f, \; T_\alpha)
* \f]
* となります。
*
* - fk_TexMode::DECAL \n
* この設定では、各ピクセルの透明度に応じて、
* ポリゴン色とピクセル色の混合が行われます。
* 光源による陰影効果は、ピクセルの透明度が低い場合に強くなります。
* 透明度は、ポリゴンの透明度がそのまま適用されます。
* これを数式として表すと、色と透明度はそれぞれ
* \f[
* (C_f (1-T_\alpha) + T_f T_\alpha, \; C_\alpha)
* \f]
* となります。
*
* - fk_TexMode::NONE \n
* この設定では、 fk_Model での設定は無視し、
* fk_Texture::setTextureMode() での設定に従います。
* .
* デフォルトでは fk_TexMode::NONE が設定されています。
* なお、同様の設定は fk_Texture::setTextureMode() でも行うことが可能で、
* fk_Model 側で fk_TexMode::NONE 以外が設定されている場合は
* fk_Model 側の設定が優先されます。
* fk_Model 側で fk_TexMode::NONE が設定されている場合のみ、
* fk_Texture 側での設定が有効となります。
*
* \param[in] mode モード
*
* \sa getTextureMode(), fk_Texture::setTextureMode()
*/
void setTextureMode(fk_TexMode mode);
//! テクスチャモード取得関数
/*!
* 現在のテクスチャモードを取得します。
*
* \return テクスチャモード
*
* \sa setTextureMode()
*/
fk_TexMode getTextureMode(void);
//! 頂点描画サイズ設定関数
/*!
* 頂点の描画サイズを設定します。
* 単位はピクセルです。整数以外も設定可能です。
*
* \param[in] size 頂点描画サイズ
*
* \sa getPointSize(), setLineWidth()
*/
void setPointSize(const double size);
//! 頂点描画サイズ参照関数
/*!
* 頂点の描画サイズを取得します。
*
* \return 頂点描画サイズ
*
* \sa setPointSize()
*/
double getPointSize(void) const;
//! 影投影設定関数
/*!
* このモデルが別モデル(やこのモデル自身)へ影を投影するかどうかの設定を行います。
* この設定を false にすると、シーン全体で影効果が有効であっても、
* 当モデルの影は別モデル(やこのモデル自身)に投影されなくなります。
* デフォルトは true です。
*
* 他モデルの影をこのモデルに投影するかどうかを制御する場合は、
* setShadowDraw() を用いてください。
*
* \param[in] mode true で有効、false で無効となります。
*
* \sa
* setShadowDraw(), getShadowEffect(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
void setShadowEffect(bool mode);
//! 影投影設定参照関数
/*!
* このモデルの影投影設定を参照します。
* 詳細は setShadowEffect() のマニュアルを参照して下さい。
*
* \return 影投影設定。true で有効、false で無効を意味します。
*
* \sa
* setShadowEffect(), getShadowDraw(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
bool getShadowEffect(void);
//! 影表示設定関数
/*!
* 別モデルやこのモデル自身の影を、このモデルに投影するかどうかの設定を行います。
*
* このモデルの影を別のモデル(や自分自身)に投影するかどうかの制御は、
* setShadowEffect() を用いて下さい。
*
* \param[in] mode true で有効、false で無効となります。
*
* \sa
* setShadowEffect(), getShadowDraw(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
void setShadowDraw(bool mode);
//! 影表示設定参照関数
/*!
* このモデルの影表示設定を参照します。
* 詳細は setShadowDraw() のマニュアルを参照して下さい。
*
* \return 影表示設定。true で有効、false で無効を意味します。
*
* \sa
* setShadowDraw(), getShadowEffect(),
* fk_Scene::setShadowMode(), fk_AppWindow::setShadowMode()
*/
bool getShadowDraw(void);
//! 霧効果設定関数
/*!
* このモデルの表示に対し霧効果の有効とするかどうかを設定します。
* デフォルトでは有効となっています。
*
* \param[in] mode true で有効、false で無効となります。
*/
void setFogMode(bool mode);
//! 霧効果設定参照関数
/*!
* 霧効果が有効かどうかを参照します。
*
* \return 有効なら true、無効なら false を返します。
*/
bool getFogMode(void);
///@}
//! \name 座標系情報参照関数
///@{
//! 継承変換行列取得関数
/*!
* モデルの位置と姿勢を表す変換行列を取得します。
* 当モデルに親モデルがあった場合、
* その親モデルの変換行列と当モデルの変換行列の積が返されます。
* 結果として、この関数を用いることでグローバル座標系における
* 当モデルの変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getMatrix() と結果が同じとなります。
*
* \return モデルの継承変換行列
*
* \sa fk_MatrixAdmin::getMatrix(), getInhInvMatrix()
*/
fk_Matrix getInhMatrix(void) const;
//! 継承逆変換行列取得関数
/*!
* モデルの位置と姿勢を表す変換行列の、逆行列を取得します。
* これは、 getInhMatrix() で得られる行列の逆行列となります。
* 当モデルに親モデルがあった場合、
* その親モデルの逆変換行列と当モデルの逆変換行列の積が返されます。
* 結果として、この関数を用いることでグローバル座標系における
* 当モデルの逆変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getInvMatrix() と結果が同じとなります。
*
* \return モデルの継承逆変換行列
*
* \sa fk_MatrixAdmin::getInvMatrix(), getInhMatrix()
*/
fk_Matrix getInhInvMatrix(void) const;
//! 継承移動・回転要素変換行列取得関数
/*!
* モデルの持つ変換要素のうち、
* 位置と姿勢のみを反映した、
* すなわち拡大縮小の要素を省いた変換行列を取得します。
* 当モデルに親モデルがあった場合、
* その親モデルの変換行列と当モデルの変換行列の積が返されます。
* その結果として、この関数を用いることでグローバル座標系における
* 当モデルの変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getBaseMatrix() と結果が同じとなります。
*
* \return モデルの継承移動・回転要素変換行列
*
* \sa fk_MatrixAdmin::getBaseMatrix(), getInhMatrix(), getInhInvBaseMatrix()
*/
fk_OrthoMatrix getInhBaseMatrix(void) const;
//! 継承移動・回転要素逆変換行列取得関数
/*!
* モデルの持つ変換要素のうち、
* 位置と姿勢のみを反映した、
* すなわち拡大縮小の要素を省いた変換行列の逆行列を取得します。
* 当モデルに親モデルがあった場合、
* その親モデルの逆変換行列と当モデルの逆変換行列の積が返されます。
* その結果として、この関数を用いることでグローバル座標系における
* 当モデルの逆変換行列を得ることができます。
* 親モデルが設定されていない場合は、
* fk_MatrixAdmin::getInvBaseMatrix() と結果が同じとなります。
*
* \return モデルの継承移動・回転要素逆変換行列
*
* \sa fk_MatrixAdmin::getInvBaseMatrix(), getInhInvMatrix(), getInhBaseMatrix()
*/
fk_OrthoMatrix getInhInvBaseMatrix(void) const;
//! 継承位置ベクトル参照関数
/*!
* モデルの位置ベクトルを取得します。
* 本関数は、親モデルの有無にかかわらず、グローバル座標系での実際の位置ベクトルを返します。
*
* \return グローバル座標系での位置ベクトル
*
* \sa getInhVec(), getInhUpvec(), getInhAngle(), fk_MatrixAdmin::getPosition()
*/
fk_Vector getInhPosition(void) const;
//! 継承方向ベクトル参照関数
/*!
* モデルの方向ベクトルを取得します。
* 本関数は、親モデルの有無にかかわらず、グローバル座標系での実際の方向ベクトルを返します。
*
* \return グローバル座標系での方向ベクトル
*
* \sa getInhPosition(), getInhUpvec(), getInhAngle(), fk_MatrixAdmin::getVec()
*/
fk_Vector getInhVec(void) const;
//! 継承アップベクトル参照関数
/*!
* モデルのアップベクトルを取得します。
* 本関数は、親モデルの有無にかかわらず、
* グローバル座標系での実際のアップベクトルを返します。
*
* \return グローバル座標系でのアップベクトル
*
* \sa getInhPosition(), getInhVec(), getInhAngle(), fk_MatrixAdmin::getUpvec()
*/
fk_Vector getInhUpvec(void) const;
#ifndef FK_DOXYGEN_USER_PROCESS
fk_Vector getInhUpVec(void) const;
void setPickMode(const bool);
bool getPickMode(void) const;
void setMaterialMode(const fk_MaterialMode mode);
fk_MaterialMode getMaterialMode(void) const;
#endif
//! 継承オイラー角参照関数
/*!
* モデルのオイラー角を取得します。
* 本関数は、親モデルの有無にかかわらず、グローバル座標系での実際のオイラー角を返します。
* オイラー角の詳細については、 fk_Angle の説明を参照して下さい。
*
* \return
*
* \sa getInhPosition(), getInhVec(), getInhUpvec(), fk_MatrixAdmin::getAngle(), fk_Angle
*/
fk_Angle getInhAngle(void) const;
//! 継承全体倍率取得関数
/*!
* モデルの全体拡大・縮小倍率を取得します。
* 親子関係の小モデルの場合、親モデルでの倍率も反映されます。
*
* \return 継承全体拡大・縮小倍率
*
* \sa getInhPosition(), getInhVec(), getInhUpvec(),
* getInhAngle(), fk_MatrixAdmin::getScale()
*/
double getInhScale(void) const;
///@}
//! \name 親子関係制御関数
///@{
//! 親モデル設定関数
/*!
* 親モデルを設定します。
* 親モデルは 1 個しか設定できません。
* 前に設定されていた場合は、前のモデル設定は破棄されます。
*
* \param[in] model 親モデルインスタンスのポインタ
*
* \param[in] setMode
* true の場合、現在のグローバル座標系の位置と姿勢を、
* 親モデル設定後も保持します。
* false の場合は、当モデルでの位置と姿勢を親モデルからの
* 相対的な位置、姿勢として扱います。
* そのため、設定後にグローバル座標系での位置や姿勢は変化することになります。
* この引数を省略した場合は false と同様の挙動となります。
*
* \return 設定に成功すれば true を、失敗すれば false を返します。
*
* \sa deleteParent(), getParent(), entryChild()
*/
bool setParent(fk_Model *model, bool setMode = false);
//! 親モデル解除関数
/*!
* 親モデルの設定を解除します。
*
* \param[in] setMode
* true の場合、現在のグローバル座標系の位置と姿勢を、
* 親モデル解除後も保持します。
* false の場合は、親モデルからの相対的な位置と姿勢を、
* 解除後のグローバル座標系に設定します。
* この引数を省略した場合は false と同様の挙動となります。
*
* \sa setParent(), getParent(), deleteChild()
*/
void deleteParent(bool setMode = false);
//! 親モデル参照関数
/*!
* 親モデルを取得します。
*
* \return 親モデルインスタンスのポインタ。
* 親モデルが設定されていない場合は nullptr を返します。
*
* \sa setParent(), deleteParent()
*/
fk_Model * getParent(void) const;
//! 子モデル設定関数
/*!
* 子モデルを設定します。
* 子モデルは複数持つことが可能なので、
* 既に子モデルが登録されている場合でも、その設定は破棄されません。
*
* \param[in] model 子モデルインスタンスのポインタ
*
* \param[in] setMode
* true の場合、子モデルの現在のグローバル座標系の位置と姿勢を、
* 設定後も保持します。
* false の場合は、子モデルでの位置と姿勢を当モデルからの
* 相対的な位置、姿勢として扱います。
* そのため、設定後にグローバル座標系での位置や姿勢は変化することになります。
* この引数を省略した場合は false と同様の挙動となります。
*
* \return 設定に成功すれば true を、失敗すれば false を返します。
*
* \sa setParent(), deleteChild(), deleteChildren(), foreachChild()
*/
bool entryChild(fk_Model *model, bool setMode = false);
//! 子モデル解除関数
/*!
* 子モデルの設定を解除します。
*
* \param[in] model
* 子モデルインスタンスのポインタ。
* もし model が子モデルの中に存在しない場合は、false を返します。
*
* \param[in] setMode
* true の場合、子モデルのグローバル座標系の位置と姿勢を、
* 解除後も保持します。
* false の場合は、親モデルからの相対的な位置と姿勢を、
* 解除後のグローバル座標系に設定します。
* この引数を省略した場合は false と同様の挙動となります。
*
* \return 解除に成功すれば true を、失敗すれば false を返します。
*
* \sa entryChild(), deleteChildren(), foreachChild()
*/
bool deleteChild(fk_Model *model, bool setMode = false);
//! 全子モデル解除関数
/*!
* 当モデルの全ての子モデルの設定を解除します。
*
* \param[in] setMode
* true の場合、子モデルのグローバル座標系の位置と姿勢を、
* 解除後も保持します。
* false の場合は、親モデルからの相対的な位置と姿勢を、
* 解除後のグローバル座標系に設定します。
* この引数を省略した場合は false と同様の挙動となります。
*
* \sa entryChild(), deleteChild(), foreachChild()
*/
void deleteChildren(bool setMode = false);
//! 子モデル逐次参照関数
/*!
* 当モデルに設定されている子モデルを順番に帰します。
* まず、引数に nullptr を渡したとき、1番目の子モデルを返します。
* 子モデルが存在しない場合は、その時点で nullptr を返します。
* 次に、1番目に帰ってきたモデルを引数として渡したとき、
* 2番目の子モデルを返します。
* このように、設定されている子モデルを順番に参照することができます。
* 最後の子モデルが引数として渡されたとき、nullptr を返します。
*
* 以下のコードは、「parent」の全ての子モデルに対し、
* 描画モードを fk_Draw::LINE に設定する例です。
*
* fk_Model parentModel, *childModel;
*
* for(childModel = parentModel.foreachChild(nullptr);
* childModel != nullptr;
* childModel = parentModel.foreachChild(childModel)) {
*
* childModel->setDrawMode(fk_Draw::LINE);
* }
*
* \param[in] model 順番に渡す子モデルインスタンスのポインタ
*
* \return 次にあたる子モデルインスタンスのポインタ。
* 引数に最後の子モデルが渡された場合、nullptr を返します。
*
* \sa entryChild(), deleteChild(), deleteChildren()
*/
fk_Model * foreachChild(fk_Model *model);
///@}
//! \name 状態保存制御関数
///@{
//! 位置・姿勢保存関数
/*!
* 現時点でのモデルの位置と姿勢を保存します。
* restore() 関数を用いることで復元します。
*
* \sa restore(void), restore(double), setInterStopMode()
*/
void snapShot(void);
//! 位置・姿勢復元関数
/*!
* snapShot() 関数によって保存した位置・姿勢を復元します。
*
* \return 復元に成功すれば true を、失敗すれば false を返します。
*
* \sa restore(double), snapShot(), setInterStopMode()
*/
bool restore(void);
//! 位置・姿勢途中復元関数
/*!
* snapShot() 関数によって保存した位置・姿勢に対し、
* 現在の位置・姿勢と線形補間した状態にします。
*
* \param[in] t
* 線形補間パラメータ。
* 0 を snapShot() 関数による保存時、
* 1 を現時点とし、
* 与えられた実数によって線形補間した位置と姿勢に設定します。
*
* \return 設定に成功すれば true を、失敗すれば false を返します。
*
* \sa snapShot(), restore(void), isCollision()
*/
bool restore(double t);
///@}
//! \name 描画制御用関数
///@{
//! シェーダー設定関数
/*!
* この関数は、モデル描画の際のシェーダーを設定するものです。
* fk_ShaderBinder::bindModel() による設定とまったく同じ挙動となります。
*
* \param[in] shader シェーダープログラム
*
* \note
* シェーダーを未設定にし、デフォルトのシェーダーで描画したい場合は、
* 引数に nullptr を入力して下さい。
*/
void setShader(fk_ShaderBinder *shader);
//! シェーダー取得関数
/*!
* setShader() (または fk_ShaderBinder::bindModel())
* によって設定されたシェーダーを返します。
*
* \return シェーダーを返します。
* シェーダーが設定されていない場合は nullptr を返します。
*/
fk_ShaderBinder * getShader(void);
#ifndef FK_DOXYGEN_USER_PROCESS
//! 描画処理事前関数
/*!
* この関数は、
* 描画エンジン内部でモデルが実際に描画される前に自動的に呼び出されます。
* デフォルトの状態では中身は空ですが、
* 関数オブジェクトまたはラムダ式で上書きすることにより、
* 描画処理前の時点の処理を記述することが可能です。
* 主な利用用途はシェーダプログラミングやデバッグ、
* あるいは独自形状描画などが考えられます。
*
* 本関数を利用するには、FK の描画エンジン内部に精通している必要があります。
* ソースコードを解析し、内部処理を理解した上で利用することを推奨します。
*/
//std::function<void(void)> preShader;
//! 描画処理事後関数
/*!
* この関数は、
* 描画エンジン内部でモデルが実際に描画された後に自動的に呼び出されます。
* デフォルトの状態では中身は空ですが、
* 関数オブジェクトまたはラムダ式で上書きすることにより、
* 描画処理後の時点の処理を記述することが可能です。
* 主な利用用途はシェーダプログラミングやデバッグ、
* あるいは独自形状描画などが考えられます。
*
* 本関数を利用するには、FK の描画エンジン内部に精通している必要があります。
* ソースコードを解析し、内部処理を理解した上で利用することを推奨します。
*/
//std::function<void(void)> postShader;
#endif
///@}
//! \name 境界ボリューム自動設定関数
///@{
//! 境界球自動設定関数
/*!
* この関数は、
* 境界ボリュームである境界球の半径を自動的に設定するものです。
* 具体的には、モデルの中心から形状の最遠点となる点と中心との距離を半径とします。
* その結果、すべての形状上の点は境界球の内側に入ることになります。
* 境界球に関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* 境界球半径は自動的に変化しません。
* 形状の全ての部分が境界球内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
*
* \sa adjustAABB(), adjustOBB(), adjustCapsule(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setSphere(), fk_Boundary::getSphere()
*/
void adjustSphere(void);
//! AABB 自動設定関数
/*!
* この関数は、
* 境界ボリュームである AABB (軸平行境界ボックス) の大きさを自動的に設定するものです。
* すべての頂点が AABB の内部と入る条件を満たす最小の大きさが設定されます。
* AABB に関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* AABB の大きさは自動的に変化しません。
* 形状の全ての部分が AABB 内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
* また、AABB はその性質上、
* モデルが回転した場合には形状が AABB の外側にはみ出る可能性がありますので、
* モデルが回転した後も形状が AABB 内部にあることを保証するには、
* 回転した後に本関数を呼ぶ必要があります。
*
* \sa adjustSphere(), adjustOBB(), adjustCapsule(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setAABBSize(double, double, double),
* fk_Boundary::setAABBSize(fk_Vector), fk_Boundary::getAABBSize()
*/
void adjustAABB(void);
//! OBB 自動設定関数
/*!
* この関数は、
* 境界ボリュームである OBB (有向境界ボックス) の大きさを自動的に設定するものです。
* すべての頂点が OBB の内部と入る条件を満たす最小の大きさが設定されます。
* OBB に関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* OBB の大きさは自動的に変化しません。
* 形状の全ての部分が OBB 内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
*
* \sa adjustSphere(), adjustAABB(), adjustCapsule(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setOBBSize(double, double, double),
* fk_Boundary::setOBBSize(fk_Vector), fk_Boundary::getOBBSize()
*/
void adjustOBB(void);
//! 境界カプセル自動設定関数
/*!
* この関数は、
* 境界ボリュームである境界カプセルの大きさを自動的に設定するものです。
* すべての頂点が境界カプセルの内部と入る条件を満たす最小の大きさが設定されます。
* 境界カプセルに関する詳細は fk_Boundary クラスを参照して下さい。
*
* \note
* setShape() で別形状を設定した場合や、設定した形状を
* fk_IndexFaceSet::moveVPosition() などの関数によって変形した場合でも、
* 境界カプセルの大きさは自動的に変化しません。
* 形状の全ての部分が境界カプセル内部に入ることを保証するためには、
* 形状変化後に本関数を呼ぶ必要があります。
*
* \param[in] S 中心軸始点位置ベクトル
* \param[in] E 中心軸終点位置ベクトル
*
* \sa adjustSphere(), adjustAABB(), adjustOBB(), isInter(), isCollision(),
* fk_Boundary::setBMode(),
* fk_Boundary::setCapsule(), fk_Boundary::getCapsuleRadius(),
* fk_Boundary::getCapsuleLength(), fk_Boundary::getCapsuleStartPos(),
* fk_Boundary::getCapsuleEndPos()
*/
void adjustCapsule(fk_Vector S, fk_Vector E);
///@}
//! \name 干渉判定・衝突判定関数
///@{
//! モデル間干渉判定関数
/*!
* この関数は、別モデルとの干渉判定を行います。
* 干渉判定に用いられる境界ボリュームの種類は、
* fk_Boundary::setBMode() で設定されたものが用いられます。
* 相手モデル側で別の種類が設定されていた場合でも、
* この関数を呼び出しているインスタンス側の設定が優先されます。
* 従って、相手モデル側の境界ボリュームも適切に設定しておく必要があります。
*
* \note
* 「干渉判定」と「衝突判定」の違いに関しては、
* 本クラスの概要を参照して下さい。
*
* \param[in] model
* 干渉判定を行うモデル
*
* \return 干渉している場合 true を、していない場合 false を返します。
*
* \sa adjustSphere(), adjustAABB(), adjustOBB(), adjustCapsule(), isCollision(),
* snapShot(), restore(void), setInterStopMode(), entryInterModel(),
* fk_Boundary::setBMode(),
* fk_Boundary::setCapsule(), fk_Boundary::getCapsuleRadius(),
* fk_Boundary::getCapsuleLength(), fk_Boundary::getCapsuleStartPos(),
* fk_Boundary::getCapsuleEndPos()
*/
bool isInter(fk_Model *model);
//! モデル間衝突判定関数
/*!
* この関数は、別モデルとの衝突判定を行います。
* 衝突判定を行うには、まずそれぞれのモデルにおいて
* snapShot() 関数によって衝突判定を行う初期状態を設定しておく必要があります。
* その状態から現在の位置まで、両モデルが等速度直線運動していると想定し、
* その間に衝突が発生したかどうかを検出します。
*
* なお、本関数を利用する際には事前に境界球の半径を適切に設定しておく必要があります。
* 現在この関数は境界球による判定のみが有効となります。
* fk_Boundary::setBMode() によって境界ボリュームが別の種類に設定されていた場合でも、
* 境界球の情報のみが用いられます。
*
* なお、衝突判定は snapShot() を呼ぶ以前や現時点以降を含めての検出となるので、
* snapShot() を呼んだ時点から現時点までの間に衝突が起こったかどうかを判定するには、
* 返値第2引数の衝突時間を考慮する必要があります。
*
* \note
* 「干渉判定」と「衝突判定」の違いに関しては、
* 本クラスの概要を参照して下さい。
*
* \param[in] model
* 衝突判定を行うモデル
*
* \return
* 第1要素は、両モデルが等速度直線運動をすると想定した場合に、
* いずれかの時刻で衝突が起きる場合 true が、衝突しない場合は false が入ります。
*
* 第2要素は,snapShot() が呼ばれた時刻を 0、
* 現時点の時刻を 1 とした場合の衝突時間が入ります。
* 第1要素が true であった場合でも、
* この値が 0 から 1 の間にないときは、
* 衝突が起こっていないことになりますので、注意して下さい。
*
* \sa adjustSphere(), adjustAABB(), adjustOBB(), adjustCapsule(), isInter(),
* snapShot(), restore(double),
* fk_Boundary::setBMode(),
* fk_Boundary::setCapsule(), fk_Boundary::getCapsuleRadius(),
* fk_Boundary::getCapsuleLength(), fk_Boundary::getCapsuleStartPos(),
* fk_Boundary::getCapsuleEndPos()
*/
std::tuple<bool, double> isCollision(fk_Model *model);
#ifndef FK_OLD_NONSUPPORT
#ifndef FK_DOXYGEN_USER_PROCESS
bool isCollision(fk_Model *model, double *time);
#endif
#endif
//! 干渉継続モード設定関数
/*!
* 干渉継続モードを有効にしておくと、
* 本モデルが isInter() 関数で他のモデルと干渉状態が検出された場合、
* resetInter() が呼ばれるまでは true を返すようになります。
*
* \param[in] mode
* true である場合、干渉継続モードが有効となります。
* false の場合無効にします。
*
* \sa isInter(), getInterMode(), getInterStatus(), resetInter(),
* setInterStopMode(), entryInterModel()
*/
void setInterMode(bool mode);
//! 干渉継続モード取得関数
/*!
* 現在の干渉継続モード状態を取得します。
*
* \return
* 干渉継続モードが有効である場合 true を、無効である場合 false を返します。
*
* \sa setInterMode()
*/
bool getInterMode(void);
//! 干渉継続状態取得関数
/*!
* 本関数は、干渉継続モードが有効である場合で、
* 前に resetInter() が呼ばれた以降で、
* isInter() によって干渉が検出されたことがあるかを検出します。
*
* \return
* 干渉検出があった場合 true を、なかった場合 false を返します。
*
* \sa isInter(), setInterMode(), resetInterStatus()
*/
bool getInterStatus(void);
//! 干渉継続状態初期化関数
/*!
* 干渉継続モードによる干渉検出状態を初期化します。
* この関数が呼ばれた以降、再び isInter() による干渉が検出されるまでは、
* getInterStatus() 関数は false を返します。
*
* \sa isInter(), setInterMode(), getInterStatus()
*/
void resetInter(void);
///@}
//! \name 干渉自動停止制御関数
///@{
//! 干渉自動停止モード設定関数
/*!
* この関数は、干渉自動停止モードの有無効を設定します。
* 「干渉自動停止モード」とは、以下のような処理を行う機能のことです。
* -# 干渉チェック対象となるモデルを事前に登録しておく。
* -# モデル移動の前に snapShot() をしておく。
* -# モデルの移動を行った際に、
* もし干渉チェック対象モデルのいずれかと干渉していた場合は、
* restore() を実行し移動前の状態に戻る。
*
* この機能を用いることで、移動後で干渉が起きてしまう移動が無効となります。
* 壁などにモデルが入らないように処理するような場面で有効となります。
*
* このモードの対象となる移動関数は以下のとおりです。
* - glRotate()
* - loRotate()
* - glRotateWithVec()
* - loRotateWithVec()
* - glTranslate()
* - loTranslate()
* - glMoveTo()
*
* これらの関数は、モデルの位置ベクトルが変化する可能性があるからです。
* その他の姿勢制御関数については停止の対象とはなりません。
*
* なお、このモードを利用する場合、 restore() した後にも干渉状態となっている場合、
* 適用モデルがまったく動かなくなるという問題が生じます。
* そのため本機能を用いたい場合は、
* 干渉チェック対象となるモデルは全て静止した状態であることを推奨します。
* また、位置のかわらない姿勢制御関数は干渉状態であっても動作しますが、
* その際に物体の回転によって非干渉状態から干渉状態となることがありえますので、
* これも注意が必要です。
*
* \note
* 干渉判定を行う際の境界ボリュームに関する設定は、
* 事前に行っておく必要があります。
*
* \note
* このモードを利用する場合、副作用として自前で管理していた
* snapShot() の情報が破棄されてしまうという問題がありますので、
* snapShot() や restore() を利用する場合はこのモードは用いないようにして下さい。
*
* \param[in] mode true の場合有効とし、 false の場合無効とします。
*
* \sa getInterStopMode(), entryInterModel(), deleteInterModel(), clearInterModel(),
* isInter(), snapShot(), restore()
*/
void setInterStopMode(bool mode);
//! 干渉自動停止モード取得関数
/*!
* 干渉自動停止モードの有無効を取得します。
*
* \return 有効である場合 true を、無効である場合 false を返します。
*
* \sa setInterStopMode()
*/
bool getInterStopMode(void);
//! 干渉自動停止モデル登録関数
/*!
* 干渉自動停止モードの対象となるモデルを登録します。
*
* \note
* 本関数で登録したモデルのインスタンスを、
* deleteInterModel() や clearInterModel() で解除する前に消去した場合、
* 動作は保証されません。
*
* \param[in] model 登録モデルインスタンス
*
* \sa setInterStopMode(), deleteInterModel(), clearInterModel()
*/
void entryInterModel(fk_Model *model);
//! 干渉自動停止モデル解除関数
/*!
* 干渉自動停止モードの対象となっていたモデルの解除を行います。
* もし入力モデルが登録されていなかった場合は、なにも起こりません。
*
* \param[in] model 解除モデルインスタンス
*
* \sa setInterStopMode(), entryInterModel(), clearInterModel()
*/
void deleteInterModel(fk_Model *model);
//! 干渉自動停止モデル初期化関数
/*!
* 干渉自動停止モード用に登録されていた全てのモデルを解除します。
*
* \sa setInterStopMode(), entryInterModel(), deleteInterModel()
*/
void clearInterModel(void);
///@}
#ifndef FK_DOXYGEN_USER_PROCESS
// カスタムテクスチャ描画用エントリポイント
virtual void connectShader(unsigned int) {};
void SetTreeDelMode(bool);
void TreePrint(void);
void setSize(double);
double getSize(void) const;
void setWidth(double);
double getWidth(void) const;
#endif
private:
std::unique_ptr<Member> _m;
void EntryTree(void);
void DeleteTree(void);
fk_TreeData * GetTreeData(fk_Model *);
bool IsBSInter(fk_Model *);
bool IsAABBInter(fk_Model *);
bool IsOBBInter(fk_Model *);
bool IsCapsuleInter(fk_Model *);
void PreMove(void);
void PostMove(void);
static std::unique_ptr<fk_Tree> modelTree;
static unsigned int globalModelID;
};
}
#endif // !__FK_MODEL_HEADER__
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* - Neither the name of the copyright holders nor the names
* of its contributors may be used to endorse or promote
* products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved.
*
* 本ソフトウェアおよびソースコードのライセンスは、基本的に
* 「修正 BSD ライセンス」に従います。以下にその詳細を記します。
*
* ソースコード形式かバイナリ形式か、変更するかしないかを問わず、
* 以下の条件を満たす場合に限り、再頒布および使用が許可されます。
*
* - ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、
* および下記免責条項を含めること。
*
* - バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の
* 資料に、上記の著作権表示、本条件一覧、および下記免責条項を
* 含めること。
*
* - 書面による特別の許可なしに、本ソフトウェアから派生した製品の
* 宣伝または販売促進に、本ソフトウェアの著作権者の名前または
* コントリビューターの名前を使用してはならない。
*
* 本ソフトウェアは、著作権者およびコントリビューターによって「現
* 状のまま」提供されており、明示黙示を問わず、商業的な使用可能性、
* および特定の目的に対する適合性に関す暗黙の保証も含め、またそれ
* に限定されない、いかなる保証もないものとします。著作権者もコン
* トリビューターも、事由のいかんを問わず、損害発生の原因いかんを
* 問わず、かつ責任の根拠が契約であるか厳格責任であるか(過失その
* 他の)不法行為であるかを問わず、仮にそのような損害が発生する可
* 能性を知らされていたとしても、本ソフトウェアの使用によって発生
* した(代替品または代用サービスの調達、使用の喪失、データの喪失、
* 利益の喪失、業務の中断も含め、またそれに限定されない)直接損害、
* 間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害に
* ついて、一切責任を負わないものとします。
*
****************************************************************************/
|
Friday, 11 December 2009
mental ray_Adding glow to the window glass
The above image was produced whilst at GMJ Design Ltd
In our latest book, we have covered a number of ways of emulating light without the need of creating a physical light.
Production companies often adopt similar methods to reduce the rendering times and retain the overall quality.
It is worth pointing out that the usage of Ambient Occlusion(i.e. AO) as a separate pass or/and directly from Max is utterly imperative for the final shot.
The following exercise will take you through another unique methodology of achieving similar results with reduced rendering times:
Another quick way of emulating “glow”/"light" on windows, is to in fact enable the glow function on the glass panes themselves.
To do this, simply go to the main material parameters, under the "refraction" group.
1-Reduce the transparency to about 0.9 to prevent the surface from being fully transparent.
2-To add a bit of blur to the transparency, decrease the glossiness to about 0.78. Note that, these values may vary depending on one’s camera angle...and the level of transparency/blurriness intended.
3-Next,change the colour swatch from white to a warm yellow.
Also, the "fast (interpolate)" function, can be enabled for quick and fast results, as the glossiness and its samples can often slow down the renders.However,it may create artifacts.
4-Pan down to the "self illumination (glow)" parameters and enable the "self illumination (glow)" function.
5-Under the "luminance" group, change it from "unitless" to "physical units: cd/m2)". Also, pick and choose any relevant bitmap (i.e. photo) that has a prominent light source.
Note: The "unitless" function often creates artifacts on glossy reflections, therefore, to be avoided at all costs.
Depending on time in hand, one can set the glow to generate light, or not, through the FG, by checking the "illuminates the scene (when using fg)" function.
...and... “...let there be light...”!!!
The final rendered image below was achieved using this technique. I hope you like it.
I hope you have found this post interesting.
Also check this new article in this Blog:
3D Realism:Practical & Easy Workflows
|
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "game/module.h"
#include "collection/vector.h"
#include "string/stringTable.h"
Module* Module::smFirst;
//-----------------------------------------------------------------------------
bool Module::_constrainedToComeBefore(Module* module, Mode mode)
{
if (module == this)
return false;
for (Dependency* dependency = _getDependencies(mode);
dependency != NULL; dependency = dependency->mNext)
{
Module* depModule = dependency->mModule;
if (!depModule)
{
depModule = EngineModuleManager::findModule(dependency->mModuleName);
if (!depModule)
{
// Module does not exist. Only emit a warning here so that modules
// can be omitted from a link without requiring the module definitions
// to be adapted.
//Platform::outputDebugString("[EngineModuleManager] Module of depends on module '%s' which does not exist");
continue;
}
dependency->mModule = depModule;
}
if (dependency->mType == DependencyBefore)
{
if (depModule == module
|| depModule->_constrainedToComeBefore(module, mode))
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
bool Module::_constrainedToComeAfter(Module* module, Mode mode)
{
if (module == this)
return false;
for (Dependency* dependency = _getDependencies(mode);
dependency != NULL; dependency = dependency->mNext)
{
Module* depModule = dependency->mModule;
if (!depModule)
{
depModule = EngineModuleManager::findModule(dependency->mModuleName);
if (!depModule)
{
// Module does not exist. Only emit a warning here so that modules
// can be omitted from a link without requiring the module definitions
// to be adapted.
//Platform::outputDebugString("[EngineModuleManager] Module of depends on module '%s' which does not exist");
continue;
}
dependency->mModule = depModule;
}
if (dependency->mType == DependencyAfter)
{
if (depModule == module
|| depModule->_constrainedToComeAfter(module, mode))
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void EngineModuleManager::_printModuleList(Vector< Module* >& moduleList)
{
//Platform::outputDebugString(_moduleListToString(moduleList));
}
//-----------------------------------------------------------------------------
void EngineModuleManager::_insertIntoModuleList(Module::Mode mode, Vector< Module* >& moduleList, Module* module)
{
// If this module is being overridden, switch over to
// the module overriding it.
Module* override;
do
{
override = _findOverrideFor(module);
if (override)
module = override;
} while (override != NULL);
// If we are already on the list, return.
if (_getIndexOfModuleInList(moduleList, module) != -1)
return;
// If we don't have dependencies, just push the module
// to the back of the list.
if (!module->_getDependencies(mode))
{
moduleList.push_back(module);
return;
}
// First make sure that all 'after' dependencies are in the list.
for (Module::Dependency* dependency = module->_getDependencies(mode);
dependency != NULL; dependency = dependency->mNext)
{
if (dependency->mType != Module::DependencyAfter)
continue;
dependency->mModule = findModule(dependency->mModuleName);
if (!dependency->mModule)
continue; // Allow modules to not exist.
if (_getIndexOfModuleInList(moduleList, dependency->mModule) == -1)
_insertIntoModuleList(mode, moduleList, dependency->mModule);
}
AssertFatal(_getIndexOfModuleInList(moduleList, module) == -1,
avar("EngineModuleManager::_insertModuleIntoList - Cycle in 'after' %s dependency chain of '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName()));
// Now add the module itself.
const U32 numModules = moduleList.size();
for (U32 i = 0; i < numModules; ++i)
{
const bool thisBeforeCurrent = module->_constrainedToComeBefore(moduleList[i], mode);
const bool currentAfterThis = moduleList[i]->_constrainedToComeAfter(module, mode);
AssertFatal(!(thisBeforeCurrent && currentAfterThis),
avar("EngineModuleManager::_insertModuleIntoList - Ambiguous %s placement of module '%s' relative to '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(), moduleList[i]->getName()));
// If no contraints relate us to this module,
// push us one more position back in the line.
if (!thisBeforeCurrent && !currentAfterThis)
continue;
// If this module is contrained to come before the
// module at our current position but that module does
// not actually have dependencies of its own, make sure
// that module is at the back of the module list so that
// if we have more dependencies, it will not prevent us
// from correctly positioning us in relation to them.
if (thisBeforeCurrent && !moduleList[i]->_getDependencies(mode) && i != numModules - 1)
{
Module* depModule = moduleList[i];
moduleList.erase(i);
--i;
moduleList.push_back(depModule);
continue;
}
// Try the reverse constraint with all remaining modules in the list.
// If there is one for which we have one, then the placement of this
// module is ambiguous.
for (U32 n = i + 1; n < numModules; ++n)
AssertFatal(!(moduleList[n]->_constrainedToComeBefore(module, mode)
|| module->_constrainedToComeAfter(moduleList[n], mode)),
avar("EngineModuleManager::_insertModuleIntoList - Ambiguous %s constraint on module '%s' to come before '%s' yet after '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(),
moduleList[i]->getName(),
moduleList[n]->getName()));
// Add the module at this position.
moduleList.push_back(module);
return;
}
moduleList.push_back(module);
}
//-----------------------------------------------------------------------------
Module* EngineModuleManager::_findOverrideFor(Module* module)
{
const char* name = module->getName();
for (Module* ptr = Module::smFirst; ptr != NULL; ptr = ptr->mNext)
for (Module::Override* override = ptr->mOverrides; override != NULL; override = override->mNext)
if (dStricmp(override->mModuleName, name) == 0)
return ptr;
return NULL;
}
//-----------------------------------------------------------------------------
S32 EngineModuleManager::_getIndexOfModuleInList(Vector< Module* >& moduleList, Module* module)
{
const U32 numModules = moduleList.size();
for (U32 i = 0; i < numModules; ++i)
if (moduleList[i] == module)
return i;
return -1;
}
//-----------------------------------------------------------------------------
S32 EngineModuleManager::_getIndexOfModuleInList(Vector< Module* >& moduleList, const char* moduleName)
{
const U32 numModules = moduleList.size();
for (U32 i = 0; i < numModules; ++i)
if (dStricmp(moduleList[i]->getName(), moduleName) == 0)
return i;
return -1;
}
//-----------------------------------------------------------------------------
void EngineModuleManager::_createModuleList(Module::Mode mode, Vector< Module* >& moduleList)
{
for (Module* module = Module::smFirst; module != NULL; module = module->mNext)
_insertIntoModuleList(mode, moduleList, module);
}
//-----------------------------------------------------------------------------
void EngineModuleManager::initializeSystem()
{
Vector< Module* > modules;
_createModuleList(Module::ModeInitialize, modules);
const U32 numModules = modules.size();
for (U32 i = 0; i < numModules; ++i)
{
Module* module = modules[i];
if (!module->mIsInitialized)
{
module->initialize();
module->mIsInitialized = true;
}
}
}
//-----------------------------------------------------------------------------
void EngineModuleManager::shutdownSystem()
{
Vector< Module* > modules;
_createModuleList(Module::ModeShutdown, modules);
const U32 numModules = modules.size();
for (U32 i = 0; i < numModules; ++i)
{
if (modules[i]->mIsInitialized)
{
modules[i]->shutdown();
modules[i]->mIsInitialized = false;
}
}
}
//-----------------------------------------------------------------------------
Module* EngineModuleManager::findModule(const char* name)
{
for (Module* module = Module::smFirst; module != NULL; module = module->mNext)
if (dStricmp(module->getName(), name) == 0)
return module;
return NULL;
}
|
/**
* Copyright 2017-2020 Stefan Ascher
*
* 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.
*/
#pragma once
#include <unordered_map>
#include <vector>
#include <sa/Assert.h>
#include <sa/TypeName.h>
#include <sa/StringHash.h>
class Subsystems
{
private:
class _Subsystem
{ };
template<typename T>
class _SubystemWrapper : public _Subsystem
{
public:
std::unique_ptr<T> object_;
explicit _SubystemWrapper(T* object) :
object_(std::move(object))
{ }
};
std::unordered_map<size_t, std::unique_ptr<_Subsystem>> systems_;
/// The creation order of the systems
std::vector<size_t> order_;
public:
Subsystems() = default;
~Subsystems() noexcept
{
Clear();
}
void Clear() noexcept
{
// Reverse delete subsystems
std::vector<size_t>::reverse_iterator itr;
for (itr = order_.rbegin(); itr != order_.rend(); ++itr)
{
auto sit = systems_.find(*itr);
ASSERT(sit != systems_.end());
(*sit).second.reset();
}
systems_.clear();
order_.clear();
}
template<typename T, typename... _CArgs>
bool CreateSubsystem(_CArgs&&... _Args)
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i != systems_.end())
return false;
T* system = new T(std::forward<_CArgs>(_Args)...);
if (system)
{
if (RegisterSubsystem<T>(system))
return true;
delete system;
}
return false;
}
/// Takes ownership of the object
template<typename T>
bool RegisterSubsystem(T* system)
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i == systems_.end())
{
systems_[key] = std::make_unique<_SubystemWrapper<T>>(system);
order_.push_back(key);
return true;
}
return false;
}
template<typename T>
void RemoveSubsystem()
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i != systems_.end())
{
auto it = std::find_if(order_.begin(), order_.end(), [&](size_t current) -> bool {
return current == key;
});
ASSERT(it != order_.end());
order_.erase(it);
systems_.erase(i);
}
}
template<typename T>
T* GetSubsystem()
{
static constexpr size_t key = sa::StringHash(sa::TypeName<T>::Get());
const auto i = systems_.find(key);
if (i != systems_.end())
{
const auto wrapper = static_cast<_SubystemWrapper<T>*>((*i).second.get());
return wrapper->object_.get();
}
return nullptr;
}
static Subsystems Instance;
};
template<typename T>
inline T* GetSubsystem()
{
return Subsystems::Instance.GetSubsystem<T>();
}
|
You Baby's Development
After many weeks of anticipation and preparation, your baby is here! Or maybe not — only 5% of women deliver on their estimated due dates, and many first-time mothers find themselves waiting up to 2 weeks after their due date for their baby to arrive.
A baby born at 40 weeks weighs, on average, about 7 pounds, 4 ounces (3,300 grams) and measures about 20 inches (51 cm). Don't expect your baby to look like the Gerber baby right off the bat — newborns often have heads temporarily misshapen from the birth canal and may be covered with vernix and blood. Your baby's skin may have skin discolorations, dry patches, and rashes — these many variations are completely normal.
Because of the presence of your hormones in your baby's system, your baby's genitals (scrotum in boys and labia in girls) may appear enlarged. Your baby, whether a boy or a girl, may even secrete milk from the tiny nipples. This should disappear in a few days and is completely normal.
Right after birth, your health care provider will suction mucus out of your baby's mouth and nose, and you'll hear that long-awaited first cry. Your baby may then be placed on your stomach, and the umbilical cord will be cut — often by the baby's dad, if he chooses to do the honors! A series of quick screening tests, such as the Apgar score, will be performed to assess your baby's responsiveness and vital signs, and he or she will be weighed and measured. If your pregnancy was high risk, or if a cesarean section was necessary, a neonatologist (a doctor who specializes in newborn intensive care) will be present at your delivery to take care of your baby right away. If your baby needs any special care to adjust to life outside the womb, it will be given — and then your newborn will be placed in your waiting arms.
This week you'll experience the moment you've been anticipating — your introduction to your baby! Before you can meet your baby, though, you have to go through labor and delivery. You may have learned about the three stages of birth in your prenatal classes. The first stage of labor works to thin and stretch your cervix by contracting your uterus at regular intervals. The second stage of labor is when you push your baby into the vaginal canal and out of your body. The third and final stage of labor is when you deliver the placenta.
If you don't go into labor within a week of your due date, your health care provider may recommend you receive a nonstress test, which monitors fetal heart rate and movement to be sure that the baby is receiving adequate oxygen and that the nervous system is responding. Talk to your health care provider to find out more about this test.
Sometimes mother nature may need a little coaxing. If your labor isn't progressing, or if your health or your baby's health requires it, your health care provider may induce labor by artificially rupturing the membranes or by administering the hormone oxytocin or other medications. If your pregnancy is high risk, or if there are any other potential complications, you may require a cesarean section delivery.
Some women know ahead of time that they will be delivering via cesarean section and are able to schedule their baby's "birth day" well in advance. If you're one of them, you've probably been able to prepare yourself emotionally and mentally for the birth — which can help to lessen the feelings of disappointment that many mothers who are unable to deliver vaginally experience. But even if you have to undergo a cesarean section that wasn't planned, rest assured that you'll still be able to bond with your baby. It might not be the birth experience you imagined, but your beautiful newborn has arrived nonetheless. The months of waiting are over!
Good luck with your baby!
|
#ifndef RxData_Cache_SelectionSubject_h_IsIncluded
#define RxData_Cache_SelectionSubject_h_IsIncluded
#include"RxData/CommonDefines.h"
#include"RxData/cache/observer/SelectionListener.h"
namespace RxData
{
template <typename DATA>
class SelectionSubject
: public SelectionObserver<DATA>
, public BaseLib::Concurrent::Observable<SelectionObserver<DATA> >
{
public:
SelectionSubject()
: selectionObserverSignaller_(new Signaller1<void, DATA>())
{}
virtual ~SelectionSubject()
{}
/**
* Called when an object enters the Selection.
*
* @param data
*/
virtual void OnObjectIn(DATA data)
{
selectionObserverSignaller_->template Signal<SelectionObserver<DATA> >(data, &SelectionObserver<DATA>::OnObjectIn);
}
/**
* Called when an object exits the Selection.
*
* @param data
*/
virtual void OnObjectOut(DATA data)
{
selectionObserverSignaller_->template Signal<SelectionObserver<DATA> >(data, &SelectionObserver<DATA>::OnObjectOut);
}
/**
* Called when the contents of an object belonging to the Selection changes
*
* @param data
*/
virtual void OnObjectModified(DATA data)
{
selectionObserverSignaller_->template Signal<SelectionObserver<DATA> >(data, &SelectionObserver<DATA>::OnObjectModified);
}
/**
* Set the SelectionListener (set_listener), that will be triggered when the composition of the
* selection changes, as well as if the members are modified. set_listener returns the
* previously set listener if any; set_listener called with a NULL parameter discards the current
* listener.
*/
virtual SlotHolder::Ptr Connect(SelectionObserver<DATA> *observer)
{
selectionObserverSignaller_->template Connect<SelectionObserver<DATA> >(observer, &SelectionObserver<DATA>::OnObjectIn);
selectionObserverSignaller_->template Connect<SelectionObserver<DATA> >(observer, &SelectionObserver<DATA>::OnObjectOut);
return selectionObserverSignaller_->template Connect<SelectionObserver<DATA> >(observer, &SelectionObserver<DATA>::OnObjectModified);
}
virtual bool Disconnect(SelectionObserver<DATA> *observer)
{
return selectionObserverSignaller_->template Disconnect<SelectionObserver<DATA> >(observer);
}
virtual void DisconnectAll()
{
selectionObserverSignaller_->DisconnectAll();
}
private:
/**
* The SelectionListener is activated when the composition of the Selection is modified as well
* as when one of its members is modified. A member can be considered as modified, either
* when the member is modified or when that member or one of its contained objects is modified
* (depending on the value of concerns_contained). Modifications in the Selection are considered
* with respect to the state of the Selection last time is was examined, for instance:
*
* - at each incoming updates processing, if auto_refresh is TRUE.
* - at each explicit call to refresh, if auto_refresh is FALSE.
*/
typename Signaller1<void, DATA>::Ptr selectionObserverSignaller_;
};
}
#endif
|
#include <iostream>
#include <vector>
#include "inputHandler.hpp"
#include "game.hpp"
InputHandler* InputHandler::instance_ = 0;
void InputHandler::initialiseJoysticks() {
if( SDL_WasInit( SDL_INIT_JOYSTICK ) == 0 ) {
SDL_InitSubSystem( SDL_INIT_JOYSTICK );
}
if( SDL_NumJoysticks() > 0 ) {
for( int i = 0; i < SDL_NumJoysticks(); i++ ) {
SDL_Joystick* joy = SDL_JoystickOpen( i );
if( joy == NULL ) {
std::cout << SDL_GetError() << std::endl;
} else {
joysticks_.push_back( joy );
//m_joystickValues.push_back( std::make_pair( new Vector2D( 0, 0 ), new Vector2D( 0, 0 ) ) );
for( int b = 0; b < SDL_JoystickNumButtons( joy ); b++ ) {
buttonStates_.push_back( false );
}
}
}
SDL_JoystickEventState( SDL_ENABLE );
joysticksInitialised_ = true;
} else {
joysticksInitialised_ = false;
}
std::cout << "Initialised " << joysticks_.size() << " joystick(s)" << std::endl;
}
void InputHandler::onKeyDown() {
keystates_ = SDL_GetKeyboardState( NULL );
if( keystates_[ SDL_SCANCODE_ESCAPE ] == 1 ) {
TheGame::Instance() -> quit();
}
}
void InputHandler::onKeyUp() {
keystates_ = SDL_GetKeyboardState( NULL );
}
bool InputHandler::isKeyDown( SDL_Scancode key ) {
if( keystates_ != 0 ) {
if( keystates_[key] == 1 ) {
return true;
} else {
return false;
}
}
return false;
}
bool InputHandler::isPressed( int button ) {
if( button == 0 ) {
if( keystates_[ SDL_SCANCODE_RIGHT ] == 1 || keystates_[ SDL_SCANCODE_L ] == 1 || currentHat_ == SDL_HAT_RIGHT || currentHat_ == SDL_HAT_RIGHTUP || currentHat_ == SDL_HAT_RIGHTDOWN ) {
return true;
}
} else if( button == 1 ) {
if( keystates_[ SDL_SCANCODE_LEFT ] == 1 || keystates_[ SDL_SCANCODE_H ] == 1 || currentHat_ == SDL_HAT_LEFT || currentHat_ == SDL_HAT_LEFTUP || currentHat_ == SDL_HAT_LEFTDOWN ) {
return true;
}
} else if( button == 2 ) {
if( keystates_[ SDL_SCANCODE_UP ] == 1 || keystates_[ SDL_SCANCODE_K ] == 1 || currentHat_ == SDL_HAT_UP || currentHat_ == SDL_HAT_LEFTUP || currentHat_ == SDL_HAT_RIGHTUP ) {
return true;
}
} else if( button == 3 ) {
if( keystates_[ SDL_SCANCODE_DOWN ] == 1 || keystates_[ SDL_SCANCODE_J ] == 1 || currentHat_ == SDL_HAT_DOWN || currentHat_ == SDL_HAT_LEFTDOWN || currentHat_ == SDL_HAT_RIGHTDOWN ) {
return true;
}
} else if( button == 4 ) { // fire
if( keystates_[ SDL_SCANCODE_F ] == 1 ) {
return true;
}
if( gamepadsInitialised_ ) {
if( buttonStates_[ 2 ] ) {
return true;
}
}
} else if( button == 5 ) { // roll
if( keystates_[ SDL_SCANCODE_D ] == 1 ) {
return true;
}
} else if( button == 6 ) { // bomb
if( keystates_[ SDL_SCANCODE_S ] ) {
return true;
}
}
/*else if( button == 7 ) { // start
if( keystates_[ SDL_SCANCODE_S ] == 1 ) {
return true;
}
} else if( button == 8 ) { // quit
if( keystates_[ SDL_SCANCODE_Q ] == 1 ) {
return true;
}
} else if( button == 9 ) { // ok
if( keystates_[ SDL_SCANCODE_O ] == 1 ) {
return true;
}
} else if( button == 10 ) { // back
if( keystates_[ SDL_SCANCODE_BACKSPACE ] == 1 ) {
return true;
}
}*/
return false;
}
void InputHandler::onHatMotion( SDL_Event &event ) {
if( !joysticksInitialised_ ) {
return;
}
for( unsigned int i = 0; i < joysticks_.size(); i++ ) {
currentHat_ = SDL_JoystickGetHat( joysticks_[i], 0 );
}
}
void InputHandler::update() {
SDL_Event event;
while( SDL_PollEvent( &event ) ) {
switch( event.type ) {
case SDL_QUIT:
TheGame::Instance() -> quit(); break;
case SDL_KEYDOWN:
onKeyDown(); break;
case SDL_KEYUP:
onKeyUp(); break;
case SDL_JOYHATMOTION:
onHatMotion( event ); break;
case SDL_JOYBUTTONDOWN:
whichOne_ = event.jaxis.which;
buttonStates_[ event.jbutton.button ] = true;
//printf( "%d pressed\n", event.jbutton.button );
break;
case SDL_JOYBUTTONUP:
whichOne_ = event.jaxis.which;
buttonStates_[ event.jbutton.button ] = false;
break;
default:
break;
}
}
}
void InputHandler::clean() {
if( gamepadsInitialised_ ) {
for( int i = 0; i < SDL_NumJoysticks(); i++ ) {
SDL_JoystickClose( joysticks_[i] );
}
}
}
|
// Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHAPS_SLOT_POLICY_H_
#define CHAPS_SLOT_POLICY_H_
#include <string>
#include "pkcs11/cryptoki.h"
namespace chaps {
class Object;
// SlotPolicy encapsulates policies for a PKCS #11 token.
class SlotPolicy {
public:
virtual ~SlotPolicy() = default;
virtual bool IsObjectClassAllowedForNewObject(
CK_OBJECT_CLASS object_class) = 0;
virtual bool IsObjectClassAllowedForImportedObject(
CK_OBJECT_CLASS object_class) = 0;
};
} // namespace chaps
#endif // CHAPS_SLOT_POLICY_H_
|
/******************************************************************************
* SSD1327ZB - Library for SSD1327ZB OLed Driver based on libohiboard
* Copyright (C) 2018 Alessio Socci & Marco Giammarini
*
* Authors:
* Alessio Socci <[email protected]>
* Marco Giammarini <[email protected]>
*
* 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 "ssd1327zb.h"
#include <string.h>
#define SSD1327ZB_CMD_SETCOLUMNADDR 0x15
#define SSD1327ZB_CMD_SETROWADDR 0x75
#define SSD1327ZB_CMD_SETCONTRAST 0x81
#define SSD1327ZB_CMD_SEGMENTREMAP 0xA0 /**< Set Display remap */
#define SSD1327ZB_CMD_STARTLINE 0xA1 /**< Set start line */
#define SSD1327ZB_CMD_DISPLAYNORMAL 0xA4
#define SSD1327ZB_CMD_DISPLAYALLON 0xA5 /**< Entire Display is ON with gray scale level to GS15 */
#define SSD1327ZB_CMD_DISPLAYALLOFF 0xA6 /**< Entire Display is OFF with gray scale level to GS0 */
#define SSD1327ZB_CMD_DISPLAYINVERSE 0xA7
#define SSD1327ZB_CMD_DISPLAYOFF 0xAE
#define SSD1327ZB_CMD_DISPLAYON 0xAF
#define SSD1327ZB_REMAP_COLUMN 0x01 /**< Enable column address remap */
#define SSD1327ZB_REMAP_NIBBLE 0x02 /**< Enable nibble remap */
#define SSD1327ZB_REMAP_ADDR_INCREMENT 0x04 /**< Enable vertical address increment */
#define SSD1327ZB_REMAP_COM 0x10 /**< Enable COM remap */
#define SSD1327ZB_REMAP_ODDEVEN_COM 0x40 /**< Enable COM split odd/even */
#define SSD1327ZB_write(value) do { \
((value & 0x01) > 0) ? Gpio_set(dev->gdl.d0) : Gpio_clear(dev->gdl.d0); \
((value & 0x02) > 0) ? Gpio_set(dev->gdl.d1) : Gpio_clear(dev->gdl.d1); \
((value & 0x04) > 0) ? Gpio_set(dev->gdl.d2) : Gpio_clear(dev->gdl.d2); \
((value & 0x08) > 0) ? Gpio_set(dev->gdl.d3) : Gpio_clear(dev->gdl.d3); \
((value & 0x10) > 0) ? Gpio_set(dev->gdl.d4) : Gpio_clear(dev->gdl.d4); \
((value & 0x20) > 0) ? Gpio_set(dev->gdl.d5) : Gpio_clear(dev->gdl.d5); \
((value & 0x40) > 0) ? Gpio_set(dev->gdl.d6) : Gpio_clear(dev->gdl.d6); \
((value & 0x80) > 0) ? Gpio_set(dev->gdl.d7) : Gpio_clear(dev->gdl.d7); \
} while (0)
static void SSD1327ZB_sendCommand (SSD1327ZB_Device* dev, uint8_t command)
{
#if defined WARCOMEB_GDL_PARALLEL
Gpio_set(dev->gdl.rd);
Gpio_clear(dev->gdl.cs);
Gpio_set(dev->gdl.wr);
// Is command message
Gpio_clear(dev->gdl.dc);
// Enable writing
Gpio_clear(dev->gdl.wr);
SSD1327ZB_write(command);
// Restore write pin
Gpio_set(dev->gdl.wr);
// Disable device
Gpio_set(dev->gdl.cs);
#elif defined WARCOMEB_GDL_I2C
#elif defined WARCOMEB_GDL_SPI
#endif
}
static void SSD1327ZB_sendData (SSD1327ZB_Device* dev, uint8_t value)
{
#if defined WARCOMEB_GDL_PARALLEL
Gpio_set(dev->gdl.rd);
Gpio_clear(dev->gdl.cs);
Gpio_set(dev->gdl.wr);
// is data message
Gpio_set(dev->gdl.dc);
// Enable writing
Gpio_clear(dev->gdl.wr);
SSD1327ZB_write(value);
// Restore write pin
Gpio_set(dev->gdl.wr);
// Disable device
Gpio_set(dev->gdl.cs);
#elif defined WARCOMEB_GDL_I2C
#elif defined WARCOMEB_GDL_SPI
#endif
}
/**
* The function set the current position into the display. The values are related to
* the internal buffer of the display.
*
* @param[in] dev The handle of the device
* @param[in] xStart The x start position into the buffer
* @param[in] xStop The x stop position into the buffer
* @param[in] yStart The y start position into the buffer
* @param[in] yStop The y stop position into the buffer
* @return Return an error if the requested position is wrong,
* GDL_ERRORS_OK otherwise.
*/
static GDL_Errors SSD1327ZB_setBufferPosition (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t xStop,
uint8_t yStart,
uint8_t yStop)
{
if ((xStart >= dev->gdl.width) || (yStart >= dev->gdl.height))
return GDL_ERRORS_WRONG_POSITION;
if ((xStop >= dev->gdl.width) || (yStop >= dev->gdl.height))
return GDL_ERRORS_WRONG_POSITION;
// Set column address
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SETCOLUMNADDR);
SSD1327ZB_sendCommand(dev,xStart/2);
SSD1327ZB_sendCommand(dev,xStop/2);
// Set row address
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SETROWADDR);
SSD1327ZB_sendCommand(dev,yStart);
SSD1327ZB_sendCommand(dev,yStop);
return GDL_ERRORS_OK;
}
void SSD1327ZB_init (SSD1327ZB_Device* dev)
{
// Set the device model
dev->gdl.model = GDL_MODELTYPE_SSD1327ZB;
// Save display size
dev->gdl.height = WARCOMEB_SSD1327ZB_HEIGHT;
dev->gdl.width = WARCOMEB_SSD1327ZB_WIDTH;
// Save default font size
dev->gdl.fontSize = 1;
dev->gdl.useCustomFont = FALSE;
// Save callback for drawing pixel
dev->gdl.drawPixel = SSD1327ZB_drawPixel;
// memset(dev->buffer, 0x00, WARCOMEB_SSD1327ZB_BUFFERDIMENSION);
#if defined WARCOMEB_GDL_PARALLEL
Gpio_config(dev->gdl.d0,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d1,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d2,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d3,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d4,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d5,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d6,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.d7,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.rd,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.dc,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.rs,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.cs,GPIO_PINS_OUTPUT);
Gpio_config(dev->gdl.wr,GPIO_PINS_OUTPUT);
Gpio_set(dev->gdl.dc);
Gpio_set(dev->gdl.rd);
Gpio_set(dev->gdl.wr);
Gpio_set(dev->gdl.cs);
Gpio_set(dev->gdl.rs);
#elif defined WARCOMEB_GDL_I2C
#elif defined WARCOMEB_GDL_SPI
#endif
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_DISPLAYON);
// Wait 100ms after on
dev->gdl.delayTime(100);
// Set display to normal
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_DISPLAYNORMAL);
// Select segment re-map, COM scan direction, COM hardware configuration and
// de-select level
// They depend on producer choice
switch (dev->gdl.product)
{
case SSD1327ZB_PRODUCT_RAYSTAR_REX128128B:
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SEGMENTREMAP);
SSD1327ZB_sendCommand(dev,SSD1327ZB_REMAP_ODDEVEN_COM);
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_STARTLINE);
SSD1327ZB_sendCommand(dev,0);
break;
}
}
GDL_Errors SSD1327ZB_drawPixel (SSD1327ZB_Device* dev,
uint8_t xPos,
uint8_t yPos,
SSD1327ZB_GrayScale color)
{
if ((xPos >= dev->gdl.width) || (yPos >= dev->gdl.height))
return GDL_ERRORS_WRONG_POSITION;
uint16_t pos = ((uint16_t) xPos/2) + ((uint16_t) yPos*(dev->gdl.width/2));
if (xPos%2)
dev->buffer[pos] = (((color << 4) & 0xF0) | (dev->buffer[pos] & 0x0F));
else
dev->buffer[pos] = ((color & 0x0F) | (dev->buffer[pos] & 0xF0));
return GDL_ERRORS_OK;
}
void SSD1327ZB_setContrast (SSD1327ZB_Device* dev, uint8_t value)
{
SSD1327ZB_sendCommand(dev,SSD1327ZB_CMD_SETCONTRAST);
SSD1327ZB_sendCommand(dev,value);
}
void SSD1327ZB_flush (SSD1327ZB_Device* dev)
{
// Set the cursor to the starting point of the display
// Print all the buffer
SSD1327ZB_setBufferPosition(dev,0,dev->gdl.width-1,0,dev->gdl.height-1);
for (uint16_t i = 0; i < WARCOMEB_SSD1327ZB_BUFFERDIMENSION; i++)
{
SSD1327ZB_sendData(dev,dev->buffer[i]);
}
}
void SSD1327ZB_flushPart (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t xStop,
uint8_t yStart,
uint8_t yStop)
{
// Set the part of the display where change the pixels
GDL_Errors error = SSD1327ZB_setBufferPosition(dev,xStart,xStop,yStart,yStop);
if (error != GDL_ERRORS_OK) return;
uint8_t xStartHalf = xStart/2;
uint8_t xStopHalf = xStop/2;
uint8_t widthHalf = dev->gdl.width/2;
for (uint8_t i = yStart; i <= yStop; i++)
{
for (uint8_t j = xStartHalf; j <= xStopHalf; j++)
{
SSD1327ZB_sendData(dev,dev->buffer[j + (i * widthHalf)]);
}
}
}
void SSD1327ZB_clear (SSD1327ZB_Device* dev)
{
// Reset memory buffer
memset(dev->buffer, 0x00, WARCOMEB_SSD1327ZB_BUFFERDIMENSION);
// Flush the new buffer
SSD1327ZB_flush(dev);
}
void SSD1327ZB_drawLine (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t yStart,
uint8_t xStop,
uint8_t yStop,
SSD1327ZB_GrayScale color)
{
GDL_drawLine(&(dev->gdl),xStart,yStart,xStop,yStop,(uint8_t)color);
}
void SSD1327ZB_drawHLine (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t yStart,
uint8_t width,
SSD1327ZB_GrayScale color)
{
SSD1327ZB_drawLine(dev,xStart,yStart,xStart+width,yStart,color);
}
void SSD1327ZB_drawVLine (SSD1327ZB_Device* dev,
uint8_t xStart,
uint8_t yStart,
uint8_t height,
SSD1327ZB_GrayScale color)
{
SSD1327ZB_drawLine(dev,xStart,yStart,xStart,yStart+height,color);
}
void SSD1327ZB_drawRectangle (SSD1327ZB_Device* dev,
uint16_t xStart,
uint16_t yStart,
uint16_t width,
uint16_t height,
SSD1327ZB_GrayScale color,
bool isFill)
{
GDL_drawRectangle(&(dev->gdl),xStart,yStart,width,height,(uint8_t)color,isFill);
}
GDL_Errors SSD1327ZB_drawChar (SSD1327ZB_Device* dev,
uint16_t xPos,
uint16_t yPos,
uint8_t c,
SSD1327ZB_GrayScale color,
SSD1327ZB_GrayScale background,
uint8_t size)
{
return GDL_drawChar(&(dev->gdl),xPos,yPos,c,(uint8_t)color,(uint8_t)background,size);
}
GDL_Errors SSD1327ZB_drawPicture (SSD1327ZB_Device* dev,
uint16_t xPos,
uint16_t yPos,
uint16_t width,
uint16_t height,
const uint8_t* picture,
GDL_PictureType pixelType)
{
if ((pixelType != GDL_PICTURETYPE_1BIT) && (pixelType != GDL_PICTURETYPE_4BIT))
return GDL_ERRORS_WRONG_VALUE;
return GDL_drawPicture(&(dev->gdl),xPos,yPos,width,height,picture,pixelType);
}
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef HDST_SHADER_H
#define HDST_SHADER_H
#include "pxr/pxr.h"
#include "pxr/imaging/hdSt/api.h"
#include "pxr/imaging/hf/perfLog.h"
#include "pxr/imaging/hd/shader.h"
#include <boost/shared_ptr.hpp>
PXR_NAMESPACE_OPEN_SCOPE
typedef boost::shared_ptr<class HdSurfaceShader> HdSurfaceShaderSharedPtr;
class HdStShader final: public HdShader {
public:
HF_MALLOC_TAG_NEW("new HdStShader");
HDST_API
HdStShader(SdfPath const& id);
HDST_API
virtual ~HdStShader();
/// Synchronizes state from the delegate to this object.
HDST_API
virtual void Sync(HdSceneDelegate *sceneDelegate,
HdRenderParam *renderParam,
HdDirtyBits *dirtyBits) override;
/// Accessor for tasks to get the parameter cached in this sprim object.
/// Don't communicate back to scene delegate within this function.
HDST_API
virtual VtValue Get(TfToken const &token) const override;
/// Returns the minimal set of dirty bits to place in the
/// change tracker for use in the first sync of this prim.
/// Typically this would be all dirty bits.
HDST_API
virtual HdDirtyBits GetInitialDirtyBitsMask() const override;
/// Causes the shader to be reloaded.
HDST_API
virtual void Reload() override;
/// Obtains the render delegate specific representation of the shader.
/// XXX: Should not be virtual.
HDST_API
virtual HdShaderCodeSharedPtr GetShaderCode() const override;
/// Replaces the shader code object with an externally created one
/// Used to set the fallback shader for prim.
/// This class takes ownership of the passed in object.
HDST_API
void SetSurfaceShader(HdSurfaceShaderSharedPtr &shaderCode);
private:
HdSurfaceShaderSharedPtr _surfaceShader;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // HDST_SHADER_H
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#ifndef TENCENTCLOUD_EB_V20210416_MODEL_LISTEVENTBUSESRESPONSE_H_
#define TENCENTCLOUD_EB_V20210416_MODEL_LISTEVENTBUSESRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/eb/v20210416/model/EventBus.h>
namespace TencentCloud
{
namespace Eb
{
namespace V20210416
{
namespace Model
{
/**
* ListEventBuses response structure.
*/
class ListEventBusesResponse : public AbstractModel
{
public:
ListEventBusesResponse();
~ListEventBusesResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取Event bus information
* @return EventBuses Event bus information
*/
std::vector<EventBus> GetEventBuses() const;
/**
* 判断参数 EventBuses 是否已赋值
* @return EventBuses 是否已赋值
*/
bool EventBusesHasBeenSet() const;
/**
* 获取Total number of event buses
* @return TotalCount Total number of event buses
*/
int64_t GetTotalCount() const;
/**
* 判断参数 TotalCount 是否已赋值
* @return TotalCount 是否已赋值
*/
bool TotalCountHasBeenSet() const;
private:
/**
* Event bus information
*/
std::vector<EventBus> m_eventBuses;
bool m_eventBusesHasBeenSet;
/**
* Total number of event buses
*/
int64_t m_totalCount;
bool m_totalCountHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_EB_V20210416_MODEL_LISTEVENTBUSESRESPONSE_H_
|
/*!
* @copyright
* Copyright (c) 2015-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 "agent-framework/module/constants/compute.hpp"
#include "agent-framework/module/constants/chassis.hpp"
#include "agent-framework/module/constants/pnc.hpp"
#include "agent-framework/module/constants/regular_expressions.hpp"
#include "agent-framework/module/model/attributes/attributes.hpp"
#include "agent-framework/module/requests/validation/common.hpp"
#include "agent-framework/module/requests/validation/json_check_type.hpp"
#include "agent-framework/module/common_components.hpp"
#include "agent-framework/validators/procedure_validator.hpp"
using namespace agent_framework::exceptions;
using namespace agent_framework::model::attribute;
namespace agent_framework {
namespace model {
namespace requests {
namespace validation {
void CommonValidator::validate_set_drive_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Drive::ASSET_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::Drive::ERASED == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::Drive::SECURELY_ERASE == name) {
// value does not matter
}
else if (literals::Drive::OEM == name) {
Oem::from_json(value);
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_processor_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Fpga::ERASED == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::Fpga::SECURELY_ERASE == name) {
// value does not matter
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_chassis_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Chassis::ASSET_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::Chassis::RESET == name) {
check_enum<enums::ResetType>(value, name, "agent-framework");
}
else if (literals::Chassis::GEO_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::Chassis::LOCATION_ID == name) {
check_string(value, name, "agent-framework");
}
else if (literals::Chassis::OEM == name) {
Oem::from_json(value);
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_system_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::System::BOOT_OVERRIDE == name) {
check_enum<enums::BootOverride>(value, name, "agent-framework");
}
else if (literals::System::BOOT_OVERRIDE_MODE == name) {
check_enum<enums::BootOverrideMode>(value, name, "agent-framework");
}
else if (literals::System::BOOT_OVERRIDE_TARGET == name) {
check_enum<enums::BootOverrideTarget>(value, name, "agent-framework");
}
else if (literals::System::RESET == name) {
check_enum<enums::ResetType>(value, name, "agent-framework");
}
else if (literals::System::ASSET_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::System::USER_MODE_ENABLED == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::System::RESET_CONFIGURATION == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::System::ERASE_CONFIGURATION_KEYS == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::System::OEM == name) {
Oem::from_json(value);
}
else if (literals::System::CURRENT_PERFORMANCE_CONFIGURATION == name) {
check_number(value, name, "agent-framework");
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_manager_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Manager::RESET == name) {
check_enum<enums::ResetType>(value, name, "agent-framework");
}
else if (literals::Manager::FACTORY_DEFAULTS == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::Manager::PACKAGE_URL == name) {
check_string(value, name, "agent-framework");
}
else if (literals::Manager::OEM == name) {
Oem::from_json(value);
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_pcie_device_attributes(const Attributes& attributes) {
jsonrpc::ProcedureValidator validator(
jsonrpc::PARAMS_BY_NAME,
literals::PcieDevice::ASSET_TAG, VALID_OPTIONAL(VALID_NULLABLE(VALID_JSON_STRING)),
literals::PcieDevice::OEM, VALID_OPTIONAL(VALID_JSON_OBJECT),
nullptr
);
validator.validate(attributes.to_json());
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_endpoint_attributes(const Attributes& attributes) {
static jsonrpc::ProcedureValidator validator(
jsonrpc::PARAMS_BY_NAME,
literals::Endpoint::USERNAME, VALID_NULLABLE(VALID_REGEX(literals::regex::Common::NO_WHITESPACE_STRING)),
literals::Endpoint::PASSWORD, VALID_OPTIONAL(VALID_NULLABLE(VALID_REGEX(literals::regex::Common::NO_WHITESPACE_STRING))),
nullptr
);
validator.validate(attributes.to_json());
log_debug("agent-framework", "Request validation passed.");
}
}
}
}
}
|
#pragma once
#include <string>
#include <vector>
namespace sf {
class Color;
}
bool equal_enough(float a, float b) noexcept;
struct GradientColor {
float pos;
float r, g, b;
bool operator==(const float p) const noexcept { return equal_enough(p, pos); }
bool operator<(const GradientColor& col) const noexcept { return pos < col.pos; }
};
struct Gradient {
std::string name_;
std::vector<GradientColor> colors;
Gradient() : name_{""} {}
Gradient(std::string name) : name_{name} {}
};
Gradient load_gradient(const std::string& name);
sf::Color color_from_gradient(const Gradient& gradient, const float pos) noexcept;
std::vector<Gradient> load_available_gradients();
|
Oil of Empires is a Codex Entry featured in Battlefield 1. It is unlocked by completing Operation Oil of Empires in the Operations gamemode.
Oil of Empires Codex Entry
When the modern combustion engine was first developed in the 1880s, few realized how much it would change the global economy. But over the next decades, in every shipyard it became obvious that oil power was superior to coal in every way.
A motor could now reach full power in 30 minutes instead of six hours, it required a fraction of the men to run it, and a ship's range increased fourfold. Even before the war the Dreadnoughts of the mighty British navy had begun to convert to oil power, but oil was to be found far from British shores.
Much of the British war effort in the Middle East was to protect British oil supplies, the Suez Canal transport route, and to take or destroy the Berlin-Baghdad railway, Germany's oil supply line to the Ottoman Empire. As the war progressed, and the airplane, the car, the submarine and the tank were produced in greater and greater numbers, oil became ever more important.
Ad blocker interference detected!
|
Tuesday, May 18, 2010
"Enough Money"
"Enough Money"
Thomas Sowell
Tuesday, May 18, 2010
The French Revolution began arbitrary executions among the hereditary aristocracy, but ended up arbitrarily executing all sorts of other people, including eventually even leaders of the Revolution itself, such as Robespierre.
Very similar patterns appeared in the Bolshevik Revolution, in the rise of the Nazis and in numerous other times and places, where expanded and arbitrary powers were put into the hands of politicians-- and were used against the population as a whole.
Both men were selling a product that others were also selling, but more people chose to buy theirs. Those people would not have voluntarily continued to pay their hard-earned money for Rockefeller's oil or Gates' software if what they received was not worth more to them than what they paid.
The fortunes that the sellers amassed were not a deduction from the buyers' wealth. Buyers and sellers both gained from these transactions or the transactions wouldn't have continued.
Ida Tarbell's famous muckraking book, "History of the Standard Oil Company," said that Rockefeller "should have been satisfied" with the money he had acquired by 1870, implying greed in his continued efforts to increase the size and profitability of Standard Oil. But would the public have been better off or worse off if Rockefeller had retired in 1870?
One of the crucial facts left out of Ida Tarbell's book was that Rockefeller's improvements in the oil industry brought down the price of oil to a fraction of what it had been before.
As just one example, oil was first shipped in barrels, which is why we still measure oil in terms of the number of barrels today, even though oil is seldom-- if ever-- actually shipped in barrels any more. John D. Rockefeller shipped his oil in railroad tank cars, reducing transportation costs, among other costs that he found ways of reducing.
Would the public have been better off if older and more costly methods of producing, processing and shipping oil had continued to be used, leading to prices far higher than necessary?
Apparently Rockefeller himself decided at some point that he had enough money, and then donated enough of it to create a world-class university from day one-- the University of Chicago-- as well as donating to innumerable other philanthropic projects.
But that is wholly different from having politicians make such decisions for other people. Politicians who take on that role stifle economic progress and drain away other people's money, in order to hand out goodies that will help get themselves re-elected. Some people call that "social justice," even when it is anti-social politics.
To read another article by Thomas Sowell, click here.
Children and Finances
Rebecca Hagelin
Tuesday, May 18, 2010
In a recent survey on personal finances, only 27 percent of parents surveyed said they feel well informed about managing household finances. Fewer than half believe they are good role models for their children regarding saving and spending.
Yet, 94 percent of students say their parents are their primary teachers on financial matters.
Oops. We have a problem. We've totally messed up our finances, and no one is teaching our children how to unravel it.
Our national debt is unsustainable. Our government is promising programs and services that it can't possibly deliver, but that will bankrupt our children in trying. Add that to the reality that today's teenagers haven't the slightest clue about how to manage their personal finances, and you realize that the future of America's economy is not just bleak, but headed for a melt down.
The economic problems we face are obvious. The question is: What are we going to do about them? While a strong alliance of policy experts and Tea Party activists around the nation join hands to try and reverse out-of-control government spending, we also need to be educating the younger generation about how to be personally fiscally responsible.
A good first step is to teach children and teens how to handle their money, rather than allowing their money to handle them.
Helping them understand how to be wise stewards is a gift that can free them from the emptiness that comes with materialism, the depression that comes with debt, and replace them with the peace that comes with financial stability and the fulfillment that comes with philanthropy.
The Bible addresses economic issues with surprising frequency. As a matter of fact, as Crown Financial Ministries points out, there are 2.350 verses on money and stewardship, making it "second to the subject of love as the most discussed subject in the Bible. In fact, two-thirds of the parables Jesus taught are about money, possessions, and stewardship."
Regardless of your faith, the wisdom of this all-time best seller is undeniable - and incredibly applicable to our world today. Here are a few examples of profound principles you and your children can start memorizing - and putting in to action - right away:
- "The wise man saves for the future, but the foolish man spends whatever he gets." (Proverbs 21:20)
- "The wicked borrow and never repay but the godly are generous givers." (Psalm 37:21)
- "The rich rules over the poor, and the borrower becomes the lender's slave." (Proverbs 22:7)
-"A good man leaves an inheritance to his children's children." (Proverbs 13:22)
-"Steady plodding brings prosperity." (Proverbs 21:5)
One of the very best resources to use in teaching your children how to practice the principles above comes from Crown Ministries at www.Crown.org . Entitled, Discovering God's Way of Handling Money Teen Study, this 10 week study guide "is designed to practically help teens create habits that will set them on a lifelong journey of handling money responsibly." If you need personal help to get your own finances in order Crown also offers free local counseling for you with what they call a Money Map Coach.
And then there is the great Dave Ramsey - noted author, radio host and "all around" genius on finances. Dave has a fabulous website filled with great tips, and he also offers one of the most life-changing programs for teens I've ever seen. It's called, Generation Change, and you can order it at www.DaveRamsey.com . Dave also offers curriculum for educators at the elementary, high school, and colleges levels. His turn-key programs are engaging and comprehensive, and will build a sound economic foundation in the lives of our young people. They are designed to be used in a school or home setting, and are exactly what we need to build hope, and financial security, into the lives of the next generation of adults.
If enough young people learn sound financial principles, perhaps they will also one day run government in a way that promotes prosperity and personal responsibility too.
1 comment:
Anonymous said...
I agree that Dave Ramsey's teachings are wonderful for teenagers, and probably college students as well. This is when the teaching needs to happen. His teachings, which are far from genius, are nonetheless very practical and down to earth. He has effectively packaged very basic common sense. I don't know that it's possible to teach common sense, but it's definitely worth a try!
|
/****************************************************************************
* Render Radiance Scaling *
* Meshlab's plugin *
* *
* Copyright(C) 2010 *
* Vergne Romain, Dumas Olivier *
* INRIA - Institut Nationnal de Recherche en Informatique et Automatique *
* *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#include "gpuProgram.h"
#include <iostream>
using namespace std;
GPUProgram::GPUProgram(GPUShader* vs,GPUShader* fs,GPUShader *gs,
int inputGeometry,int outputGeometry,int outVertices)
: _vs(vs),
_fs(fs),
_gs(gs),
_inputGeometry(inputGeometry),
_outputGeometry(outputGeometry),
_outVertices(outVertices) {
_programId = glCreateProgram();
setGeometryParameters(_inputGeometry,_outputGeometry,_outVertices);
attachAndLink();
}
GPUProgram::GPUProgram(const string &vsFile,
const string &fsFile,
const string &gsFile,
int inputGeometry,
int outputGeometry,
int outVertices)
:_inputGeometry(inputGeometry),
_outputGeometry(outputGeometry),
_outVertices(outVertices) {
_vs = _fs = _gs = NULL;
if(vsFile!="")
_vs = new GPUShader(VERT,vsFile);
if(fsFile!="")
_fs = new GPUShader(FRAG,fsFile);
if(gsFile!="")
_gs = new GPUShader(GEOM,gsFile);
_programId = glCreateProgram();
setGeometryParameters(_inputGeometry,_outputGeometry,_outVertices);
attachAndLink();
}
GPUProgram::~GPUProgram() {
detach();
if(_vs!=NULL) {
delete _vs;
}
if(_fs!=NULL) {
delete _fs;
}
if(_gs!=NULL) {
delete _gs;
}
glDeleteProgram(_programId);
}
void GPUProgram::setGeometryParameters(int inputGeometry,int outputGeometry,int outVertices) {
#ifdef GL_EXT_geometry_shader4
if(GL_EXT_geometry_shader4 && _gs!=NULL && _gs->id()!=0) {
glProgramParameteriEXT(_programId,GL_GEOMETRY_INPUT_TYPE_EXT,inputGeometry);
glProgramParameteriEXT(_programId,GL_GEOMETRY_OUTPUT_TYPE_EXT,outputGeometry);
glProgramParameteriEXT(_programId,GL_GEOMETRY_VERTICES_OUT_EXT,outVertices);
}
#endif
}
void GPUProgram::attach() {
if(_vs!=NULL) {
glAttachShader(_programId,_vs->id());
}
if(_fs!=NULL) {
glAttachShader(_programId,_fs->id());
}
if(_gs!=NULL) {
glAttachShader(_programId,_gs->id());
}
}
void GPUProgram::detach() {
if(_vs!=NULL) {
glDetachShader(_programId,_vs->id());
}
if(_fs!=NULL) {
glDetachShader(_programId,_fs->id());
}
if(_gs!=NULL) {
glDetachShader(_programId,_gs->id());
}
}
bool GPUProgram::link() {
int linked = 1;
glLinkProgram(_programId);
glGetObjectParameterivARB(_programId,GL_OBJECT_LINK_STATUS_ARB,&linked);
if(linked)
return true;
return false;
}
bool GPUProgram::attachAndLink() {
attach();
return link();
}
void GPUProgram::reload() {
detach();
bool allOk = true;
if(_vs!=NULL) {
allOk = allOk && _vs->loadAndCompile();
}
if(_fs!=NULL) {
allOk = allOk && _fs->loadAndCompile();
}
if(_gs!=NULL) {
allOk = allOk && _gs->loadAndCompile();
}
if(!allOk){
std::cout << "reload fail, maybe missing file" << std::endl;
}
setGeometryParameters(_inputGeometry,_outputGeometry,_outVertices);
attachAndLink();
// reload uniforms
for(map<string,GLint>::iterator i=_uniformLocations.begin();i!=_uniformLocations.end();i++) {
_uniformLocations[(*i).first] = glGetUniformLocation(_programId,(*i).first.c_str());
}
// reload attributes
for(map<string,GLint>::iterator i=_attributeLocations.begin();i!=_attributeLocations.end();i++) {
_uniformLocations[(*i).first] = glGetAttribLocation(_programId,(*i).first.c_str());
}
// free textures
_textures.clear();
}
void GPUProgram::addUniform(const string &uniformName) {
GLint location = glGetUniformLocation(_programId,uniformName.c_str());
_uniformLocations[uniformName] = location;
}
void GPUProgram::addAttribute(const string &attributeName) {
GLint location = glGetAttribLocation(_programId,attributeName.c_str());
_attributeLocations[attributeName] = location;
}
bool GPUProgram::haveShaderOfType(SHADER_TYPE type) {
if(type==VERT)
return _vs!=NULL;
if(type==FRAG)
return _fs!=NULL;
if(type==GEOM)
return _gs!=NULL;
cout << "Warning : unknown type !" << endl;
return false;
}
string GPUProgram::filename(SHADER_TYPE type) {
if(type==VERT && _vs!=NULL)
return _vs->filename();
if(type==FRAG && _fs!=NULL)
return _fs->filename();
if(type==GEOM && _gs!=NULL)
return _gs->filename();
cout << "Warning : unknown type !" << endl;
return "";
}
|
/*
Copyright (C) 2013-present The DataCentric Authors.
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 <dc/declare.hpp>
#include <dc/types/record/value_type.hpp>
#include <dot/noda_time/local_date_util.hpp>
#include <dot/noda_time/local_time_util.hpp>
#include <dot/noda_time/local_minute_util.hpp>
#include <dot/noda_time/local_date_time_util.hpp>
#include <dot/system/enum.hpp>
#include <dot/system/object.hpp>
#include <dot/system/string.hpp>
#include <dot/system/type.hpp>
#include <dot/noda_time/local_date_time.hpp>
#include <dot/noda_time/local_minute.hpp>
namespace dc
{
/// Variant type can hold any atomic value or be empty.
class DC_CLASS Variant
{
typedef Variant self;
private: // FIELDS
dot::Object value_;
public: // CONSTRUCTORS
/// Default constructor.
Variant();
/// Create from Object of supported types, error message if argument type is unsupported.
Variant(dot::Object value);
public: // PROPERTIES
/// Type of the value held by the Variant.
ValueType get_value_type()
{
if (value_ == nullptr)
return ValueType::empty_type;
dot::Type value_type = value_->get_type();
// The purpose of this check is to ensure that Variant holds only one of the supported types
if (value_type->equals(dot::typeof<dot::String>())) return ValueType::string_type;
if (value_type->equals(dot::typeof<double>())) return ValueType::double_type;
if (value_type->equals(dot::typeof<bool>())) return ValueType::bool_type;
if (value_type->equals(dot::typeof<int>())) return ValueType::int_type;
if (value_type->equals(dot::typeof<int64_t>())) return ValueType::long_type;
if (value_type->equals(dot::typeof<dot::LocalDate>())) return ValueType::local_date_type;
if (value_type->equals(dot::typeof<dot::LocalTime>())) return ValueType::local_time_type;
if (value_type->equals(dot::typeof<dot::LocalMinute>())) return ValueType::local_minute_type;
if (value_type->equals(dot::typeof<dot::LocalDateTime>())) return ValueType::local_date_time_type;
if (value_type->is_enum()) return ValueType::enum_type;
// Error message if any other type, should normally not get to here
throw dot::Exception(get_wrong_type_error_message(value_));
}
/// Value held by the Variant, which may be null.
dot::Object get_value()
{
return value_;
}
public: // METHODS
/// Check if the Variant is equal to default constructed Object.
bool is_empty();
/// Provides alternate serialization of certain value types.
dot::String to_string();
/// Hash code is zero for null objects.
size_t hash_code();
/// Variants are equal when both types and values are equal.
/// Comparison of doubles is performed with roundoff tolerance.
bool equals(const Variant& other);
public: // OPERATORS
/// Variants are equal when both types and values are equal.
/// Comparison of doubles is performed with roundoff tolerance.
bool operator==(const Variant& other);
/// Variants are equal when both types and values are equal.
/// Comparison of doubles is performed with roundoff tolerance.
bool operator!=(const Variant& other);
public: // STATIC
static Variant parse(ValueType value_type, dot::String value);
template <class T>
static Variant parse(dot::String value)
{
if (dot::String::is_null_or_empty(value))
{
// Empty value
return Variant();
}
dot::Type value_type = dot::typeof<T>();
// The purpose of this check is to ensure that Variant holds only one of the supported types
if (value_type->equals(dot::typeof<dot::String>())) return Variant(value);
if (value_type->equals(dot::typeof<double>())) return Variant(dot::DoubleImpl::parse(value));
if (value_type->equals(dot::typeof<bool>())) return Variant(dot::BoolImpl::parse(value));
if (value_type->equals(dot::typeof<int>())) return Variant(dot::IntImpl::parse(value));
if (value_type->equals(dot::typeof<int64_t>())) return Variant(dot::LongImpl::parse(value));
if (value_type->equals(dot::typeof<dot::LocalDate>())) return Variant(dot::LocalDateUtil::parse(value));
if (value_type->equals(dot::typeof<dot::LocalTime>())) return Variant(dot::LocalTimeUtil::parse(value));
if (value_type->equals(dot::typeof<dot::LocalMinute>())) return Variant(dot::LocalMinuteUtil::parse(value));
if (value_type->equals(dot::typeof<dot::LocalDateTime>())) return Variant(dot::LocalDateTimeUtil::parse(value));
if (value_type->is_enum()) return Variant(dot::EnumBase::parse(value_type, value));
// Error message if any other type
throw dot::Exception(get_wrong_type_error_message(T()));
}
private: // PRIVATE
static dot::String get_wrong_type_error_message(dot::Object value);
};
}
|
Tiền tệ:
Đầu Cơ Kamui Black
Hardness *Hard→Soft
Popular hardness barometer.
The hardness is tested with static hardness measurement.
This measurement does not take time and speed of acceleration into considaration.
Elasticity *High→Low
Elasticity stands for bouncing force generated when a tip impacts a cue ball with the speed of acceleration.
When elastlicity of a tip gets higher, the contact time of the tip and cue ball gets longer so that you can have more spin on a cue ball and feel bouncy shot feeling.
On the other hand, the contact time is shrotend as elasticity gets lower. So that you can get more solid shot feeling.
Giá: 0 VND
Số lượng:
|
By Irene Klotz
CAPE CANAVERAL, Florida (Reuters) - Despite searing daytime temperatures, Mercury, the planet closest to the sun, has ice and frozen organic materials inside permanently shadowed craters in its north pole, NASA scientists said on Thursday.
Earth-based telescopes have been compiling evidence for ice on Mercury for 20 years, but the finding of organics was a surprise, say researchers with NASA's MESSENGER spacecraft, the first probe to orbit Mercury.
Both ice and organic materials, which are similar to tar or coal, were believed to have been delivered millions of years ago by comets and asteroids crashing into the planet.
"It's not something we expected to see, but then of course you realize it kind of makes sense because we see this in other places," such as icy bodies in the outer solar system and in the nuclei of comets, planetary scientist David Paige, with the University of California, Los Angeles, told Reuters.
Unlike NASA's Mars rover Curiosity, which will be sampling rocks and soils to look for organic materials directly, the MESSENGER probe bounces laser beams, counts particles, measures gamma rays and collects other data remotely from orbit.
The discoveries of ice and organics, painstakingly pieced together for more than a year, are based on computer models, laboratory experiments and deduction, not direct analysis.
"The explanation that seems to fit all the data is that it's organic material," said lead MESSENGER scientist Sean Solomon, with Columbia University in New York.
Added Paige, "It's not just a crazy hypothesis. No one has got anything else that seems to fit all the observations better."
Scientists believe the organic material, which is about twice as dark as most of Mercury's surface, was mixed in with comet- or asteroid-delivered ice eons ago.
The ice vaporized, then re-solidified where it was colder, leaving dark deposits on the surface. Radar imagery shows the dark patches subside at the coldest parts of the crater, where ice can exist on the surface.
The areas where the dark patches are seen are not cold enough for surface ice without the overlying layer of what is believed to be organics.
So remote was the idea of organics on Mercury that MESSENGER got a relatively easy pass by NASA's planetary protection protocols that were established to minimize the chance of contaminating any indigenous life-potential material with hitchhiking microbes from Earth.
Scientists don't believe Mercury is or was suitable for ancient life, but the discovery of organics on an inner planet of the solar system may shed light on how life got started on Earth and how life may evolve on planets beyond the solar system.
"Finding a place in the inner solar system where some of these same ingredients that may have led to life on Earth are preserved for us is really exciting," Paige said.
MESSENGER, which stands for Mercury Surface, Space Environment, Geochemistry and Ranging, is due to complete its two-year mission at Mercury in March.
Scientists are seeking NASA funding to continue operations for at least part of a third year. The probe will remain in Mercury's orbit until the planet's gravity eventually causes it to crash onto the surface.
Whether the discovery of organics now prompts NASA to select a crash zone rather than leave it up to chance remains to be seen. Microbes that may have hitched a ride on MESSENGER likely have been killed off by the harsh radiation environment at Mercury.
The research is published in this week's edition of the journal Science.
(Editing by Kevin Gray and Vicki Allen)
|
What level of LabVIEW user are you—a developer, engineer, or architect? Is it even important?
Absolutely. These categories make it easy for NI to tailor helpful resources to your individual needs. By visiting the LabVIEW Skills Guide, you can see what defines these levels and which trainings or guides we recommend each use to help them develop successful applications faster.
Here are a few examples of skills you can learn from the latest guide:
For Technicians or Basic Developers
- Troubleshoot and debug LabVIEW code
- Apply key LabVIEW elements for relating data (such as arrays, clusters, and typedefs)
- Apply design patterns and templates
For Software Engineers
- Optimize reuse of existing code for your projects
- Design, implement, document, and test code modules for each task
- Derive a task list and high-level flowchart to guide design and development
For Software Architects
- Analyze, critique, and improve the architecture of a LabVIEW application
- Optimize code and resources to effectively reduce development time and costs
- Design an application using object-oriented design principles
Best of all, many of these resources are free or available at a discounted price for students. Questions? Post your comments below and we’ll follow up on them personally.
|
/** @file
@brief Header
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// 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.
#ifndef INCLUDED_ConfigParams_h_GUID_22101CEF_879B_4781_2733_F5F7AE4E3633
#define INCLUDED_ConfigParams_h_GUID_22101CEF_879B_4781_2733_F5F7AE4E3633
// Internal Includes
#include "BlobParams.h"
// Library/third-party includes
// - none
// Standard includes
#include <cstdint>
#include <string>
namespace osvr {
namespace vbtracker {
static const double BaseMeasurementVariance = 3.0;
struct IMUInputParams {
std::string path =
"/com_osvr_Multiserver/OSVRHackerDevKit0/semantic/hmd";
/// Should we use the IMU orientation data for calibration even if
/// useOrientation is false?
bool calibrateAnyway = false;
/// Should orientation reports be used once calibration completes?
bool useOrientation = true;
/// units: rad^2
double orientationVariance = 1.0e-7;
std::int32_t orientationMicrosecondsOffset = 0;
/// Should angular velocity reports be used once calibration completes?
bool useAngularVelocity = true;
/// units: (rad/sec)^2
double angularVelocityVariance = 1.0e-1;
std::int32_t angularVelocityMicrosecondsOffset = 0;
};
struct TuningParams {
TuningParams();
double noveltyPenaltyBase;
double distanceMeasVarianceBase;
double distanceMeasVarianceIntercept;
};
/// If you add an entry here, must also update both
/// getConfigStringForTargetSet and AllBuiltInTargetSets in
/// ConfigurationParser.h
enum class BuiltInTargetSets { HDK1xChassis, HDK2Chassis };
/// General configuration parameters
struct ConfigParams {
/// Not intended to be manually configurable - enabled when doing things
/// like running an optimization algorithm so some things like a debug
/// view might need to change.
bool performingOptimization = false;
/// For optimization usage.
bool silent = false;
/// For recording tuning data - whether we should record the raw blob
/// data.
bool logRawBlobs = false;
/// For recording tuning data - whether we should record the data from
/// just the usable LEDs each frame after they're associated.
bool logUsableLeds = false;
TuningParams tuning;
/// Parameters specific to the blob-detection step of the algorithm
BlobParams blobParams;
/// Parameters specific to the edge hole based LED extraction algorithm.
EdgeHoleParams extractParams;
/// When using hard-coded target sets, which one to use.
BuiltInTargetSets targetSet = BuiltInTargetSets::HDK1xChassis;
/// Should we have the tracking thread update the reporting vector for
/// every (IMU) message, instead of waiting/buffering for a few
/// milliseconds between updates?
bool continuousReporting = true;
/// Should we open the camera in high-gain mode?
bool highGain = true;
/// Seconds beyond the current time to predict, using the Kalman state.
double additionalPrediction = 0.;
/// Max residual, in meters at the expected XY plane of the beacon in
/// space, for a beacon before applying a variance penalty.
double maxResidual = 0.03631354168383816;
/// Initial beacon error for autocalibration (units: m^2).
/// 0 effectively turns off beacon auto-calib.
/// This is a variance number, so std deviation squared, but it's
/// pretty likely to be between 0 and 1, so the variance will be smaller
/// than the standard deviation.
double initialBeaconError = 1e-7; // 0.001;
/// Maximum distance a blob can move, in multiples of its previous
/// "keypoint diameter", and still be considered the same blob.
double blobMoveThreshold = 3.5;
/// Whether to show the debug windows and debug messages.
bool debug = false;
/// How many threads to let OpenCV use. Set to 0 or less to let OpenCV
/// decide (that is, not set an explicit preference)
int numThreads = 1;
/// This is the autocorrelation kernel of the process noise. The first
/// three elements correspond to position, the second three to
/// incremental rotation.
double processNoiseAutocorrelation[6];
/// The value used in exponential decay of linear velocity: it's the
/// proportion of that velocity remaining at the end of 1 second. Thus,
/// smaller = faster decay/higher damping. In range [0, 1]
double linearVelocityDecayCoefficient = 0.9040551503451977;
/// The value used in exponential decay of angular velocity: it's the
/// proportion of that velocity remaining at the end of 1 second. Thus,
/// smaller = faster decay/higher damping. In range [0, 1]
double angularVelocityDecayCoefficient = 0.8945437897688864;
/// The value used in an additional exponential decay of linear velocity
/// when we've lost sight of all beacons, to quickly attenuate coasting.
/// it's the proportion of that velocity remaining at the end of 1
/// second. Thus, smaller = faster decay/higher damping. In range [0, 1]
double noBeaconLinearVelocityDecayCoefficient = 0.005878868009089861;
/// The measurement variance (units: m^2) is included in the plugin
/// along with the coordinates of the beacons. Some beacons are
/// observed with higher variance than others, due to known difficulties
/// in tracking them, etc. However, for testing you may fine-tine the
/// measurement variances globally by scaling them here.
double measurementVarianceScaleFactor = 1.5;
/// Whether the tracking algorithm internally adjusts beacon positions
/// based on the centroid of the input beacon positions.
bool offsetToCentroid = false;
/// Manual beacon offset (in m) - only really sensible if you only have
/// one target, only used if offsetToCentroid is false.
double manualBeaconOffset[3];
/// If true, this will replace the two sensors with just a single one,
/// including the beacons at the back of the head "rigidly" as a part of
/// it. If true, recommend offsetToCentroid = false, and
/// manualBeaconOffset to be 0, 0, -75.
bool includeRearPanel = true;
/// Head circumference at the head strap, in cm - 55.75 is our estimate
/// for an average based on some hat sizing guidelines. Only matters if
/// includeRearPanel is true.
double headCircumference = 55.75;
/// This is the distance fron the front of the head to the origin of the
/// front sensor coordinate system in the Z axis, in mm.
/// This is a rough estimate - the origin of the coordinate system is
/// roughly the flat part of the hard plastic.
double headToFrontBeaconOriginDistance = 0;
/// This used to be different than the other beacons, but now it's
/// mostly the same.
double backPanelMeasurementError = BaseMeasurementVariance;
/// This is the process-model noise in the beacon-auto-calibration, in
/// mm^2/s. Not fully accurate, since it only gets applied when a beacon
/// gets used for a measurement, but it should be enough to keep beacons
/// from converging in a bad local minimum.
double beaconProcessNoise = 1.e-19;
/// This is the multiplicative penalty applied to the variance of
/// measurements with a "bad" residual
double highResidualVariancePenalty = 7.513691210865344;
/// When true, will stream debug info (variance, pixel measurement,
/// pixel residual) on up to the first 34 beacons of your first sensor
/// as analogs.
bool streamBeaconDebugInfo = false;
/// This should be the ratio of lengths of sides that you'll permit to
/// be filtered in. Larger side first, please.
///
/// Not currently being used.
float boundingBoxFilterRatio = 5.f / 4.f;
/// This should be a negative number - it's the largest the z component
/// of the camera-space LED emission vector is permitted to be and still
/// be used in estimation. acos(this number) is the maximum angle away
/// from pointing at the camera that we'll accept an LED pointing.
double maxZComponent = -0.3;
/// Should we attempt to skip bright-mode LEDs? The alternative is to
/// just give them slightly higher variance.
bool shouldSkipBrightLeds = false;
/// If shouldSkipBrightLeds is false, we use this value as a factor to
/// increase the measurement variance of bright LEDs, to account for the
/// fact that they are less accurate because they tend to refract
/// through surrounding materials, etc.
double brightLedVariancePenalty = 28.32749811268542;
/// If this option is set to true, then while some of the pattern
/// identifier is run each frame, an "early-out" will be taken if the
/// blob/LED already has a valid (non-negative) ID assigned to it. This
/// can help keep IDs on hard to identify blobs, but it can also persist
/// errors longer. That's why it's an option.
///
/// Defaulting to off because it adds some jitter for some reason.
bool blobsKeepIdentity = false;
/// Extra verbose developer debugging messages
bool extraVerbose = false;
/// If non-empty, the file to load (or save to) for calibration data.
/// Only make sense for a single target.
std::string calibrationFile = "";
/// IMU input-related parameters.
IMUInputParams imu;
/// x, y, z, with y up, all in meters.
double cameraPosition[3];
/// Whether we should adjust transforms to assume the camera looks along
/// the YZ plane in the +Z direction.
bool cameraIsForward = true;
/// Should we permit the whole system to enter Kalman mode? Not doing so
/// is usually a bad idea, unless you're doing something special like
/// development on the tracker itself...
bool permitKalman = true;
/// Time offset for the camera timestamp, in microseconds.
/// Default is measured on Windows 10 version 1511.
std::int32_t cameraMicrosecondsOffset = -27000;
/// Should we permit a reset to be "soft" (blended by a Kalman) rather
/// than a hard state setting, in certain conditions? Only available in
/// the Unified tracker.
bool softResets = false;
/// Soft reset data incorporation parameter: Positional variance scale -
/// multiplied by the square of the distance from the camera.
double softResetPositionVarianceScale = 1.e-1;
/// Soft reset data incorporation parameter: Orientation variance
double softResetOrientationVariance = 1.e0;
ConfigParams();
};
} // namespace vbtracker
} // namespace osvr
#endif // INCLUDED_ConfigParams_h_GUID_22101CEF_879B_4781_2733_F5F7AE4E3633
|
/*============================================================================
Copyright 2015 by:
Commonwealth Scientific and Industrial Research Organisation (CSIRO)
This file is licensed by CSIRO under the copy of the CSIRO Open Source
Software License Agreement (variation of the BSD / MIT License) included
with the file.
As a condition of this license, you agree that where you make any
adaptations, modifications, further developments, or additional features
available to CSIRO or the public in connection with your access to the
Software, you do so on the terms of the BSD 3-Clause License template,
a copy available at: http://opensource.org/licenses/BSD-3-Clause
For further information, contact the CSIRO Workspace Team:
[email protected]
This copyright notice must be included with all copies of the source code.
============================================================================*/
/*
Copyright (c) 2015, Stuart Mead - Risk Frontiers, Macquarie University
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
For further information, contact:
Stuart Mead
Risk Frontiers
Dept. of Environmental Sciences
Macquarie University
North Ryde NSW 2109
*/
#include <cassert>
#include <iostream>
#include <QString>
#include "Workspace/Application/LanguageUtils/streamqstring.h"
#include "Workspace/DataExecution/DataObjects/typedobject.h"
#include "Workspace/DataExecution/InputOutput/inputscalar.h"
#include "Workspace/DataExecution/InputOutput/inputarray.h"
#include "Workspace/DataExecution/InputOutput/output.h"
#include "Workspace/DataExecution/Operations/typedoperationfactory.h"
#include "Mesh/DataStructures/MeshModelInterface/meshmodelinterface.h"
#include "Mesh/DataStructures/MeshModelInterface/meshelementsinterface.h"
#include "Mesh/DataStructures/MeshModelInterface/meshnodesinterface.h"
#include "pointcloudplugin.h"
#include "mlssample.h"
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>
namespace CSIRO
{
using namespace Mesh;
using namespace DataExecution;
namespace PointCloud
{
/**
* \internal
*/
class MlsSampleImpl
{
// Allow string translation to work properly
Q_DECLARE_TR_FUNCTIONS(MlsSampleImpl)
public:
MlsSample& op_;
// Data objects
DataExecution::TypedObject< MeshModelInterface > dataMesh_;
DataExecution::TypedObject< bool > dataOMP_;
DataExecution::TypedObject< MeshModelInterface > dataOutputMesh_;
DataExecution::TypedObject< double > searchRadius_;
DataExecution::TypedObject< int > polyOrder_;
DataExecution::TypedObject< bool > polyFit_;
DataExecution::TypedObject< bool > upsample_;
DataExecution::TypedObject< double > upsampRadius_;
DataExecution::TypedObject< double > stepSize_;
// Inputs and outputs
DataExecution::InputScalar inputMesh_;
DataExecution::InputScalar inputOMP_;
DataExecution::InputScalar inputSearchRadius_;
DataExecution::InputScalar inputpolyOrder_;
DataExecution::InputScalar inputpolyFit_;
DataExecution::InputScalar inputupsample_;
DataExecution::InputScalar inputupsampRadius_;
DataExecution::InputScalar inputstepSize_;
DataExecution::Output outputMesh_;
MlsSampleImpl(MlsSample& op);
bool execute();
void logText(const QString& msg) { op_.logText(msg); }
};
/**
*
*/
MlsSampleImpl::MlsSampleImpl(MlsSample& op) :
op_(op),
dataMesh_(),
dataOMP_(false),
dataOutputMesh_(),
searchRadius_(2.0),
polyOrder_(2),
polyFit_(true),
upsample_(true),
upsampRadius_(3.0),
stepSize_(0.5),
inputMesh_("Points", dataMesh_, op_),
inputOMP_("Use OpenMP", dataOMP_, op_),
inputSearchRadius_("Search Radius", searchRadius_, op_),
inputpolyOrder_("Polynomial Order", polyOrder_, op_),
inputpolyFit_("Polynomial Fitting", polyFit_, op_),
inputupsample_("Upsampling enabled", upsample_, op_),
inputupsampRadius_("Upsampling radius", upsampRadius_, op_),
inputstepSize_("Upsampling step sizes", stepSize_, op_),
outputMesh_("Mesh Model", dataOutputMesh_, op_)
{
inputSearchRadius_.setDescription("Set the sphere radius that is to be used for determining the k-nearest neighbors used for fitting");
inputOMP_.setDescription("Enables OpenMP based computation, threads will be determined on the OMP_NUM_THREADS environment variable");
inputpolyOrder_.setDescription("Order of the polynomial to be fit, if polynomial fitting is true");
inputpolyFit_.setDescription("Approximate the surface and normal using a polynomial, if not, tangent estimation is used");
inputupsampRadius_.setDescription("Radius of the circle in the local point plan that will be sampled");
inputstepSize_.setDescription("Step size for the local plane upsampling");
}
/**
*
*/
bool MlsSampleImpl::execute()
{
MeshModelInterface& mesh = *dataMesh_;
MeshModelInterface& outputMesh = *dataOutputMesh_;
MeshNodesInterface& nodes = mesh.getNodes();
/* No rgb states in mls at the moment after GSOC 2014 might be different
if (!nodes.hasState("RGBA"))
{
std::cout << QString("ERROR: Nodes do not have RGBA state") + "\n";
return false;
}
NodeStateHandle inputRgba = nodes.getStateHandle("RGBA");
*/
outputMesh.clear();//Always clear outputmesh
MeshNodesInterface& outputNodes = outputMesh.getNodes();
//Kinect stuff
const NodeStateHandle* pixIdStateIn = 0;
const NodeStateHandle* textureSStateOut = 0;
const NodeStateHandle* textureTStateOut = 0;
if (nodes.hasState("pixId"))
{
pixIdStateIn = &nodes.getStateHandle("pixId");
textureSStateOut = &outputNodes.addState<double>("textureS", 0.0);
textureTStateOut = &outputNodes.addState<double>("textureT", 0.0);
}
//Add states for normal and curvature
const NodeStateHandle& normalStateOut = outputNodes.addState("normal", Vector3d(0,0,-1));
const NodeStateHandle& curvatureStateOut = outputNodes.addState<double>("curvature",0.0);
//Finish if input mesh is empty
if(nodes.size() == 0)
{
std::cout << QString("WARNING: Mesh has no nodes, returning successfully") + "\n";
return true;
}
//For each node add point to point cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
//pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_rgba (new pcl::PointCloud<pcl::PointXYZRGBA>);//RGBA states
MeshNodesInterface::const_iterator nIter = nodes.begin();
MeshNodesInterface::const_iterator end = nodes.end();
for(; nIter != end; ++nIter)
{
int rgba = 0;
Vector3d v = nodes.getPosition(*nIter);
//nodes.getState(*nIter,inputRgba,rgba);
pcl::PointXYZ p;
p.x = v.x;
p.y = v.y;
p.z = v.z;
//p.rgb = rgba;
cloud->push_back(pcl::PointXYZ(p));
}
std::cout << QString("Point cloud generated, has %1 points").arg(cloud->size()) + "\n";
// Create a KD-Tree
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
// Output has the PointNormal type in order to store the normals from mls
pcl::PointCloud<pcl::PointNormal> mls_cloud;
#ifdef _OPENMP
if (*dataOMP_)
{
// Init object (second point type is for the normals, even if unused)
pcl::MovingLeastSquaresOMP<pcl::PointXYZ, pcl::PointNormal> mls;
char * ompThreads;
ompThreads = getenv("OMP_NUM_THREADS");
if (ompThreads != NULL)
{
mls.setNumberOfThreads(atoi(ompThreads));
}
else {
std::cout << QString("WARNING: OMP selected, but OMP_NUM_THREADS not set - using automatic detection") + "\n";
}
//For time being, we will make sure we only calc normals, maybe not later.
mls.setComputeNormals(true);
//Set input parameters
mls.setInputCloud(cloud);
if (*polyFit_)
{
mls.setPolynomialFit(true);
mls.setPolynomialOrder(*polyOrder_);
}
mls.setSearchMethod(tree);
mls.setSearchRadius(*searchRadius_);
//Paramaters for upsampling
if (*upsample_)
{
mls.setUpsamplingMethod (pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal>::SAMPLE_LOCAL_PLANE);
mls.setUpsamplingRadius (*upsampRadius_);
mls.setUpsamplingStepSize (*stepSize_);
}
//Reconstruct
mls.process(mls_cloud);
}
else
#endif
{
// Init object (second point type is for the normals, even if unused)
pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls;
//For time being, we will make sure we only calc normals, maybe not later.
mls.setComputeNormals(true);
//Set input parameters
mls.setInputCloud(cloud);
if (*polyFit_)
{
mls.setPolynomialFit(true);
mls.setPolynomialOrder(*polyOrder_);
}
mls.setSearchMethod(tree);
mls.setSearchRadius(*searchRadius_);
//Paramaters for upsampling
if (*upsample_)
{
mls.setUpsamplingMethod (pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal>::SAMPLE_LOCAL_PLANE);
mls.setUpsamplingRadius (*upsampRadius_);
mls.setUpsamplingStepSize (*stepSize_);
}
//Reconstruct
mls.process(mls_cloud);
}
//Now add the filtered nodes to the output mesh model
int a = 0;
NodeStateHandle rgbahandle = outputNodes.addState("RGBA", a);
for (size_t i = 0; i < mls_cloud.points.size (); ++i)
{
Vector3d vo,no;
vo.x = mls_cloud.points[i].x;
vo.y = mls_cloud.points[i].y;
vo.z = mls_cloud.points[i].z;
no.x = mls_cloud.points[i].normal_x;
no.y = mls_cloud.points[i].normal_y;
no.z = mls_cloud.points[i].normal_z;
NodeHandle node = outputNodes.add(vo);
outputNodes.setState(node,normalStateOut,no);
outputNodes.setState(node,curvatureStateOut,mls_cloud.points[i].curvature);
//int alph = static_cast<int> (mls_cloud.points[i].rgb);
//outputNodes.setState(node,rgbahandle,alph);
}
return true;
}
/**
*
*/
MlsSample::MlsSample() :
DataExecution::Operation(
DataExecution::OperationFactoryTraits< MlsSample >::getInstance(),
tr("MLS sample local plane upsampling"))
{
pImpl_ = new MlsSampleImpl(*this);
}
/**
*
*/
MlsSample::~MlsSample()
{
delete pImpl_;
}
/**
*
*/
bool MlsSample::execute()
{
return pImpl_->execute();
}
}
}
using namespace CSIRO;
using namespace PointCloud;
DEFINE_WORKSPACE_OPERATION_FACTORY(MlsSample,
PointCloud::PointCloudPlugin::getInstance(),
DataExecution::Operation::tr("PointCloud/Upsampling"))
|
/******************************************************************************
*
* Project: ESRI ArcSDE Raster reader
* Purpose: Rasterband implementation for ESRI ArcSDE Rasters
* Author: Howard Butler, [email protected]
*
* This work was sponsored by the Geological Survey of Canada, Natural
* Resources Canada. http://gsc.nrcan.gc.ca/
*
******************************************************************************
* Copyright (c) 2007, Howard Butler <[email protected]>
*
* 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 "sderasterband.h"
CPL_CVSID("$Id$")
/************************************************************************/
/* SDERasterBand implements a GDAL RasterBand for ArcSDE. This class */
/* carries around a pointer to SDE's internal band representation */
/* is of type SE_RASBANDINFO*. SDERasterBand provides the following */
/* capabilities: */
/* */
/* -- Statistics support - uses SDE's internal band statistics */
/* -- Colortable - translates SDE's internal colortable to GDAL's */
/* -- Block reading through IReadBlock */
/* -- Overview support */
/* -- NODATA support */
/* */
/* Instantiating a SDERasterBand is rather expensive because of all */
/* of the round trips to the database the SDE C API must make to */
/* calculate band information. This overhead hit is also taken in */
/* the case of grabbing an overview, because information between */
/* bands is not shared. It might be possible in the future to do */
/* do so, but it would likely make things rather complicated. */
/* In particular, the stream, constraint, and queryinfo SDE objects */
/* could be passed around from band to overview band without having */
/* to be instantiated every time. Stream creation has an especially */
/* large overhead. */
/* */
/* Once the band or overview band is established, querying raster */
/* blocks does not carry much more network overhead than that required */
/* to actually download the bytes. */
/* */
/* Overview of internal methods: */
/* -- InitializeBand - does most of the work of construction */
/* of the band and communication with SDE. */
/* Calls InitializeConstraint and */
/* InitializeQuery. */
/* -- InitializeQuery - Initializes a SDE queryinfo object */
/* that contains information about which */
/* tables we are querying from. */
/* -- InitializeConstraint - Specifies block constraints (which */
/* are initially set to none in */
/* InitializeBand) as well as which */
/* band for SDE to query from. */
/* -- MorphESRIRasterType - translates SDE's raster type to GDAL*/
/* -- MorphESRIRasterDepth - calculates the bit depth from SDE */
/* -- ComputeColorTable - does the work of getting and */
/* translating the SDE colortable to GDAL. */
/* -- ComputeSDEBandNumber - returns the band # for SDE's */
/* internal representation of the band.*/
/* -- QueryRaster - Does the work of setting the constraint */
/* and preparing for querying tiles from SDE. */
/* */
/************************************************************************/
/************************************************************************/
/* SDERasterBand() */
/************************************************************************/
SDERasterBand::SDERasterBand( SDEDataset *poDS,
int nBand,
int nOverview,
const SE_RASBANDINFO* band )
{
// Carry some of the data we were given at construction.
// If we were passed -1 for an overview at construction, reset it
// to 0 to ensure we get the zero'th level from SDE.
// The SE_RASBANDINFO* we were given is actually owned by the
// dataset. We want it around for convenience.
this->poDS = poDS;
this->nBand = nBand;
this->nOverview = nOverview;
this->poBand = band;
// Initialize our SDE opaque object pointers to NULL.
// The nOverviews private data member will be updated when
// GetOverviewCount is called and subsequently returned immediately in
// later calls if it has been set to anything other than 0.
this->hConstraint = NULL;
this->hQuery = NULL;
this->poColorTable = NULL;
if (this->nOverview == -1 || this->nOverview == 0)
this->nOverviews = SDERasterBand::GetOverviewCount();
else
this->nOverviews = 0;
if (nOverview == -1) {
this->papoOverviews = (GDALRasterBand**) CPLMalloc( nOverviews * sizeof(GDALRasterBand*) );
}
else {
this->papoOverviews = NULL;
}
this->eDataType = SDERasterBand::GetRasterDataType();
// nSDERasterType is set by GetRasterDataType
this->dfDepth = MorphESRIRasterDepth(nSDERasterType);
InitializeBand(this->nOverview);
}
/************************************************************************/
/* ~SDERasterBand() */
/************************************************************************/
SDERasterBand::~SDERasterBand( void )
{
if (hQuery)
SE_queryinfo_free(hQuery);
if (hConstraint)
SE_rasconstraint_free(hConstraint);
if (papoOverviews)
for (int i=0; i < nOverviews; i++)
delete papoOverviews[i];
CPLFree(papoOverviews);
if (poColorTable != NULL)
delete poColorTable;
}
/************************************************************************/
/* GetColorTable() */
/************************************************************************/
GDALColorTable* SDERasterBand::GetColorTable(void)
{
if (SE_rasbandinfo_has_colormap(*poBand)) {
if (poColorTable == NULL)
ComputeColorTable();
return poColorTable;
} else {
return NULL;
}
}
/************************************************************************/
/* GetColorInterpretation() */
/************************************************************************/
GDALColorInterp SDERasterBand::GetColorInterpretation()
{
// Only return Paletted images when SDE has a colormap. Otherwise,
// just return gray, even in the instance where we have 3 or 4 band,
// imagery. Let the client be smart instead of trying to do too much.
if (SE_rasbandinfo_has_colormap(*poBand))
return GCI_PaletteIndex;
else
return GCI_GrayIndex;
}
/************************************************************************/
/* GetOverview() */
/************************************************************************/
GDALRasterBand* SDERasterBand::GetOverview( int nOverviewValue )
{
if (papoOverviews) {
return papoOverviews[nOverviewValue];
}
else
return NULL;
}
/************************************************************************/
/* GetOverviewCount() */
/************************************************************************/
int SDERasterBand::GetOverviewCount( void )
{
// grab our existing overview count if we have already gotten it,
// otherwise request it from SDE and set our member data with it.
long nSDEErr;
BOOL bSkipLevel;
LONG nOvRet;
// return nothing if we were an overview band
if (nOverview != -1)
return 0;
nSDEErr = SE_rasbandinfo_get_max_level(*poBand, &nOvRet, &bSkipLevel);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_band_size" );
}
nOverviews = nOvRet;
return nOverviews;
}
/************************************************************************/
/* GetRasterDataType() */
/************************************************************************/
GDALDataType SDERasterBand::GetRasterDataType(void)
{
// Always ask SDE what it thinks our type is.
LONG nSDEErr;
nSDEErr = SE_rasbandinfo_get_pixel_type(*poBand, &nSDERasterType);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_pixel_type" );
return GDT_Byte;
}
return MorphESRIRasterType(nSDERasterType);
}
/************************************************************************/
/* GetStatistics() */
/************************************************************************/
CPLErr SDERasterBand::GetStatistics( int bApproxOK, int bForce,
double *pdfMin, double *pdfMax,
double *pdfMean, double *pdfStdDev )
{
// if SDE hasn't already cached our statistics, we'll depend on the
// GDALRasterBands's method for getting them.
bool bHasStats;
bHasStats = SE_rasbandinfo_has_stats (*poBand);
if (!bHasStats)
return GDALRasterBand::GetStatistics( bApproxOK,
bForce,
pdfMin,
pdfMax,
pdfMean,
pdfStdDev);
// bForce has no effect currently. We always go to SDE to get our
// stats if SDE has them.
// bApproxOK has no effect currently. If we're getting stats from
// SDE, we're hoping SDE calculates them in the way we want.
long nSDEErr;
nSDEErr = SE_rasbandinfo_get_stats_min(*poBand, pdfMin);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_min" );
return CE_Fatal;
}
nSDEErr = SE_rasbandinfo_get_stats_max(*poBand, pdfMax);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_max" );
return CE_Fatal;
}
nSDEErr = SE_rasbandinfo_get_stats_mean(*poBand, pdfMean);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_mean" );
return CE_Fatal;
}
nSDEErr = SE_rasbandinfo_get_stats_stddev(*poBand, pdfStdDev);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_stddev" );
return CE_Fatal;
}
return CE_None;
}
/************************************************************************/
/* GetMinimum() */
/************************************************************************/
double SDERasterBand::GetMinimum(int *pbSuccess)
{
double dfMin, dfMax, dfMean, dfStdDev;
CPLErr error = GetStatistics( TRUE, TRUE,
&dfMin,
&dfMax,
&dfMean,
&dfStdDev );
if (error == CE_None) {
*pbSuccess = TRUE;
return dfMin;
}
*pbSuccess = FALSE;
return 0.0;
}
/************************************************************************/
/* GetMaximum() */
/************************************************************************/
double SDERasterBand::GetMaximum(int *pbSuccess)
{
double dfMin, dfMax, dfMean, dfStdDev;
CPLErr error = GetStatistics( TRUE, TRUE,
&dfMin,
&dfMax,
&dfMean,
&dfStdDev );
if (error == CE_None) {
*pbSuccess = TRUE;
return dfMax;
}
*pbSuccess = FALSE;
return 0.0;
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr SDERasterBand::IReadBlock( int nBlockXOff,
int nBlockYOff,
void * pImage )
{
// grab our Dataset to limit the casting we have to do.
SDEDataset *poGDS = (SDEDataset *) poDS;
// SDE manages the acquisition of raster data in "TileInfo" objects.
// The hTile is the only heap-allocated object in this method, and
// we should make sure to delete it at the end. Once we get the
// pixel data, we'll memcopy it back on to the pImage pointer.
SE_RASTILEINFO hTile;
long nSDEErr;
nSDEErr = SE_rastileinfo_create(&hTile);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_create" );
return CE_Fatal;
}
hConstraint = InitializeConstraint( (long*) &nBlockXOff, (long*) &nBlockYOff );
if (!hConstraint)
CPLError( CE_Failure, CPLE_AppDefined,
"ConstraintInfo initialization failed");
CPLErr error = QueryRaster(hConstraint);
if (error != CE_None)
return error;
LONG level;
nSDEErr = SE_rastileinfo_get_level(hTile, &level);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_get_level" );
return CE_Fatal;
}
nSDEErr = SE_stream_get_raster_tile(poGDS->hStream, hTile);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_get_raster_tile" );
return CE_Fatal;
}
LONG row, column;
nSDEErr = SE_rastileinfo_get_rowcol(hTile, &row, &column);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_get_level" );
return CE_Fatal;
}
LONG length;
unsigned char* pixels;
nSDEErr = SE_rastileinfo_get_pixel_data(hTile, (void**) &pixels, &length);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_get_pixel_data" );
return CE_Fatal;
}
int bits_per_pixel = static_cast<int>(dfDepth * 8 + 0.0001);
int block_size = (nBlockXSize * bits_per_pixel + 7) / 8 * nBlockYSize;
int bitmap_size = (nBlockXSize * nBlockYSize + 7) / 8;
if (length == 0) {
// ArcSDE says the block has no data in it.
// Write 0's and be done with it
memset( pImage, 0,
nBlockXSize*nBlockYSize*GDALGetDataTypeSize(eDataType)/8);
return CE_None;
}
if ((length == block_size) || (length == (block_size + bitmap_size))) {
if (bits_per_pixel >= 8) {
memcpy(pImage, pixels, block_size);
} else {
GByte *p = reinterpret_cast<GByte*>(pImage);
int bit_mask = (2 << bits_per_pixel) - 1;
int i = 0;
for (int y = 0; y < nBlockYSize; ++y) {
for (int x = 0; x < nBlockXSize; ++x) {
*p++ = (pixels[i >> 3] >> (i & 7)) & bit_mask;
i += bits_per_pixel;
}
i = (i + 7) / 8 * 8;
}
}
} else {
CPLError( CE_Failure, CPLE_AppDefined,
"Bit size calculation failed... "\
"SDE's length:%d With bitmap length: %d Without bitmap length: %d",
length, block_size + bitmap_size, block_size );
return CE_Fatal;
}
SE_rastileinfo_free (hTile);
return CE_None ;
}
/* ---------------------------------------------------------------------*/
/* Private Methods */
/************************************************************************/
/* ComputeColorTable() */
/************************************************************************/
void SDERasterBand::ComputeColorTable(void)
{
SE_COLORMAP_TYPE eCMap_Type;
SE_COLORMAP_DATA_TYPE eCMap_DataType;
LONG nCMapEntries;
void *phSDEColormapData = NULL;
long nSDEErr =
SE_rasbandinfo_get_colormap( *poBand,
&eCMap_Type,
&eCMap_DataType,
&nCMapEntries,
&phSDEColormapData );
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_colormap" );
}
// Assign both the short and char pointers
// to the void*, and we'll switch and read based
// on the eCMap_DataType
unsigned char* puszSDECMapData = (unsigned char*) phSDEColormapData;
unsigned short* pushSDECMapData = (unsigned short*) phSDEColormapData;
poColorTable = new GDALColorTable(GPI_RGB);
int red, green, blue, alpha;
CPLDebug("SDERASTER", "%d colormap entries specified", nCMapEntries);
switch (eCMap_DataType) {
case SE_COLORMAP_DATA_BYTE:
switch (eCMap_Type){
case SE_COLORMAP_RGB:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*3;
red = puszSDECMapData[j];
green = puszSDECMapData[j+1];
blue = puszSDECMapData[j+2];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = 255;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_BYTE "\
"SE_COLORMAP_RGB Colormap Entry: %d %d %d",
red, blue, green);
}
break;
case SE_COLORMAP_RGBA:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*4;
red = puszSDECMapData[j];
green = puszSDECMapData[j+1];
blue = puszSDECMapData[j+2];
alpha = puszSDECMapData[j+3];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = alpha;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_BYTE "\
"SE_COLORMAP_RGBA Colormap Entry: %d %d %d %d",
red, blue, green, alpha);
}
break;
case SE_COLORMAP_NONE:
break;
}
break;
case SE_COLORMAP_DATA_SHORT:
switch (eCMap_Type) {
case SE_COLORMAP_RGB:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*3;
red = pushSDECMapData[j];
green = pushSDECMapData[j+1];
blue = pushSDECMapData[j+2];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = 255;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_SHORT "\
"SE_COLORMAP_RGB Colormap Entry: %d %d %d",
red, blue, green);
}
break;
case SE_COLORMAP_RGBA:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*4;
red = pushSDECMapData[j];
green = pushSDECMapData[j+1];
blue = pushSDECMapData[j+2];
alpha = pushSDECMapData[j+3];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = alpha;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_SHORT "\
"SE_COLORMAP_RGBA Colormap Entry: %d %d %d %d",
red, blue, green, alpha);
}
break;
case SE_COLORMAP_NONE:
break;
}
break;
}
SE_rasbandinfo_free_colormap(phSDEColormapData);
}
/************************************************************************/
/* InitializeBand() */
/************************************************************************/
CPLErr SDERasterBand::InitializeBand( int nOverview )
{
SDEDataset *poGDS = (SDEDataset *) poDS;
long nSDEErr;
hConstraint = InitializeConstraint( NULL, NULL );
if (!hConstraint)
CPLError( CE_Failure, CPLE_AppDefined,
"ConstraintInfo initialization failed");
if (!hQuery) {
hQuery = InitializeQuery();
if (!hQuery)
CPLError( CE_Failure, CPLE_AppDefined,
"QueryInfo initialization failed");
}
nSDEErr = SE_stream_close(poGDS->hStream, 1);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_close" );
return CE_Fatal;
}
nSDEErr = SE_stream_query_with_info(poGDS->hStream, hQuery);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_query_with_info" );
return CE_Fatal;
}
nSDEErr = SE_stream_execute (poGDS->hStream);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_execute" );
return CE_Fatal;
}
nSDEErr = SE_stream_fetch (poGDS->hStream);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_fetch" );
return CE_Fatal;
}
CPLErr error = QueryRaster(hConstraint);
if (error != CE_None)
return error;
LONG nBXRet, nBYRet;
nSDEErr = SE_rasterattr_get_tile_size (poGDS->hAttributes,
&nBXRet, &nBYRet);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasterattr_get_tile_size" );
return CE_Fatal;
}
nBlockXSize = nBXRet;
nBlockYSize = nBYRet;
LONG offset_x, offset_y, num_bands, nXSRet, nYSRet;
nSDEErr = SE_rasterattr_get_image_size_by_level (poGDS->hAttributes,
&nXSRet, &nYSRet,
&offset_x,
&offset_y,
&num_bands,
(nOverview == -1) ? (0): (nOverview));
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasterattr_get_image_size_by_level" );
return CE_Fatal;
}
nRasterXSize = nXSRet;
nRasterYSize = nYSRet;
nBlockSize = nBlockXSize * nBlockYSize;
// We're the base level
if( nOverview == -1 )
{
for( int i = 0; i<this->nOverviews; i++ )
{
papoOverviews[i]= new SDERasterBand(poGDS, nBand, i, poBand);
}
}
return CE_None;
}
/************************************************************************/
/* InitializeConstraint() */
/************************************************************************/
SE_RASCONSTRAINT& SDERasterBand::InitializeConstraint( long* nBlockXOff,
long* nBlockYOff)
{
long nSDEErr;
if (!hConstraint) {
nSDEErr = SE_rasconstraint_create(&hConstraint);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_create" );
}
nSDEErr = SE_rasconstraint_set_level(hConstraint, (nOverview == -1) ? (0): (nOverview));
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_create" );
}
LONG nBandIn = nBand;
nSDEErr = SE_rasconstraint_set_bands(hConstraint, 1, &nBandIn);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_set_bands" );
}
nSDEErr = SE_rasconstraint_set_interleave(hConstraint, SE_RASTER_INTERLEAVE_BSQ);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_set_interleave" );
}
}
if (nBlockXSize != -1 && nBlockYSize != -1) { // we aren't initialized yet
if (nBlockXSize >= 0 && nBlockYSize >= 0) {
if (nBlockXOff != NULL && nBlockYOff != NULL &&
*nBlockXOff >= 0 && *nBlockYOff >= 0) {
long nMinX, nMinY, nMaxX, nMaxY;
nMinX = *nBlockXOff;
nMinY = *nBlockYOff;
nMaxX = *nBlockXOff;
nMaxY = *nBlockYOff;
nSDEErr = SE_rasconstraint_set_envelope (hConstraint,
nMinX,
nMinY,
nMaxX,
nMaxY);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_set_envelope" );
}
}
}
}
return hConstraint;
}
/************************************************************************/
/* InitializeQuery() */
/************************************************************************/
SE_QUERYINFO& SDERasterBand::InitializeQuery( void )
{
SDEDataset *poGDS = (SDEDataset *) poDS;
long nSDEErr;
nSDEErr = SE_queryinfo_create(&hQuery);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_create" );
}
nSDEErr = SE_queryinfo_set_tables(hQuery,
1,
(const char**) &(poGDS->pszLayerName),
NULL);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_set_tables" );
}
nSDEErr = SE_queryinfo_set_where_clause(hQuery, (const char*) "");
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_set_where" );
}
nSDEErr = SE_queryinfo_set_columns(hQuery,
1,
(const char**) &(poGDS->pszColumnName));
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_set_where" );
}
return hQuery;
}
/************************************************************************/
/* MorphESRIRasterDepth() */
/************************************************************************/
double SDERasterBand::MorphESRIRasterDepth(int gtype) {
switch (gtype) {
case SE_PIXEL_TYPE_1BIT:
return 0.125;
case SE_PIXEL_TYPE_4BIT:
return 0.5;
case SE_PIXEL_TYPE_8BIT_U:
return 1.0;
case SE_PIXEL_TYPE_8BIT_S:
return 1.0;
case SE_PIXEL_TYPE_16BIT_U:
return 2.0;
case SE_PIXEL_TYPE_16BIT_S:
return 2.0;
case SE_PIXEL_TYPE_32BIT_U:
return 4.0;
case SE_PIXEL_TYPE_32BIT_S:
return 4.0;
case SE_PIXEL_TYPE_32BIT_REAL:
return 4.0;
case SE_PIXEL_TYPE_64BIT_REAL:
return 8.0;
default:
return 2.0;
}
}
/************************************************************************/
/* MorphESRIRasterType() */
/************************************************************************/
GDALDataType SDERasterBand::MorphESRIRasterType(int gtype) {
switch (gtype) {
case SE_PIXEL_TYPE_1BIT:
return GDT_Byte;
case SE_PIXEL_TYPE_4BIT:
return GDT_Byte;
case SE_PIXEL_TYPE_8BIT_U:
return GDT_Byte;
case SE_PIXEL_TYPE_8BIT_S:
return GDT_Byte;
case SE_PIXEL_TYPE_16BIT_U:
return GDT_UInt16;
case SE_PIXEL_TYPE_16BIT_S:
return GDT_Int16;
case SE_PIXEL_TYPE_32BIT_U:
return GDT_UInt32;
case SE_PIXEL_TYPE_32BIT_S:
return GDT_Int32;
case SE_PIXEL_TYPE_32BIT_REAL:
return GDT_Float32;
case SE_PIXEL_TYPE_64BIT_REAL:
return GDT_Float64;
default:
return GDT_UInt16;
}
}
/************************************************************************/
/* QueryRaster() */
/************************************************************************/
CPLErr SDERasterBand::QueryRaster( SE_RASCONSTRAINT& constraint ) const
{
SDEDataset *poGDS = (SDEDataset *) poDS;
long nSDEErr;
nSDEErr = SE_stream_query_raster_tile(poGDS->hStream, constraint);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_query_raster_tile" );
return CE_Fatal;
}
nSDEErr = SE_stream_get_raster (poGDS->hStream, 1, poGDS->hAttributes);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_fetch" );
return CE_Fatal;
}
return CE_None;
}
//T:\>gdal_translate -of GTiff SDE:nakina.gis.iastate.edu,5151,,geoservwrite,EsrI4ever,sde_master.geoservwrite.century foo.tif
//T:\>gdalinfo SDE:nakina.gis.iastate.edu,5151,,geoservwrite,EsrI4ever,sde_master.geoservwrite.century
|
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Header: COMObject.cpp
**
** Author: Derek Yenzer (dereky)
**
** Purpose: Native methods on System.Object
**
** Date: March 27, 1998
**
===========================================================*/
#include "common.h"
#include <object.h>
#include "excep.h"
#include "vars.hpp"
#include "field.h"
#include "COMObject.h"
#include "COMClass.h"
#include "COMSynchronizable.h"
#include "gcscan.h"
#include "remoting.h"
/********************************************************************/
/* gets an object's 'value'. For normal classes, with reference
based semantics, this means the object's pointer. For boxed
primitive types, it also means just returning the pointer (because
they are immutable), for other value class, it means returning
a boxed copy. */
FCIMPL1(Object*, ObjectNative::GetObjectValue, Object* obj)
if (obj == 0)
return(obj);
MethodTable* pMT = obj->GetMethodTable();
if (pMT->GetNormCorElementType() != ELEMENT_TYPE_VALUETYPE)
return(obj);
Object* retVal;
OBJECTREF or(obj);
HELPER_METHOD_FRAME_BEGIN_RET_1(or); // Set up a frame
retVal = OBJECTREFToObject(FastAllocateObject(pMT));
CopyValueClass(retVal->GetData(), or->GetData(), pMT, retVal->GetAppDomain());
HELPER_METHOD_FRAME_END();
return(retVal);
FCIMPLEND
// Note that we obtain a sync block index without actually building a sync block.
// That's because a lot of objects are hashed, without requiring support for
FCIMPL1(INT32, ObjectNative::GetHashCode, Object* or) {
if (or == 0)
return 0;
VALIDATEOBJECTREF(or);
DWORD idx = or->GetSyncBlockIndex();
_ASSERTE(idx != 0);
// If the syncblock already exists, it has now become precious. Otherwise the
// hash code would not be stable across GCs.
SyncBlock *psb = or->PassiveGetSyncBlock();
if (psb)
psb->SetPrecious();
return idx;
}
FCIMPLEND
//
// Compare by ref for normal classes, by value for value types.
//
// @todo: it would be nice to customize this method based on the
// defining class rather than doing a runtime check whether it is
// a value type.
//
FCIMPL2(BOOL, ObjectNative::Equals, Object *pThisRef, Object *pCompareRef)
{
if (pThisRef == pCompareRef)
return TRUE;
// Since we are in FCALL, we must handle NULL specially.
if (pThisRef == NULL || pCompareRef == NULL)
return FALSE;
MethodTable *pThisMT = pThisRef->GetMethodTable();
// If it's not a value class, don't compare by value
if (!pThisMT->IsValueClass())
return FALSE;
// Make sure they are the same type.
if (pThisMT != pCompareRef->GetMethodTable())
return FALSE;
// Compare the contents (size - vtable - sink block index).
BOOL ret = !memcmp((void *) (pThisRef+1), (void *) (pCompareRef+1), pThisRef->GetMethodTable()->GetBaseSize() - sizeof(Object) - sizeof(int));
FC_GC_POLL_RET();
return ret;
}
FCIMPLEND
LPVOID __stdcall ObjectNative::GetClass(GetClassArgs *args)
{
OBJECTREF or = args->m_pThis;
REFLECTCLASSBASEREF refClass = NULL;
EEClass* pClass = or->GetTrueMethodTable()->m_pEEClass;
// Arrays of Pointers are implemented by reflection,
// defer to COMClass for them.
if (pClass->IsArrayClass()) {
// This code is essentially duplicated in GetExistingClass.
ArrayBase* array = (ArrayBase*) OBJECTREFToObject(or);
TypeHandle arrayType = array->GetTypeHandle();
refClass = (REFLECTCLASSBASEREF) arrayType.AsArray()->CreateClassObj();
}
else if (or->GetClass()->IsThunking()) {
refClass = CRemotingServices::GetClass(or);
}
else
refClass = (REFLECTCLASSBASEREF) pClass->GetExposedClassObject();
LPVOID rv;
_ASSERTE(refClass != NULL);
*((REFLECTCLASSBASEREF *)&rv) = refClass;
return rv;
}
// *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING
//
// IF YOU CHANGE THIS METHOD, PLEASE ALSO MAKE CORRESPONDING CHANGES TO
// CtxProxy::Clone() AS DESCRIBED BELOW.
//
// *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING
LPVOID __stdcall ObjectNative::Clone(NoArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
_ASSERTE(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
// ObjectNative::Clone() ensures that the source and destination are always in
// the same context. CtxProxy::Clone() must clone an object into a different
// context. Leaving aside that difference, the rest of the two methods should
// be the same and should be maintained together.
// @TODO: write barrier!
MethodTable* pMT;
OBJECTREF clone;
LPVOID pvSrc;
LPVOID pvClone;
DWORD cb;
pMT = pargs->m_pThis->GetMethodTable();
// assert that String has overloaded the Clone() method
_ASSERTE(pMT != g_pStringClass);
cb = pMT->GetBaseSize() - sizeof(ObjHeader);
if (pMT->IsArray()) {
// @TODO: step through array cloning
// _ASSERTE(!"array cloning hasn't been tested yet");
BASEARRAYREF base = (BASEARRAYREF)pargs->m_pThis;
cb += base->GetNumComponents() * pMT->GetComponentSize();
// @TODO: it would be nice to get a non-zeroed array,
// since we're gonna blast over it anyway
clone = DupArrayForCloning(base);
} else {
// @TODO: it would be nice to get a non-zeroed object,
// since we're gonna blast over it anyway
// We don't need to call the <cinit> because we know
// that it has been called....(It was called before this was created)
clone = AllocateObject(pMT);
}
// copy contents of "this" to the clone
*((OBJECTREF *)&pvSrc) = pargs->m_pThis;
*((OBJECTREF *)&pvClone) = clone;
memcpyGCRefs(pvClone, pvSrc, cb);
return pvClone;
}
INT32 __stdcall ObjectNative::WaitTimeout(WaitTimeoutArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
ASSERT(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
if ((pargs->m_Timeout < 0) && (pargs->m_Timeout != INFINITE_TIMEOUT))
COMPlusThrowArgumentOutOfRange(L"millisecondsTimeout", L"ArgumentOutOfRange_NeedNonNegNum");
OBJECTREF or = pargs->m_pThis;
return or->Wait(pargs->m_Timeout,pargs->m_exitContext);
}
void __stdcall ObjectNative::Pulse(NoArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
ASSERT(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
OBJECTREF or = pargs->m_pThis;
or->Pulse();
}
void __stdcall ObjectNative::PulseAll(NoArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
ASSERT(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
OBJECTREF or = pargs->m_pThis;
or->PulseAll();
}
// This method will return a Class object for the object
// iff the Class object has already been created.
// If the Class object doesn't exist then you must call the GetClass() method.
FCIMPL1(Object*, ObjectNative::GetExistingClass, Object* thisRef) {
if (thisRef == NULL)
FCThrow(kNullReferenceException);
EEClass* pClass = thisRef->GetTrueMethodTable()->m_pEEClass;
// For marshalbyref classes, let's just punt for the moment
if (pClass->IsMarshaledByRef())
return 0;
OBJECTREF refClass;
if (pClass->IsArrayClass()) {
// This code is essentially a duplicate of the code in GetClass, done for perf reasons.
ArrayBase* array = (ArrayBase*) OBJECTREFToObject(thisRef);
TypeHandle arrayType;
// Erect a GC Frame around the call to GetTypeHandle, since on the first call,
// it can call AppDomain::RaiseTypeResolveEvent, which allocates Strings and calls
// a user-provided managed callback. Yes, we have to do an allocation to do a
// lookup, since TypeHandles are used as keys. Yes this sucks. -- BrianGru, 9/12/2000
HELPER_METHOD_FRAME_BEGIN_RET_1(array);
arrayType = array->GetTypeHandle();
refClass = COMClass::QuickLookupExistingArrayClassObj(arrayType.AsArray());
HELPER_METHOD_FRAME_END();
}
else
refClass = pClass->GetExistingExposedClassObject();
return OBJECTREFToObject(refClass);
}
FCIMPLEND
|
“รานิเอรี่” กร้าว “เลสเตอร์” ไม่หวั่นใครแน่นอน ในชปล.
กุนซือของสโมสรเลสเตอร์ ซิตี้ ทีมชื่อดังในพรีเมียร์ลีก อังกฤษ อย่าง เคลาดิโอ รานิเอรี่ได้ออกมาเผยว่า ต้นสังกัดของตนนั้น จะลงสนามแบบไม่หวั่นใครหน้าไหนเลย ในนัดการแข่งขันยูฟ่า แชมเปี้ยนส์ ลีก ซีซั่นหน้า ซึ่งจากการคอนเฟิร์มแชมป์ลีกแดนผู้ดี จะเป็นทีมวางในเกมแบ่งกลุ่มแชมเปี้ยนส์ลีก ซึ่งมีแววว่าคงไม่ได้เจอกับทีมแกร่งในยุโรป แต่ เคลาดิโอ ก็บอกว่าตั้งใจเล่นต่อไปเช่นกัน
โดน รานิเอรี่ ได้กล่าวถึงเรื่องนี้เอาไว้่า “ผมมั่นใจว่า เมื่อมีการแบ่งกลุ่ ต้องมีหลาบสโมสรที่อยากจะแข่งกับทีมของเรา เนื่องจากเลสเตอร์ พึ่งจะได้ลงสนาม ที่ยุโรป เป็นรอบแรก โดยทีมของพวกเขานึกว่าจิ้งจอกสีน้ำเงิน เป็นเพียงแค่ทีมรองบ่อนเท่านั้น ซึ่งผมเชื่อว่า ทีมรองบ่อนก็น่ากลัวไม่น้อยเหมือนกกัน เพราะว่าเมื่อปี 2013 เคยสอยแชมป์แชมเปี้ยนชิพ มาแล้ว ซึ่งมันก็ยากอยู่กว่าจะได้มา”
ทั้งนี้ เทรนเนอร์ของทีมจิ้งจอก ยังระบุเพิ่มเติ่ม เรื่องการดึงนักเตะเข้ามาร่วมงานด้วยตอนช่วงหน้าร้อนนี้ เพื่อผนึกกำลังให้ทีม เอาไว้ว่า “ผมมองว่า ทีมของเราจะได้ แข้งที่สุดมาร่วมงานด้วยกัน และผู้เล่นที่จะแทนตัว นักเตะที่ขาดหายไปได้ด้วย เพราะว่ายังมีเกมที่สำคัญรอพวกเราอีกเช่นกัน”
Considerations Before opening savings accounts Banks
When I open a savings account for the first time, there are a few features you should look for banks that we satisfy your needs. Many financial institutions dedicated to building their client list at any cost. I will say that the features they offer, but they may not emphasize the fees they charge, how to avoid the fees and what to do in order to not overdraw your account.
A savings account is designed to help you save money and build interest. Some banks offer higher interest rates than others, but that does not mean it is the best option. It is important to ask the associates what it takes to open a savings account. Ask any fees associated with your account, and make sure to find out which fees are unavoidable and that. This allows you to be sure that you only pay the necessary fees.
You want to be sure that a number of physical locations available in your area. If you need a check book, you want to be sure that you know that this is in print with ease. If you have to drive for hours to be able to control the print, you more than likely will not be able to make the best use of the account.
I would also like to ask how long it takes to do a transfer. When buying a new car or boat, you need to put down an advance, and quickly transferred the money will allow you to avoid the hassle of getting a check. We also want to make sure that you can get the money to the employer directly deposited into your account, if needed. Also, if you have little money, and someone wants to make money, you want to make sure that the transfer is as smooth as possible.
You will also want to know that the banks are offering protection to overdraw. If you have a checking account, the institution, we want to make sure that the bank will automatically draw money from the savings account to cover the difference. This allows you to make sure that you never expect overdraft fees, and that you are able to pay the bills, even if there is no money in the account at the time. This is a feature that not all banks offer, and it is important to be sure to ask the associates about it because it can be a great way to protect yourself and your money.
The most important feature to look for the banks
The account type
types of functions
Compare the details
Hire a professional to get things done Winners
As the weather gets warmer and more people start to relocate, you will start to see more moving truck on the road. You are in the process of working on their own living conditions. Although you may feel as if there is never a perfect time to have to move, there is no reason why you let this situation that’s best for you. If you hire some professional movers special day, then the only thing you need to concern yourself make sure you have done.
If you do not make your plans early, you can run into some trouble when it comes time to do things in a different place. There is nothing worse than moving the check-in day, and we still have yet to finish packing. If you’re like most people, this is one task you end up procrastinating indefinitely. If pressed for time and can not seem to get things done yourself, contact a professional Movers and consider whether or not to provide packaging services.
There is no reason to feel overwhelmed by your situation. While you may think that it’s a good idea to hire friends and family for a move if you are planning to get things done-to-date and professional manner, it is not. So many things can go wrong if you rely on people to do professional movers. Not only that, an increased risk of damaged property, you also have a higher risk of disputes and other issues that could cause some very stressful and tense moments.
Do yourself a favor and hire professional movers must move all the time. You do not have to wait for hours at the end everything must be done and you will not have to take several days off work in order to put himself in the new location. When you hire professionals should not have to stress out about how things are going to continue. You will be able to give yourself peace of mind knowing that all things are in good hands.
The next time you are thinking about relocating, do not forget to contact several companies that have professional movers. Do your homework, so you pick the most qualified, experienced and professional service to you. Fees and services so that you get the most out of your money. Take advantage of these services, so it’s easier time getting everything together with the moving day. No matter how busy your schedule, you can get everything done in the most efficient way possible without any extra obligations or stress in your life.
Choosing the right mattress
We choose the mattress according to what feels good when touched, but soon we realize After use, it may be something wrong with it. First, consumers tend to choose without trying out, since they are under the assumption that anything will do. While others buy the same things that you are trying to use is not that right in the past few years one or not. These days, they are usually selling offer their customers the opportunity to try out all of them in order to find the right one. The reality is that that is not our preference could be better for our body.
types of mattresses
It is extremely important that the mattress is firm and stable support with the person who will be using. Many people prefer the innerspring, because they are pretty assistance of two or more people on the bed. The problem with this kind is that the spring eventually lose their springiness and become limp or eventually poke holes in the fabric and one would be lying on the bed. This can be a problem because of the discomfort to the report. The fabric and insulation that is in place can become lumpy and greasy at the same time, which would result in an uneven place to lie down. The spring is more, it must be even harder. One advantage of this type of the air flow added to the right owners. Since the space in the upper and lower, there is a better circulation. This means that the cooler for those who use it.
Polyurethane foam mattresses durable than all other types of mattresses. They also have different degrees of hardness, so that people can choose from, but you can warm or warmer than the innerspring types. The reason for this is because of the inability of the material to “breathe”. The polyurethane foam is a dense, compact material, it is very solid and stable. This is also the reason why this may be warmer than the other types. In colder climates, it can be an advantage, while in warmer areas can be a disadvantage. The denseness of the material also means, that is quite durable, and even also in the innerspring.
Another type of bed waterbed. This is a bed that can be either like or do not like about this there is no in between. Made up of a durable material, which is separated into compartments to be filled with water. The compartments dictate that a stable water bed. The multiple compartments of the water bed more stable in this type of mattresses. Despite the setting of stability, this is a very movable bed, and, where appropriate, the owner of dizzy or uncomfortable during use.
These are the three main types of mattress consumers. The three come in varying degrees of strength.
Why Buy Hunting Supplies stores better than shopping online
The Internet has made it easy to find and all types of equipment you might need to enjoy a great day of hunting; but it will not be a lot to gain by buying hunting stores to buy items online. Many people do not realize how important it is to get the right equipment when they go hunting. Whether you’ve hunted deer for years or are just starting out, shopping stores to hunt for the best way to get the equipment you need.
If you physically go to the store, you can be sure that staff are knowledgeable and will be able to answer any and all questions. If you buy the products on the Internet, many people who have not even seen the customer service departments of deer in real life. You look online and you get a regurgitated answer that they more than likely do not understand. The shop staff hunt, fish, and knows what he’s talking about when they answer your questions.
The hunting stores will also have the latest and greatest products on display. It allows you to stay in the loop at all times and make sure that you have the ultimate advantage when you go to the next big hunt. You will be able to see and touch the items in person. This allows you to get to know the quality of items before actually investing in them. Many companies make amazing things over the internet, but when the product arrives, can not be all that the company claims.
If you find that the product does not work, and you think that you need, you can simply walk into one of the search business to return, but if you buy the product online, you will need to deal with the hassle of shipping could pay for the shipping cost back and may not be able to get your money back when it’s all said and done. The shops are a return policy on what to see and to read before buying any product. This allows you to rest assured that you will be completely satisfied with the equipment, what to buy, easy to get a refund or replacement product or the company.
Shopping in stores takes all the hassle and guesswork out of buying high quality equipment. Do not let the big one get away. Already the gear you need, pay for affordable and rest assured that you are prepared for anything that comes from the purchase of hunting shops.
Understanding the basis for the tax sale
Why is it necessary for a tax sale in the United States, you ask? Since our country existed, it depended on the government to pay local taxes to municipalities that required the city to work. Roads, schools, public areas and services such as garbage pickup and fire department is funded by taxes paid by citizens. If someone decides not to pay taxes to owe the government the power to take control of the property to pay the money to the shareholders. We usually will happen to the government to levy taxes against the property owner, the owner of the market debt auction. Two types of auctions, auction certificate and a deed auction. While the two options offered by the bidder eventually take ownership of real estate, they both function in different ways.
Tax certificate sale at a public auction, which resulted in the taxpayer’s delinquent debt that is sold to the highest bidder. The auctions will be held at the county and usually only once a year. If you are looking to bid on one of these auctions, the information is usually found in local government websites. If you win this auction, you are essentially loaning money to criminals owners take the performance of debt. If the former owner is unable to pay the debt in a designated time, it will take over the right to the property and stand up to all future taxes.
If the tax sale on a document, you can bid on the property of the taxpayer made it criminal. Keep in mind that all parties concerned had to notify the auction, and the previous owner had been given the opportunity to pay back the money thus remains the property of the owner of the property. Foreclosures are not from one day to the next, as I remember, there was an extensive process that happened before the auction even been announced. The difference between the tax sale certificate that you buy the property instead of the final offering credit to delinquent property owner. Buying the property final will reduce the risk, because you are guaranteed ownership, but is waiting to see if the previous owner to pay back the debt. There will, however, be forced to float more money in advance if they win the deed auction.
As you can see, this type of auctions may be worth the investment if the money to bid. Make sure to do a thorough inspection of the property before they decide to make the investment. Always assume, first, that there is a serious problem that the property should be secured major improvements. Also, be sure to learn the rules and regulations of how the state handles auctions. If necessary, the assistance of a lawyer to help the real estate auction process. This made it big advantage of investing in a tax sale.
Quality printers
If you are trying to figure out ways to improve the look and quality of the materials, it is worth re-elected printers. While it may be trying to save money to all within the company, if you do not want to sacrifice quality in the process. No matter what type of business you run, it may be difficult to focus on the printing department and run a successful business. Now is the perfect time to start learning providers in the industry and how they can benefit your business.
Keep in mind that although it may be a lot of professional printers to choose from, the industry is very competitive. This means that if you’re willing to invest a little time and ingenuity, you can find a good service to enhance its operations. Although you might be looking at all the different companies to choose from, you do not have to contact all of you to the list. If you go online and you can ask your colleagues and peers, you can get the names of some of the popular and recommended printers in the business.
Do a little research on the internet and look for more of these services. You want to end up in companies that have a great reputation in the industry. Do not forget to take into consideration how long they have been around in the business. While you may be more tempted to go with a company that is surrounded by several years, do not be so quick to rule out some younger companies do.
Take a look at the prices that are available, and a comparison with other printers. Keep in mind that the pricing is very competitive, and in some places willing to offer special rates and discounts depending on the size of the order. Do not let what seems to be the lowest price you roll. You have to try the service out before we know whether or not it wants to develop a good working relationship with them.
Be aware that this will not be like other types of transactions, where you can sample the goods before you commit or purchase. You should do a trial run of the printers you are interested in doing business with. Try a system that allows you to get a better idea of how well their work will increase the materials and campaigns. Pay attention to how well the provider complies with the policies and preferences. Pay attention to how quickly they are able to meet filed after ordering. Do not forget to also pay attention to how to follow up if there is uncertainty or a need for communication. Ultimately, you want service that is efficient, courteous, helpful and very professional.
Getting preapproved mortgage companies
If you are planning to buy a house, it is wise to pre-approved mortgage companies before you start your search for a home. It’s exciting to go looking at the open houses or scout around the property with a realtor. If you do not know whether you can get credit, but it will waste everyone’s time. There are many factors that determine whether you will be seen as a good risk as a homebuyer. In recent years, banks have tightened the testing of applicants to avoid getting the last housing crunch.
How much can you afford?
Maybe your dream is dying at home no matter the cost. It is wise to be careful when calculating what you think you can afford. A rule of thumb is a maximum monthly payment equal to one-quarter or one-third of take-home pay. Do not forget the homeowner, not a renter, you will have to pay for the repairs and maintenance, as well as PITI. PITI is payment including taxes and insurance. It all adds up, and you do not want to end up “house poor”, which means that you can not afford to have anything else, just sitting in the house.
What is a credit score?
Everyone needs a decent credit score before preapproved mortgage-company loans. This means you need to register as a responsible bill paying. The interest rate you get, if approved, will depend on your score. If you have intermittent paying the bills, it is likely that you will not get denied or have to pay extra for having a higher risk. If some mistakes in this area, it’s wise to wait a bit before. Spend a few more years for a better credit history and score.
Do you know where the paperwork?
must be in order to be approved in advance by the mortgage companies, you’re going to show them who you are and papers. You’re going to come up with a few years of income tax, paystubs, bank statements and anything else related to your finances. Your employer can vouch for job performance, and it is planned that already used for some time. If you do not remember what happened to income taxes and all the paperwork disorganized, it’s time to do everything before approaching the bankers.
Buying a house can be exciting realization of the American dream. If you want to make the dream a reality, you can get preapproved by mortgage companies. Figure out what you can really afford, find out your credit score and collect the papers.
Funeral homes and services
Funeral homes are the places where we bring our loved ones when we departed. These places of business services for those who are deceased friends and relatives. These services are generally a result of the center, as well as before, during and after the funeral, the funeral and other events related to the individual religious or community. The choice is one that is able to accommodate the wishes and preferences, who missed a priority. Most people actually choose this place before they are passed to make sure that their wishes and preferences understand and be brought forward when the day comes. On the other hand, some people have to deal with the choice of many funeral when someone they love has passed away.
The services that come in these places is not only a result of the business center, but the paperwork that is needed when someone dies. The government must call the death of the individual and are licenses and other documents that must be submitted in declaring the death of the person. Arrangements with the cemetery and the obituary that is attached to the services of the salon. It is important to declare the death of the individual to the government because of the legal consequences that follow it. Other places of business that relate to the person who receives the deceased’s knowledge of his passes. Funeral Homes also those relating to arrangements with the cemetery burial of the individual.
Other services are also available visitation services that are viewing a few days before the funeral of the deceased. Typically, a portion is reserved for the group of mourners at the salon and see the remains of a friend or relative in relative peace and in a way that religion and belief sees fit. According to the religious service of the religion or beliefs of the deceased they were also held in the parlor, where the visual is considered at the moment. In most cases, relatives are usually informs you that the people who run the business, to inform them of the schedule. Cremation is also an option that can be added to the living room to the relatives of the person who died or those who are interested.
Embalming is something that is usually in order to delay the decomposition process of the body before the funeral takes place. The reconstruction disfigurements during which the accident took place, is also a service that can provide a funeral for family and friends of the deceased. The embalmer can make use of the technique that he had been taught in school. In cases where the body can be deformed so that the embalmer not reconstruct the closed coffin could be a possibility.
|
#pragma once
#include "Chain_Complexes/Chains.hpp"
#include "Utility/General.hpp"
#include "Smith.hpp"
#include "Abelian.hpp"
///@file
///@brief Contains the class \ref mackey::Homology.
namespace mackey {
///The Homology of a Junction
//
///@tparam rank_t The rank type is a dense Eigen row vector of signed integer scalar eg Eigen::Matrix<int,1,-1>.
///It stores the ranks of the modules of the differentials
///Eg in the G equivariant case \f$[1,2,4]\f$ means \f$Z[G/G}\oplus Z[G/G']\oplus Z[G/G'']\f$ where \f$|G:G'|=2, |G/G''|=4\f$ (current implementation only for prime power cyclic groups)
///@tparam diff_t The different
template<typename rank_t, typename diff_t>
class Homology {
typedef std::conditional_t<SFINAE::is_finite_cyclic<scalar_t<diff_t>>::value, scalar_t<diff_t>, int64_t> HScalar; //scalar with extended accuracy for Z coefficients (no change for Z/N coefficients)
typedef std::conditional_t<SFINAE::is_Dense<diff_t>::value, Eigen::Matrix<HScalar, -1, -1>, Eigen::SparseMatrix<HScalar, 0, storage_t<diff_t>>> diff_t_C; //diff_t column major with the scalar above
typedef std::conditional_t<SFINAE::is_Dense<diff_t>::value, Eigen::Matrix<HScalar, -1, -1, 1>, Eigen::SparseMatrix<HScalar, 1, storage_t<diff_t>>> diff_t_R; //diff_t row major with the scalar above
public:
///The type of our matrix of generators
typedef diff_t_C Gens_t;
///The dense type of our generators (a column in the generator matrix, always dense for convenience)
typedef col_vector_t<diff_t_C> gen_t;
AbelianGroup<rank_t> group;///<Encodes the homology groups as follows: group=[1,2,3] means homology Z+Z/2+Z/3. This works even for Z/n coefficients: the free module (Z/n)^, is encoded as [n,n,...,n]
Gens_t generators;///<Encodes the generators homology groups as follows: The i-th column corresponds to the generator for group[i]
bool isZero;///<1 if the homology is trivial
///Default constructor
Homology()=default;
///Compute the homology of Junction from the given Junction
///@param J The given Junction
///@param getQ Whether we want to store the Q matrix; this is used by the boundary function
Homology(const Junction<rank_t, diff_t>& J, bool getQ=0);
//////////////////////////////////////
///Given an element in homology, write it as a linear combination of the generators of the homology
///The answer is encoded as follows: basis=[-1,0,3] means element=-gen[0]+3*gen[2]
///////////////////////////////////////
rank_t basis(const gen_t&) const;
///Given an x that is a boundary returns a y s.t. dy=x
gen_t boundary(const gen_t&) const;
private:
diff_t_R Out_Qi, In_P_full, In_P_reduced;
std::vector<typename diff_t::StorageIndex> dontModOut;
diff_t_C In_Q;
row_vector_t<diff_t_C> diagonal;
typename diff_t::StorageIndex M;
diff_t_C getKernel(diff_t_C&);
void KernelModImage(diff_t_C&, diff_t_C&, bool);
};
}
#include "impl/Homology.ipp"
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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.
//=========================================================================
#ifndef __ELASTOS_DROID_SYSTEMUI_RECENTS_MODEL_RECENTSTASKLOADER_H__
#define __ELASTOS_DROID_SYSTEMUI_RECENTS_MODEL_RECENTSTASKLOADER_H__
#include "_Elastos.Droid.SystemUI.h"
#include "Elastos.Droid.App.h"
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.Graphics.h"
#include "Elastos.Droid.Os.h"
#include "Elastos.CoreLibrary.Utility.h"
#include "Elastos.CoreLibrary.Utility.Concurrent.h"
#include <elastos/core/Runnable.h>
#include "elastos/droid/systemui/recents/RecentsConfiguration.h"
#include "elastos/droid/systemui/recents/misc/SystemServicesProxy.h"
#include "elastos/droid/systemui/recents/model/BitmapLruCache.h"
#include "elastos/droid/systemui/recents/model/DrawableLruCache.h"
#include "elastos/droid/systemui/recents/model/RecentsPackageMonitor.h"
#include "elastos/droid/systemui/recents/model/StringLruCache.h"
using Elastos::Droid::App::IActivityManagerTaskDescription;
using Elastos::Droid::Content::IContext;
using Elastos::Droid::Content::Res::IResources;
using Elastos::Droid::Content::Pm::IActivityInfo;
using Elastos::Droid::Graphics::IBitmap;
using Elastos::Droid::Graphics::Drawable::IBitmapDrawable;
using Elastos::Droid::Os::IHandler;
using Elastos::Droid::Os::IHandlerThread;
using Elastos::Core::Runnable;
using Elastos::Droid::SystemUI::Recents::Misc::SystemServicesProxy;
using Elastos::Droid::SystemUI::Recents::Model::BitmapLruCache;
using Elastos::Droid::SystemUI::Recents::Model::DrawableLruCache;
using Elastos::Droid::SystemUI::Recents::Model::IPackageCallbacks;
using Elastos::Droid::SystemUI::Recents::Model::ITask;
using Elastos::Droid::SystemUI::Recents::Model::ITaskKey;
using Elastos::Droid::SystemUI::Recents::Model::RecentsPackageMonitor;
using Elastos::Droid::SystemUI::Recents::Model::StringLruCache;
using Elastos::Utility::ICollection;
using Elastos::Utility::Concurrent::IConcurrentLinkedQueue;
namespace Elastos {
namespace Droid {
namespace SystemUI {
namespace Recents {
namespace Model {
/* Recents task loader
* NOTE: We should not hold any references to a Context from a static instance */
class RecentsTaskLoader
: public Object
{
private:
/** Handle to an ActivityInfo */
class ActivityInfoHandle
: public Object
{
public:
AutoPtr<IActivityInfo> mInfo;
};
/** A bitmap load queue */
class TaskResourceLoadQueue
: public Object
{
public:
AutoPtr<IConcurrentLinkedQueue> mQueue;
public:
TaskResourceLoadQueue();
/** Adds a new task to the load queue */
CARAPI_(void) AddTasks(
/* [in] */ ICollection* tasks);
/** Adds a new task to the load queue */
CARAPI_(void) AddTask(
/* [in] */ ITask* t);
/**
* Retrieves the next task from the load queue, as well as whether we want that task to be
* force reloaded.
*/
CARAPI_(AutoPtr<ITask>) NextTask();
/** Removes a task from the load queue */
CARAPI_(void) RemoveTask(
/* [in] */ ITask* t);
/** Clears all the tasks from the load queue */
CARAPI_(void) ClearTasks();
/** Returns whether the load queue is empty */
CARAPI_(Boolean) IsEmpty();
};
/* Task resource loader */
class TaskResourceLoader
: public Runnable
{
public:
/** Constructor, creates a new loading thread that loads task resources in the background */
TaskResourceLoader(
/* [in] */ TaskResourceLoadQueue* loadQueue,
/* [in] */ DrawableLruCache* applicationIconCache,
/* [in] */ BitmapLruCache* thumbnailCache,
/* [in] */ IBitmap* defaultThumbnail,
/* [in] */ IBitmapDrawable* defaultApplicationIcon);
/** Restarts the loader thread */
CARAPI_(void) Start(
/* [in] */ IContext* context);
/** Requests the loader thread to stop after the current iteration */
CARAPI_(void) Stop();
// @Override
CARAPI Run();
CARAPI_(AutoPtr<IDrawable>) GetTaskDescriptionIcon(
/* [in] */ ITaskKey* taskKey,
/* [in] */ IBitmap* iconBitmap,
/* [in] */ const String& iconFilename,
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ IResources* res);
public:
AutoPtr<IContext> mContext;
AutoPtr<IHandlerThread> mLoadThread;
AutoPtr<IHandler> mLoadThreadHandler;
AutoPtr<IHandler> mMainThreadHandler;
AutoPtr<SystemServicesProxy> mSystemServicesProxy;
AutoPtr<TaskResourceLoadQueue> mLoadQueue;
AutoPtr<DrawableLruCache> mApplicationIconCache;
AutoPtr<BitmapLruCache> mThumbnailCache;
AutoPtr<IBitmap> mDefaultThumbnail;
AutoPtr<IBitmapDrawable> mDefaultApplicationIcon;
Boolean mCancelled;
Boolean mWaitingOnLoadQueue;
};
class MyRunnable
: public Runnable
{
public:
MyRunnable(
/* [in] */ ITask* t,
/* [in] */ IDrawable* d,
/* [in] */ IBitmap* b);
//@Override
CARAPI Run();
private:
AutoPtr<ITask> mTask;
AutoPtr<IDrawable> mNewIcon;
AutoPtr<IBitmap> mNewThumbnail;
};
private:
/** Private Constructor */
RecentsTaskLoader(
/* [in] */ IContext* context);
public:
/** Initializes the recents task loader */
static CARAPI_(AutoPtr<RecentsTaskLoader>) Initialize(
/* [in] */ IContext* context);
/** Returns the current recents task loader */
static CARAPI_(AutoPtr<RecentsTaskLoader>) GetInstance();
/** Returns the system services proxy */
CARAPI GetSystemServicesProxy(
/* [out] */ SystemServicesProxy** ssp);
private:
/** Gets the list of recent tasks, ordered from back to front. */
static CARAPI_(AutoPtr<IList>) GetRecentTasks(
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ Boolean isTopTaskHome);
public:
/** Returns the activity icon using as many cached values as we can. */
CARAPI_(AutoPtr<IDrawable>) GetAndUpdateActivityIcon(
/* [in] */ ITaskKey* taskKey,
/* [in] */ IActivityManagerTaskDescription* td,
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ IResources* res,
/* [in] */ ActivityInfoHandle* infoHandle,
/* [in] */ Boolean preloadTask);
/** Returns the activity label using as many cached values as we can. */
CARAPI_(String) GetAndUpdateActivityLabel(
/* [in] */ ITaskKey* taskKey,
/* [in] */ IActivityManagerTaskDescription* td,
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ ActivityInfoHandle* infoHandle);
/** Returns the activity's primary color. */
CARAPI_(Int32) GetActivityPrimaryColor(
/* [in] */ IActivityManagerTaskDescription* td,
/* [in] */ RecentsConfiguration* config);
/** Reload the set of recent tasks */
CARAPI_(AutoPtr<ISpaceNode>) Reload(
/* [in] */ IContext* context,
/* [in] */ Int32 preloadCount,
/* [in] */ Boolean isTopTaskHome);
/** Creates a lightweight stack of the current recent tasks, without thumbnails and icons. */
CARAPI_(AutoPtr<ITaskStack>) GetTaskStack(
/* [in] */ SystemServicesProxy* ssp,
/* [in] */ IResources* res,
/* [in] */ Int32 preloadTaskId,
/* [in] */ Int32 preloadTaskCount,
/* [in] */ Boolean loadTaskThumbnails,
/* [in] */ Boolean isTopTaskHome,
/* [in] */ IList* taskKeysOut,
/* [in] */ IList* tasksToLoadOut);
/** Acquires the task resource data directly from the pool. */
CARAPI_(void) LoadTaskData(
/* [in] */ ITask* t);
/** Releases the task resource data back into the pool. */
CARAPI_(void) UnloadTaskData(
/* [in] */ ITask* t);
/** Completely removes the resource data from the pool. */
CARAPI_(void) DeleteTaskData(
/* [in] */ ITask* t,
/* [in] */ Boolean notifyTaskDataUnloaded);
/** Stops the task loader and clears all pending tasks */
CARAPI_(void) StopLoader();
/** Registers any broadcast receivers. */
CARAPI_(void) RegisterReceivers(
/* [in] */ IContext* context,
/* [in] */ IPackageCallbacks* cb);
/** Unregisters any broadcast receivers. */
CARAPI_(void) UnregisterReceivers();
/**
* Handles signals from the system, trimming memory when requested to prevent us from running
* out of memory.
*/
CARAPI_(void) OnTrimMemory(
/* [in] */ Int32 level);
private:
static const String TAG;
public:
static AutoPtr<RecentsTaskLoader> sInstance;
AutoPtr<SystemServicesProxy> mSystemServicesProxy;
AutoPtr<DrawableLruCache> mApplicationIconCache;
AutoPtr<BitmapLruCache> mThumbnailCache;
AutoPtr<StringLruCache> mActivityLabelCache;
AutoPtr<TaskResourceLoadQueue> mLoadQueue;
AutoPtr<TaskResourceLoader> mLoader;
AutoPtr<RecentsPackageMonitor> mPackageMonitor;
Int32 mMaxThumbnailCacheSize;
Int32 mMaxIconCacheSize;
AutoPtr<IBitmapDrawable> mDefaultApplicationIcon;
AutoPtr<IBitmap> mDefaultThumbnail;
};
} // namespace Model
} // namespace Recents
} // namespace SystemUI
} // namespace Droid
} // namespace Elastos
#endif // __ELASTOS_DROID_SYSTEMUI_RECENTS_MODEL_RECENTSTASKLOADER_H__
|
/*
* Copyright (C) Cvitek Co., Ltd. 2019-2020. All rights reserved.
*
* File Name: TgBf16MatchTemplateKenrel.cpp
* Description:
*/
#include "CviBackendContext.h"
#include "backend/backend_tl_api.h"
#include <cmath>
#include <iostream>
#include <llvm/Support/Debug.h>
#include <llvm/Support/Format.h>
#include <llvm/Support/raw_ostream.h>
#define DEBUG_TYPE "cvi_backend_match_template_kernel"
#define ASSERT(x) assert(x)
static cvk_tl_t *load(const CviBackendContext &ctx, cvk_tl_shape_t &tl_shape,
cvk_tg_stride_t &gstride, uint64_t ga_src, cvk_fmt_t ifmt,
cvk_fmt_t fmt, uint32_t layer_id, float_t mean) {
cvk_tl_t *tl_ifmap = ctx.lmem_alloc_tensor(tl_shape, fmt, 1);
ASSERT(tl_ifmap);
cvk_tdma_g2l_tensor_copy_param_t p = {0};
cvk_tg_t tg_src;
tg_src.start_address = ga_src;
tg_src.base_reg_index = ctx.getTdmaBaseSelectIndexFromGaddr(tg_src.start_address);
tg_src.int8_rnd_mode = 0;
tg_src.fmt = ifmt;
tg_src.shape = ctx.tg_shape_t4(tl_shape.n, tl_shape.c, tl_shape.h, tl_shape.w);
tg_src.stride = gstride;
p.src = &tg_src;
p.dst = tl_ifmap;
ctx.tdma_g2l_tensor_copy(&p);
// temporary fix overflow issue, for some extream case it still don't work
if (mean != 0){
cvk_tiu_add_param_t p1 = {0};
p1.res_high = nullptr;
p1.res_low = tl_ifmap;
p1.a_high = nullptr;
p1.a_low = tl_ifmap;
p1.b_is_const = true;
p1.b_const.val = ctx.convert_fp32_to_bf16(-mean);
p1.b_const.is_signed = 1;
p1.rshift_bits = 0;
p1.layer_id = layer_id;
p1.relu_enable = false;
ctx.tiu_add(&p1);
}
return tl_ifmap;
}
static cvk_tl_t *load_template(const CviBackendContext &ctx, int64_t ga_src,
int32_t c_step, int32_t h, int32_t w,
cvk_fmt_t ifmt, cvk_fmt_t fmt,
bool boradcast, uint32_t layer_id, float_t &mean) {
cvk_tl_shape_t tl_tshape;
if (boradcast)
// load and broadcast template to lanes
tl_tshape = ctx.tl_shape_t4(1, NPU_NUM, h, w);
else
tl_tshape = ctx.tl_shape_t4(1, c_step, h, w);
cvk_tg_stride_t tg_tstride = ctx.tg_default_stride({1, 1, tl_tshape.h, tl_tshape.w}, ifmt);
tg_tstride.n = 0;
tg_tstride.c = 0;
cvk_tl_t *tl_template = load(ctx, tl_tshape, tg_tstride, ga_src, ifmt, fmt, layer_id, mean);
return tl_template;
}
// _____________ _____________
// ||slide | | | | output
// ||window|th | | _______| _____
// ||__tw__| ih ...... | | | --> | | n
// | | | | | |____|
// |______iw____| |_____|______| c
void cvi_backend_tg_bf16_match_template_kernel(
const CviBackendContext &ctx, uint32_t layer_id,
gaddr_t ga_input, gaddr_t ga_template,
gaddr_t ga_table, gaddr_t ga_mantissa_table,
gaddr_t ga_output, int ih, int iw,
int th, int tw, const char* mode) {
int32_t n, c, h, w, stride, outer_size, reduce_size;
uint32_t lmem_used = 0;
cvk_fmt_t fmt = CVK_FMT_BF16;
// according to which set in Quantization.cpp:145
cvk_fmt_t ifmt = CVK_FMT_U8;
float_t mean = 0.;
int32_t g_elt_size = ctx.bytesize_of_fmt(ifmt);
bool boradcast = false;
// reshape input
n = ih - th + 1;
c = iw - tw + 1;
h = th;
w = tw;
stride = iw;
outer_size = n * c;
reduce_size = h * w;
if (h >= MAX_WIDTH || w >= MAX_WIDTH) {
llvm::errs() << llvm::format("Template size[%d] is too large\n", reduce_size);
assert(0);
}
// load table
cvk_tl_shape_t table_shape = ctx.lut_table_shape(fmt);
cvk_tl_t *tl_lut = ctx.lmem_alloc_tensor(table_shape, fmt, 1);
cvk_tl_t *tl_lut_mantissa = ctx.lmem_alloc_tensor(table_shape, fmt, 1);
ctx.tdma_load(tl_lut, ga_table);
ctx.tdma_load(tl_lut_mantissa, ga_mantissa_table);
lmem_used += 2 * ctx.lmem_tensor_to_size(table_shape, fmt, 1);
// tile policy
int c_step = std::min(outer_size, MAX_CHANNEL);
while (c_step > 0) {
// for table
uint32_t mem_need = lmem_used;
// for input
mem_need += ctx.lmem_tensor_to_size(1, c_step, h, w, fmt, 1);
// for intermidate value and output
uint32_t out_mem_need = ctx.lmem_tensor_to_size(1, c_step, 1, 1, fmt, 1);
if (!strcmp(mode, "TM_CCOEFF_NORMED")) {
// for template. boradcast defult is false
mean = 128.;
if (boradcast)
mem_need += ctx.lmem_tensor_to_size(1, NPU_NUM, h, w, fmt, 1); // for test
else
mem_need += ctx.lmem_tensor_to_size(1, c_step, h, w, fmt, 1);
// 4 means tl_out, tl_inter_res, tl_buf, tl_lut_out
mem_need += 4 * out_mem_need;
}
else if(!strcmp(mode, "TM_SQDIFF")){
// broadcast template,
mem_need += ctx.lmem_tensor_to_size(1, NPU_NUM, h, w, fmt, 1);
// for output, tl_buf, tl_lut_out
mem_need += 3 * out_mem_need;
boradcast = true;
}
else {
llvm::errs() << llvm::format("Match template not support [%s] method.\n", mode);
assert(0);
}
if (mem_need <= (uint32_t) LOCAL_MEM_SIZE){
break;
}
if(c_step % NPU_NUM != 0){
c_step -= c_step % NPU_NUM;
} else {
c_step -= NPU_NUM;
}
}
if (c_step <= 0){
llvm::errs() << llvm::format("Tilling Match Template failed, src shape:[1,%d,%d,%d]\n",
outer_size, h, w);
assert(0);
}
cvk_tl_t *tl_template = load_template(ctx, ga_template, c_step, h, w,
ifmt, fmt, boradcast, layer_id, mean);
cvk_tg_stride_t tg_istride = {
(uint32_t)(stride * g_elt_size), (uint32_t)g_elt_size,
(uint32_t)(stride * g_elt_size), (uint32_t)g_elt_size
};
if (!strcmp(mode, "TM_CCOEFF_NORMED")) {
ctx.parallel_disable();
for (int c_pos = 0; c_pos < outer_size;){
int _c = std::min(c_step, outer_size - c_pos);
uint64_t in_offset = (c_pos / c * stride + c_pos % c) * g_elt_size;
uint64_t out_offset = c_pos * ctx.bytesize_of_fmt(fmt);
if (c_pos / c != (c_pos + _c - 1) / c){
// if end idx in next row , cut off rest and next loop will cal from next row.
_c -= (c_pos + _c) % c; // num of windows keep
c_pos += _c;
}
else{
c_pos += c_step;
}
// load input. For now input assume always be uint8
cvk_tl_shape_t tl_ishape = ctx.tl_shape_t4(1, _c, h, w);
cvk_tl_shape_t tl_oshape = ctx.tl_shape_t4(1, _c, 1, 1);
cvk_tl_t *tl_input = load(ctx, tl_ishape, tg_istride, ga_input + in_offset,
ifmt, fmt, layer_id, mean);
cvk_tl_t *tl_output = ctx.lmem_alloc_tensor(tl_oshape, fmt, 1);
cvk_tl_t *tl_inter_res = ctx.lmem_alloc_tensor(tl_oshape, fmt, 1);
// cal reduce_sum(pow(input, 2))
cvk_tiu_depthwise_pt_convolution_param_t p2 = {0};
p2.ofmap = tl_inter_res;
p2.ifmap = tl_input;
p2.weight = tl_input;
p2.bias = nullptr;
p2.ins_h = 0;
p2.ins_w = 0;
p2.ins_last_h = 0;
p2.ins_last_w = 0;
p2.pad_bottom = 0;
p2.pad_top= 0;
p2.pad_left = 0;
p2.pad_right = 0;
p2.stride_h = 1;
p2.stride_w = 1;
p2.dilation_h = 1;
p2.dilation_w = 1;
p2.rshift_bits = 0;
p2.relu_enable = 0;
p2.layer_id = layer_id;
ctx.tiu_pt_depthwise_convolution(&p2);
// cal reduce_sum(mul(input, tmplate))
cvk_tl_t _tl_template;
_tl_template.start_address = tl_template->start_address;
_tl_template.shape = tl_input->shape;
_tl_template.stride = tl_input->stride;
_tl_template.fmt = tl_template->fmt;
if (boradcast){
_tl_template.stride.n = 0;
_tl_template.stride.c = 0;
cvk_tiu_mul_param_t p0 = {0};
p0.res_high = nullptr;
p0.res_low = tl_input;
p0.a = tl_input;
p0.b = &_tl_template;
p0.b_is_const = 0;
p0.rshift_bits = 0;
p0.layer_id = layer_id;
p0.relu_enable = 0;
ctx.tiu_mul(&p0);
cvk_tiu_average_pooling_param_t param = {0};
param.ofmap = tl_output;
param.ifmap = tl_input;
param.kh = h;
param.kw = w;
param.pad_top = 0;
param.pad_bottom = 0;
param.pad_left = 0;
param.pad_right = 0;
param.stride_h = 1;
param.stride_w = 1;
param.avg_pooling_const = ctx.convert_fp32_to_bf16(h * w);
param.layer_id = layer_id;
param.ins_val = 0;
param.ins_fp = param.avg_pooling_const;
ctx.tiu_average_pooling(¶m);
} else{
// it seems more efficient in cuerrent case.
cvk_tiu_depthwise_pt_convolution_param_t p1 = {0};
p1.ofmap = tl_output;
p1.ifmap = tl_input;
p1.weight = tl_template;
p1.bias = nullptr;
p1.ins_h = 0;
p1.ins_w = 0;
p1.ins_last_h = 0;
p1.ins_last_w = 0;
p1.pad_bottom = 0;
p1.pad_top= 0;
p1.pad_left = 0;
p1.pad_right = 0;
p1.stride_h = 1;
p1.stride_w = 1;
p1.dilation_h = 1;
p1.dilation_w = 1;
p1.rshift_bits = 0;
p1.relu_enable = 0;
p1.layer_id = layer_id;
ctx.tiu_pt_depthwise_convolution(&p1);
}
// lut reduce)sum(sqrt(power(input, 2)))
cvk_tl_t *tl_buf = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tl_t *tl_lut_out = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tiu_bf16_lookup_interp_table_param_t p3 = {0};
p3.ifmap = tl_inter_res;
p3.buf = tl_buf;
p3.tbl_answer = tl_lut;
p3.tbl_answer_mantissa = tl_lut_mantissa;
p3.ofmap = tl_lut_out;
p3.is_scientific = 1;
ctx.tiu_bf16_lookup_interp_table(&p3);
// mul numerator and denominator
cvk_tiu_mul_param_t p4 = {0};
p4.res_high = nullptr;
p4.res_low = tl_output;
p4.a = tl_output;
p4.b = tl_lut_out;
p4.b_is_const = 0;
p4.rshift_bits = 0;
p4.layer_id = layer_id;
p4.relu_enable = 0;
ctx.tiu_mul(&p4);
ctx.tdma_store(tl_output, ga_output + out_offset);
ctx.lmem_free_tensor(tl_lut_out);
ctx.lmem_free_tensor(tl_buf);
ctx.lmem_free_tensor(tl_inter_res);
ctx.lmem_free_tensor(tl_output);
ctx.lmem_free_tensor(tl_input);
} // end for
} // end if
else {
// param: prevent overflow
float_t scale = 1. / (h * w * 100);
float_t esp = 1e-5;
ctx.parallel_disable();
for (int c_pos = 0; c_pos < outer_size;){
int _c = std::min(c_step, outer_size - c_pos);
uint64_t in_offset = (c_pos / c * stride + c_pos % c) * g_elt_size;
uint64_t out_offset = c_pos * ctx.bytesize_of_fmt(fmt);
if (c_pos / c != (c_pos + _c - 1) / c){
_c -= (c_pos + _c) % c;
c_pos += _c;
}
else{
c_pos += c_step;
}
cvk_tl_shape_t tl_ishape = ctx.tl_shape_t4(1, _c, h, w);
cvk_tl_shape_t tl_oshape = ctx.tl_shape_t4(1, _c, 1, 1);
cvk_tl_t *tl_input = load(ctx, tl_ishape, tg_istride, ga_input + in_offset,
ifmt, fmt, layer_id, mean);
cvk_tl_t *tl_output = ctx.lmem_alloc_tensor(tl_oshape, fmt, 1);
cvk_tl_t _tl_template;
_tl_template.start_address = tl_template->start_address;
_tl_template.shape = tl_input->shape;
_tl_template.stride = tl_input->stride;
_tl_template.stride.n = 0;
_tl_template.stride.c = 0;
_tl_template.fmt = tl_template->fmt;
// cal input - tmplate
cvk_tiu_sub_param_t p1 = {0};
p1.res_high = 0;
p1.res_low = tl_input;
p1.a_high = 0;
p1.a_low = tl_input;
p1.b_high = 0;
p1.b_low = &_tl_template;
p1.rshift_bits = 0;
p1.layer_id = layer_id;
ctx.tiu_sub(&p1);
// cal reduce_sum(pow((input - tmplate), 2))
cvk_tiu_depthwise_pt_convolution_param_t p2 = {0};
p2.ofmap = tl_output;
p2.ifmap = tl_input;
p2.weight = tl_input;
p2.bias = nullptr;
p2.ins_h = 0;
p2.ins_w = 0;
p2.ins_last_h = 0;
p2.ins_last_w = 0;
p2.pad_bottom = 0;
p2.pad_top= 0;
p2.pad_left = 0;
p2.pad_right = 0;
p2.stride_h = 1;
p2.stride_w = 1;
p2.dilation_h = 1;
p2.dilation_w = 1;
p2.rshift_bits = 0;
p2.relu_enable = 0;
p2.layer_id = layer_id;
ctx.tiu_pt_depthwise_convolution(&p2);
// diff from ccoeff sqdiff need min value
cvk_tiu_mul_param_t p3 = {0}; // prevent precision truncation
p3.res_high = nullptr;
p3.res_low = tl_output;
p3.a = tl_output;
p3.b_const.val = ctx.convert_fp32_to_bf16(scale);
p3.b_const.is_signed = 1;
p3.b_is_const = true;
p3.rshift_bits = 0;
p3.layer_id = layer_id;
p3.relu_enable = false;
ctx.tiu_mul(&p3);
cvk_tiu_add_param_t p4 = {0}; // prevent overflow
p4.res_high = nullptr;
p4.res_low = tl_output;
p4.a_high = nullptr;
p4.a_low = tl_output;
p4.b_is_const = true;
p4.b_const.val = ctx.convert_fp32_to_bf16(esp);
p4.b_const.is_signed = 1;
p4.rshift_bits = 0;
p4.layer_id = layer_id;
p4.relu_enable = false;
ctx.tiu_add(&p4);
// convert max to min
cvk_tl_t *tl_buf = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tl_t *tl_lut_out = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tiu_bf16_lookup_interp_table_param_t p5 = {0};
p5.ifmap = tl_output;
p5.buf = tl_buf;
p5.tbl_answer = tl_lut;
p5.tbl_answer_mantissa = tl_lut_mantissa;
p5.ofmap = tl_lut_out;
p5.is_scientific = 1;
ctx.tiu_bf16_lookup_interp_table(&p5);
ctx.tdma_store(tl_lut_out, ga_output + out_offset);
ctx.lmem_free_tensor(tl_lut_out);
ctx.lmem_free_tensor(tl_buf);
ctx.lmem_free_tensor(tl_output);
ctx.lmem_free_tensor(tl_input);
} // end for
} // end else
// free table and template
ctx.lmem_free_tensor(tl_template);
ctx.lmem_free_tensor(tl_lut_mantissa);
ctx.lmem_free_tensor(tl_lut);
} // end fun
|
Input management with Dependency Injection
Object oriented programming has a lot of patterns that can be very useful for making games. One of those patterns is the Dependency Injection, a pattern that helps to decouple classes that would otherwise be tightly connected. So let’s take something that’s really connected and see how dependency injection can help us: the input management.
Wait what’s this Dependency Injection?
Usually if you have a thing (call it client) that uses another thing (call it service), when you change the service, then you have to also change the client. And that’s bad. Let’s say the client is your game logic and you are porting your game from pc to mobile, and that therefore you need to switch from a keyboard + mouse input to a touch one. Since all inputs are changed (perhaps radically since your WASD is now a UI element) you now need to change some input-read line in your game logic even if you used an intermediate class to get those button inputs.
The Dependency Injection way to do it instead is to have the input manager call the game logic functions. Without it knowing whose functions they are. You just set them as callbacks and call them when needed. Who sets the callbacks? The naive option is: the client. But then you still have a direct dependency between the classes. Enter the DIC: Dependency Injection Container. He takes the callbacks from the client and gives them to the service, thus eliminating the dependency between them (and adding another class to your code, that’s not a free lunch).
And what are those de-leee-gates?
A delegate is just a way to pass a function as an argument, it can also be stored as a variable and given a type name to be checked so that only the functions that match a certain signature can be stored or passed as a delegate of a specific type.
Let’s read some Input!
string XbuttonName = "Fire1";
// other button names
string LeftStickHorizontalName = "Horizontal";
string LeftStickVerticalName = "Vertical";
//other axis names
First of all we’ll need the names of the input buttons and axis we’re going to read, for this example I’ve used a regular xbox controller. We’ll do this with the old unity input system, not the (currently) experimental one, so we’ll need a string name for it. If you’ve read my other tutorials you know I’ve a personal feud with strings, but this is one of the few cases you really have to use them: if you are building an input manager you don’t want to force whoever uses it to edit code just to rename an input field, so you really want to have that in the inspector, which means a serialized string. Notice that for thumbsticks we’ll need two axis per stick, so two thumbsticks means four axis.
public static InputManager instance;
InputManagerDIC inputDIC;
float triggerSensibility = 0.2f;
As for the other variables, the instance reference will be used to make this class a singleton, the inputDIC is needed to ask for the injection, and the trigger sensibility trashold will be used to get a button behaviour from an axis, because back in my days triggers were fucking buttons and I like it that way.
public delegate void buttonReaction();
public delegate void axisEffect(Vector2 axisVal);
Although we could make this all with predefined System Actions, I’d rather estabilish a more specific interface that reminds whoever writes the game logic code what is supposed to act as a button and what is supposed to act as an axis. It’s just a reminder, nothing more.
good old controller
good old controller
public static buttonReaction XbuttonPress = delegate () { };
//other press callbacks ...
public static buttonReaction XbuttonPressContinuous = delegate () { };
//other continuous callbacks
public static axisEffect leftStickEffect = delegate (Vector2 a) { };
public static axisEffect rightStickEffect = delegate (Vector2 a) { };
public static System.Action InputStartRead = delegate () { };
Each callback is initialized to an empty delegate because if for whatever reason we don’t want to use something, we don’t want a nullreference exception to pop out after the change.
Now, we can define a lot of callbacks for each Input since every button has four relevant conditions:
• just pressed
• pressed (continuously)
• just released
• released (continuously)
In this example I’ll use four buttons and the triggers and read only two condition for the buttons (just pressed and continuous press) and one for the triggers (continuous press), for each of the conditions I want to read I need to define a callback.
The same goes for what to do with thumbsticks, but in that case I just want to read a direction out of them and let the game logic interpret it.
The last callback isn’t really needed but for this tutorial I’ve also built a public repository where you can download a test scene and I need to clean the UI state at the beginning of every frame, so I want a callback for that too.
void Awake()
if (instance == null)
instance = this;
As I said before this is going to be a Singleton. And at the beginning of execution we want the DIC to inject his callbacks in the InputManager, so we’ll call his loading function here.
void Update()
if (Input.GetButtonDown(XbuttonName))
{ XbuttonPress(); }
//read other buttonDowns
if (Input.GetButton(XbuttonName))
{ XbuttonPressContinuous(); }
//read other buttons
if (Input.GetAxis(leftTriggerName) > triggerSensibility)
{ leftTriggerPressContinuous(); }
if (Input.GetAxis(rightTriggerName) > triggerSensibility)
{ rightTriggerPressContinuous(); }
leftStickEffect(new Vector2(Input.GetAxis(LeftStickHorizontalName), Input.GetAxis(LeftStickVerticalName)));
rightStickEffect(new Vector2(Input.GetAxis(RightStickHorizontalName), Input.GetAxis(RightStickVerticalName)));
And at last here’s the action. At first we call the “start reading” callback, then for each button we check the relevant states. Notice that for the trigger we read an axis input and only when it’s over the trashold we’ve set before we call a callback just as if it were a regular button. From the game logic standpoint that trigger will be undistinguishable from a button, it even uses the same delegate type for the callback. For the thumbsticks instead we’ll read the two axis in a single Vector2 variable and use that to call the appropriate axisEffect callback.
How about a UI class for testing this?
a really simple ui
a really simple ui
I’ve made it as basic as it gets, sorry but no fancy stuff here:
Toggle xButton;
//other toggles
Text rStick;
//other texts
For each button I’ll set a toggle on and off, while for the sticks I’ll show the direction in a text. All the references are passed with serialized fields in the inspector.
public void LogCallTLCont() { ShowLogButton(lTriggerButton, "TL Cont"); }
public void LogCallTRCont() { ShowLogButton(rTriggerButton, "TR Cont"); }
public void LogCallA() { ShowLogButton(aButton, "A "); }
public void LogCallB() { ShowLogButton(bButton, "B "); }
public void LogCallX() { ShowLogButton(xButton, "X "); }
public void LogCallY() { ShowLogButton(yButton, "Y "); }
public void LogCallACont() { ShowLogButton(aButton, "A Cont"); }
public void LogCallBCont() { ShowLogButton(bButton, "B Cont"); }
public void LogCallXCont() { ShowLogButton(xButton, "X Cont"); }
public void LogCallYCont() { ShowLogButton(yButton, "Y Cont"); }
public void LogCallL(Vector2 direction) { ShowLogAxis(lStick, "L stick with dir", direction); }
public void LogCallR(Vector2 direction) { ShowLogAxis(rStick, "R stick with dir", direction); }
void ShowLogButton(Toggle toggle, string text)
toggle.isOn = true;
void ShowLogAxis(Text field, string text, Vector2 direction)
field.text = direction.ToString();
Debug.Log(text + direction);
All the callbacks are actually using the same couple of functions, logging and setting an UI element each time. But who’s going to reset all those toggles when we didn’t read the button’s release? Our reset function of course:
public void ResetUI()
xButton.isOn = false;
yButton.isOn = false;
aButton.isOn = false;
bButton.isOn = false;
lTriggerButton.isOn = false;
rTriggerButton.isOn = false;
rStick.text =;
lStick.text =;
It’s Injection time
dependency injection input time
dependency injection input time
Also the DIC is really simple, all it does is to set the callbacks in the InputManager, so it only needs a load function and a field to specify from which class instance it should take the callbacks:
UserExample target;
public void LoadInputManager()
InputManager.XbuttonPress = target.LogCallX;
InputManager.YbuttonPress = target.LogCallY;
InputManager.AbuttonPress = target.LogCallA;
InputManager.BbuttonPress = target.LogCallB;
InputManager.XbuttonPressContinuous = target.LogCallXCont;
InputManager.YbuttonPressContinuous = target.LogCallYCont;
InputManager.AbuttonPressContinuous = target.LogCallACont;
InputManager.BbuttonPressContinuous = target.LogCallBCont;
InputManager.leftStickEffect = target.LogCallL;
InputManager.rightStickEffect = target.LogCallR;
InputManager.leftTriggerPressContinuous = target.LogCallTLCont;
InputManager.rightTriggerPressContinuous = target.LogCallTRCont;
InputManager.InputStartRead = target.ResetUI;
So, as you can see the InputManager has no dependecy towards the client class and the UserExample doesn’t even know that his functions are linked to an input. Any maintenance change on either class will stop here in the DIC and will be as trivial as just changing wich callback is assigned to what variable since that’s all that can happen here.
But what if I just changed Input Settings instead of doing all that?
That’s cool and that’s also the proper way to do it (until you are not porting from pc/console to mobile). Really, until you are not changing between radically different input sources in unity, you’re better off using Unity3d’s input system to remap controls and avoid changing code. I only used the Input management as the easiest-to-explain example, if one thinks this technique is just for that, he’s totally missing the point. This technique can (and according to some people should) be used for absolutely everything.
That’s all folks
Thanks for the read. This time no copy-paste, you get a repository with the whole project already set up and ready to use here. If you have any questions or comments please do express that either in the comments here or just hit me on twitter. And if you don’t want to lose my future stuff, consider my newsletter.
P.S.: I’m currently looking for a job, if you are interested take a look at my portfolio.
|
/**
* Copyright(c) 2020-present, Odysseas Georgoudis & quill contributors.
* Distributed under the MIT License (http://opensource.org/licenses/MIT)
*/
#pragma once
#include "quill/LogLevel.h"
#include "quill/detail/LoggerDetails.h"
#include "quill/detail/ThreadContextCollection.h"
#include "quill/detail/misc/Macros.h"
#include "quill/detail/misc/Utilities.h"
#include "quill/detail/record/LogRecord.h"
#include <atomic>
#include <cstdint>
#include <vector>
namespace quill
{
namespace detail
{
class LoggerCollection;
}
/**
* Thread safe logger.
* Logger must be obtained from LoggerCollection get_logger(), therefore constructors are private
*/
class alignas(detail::CACHELINE_SIZE) Logger
{
public:
/**
* Deleted
*/
Logger(Logger const&) = delete;
Logger& operator=(Logger const&) = delete;
/**
* We align the logger object to it's own cache line. It shouldn't make much difference as the
* logger object size is exactly 1 cache line
* @param i
* @return
*/
void* operator new(size_t i) { return detail::aligned_alloc(detail::CACHELINE_SIZE, i); }
void operator delete(void* p) { detail::aligned_free(p); }
/**
* @return The log level of the logger
*/
QUILL_NODISCARD LogLevel log_level() const noexcept
{
return _log_level.load(std::memory_order_relaxed);
}
/**
* Set the log level of the logger
* @param log_level The new log level
*/
void set_log_level(LogLevel log_level) noexcept
{
_log_level.store(log_level, std::memory_order_relaxed);
}
/**
* Checks if the given log_statement_level can be logged by this logger
* @param log_statement_level The log level of the log statement to be logged
* @return
*/
QUILL_NODISCARD bool should_log(LogLevel log_statement_level) const noexcept
{
return log_statement_level >= log_level();
}
/**
* Checks if the given log_statement_level can be logged by this logger
* @tparam log_statement_level
* @return
*/
template <LogLevel log_statement_level>
QUILL_NODISCARD_ALWAYS_INLINE_HOT bool should_log() const noexcept
{
return log_statement_level >= log_level();
}
/**
* Push a log record to the spsc queue to be logged by the backend thread.
* One queue per caller thread.
* We have this enable_if to use unlikely since no if constexpr in C++14
* @note This function is thread-safe.
*/
template <LogLevel log_statement_level, typename... FmtArgs>
QUILL_ALWAYS_INLINE_HOT
typename std::enable_if_t<(log_statement_level == LogLevel::TraceL3 || log_statement_level == LogLevel::TraceL2 ||
log_statement_level == LogLevel::TraceL1 || log_statement_level == LogLevel::Debug),
void>
log(detail::StaticLogRecordInfo const* log_line_info, FmtArgs&&... fmt_args)
{
// it is usually likely we will not log those levels
if (QUILL_LIKELY(!should_log<log_statement_level>()))
{
return;
}
// Resolve the type of the record first
using log_record_t = quill::detail::LogRecord<FmtArgs...>;
// emplace to the spsc queue owned by the ctx
_thread_context_collection.local_thread_context()->spsc_queue().emplace<log_record_t>(
log_line_info, std::addressof(_logger_details), std::forward<FmtArgs>(fmt_args)...);
}
/**
* Push a log record to the spsc queue to be logged by the backend thread.
* One queue per caller thread.
* We have this enable_if to use unlikely since no if constexpr in C++14
* @note This function is thread-safe.
*/
template <LogLevel log_statement_level, typename... FmtArgs>
QUILL_ALWAYS_INLINE_HOT
typename std::enable_if_t<(log_statement_level == LogLevel::Info || log_statement_level == LogLevel::Warning ||
log_statement_level == LogLevel::Error || log_statement_level == LogLevel::Critical),
void>
log(detail::StaticLogRecordInfo const* log_line_info, FmtArgs&&... fmt_args)
{
// it is usually unlikely we will not log those levels
if (QUILL_UNLIKELY(!should_log<log_statement_level>()))
{
return;
}
// Resolve the type of the record first
using log_record_t = quill::detail::LogRecord<FmtArgs...>;
// emplace to the spsc queue owned by the ctx
_thread_context_collection.local_thread_context()->spsc_queue().emplace<log_record_t>(
log_line_info, std::addressof(_logger_details), std::forward<FmtArgs>(fmt_args)...);
}
private:
friend class detail::LoggerCollection;
/**
* Constructs new logger object
* @param logger_id A unique id per logger
* @param log_level The log level of the logger
*/
Logger(char const* name, Handler* handler, detail::ThreadContextCollection& thread_context_collection)
: _logger_details(name, handler), _thread_context_collection(thread_context_collection)
{
}
/**
* Constructs a new logger object with multiple handlers
* @param name
* @param handlers
* @param thread_context_collection
*/
Logger(char const* name, std::vector<Handler*> handlers, detail::ThreadContextCollection& thread_context_collection)
: _logger_details(name, std::move(handlers)), _thread_context_collection(thread_context_collection)
{
}
private:
detail::LoggerDetails _logger_details;
detail::ThreadContextCollection& _thread_context_collection;
std::atomic<LogLevel> _log_level{LogLevel::Info};
};
#if !(defined(_WIN32) && defined(_DEBUG))
// In MSVC debug mode the class has increased size
static_assert(sizeof(Logger) <= detail::CACHELINE_SIZE, "Logger needs to fit in 1 cache line");
#endif
} // namespace quill
|
This “The Best…” list is a companion to The Best Sites To Learn About The U.S. Financial Crisis. Those sites tried to explain how we got into this mess. The resources on this list share what is happening to us as a result. These sites try to give a picture of the recession’s effects throughout the world.
These sites, all relatively accessible to English Language Learners, are divided into three sections. The first are some narrative reports on what is occurring. The second are interactive charts or graphs that show “the numbers.” The third are multimedia presentations giving a human face to the recession (of course, most of my students are experiencing that human face directly in their own lives).
Here are my picks for The Best Sites To Learn About The Recession:
Voice of America’s Special English has a report (with audio support for the text) titled Trying To Live With A Recession In The World’s Largest Economy.
Breaking New English has a lesson (again, with audio support for the text) called Huge U.S. Job Losses Spark Recession Fears.
ESL Podcast Blog has an engaging report on ways a recession affects society
CBBC has a good report on the recession in the United Kingdom.
CHARTS & GRAPHS:
Where Does Your State Rank? is a map from CNN showing the recession’s effect across the United States.
Layoffs Pile-Up is a graph from the Wall Street Journal showing what economic sectors are experiencing the worst job loss.
USA Today has a very complete analysis on jobs loss and growth in the United States.
The National Conference of State Legislatures also has an interactive map on the effects of the recession in all fifty states.
These would require some teacher explanation, but are intriguing nevertheless. They’re are two infographics showing how the proposed economic stimulus would be used — one from the Washington Post and the other from Credit Loan. CNN has a new interactive on the compromise that the Senate and House just agreed to.
The Obamameter is a regularly updated visual representation of different aspects of the U.S. economy. It would be accessible to Intermediate English Language Learners with some explanation.
FinViz shows the stock market in a vivid color-code.
The Economy Tracker from CNN shows the latest economic data on a map, and combines that with personal stories of those affected.
The Geography Of A Recession comes from The New York Times and shows, in detail, unemployment rates throughout the United States.
Maplibs has a color-coded world map that shows international financial centers. The key is the color — if it’s shown in red then it’s down, if it’s shown in green then it’s up.
The Sacramento Bee has a scary map of unemployment in California.
Economic Reality Check is from CNN and provide short facts about different aspects of the recession.
The Sacramento Bee has just published an Income Gap Interactive Graphic. It’s based on Sacramento data, but I suspect the information is similar across the United States. It vividly, and in a way that’s accessible to English Language Learners, shows how long it takes for different people (by occupation, ethnicity, and educational background) to earn $100,000.
MSNBC has developed what they call an Adversity Index. It’s an animated map that “measures the economic health of 381 metro areas and all 50 states.” It’s pretty intriguing, though would probably require some initial explanation before English Language Learners could fully decipher it. Right below the Adversity Map, you can also find a “Map:Recession-resistant areas” that highlights communities in the U.S. that have escaped the recession’s effects.
The San Francisco Chronicle published a simple and very accessible chart today titled Unemployment Characteristics. It “breaks down” unemployment data by race, gender, and education background.
Great Depression Comparison is an excellent interactive comparing the Depression to our present Recession.
Here’s a very accessible infographic that shows the change in unemployment in major US cities over the past year.
The Associated Press has an Economic Stress Index which shows, in an interactive graphic form, what is happening to every county in the United States economically. It measures bankruptcies, home foreclosures, and unemployment, and then interprets it into what they call a “stress index.”
The New York Times has published an interactive graphic titled Broad Unemployment Across the U.S. It shows both the official unemployment rate, and what the rate would be if it included “ipart-time workers who want to work full time, as well some people who want to work but have not looked for a job in the last four weeks.”
Moody’s has put together an impressive and accessible Global Recession Map showing how all the economies in the world are going.
“Food Assistance” is a very simple and visual infographic from GOOD Magazine tracking the rise of food stamps over the past year.
Times Of Crisis is an extraordinary interactive timeline showing the critical events of the economic recession over the past 365 days.
The Geography of Jobs is an excellent animated map demonstrating the loss of jobs in different parts of the United States during the recession.
Flowing Data has some maps that very visually show where unemployment has increased over the past few years.
The Unemployed States of America, a nice infographic (in terms of accessibility, not because it shares good news)
How the Great Recession Reshaped the U.S. Job Market, an informative (and a bit “busy” looking) interactive from The Wall Street Journal.
“America’s 35 Hardest-Hit Cities” is a very accessible infographic showing the communities around the U.S. with the highest unemployment rates. Quite a few of them are located right here in California’s Central Valley.
Comparing This Recession to Previous Ones: Job Changes is a New York Times graphic that very clearly shows we’re not doing so great right now.
“How The Great Recession Has Changed Life In America” is an interactive from The Pew Center.
Who’s Hurting? is a Wall Street Journal interactive showing which economic sector is losing/gaining jobs
How Do Americans Feel About The Recession? is an infographic from MINT.It has some interesting information, and a teacher could ask similar questions of their students.
“Decline and fall of the California job market” is a very good interactive from The Sacramento Bee showing the chronological progress of the monthly unemployment rate for each county in the state over the past three years.
Visual Economics has published two good infographics in one place: “Cities That Have Missed The Recovery” and “Cities That Are Having A Great Recovery.”
“How The Recession Has Changed Us” is what I think is a pretty amazing infographic from The Atlantic.
Where Are The Jobs? is a very good interactive infographic from The Washington Post showing which economic sectors are increasing jobs and which are not doing so well.
GOOD has just published a very good series of infographics explaining the economy.
It’s called All About The Benjamins.
VIDEOS & SLIDESHOWS:
Boomtown To Bust is a New York Times slideshow on the recession’s effect in Florida.
The Sacramento Bee has a series of photos Chronicling The Economic Downturn.
Long Lines Of Job Seekers Continue is a slideshow from The Washington Post.
Downturn Leaves More Families Homeless is another slideshow from The Washington Post.
The Wall Street Journal has excerpts from recent songs that have been written about the recession.
Following A Closing, The Struggle To Find Work is another slideshow from The New York Times.
A Community Facing Hunger is a video from The New York Times.
Out Of Work In China is a video showing the effects of the recession in that country.
A Painful Return is a slideshow discussing the recession’s effects in China.
Tough Times For Summitville Tiles is a Wall Street Journal slideshow about the closing of a factory.
Black Thursday In France is a Wall Street Journal slideshow about protests in that country demanding that the government do more to stop the recession.
Ohio Town Faces Economic Collapse is a slideshow from Pixcetra.
The American Economy: Down and Out is a slideshow from TIME Magazine.
Tough Times In Cleveland is another TIME slideshow.
An audio slideshow from The New York Times called In Economic Vise, Pontiac Struggles.
There Goes Retirement is an online video from The Wall Street Journal.
The progressive magazine The Nation has a useful slideshow called The Great Recession. It’s a bit ideological, but provides a different kind of analysis and response to the recession. It also includes links to articles that would not be accessible to ELL’s. However, the images, teacher modifications of the articles, and lesson ideas provided by them could offer some good opportunities for student discussion and higher order thinking.
The Faces Of The Unemployed is a slideshow from The New York Times.
Searching For A Job is a series of photos from the Sacramento Bee.
Looking For Work is an audio slideshow from Reuters.
Desperately Seeking A Salary is another audio slideshow from Reuters.
Job Seekers Flood Local Job Fair is a slideshow from The Sacramento Bee.
Recession Hits The Saddle is a slideshow from The New York Times.
Auto Town Struggles With Unemployment is a slideshow from The New York Times.
Dark Stores from TIME Magazine.
The New York Times has an audio slideshow about people looking for work in the state of Tennessee.
Inside California’s Tent Cities is the newest addition to this list. It’s a New York Times slideshow on the growing number of homeless encampments around the United States, particularly here in Sacramento (which was recently featured on Oprah Winfrey’s show) and in Fresno.
The Death of the American Mall is a slideshow from The Wall Street Journal.
Stimulus Watch is a site that doesn’t really fit into any of the categories on this list, but it’s intriguing. It supposedly lists all the projects different governmental projects have proposed to do with stimulus money, and then people can vote which ones they think are best. They’re categorized by community, so they’re very accessible. The only drawback to it is since it’s a wiki, even though all the projects are listed, many don’t have detailed information yet on what the project entails. Nevertheless, its interactivity could offer some good possibilities for student engagement.
How Do You Feel About The Economy? is a great interactive graphic — especially for English Language Learners — from The New York Times. You’re supposed to be able to enter a word that indicates how you’re filling, and you’re given many choices. It’s a good opportunity for vocabulary development.
Picturing The Recession is yet another exceptional interactive from The New York Times. It’s composed of photos contributed by readers, including captions, divided by topic or location.
Adapting To Job Loss is a slideshow from The Washington Post.
Survival Strategies is a new interactive feature from The New York Times. People offer brief ideas on how they’re saving money now in the recession. Readers can vote on which ones they think are best. You have to register in order to vote, offer suggestions, or contribute your own.
Forced From Home is a slideshow from The Wall Street Journal.
Ghost Factories is a slideshow from The New York Times.
“The Long-Term Unemployed” is a multimedia interactive from The Wall Street Journal.
“America Out Of Work” is ongoing series of video interviews the Los Angeles Times is doing with the unemployed.
America at Work is slideshow from The Atlantic.
As always, feedback is welcome.
|
#pragma once
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <string>
#include <sstream>
#include <fstream>
#ifdef WIN32
#undef min
#undef max
#endif
enum class Orientation
{
vertical,
horizontal
};
template<typename T>
inline T clamp(T val, T from, T to) { return std::max(from, std::min(to, val)); }
inline float mix(float a, float b, float t)
{
return a * (1 - t) + b * t;
}
typedef std::unordered_map<std::string, std::string> PropertyBag;
struct str
{
operator std::string() const
{
return _ss.str();
}
template<class T>
str& operator<<(T&& t)
{
_ss << t;
return *this;
}
std::ostringstream _ss;
};
struct Color3 {
float r, g, b;
Color3 brighten(float f) const
{
return { clamp(r * f, 0.0f, 1.0f),
clamp(g * f, 0.0f, 1.0f),
clamp(b * f, 0.0f, 1.0f) };
}
Color3 operator-() const
{
return { 1.0f - r, 1.0f - g, 1.0f - b };
}
Color3 to_grayscale() const
{
auto avg = (r + g + b) / 3;
return { avg, avg, avg };
}
Color3 mix_with(const Color3& other, float t) const
{
return { mix(r, other.r, t),
mix(g, other.b, t),
mix(b, other.b, t) };
}
};
inline std::ostream & operator << (std::ostream & o, const Color3& c)
{
o << (int)(255 * c.r) << ","
<< (int)(255 * c.g) << ","
<< (int)(255 * c.b);
return o;
}
inline std::string read_all_text(const std::string& filename)
{
std::ifstream stream(filename, std::ios::in);
if(!stream.is_open())
{
throw std::runtime_error(str() << "File '" << filename << "' not found!");
}
auto buffer = std::vector<char>((std::istreambuf_iterator<char>(stream)),
std::istreambuf_iterator<char>());
buffer.push_back('\0');
return std::string(buffer.data());
}
class Size
{
public:
Size() : _pixels(0), _is_pixels(true) {} // Default is Auto
Size(int pixels) : _pixels(pixels) {}
Size(float percents)
: _percents(percents), _is_pixels(false) {}
static Size All() { return Size(1.0f); }
static Size Nth(int n) { return Size(1.0f / n); }
static Size Auto() { return Size(0); }
int to_pixels(int base_pixels) const
{
if (_is_pixels) return _pixels;
else return (int) (_percents * base_pixels);
}
bool is_const() const { return _is_pixels; }
float get_percents() const { return _percents; }
int get_pixels() const { return _pixels; }
bool is_auto() const { return _pixels == 0 && _is_pixels; }
Size add_pixels(int px) const
{
if (_is_pixels && _pixels != 0) return Size(_pixels + px);
else return *this;
}
private:
int _pixels;
float _percents;
bool _is_pixels = true;
};
struct Size2
{
Size x, y;
};
inline std::ostream & operator << (std::ostream & o, const Size& r)
{
if (r.is_auto()) o << "auto";
else if (r.is_const()) o << r.get_pixels() << "px";
else o << (int)(r.get_percents() * 100) << "%";
return o;
}
inline Size2 Auto() { return { Size::Auto(), Size::Auto() }; }
inline std::ostream & operator << (std::ostream & o, const Size2& r)
{
return o << r.x << ", " << r.y;
}
struct Int2 {
int x, y;
};
inline bool operator==(const Int2& a, const Int2& b) {
return (a.x == b.x) && (a.y == b.y);
}
inline std::ostream & operator << (std::ostream & o, const Int2& r)
{
return o << "(" << r.x << ", " << r.y << ")";
}
struct Rect
{
Int2 position, size;
};
inline bool operator==(const Rect& a, const Rect& b)
{
return (a.position == b.position) && (a.size == b.size);
}
inline std::ostream & operator << (std::ostream & o, const Rect& r)
{
return o << "[" << r.position << ", " << r.size << "]";
}
inline bool contains(const Rect& rect, const Int2& v)
{
return (rect.position.x <= v.x && rect.position.x + rect.size.x >= v.x) &&
(rect.position.y <= v.y && rect.position.y + rect.size.y >= v.y);
}
struct Margin
{
int left, right, top, bottom;
Margin(int v) : left(v), right(v), top(v), bottom(v) {}
Margin(int x, int y) : left(x), right(x), top(y), bottom(y) {}
Margin(int left, int top, int right, int bottom)
: left(left), right(right), top(top), bottom(bottom) {}
operator bool() const {
return left != 0 || right != 0 || top != 0 || bottom != 0;
}
Margin operator-()
{
return { -left, -right, -top, -bottom };
}
Rect apply(const Rect& r) const
{
return { { r.position.x - left, r.position.y - top },
{ r.size.x + left + right, r.size.y + top + bottom } };
}
Size2 apply(const Size2 s) const
{
return { s.x.add_pixels(left + right), s.y.add_pixels(top + bottom) };
}
};
enum class MouseButton
{
left,
middle,
right
};
enum class MouseState
{
down,
up
};
enum class Alignment
{
left,
center,
right
};
|
A nuzzle of the neck, a stroke of the wrist, a brush of the knee—these caresses often signal a loving touch, but can also feel highly aversive, depending on who is delivering the touch, and to whom. Interested in how the brain makes connections between touch and emotion, neuroscientists at the California Institute of Technology (Caltech) have discovered that the association begins in the brain’s primary somatosensory cortex, a region that, until now, was thought only to respond to basic touch, not to its emotional quality.
“We demonstrated for the first time that the primary somatosensory cortex—the brain region encoding basic touch properties such as how rough or smooth an object is—also is sensitive to the social meaning of a touch,” explains Michael Spezio, a visiting associate at Caltech who is also an assistant professor of psychology at Scripps College in Claremont, California. “It was generally thought that there are separate brain pathways for how we process the physical aspects of touch on the skin and for how we interpret that touch emotionally—that is, whether we feel it as pleasant, unpleasant, desired, or repulsive. Our study shows that, to the contrary, emotion is involved at the primary stages of social touch.”
|
/****************************************************************
toolkit.h
=============================================================
Copyright 1996-2020 Tom Barbalet. All rights reserved.
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.
This software is a continuing work of Tom Barbalet, begun on
13 June 1996. No apes or cats were harmed in the writing of
this software.
****************************************************************/
/*! \file toolkit.h
* \brief This is the interface between the ApeSDK toolkit and what consumes
the ApeSDK toolkit.
*/
#ifndef _TOOLKIT_H_
#define _TOOLKIT_H_
/* Variable Definitions */
#include <signal.h> // for SIMULATED_APE_ASSERT
#undef COMMAND_LINE_DEBUG /* Sends the debug output as printf output - added through command line build */
#define CHAR_SPACE (32)
#define IS_RETURN(val) (((val) == 10) || ((val) == 13))
#define IS_SPACE(val) ((val) == CHAR_SPACE)
#undef SIMULATED_APE_ASSERT
#define PACKED_DATA_BLOCK (32*32*32*2)
typedef double n_double;
#define TWO_PI ((n_double)(6.2831853071795864769252867665590057683943))
#define SINE_MAXIMUM (26880)
#define BIG_INTEGER (2147483647)
#define BIG_NEGATIVE_INTEGER (0-2147483648)
#define NOTHING (0L)
typedef char n_char;
/*! @typedef n_string
@discussion This is the string format for the Simulated Ape development */
typedef n_char * n_string;
typedef const n_char * n_constant_string;
#define STRING_BLOCK_SIZE (2048)
typedef n_char n_string_block[STRING_BLOCK_SIZE];
/*! @typedef n_byte
@discussion This is a single byte data unit. */
typedef unsigned char n_byte;
/*! @typedef n_byte2
@discussion This is a two byte data unit. There is no
expectations on the byte ordering. */
typedef unsigned short n_byte2;
typedef unsigned int n_byte4;
typedef int n_c_int;
#ifndef _WIN64
/*! @typedef n_uint
@discussion This is a four byte data unit. Please note that
this form may be shown as unsigned int on some 64-bit
implementations. */
typedef unsigned long n_uint;
/*! @typedef n_int
@discussion This is the native integer data unit. It can be
whatever length is specified by the implementation. */
typedef long n_int;
#else
typedef unsigned long long n_uint;
typedef long long n_int;
#endif
typedef enum
{
FILE_TYPE_BYTE = 0x01,
FILE_TYPE_BYTE2 = 0x02,
FILE_TYPE_BYTE_EXT = 0x03,
FILE_TYPE_PACKED = 0x05,
FILE_TYPE_BYTE4 = 0x06
} file_element_type;
#ifdef SIMULATED_APE_ASSERT
#define NA_ASSERT(test, message) if(!(test)){io_assert(message, __FILE__, __LINE__); raise(SIGINT);}
void io_assert(n_string message, n_string file_loc, n_int line);
#else
#define NA_ASSERT(test, message) /* test message */
#endif
typedef union
{
struct
{
n_int x;
n_int y;
};
n_int data[2];
}n_vect2;
typedef union
{
struct
{
n_vect2 top_left;
n_vect2 bottom_right;
};
n_int data[4];
} n_area2;
typedef union
{
struct
{
n_double x;
n_double y;
n_double z;
};
n_double data[3];
} n_vect3;
typedef struct {
n_byte r;
n_byte g;
n_byte b;
n_byte a;
}n_rgba;
typedef union
{
n_rgba rgba;
n_byte4 thirtytwo;
}n_rgba32;
typedef struct {
n_vect2 * points;
n_int no_of_points;
n_int max_points;
}n_points;
typedef struct
{
n_byte4 date;
n_byte2 location[2];
n_byte4 time;
}
n_spacetime;
/*! @struct
@field characters Characters that represent these values in the file.
@field incl_kind Included type and the kind of value combined together.
@field number Number of these values.
@field location Byte location of the start of these values within the struct.
@field what_is_it Provides a string output for HTML documentation for the user.
@discussion This is the line by line definition of the Simulated Ape file types.
*/
typedef struct
{
n_byte characters[7];
n_byte incl_kind;
n_uint number_entries;
n_uint start_location;
const n_string what_is_it;
} simulated_file_entry;
#define POPULATED(ch) ((ch[0] != 0) || (ch[1] != 0) || (ch[2] != 0) || (ch[3] != 0) || (ch[4] != 0) || (ch[5] != 0))
/* include externally, if needed */
#define FILE_COPYRIGHT 0x00
#define FILE_INCL(num) ((num) & 0xf0)
#define FILE_KIND(num) ((num) & 0x0f)
#define FILE_EOF 0x0100
#define ASCII_NUMBER(val) (((val) >= '0') && ((val) <= '9'))
#define ASCII_LOWERCASE(val) (((val) >= 'a') && ((val) <= 'z'))
#define ASCII_UPPERCASE(val) (((val) >= 'A') && ((val) <= 'Z'))
#define FILE_OKAY 0x0000
#define FILE_ERROR (-1)
typedef n_byte (n_pixel)(n_int px, n_int py, n_int dx, n_int dy, void * information);
typedef n_int (n_memory_location)(n_int px, n_int py);
typedef n_byte2 (n_patch)(n_byte2 * local);
typedef n_int (n_file_in)(n_byte * buff, n_uint len);
typedef n_byte * (n_file_out)(n_uint * len);
/*! @struct
@field pixel_draw The n_pixel function used to draw pixels into
the window buffer.
@field information This is the pointer information passed into
the pixel_draw function.
@discussion This drawing interface was designed to write to
window buffer information where the window buffer could be
either color or monochrome. The interface needed to be relatively
independent to allow for text to be written into either a color
window or a monochrome window or a line to be drawn through
either window buffer without there being any difference in the
implementation algorithm. Think of this method as a way of
translating high-level drawing and low-level drawing.
*/
typedef struct
{
n_pixel * pixel_draw;
void * information;
} n_join;
typedef struct
{
n_byte * screen;
n_byte * background;
} n_background8;
typedef struct
{
n_byte * screen;
n_byte color;
} n_color8;
/*! @struct
@field size The size of the file in bytes.
@field location The location of the accessing pointer within the
file. This is useful for both input and output files.
@field data The data stored in bytes.
@discussion This is the primary file handling structure in the ApeSDK. It is used for both input and output files. It is the method
used to pass file information from the platform layer into the
platform independent layers of Simulated Ape.
*/
typedef struct
{
n_uint size;
n_uint location;
n_byte *data;
} n_file;
typedef void (n_file_specific)(n_string string, n_byte * reference);
typedef struct
{
void * data;
n_uint expected_bytes;
n_uint hash;
void * next;
} n_file_chain;
typedef enum
{
OBJECT_EMPTY = 0,
OBJECT_STRING,
OBJECT_NUMBER,
OBJECT_OBJECT,
OBJECT_ARRAY = 4,
}n_object_type;
typedef enum
{
OBJ_TYPE_EMPTY = 0,
OBJ_TYPE_STRING_NOTATION,
OBJ_TYPE_NUMBER,
OBJ_TYPE_COLON,
OBJ_TYPE_COMMA,
OBJ_TYPE_OBJECT_OPEN,
OBJ_TYPE_OBJECT_CLOSE,
OBJ_TYPE_ARRAY_OPEN,
OBJ_TYPE_ARRAY_CLOSE
}n_object_stream_type;
typedef struct
{
n_string data;
void* next;
n_object_type type;
}n_array;
typedef struct
{
n_array primitive;
n_string name;
n_uint name_hash;
}n_object;
n_file * obj_json(n_object * object);
n_array * array_number(n_int set_number);
n_array * array_string(n_string set_string);
n_array * array_object(n_object * set_object);
n_array * array_array(n_array * set_array);
n_array * array_add(n_array * array, n_array * element);
n_object * object_number(n_object * obj, n_string name, n_int number);
n_object * object_string(n_object * obj, n_string name, n_string string);
n_object * object_object(n_object * obj, n_string name, n_object * object);
n_object * object_array(n_object * obj, n_string name, n_array * array);
void object_top_object(n_file * file, n_object * top_level);
n_object * object_file_to_tree(n_file * file);
void obj_free(n_object ** object);
n_string obj_contains(n_object* base, n_string name, n_object_type type);
n_int obj_contains_number(n_object* base, n_string name, n_int *number);
n_int obj_contains_array_numbers(n_object* base, n_string name, n_int *array_numbers, n_int size);
n_int obj_contains_array_nbyte2(n_object* base, n_string name, n_byte2 *array_numbers, n_int size);
n_array * obj_get_array(n_string array);
n_object * obj_get_object(n_string object);
n_int obj_get_number(n_string object);
n_array * obj_array_next(n_array * array, n_array * element);
n_int obj_array_count(n_array * array_obj);
/** \brief sine and cosine conversation */
#define NEW_SD_MULTIPLE 26880
extern n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number);
#define SHOW_ERROR(val) (draw_error(val, __FILE__, __LINE__))
#define IO_LOWER_CHAR(value) if(ASCII_UPPERCASE(value)) (value) += 'a' - 'A'
typedef n_int (execute_function)(void * general_data, void * read_data, void * write_data);
typedef void (execute_thread_stub)(execute_function function, void * general_data, void * read_data, void * write_data);
void execute_group(execute_function * function, void * general_data, void * read_data, n_int count, n_int size);
void area2_add(n_area2 * area, n_vect2 * vect, n_byte first);
n_int vect2_distance_under(n_vect2 * first, n_vect2 * second, n_int distance);
void vect2_byte2(n_vect2 * converter, n_byte2 * input);
void vect2_add(n_vect2 * equals, n_vect2 * initial, n_vect2 * second);
void vect2_center(n_vect2 * center, n_vect2 * initial, n_vect2 * second);
void vect2_subtract(n_vect2 * equals, n_vect2 * initial, n_vect2 * second);
void vect2_divide(n_vect2 * equals, n_vect2 * initial, n_vect2 * second, n_int divisor);
void vect2_multiplier(
n_vect2 * equals, n_vect2 * initial,
n_vect2 * second, n_int multiplier, n_int divisor);
void vect2_d(
n_vect2 * initial, n_vect2 * second,
n_int multiplier, n_int divisor);
n_int vect2_dot(
n_vect2 * initial, n_vect2 * second,
n_int multiplier, n_int divisor);
void vect2_rotate90(n_vect2 * rotation);
void vect2_direction(n_vect2 * initial, n_int direction, n_int divisor);
void vect2_delta(n_vect2 * initial, n_vect2 * delta);
void vect2_offset(n_vect2 * initial, n_int dx, n_int dy);
void vect2_back_byte2(n_vect2 * converter, n_byte2 * output);
void vect2_copy(n_vect2 * to, n_vect2 * from);
void vect2_populate(n_vect2 * value, n_int x, n_int y);
void vect2_rotation(n_vect2 * location, n_vect2 * rotation);
void vect2_rotation_bitshift(n_vect2 * location, n_vect2 * rotation);
n_int vect2_nonzero(n_vect2 * nonzero);
n_vect2 * vect2_min_max_init(void);
void vect2_min_max(n_vect2 * points, n_int number, n_vect2 * maxmin);
void vect2_scalar_multiply(n_vect2 * value, n_int multiplier);
void vect2_scalar_divide(n_vect2 * value, n_int divisor);
void vect2_scalar_bitshiftdown(n_vect2 * value, n_int bitshiftdown);
void vect3_double(n_vect3 * converter, n_double * input);
void vect3_add(n_vect3 * equals, n_vect3 * initial, n_vect3 * second);
void vect3_center(n_vect3 * center, n_vect3 * initial, n_vect3 * second);
void vect3_subtract(n_vect3 * equals, n_vect3 * initial, n_vect3 * second);
void vect3_divide(n_vect3 * equals, n_vect3 * initial, n_vect3 * second, n_double divisor);
void vect3_multiplier(n_vect3 * equals, n_vect3 * initial, n_vect3 * second,
n_double multiplier, n_double divisor);
void vect3_d(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor);
n_double vect3_dot(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor);
void vect3_delta(n_vect3 * initial, n_vect3 * delta);
void vect3_offset(n_vect3 * initial, n_double dx, n_double dy, n_double dz);
void vect3_back_double(n_vect3 * converter, n_double * output);
void vect3_copy(n_vect3 * to, n_vect3 * from);
void vect3_populate(n_vect3 * value, n_double x, n_double y, n_double z);
n_int vect3_nonzero(n_vect3 * nonzero);
n_byte * math_general_allocation(n_byte * bc0, n_byte * bc1, n_int i);
void math_general_execution(n_int instruction, n_int is_constant0, n_int is_constant1,
n_byte * addr0, n_byte * addr1, n_int value0, n_int * i,
n_int is_const0, n_int is_const1,
n_byte * pspace,
n_byte *bc0, n_byte *bc1,
n_int braincode_min_loop);
n_byte4 math_hash_fnv1(n_constant_string key);
n_uint math_hash(n_byte * values, n_uint length);
void math_bilinear_8_times(n_byte * side512, n_byte * data, n_byte double_spread);
n_uint math_root(n_uint squ);
n_byte math_turn_towards(n_vect2 * p, n_byte fac, n_byte turn);
#undef DEBUG_RANDOM
#undef VERBOSE_DEBUG_RANDOM
#ifdef DEBUG_RANDOM
#include <stdio.h>
#define math_random(num) math_random_debug(num, __FILE__, __LINE__)
#define math_random3(num) math_random_debug(num, __FILE__, __LINE__)
#define mrdc(string) math_random_debug_count(string)
n_byte2 math_random_debug(n_byte2 * local, n_string file_string, n_int line_number);
void math_random_debug_count(n_string place);
#else
#define mrdc(string) /* math_random_debug_count(string) */
n_byte2 math_random(n_byte2 * local);
void math_random3(n_byte2 * local);
#endif
n_byte math_join(n_int sx, n_int sy, n_int dx, n_int dy, n_join * draw);
n_int math_spread_byte(n_byte val);
n_int math_sine(n_int direction, n_int divisor);
n_byte math_join_vect2(n_int sx, n_int sy, n_vect2 * vect, n_join * draw);
n_byte math_line_vect(n_vect2 * point1, n_vect2 * point2, n_join * draw);
n_byte math_line(n_int x1, n_int y1, n_int x2, n_int y2, n_join * draw);
n_int math_seg14(n_int character);
n_byte math_do_intersect(n_vect2 * p1, n_vect2 * q1, n_vect2 * p2, n_vect2 * q2);
void io_number_to_string(n_string value, n_uint number);
void io_string_number(n_string output_string, n_string input_string, n_uint number);
void io_three_strings(n_string output_string, n_string first_string, n_string second_string, n_string third_string, n_byte new_line);
void io_entry_execution(n_int argc, n_string * argv);
void io_command_line_execution_set(void);
n_int io_command_line_execution(void);
void io_lower(n_string value, n_int length);
void io_whitespace(n_file * input);
void io_whitespace_json(n_file * input);
void io_audit_file(const simulated_file_entry * format, n_byte section_to_audit);
void io_search_file_format(const simulated_file_entry * format, n_string compare);
void io_string_write(n_string dest, n_string insert, n_int * pos);
n_int io_read_bin(n_file * fil, n_byte * local_byte);
n_int io_file_write(n_file * fil, n_byte byte);
void io_file_reused(n_file * fil);
n_int io_write(n_file * fil, n_constant_string ch, n_byte new_line);
n_int io_writenumber(n_file * fil, n_int loc_val, n_uint numer, n_uint denom);
n_int io_length(n_string value, n_int max);
n_int io_find(n_string check, n_int from, n_int max, n_string value_find, n_int value_find_length);
n_int io_read_buff(n_file * fil, n_byte * data, const simulated_file_entry * commands);
n_int io_write_buff(n_file * fil, void * data, const simulated_file_entry * commands, n_byte command_num, n_file_specific * func);
n_int io_write_csv(n_file * fil, n_byte * data, const simulated_file_entry * commands, n_byte command_num, n_byte initial) ;
void memory_copy(n_byte * from, n_byte * to, n_uint number);
void * memory_new(n_uint bytes);
void memory_free(void ** ptr);
void * memory_new_range(n_uint memory_min, n_uint *memory_allocated);
n_file * io_file_new(void);
void io_file_free(n_file ** file);
void io_file_debug(n_file * file);
n_int io_number(n_string number_string, n_int * actual_value, n_int * decimal_divisor);
void memory_erase(n_byte * buf_offscr, n_uint nestop);
n_int io_disk_read(n_file * local_file, n_string file_name);
n_int io_disk_read_no_error(n_file * local_file, n_string file_name);
n_int io_disk_write(n_file * local_file, n_constant_string file_name);
n_int io_disk_check(n_constant_string file_name);
n_string * io_tab_delimit_to_n_string_ptr(n_file * tab_file, n_int * size_value, n_int * row_value);
void io_three_string_combination(n_string output, n_string first, n_string second, n_string third, n_int count);
void io_time_to_string(n_string value);
n_string io_string_copy(n_string string);
n_int io_read_byte4(n_file * fil, n_uint * actual_value, n_byte * final_char);
n_int io_writenum(n_file * fil, n_int loc_val, n_byte ekind, n_byte new_line);
n_int io_command(n_file * fil, const simulated_file_entry * commands);
n_int io_read_data(n_file * fil, n_byte2 command, n_byte * data_read);
void io_output_contents(n_file * file);
n_uint io_file_hash(n_file * file);
n_file * io_file_ready(n_int entry, n_file * file);
void io_file_cleanup(n_int * entry, n_file ** file);
void io_file_writeon(n_int * entry, n_file ** file, n_byte blocked_write);
void io_file_writeoff(n_int * entry, n_file * file);
void io_file_string(n_int entry, n_file * file, n_constant_string string);
n_uint io_find_size_data(simulated_file_entry * commands);
#define ASCII_QUOTE(num) ((num) == '"')
#define ASCII_TEXT(num) ((ASCII_UPPERCASE(num) || ASCII_LOWERCASE(num)) || ((num) == '_'))
#define ASCII_SEMICOLON(num) ((num) == ';')
#define ASCII_COLON(num) ((num) == ':')
#define ASCII_COMMA(num) ((num) == ',')
#define ASCII_EQUAL(num) ((num) == '=')
#define ASCII_BRACKET(num) (((num) == '(')||((num) == ')'))
#define ASCII_BRACES(num) (((num) == '{')||((num) == '}'))
#define ASCII_LOGICAL(num) ((((num) == '&')||((num) == '|'))||(((num) == '^')||((num) == '!')))
#define ASCII_ARITHMETIC(num) ((((num) == '+')||((num) == '-'))||(((num) == '*')||((num) == '/')))
#define ASCII_DIRECTIONAL(num) (((num)=='<')||((num)=='>'))
#define CODE_VALUE_REQUIRED(num) (((num) == APESCRIPT_OPERATOR || (num) == APESCRIPT_NUMBER) || ((num) == APESCRIPT_TEXT))
#define SIZEOF_NUMBER_WRITE (sizeof(n_int))
void io_int_to_bytes(n_int value, n_byte * bytes);
n_int io_bytes_to_int(n_byte * bytes);
#ifndef ABS
#define ABS(a) (((a) < 0) ? -(a) : (a))
#endif
typedef short n_audio;
#define AUDIO_FFT_MAX_BITS (15)
#define AUDIO_FFT_MAX_BUFFER (1<<AUDIO_FFT_MAX_BITS)
void audio_fft(n_byte inverse, n_uint power_sample);
void audio_new_fft(n_uint power_sample,
n_int InverseTransform,
n_double *RealIn,
n_double *ImagIn,
n_double *RealOut,
n_double *ImagOut );
void audio_clear_buffers(n_uint length);
void audio_clear_output(n_audio * audio, n_uint length);
void audio_equal_output(n_audio * audio, n_uint length);
void audio_multiply_output(n_audio * audio, n_uint length);
void audio_set_frequency(n_uint entry, n_uint value);
void audio_low_frequency(n_audio * buffer, n_int number_freq, n_int debug);
void audio_buffer_clear(n_audio * buffer, n_int size);
void audio_buffer_double_clear(n_double * buffer, n_int size);
void audio_buffer_copy_to_audio(n_double * buffer_double, n_audio * buffer_audio, n_int size);
void audio_buffer_copy_to_double(n_audio * buffer_audio, n_double * buffer_double, n_int size);
void audio_buffer_copy_to_double_double(n_double * buffer_double1, n_double * buffer_double2, n_int size);
void audio_buffer_copy_to_double_double(n_double * buffer_double_to, n_double * buffer_double_from, n_int size);
void graph_init(n_int four_byte_factory);
void graph_erase(n_byte * buffer, n_vect2 * img, n_rgba32 * color);
/* draws a line */
void graph_line(n_byte * buffer,
n_vect2 * img,
n_vect2 * previous,
n_vect2 * current,
n_rgba32 * color,
n_byte thickness);
void graph_curve(n_byte * buffer,
n_vect2 * img,
n_vect2 * pt0,
n_vect2 * pt1,
n_vect2 * pt2,
n_rgba32 * color,
n_byte radius_percent,
n_uint start_thickness,
n_uint end_thickness);
void graph_fill_polygon(n_vect2 * points, n_int no_of_points,
n_rgba32 * color, n_byte transparency,
n_byte * buffer, n_vect2 * img);
typedef n_string (n_console_input)(n_string value, n_int length);
typedef void (n_console_output)(n_constant_string value);
typedef n_int (n_console)(void * ptr, n_string response, n_console_output output_function);
typedef struct
{
n_console * function;
n_string command;
n_string addition;
n_string help_information;
} simulated_console_command;
void audio_aiff_header(void * fptr, n_uint total_samples);
n_int audio_aiff_is_header(void * fptr, n_uint *samples);
void audio_aiff_body(void * fptr, n_audio *samples, n_uint number_samples);
n_int io_quit(void * ptr, n_string response, n_console_output output_function);
n_int io_help(void * ptr, n_string response, n_console_output output_function);
n_string io_console_entry_clean(n_string string, n_int length);
n_string io_console_entry(n_string string, n_int length);
void io_console_out(n_constant_string value);
n_int io_console(void * ptr, simulated_console_command * commands, n_console_input input_function, n_console_output output_function);
void io_help_line(simulated_console_command * specific, n_console_output output_function);
void io_console_quit(void);
#endif /* _TOOLKIT_H_ */
|
WE have in this chapter to consider why the females of many birds have not acquired the same ornaments as the male; and why, on the other hand, both sexes of many other birds are equally, or almost equally, ornamented? In the following chapter we shall consider the few cases in which the female is more conspicuously coloured than the male.
In my Origin of Species* I briefly suggested that the long tail of the peacock would be inconvenient and the conspicuous black colour of the male capercailzie dangerous, to the female during the period of incubation: and consequently that the transmission of these characters from the male to the female offspring had been checked through natural selection. I still think that this may have occurred in some few instances: but after mature reflection on all the facts which I have been able to collect, I am now inclined to believe that when the sexes differ, the successive variations have generally been from the first limited in their transmission to the same sex in which they first arose. Since my remarks appeared, the subject of sexual colouration has been discussed in some very interesting papers by Mr. Wallace,*(2) who believes that in almost all cases the successive variations tended at first to be transmitted equally to both sexes; but that the female was saved, through natural selection, from acquiring the conspicuous colours of the male, owing to the danger which she would thus have incurred during incubation.
* Fourth edition, 1866, p. 241.
*(2) Westminster Review, July, 1867. Journal of Travel, vol. i., 1868, p. 73.
This view necessitates a tedious discussion on a difficult point, namely, whether the transmission of a character, which is at first inherited by both sexes can be subsequently limited in its transmission to one sex alone by means of natural selection. We must bear in mind, as shewn in the preliminary chapter on sexual selection, that characters which are limited in their development to one sex are always latent in the other. An imaginary illustration will best aid us in seeing the difficulty of the case; we may suppose that a fancier wished to make a breed of pigeons, in which the males alone should be coloured of a pale blue, whilst the females retained their former slaty tint. As with pigeons characters of all kinds are usually transmitted to both sexes equally, the fancier would have to try to convert this latter form of inheritance into sexually-limited transmission. All that he could do would be to persevere in selecting every male pigeon which was in the least degree of a paler blue; and the natural result of this process, if steadily carried on for a long time, and if the pale variations were strongly inherited or often recurred, would be to make his whole stock of a lighter blue. But our fancier would be compelled to match, generation after generation, his pale blue males with slaty females, for he wishes to keep the latter of this colour. The result would generally be the production either of a mongrel piebald lot, or more probably the speedy and complete loss of the pale-blue tint; for the primordial slaty colour would be transmitted with prepotent force. Supposing, however, that some pale-blue males and slaty females were produced during each successive generation, and were always crossed together, then the slaty females would have, if I may use the expression, much blue blood in their veins, for their fathers, grandfathers, &c., will all have been blue birds. Under these circumstances it is conceivable (though I know of no distinct facts rendering it probable) that the slaty females might acquire so strong a latent tendency to pale-blueness, that they would not destroy this colour in their male offspring, their female offspring still inheriting the slaty tint. If so, the desired end of making a breed with the two sexes permanently different in colour might be gained.
The extreme importance, or rather necessity in the above case of the desired character, namely, pale-blueness, being present though in a latent state in the female, so that the male offspring should not be deteriorated, will be best appreciated as follows: the male of Soemmerring's pheasant has a tail thirty-seven inches in length, whilst that of the female is only eight inches; the tail of the male common pheasant is about twenty inches, and that of the female twelve inches long. Now if the female Soemmerring pheasant with her short tail were crossed with the male common pheasant, there can be no doubt that the male hybrid offspring would have a much longer tail than that of the pure offspring of the common pheasant. On the other hand, if the female common pheasant, with a tail much longer than that of the female Soemmerring pheasant, were crossed with the male of the latter, the male hybrid offspring would have a much shorter tail than that of the pure offspring of Soemmerring's pheasant.*
* Temminck says that the tail of the female Phasianus Soemmerringii is only six inches long, Planches coloriees, vol. v., 1838, pp. 487 and 488: the measurements above given were made for me by Mr. Sclater. For the common pheasant, see Macgillivray, History of British Birds, vol. i., pp. 118-121.
Our fancier, in order to make his new breed with the males of a pale-blue tint, and the females unchanged, would have to continue selecting the males during many generations; and each stage of paleness would have to be fixed in the males, and rendered latent in the females. The task would be an extremely difficult one, and has never been tried, but might possibly be successfully carried out. The chief obstacle would be the early and complete loss of the pale-blue tint, from the necessity of reiterated crosses with the slaty female, the latter not having at first any latent tendency to produce pale-blue offspring.
On the other hand, if one or two males were to vary ever so slightly in paleness, and the variations were from the first limited in their transmission to the male sex, the task of making a new breed of the desired kind would be easy, for such males would simply have to be selected and matched with ordinary females. An analogous case has actually occurred, for there are breeds of the pigeon in Belgium* in which the males alone are marked with black striae. So again Mr. Tegetmeier has recently shewn*(2) that dragons not rarely produce silver-coloured birds, which are almost always hens; and he himself has bred ten such females. It is on the other hand a very unusual event when a silver male is produced; so that nothing would be easier, if desired, than to make a breed of dragons with blue males and silver females. This tendency is indeed so strong that when Mr. Tegetmeier at last got a silver male and matched him with one of the silver females, he expected to get a breed with both sexes thus coloured; he was however disappointed, for the young male reverted to the blue colour of his grandfather, the young female alone being silver. No doubt with patience this tendency to reversion in the males, reared from an occasional silver male matched with a silver hen, might be eliminated, and then both sexes would be coloured alike; and this very process has been followed with success by Mr. Esquilant in the case of silver turbits.
* Dr. Chapius, Le Pigeon Voyageur Belge, 1865, p. 87.
*(2) The Field, Sept., 1872.
With fowls, variations of colour, limited in their transmission to the male sex, habitually occur. When this form of inheritance prevails, it might well happen that some of the successive variations would be transferred to the female, who would then slightly resemble the male, as actually occurs in some breeds. Or again, the greater number, but not all, of the successive steps might be transferred to both sexes, and the female would then closely resemble the male. There can hardly be a doubt that this is the cause of the male pouter pigeon having a somewhat larger crop, and of the male carrier pigeon having somewhat larger wattles, than their respective females; for fanciers have not selected one sex more than the other, and have had no wish that these characters should be more strongly displayed in the male than in the female, yet this is the case with both breeds.
The same process would have to be followed, and the same difficulties encountered, if it were desired to make a breed with the females alone of some new colour.
Lastly, our fancier might wish to make a breed with the two sexes differing from each other, and both from the parent species. Here the difficulty would be extreme, unless the successive variations were from the first sexually limited on both sides, and then there would be no difficulty. We see this with the fowl; thus the two sexes of the pencilled Hamburghs differ greatly from each other, and from the two sexes of the aboriginal Gallus bankiva; and both are now kept constant to their standard of excellence by continued selection, which would be impossible unless the distinctive characters of both were limited in their transmission.
The Spanish fowl offers a more curious case; the male has an immense comb, but some of the successive variations, by the accumulation of which it was acquired, appear to have been transferred to the female; for she has a comb many times larger than that of the females of the parent species. But the comb of the female differs in one respect from that of the male, for it is apt to lop over; and within a recent period it has been ordered by the fancy that this should always be the case, and success has quickly followed the order. Now the lopping of the comb must be sexually limited in its transmission, otherwise it would prevent the comb of the male from being perfectly upright, which would be abhorrent to every fancier. On the other hand, the uprightness of the comb in the male must likewise be a sexually-limited character, otherwise it would prevent the comb of the female from lopping over.
From the foregoing illustrations, we see that even with almost unlimited time at command, it would be an extremely difficult and complex, perhaps an impossible process, to change one form of transmission into the other through selection. Therefore, without distinct evidence in each case, I am unwilling to admit that this has been effected in natural species. On the other hand, by means of successive variations, which were from the first sexually limited in their transmission, there would not be the least difficulty in rendering a male bird widely different in colour or in any other character from the female; the latter being left unaltered, or slightly altered, or specially modified for the sake of protection.
As bright colours are of service to the males in their rivalry with other males, such colours would be selected whether or not they were transmitted exclusively to the same sex. Consequently the females might be expected often to partake of the brightness of the males to a greater or less degree; and this occurs with a host of species. If all the successive variations were transmitted equally to both sexes, the females would be indistinguishable from the males; and this likewise occurs with many birds. If, however, dull colours were of high importance for the safety of the female during incubation, as with many ground birds, the females which varied in brightness, or which received through inheritance from the males any marked accession of brightness, would sooner or later be destroyed. But the tendency in the males to continue for an indefinite period transmitting to their female offspring their own brightness, would have to be eliminated by a change in the form of inheritance; and this, as shewn by our previous illustration, would be extremely difficult. The more probable result of the long-continued destruction of the more brightly-coloured females, supposing the equal form of transmission to prevail would be the lessening or annihilation of the bright colours of the males, owing to their continual crossing with the duller females. It would be tedious to follow out all the other possible results; but I may remind the reader that if sexually limited variations in brightness occurred in the females, even if they were not in the least injurious to them and consequently were not eliminated, yet they would not be favoured or selected, for the male usually accepts any female, and does not select the more attractive individuals; consequently these variations would be liable to be lost, and would have little influence on the character of the race; and this will aid in accounting for the females being commonly duller-coloured than the males.
In the eighth chapter instances were given, to which many might here be added, of variations occurring at various ages, and inherited at the corresponding age. It was also shewn that variations which occur late in life are commonly transmitted to the same sex in which they first appear; whilst variations occurring early in life are apt to be transmitted to both sexes; not that all the cases of sexually-limited transmission can thus be accounted for. It was further shewn that if a male bird varied by becoming brighter whilst young, such variations would be of no service until the age for reproduction had arrived, and there was competition between rival males. But in the case of birds living on the ground and commonly in need of the protection of dull colours, bright tints would be far more dangerous to the young and inexperienced than to the adult males. Consequently the males which varied in brightness whilst young would suffer much destruction and be eliminated through natural selection; on the other hand, the males which varied in this manner when nearly mature, notwithstanding that they were exposed to some additional danger, might survive, and from being favoured through sexual selection, would procreate their kind. As a relation often exists between the period of variation and the form of transmission, if the bright-coloured young males were destroyed and the mature ones were successful in their courtship, the males alone would acquire brilliant colours and would transmit them exclusively to their male offspring. But I by no means wish to maintain that the influence of age on the form of transmission, is the sole cause of the great difference in brilliancy between the sexes of many birds.
When the sexes of birds differ in colour, it is interesting to determine whether the males alone have been modified by sexual selection, the females having been left unchanged, or only partially and indirectly thus changed; or whether the females have been specially modified through natural selection for the sake of protection. I will therefore discuss this question at some length, even more fully than its intrinsic importance deserves; for various curious collateral points may thus be conveniently considered.
Before we enter on the subject of colour, more especially in reference to Mr. Wallace's conclusions, it may be useful to discuss some other sexual differences under a similar point of view. A breed of fowls formerly existed in Germany* in which the hens were furnished with spurs; they were good layers, but they so greatly disturbed their nests with their spurs that they could not be allowed to sit on their own eggs. Hence at one time it appeared to me probable that with the females of the wild Gallinaceae the development of spurs had been checked through natural selection, from the injury thus caused to their nests. This seemed all the more probable, as wing-spurs, which would not be injurious during incubation, are often as well developed in the female as in the male; though in not a few cases they are rather larger in the male. When the male is furnished with leg-spurs the female almost always exhibits rudiments of them,- the rudiment sometimes consisting of a mere scale, as in Gallus. Hence it might be argued that the females had aboriginally been furnished with well-developed spurs, but that these had subsequently been lost through disuse or natural selection. But if this view be admitted, it would have to be extended to innumerable other cases; and it implies that the female progenitors of the existing spur-bearing species were once encumbered with an injurious appendage.
* Bechstein, Naturgeschichte Deutschlands, 1793, B. iii., 339.
In some few genera and species, as in Galloperdix, Acomus, and the Javan peacock (Pavo muticus), the females, as well as the males, possess well-developed leg-spurs. Are we to infer from this fact that they construct a different sort of nest from that made by their nearest allies, and not liable to be injured by their spurs; so that the spurs have not been removed? Or are we to suppose that the females of these several species especially require spurs for their defence? It is a more probable conclusion that both the presence and absence of spurs in the females result from different laws of inheritance having prevailed, independently of natural selection. With the many females in which spurs appear as rudiments, we may conclude that some few of the successive variations, through which they were developed in the males, occurred very early in life, and were consequently transferred to the females. In the other and much rarer cases, in which the females possess fully developed spurs, we may conclude that all the successive variations were transferred to them; and that they gradually acquired and inherited the habit of not disturbing their nests.
The vocal organs and the feathers variously modified for producing sound, as well as the proper instincts for using them, often differ in the two sexes, but are sometimes the same in both. Can such differences be accounted for by the males having acquired these organs and instincts, whilst the females have been saved from inheriting them, on account of the danger to which they would have been exposed by attracting the attention of birds or beasts of prey? This does not seem to me probable, when we think of the multitude of birds which with impunity gladden the country with their voices during the spring.* It is a safer conclusion that, as vocal and instrumental organs are of special service only to the males during their courtship, these organs were developed through sexual selection and their constant use in that sex alone- the successive variations and the effects of use having been from the first more or less limited in transmission to the male offspring.
* Daines Barrington, however, thought it probable (Philosophical Transactions, 1773, p. 164) that few female birds sing, because the talent would have been dangerous to them during incubation. He adds, that a similar view may possibly account for the inferiority of the female to the male in plumage.
Many analogous cases could be adduced; those for instance of the plumes on the head being generally longer in the male than in the female, sometimes of equal length in both sexes, and occasionally absent in the female,- these several cases occurring in the same group of birds. It would be difficult to account for such a difference between the sexes by the female having been benefited by possessing a slightly shorter crest than the male, and its consequent diminution or complete suppression through natural selection. But I will take a more favourable case, namely the length of the tail. The long train of the peacock would have been not only inconvenient but dangerous to the peahen during the period of incubation and whilst accompanying her young. Hence there is not the least a priori improbability in the development of her tail having been checked through natural selection. But the females of various pheasants, which apparently are exposed on their open nests to as much danger as the peahen, have tails of considerable length. The females as well as the males of the Menura superba have long tails, and they build a domed nest, which is a great anomaly in so large a bird. Naturalists have wondered how the female Menura could manage her tail during incubation; but it is now known* that she "enters the nest head first, and then turns round with her tail sometimes over her back, but more often bent round by her side. Thus in time the tail becomes quite askew, and is a tolerable guide to the length of time the bird has been sitting." Both sexes of an Australian kingfisher (Tanysiptera sylvia) have the middle tail-feathers greatly lengthened, and the female makes her nest in a hole; and as I am informed by Mr. R. B. Sharpe these feathers become much crumpled during incubation.
* Mr. Ramsay, in Proc. Zoolog. Soc., 1868, p. 50.
In these two latter cases the great length of the tail-feathers must be in some degree inconvenient to the female; and as in both species the tail-feathers of the female are somewhat shorter than those of the male, it might be argued that their full development had been prevented through natural selection. But if the development of the tail of the peahen had been checked only when it became inconveniently or dangerously great, she would have retained a much longer tail than she actually possesses; for her tail is not nearly so long, relatively to the size of her body, as that of many female pheasants, nor longer than that of the female turkey. It must also be borne in mind that, in accordance with this view, as soon as the tail of the peahen became dangerously long, and its development was consequently checked, she would have continually reacted on her male progeny, and thus have prevented the peacock from acquiring his present magnificent train. We may therefore infer that the length of the tail in the peacock and its shortness in the peahen are the result of the requisite variations in the male having been from the first transmitted to the male offspring alone.
We are led to a nearly similar conclusion with respect to the length of the tail in the various species of pheasants. In the Eared pheasant (Crossoptilon auritum) the tail is of equal length in both sexes, namely sixteen or seventeen inches; in the common pheasant it is about twenty inches long in the male and twelve in the female; in Soemmerring's pheasant, thirty-seven inches in the male and only eight in the female; and lastly in Reeve's pheasant it is sometimes actually seventy-two inches long in the male and sixteen in the female. Thus in the several species, the tail of the female differs much in length, irrespectively of that of the male; and this can be accounted for, as it seems to me, with much more probability, by the laws of inheritance,- that is by the successive variations having been from the first more or less closely limited in their transmission to the male sex than by the agency of natural selection, resulting from the length of tail being more or less injurious to the females of these several allied species.
We may now consider Mr. Wallace's arguments in regard to the sexual colouration of birds. He believes that the bright tints originally acquired through sexual selection by the males would in all, or almost all cases, have been transmitted to the females, unless the transference had been checked through natural selection. I may here remind the reader that various facts opposed to this view have already been given under reptiles, amphibians, fishes and lepidoptera. Mr. Wallace rests his belief chiefly, but not exclusively, as we shall see in the next chapter, on the following statement,* that when both sexes are coloured in a very conspicuous manner, the nest is of such a nature as to conceal the sitting bird; but when there is a marked contrast of colour between the sexes, the male being gay and the female dull-coloured, the nest is open and exposes the sitting bird to view. This coincidence, as far as it goes, certainly seems to favour the belief that the females which sit on open nests have been specially modified for the sake of protection; but we shall presently see that there is another and more probable explanation, namely, that conspicuous females have acquired the instinct of building domed nests oftener than dull-coloured birds. Mr. Wallace admits that there are, as might have been expected, some exceptions to his two rules, but it is a question whether the exceptions are not so numerous as seriously to invalidate them.
* Journal of Travel, edited by A. Murray, vol. i., 1868, p. 78.
There is in the first place much truth in the Duke of Argyll's remark* that a large domed nest is more conspicuous to an enemy, especially to all tree-haunting carnivorous animals, than a smaller open nest. Nor must we forget that with many birds which build open nests, the male sits on the eggs and aids the female in feeding the young: this is the case, for instance, with Pyranga aestiva,*(2) one of the most splendid birds in the United States, the male being vermilion, and the female light brownish-green. Now if brilliant colours had been extremely dangerous to birds whilst sitting on their open nests, the males in these cases would have suffered greatly. It might, however, be of such paramount importance to the male to be brilliantly coloured, in order to beat his rivals, that this may have more than compensated some additional danger.
* Journal of Travel, edited by A. Murray, vol. i., 1868, p. 281.
*(2) Audubon, Ornithological Biography, vol. i., p. 233.
Mr. Wallace admits that with the king-crows (Dicrurus), orioles, and Pittidae, the females are conspicuously coloured, yet build open nests; but he urges that the birds of the first group are highly pugnacious and could defend themselves; that those of the second group take extreme care in concealing their open nests, but this does not invariably hold good;* and that with the birds of the third group the females are brightly coloured chiefly on the under surface. Besides these cases, pigeons which are sometimes brightly, and almost always conspicuously coloured, and which are notoriously liable to the attacks of birds of prey, offer a serious exception to the rule, for they almost always build open and exposed nests. In another large family, that of the humming-birds, all the species build open nests, yet with some of the most gorgeous species the sexes are alike; and in the majority, the females, though less brilliant than the males, are brightly coloured. Nor can it be maintained that all female humming-birds, which are brightly coloured, escape detection by their tints being green, for some display on their upper surfaces red, blue, and other colours.*(2)
* Jerdon, Birds of India, vol. ii., p. 108. Gould's Handbook of the Birds of Australia, vol. i., p. 463.
*(2) For instance, the female Eupetomena macroura has the head and tail dark blue with reddish loins; the female Lampornis porphyrurus is blackish-green on the upper surface, with the lores and sides of the throat crimson; the female Eulampis jugularis has the top of the head and back green, but the loins and the tail are crimson. Many other instances of highly conspicuous females could be given. See Mr. Gould's magnificent work on this family.
In regard to birds which build in holes or construct domed nests, other advantages, as Mr. Wallace remarks, besides concealment are gained, such as shelter from the rain, greater warmth, and in hot countries protection from the sun;* so that it is no valid objection to his view that many birds having both sexes obscurely coloured build concealed nests.*(2) The female horn-bill (Buceros), for instance, of India and Africa is protected during incubation with extraordinary care, for she plasters up with her own excrement the orifice of the hole in which she sits on her eggs, leaving only a small orifice through which the male feeds her; she is thus kept a close prisoner during the whole period of incubation;*(3) yet female horn-bills are not more conspicuously coloured than many other birds of equal size which build open nests. It is a more serious objection to Mr. Wallace's view, as is admitted by him, that in some few groups the males are brilliantly coloured and the females obscure, and yet the latter hatch their eggs in domed nests. This is the case with the Grallinae of Australia, the superb warblers (Maluridae) of the same country, the sun-birds (Nectariniae), and with several of the Australian honey-suckers or Meliphagidae.*(4)
* Mr. Salvin noticed in Guatemala (Ibis, 1864, p. 375) that humming-birds were much more unwilling to leave their nests during very hot weather, when the sun was shining brightly, as if their eggs would be thus injured, than during cool, cloudy, or rainy weather.
*(2) I may specify, as instances of dull-coloured birds building concealed nests, the species belonging to eight Australian genera described in Gould's Handbook of the Birds of Australia, vol. i., pp. 340, 362, 365, 383, 387, 389, 391, 414.
*(3) Mr. C. Horne, Proc. Zoolog. Soc., 1869. p. 243.
*(4) On the nidification and colours of these latter species, see Gould's Handbook of the Birds of Australia, vol. i., pp. 504, 527.
If we look to the birds of England we shall see that there is no close and general relation between the colours of the female and the nature of the nest which is constructed. About forty of our British birds (excluding those of large size which could defend themselves) build in holes in banks, rocks, or trees, or construct domed nests. If we take the colours of the female goldfinch, bullfinch, or black-bird, as a standard of the degree of conspicuousness, which is not highly dangerous to the sitting female, then out of the above forty birds the females of only twelve can be considered as conspicuous to a dangerous degree, the remaining twenty-eight being inconspicuous.* Nor is there any close relation within the same genus between a well-pronounced difference in colour between the sexes, and the nature of the nest constructed. Thus the male house sparrow (Passer domesticus) differs much from the female, the male tree-sparrow (P. montanus) hardly at all, and yet both build well-concealed nests. The two sexes of the common fly-catcher (Muscicapa grisola) can hardly be distinguished, whilst the sexes of the pied fly-catcher (M. luctuosa) differ considerably, and both species build in holes or conceal their nests. The female blackbird (Turdus merula) differs much, the female ring-ouzel (T. torquatus) differs less, and the female common thrush (T. musicus) hardly at all from their respective males; yet all build open nests. On the other hand, the not very distantly-allied water-ouzel (Cinclus aquaticus) builds a domed nest, and the sexes differ about as much as in the ring-ouzel. The black and red grouse (Tetrao tetrix and T. scoticus) build open nests in equally well-concealed spots, but in the one species the sexes differ greatly, and in the other very little.
* I have consulted, on this subject, Macgillivray's British Birds, and though doubts may be entertained in some cases in regard to the degree of concealment of the nest, and to the degree of conspicuousness of the female, yet the following birds, which all lay their eggs in holes or in domed nests, can hardly be considered, by the above standard, as conspicuous: Passer, 2 species; Sturnus, of which the female is considerably less brilliant than the male; Cinclus; Motallica boarula (?); Erithacus (?); Fruticola, 2 sp.; Saxicola; Ruticilla, 2 sp.; Sylvia, 3 sp.; Parus, 3 sp.; Mecistura anorthura; Certhia; Sitta; Yunx; Muscicapa, 2 sp.; Hirundo, 3 sp.; and Cypselus. The females of the following 12 birds may be considered as conspicuous according to the same standard, viz., Pastor, Motacilla alba, Parus major and P. caeruleus, Upupa, Picus, 4 sp., Coracias, Alcedo, and Merops.
Notwithstanding the foregoing objections, I cannot doubt, after reading Mr. Wallace's excellent essay, that looking to the birds of the world, a large majority of the species in which the females are conspicuously coloured (and in this case the males with rare exceptions are equally conspicuous), build concealed nests for the sake of protection. Mr. Wallace enumerates* a long series of groups in which this rule bolds good; but it will suffice here to give, as instances, the more familiar groups of kingfishers, toucans, trogons, puff-birds (Capitonidae), plantain-eaters (Musophagae, woodpeckers, and parrots. Mr. Wallace believes that in these groups, as the males gradually acquired through sexual selection their brilliant colours, these were transferred to the females and were not eliminated by natural selection, owing to the protection which they already enjoyed from their manner of nidification. According to this view, their present manner of nesting was acquired before their present colours. But it seems to me much more probable that in most cases, as the females were gradually rendered more and more brilliant from partaking of the colours of the male, they were gradually led to change their instincts (supposing that they originally built open nests), and to seek protection by building domed or concealed nests. No one who studies, for instance, Audubon's account of the differences in the nests of the same species in the northern and southern United States,*(2) will feel any great difficulty in admitting that birds, either by a change (in the strict sense of the word) of their habits, or through the natural selection of so-called spontaneous variations of instinct, might readily be led to modify their manner of nesting.
* Journal of Travel, edited by A. Murray, vol. i., p. 78.
*(2) See many statements in the Ornithological Biography. See also some curious observations on the nests of Italian birds by Eugenio Bettoni, in the Atti della Societa Italiana, vol. xi., 1869, p. 487.
This way of viewing the relation, as far as it holds good, between the bright colours of female birds and their manner of nesting, receives some support from certain cases occurring in the Sahara Desert. Here, as in most other deserts, various birds, and many other animals, have had their colours adapted in a wonderful manner to the tints of the surrounding surface. Nevertheless there are, as I am informed by the Rev. Mr. Tristram, some curious exceptions to the rule; thus the male of the Monticola cyanea is conspicuous from his bright blue colour, and the female almost equally conspicuous from her mottled brown and white plumage; both sexes of two species of Dromolaea are of a lustrous black; so that these three species are far from receiving protection from their colours, yet they are able to survive, for they have acquired the habit of taking refuge from danger in holes or crevices in the rocks.
With respect to the above groups in which the females are conspicuously coloured and build concealed nests, it is not necessary to suppose that each separate species had its nidifying instinct specially modified; but only that the early progenitors of each group were gradually led to build domed or concealed nests, and afterwards transmitted this instinct, together with their bright colours, to their modified descendants. As far as it can be trusted, the conclusion is interesting, that sexual selection together with equal or nearly equal inheritance by both sexes, have indirectly determined the manner of nidification of whole groups of birds.
According to Mr. Wallace, even in the groups in which the females, from being protected in domed nests during incubation, have not had their bright colours eliminated through natural selection, the males often differ in a slight, and occasionally in a considerable degree from the females. This is a significant fact, for such differences in colour must be accounted for by some of the variations in the males having been from the first limited in transmission to the same sex; as it can hardly be maintained that these differences, especially when very slight, serve as a protection to the female. Thus all the species in the splendid group of the trogons build in holes; and Mr. Gould gives figures* of both sexes of twenty-five species, in all of which, with one partial exception, the sexes differ sometimes slightly, sometimes conspicuously, in colour,- the males being always finer than the females, though the latter are likewise beautiful. All the species of kingfishers build in holes, and with most of the species the sexes are equally brilliant, and thus far Mr. Wallace's rule holds good; but in some of the Australian species the colours of the females are rather less vivid than those of the male; and in one splendidly-coloured species, the sexes differ so much that they were at first thought to be specifically distinct.*(2) Mr. R. B. Sharpe, who has especially studied this group, has shewn me some American species (Ceryle) in which the breast of the male is belted with black. Again, in Carcineutes, the difference between the sexes is conspicuous: in the male the upper surface is dull-blue banded with black, the lower surface being partly fawn-coloured, and there is much red about the head; in the female the upper surface is reddish-brown banded with black, and the lower surface white with black markings It is an interesting fact, as shewing how the same peculiar style of sexual colouring often characterises allied forms, that in three species of Dacelo the male differs from the female only in the tail being dull-blue banded with black, whilst that of the female is brown with blackish bars; so that here the tail differs in colour in the two sexes in exactly the same manner as the whole upper surface in the two sexes of Carcineutes.
* See his Monograph of the Trogonidae, 1st edition.
*(2) Namely, Cyanalcyon. Gould's Handbook of the Birds of Australia, vol. i., p. 133; see, also, pp. 130, 136.
With parrots, which likewise build in holes, we find analogous cases: in most of the species, both sexes are brilliantly coloured and indistinguishable, but in not a few species the males are coloured rather more vividly than the females, or even very differently from them. Thus, besides other strongly-marked differences, the whole under surface of the male king lory (Aprosmictus scapulatus) is scarlet, whilst the throat and chest of the female is green tinged with red: in the Euphema splendida there is a similar difference, the face and wing coverts moreover of the female being of a paler blue than in the male.* In the family of the tits (Parinae), which build concealed nests, the female of our common blue tomtit (Parus caeruleus), is "much less brightly coloured" than the male: and in the magnificent sultan yellow tit of India the difference is greater.*(2)
* Every gradation of difference between the sexes may be followed in the parrots of Australia. See Gould, op. cit., vol. ii., pp. 14-102.
*(2) Macgillivray's British Birds, vol. ii., p. 433. Jerdon, Birds of India, vol. ii., p. 282.
Again, in the great group of the woodpeckers,* the sexes are generally nearly alike, but in the Megapicus validus all those parts of the head, neck, and breast, which are crimson in the male are pale brown in the female. As in several woodpeckers the head of the male is bright crimson, whilst that of the female is plain, it occurred to me that this colour might possibly make the female dangerously conspicuous, whenever she put her head out of the hole containing her nest, and consequently that this colour, in accordance with Mr. Wallace's belief, had been eliminated. This view is strengthened by what Malherbe states with respect to Indopicus carlotta; namely, that the young females, like the young males, have some crimson about their heads, but that this colour disappears in the adult female, whilst it is intensified in the adult male. Nevertheless the following considerations render this view extremely doubtful: the male takes a fair share in incubation,*(2) and would be thus almost equally exposed to danger; both sexes of many species have their heads of an equally bright crimson; in other species the difference between the sexes in the amount of scarlet is so slight that it can hardly make any appreciable difference in the danger incurred; and lastly, the colouring of the head in the two sexes often differs slightly in other ways.
* All the following facts are taken from M. Malherbe's magnificent Monographie des Picidees, 1861.
*(2) Audubon's Ornithological Biography, vol. ii., p. 75; see also the Ibis, vol. i., p. 268.
The cases, as yet given, of slight and graduated differences in colour between the males and females in the groups, in which as a general rule the sexes resemble each other, all relate to species which build domed or concealed nests. But similar gradations may likewise be observed in groups in which the sexes as a general rule resemble each other, but which build open nests.
As I have before instanced the Australian parrots, so I may here instance, without giving any details, the Australian pigeons.* It deserves especial notice that in all these cases the slight differences in plumage between the sexes are of the same general nature as the occasionally greater differences. A good illustration of this fact has already been afforded by those kingfishers in which either the tail alone or the whole upper surface of the plumage differs in the same manner in the two sexes. Similar cases may be observed with parrots and pigeons. The differences in colour between the sexes of the same species are, also, of the same general nature as the differences in colour between the distinct species of the same group. For when in a group in which the sexes are usually alike, the male differs considerably from the female, he is not coloured in a quite new style. Hence we may infer that within the same group the special colours of both sexes when they are alike, and the colours of the male, when he differs slightly or even considerably from the female, have been in most cases determined by the same general cause; this being sexual selection.
* Gould's Handbook of the Birds of Australia, vol. ii., pp. 109-149.
It is not probable, as has already been remarked, that differences in colour between the sexes, when very slight, can be of service to the female as a protection. Assuming, however, that they are of service, they might be thought to be cases of transition; but we have no reason to believe that many species at any one time are undergoing change. Therefore we can hardly admit that the numerous females which differ very slightly in colour from their males are now all commencing to become obscure for the sake of protection. Even if we consider somewhat more marked sexual differences, is it probable, for instance, that the head of the female chaffinch,- the crimson on the breast of the female bullfinch,- the green of the female greenfinch,- the crest of the female golden-crested wren, have all been rendered less bright by the slow process of selection for the sake of protection? I cannot think so; and still less with the slight differences between the sexes of those birds which build concealed nests. On the other hand, the differences in colour between the sexes, whether great or small, may to a large extent be explained on the principle of the successive variations, acquired by the males through sexual selection, having been from the first more or less limited in their transmission to the females. That the degree of limitation should differ in different species of the same group will not surprise any one who has studied the laws of inheritance, for they are so complex that they appear to us in our ignorance to be capricious in their action.*
* See remarks to this effect in Variation of Animals and Plants under Domestication, vol. ii., chap. xii.
As far as I can discover there are few large groups of birds in which all the species have both sexes alike and brilliantly coloured, but I hear from Mr. Sclater, that this appears to be the case with the Musophagae or plantain-eaters. Nor do I believe that any large group exists in which the sexes of all the species are widely dissimilar in colour: Mr. Wallace informs me that the chatterers of S. America (Cotingidae) offer one of the best instances; but with some of the species, in which the male has a splendid red breast, the female exhibits some red on her breast; and the females of other species shew traces of the green and other colours of the males. Nevertheless we have a near approach to close sexual similarity or dissimilarity throughout several groups: and this, from what has just been said of the fluctuating nature of inheritance, is a somewhat surprising circumstance. But that the same laws should largely prevail with allied animals is not surprising. The domestic fowl has produced a great number of breeds and sub-breeds, and in these the sexes generally differ in plumage; so that it has been noticed as an unusual circumstance when in certain sub-breeds they resemble each other. On the other hand, the domestic pigeon has likewise produced a vast number of distinct breeds and sub-breeds, and in these, with rare exceptions, the two sexes are identically alike.
Therefore if other species of Gallus and Columba were domesticated and varied, it would not be rash to predict that similar rules of sexual similarity and dissimilarity, depending on the form of transmission, would hold good in both cases. In like manner the same form of transmission has generally prevailed under nature throughout the same groups, although marked exceptions to this rule occur. Thus within the same family or even genus, the sexes may be identically alike, or very different in colour. Instances have already been given in the same genus, as with sparrows, flycatchers, thrushes and grouse. In the family of pheasants the sexes of almost all the species are wonderfully dissimilar, but are quite alike in the eared pheasant or Crossoptilon auritum. In two species of Chloephaga, a genus of geese, the male cannot be distinguished from the females, except by size; whilst in two others, the sexes are so unlike that they might easily be mistaken for distinct species.*
* The Ibis, vol. vi., 1864, p. 122.
The laws of inheritance can alone account for the following cases, in which the female acquires, late in life, certain characters proper to the male, and ultimately comes to resemble him more or less completely. Here protection can hardly have come into play. Mr. Blyth informs me that the females of Oriolus melanocephalus and of some allied species, when sufficiently mature to breed, differ considerably in plumage from the adult males; but after the second or third moults they differ only in their beaks having a slight greenish tinge. In the dwarf bitterns (Ardetta), according to the same authority, "the male acquires his final livery at the first moult, the female not before the third or fourth moult; in the meanwhile she presents an intermediate garb, which is ultimately exchanged for the same livery as that of the male." So again the female Falco peregrinus acquires her blue plumage more slowly than the male. Mr. Swinhoe states that with one of the drongo shrikes (Dicrurus macrocercus) the male, whilst almost a nestling, moults his soft brown plumage and becomes of a uniform glossy greenish-black; but the female retains for a long time the white striae and spots on the axillary feathers; and does not completely assume the uniform black colour of the male for three years. The same excellent observer remarks that in the spring of the second year the female spoon-bill (Platalea) of China resembles the male of the first year, and that apparently it is not until the third spring that she acquires the same adult plumage as that possessed by the male at a much earlier age. The female Bombycilla carolinensis differs very little from the male, but the appendages, which like beads of red sealing-wax ornament the wing-feathers,* are not developed in her so early in life as in the male. In the male of an Indian parrakeet (Paloeornis javanicus) the upper mandible is coral-red from his earliest youth, but in the female, as Mr. Blyth has observed with caged and wild birds, it is at first black and does not become red until the bird is at least a year old, at which age the sexes resemble each other in all respects. Both sexes of the wild turkey are ultimately furnished with a tuft of bristles on the breast, but in two-year-old birds the tuft is about four inches long in the male and hardly apparent in the female; when, however, the latter has reached her fourth year, it is from four to five inches in length.*(2)
* When the male courts the female, these ornaments are vibrated, and "are shewn off to great advantage," on the outstretched wings: A. Leith Adams, Field and Forest Rambles, 1873, p. 153.
*(2) On Ardetta, Translation of Cuvier's Regne Animal, by Mr. Blyth, footnote, p. 159. On the peregrine falcon, Mr. Blyth, in Charlesworth's Mag. of Nat. Hist., vol. i., 1837, p. 304. On Dicrurus, Ibis, 1863, p. 44. On the Platalea, Ibis, vol. vi., 1864, p. 366. On the Bombycilla, Audubon's Ornitholog. Biography, vol. i., p. 229. On the Palaeornis, see, also, Jerdon, Birds of India, vol. i., p. 263. On the wild turkey, Audubon, ibid., vol. i., p. 15; but I hear from Judge Caton that in Illinois the female very rarely acquires a tuft. Analogous cases with the females of Petrcocssyphus are given by Mr. R. Sharpe, Proeedings of the Zoological Society, 1872, p. 496.
These cases must not be confounded with those where diseased or old females abnormally assume masculine characters, nor with those where fertile females, whilst young, acquire the characters of the male, through variation or some unknown cause.* But all these cases have so much in common that they depend, according to the hypothesis of pangenesis, on gemmules derived from each part of the male being present, though latent, in the female; their development following on some slight change in the elective affinities of her constituent tissues.
* Of these latter cases Mr. Blyth has recorded (Translation of Cuvier's Regne Animal, p. 158) various instances with Lanius, Ruticilla, Linaria, and Anas. Audubon has also recorded a similar case (Ornitholog. Biography, vol. v., p. 519) with Pyranga aestiva.
A few words must be added on changes of plumage in relation to the season of the year. From reasons formerly assigned there can be little doubt that the elegant plumes, long pendant feathers, crests, &c., of egrets, herons, and many other birds, which are developed and retained only during the summer, serve for ornamental and nuptial purposes, though common to both sexes. The female is thus rendered more conspicuous during the period of incubation than during the winter; but such birds as herons and egrets would be able to defend themselves. As, however, plumes would probably be inconvenient and certainly of no use during the winter, it is possible that the habit of moulting twice in the year may have been gradually acquired through natural selection for the sake of casting off inconvenient ornaments during the winter. But this view cannot be extended to the many waders, whose summer and winter plumages differ very little in colour. With defenceless species, in which both sexes, or the males alone, become extremely conspicuous during the breeding-season,- or when the males acquire at this season such long wing or tail-feathers as to impede their flight, as with Cosmetornis and Vidua,- it certainly at first appears highly probable that the second moult has been gained for the special purpose of throwing off these ornaments. We must, however, remember that many birds, such as some of the birds of paradise, the Argus pheasant and peacock, do not cast their plumes during the winter; and it can hardly be maintained that the constitution of these birds, at least of the Gallinaceae, renders a double moult impossible, for the ptarmigan moults thrice in the year.* Hence it must be considered as doubtful whether the many species which moult their ornamental plumes or lose their bright colours during the winter, have acquired this habit on account of the inconvenience or danger which they would otherwise have suffered.
* See Gould's Birds of Great Britain.
I conclude, therefore, that the habit of moulting twice in the year was in most or all cases first acquired for some distinct purpose, perhaps for gaining a warmer winter covering; and that variations in the plumage occurring during the summer were accumulated through sexual selection, and transmitted to the offspring at the same season of the year; that such variations were inherited either by both sexes or by the males alone, according to the form of inheritance which prevailed. This appears more probable than that the species in all cases originally tended to retain their ornamental plumage during the winter, but were saved from this through natural selection, resulting from the inconvenience or danger thus caused.
I have endeavoured in this chapter to shew that the arguments are not trustworthy in favour of the view that weapons, bright colours, and various ornaments, are now confined to the males owing to the conversion, by natural selection, of the equal transmission of characters to both sexes, into transmission to the male sex alone. It is also doubtful whether the colours of many female birds are due to the preservation, for the sake of protection, of variations which were from the first limited in their transmission to the female sex. But it will be convenient to defer any further discussion on this subject until I treat, in the following chapter, of the differences in plumage between the young and old.
|
See also the
Dr. Math FAQ:
order of operations
Browse High School Basic Algebra
Stars indicate particularly interesting answers or
good places to begin browsing.
Selected answers to common questions:
Solving simple linear equations.
Positive/negative integer rules.
Completing the square.
Direct and indirect variation.
Inequalities and negative numbers.
- Normalization [08/01/2001]
How do I figure out: 90 + 70 + 88 + 94 + x / 5 = 85 ?
- The Nth Root of N [11/28/2000]
Is the nth root of n (a whole number other than 1) ever a rational
- Number of Equations Needed in a Simultaneous Linear System [10/29/2003]
Could you tell me why we need the same number of equations as
variables in order to get a unique solution to a system of
simultaneous linear equations?
- Number * Sum of Remaining Four Numbers [04/03/2003]
Find 5 numbers such that when each number is multiplied by the sum of
the remaining 4 numbers, the following values will result: 152, 245,
297, 320, 360.
- Objects in a Pyramid [7/8/1996]
Objects are stacked in a triangular pyramid... how many objects are in
the nth layer from the top?
- Old Test Questions Answered [1/23/1995]
I am studying for my midterm, and I've come across two questions that I
got wrong and don't understand why....
- One Variable Equations with Decimals [02/11/1997]
How do you solve 8.25x + 3 = 17.5 + x?
- Open Sentence, Statement [09/18/2001]
What is an open sentence?
- Operator Precedence [08/13/2003]
Since the following statement is true: (1+1)**(5-2) is 8, why is the
following statement true and not false: 2**1+1 is 3 and not 4, and
3*1**3 is 3 and not 27...' ?
- Ordering Exponents and Variables [04/08/2000]
Is there a rule for putting terms in descending order if the variables
have the same exponent? What about negative exponents and descending
- Ordering Products, Powers, and Parameters of Trigonometric Functions [10/31/2010]
A student wants to know how to unambiguously interpret strings of trigonometric
functions, multiplication, and exponentiation. Doctor Peterson digs into a history book
-- as well as another math doctor's conversation -- to illuminate the vagaries of the
- Order in Linear Expressions [11/20/2001]
Can you give me a convincing argument as to why, in an equation such as
y=13-7x, where y is a function of x, it should be written as y=-7x+13?
- Order of Operations [05/19/1999]
Given a, b, x, and y, find ax/by.
- Order of Operations with Percentages [04/05/2001]
Why does the order of operations exclude percentage, square roots, etc.?
- Other Ways to Get the Quadratic Formula [02/19/2010]
Doctor Jacques shares two ways to derive [-b +/- SQRT(b^2 - 4ac)]/2a
without explicitly completing the square.
- Pairs of Odd Integers [09/24/1997]
Find all pairs of odd integers a and b that satisfy the equation: a +
128b = 3ab.
- Parabola with Horizontal or Vertical Axis [05/03/2001]
How can I find the focus and directrix of a parabola whose axis is either
horizontal or vertical, like 2x^2 = -y?
- Parabolic Golf Shot Equations [01/24/2002]
Does the ball reach the green?
- Parallel and Perpendicular Lines [01/14/1999]
How do you tell without graphing whether the graphs of these equations
are parallel, perpendicular, or neither?
- Parallel Lines [12/31/1998]
What are some ways of proving lines parallel - geometrically and
- Parametric Form for Equation of a Line [6/30/1996]
How can you convert an equation such as y = -3x/4 + 7/2 to parametric
- Parity [8/2/1996]
How do I determine if the given function is odd, even or neither? What's
the symmetry of the graph?
- Partial Fractions [01/29/1998]
How do I express 3/1-(x^3) in partial fractions?
- Pascal's Triangle Pattern [04/22/1999]
What pattern does multiplying each entry by 1, 2, 3, 4, 5... in order,
and adding the products yield?
- Perfect Square: Solving Two Equations [6/14/1996]
x^2 + 5 is a perfect square, and x^2 - 5 is a perfect square.
- Perimeter Equals Area in a Triangle [4/2/1996]
When will the area and perimeter of a right triangle be numerically
- Picture Frame, Triangle Measurements [5/20/1996]
My teacher gave us ten questions to answer and I could do all except two:
1) A framed rectangular picture is 35cm long and 25cm wide... 2) The base
of a triangle is 9cm more than the perpendicular height...
- Plus or Minus Sign [03/08/2002]
What does this equation mean: y = +- k ? The - sign is directly under the
- Point Equidistant from 3 Other Points [04/11/1999]
How do you find a point that is equidistant from three other points?
- Point on a Line [03/23/2001]
Can you please tell me a formula to find if a point exists on a line?
Both are in x,y form.
- Polynomial Brain-Twisters [12/4/1995]
I'm stumped on some similar polynomial problems...
- Polynomial Degrees and Definition of a Field [03/02/1998]
The degree of polynomials added together, and definition of a field.
- Polynomial Factoring Rules [04/02/1997]
How do I apply the polynomial factoring rules to t^21+1 and 25y^2-144 =
- Polynomial Problem [3/11/1995]
A remainder of 9 results when the polynomial p(x) is divided by x-2, a
remainder of -3 when p(x) is divided by x+2, and a remainder of 3 when
divided by x-1. Find the remainder when p(x) is divided by (x-2)(x+2)(x-
- Population and Percentage [03/07/1999]
Given population data, find the number of women in two different years.
- Positive Unit Fractions [10/02/2002]
Find five different positive unit fractions whose sum is 1. (A unit
fraction is a fraction whose numerator is 1. All denominators must
also be natural numbers.)
- Precedence of Unary Operators [09/01/99]
The PEMDAS rule for order of operations ignores unary operators. Can you
explain the proper precedence for them, and give an example showing how
not knowing the rule can cause an incorrect result?
- Preparing for an Algebra Test [11/1/1995]
A 9th grade math student asks for help preparing for final exams. What is
the difference between the terms: solve and simplify? How do you find the
gradient in a graph?
- Prize Money [09/04/1997]
If first prize wins $1,000 out of $6,000 and twentieth prize wins $100,
how much money do second through nineteenth place win? Is this a
- Probability of a Function Having Complex Roots [05/11/2000]
What is the probability that the function f(x) = x^2 + px + q = 0 will
have complex roots when p and q lie between 0 and 1? ...when p and q lie
between 0 and 5? ...when p and q are greater than 0?
|
Hydrocele Operation: aka Hydroceles, Hydrocele Sac, Swollen Testicle, Hydrocelectomy
What is it?
Hydrocele operations or hydrocele surgery is to release fluid that forms in a sac within the scrotum. Typically hydroceles develop when the testicle passes into the scrotum but the passage through which this occur fails to close properly. Fluid can accumulate in this passage from the abdomen, and then enters the scrotum causing it to swell.
This can cause one or both sides of the scrotum to swell and the testicle itself to swell or become damage and inflamed. Fluid can also block the tube where sperm typically flow from. Hydroceles are more common in newborn boys but are not exclusive to newborn boys. To diagnose a hydrocele typically a doctor will look for swelling in the scrotum caused primarily by fluid build up or will look for something solid like a fluid-filled sac in the scrotum.
Typically fluid is removed from the hydrocele sac during a procedure called a hydrocelectomy. For the most part this is a straightforward and uncomplicated procedure that may produce a moderate amount of soreness for a few days following the procedure. The long-term benefits far outweigh any short-term soreness.
Many times the patient is a young patient under the age of 10 or in many cases a newborn baby that is born with a hydrocele defect. Usually a surgery takes placed under general anesthesia. A surgeon will make a small incision in the scrotum that will allow fluid to be drained from the scrotum and then seal the passage from the scrotum to the abdomen. Usually the incision is then closed with stitches that will dissolve on their own so they do not have to be removed later.
Alternatives to Surgery
There are no known alternatives to this surgery currently.
Before the Operation
Prior to the operation the doctor will confirm a fluid filled sac exists by placing a light to the scrotum which will light up the testicles, veins in the scrotum and the fluid filled sac which will appear clear to the light.
A doctor will also perform a comprehensive medical history and check any medications the patient is currently taking. Patients are advised not to eat or drink anything up to 12 hours before the procedure because it is performed under general anesthesia.
After the Operation- At Home
Once the operation is complete the patient will recover usually for a few hours in a day bed. The procedure is usually performed on an outpatient basis meaning the patient can usually go home on the same day. Most of the time it is best to wear looser fitting close that will prevent irritation and discomfort on leaving.
There are some risks associated with this procedure as there are with any procedure including a small risk of infection. Other risks including the risk of bleeding during or after the procedure, and a risk of a blood clot forming in the area of the procedure. The doctor may accidentally damage the scrotum or the tissues surrounding this area too.
Anytime a patient undergoes general anesthesia there are risks associated with this too including a risk of pneumonia following surgery. The nurse or doctor will encourage the patient to take deep breaths to clear the lungs following surgery. Many people especially younger children undergoing this operation may report feeling nauseous or dizzy following the procedure, a side effect largely associated with the general anesthesia. These complications are usually temporary however and resolve within a couple of days of treatment.
A hydrocele procedure is generally performed to relieve fluid build up around the testicle or within the scrotum. This procedure is relatively simple with few complications. The primary risks include a risk of infection and risk of rupture or nicks to nearby tissues or structures. If you work with a competent health professional you reduce your odds of complications.
Because these surgeries are often performed on younger individuals it pays to ask someone if they have experience working on youths or pediatric patients. You may need to pay a small amount extra to work with someone that specializes in pediatrics or even geriatrics if you are over 50 or 60 and have a fluid-filled sac in the scrotum that you require surgery for. Regardless of where you go or who you see make sure they practice safe hygiene practices to ensure your safety and wellness.
Estimated Costs for Hydrocele Operation
The cost of surgery varies widely and may depend partly on the patient’s age and overall health and wellness. Patients that do not require extensive health accommodations or hospital stays are likely to have to pay the least in adjunctive healthcare therapy. That said you should always be prepared to foot the bill for extra expenses including any complications that may rise from treatment. Health insurance may offset some of these costs.
Keep in mind there may be separate fees associated with anesthesia. The hospital and anesthesia fees are usually separate from the fees charged for the procedure itself, although some medical tourism companies tend to provide all-inclusive packages for their patients. This may be the best option for individuals that plan to travel abroad already and want to fit in a little health care while traveling for pleasure.
|Country||Costs Hydrocele Operation|
|
Welcome to MedLibrary.org. For best results, we recommend beginning with the navigation links at the top of the page, which can guide you through our collection of over 14,000 medication labels and package inserts. For additional information on other topics which are not covered by our database of medications, just enter your topic in the search box below:
Chromatography [|krəʊmə|tɒgrəfi] (from Greek χρῶμα chroma "color" and γράφειν graphein "to write") is the collective term for a set of laboratory techniques for the separation of mixtures. The mixture is dissolved in a fluid called the mobile phase, which carries it through a structure holding another material called the stationary phase. The various constituents of the mixture travel at different speeds, causing them to separate. The separation is based on differential partitioning between the mobile and stationary phases. Subtle differences in a compound's partition coefficient result in differential retention on the stationary phase and thus changing the separation.
Chromatography may be preparative or analytical. The purpose of preparative chromatography is to separate the components of a mixture for more advanced use (and is thus a form of purification). Analytical chromatography is done normally with smaller amounts of material and is for measuring the relative proportions of analytes in a mixture. The two are not mutually exclusive.
Chromatography, literally "color writing", was first employed by Russian-Italian scientist Mikhail Tsvet in 1900. He continued to work with chromatography in the first decade of the 20th century, primarily for the separation of plant pigments such as chlorophyll, carotenes, and xanthophylls. Since these components have different colors (green, orange, and yellow, respectively) they gave the technique its name. New types of chromatography developed during the 1930s and 1940s made the technique useful for many separation processes.
Chromatography technique developed substantially as a result of the work of Archer John Porter Martin and Richard Laurence Millington Synge during the 1940s and 1950s. They established the principles and basic techniques of partition chromatography, and their work encouraged the rapid development of several chromatographic methods: paper chromatography, gas chromatography, and what would become known as high performance liquid chromatography. Since then, the technology has advanced rapidly. Researchers found that the main principles of Tsvet's chromatography could be applied in many different ways, resulting in the different varieties of chromatography described below. Advances are continually improving the technical performance of chromatography, allowing the separation of increasingly similar molecules.
Chromatography terms
- The analyte is the substance to be separated during chromatography.
- Analytical chromatography is used to determine the existence and possibly also the concentration of analyte(s) in a sample.
- A bonded phase is a stationary phase that is covalently bonded to the support particles or to the inside wall of the column tubing.
- A chromatogram is the visual output of the chromatograph. In the case of an optimal separation, different peaks or patterns on the chromatogram correspond to different components of the separated mixture.
- Plotted on the x-axis is the retention time and plotted on the y-axis a signal (for example obtained by a spectrophotometer, mass spectrometer or a variety of other detectors) corresponding to the response created by the analytes exiting the system. In the case of an optimal system the signal is proportional to the concentration of the specific analyte separated.
- A chromatograph is equipment that enables a sophisticated separation e.g. gas chromatographic or liquid chromatographic separation.
- Chromatography is a physical method of separation that distributes components to separate between two phases, one stationary (stationary phase), while the other (the mobile phase) moves in a definite direction.
- The eluate is the mobile phase leaving the column.
- The eluent is the solvent that carries the analyte.
- An eluotropic series is a list of solvents ranked according to their eluting power.
- An immobilized phase is a stationary phase that is immobilized on the support particles, or on the inner wall of the column tubing.
- The mobile phase is the phase that moves in a definite direction. It may be a liquid (LC and Capillary Electrochromatography (CEC)), a gas (GC), or a supercritical fluid (supercritical-fluid chromatography, SFC). The mobile phase consists of the sample being separated/analyzed and the solvent that moves the sample through the column. In the case of HPLC the mobile phase consists of a non-polar solvent(s) such as hexane in normal phase or polar solvents in reverse phase chromotagraphy and the sample being separated. The mobile phase moves through the chromatography column (the stationary phase) where the sample interacts with the stationary phase and is separated.
- Preparative chromatography is used to purify sufficient quantities of a substance for further use, rather than analysis.
- The retention time is the characteristic time it takes for a particular analyte to pass through the system (from the column inlet to the detector) under set conditions. See also: Kovats' retention index
- The sample is the matter analyzed in chromatography. It may consist of a single component or it may be a mixture of components. When the sample is treated in the course of an analysis, the phase or the phases containing the analytes of interest is/are referred to as the sample whereas everything out of interest separated from the sample before or in the course of the analysis is referred to as waste.
- The solute refers to the sample components in partition chromatography.
- The solvent refers to any substance capable of solubilizing another substance, and especially the liquid mobile phase in liquid chromatography.
- The stationary phase is the substance fixed in place for the chromatography procedure. Examples include the silica layer in thin layer chromatography
Chromatography is based on the concept of partition coefficient. Any solute partitions between two immiscible solvents. When we make one solvent immobile (by adsorption on a solid support matrix) and another mobile it results in most common applications of chromatography. If matrix support is polar (e.g. paper, silica etc.) it is forward phase chromatography, and if it is non polar (C-18) it is reverse phase.
Techniques by chromatographic bed shape
Column chromatography
Column chromatography is a separation technique in which the stationary bed is within a tube. The particles of the solid stationary phase or the support coated with a liquid stationary phase may fill the whole inside volume of the tube (packed column) or be concentrated on or along the inside tube wall leaving an open, unrestricted path for the mobile phase in the middle part of the tube (open tubular column). Differences in rates of movement through the medium are calculated to different retention times of the sample.
In 1978, W. C. Still introduced a modified version of column chromatography called flash column chromatography (flash). The technique is very similar to the traditional column chromatography, except for that the solvent is driven through the column by applying positive pressure. This allowed most separations to be performed in less than 20 minutes, with improved separations compared to the old method. Modern flash chromatography systems are sold as pre-packed plastic cartridges, and the solvent is pumped through the cartridge. Systems may also be linked with detectors and fraction collectors providing automation. The introduction of gradient pumps resulted in quicker separations and less solvent usage.
In expanded bed adsorption, a fluidized bed is used, rather than a solid phase made by a packed bed. This allows omission of initial clearing steps such as centrifugation and filtration, for culture broths or slurries of broken cells.
Phosphocellulose chromatography utilizes the binding affinity of many DNA-binding proteins for phosphocellulose. The stronger a protein's interaction with DNA, the higher the salt concentration needed to elute that protein.
Planar chromatography
Planar chromatography is a separation technique in which the stationary phase is present as or on a plane. The plane can be a paper, serving as such or impregnated by a substance as the stationary bed (paper chromatography) or a layer of solid particles spread on a support such as a glass plate (thin layer chromatography). Different compounds in the sample mixture travel different distances according to how strongly they interact with the stationary phase as compared to the mobile phase. The specific Retention factor (Rf) of each chemical can be used to aid in the identification of an unknown substance.
Paper chromatography
Paper chromatography is a technique that involves placing a small dot or line of sample solution onto a strip of chromatography paper. The paper is placed in a jar containing a shallow layer of solvent and sealed. As the solvent rises through the paper, it meets the sample mixture, which starts to travel up the paper with the solvent. This paper is made of cellulose, a polar substance, and the compounds within the mixture travel farther if they are non-polar. More polar substances bond with the cellulose paper more quickly, and therefore do not travel as far.
Thin layer chromatography
Thin layer chromatography (TLC) is a widely employed laboratory technique and is similar to paper chromatography. However, instead of using a stationary phase of paper, it involves a stationary phase of a thin layer of adsorbent like silica gel, alumina, or cellulose on a flat, inert substrate. Compared to paper, it has the advantage of faster runs, better separations, and the choice between different adsorbents. For even better resolution and to allow for quantification, high-performance TLC can be used.
Displacement chromatography
The basic principle of displacement chromatography is: A molecule with a high affinity for the chromatography matrix (the displacer) competes effectively for binding sites, and thus displace all molecules with lesser affinities. There are distinct differences between displacement and elution chromatography. In elution mode, substances typically emerge from a column in narrow, Gaussian peaks. Wide separation of peaks, preferably to baseline, is desired for maximum purification. The speed at which any component of a mixture travels down the column in elution mode depends on many factors. But for two substances to travel at different speeds, and thereby be resolved, there must be substantial differences in some interaction between the biomolecules and the chromatography matrix. Operating parameters are adjusted to maximize the effect of this difference. In many cases, baseline separation of the peaks can be achieved only with gradient elution and low column loadings. Thus, two drawbacks to elution mode chromatography, especially at the preparative scale, are operational complexity, due to gradient solvent pumping, and low throughput, due to low column loadings. Displacement chromatography has advantages over elution chromatography in that components are resolved into consecutive zones of pure substances rather than “peaks”. Because the process takes advantage of the nonlinearity of the isotherms, a larger column feed can be separated on a given column with the purified components recovered at significantly higher concentrations.
Techniques by physical state of mobile phase
Gas chromatography
Gas chromatography (GC), also sometimes known as gas-liquid chromatography, (GLC), is a separation technique in which the mobile phase is a gas. Gas chromatography is always carried out in a column, which is typically "packed" or "capillary" (see below).
Gas chromatography is based on a partition equilibrium of analyte between a solid stationary phase (often a liquid silicone-based material) and a mobile gas (most often helium). The stationary phase is adhered to the inside of a small-diameter glass tube (a capillary column) or a solid matrix inside a larger metal tube (a packed column). It is widely used in analytical chemistry; though the high temperatures used in GC make it unsuitable for high molecular weight biopolymers or proteins (heat denatures them), frequently encountered in biochemistry, it is well suited for use in the petrochemical, environmental monitoring and remediation, and industrial chemical fields. It is also used extensively in chemistry research.
Liquid chromatography
Liquid chromatography (LC) is a separation technique in which the mobile phase is a liquid. Liquid chromatography can be carried out either in a column or a plane. Present day liquid chromatography that generally utilizes very small packing particles and a relatively high pressure is referred to as high performance liquid chromatography (HPLC).
In HPLC the sample is forced by a liquid at high pressure (the mobile phase) through a column that is packed with a stationary phase composed of irregularly or spherically shaped particles, a porous monolithic layer, or a porous membrane. HPLC is historically divided into two different sub-classes based on the polarity of the mobile and stationary phases. Methods in which the stationary phase is more polar than the mobile phase (e.g., toluene as the mobile phase, silica as the stationary phase) are termed normal phase liquid chromatography (NPLC) and the opposite (e.g., water-methanol mixture as the mobile phase and C18 = octadecylsilyl as the stationary phase) is termed reversed phase liquid chromatography (RPLC). Ironically the "normal phase" has fewer applications and RPLC is therefore used considerably more.
Specific techniques under this broad heading are listed below.
Affinity chromatography
Affinity chromatography is based on selective non-covalent interaction between an analyte and specific molecules. It is very specific, but not very robust. It is often used in biochemistry in the purification of proteins bound to tags. These fusion proteins are labeled with compounds such as His-tags, biotin or antigens, which bind to the stationary phase specifically. After purification, some of these tags are usually removed and the pure protein is obtained.
Affinity chromatography often utilizes a biomolecule's affinity for a metal (Zn, Cu, Fe, etc.). Columns are often manually prepared. Traditional affinity columns are used as a preparative step to flush out unwanted biomolecules.
However, HPLC techniques exist that do utilize affinity chromatogaphy properties. Immobilized Metal Affinity Chromatography (IMAC) is useful to separate aforementioned molecules based on the relative affinity for the metal (I.e. Dionex IMAC). Often these columns can be loaded with different metals to create a column with a targeted affinity.
Supercritical fluid chromatography
Supercritical fluid chromatography is a separation technique in which the mobile phase is a fluid above and relatively close to its critical temperature and pressure.
Techniques by separation mechanism
Ion exchange chromatography
Ion exchange chromatography (usually referred to as ion chromatography) uses an ion exchange mechanism to separate analytes based on their respective charges. It is usually performed in columns but can also be useful in planar mode. Ion exchange chromatography uses a charged stationary phase to separate charged compounds including anions, cations, amino acids, peptides, and proteins. In conventional methods the stationary phase is an ion exchange resin that carries charged functional groups that interact with oppositely charged groups of the compound to retain. Ion exchange chromatography is commonly used to purify proteins using FPLC.
Size-exclusion chromatography
Size-exclusion chromatography (SEC) is also known as gel permeation chromatography (GPC) or gel filtration chromatography and separates molecules according to their size (or more accurately according to their hydrodynamic diameter or hydrodynamic volume). Smaller molecules are able to enter the pores of the media and, therefore, molecules are trapped and removed from the flow of the mobile phase. The average residence time in the pores depends upon the effective size of the analyte molecules. However, molecules that are larger than the average pore size of the packing are excluded and thus suffer essentially no retention; such species are the first to be eluted. It is generally a low-resolution chromatography technique and thus it is often reserved for the final, "polishing" step of a purification. It is also useful for determining the tertiary structure and quaternary structure of purified proteins, especially since it can be carried out under native solution conditions.
Expanded Bed Adsorption (EBA) Chromatographic Separation
Expanded Bed Adsorption (EBA) Chromatographic Separation captures a target protein from a crude feed stream when it passes through a chromatography column system containing adsorbent beads. With this technique the crude feedstock can be treated directly in the chromatographic column, avoiding the traditional clarification and pre-treatment steps. EBA Chromatographic Separation is highly scalable, from laboratory-based 1 cm diameter columns to large production columns up to 2 meter in diameter. These columns can typically handle feed stock throughput of more than 1,000,000 liter per day with a production capacity of 1000 MT protein per year.
Special techniques
Reversed-phase chromatography
Reversed-phase chromatography (RPC) is any liquid chromatography procedure in which the mobile phase is significantly more polar than the stationary phase. It is so named because in normal-phase liquid chromatography, the mobile phase is significantly less polar than the stationary phase. Hydrophobic molecules in the mobile phase tend to adsorb to the relatively hydrophobic stationary phase. Hydrophilic molecules in the mobile phase will tend to elute first.
Two-dimensional chromatography
In some cases, the chemistry within a given column can be insufficient to separate some analytes. It is possible to direct a series of unresolved peaks onto a second column with different physico-chemical (Chemical classification) properties. Since the mechanism of retention on this new solid support is different from the first dimensional separation, it can be possible to separate compounds that are indistinguishable by one-dimensional chromatography. The sample is spotted at one corner of a square plate,developed, air-dried, then rotated by 90° and usually redeveloped in a second solvent system.
Simulated moving-bed chromatography
Pyrolysis gas chromatography
Pyrolysis gas chromatography mass spectrometry is a method of chemical analysis in which the sample is heated to decomposition to produce smaller molecules that are separated by gas chromatography and detected using mass spectrometry.
Pyrolysis is the thermal decomposition of materials in an inert atmosphere or a vacuum. The sample is put into direct contact with a platinum wire, or placed in a quartz sample tube, and rapidly heated to 600–1000 °C. Depending on the application even higher temperatures are used. Three different heating techniques are used in actual pyrolyzers: Isothermal furnace, inductive heating (Curie Point filament), and resistive heating using platinum filaments. Large molecules cleave at their weakest points and produce smaller, more volatile fragments. These fragments can be separated by gas chromatography. Pyrolysis GC chromatograms are typically complex because a wide range of different decomposition products is formed. The data can either be used as fingerprint to prove material identity or the GC/MS data is used to identify individual fragments to obtain structural information. To increase the volatility of polar fragments, various methylating reagents can be added to a sample before pyrolysis.
Besides the usage of dedicated pyrolyzers, pyrolysis GC of solid and liquid samples can be performed directly inside Programmable Temperature Vaporizer (PTV) injectors that provide quick heating (up to 30 °C/s) and high maximum temperatures of 600–650 °C. This is sufficient for some pyrolysis applications. The main advantage is that no dedicated instrument has to be purchased and pyrolysis can be performed as part of routine GC analysis. In this case quartz GC inlet liners have to be used. Quantitative data can be acquired, and good results of derivatization inside the PTV injector are published as well.
Fast protein liquid chromatography
Fast protein liquid chromatography (FPLC) is a term applied to several chromatography techniques which are used to purify proteins. Many of these techniques are identical to those carried out under high performance liquid chromatography, however use of FPLC techniques are typically for preparing large scale batches of a purified product.
Countercurrent chromatography
Countercurrent chromatography (CCC) is a type of liquid-liquid chromatography, where both the stationary and mobile phases are liquids. The operating principle of CCC equipment requires a column consisting of an open tube coiled around a bobbin. The bobbin is rotated in a double-axis gyratory motion (a cardioid), which causes a variable gravity (G) field to act on the column during each rotation. This motion causes the column to see one partitioning step per revolution and components of the sample separate in the column due to their partitioning coefficient between the two immiscible liquid phases used. There are many types of CCC available today. These include HSCCC (High Speed CCC) and HPCCC (High Performance CCC). HPCCC is the latest and best performing version of the instrumentation available currently.
Chiral chromatography
Chiral chromatography involves the separation of stereoisomers. In the case of enantiomers, these have no chemical or physical differences apart from being three-dimensional mirror images. Conventional chromatography or other separation processes are incapable of separating them. To enable chiral separations to take place, either the mobile phase or the stationary phase must themselves be made chiral, giving differing affinities between the analytes. Chiral chromatography HPLC columns (with a chiral stationary phase) in both normal and reversed phase are commercially available.
See also
- IUPAC Nomenclature for Chromatography IUPAC Recommendations 1993, Pure & Appl. Chem., Vol. 65, No. 4, pp.819–872, 1993.
- Still, W. C.; Kahn, M.; Mitra, A. J. Org. Chem. 1978, 43(14), 2923–2925. doi:10.1021/jo00408a041
- Laurence M. Harwood, Christopher J. Moody (13 June 1989). Experimental organic chemistry: Principles and Practice (Illustrated ed.). WileyBlackwell. pp. 180–185. ISBN 978-0-632-02017-1 [Amazon-US | Amazon-UK].
- Christian B. Anfinsen, John Tileston Edsall, Frederic Middlebrook Richards Advances in Protein Chemistry. Science 1976, 6-7.
- Displacement Chromatography 101. Sachem, Inc. Austin, TX 78737
- Pascal Bailon, George K. Ehrlich, Wen-Jian Fung and Wolfgang Berthold, An Overview of Affinity Chromatography, Humana Press, 2000. ISBN 978-0-89603-694-9 [Amazon-US | Amazon-UK], ISBN 978-1-60327-261-2 [Amazon-US | Amazon-UK].
- IUPAC Nomenclature for Chromatography
- Chromedia On line database and community for chromatography practitioners (paid subscription required)
- Library 4 Science: Chrom-Ed Series
- Overlapping Peaks Program – Learning by Simulations
- Chromatography Videos – MIT OCW – Digital Lab Techniques Manual
- Chromatography Equations Calculators – MicroSolv Technology Corporation
|
BINGE EATING DISORDER
"Signs and Symptoms"
To date, there has been some degree of confusion as to what exactly the term "binge eating" really means. Although the professional community still has yet to define [or quantify] what constitutes a binge-eating episode, it's reasonable to assume the signs and symptoms listed below are a good barometer of what is characteristic binge eating. In many respects, Binge Eating Disorder [BED] is similar to Bulimia without the compensatory behaviors. In addition, the term compulsive overeating may be "interchangeable" with BED - although some compulsive overeaters have a pattern of eating constantly ["grazing"] rather than experiencing episodes of binge eating per se.
Signs and symptoms Binge Eating / Compulsive Overeating [COE]
- Preoccupation with food.
- Rapid consumption of food in significant excess of nutritional need
- Sneaking or hoarding food - even immediately after meals.
- Feeling ashamed or fearful when confronted about the problem.
- Excessive concern about weight and body shape.
- Sense of "losing control" during binge episode.
- Feeling lonely, depressed, worried, self preoccupied
- Spending a great deal of time alone / social isolation
- Alternating between binge eating and "dieting"
Treating BED at Milestones
As with many other eating disorders, the characteristics of a binge eating disorder appear to mimic [inherent among] other dependencies or addictions - whether to a substance or set of behaviors. In fact, the most recent committee of the American Psychiatric Association "officially" included BED as a bona fide disorder [disease]. The link below lists the criteria for "dependency" and requires only three of the several criteria "fit" for a diagnosis of dependency [aka addiction] to be considered.
The program offered at Milestones is comprised of two primary components, making the treatment experience unique in comparison to other programs.
The first is the setting - utilizing apartment-style residences affording residential participants an opportunity to experience treatment in a "real world" environment. Participants grocery shop with our dietitian within the community, learn to prepare their own meals per the prescribed [meal] food / meal plan they have formulated with the dietitian, attend a full schedule of groups and individual therapies at our clinical campus [near the residential complex], attend local community support groups in the evenings, and visit with our physicians and clinical staff regularly throughout their stay. In effect, the experience is one of providing a supportive and structured setting without the restrictive elements of a "hospital" or institutional facility. A key element in providing the support necessary to begin recovery is remaining in the company of other participants during the initial phase of the treatment. This provides both a form of supervision and a deterrent from the behavior often associated with binge eating: namely eating in isolation or alone.
Secondly, Milestones approaches treatment from a more "holistic" perspective. Doing so is best described by the acronym "SERF" - Spirituality, Exercise, Rest, and Food Plan.
Spirituality need not equate with any religious or spiritual beliefs imposed on or by anyone. In fact, Spirituality at Milestones simply is left up to the individual to cultivate with his or her own working definition. For most, it is a belief in a "higher power" and still for others it may be a return to some of their original religious beliefs. For everyone, it is an individual journey.
Exercise is individualized and represents collaboration between the resident and clinical team. It is meant to be in the service of restoring and maintaining a healthy body rather than an "intensive" means of controlling body weight.
Rest is simply about finding the correct balance in recovery between work and play and narrowing the gap between an "all or none", "feast or famine" approach to daily living.
The food plan suggested by Milestones is a blend of structured eating and a combination of healthy, whole foods that are bought and prepared by PARTICIPANTS with the guidance and supervision of our dietitian and ancillary staff. In brief participants select their own preferences within the guidelines of their individual food plans. The guidelines require participants to abstain from "junk foods" and eliminate most highly processed [sugar and flour laden] food products as well as weigh and measure portions per their food plan while in residence.
It is important to mention most participants who seek treatment for most eating disorders may have a tendency to focus on "trading in the binging and/or "purging" to become better at restricting or "losing weight" and as such, it is important to understand the predisposition to replace one form of an eating disorder for another. Acknowledging this is helpful to maintaining the prescribed treatment plan both during and after the residential treatment experience. Body mass and subsequent weight loss will likely change as a result of abstaining from overeating and move in the direction [towards] of a healthy "set point" as an outcome of the recovery process.
Each participant is assigned an individual therapist whom they meet with on a regular basis during their stay as well as attend groups and experiential therapies per the schedule In sum, the physical and emotional aspects of their eating disorder are addressed within these formats.
|
Tuesday, March 03, 2015
Bibi at the Barricade
Cal Thomas | Mar 03, 2015
Israeli Prime Minister Benjamin Netanyahu seen at the Western Wall on January 22, 2013. ( Marc Israel Sellem/POOL/FLASH90)
The White House opposes Israeli Prime Minister Benjamin Netanyahu speaking to Congress, but not because the speech has political implications, coming as it does just two weeks before Israel's March 17election. If the administration truly had political concerns it would not have dispatched a team of Obama loyalists to Israel to help defeat Netanyahu.
No, many believe the real reason the administration opposes Netanyahu's speech is because he will tell the truth about Iran's nuclear threat and the administration wants to cover up what could ultimately become a very bad deal. Iran wants nuclear weapons. And yet the U.S. is promoting the fiction that despite past behavior and the apocalyptic statements by its leaders, Iran will agree to stop its nuclear program. It will not.
"Six powers -- the United States, Russia, China, Britain, France and Germany -- are negotiating with Iran toward an agreement to restrain Tehran's nuclear program in exchange for easing economic sanctions," writes Reuters. "Netanyahu has spoken scathingly about a possible deal and says a nuclear-armed Iran would pose an existential threat to the Jewish state." Netanyahu is right.
Iran cannot be trusted to honor any agreement. Iran wants to become a global player. It wants Israel gone. No agreement meant to hamper either goal will have any lasting effect.
Netanyahu's defiance of American dictates has precedence. On June 7, 1981, Prime Minister Menachem Begin ordered the destruction of the Iraqi Osirak reactor just before it would become operational. The attack occurred three weeks before Israel's June 30
election. There were the predictable denunciations from all quarters about how the attack would hurt the "peace process," which has never existed, but privately Reagan administration officials were said to have cheered Israel's actions.
President Obama and the State Department are on the wrong side of history and public opinion when it comes to Iran and the threat it poses to global stability. BloombergView.com cites a Paragon Insights poll conducted for The Israel Project, a pro-Israel group, which found that 51 percent disapprove of Obama's foreign policy, 41 percent approve. A wider margin -- 43 percent to 25 percent -- approve of Netanyahu speaking to Congress and 47 percent oppose the way the president has handled the Netanyahu address, Just 32 percent are in favor.
Other polls, including one by CNN/ORC, which Israel supporters say is flawed, found that 63 percent of those Americans surveyed were opposed to the Netanyahu visit.
It isn't just American public opinion that mostly opposes the president on Netanyahu and Iran. Pro-U.S. regimes in much of the Arab world understand the existential threat they face against a nuclear Iran. These nations -- Saudi Arabia, Kuwait, Bahrain, Abu Dhabi, Dubai, Oman, Qatar, Jordan and Egypt -- are regarded as apostates by Iran's theocratic rulers who view them as targets, not fellow Muslim neighbors, possibly because Iran has become the world's number one exporter of terrorism, including to these countries.
These nations are not convinced by the president's laughable contention that "the world is less violent than it has ever been." Compared to what? There are none so blind as those who will not see. The Obama administration should open its eyes to a world that is aflame.
President Obama's defenders say he, not Congress, should shape foreign policy, but that's not what the Constitution says. The State Department acknowledges: "The United States Constitution divides foreign policy powers between the President and the Congress so that both share in the making of foreign policy. The executive and legislative branches each play important roles that are different but that often overlap. Both branches have continuing opportunities to initiate and change foreign policy, and the interaction between them continues indefinitely throughout the life of a policy."
Former ABC newsman Ted Koppel once said: "Our society finds truth too strong a medicine to digest undiluted. In its purest form, truth is not a polite tap on the shoulder. It is a howling reproach."
Israel's prime minister should offer such a howling reproach to America's disastrous policy with Iran and the administration's failure to tell the truth about the threat should Iran go nuclear.
No comments:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.