The New Survivalist
|
|
|
Chapter 8:
|
|
Energy is the Key to SurvivalIn physics class we learned that energy is the capacity to do work. We saw earlier that food is the stored energy which makes life possible. Every human activity requires energy. We need it to charge our phones and to heat our homes. From growing our food to cooking it, energy is the key to survival. In this chapter we will explore this important topic and look at sources of energy that we might draw upon during an emergency.Virtually all of the energy on Earth comes from the Sun. Plants absorb energy directly from sunlight and plant-eating animals get it by consuming plants. Then carnivores eat plant-eating animals and so goes the food chain right to the top where humans are found. The sun's energy stored in trees is released when we burn wood. The energy stored in plants and animals that died millions of years ago provides us today with the coal, oil and natural gas that we depend on to run our economies. Even the electricity we get from hydroelectric dams comes from the sun, which evaporated the waters which produced the rain and snow which fed the rivers and lakes. When humans discovered fire we were able to move from the warmer regions of the earth to the colder areas. The discovery of fossil fuelsfirst coal, and then oil and natural gasled to the industrial revolution. With inexpensive fertilizers produced from natural gas, and abundant cheap gasoline and diesel fuel to power farming equipment, we were able to produce food more efficiently and abundantly than ever before, and to transport it in refrigerated trucks over great distances. As a result of cheap energy, today we expect to find fresh fruits and vegetables in our grocery stores regardless of the season. We take this cornucopia of inexpensive food for granted, but global warming, obesity and overpopulation have now became concerns. But Nature is not without her own system of checks and balances. Geologists are warning us today about "Peak Oil," as fossil fuel production worldwide has begun to decline due to dwindling resources. Unfortunately they just aren't making dinosaurs anymore, and even if they were, we can't wait the millions of years that would be necessary to churn them into new fossil fuels. Many scientists are predicting that in the very near future our dwindling fossil fuel resources will become critical, leading first to extraordinarily high energy prices, and eventually maybe even to a tragic depopulation of the Earth. Some scientists say that we have already approached this critical point, and the higher fuel prices that we have witnessed over the past few years are just the beginnings of the birth pangs, as compared to what we will experience in the not-too-distant future. Throughout the past century, the abundance of cheap energy from fossil fuels has spoiled us, resulting in some unusual habits. We have become accustomed to wearing T-shirts and shorts in our homes during the coldest months of the year, and long sleeves and woolen suits in our air-conditioned offices during the hottest months. We have become so used to this unnatural state that we now even design many of our new office buildings with windows that can't even be opened! It is absurd that, even while our scientists are warning us about the dangers of greenhouse gases, we Americans continue to buy the largest gas-guzzling vehicles that we can get our hands on. The reprehensible SUV has replaced the more sensible economy cars that appeared on the scene after the energy crisis of the 1970's. But here is the bad news: Geologists tell us that there is a huge difference between the approaching energy crisis and the one of the 1970's. The energy crisis of the 1970's was not caused by an actual shortage of oil, but rather by a politically motivated embargo on the part of major oil producing nations. The energy crisis that we are facing today is due to the actual depletion of the world's easily-accessible (i.e., inexpensive) fossil fuel reserves. Make no mistake about it, this situation is not going to improve. It will only get worse. To the survivalist this is just one more reason why preparedness is more important today than ever before! |
|||
| "If kindness and comfort are, as I suspect, the results of an energy surplus, then, as the supply contracts, we could be expected to start fighting once again like cats in a sack." George Monbiot | |||
PreparednessWhether the next emergency comes from a hurricane, earthquake, terrorist attack, or peak oil crisis, we will want to consider alternative ways for heating our homes during the cold winter months when there is an interruption to our electric, natural gas, and heating oil supplies. We will also need to consider alternative methods for cooking food, and for the numerous other energy-consuming activities of daily life from washing our dishes to powering our portable radios. |
|||
GeneratorsA generator can provide essential electric power during a short-term emergency. There are two basic types: portable generators and standby generators. A portable generator usually runs on gasoline. If nothing else
it may be able to provide enough power to keep your refrigerator and freezer
operating long enough for you to consume your cold food before it spoils.
The major disadvantage of a portable generator is that it operates on
gasoline, which does not store well. Gasoline should not be stored for
longer than a year because it deteriorates quickly leading to clogged
fuel lines or other mechanical problems. Gasoline is also highly volatile
and very dangerous to store. If you can afford the higher cost, a standby generator that will
run on either natural gas or propane can provide plenty of emergency power
for short-term emergencies. A standby generator can be hooked directly
into your home's existing natural gas line and will automatically provide
electricity during an electrical power outage. The system constantly monitors
utility power 24 hours a day. When power from the utility line fails an
automatic transfer switch safely disconnects the utility feed wires and
connects the generator feed. This eliminates the harmful back-feeding
of electricity from the houses generator power to the utility lines.
A signal is sent starting the generator and powering up your home. Automatic
generators continue to monitor utility power and reverse the switch when
the power outage ends, returning to standby mode. A propane dealer can
provide you with an underground propane tank that is protected from the
elements so that a constant source of fuel is available. According to
propane dealers, on average a 250 gallon propane tank fueling a seven
kilowatt standby generator will provide enough electricity to power a
home for five days. A 500 gallon underground tank will provide power on
average for 11 days. Of course, if you can conserve electricity by operating
only essential appliances when they are really needed (an air conditioner
is not an essential appliance) then your propane supply will last much
longer. Even if you have a natural gas line to your home, I recommend
that you go to the extra expense of having a propane tank installed, allowing
you to switch your generator from natural gas to propane if the natural
gas supply is interrupted. If you do not have a propane tank professionally
installed you should at least be quipped to switch your generator over
to a portable propane tank if the need should arise. Many of us will not be able to afford a costly standby generator. And even those who are fortunate enough to have one will perhaps want to make plans for when their fuel runs out. What will we do then when the lights go out and the gas ceases to flow? First consider what essential services these utilities provide:
I will discuss communication and transportation in later chapters of this web site. In the remainder of this chapter we will consider lighting, cooking and heating. I purposefully left air-conditioning off this list because I do not consider it essential. There are some who will disagree. My argument is that air conditioning only became widely available a mere 50 or so years ago. Humans have survived just fine for thousands if not millions of years without it. Many people survive today in very hot climates without air-conditioning. If you are in a building in which you don't believe you will survive without air-conditioning, then I suggest you consider another location. When the electricity goes out for a prolonged period of time, there will simply be no air-conditioning, and there are few alternatives other than just sweating it out the best way you can. |
|||
LightingOne solution to the problem of lighting is to make the most of natural light or sunlight. This means getting up and going to bed with the sun. (As you can see, a large part of survival is simply common sense.) But what about those times when you really need to see in the dark, particularly during the months of the year in which the daylight period is shortened? |
|||
|
A solar charger can be used to recharge your rechargeable batteries during a prolonged power outage. The solar charger pictured above folds to the size of a pocket calculator and can charge three AA batteries at a time in the included battery pack. The detachable battery pack with multi-plug can also be used as a power supply for small devices like radios. |
|||
ElectricityA short-term solution for some of our lighting needs will be battery-operated lights. Certainly a good flashlight with fresh batteries is an essential emergency item for any home. You should also keep one in your car. You might also consider buying rechargeable batteries, and perhaps even a solar charger. I suggest that you keep a supply of both regular batteries and rechargeable batteries in your survival stash. The newer nickel-metal hydride (NiMH) rechargeable batteries are much better than the older nickel-cadmium (NiCd) type. Rotate your regular batteries to keep them fresh and ready for an emergency. You can store batteries in your refrigerator or freezer to prolong their shelf-life. (I will further discuss batteries toward |
|||
|
LED flashlights are the most efficient type providing the most light for the amount of energy used. The LED lights use very little electricity so their batteries will last much longer. The wind-up type of LED flashlight never needs batteries or a new bulb. It has a crank on the side that you turn for about 60 seconds to charge up the permanent internal rechargeable battery. This flashlight provides a low intensity light that lasts a surprisingly long amount of time on each windup. Wind-up electrical devices like the LED flashlight pictured above come in very handy during power outages. Wind-up portable radios are also available. Turning the crank for a couple of minutes recharges the internal battery. The crank folds conveniently away when not in use. Some wind-up devices are multifunctional, providing a radio and light in one unit for example, and some can even be used to charge the batteries in your cell phone. These wind-up devices are available at Amazon.com. |
|||
CandlesCandles also provide inexpensive emergency lighting and every survival stash should include a nice supply. Lit candles should be watched carefully, especially when used around pets or children. Many houses have burned down as a result of fires started by carelessly placed or unattended candles. Don't forget to store plenty of matches as well! I frequently pick up candles at estate sales whenever I find them for 5 to 10 cents a piece. I have a huge box filled with candles in my survival supplies which I purchased for pennies on the dollar. If I have more than I can use during an emergency I can always use them for barter, since candles will be a highly sought after commodity during any prolonged emergency and few people store them these days. |
|||
|
KeroseneKerosene lanterns are also a good option for providing light during a power outage. These too are abundant at estate sales where they can be picked up very economically. In addition to kerosene they will also burn lantern oil, which comes in plastic bottles. Lantern oil is more refined and burns cleaner but is much more expensive and some complain that it does not wick as well as kerosene. I never buy lantern oil new but I have picked up many bottles at estate sales for practically nothing and as a result I have quite a stash. If you plan on using kerosene lanterns you will also want to store a supply of kerosene, extra mantles or wicks, and extra globes in case yours breaks. Kerosene will keep longer than gasoline, but I still recommend that you try to rotate it out every few years or so. If you also have a kerosene heater you can burn your kerosene during the cold months each year so you can replace your supply with fresh stock. |
|||
GasolineGasoline doesn't store as long as kerosene and for that reason I do not recommend gasoline lanterns or stoves. If you want you can keep one on hand so you will have the option of using gasoline, if you can get your hands on it during a prolonged emergency, but be sure that you do not store gasoline in your stove or lantern. It goes bad rather quickly and will gum up the worksthe last thing you want when you pull the appliance out of storage to use during an emergency. |
|||
|
PropaneIf you are well equipped for camping, you will also be well equipped for any emergency. Hopefully you will have a good propane lantern as part of your camping equipment. I consider propane lanterns to be a very good choice. Propane is safe to store and it will keep for a very long time, making it one of the best choices for stockpiling energy. Be sure to store plenty of extra mantles for your propane lantern. |
|||
Cooking
PropaneI also consider propane to be a good choice for your emergency cooking needs. But, as always, it is a good idea to have more than one alternative to fall back on during an emergency. Alcohol stoves, including the ones that run on canned fuel or "Sterno" are nice alternatives, especially if you live in a small apartment and don't have a lot of room to store propane tanks. Outdoor barbecue grills can be use for cooking during emergencies, but they are terribly inefficient when compared to camping stoves. Since you will want to conserve your propane to make it last as long as possible, I recommend that you avoid using a large outdoor grill, preferring a smaller camping stove instead. (Warning: Never use a barbecue grill or hibachi to burn charcoal inside your home. They produce dangerous carbon monoxide gas and are therefore for outdoor use only. People have died during power outages as a result of carbon monoxide poisoning from indoor charcoal fires!) A double burner propane stove and two single burner propane stoves are pictured above. Propane is clean, safe and it stores very well making it the ideal fuel for emergencies. |
|||
|
Alcohol or Canned FuelAlcohol or Sterno is an alternative cooking fuel that may be suitable for those who live in small apartments. The two stoves on the right in the photograph above fold flat for storage and are designed for canned cooking fuel while the two stoves on the left are designed for bottled fondue fuel or alcohol. Canned fuel keeps very well and can be stored for an indefinite amount of time. |
|||
WoodWood burning stoves are also a good option if you have a class A chimney flue in your home. They can be used for both heating and cooking, and you can often find fire wood for free. I will have more to say about using wood as a fuel source in the next section of this chapter when we discuss alternative ways for heating your home during an emergency. |
|||
|
SolarSolar ovens are another excellent alternative for cooking your food. Solar energy is free, and simple solar stoves are surprisingly easy and inexpensive to make. Below are a few simple designs. There are excellent online sources where you can get plans for building a solar oven, including http://solarcooking.org/. Perhaps the simplest and easiest design for a solar oven is the box type pictured above. This homemade solar oven consists of a wooden box with a double paned sliding glass top. The outside of the box is painted black with nontoxic paint for maximum heat absorption. There are two different opinions as to whether the inside should be painted black as well or coated with a reflective material such as aluminum foil. Even though the oven in the picture above has been painted black on the inside, I believe that it is usually better for the inside to be reflective material. If the box is black then the box will certainly heat up, but the idea is to heat up the cooking container inside the box, and my experience has been that a reflective material inside the box does a better job of that. |
|||
|
Regardless of the design, most solar ovens require a reflector, such as the one pictured above, to concentrate the light and heat from the sun. The reflector above was made by simply covering a piece of cardboard with aluminum foil. The aluminum foil is stuck to the cardboard using a spray on adhesive. You can also use ordinary multipurpose glue, thinned slightly with water so that it will spread on easily with a paint brush. |
|||
|
These two 100% whole wheat French baguettes were cooked to perfection in a baguette bread pan inside this simple solar oven in about three hours. A more efficient solar oven will do the job in less than half the time. The efficiency of a solar oven can be improved by insulating the box or improving the reflector. |
|||
|
Another creative design for a solar oven is the inner tube oven pictured above. It consists of a large black inner tube sandwiched between two panes of glass. The pan inside the oven should be black to maximize heat absorption. The oven pictured above is sitting on a smooth blacktop surface so the bottom pane of glass was omitted. It is important that the glass fit smoothly against the inner tube all the way around to seal the inside from heat loss. Even though this photograph does not show a reflector, this type of oven will also require a reflector like the one pictured with the box oven above. |
|||
|
The third type of solar oven that I will mention here is the parabolic type. At the end of this chapter I have provided step by step instructions on how I made the parabolic solar cooker pictured above from an old satellite dish. For more creative and innovative designs for all types of solar ovens visit http://solarcooking.org/. |
|||
|
Cooking in a Solar OvenSolar ovens generally do not get as hot as conventional ovens, so a longer cooking time will often be required. For example, when I make whole wheat bread in my kitchen oven I bake it for 30 minutes at 350o F (177o C.) Baking a similar loaf in a simple box-type solar oven can take up to three hours, depending on the efficiency of the solar oven and the amount of sun. I have successfully baked bread at temperatures as low as 155o to 175o F (68o to 80o C.)  If you cook meat in your solar oven I recommend that you use a meat thermometer. You may never get your meat to the temperature recommended for conventional cooking and so again a longer cooking time may be required. I recommend that you strive for an internal temperature of at least 165o F (74o C) as measured by a meat thermometer. |
|||
|
Food Safety When Solar CookingRegardless of the cooking method, the danger zone for cooked food is between 50o and 125o F (10o and 52o C.) It is recommended that cooked food be kept either above this zone or below it. When cooked food has been in the danger zone for three to four hours it should be discarded due to the possibility of food poisoning by botulism or salmonella. Spoiled foods may contain dangerous toxins without showing any noticeable signs of spoilage. Suspect foods should not even be tasted since even a small amount of toxin can be very dangerous. Reheating food that has been in the danger zone for too long will not destroy the toxins nor render the food safe. When using a solar oven the danger occurs when the food is partially cooked and then allowed to remain in the cooker too long after the oven temperature falls into the danger zone. This is not usually a problem because it is not difficult to keep the temperature above the danger zone. The problem could occur if food remains in the oven for hours at the end of the day or after the sun is obscured by clouds. If the food in your solar oven is not done due to one of these conditions then another method of cooking should be used to finish the job. For additional information on solar cooking safety see http://solarcooking.org/foodsafety.htm. As long as the above precautions are kept in mind, solar cooking lends itself very well to absentee cooking. Raw, refrigerated or frozen foods, even meat or chicken, may be placed in a solar oven while it is still dark outsideseveral hours before the sun begins the cooking process. The food will remain cold enough to prevent spoilage and when the sun rises the cooker will reach a safe level of heat quickly enough to prevent it from being in the danger zone too long. Since it is difficult to overcook or burn food in a solar oven, when the food is done it will simply stay hot and above the danger zone until your return. |
|||
Heating your Home During an EmergencyIf you are already relying on stockpiled heating oil or propane for your heating needs then you may already have a nice supply of stored energy for an emergency. But your thermostat and furnace will not work when the electricity is off. You could also experience this problem if you heat your home using natural gas. You can look into ways of providing electricity to your furnace when the power is off, but it would be even better to install a natural gas space heater or a small furnace that does not require electricity, for a backup during those times in which you lose electrical power but still have gas or oil. If your oven uses natural gas you will have to light it with a match since the electronic lighters will not work when the electricity is off. Some people try to heat their homes when the electricity is off by operating their natural gas ovens with the door open, but the gas company does not recommend this procedure because it can be dangerous. Install a natural gas space heater instead. However, when the electricity is off during cold weather, that would be a good time to catch up on your baking if you have natural gas, since a hot stove will provide supplemental heat for your home. After your baking is done and the oven is turned off, leave the oven door open for a while to let the escaping heat help keep you warm. During an emergency your natural gas service could also become interrupted. Alternative methods for heating your home include a kerosene heater, a portable propane heater (like those used when camping in cold weather) and a wood burning stove or fireplace. You will need to stockpile your emergency energy source and conserve it so that it will last as long as possible. You can save energy during an emergency by heating only a portion of your home, closing off the rooms that are not needed. You can also save a considerable amount of energy by not trying to keep your house as warm as you have grown accustomed to during times of plentiful energy. Wear plenty of warm clothing in your house, including a wool cap or similar headgear, and you can be comfortable with inside temperatures as low as 60o F (16o C.) Remember that most heat loss from the human body occurs from the head, so don't neglect the warm headgear! |
|||
|
|||
|
A heat reclaimer like the one pictured above greatly improves the efficiency of a wood burning stove by capturing some of the heat that would otherwise escape up the chimney or flue and redistributing it into the room. |
|||
|
After every wind storm I pick up loads of free firewood from downed trees. People often leave wood by the curbside for the city to dispose of. Sometimes it is already cut into nice-sized logs that will fit right into my wood-burning stove, but usually I have to do some additional cutting so I take my chain saw, another good survival item, with me when I am looking for free firewood. |
|||
|
If you plan on using wood as an alternative heating and cooking fuel there are additional tools that you will need, including a wood splitting maul and wedges. |
|||
KeroseneMany people choose a kerosene heater for their emergency heating needs. Kerosene is certainly an option but it presents some disadvantages. Although kerosene has a longer storage life than gasoline, like gasoline it will deteriorate in time. One source that I checked recommended a one-year shelf-life for kerosene. Another said that kerosene could be kept indefinitely if stored in a tightly-closed container. I suspect that the truth lies somewhere between these two extremes. I have stored kerosene for many years without any problems. One thing is for sure and that is kerosene should not be stored in your kerosene heater nor in your oil lamps. These are not airtight and the kerosene will deteriorate and gum up the wick. Manufacturers of kerosene heaters usually recommend that the wick be replaced each year, and that is one reason why I do not like kerosene heaters. (The wick will actually last for years, but it will work less efficiently as carbon deposits build up on the burning end.) A kerosene additive is available at most hardware stores that is purported to extend the storage life of kerosene and make it burn cleaner. I recommend that you use this additive if you plan on storing kerosene for long periods of time. If you use kerosene as your alternative fuel be sure to rotate your fuel out of storage and replace your stock every few years. At the end of the cold season completely empty your kerosene heater before putting it away for summer storage. |
|||
GasolineGasoline burning heaters and stoves are available but I don't recommend them. Gasoline has a recommended storage life of only 6 months. Gasoline is also very volatile and dangerous to store in large quantities. When you use old gasoline there is a tendency for it to gum up the valves in your stove or heater. Never store a gasoline appliance with fuel in it or you will have problems for sure. Coleman makes a special fuel (shown on the left in the photograph above) for their stoves which is highly refined and less likely to cause problems. If you use a gasoline stove or heater you should use the recommended fuel. But this fuel is expensive and it still has a relatively short shelf-life when compared to other energy sources and I do not recommend it for long-term storage. This photograph also shows a catalytic heater (right back) designed to burn the same type of fuel and a two-burner stove (in the middle.) In the foreground on the right is a black heat drum designed to convert the one-burner stove (left foreground) into a heater. |
|||
|
PropanePropane burns cleaner than gasoline or kerosene and has a much longer storage life. Propane heaters and stoves are very reliable, requiring almost no maintenance. Propane is my preferred source of emergency fuel for both heating and cooking. Two types of propane heaters are shown above. Portable propane camping equipment, including heaters, lanterns and stoves, are excellent for emergencies. |
|||
|
The handy adapter shown above allows you to refill your small propane bottles from your 20 lb propane tank. (Propane is far cheaper to buy in refillable 20 lb tanks.) |
|||
|
The photograph above shows the corner of my unattached garage where I keep my emergency propane stash. I pick up used 20 lb propane tanks for about $5 each at estate sales (sometimes they even come with propane) and get them refilled at my local hardware store, where the propane is much cheaper than swap-out places like grocery stores. |
|||
|
Caution:
The combustion of most materials, including wood, camping fuel,
gasoline, propane and natural gas, releases varying amounts of potentially
dangerous carbon monoxide gas, so adequate ventilation is recommended,
especially when operating any camping equipment indoors. Carbon monoxide
is an odorless, invisible and lethal gas that you will not be aware of
until it is too late. That is why I strongly recommend the use of a battery-operated
carbon monoxide detector in your home. And never burn charcoal indoors!
|
|||
DC PowerThe electricity that comes into our homes from the electric company is Alternating Current (AC.) AC has the advantage of being transferred with low resistance over large distances through electrical wires or power lines. Most of the appliances in our homes are designed to operate on AC. The ones that don't either run on batteries or have a transformer that converts AC into DC (Direct Current.) All batteries, like the ones in your flashlight, cell phone and automobile, provide DC power. Solar panels also produce DC power. In my video on Ham radios which appears in Chapter 11, I describe a simple inexpensive 12-volt solar powered system that I use. Use this link to watch that video starting at the point where I begin discussing my 12-volt system, pictured below: Click here to watch the video describing this inexpensive system. |
|||
|
An Inverter is an electrical device that converts DC power to AC. You can purchase small, portable inverters, like the one pictured above, to convert 12 Volt DC power, such as that from your automobile, into AC power that you can use to run AC appliances. The problem with inverters is that they are inefficient because some of the DC power is converted into heat rather than into AC power. They even contain an internal fan to help dissipate the heat to prevent overheating. This means that a lot of your DC power is wasted and as a result your battery will be drained quicker. For this reason, if you use DC power, it is far better to use it to run DC appliances rather than to convert it into AC power to run AC appliances. |
|||
|
Various types of rechargeable 12 Volt DC power supplies are available, such as the one pictured above. These are usually purchased for recharging dead automobile batteries, but they can also provide emergency power during an electrical outage. Ordinary automobile batteries are not suitable for this type of use because they are not designed for repeated deep discharges (discharges of more than 50%.) If you want a battery for an emergency power supply you will need to purchase a heavy duty deep cycle lead acid battery, which has thicker plates and lead-antimony support grids for years of over 50% deep cycle charges and discharges. |
|||
|
Twelve volt solar panels can be used to recharge your automobile battery or any other rechargeable 12 volt power supply. The larger panel shown in the photograph above provides up to 4.5 watts of power and is suitable for recharging any 12 volt battery, even one that has been completely discharged. The smaller unit in the foreground is a battery charge maintainer, or trickle charger, which will not recharge a dead battery but is designed rather to maintain a battery in an automobile that is parked for a period of time. The trickle charger is plugged into the cigarette lighter and placed on the dashboard where it will receive maximum exposure to the sun. |
|||
|
Various devices and appliances are available for 12 volt DC power supplies. These are popular with truckers and can be found in the stores located at truck stops. The 12 volt oven pictured above can be used to cook an entire meal. The 12 volt cooler pictured below can be used to keep food either cold or hot. |
|||
Renewable Energy (Photovoltaics, Wind Turbines,
Micro-Hydropower)
|
|||
|
Action Step 14: Energy Check ListsTurn to the page in your Action Planner where you have begun your "Get" and "Do" lists for energy and begin making your lists. The check List below will help you with your "Get" list. Energy Check List:
Lighting
|
|||
The simplest, easiest and most versatile type of solar cooker is probably the box type. But those inventive souls among us who like to tinker with new technologies might be interested in designing and building their own parabolic cookers. There are many ways to make a parabolic cooker. I have seen them made from umbrellas and even cardboard. Plans for various designs are available at http://solarcooking.org/. Here is how I made my parabolic solar cooker, using an old satellite dish: An old satellite dish has some nice advantages. It was designed to be adjustable, so it can be rotated and tilted to the most efficient position for capturing the sun's rays. The first step in making a parabolic cooker from a satellite dish is to mount the dish on a sturdy base that is heavy enough to resist toppling over in the wind. |
|||
|
After removing the LNB's from the LNB mount, I removed the dish from the supporting pole and reinstalled it on the pole upside down. Turning the dish upside down moved the LNB mount from the bottom to the top, where it can be used for hanging the cooking pot. |
|||
|
I found that a 1x2 inch board would fit perfectly into this type of LNB mount. I made the arm adjustable by drilling holes in the board about one inch apart, and using a nail to hold it at whatever position I desired. I also put a hook in the end of the board to hang the cooking pot on. |
|||
|
For the reflector I glued aluminum foil to the satellite dish. I used ordinary white multipurpose glue, thinning it with a little water so I could easily brush it on the dish. |
|||
|
The dish should be positioned at a 90o angle to the sun's rays. I replaced the angle adjustment nuts with wing nuts so they could be loosened and tightened by hand. The angle remains the same throughout the day. It changes only when the angle of the sun changes, according to the season of the year. However, when in use the dish must be rotated to follow the sun throughout the day, so I left the nuts which hold the dish on the post loose so the dish could be freely rotated. |
|||
|
For maximum absorption of heat and light, I painted the cooking pot solid black using high temperature paint (the kind you use to paint barbecue grills.) |
|||
|
I'm sure we have all, at one time or another, used a magnifying glass to focus the sun's rays to set a piece of paper on fire. A parabolic reflector works in a similar way, as demonstrated in the photograph above. A newspaper held at the focal point of this parabolic cooker took only 15 seconds to ignite into flames. This experiment was conducted in September at 8:30 AM with the sun still low in the sky and an ambient temperature of only 65o F (18.3o C.) |
|||
|
It is important to position the cooking pot at the precise focal point of the parabolic cooker. Throughout the cooking process, the cooker will need to be rotated slightly, about twice every hour, to follow the sun as it travels across the sky. For this reason, a parabolic cooker does not lend itself to absentee cooking as well as a box-type solar oven, which can be left in the same position all day. |
|||
|
A final and necessary step is to insulate the cooking pot to prevent heat loss to the surrounding air. This greatly improves the efficiency of the cooker and increases the temperature in the cooking pot. This can be accomplished by placing the black pot inside a clear Pyrex glass dish, or as illustrated above, by placing a clear plastic cooking bag around the pot (the same kind of clear cooking bag that you use in your oven.) |
|||
A Final Warning about Parabolic Cookers:A parabolic solar cooker produces an intense light and heat at its focal point that can be very dangerous. I have even heard of one man who inadvertently set his house on fire with a parabolic cooker that was not even in use. Always wear sunglasses when working with any solar cooker outdoors. Just as you would never look directly into the sun, be careful not to look directly into the focal point of your parabolic cooker, where the sun's rays are intensified many times. Never allow children to play with a solar cookerparticularly a parabolic solar cooker! |
|||
Recommended Reading: |
|||
Recommended Products: |
|||
|
Take
a stand against Socialized Medicine |


An awesome HTTP client! Search APIs. Star, save, fork, share, and create your own. Learn how the web works. Find APIs to power your next app!
When you opened this page the browser made a GET {{url}} HTTP/1.1
request to get the page from the server. Every time you go to a new page the browser makes a GET
request to load the page. GET
tells the browser to read data. You can also create POST
, update PUT
, and delete DELETE
data on the web.
 You can only GET
this type of data. Sites like Twitter, Facebook, and suri.io you send JSON to and from the server to update your status, change your profile, etc. Data is sent using JavaScript and is called an AJAX request or an XHR. When you create a new status you POST
data to the server. When you update your profile you PUT
your updated profile. Suri is designed to let you play with these APIs. You can see how the raw data is sent and received.
Signing into suri.io uses Google's OAuth2 and OpenID Connect. Using OAuth means suri never needs to know your username or password. When you authorize access with Google it will send an id_token
back to suri. Suri uses your ID to give you access to your private APIs and prevent other people from seeing them.
Non-CORS enabled APIs have to proxy through the suri.io server to avoid cross-site scripting. Browsers don't allow calling hosts other than the current host ({{hostname}}
) for security reasons. CORS enabled APIs will directly call their host from your browser. These APIs don't need to be proxied through suri.io. CORS is the prefered approach if the API supports it since there is no intermediate server.
Suri is a full stack JavaScript application built on some of the coolest new technology.
{{url}}
starts with HTTP? That means it got the web page using the HTTP protocol.{{hostname}}
for example).


Car2Car
Inbox
Bookings
Add Car
Logout
Login
Signup
Matching Cars
Rego
123-345
Make
Ford
Model
86
Year
2014
Suburb
Bondi
Transmission
Auto
Kms
10000-14999km
Available
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Weekends
Weekdays
Public Holidays


Creates Session EJB Facade based on Entity class. This template creates Session EJB for every Entity class with basic access methods.


graph4nlp.loss¶
Losses¶
-
class
graph4nlp.loss.
CoverageLoss
(cover_loss)¶ The loss function for coverage mechanism.
- Parameters
cover_loss (float) – The weight for coverage loss.
Methods
add_module
(name, module)Adds a child module to the current module.
apply
(fn)Applies
fn
recursively to every submodule (as returned by.children()
) as well as self.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Returns an iterator over module buffers.
children
()Returns an iterator over immediate children modules.
cpu
()Moves all model parameters and buffers to the CPU.
cuda
([device])Moves all model parameters and buffers to the GPU.
double
()Casts all floating point parameters and buffers to
double
datatype.eval
()Sets the module in evaluation mode.
extra_repr
()Set the extra representation of the module
float
()Casts all floating point parameters and buffers to
float
datatype.forward
(enc_attn_weights, coverage_vectors)The calculation function.
get_buffer
(target)Returns the buffer given by
target
if it exists, otherwise throws an error.get_parameter
(target)Returns the parameter given by
target
if it exists, otherwise throws an error.get_submodule
(target)Returns the submodule given by
target
if it exists, otherwise throws an error.half
()Casts all floating point parameters and buffers to
half
datatype.load_state_dict
(state_dict[, strict])Copies parameters and buffers from
state_dict
into this module and its descendants.modules
()Returns an iterator over all modules in the network.
named_buffers
([prefix, recurse])Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children
()Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse])Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
parameters
([recurse])Returns an iterator over module parameters.
register_backward_hook
(hook)Registers a backward hook on the module.
register_buffer
(name, tensor[, persistent])Adds a buffer to the module.
register_forward_hook
(hook)Registers a forward hook on the module.
register_forward_pre_hook
(hook)Registers a forward pre-hook on the module.
register_full_backward_hook
(hook)Registers a backward hook on the module.
register_parameter
(name, param)Adds a parameter to the module.
requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
share_memory
()See
torch.Tensor.share_memory_()
state_dict
([destination, prefix, keep_vars])Returns a dictionary containing a whole state of the module.
to
(*args, **kwargs)Moves and/or casts the parameters and buffers.
to_empty
(*, device)Moves the parameters and buffers to the specified device without copying storage.
train
([mode])Sets the module in training mode.
type
(dst_type)Casts all parameters and buffers to
dst_type
.xpu
([device])Moves all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Sets gradients of all model parameters to zero.
__call__
-
forward
(enc_attn_weights, coverage_vectors)¶ The calculation function.
- Parameters
enc_attn_weights (list[torch.Tensor]) – The list containing all decoding steps’ attention weights. The length should be the decoding step. Each element should be the tensor.
coverage_vectors (list[torch.Tensor]) – The list containing all coverage vectors in decoding module.
- Returns
coverage_loss – The loss.
- Return type
torch.Tensor
-
class
graph4nlp.loss.
SeqGenerationLoss
(ignore_index, use_coverage=False, coverage_weight=0.3)¶ The general loss for
Graph2Seq
model.- Parameters
ignore_index (ignore_index) – The token index which will be ignored during calculation. Usually it is the padding index.
use_coverage (bool, default=False) – Whether use coverage mechanism. If set
True
, the we will add the coverage loss.coverage_weight (float, default=0.3) – The weight of coverage loss.
Methods
add_module
(name, module)Adds a child module to the current module.
apply
(fn)Applies
fn
recursively to every submodule (as returned by.children()
) as well as self.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Returns an iterator over module buffers.
children
()Returns an iterator over immediate children modules.
cpu
()Moves all model parameters and buffers to the CPU.
cuda
([device])Moves all model parameters and buffers to the GPU.
double
()Casts all floating point parameters and buffers to
double
datatype.eval
()Sets the module in evaluation mode.
extra_repr
()Set the extra representation of the module
float
()Casts all floating point parameters and buffers to
float
datatype.forward
(logits, label[, enc_attn_weights, …])The calculation method.
get_buffer
(target)Returns the buffer given by
target
if it exists, otherwise throws an error.get_parameter
(target)Returns the parameter given by
target
if it exists, otherwise throws an error.get_submodule
(target)Returns the submodule given by
target
if it exists, otherwise throws an error.half
()Casts all floating point parameters and buffers to
half
datatype.load_state_dict
(state_dict[, strict])Copies parameters and buffers from
state_dict
into this module and its descendants.modules
()Returns an iterator over all modules in the network.
named_buffers
([prefix, recurse])Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children
()Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse])Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
parameters
([recurse])Returns an iterator over module parameters.
register_backward_hook
(hook)Registers a backward hook on the module.
register_buffer
(name, tensor[, persistent])Adds a buffer to the module.
register_forward_hook
(hook)Registers a forward hook on the module.
register_forward_pre_hook
(hook)Registers a forward pre-hook on the module.
register_full_backward_hook
(hook)Registers a backward hook on the module.
register_parameter
(name, param)Adds a parameter to the module.
requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
share_memory
()See
torch.Tensor.share_memory_()
state_dict
([destination, prefix, keep_vars])Returns a dictionary containing a whole state of the module.
to
(*args, **kwargs)Moves and/or casts the parameters and buffers.
to_empty
(*, device)Moves the parameters and buffers to the specified device without copying storage.
train
([mode])Sets the module in training mode.
type
(dst_type)Casts all parameters and buffers to
dst_type
.xpu
([device])Moves all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Sets gradients of all model parameters to zero.
__call__
-
forward
(logits, label, enc_attn_weights=None, coverage_vectors=None)¶ The calculation method.
- Parameters
logits (torch.Tensor) – The probability with the shape of
[batch_size, max_decoder_step, vocab_size]
. Note that it is calculated bysoftmax
.label (torch.Tensor) – The ground-truth with the shape of
[batch_size, max_decoder_step]
.enc_attn_weights (list[torch.Tensor], default=None) – The list containing all decoding steps’ attention weights. The length should be the decoding step. Each element should be the tensor.
coverage_vectors (list[torch.Tensor], default=None) – The list containing all coverage vectors in decoding module.
- Returns
- graph2seq_loss: torch.Tensor
-
class
graph4nlp.loss.
GeneralLoss
(loss_type, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean', pos_weight=None)¶ This general loss are backended on the pytorch loss function. The detailed decription for each loss function can be found at:
pytorch loss function <https://pytorch.org/docs/stable/nn.html#loss-functions>
- Parameters
- loss_type: str
the loss function to select (
NLL
,``BCEWithLogits``,MultiLabelMargin
,``SoftMargin`` ,``CrossEntropy`` )NLL loss<https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html#NLLLoss> measures the negative log likelihood loss. It is useful to train a classification problem with C classes.
BCEWithLogits loss <https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html#BCEWithLogitsLoss> combines a Sigmoid layer and the BCELoss in one single class. This version is more numerically stable than using a plain Sigmoid`followed by a `BCELoss as, by combining the operations into one layer, we take advantage of the log-sum-exp trick for numerical stability.
BCE Loss<https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html#BCELoss> creates a criterion that measures the Binary Cross Entropy between the target and the output.
MultiLabelMargin loss <https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html#MultiLabelMarginLoss> creates a criterion that optimizes a multi-class multi-classification hinge loss (margin-based loss) between input \(x\) (a 2D mini-batch Tensor) and output \(y\) (which is a 2D Tensor of target class indices).
SoftMargin loss <https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html#SoftMarginLoss> creates a criterion that optimizes a two-class classification logistic loss between input tensor \(x\) and target tensor \(y\) (containing 1 or -1).
CrossEntropy loss <https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html#CrossEntropyLoss> ` combines pytorch function `nn.LogSoftmax and nn.NLLLoss in one single class. It is useful when training a classification problem with C classes.
- weight: Tensor, optional
a manual rescaling weight given to the loss of each batch element. If given, has to be a Tensor of size nbatch. This parameter is not suitable for
SoftMargin
loss functions.- size_average: bool, optional
By default,the losses are averaged over each loss element in the batch. Note that for some losses, there are multiple elements per sample. If the field
size_average
is set toFalse
, the losses are instead summed for each minibatch. Ignored when reduce isFalse
. Default:True
.- reduce: bool, optional
By default, the losses are averaged or summed over observations for each minibatch depending on
size_average
. Whenreduce
isFalse
, returns a loss per batch element instead and ignoressize_average
. Default:True
- reduction: string, optional
Specifies the reduction to apply to the output:
'none'
|'mean'
|'sum'
.'none'
: no reduction will be applied,'mean'
: the sum of the output will be divided by the number of elements in the output,'sum'
: the output will be summed.Note:
size_average
andreduce
are in the process of being deprecated, and in the meantime, specifying either of those two args will overridereduction
. Default:'mean'
- pos_weight:Tensor, optional
A weight of positive examples. Must be a vector with length equal to the number of classes. This paramter is only suitable for
BCEWithLogits
loss function.- ignore_index: int, optional
Specifies a target value that is ignored and does not contribute to the input gradient. When
size_average
isTrue
, the loss is averaged over non-ignored targets. This paramter is only suitable forCrossEntropy
loss function.
Methods
add_module
(name, module)Adds a child module to the current module.
apply
(fn)Applies
fn
recursively to every submodule (as returned by.children()
) as well as self.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Returns an iterator over module buffers.
children
()Returns an iterator over immediate children modules.
cpu
()Moves all model parameters and buffers to the CPU.
cuda
([device])Moves all model parameters and buffers to the GPU.
double
()Casts all floating point parameters and buffers to
double
datatype.eval
()Sets the module in evaluation mode.
extra_repr
()Set the extra representation of the module
float
()Casts all floating point parameters and buffers to
float
datatype.forward
(input, target)Compute the loss.
get_buffer
(target)Returns the buffer given by
target
if it exists, otherwise throws an error.get_parameter
(target)Returns the parameter given by
target
if it exists, otherwise throws an error.get_submodule
(target)Returns the submodule given by
target
if it exists, otherwise throws an error.half
()Casts all floating point parameters and buffers to
half
datatype.load_state_dict
(state_dict[, strict])Copies parameters and buffers from
state_dict
into this module and its descendants.modules
()Returns an iterator over all modules in the network.
named_buffers
([prefix, recurse])Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children
()Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse])Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
parameters
([recurse])Returns an iterator over module parameters.
register_backward_hook
(hook)Registers a backward hook on the module.
register_buffer
(name, tensor[, persistent])Adds a buffer to the module.
register_forward_hook
(hook)Registers a forward hook on the module.
register_forward_pre_hook
(hook)Registers a forward pre-hook on the module.
register_full_backward_hook
(hook)Registers a backward hook on the module.
register_parameter
(name, param)Adds a parameter to the module.
requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
share_memory
()See
torch.Tensor.share_memory_()
state_dict
([destination, prefix, keep_vars])Returns a dictionary containing a whole state of the module.
to
(*args, **kwargs)Moves and/or casts the parameters and buffers.
to_empty
(*, device)Moves the parameters and buffers to the specified device without copying storage.
train
([mode])Sets the module in training mode.
type
(dst_type)Casts all parameters and buffers to
dst_type
.xpu
([device])Moves all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Sets gradients of all model parameters to zero.
__call__
-
forward
(input, target)¶ Compute the loss.
- Parameters
- NLL loss:
- Input: tensor.
\((N, C)\) where C = number of classes, or \((N, C, d_1, d_2, ..., d_K)\) with \(K \geq 1\) in the case of K-dimensional loss.
- Target: tensor.
\((N)\) where each value is \(0 \leq \text{targets}[i] \leq C-1\), or \((N, d_1, d_2, ..., d_K)\) with \(K \geq 1\) in the case of K-dimensional loss.
- Output: scalar.
If
reduction
is'none'
, then the same size as the target: \((N)\), or \((N, d_1, d_2, ..., d_K)\) with \(K \geq 1\) in the case of K-dimensional loss.
- BCE/BCEWithLogits loss:
- Input: Tensor.
\((N, *)\) where \(*\) means, any number of additional dimensions
- Target: Tensor.
\((N, *)\), same shape as the input
- Output: scalar.
If
reduction
is'none'
, then \((N, *)\), same shape as input.
- MultiLabelMargin loss:
- Input: Tensor.
\((C)\) or \((N, C)\) where N is the batch size and C is the number of classes.
- Target: Tensor.
\((C)\) or \((N, C)\), label targets padded by -1 ensuring same shape as the input.
- Output: Scalar.
If
reduction
is'none'
, then \((N)\).
- SoftMargin loss:
- Input: Tensor.
\((*)\) where \(*\) means, any number of additional dimensions
- Target: Tensor.
\((*)\), same shape as the input
- Output: scalar.
If
reduction
is'none'
, then same shape as the input
- CrossEntropy:
- Input: Tensor.
\((N, C)\) where C = number of classes, or \((N, C, d_1, d_2, ..., d_K)\) with \(K \geq 1\) in the case of K-dimensional loss.
- Target: Tensor.
\((N)\) where each value is \(0 \leq \text{targets}[i] \leq C-1\), or \((N, d_1, d_2, ..., d_K)\) with \(K \geq 1\) in the case of K-dimensional loss.
- Output: scalar.
If
reduction
is'none'
, then the same size as the target: \((N)\), or \((N, d_1, d_2, ..., d_K)\) with \(K \geq 1\) in the case of K-dimensional loss.
-
class
graph4nlp.loss.
KGLoss
(loss_type, size_average=None, reduce=None, reduction='mean', adv_temperature=None, weight=None)¶ In the state-of-the-art KGE models, loss functions were designed according to various pointwise, pairwise and multi-class approaches. Refers to Loss Functions in Knowledge Graph Embedding Models
Pointwise Loss Function
MSELoss Creates a criterion that measures the mean squared error (squared L2 norm) between each element in the input \(x\) and target \(y\).
SOFTMARGINLOSS Creates a criterion that optimizes a two-class classification logistic loss between input tensor \(x\) and target tensor \(y\) (containing 1 or -1). Tips: The number of positive and negative samples should be about the same,
otherwise it’s easy to overfit
\[\text{loss}(x, y) = \sum_i \frac{\log(1 + \exp(-y[i]*x[i]))}{\text{x.nelement}()}\]Pairwise Loss Function
SoftplusLoss refers to the paper OpenKE: An Open Toolkit for Knowledge Embedding
SigmoidLoss refers to the paper OpenKE: An Open Toolkit for Knowledge Embedding
Multi-Class Loss Function
Binary Cross Entropy Loss Creates a criterion that measures the Binary Cross Entropy between the target and the output. Note that the targets \(y\) should be numbers between 0 and 1.
Methods
add_module
(name, module)Adds a child module to the current module.
apply
(fn)Applies
fn
recursively to every submodule (as returned by.children()
) as well as self.bfloat16
()Casts all floating point parameters and buffers to
bfloat16
datatype.buffers
([recurse])Returns an iterator over module buffers.
children
()Returns an iterator over immediate children modules.
cpu
()Moves all model parameters and buffers to the CPU.
cuda
([device])Moves all model parameters and buffers to the GPU.
double
()Casts all floating point parameters and buffers to
double
datatype.eval
()Sets the module in evaluation mode.
extra_repr
()Set the extra representation of the module
float
()Casts all floating point parameters and buffers to
float
datatype.forward
([input, target, p_score, n_score])- Parameters
get_buffer
(target)Returns the buffer given by
target
if it exists, otherwise throws an error.get_parameter
(target)Returns the parameter given by
target
if it exists, otherwise throws an error.get_submodule
(target)Returns the submodule given by
target
if it exists, otherwise throws an error.half
()Casts all floating point parameters and buffers to
half
datatype.load_state_dict
(state_dict[, strict])Copies parameters and buffers from
state_dict
into this module and its descendants.modules
()Returns an iterator over all modules in the network.
named_buffers
([prefix, recurse])Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children
()Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules
([memo, prefix, remove_duplicate])Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters
([prefix, recurse])Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
parameters
([recurse])Returns an iterator over module parameters.
register_backward_hook
(hook)Registers a backward hook on the module.
register_buffer
(name, tensor[, persistent])Adds a buffer to the module.
register_forward_hook
(hook)Registers a forward hook on the module.
register_forward_pre_hook
(hook)Registers a forward pre-hook on the module.
register_full_backward_hook
(hook)Registers a backward hook on the module.
register_parameter
(name, param)Adds a parameter to the module.
requires_grad_
([requires_grad])Change if autograd should record operations on parameters in this module.
share_memory
()See
torch.Tensor.share_memory_()
state_dict
([destination, prefix, keep_vars])Returns a dictionary containing a whole state of the module.
to
(*args, **kwargs)Moves and/or casts the parameters and buffers.
to_empty
(*, device)Moves the parameters and buffers to the specified device without copying storage.
train
([mode])Sets the module in training mode.
type
(dst_type)Casts all parameters and buffers to
dst_type
.xpu
([device])Moves all model parameters and buffers to the XPU.
zero_grad
([set_to_none])Sets gradients of all model parameters to zero.
__call__
-
forward
(input=None, target=None, p_score=None, n_score=None)¶ - Parameters
- MSELoss
- input: Tensor.
\((N,*)\) where \(*\) means any number of additional dimensions
- target: Tensor.
\((N,*)\), same shape as the input
- output:
If reduction is ‘none’, then same shape as the input
- SoftMarginLoss
- input: Tensor.
\((*)\) where * means, any number of additional dimensions
- target: Tensor.
same shape as the input
- output: scalar.
If reduction is ‘none’, then same shape as the input
- SoftplusLoss
- p_score: Tensor.
\((*)\) where * means, any number of additional dimensions
- n_score: Tensor.
\((*)\) where * means, any number of additional dimensions. The dimension could be different from the p_score dimension.
output: scalar.
- SigmoidLoss
- p_score: Tensor.
\((*)\) where * means, any number of additional dimensions
- n_score: Tensor.
\((*)\) where * means, any number of additional dimensions. The dimension could be different from the p_score dimension.
output: scalar.
- BCELoss:
- Input: Tensor.
\((N, *)\) where \(*\) means, any number of additional dimensions
- Target: Tensor.
\((N, *)\), same shape as the input
- Output: scalar.
If
reduction
is'none'
, then \((N, *)\), same shape as input.


{% extends "base.html" %} {% load bulma_tags %} {% block content %} About {{ website_name }} Redirect Service {{ website_name }} uses the {{ site_name }} domain as part of a service to protect users from harmful activity, to provide value for the developer ecosystem, and as a quality signal for surfacing relevant, intresting user activity {% endblock content %}
{{ website_name }} uses the {{ site_name }} domain as part of a service to protect users from harmful activity, to provide value for the developer ecosystem, and as a quality signal for surfacing relevant, intresting user activity


TypeToSearch Demo
Start typing -- a search form will magically appear.
Press enter when you're done.
Search
Press Enter To Search
Close


What if we wanted to do the same set of steps multiple times? It would be very tiring to type out the same thing over and over again, and it would make our code very messy. Functions allow us to associate a command with an action.
We need the following to create a function:
When you call a function, the information you pass to the function (the part in parenthesis) is called an argument.
View syntax example
function sayHello(name) {
console.log("Hello " + name);
}
sayHello("Mark");


--- layout: page title: About header-img: "img/about-bg.png" ---
My name's Adam Priest. I live in Thomasville, GA. About 30 minutes from Tallahassee, Fl. I'm originally from Buffalo, NY. I've been programming on and off for about 4 years. My biggest strength right now is Python. Getting my JavaScript/Ruby skills up now.


SchemaSpy¶
Document your database simply and easily
Do you hate starting on a new project and having to try to figure out someone else’s idea of a database? Or are you in QA and the developers expect you to understand all the relationships in their schema? If so then this tool’s for you.
What is SchemaSpy ?¶
SchemaSpy is a Java-based tool (requires Java 8 or higher) that analyzes the metadata of a schema in a database and generates a visual representation of it in a browser-displayable format. It lets you click through the hierarchy of database tables via child and parent table relationships as represented by both HTML links and entity-relationship diagrams. It’s also designed to help resolve the obtuse errors that a database sometimes gives related to failures due to constraints. It is free software that is distributed under the terms of the MIT License.
If you like SchemaSpy then please give the start on Github project.
SchemaSpy uses the dot executable from Graphviz to generate graphical representations of the table/view relationships. This was initially added for people who see things visually. Now the graphical representation of relationships is a fundamental feature of the tool. Graphvis is not required to view the output generated by SchemaSpy, but the dot program should be in your PATH (not CLASSPATH) when running SchemaSpy or none of the entity relationship diagrams will be generated (or use the -gv option).
SchemaSpy uses JDBC’s database metadata extraction services to gather the majority of its information, but has to make vendor-specific SQL queries to gather some information such as the SQL associated with a view and the details of check constraints. The differences between vendors have been isolated to configuration files and are extremely limited. Almost all of the vendor-specific SQL is optional.
Smaple documentation¶
Browse some sample documentation generated by SchemaSpy. Note that this was run against an extremely limited schema so it doesn’t show the full power of the tool.
SchemaSpy GUI¶
SchemaSpy is a command line tool. If you’re more comfortable with the point-and-click approach then try out Joachim Uhl’s SchemaSpyGUI.
SchemaSpy was mentioned in one of th O’Reilly’s book Java Power Tools


screenshot-as-a-service
with or without the http:// prefix
in pixels
e.g. {"top":14,"left":3,"width":400,"height":300}
Enable JavaScript
Load Images
Enable Local To Remote Url Access
Submit


haskell-jp / english #1
Top
com01evi
2017-11-06 14:25:35 +0900
@com01evi has joined the channel
2017-11-09 17:44:12 +0900
@ has joined the channel
aiya000
2017-11-12 23:22:45 +0900
@aiya000 has joined the channel
aiya000
2017-11-12 23:22:51 +0900
hi
2017-11-14 17:34:29 +0900
@ has joined the channel
2017-11-30 08:58:58 +0900
@ has joined the channel
Hiroto
2017-12-15 16:43:10 +0900
@Hiroto has joined the channel
oganao
2017-12-23 16:55:42 +0900
@oganao has joined the channel
rnons
2017-12-25 16:57:56 +0900
@rnons has joined the channel
takisawa
2018-01-18 08:31:28 +0900
@takisawa has joined the channel
yokomotod
2018-01-25 19:49:12 +0900
@yokomotod has joined the channel
hsjoihs
2018-02-14 08:06:22 +0900
@hsjoihs has joined the channel
MIYATA Tadaaki
2018-03-30 17:18:59 +0900
@MIYATA Tadaaki has joined the channel
sgsh
2018-05-11 00:41:02 +0900
@sgsh has joined the channel
2018-07-20 00:05:12 +0900
@ has joined the channel
はなかず
2018-08-30 03:24:38 +0900
@はなかず has joined the channel
2018-09-22 00:03:37 +0900
@ has joined the channel
zeronone
2018-09-24 14:32:49 +0900
@zeronone has joined the channel
Yugo Osano
2018-10-07 14:47:19 +0900
@Yugo Osano has joined the channel
olafs
2018-11-08 20:31:06 +0900
@olafs has joined the channel
fumieval
2018-11-12 11:05:13 +0900
@fumieval archived the channel
Top


A pair of commuting bounded operators $(S,P)$ acting on a Hilbert space, is
called a $\Gamma$-contraction, if it has the symmetrised bidisc $$\Gamma=\{
(z_1+z_2,z_1z_2):|z_1| \leq 1,|z_2| \leq 1 \}\subseteq \mathbb{C}^2$$ as a spectral
set. For
every $\Gamma$-contraction $(S,P)$, the operator equation $$S-S^*P=D_PFD_P$$ has a
unique solution $F$ with numerical radius, $w(F)$ no greater than one, where $D_P$
is the
positive square root of $(I-P^*P)$. This unique operator is called the fundamental
operator of
$(S,P)$. This thesis constructs an explicit normal boundary dilation for a
$\Gamma$-contraction. A triple of commuting bounded operators $(A,B,P)$ acting on a
Hilbert space with the closure of the tetrablock $E=\{(a_{11},a_{22},\text{det}A):
A=\begin{pmatrix} a_{11} & a_{12} \\
a_{21} & a_{22} \end{pmatrix}\text{ with }\lVert A \rVert < 1\}\subseteq\mathbb{C}^3
$$ as a spectral set, is called a tetrablock contraction. Every tetrablock contraction
possesses two fundamental operators and these are the unique solutions of $$
A-B^*P=D_PF_1D_P, \text{ and } B-A^*P=D_PF_2D_P. $$ Moreover, $w(F_1)$ and
$w(F_2)$ are no greater than one. This thesisalso constructs an explicit normal
boundary
dilation for a tetrablock contraction. In these constructions, the fundamental
operators play a
pivotal role. Both the dilations in the symmetrized bidisc and in the tetrablock are
proved to
be minimal. But unlike the one variable case, uniqueness of minimal dilations
usually does
not hold good in several variables, e.g., Ando's dilation is not unique. However, we
show that
the dilations are unique under a certain natural condition. In view of the abundance of
operators and their complicated structure, a basic problem in operator theory is to
find nice
functional models and complete sets of unitary invariants. We develop a functional
model
theory for a special class of triples of commuting bounded operators associated with
the
tetrablock. We also find a set of complete sort of unitary invariants for this
special class.
Along the way, we find a Beurling-Lax-Halmos type of result for a triple of
multiplication
operators acting on vector-valuedHardy spaces. In both the model theory and unitary
invariance,fundamental operators play a fundamental role. This thesis answers the
question
when two operators $F$ and $G$ with $w(F)$ and $w(G)$ no greater than one, are
admissible as fundamental operators, in other words, when there exists a
$\Gamma$-contraction $(S,P)$ such that $F$ is the fundamental operator of $(S,P)$ and
$G$ is the fundamental operator of $(S^*,P^*)$. This thesis also answers a similar
question
in the tetrablock setting.


Java-like Object.equals() behavior in ABAP
Java’s equals() can be very useful: using it allows us to compare objects by their attributes. This is opposed to the traditional comparison with ‘==’ that compares whether two object references point to the same memory address.
For example, if we define a Car class with the attributes producer, model and year, and then we define two new objects of class Car – car1 and car2 – and we set each to be a Mercedes (producer) E400 (model) from 2016 (year), comparing them with ‘==’ would return false, while doing car1.equals(car2) would return true.
Today, I was wondering how we can achieve this in ABAP; unfortunately, it turns out, SAP does not provide a default way to do this. However, a coworker managed to find the if_xlf_comparable interface that requires you to implement an equals() method. While this specific interface is supposed to be used only with XLF-related objects, as evident by the name, its signature seemed general enough, so I used it as a basis, and for the actual implementation, I followed the Java way.
Defining a class to implement equals()
To continue with the example described above, I defined the Car class below, with its relevant attributes:
CLASS car DEFINITION.
PUBLIC SECTION.
METHODS:
constructor IMPORTING producer TYPE string
model TYPE string
year TYPE i.
PRIVATE SECTION.
DATA:
producer TYPE string,
model TYPE string,
year TYPE i.
ENDCLASS.
Then, in the public methods, I defined the equals method by copy-pasting the signature from the above-mentioned interface:
METHODS:
equals IMPORTING object TYPE REF TO object
RETURNING VALUE(is_equal) TYPE abap_bool.
Writing the equals() method
Then, obviously, the most important task remained: writing the equals() method. The traditional way to implement equals() in Java is as follows:
- Check if the other object reference is actually a reference to the same object; if so, return true
- Check if the other object reference is null; if so, return false
- Check if the other object’s class is the same as the caller object’s class; if not so, return false
- Downcast the other object to the relevant class and compare the relevant attributes; if all relevant attributes are equal, return true
An excellent example for this is Pricenton’s implementation in their class representing a point in a 2-dimensional space – Point2D (source):
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Point2D that = (Point2D) other;
return this.x == that.x && this.y == that.y;
}
Then, I implemented the code above in ABAP, with the obvious difference that instead of comparing a point’s x and y coordinate, I was to compare the producer, model, and year attributes in my Car class.
METHOD equals.
IF object EQ me.
is_equal = abap_true.
RETURN.
ENDIF.
IF object IS NOT BOUND.
is_equal = abap_false.
RETURN.
ENDIF.
TRY.
DATA(other) = CAST car( object ).
is_equal = xsdbool( me->producer EQ other->producer AND me->model EQ other->model AND me->year EQ other->year ).
CATCH cx_sy_move_cast_error.
is_equal = abap_false.
ENDTRY.
ENDMETHOD.
Simple demo
To test this, I created a few objects of the class, as well as one from a Truck class (refer to the full code at the end for its definition), and used the equals method in all possible cases:
DATA(car1) = NEW car( producer = 'Mercedes' model = 'E400' year = 2016 ).
DATA(car2) = NEW car( producer = 'BMW' model = 'X5' year = 2013 ).
DATA(car3) = NEW car( producer = 'Mercedes' model = 'E400' year = 2016 ).
DATA car4 TYPE REF TO car.
DATA(car5) = car1.
DATA(truck1) = NEW truck( producer = 'CAT' model = 'CT660' ).
" 2 different non-null Car objects with different attributes
cl_demo_output=>write( |Car 1 and Car 2 are the same: { car1->equals( car2 ) }| ).
" 2 different non-null Car objects with the same attributes
cl_demo_output=>write( |Car 1 and Car 3 are the same: { car1->equals( car3 ) }| ).
" 1 non-null Car object with 1 null Car object
cl_demo_output=>write( |Car 1 is the same as Car 4: { car1->equals( car4 ) }| ).
" 2 different references to the same Car object
cl_demo_output=>write( |Car 1 is the same as Car 5: { car1->equals( car5 ) }| ).
" Self as an argument
cl_demo_output=>write( |Car 1 is the same as itself: { car1->equals( car1 ) }| ).
" 1 Car object with 1 Truck object
cl_demo_output=>write( |Car 1 and Truck 1 are the same: { car1->equals( truck1 ) }| ).
cl_demo_output=>display( ).
After running this code, we have the following output:
Car 1 and Car 2 are the same:
Car 1 and Car 3 are the same: X
Car 1 is the same as Car 4:
Car 1 is the same as Car 5: X
Car 1 is the same as itself: X
Car 1 and Truck 1 are the same:
Closing notes
To conclude, this article demonstrates how to implement an equals() method in ABAP the same way that you would do it in Java. To stick with something SAP-provided, I used the signature of the equals() method in the if_xlf_comparable interface. The equals() method described here is not related to this specific interface – it can also be used with an interface you have written, or without any interface!
Full Code
*&---------------------------------------------------------------------*
*& Report zss_demo_comparable
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT zss_demo_comparable.
CLASS car DEFINITION.
PUBLIC SECTION.
METHODS:
constructor IMPORTING producer TYPE string
model TYPE string
year TYPE i,
equals IMPORTING object TYPE REF TO object
RETURNING VALUE(is_equal) TYPE abap_bool.
PRIVATE SECTION.
DATA:
producer TYPE string,
model TYPE string,
year TYPE i.
ENDCLASS.
CLASS car IMPLEMENTATION.
METHOD constructor.
me->producer = producer.
me->model = model.
me->year = year.
ENDMETHOD.
METHOD equals.
IF object EQ me.
is_equal = abap_true.
RETURN.
ENDIF.
IF object IS NOT BOUND.
is_equal = abap_false.
RETURN.
ENDIF.
TRY.
DATA(other) = CAST car( object ).
is_equal = xsdbool( me->producer EQ other->producer AND me->model EQ other->model AND me->year EQ other->year ).
CATCH cx_sy_move_cast_error.
is_equal = abap_false.
ENDTRY.
ENDMETHOD.
ENDCLASS.
CLASS truck DEFINITION.
PUBLIC SECTION.
METHODS:
constructor IMPORTING producer TYPE string
model TYPE string.
PRIVATE SECTION.
DATA:
producer TYPE string,
model TYPE string.
ENDCLASS.
CLASS truck IMPLEMENTATION.
METHOD constructor.
me->producer = producer.
me->model = model.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA(car1) = NEW car( producer = 'Mercedes' model = 'E400' year = 2016 ).
DATA(car2) = NEW car( producer = 'BMW' model = 'X5' year = 2013 ).
DATA(car3) = NEW car( producer = 'Mercedes' model = 'E400' year = 2016 ).
DATA car4 TYPE REF TO car.
DATA(car5) = car1.
DATA(truck1) = NEW truck( producer = 'CAT' model = 'CT660' ).
" 2 different non-null Car objects with different attributes
cl_demo_output=>write( |Car 1 and Car 2 are the same: { car1->equals( car2 ) }| ).
" 2 different non-null Car objects with the same attributes
cl_demo_output=>write( |Car 1 and Car 3 are the same: { car1->equals( car3 ) }| ).
" 1 non-null Car object with 1 null Car object
cl_demo_output=>write( |Car 1 is the same as Car 4: { car1->equals( car4 ) }| ).
" 2 different references to the same Car object
cl_demo_output=>write( |Car 1 is the same as Car 5: { car1->equals( car5 ) }| ).
" Self as an argument
cl_demo_output=>write( |Car 1 is the same as itself: { car1->equals( car1 ) }| ).
" 1 Car object with 1 Truck object
cl_demo_output=>write( |Car 1 and Truck 1 are the same: { car1->equals( truck1 ) }| ).
cl_demo_output=>display( ).


Visualize gene expression on top of cell tissues by use of OpenSeadragon
Quick start:
Click the button Open some example data files and layouts to view some examples. You can now create your own layout by filling out gene names in the add gene input field that is auto-completed. The added genes are visible as a new-line-separated list of names in the gene list.
After clicking "Create layout from gene list", an OpenSeadragon window appears where each of the genes have had its gene expression values painted as circles on top of the cell tissue microscope photos.
Example files from a new gene expression meassurement technology: Some st_exp_protobuf files were created by the shell script download_and_convert_example_data.sh out of data sets from www.spatialtranscriptomicsresearch.org.
The datasets are gene expression meassurements done with the technology described in the scientific paper
Visualization and analysis of gene expression in tissue sections by spatial transcriptomics published in Science June 2016. The generated example files (e.g. example file (34 Mb), example file (17 Mb) can be opened in the viewer either as remote URL:s or as local files after downloading them.
Hosting st_exp_protobuf files: When using a URL for accessing the st_exp_protobuf file,
the web server neeeds to support the HTTP request header RANGE (see Wikipedia article about
More in-depth information: The st_exp_protobuf file
format stores pyramid image tiles of high-resolution microscope photos that
can be displayed by a slightly modified
OpenSeadragon. The file format also contains gene expression values stored indexed by gene. A small header
in the beginning of the file contains indexes to the rest of the file. With this design, opening and displaying the gene expression will be very
fast because only a fraction of the whole st_exp_protobuf file needs to be downloaded (or read). The relevant parts of the data will be retrieved
as byte ranges.
The source code for this software project is located in the osd-spot-viewer github project
under this directory and it is licensed under the MIT license.
| filename | number of genes |
|---|


{tag_itemid} | Item's system ID |
{tag_address1} | Address1 |
{tag_address2} | Address2 |
{tag_addresscity} | City |
{tag_addresscountry} | Country |
{tag_addressglatlng} | This tag provides a shortcut to generate GLatLng objects for use with the Google Maps API. |
{tag_addresslatitude} | Latitutde of web app item address |
{tag_addresslongitude} | Longitude of web app item address |
{tag_addressstate} | State |
{tag_addresszipcode} | ZIP code |
{tag_addtofavorites,add_Image, remove_Image} |
Add the news item to favorites list. Optionally customize to display your own custom image for adding and removing. Here is an example - {tag_addtofavorites,,} |
{tag_button,Your Text} | will output a hyperlink with the text "Your Text" and when clicked will take the site visitor to the detail layout |
{tag_commentcount} | Number of comments for current post |
{tag_counter} | Incremental count of the item on the page |
{tag_delete} | Creates a link that allows current customer to edit a web app item they have previously submitted (only available if customer logged in to a secure zone) |
{tag_description,number of characters} | Description of item (editor content). On the "List Layout (Backup)" you can use {tag_description,10} to display the first 10 characters of the webapp item's description. |
{tag_edit} | Creates a link that allows current customer to edit a web app item they have previously submitted (only available if customer logged in to a secure zone). Clicking this link will open up the edit layout |
{tag_expirydate} | Expiry date of item in this format - 01-Jan-9999
|
{tag_lastupdatedate} | Last update date of item in this format - 28-May-2014 11:07 PM |
{tag_name_nolink} | Name of item (without hyperlink) |
{tag_name} | Name of the item - will have hyperlink that points to the item's detail layout |
{tag_releasedate} | Release date of item in this format - 08-Sep-2014 |
{tag_weight} | Weighting of item |
{tag_itemurl_withhost} | Full URL of the web app item including host for example http://mysamplesite.com/car-catalogue/ford-explorer |
{tag_itemurl_nolink} | Relative URL of the web app item for example /car-catalogue/ford-explorer |
{tag_rowcss,myclass} | Replate myclass with your own CSS class. Alternates between classes, such as "myclass" and "myclass_alternate" |
{tag_tellafriend} | Tell a friend about this item |
{tag_small image_value} |
renders the image's src |
{tag_small image_nolink} |
renders the image |
{tag_large image_value} |
renders the image's src |
{tag_large image_nolink} |
renders the image |
{tag_datasource_id} |
renders the ID of the datasource field |
{tag_datasource} |
renders a link to the datasource item |


The database level security is controlled in couchdb by a special document called _security. The _security document is unique to every database. Let's see what it looks like.
Taking an example from couchdb docs:-
{
"admins": {
"names": [
"superuser"
],
"roles": [
"admins"
]
},
"members": {
"names": [
"user1",
"user2"
],
"roles": [
"developers"
]
}
}
Every _security document[1] consists of two mandatory fields called admins
and members
. Both admins and
members are json objects that in turn are made up of
arrays called names
and roles
. The name in an admin or a member property must[2] be the name of
the user stored in _users database. When couchdb
authenticates a user
from the _users database it
can run checks[3] against the _security document of each database to determine whether the authenticated
user is an admin or a member.
The roles property on the other hand is free form--- meaning you can supply any value in the roles[4] array. What roles you choose would depend upon your application. If for example you are making an online library with couchdb you could use "librarian" and "reader" as roles. The significance of roles is that you can add role based checks in document validate functions and choose who updates what documents.
An admin is authorized to perform CRUD on _design and _security documents.[5]
A member can only read or write normal documents--- all documents except _design and the _security documents.[6]
Once you add a _security to the database then the database can only be accessed by the person who is a part of the _security document. Any un-authorized person would be forbidden from accessing the database. [7]
The conclusion is pretty easy to draw. couchdb offers minimal read level security on the normal documents (that is all documents except the special _design and _security documents). Minimal because once you set either an admin or a member in the _security document then only the person that has been added to _security object can read from the database. But you can't set conditional reading. Any member or any admin will be able to read all normal documents. That is there is no validate_on read function (In rcouch there is a validate_doc_read function). [8]
On the other hand couchdb offers full write level security. You can add conditional checks on who creates, updates or deletes a document using document update functions.
In short couchdb has two levels of security: -
the server level (which is set by the configuration files)
and the database level(which is set by the _security document)
The _security document consists of members and admins.
admins have the ability to write, read and update special documents of the database (_design and _security) where as the the members only have permission to read and write the normal documents (that is all documents except _design and _security).
Finally the write level protection can be enhanced by the use of document validate functions. [9]
Notes from Alexander
Thank you for proofreading this Alex :)
Two guys go to a bar...


The complexity of an expression is defined by the number of or
and and
conditions it
contains. A single expression's complexity should not become too high to keep the code readable. Try to extract some
sub-conditions to make the overall condition more understandable.
This rule checks that the number of conditions is not greater than 3.
if $var1 > 2 and $var2 > 3 or ($var3 > $var4 and $var1 < $var3) or $var5 > 4 { } # Noncompliant: 4 'and' and 'or' conditions
$is_position_valid = $var3 > $var4 and $var1 < $var3 if $var1 > 2 and $var2 > 3 or $is_position_valid or $var5 > 4 { }


# Daily jQuery
## **With Chris Kihneman**
# I...
...work at [Mindgruve](http://mindgruve.com) - a digital agency downtown.
...am a lead developer - "frontend focused"...
...code lots of JavaScript for...
large CMS driven sites,
apps, on PhoneGap for iOS, Pokki - Backbone.js, CoffeeScript, Underscore.js (among other things).
Oh, and I use jQuery pretty much every day.
![jQuery Everywhere](images/meme-jquery-everywhere.jpg)
# It keeps us sane when...
![Only ie7](images/meme-only-ie7.jpg)
![Success](images/meme-success.jpg)
# Know your JavaScript
### **jQuery is JavaScript afterall.**
# Know your debugger
### Chrome Dev Tools
#### vs
### Firebug
## Don't hurt yourself with
$( '.some-selector' ).on( 'click', function() {
alert( 'the pain.' );
});
## Help yourself with
$( 'div' ).on( 'click', function( e ) {
console.log( 'something useful.' );
console.log( 'two aruments or more', this, e, e.type );
// view the element as its html
console.log( this );
// inspect the element as an object, very useful
// for digging into the internals of JavaScript
console.dir( this );
});
## **`$0`** is your friend
So awesome -
1. Inspect an element
2. Hit escape to activate your console as well
3. Type **`$0`** into the console.
To get a jQuery object, just do **`$($0)`**. Boom! Now you can test something on the fly if you please. If you are in `jQuery.noConflict()` (as some CMS's do by default, Wordpress), then **jQuery($0)**.
## OMG Nothing is happening
* Did you get your selector right?
* Check `$('.some-selector').length` (maybe in a `console.log` call) to ensure you didnt either mess up your selector, or not put the element in your html.
* Do you have other plugins on the page?
* Sometimes plugins will prevent events from bubbling and could be blocking what you are trying to accomplish. Sometimes, you just have to read through a plugins code...
## My event isn't firing!?
* Have you AJAXed some content?
* Have you appended elements to the dom?
[fiddle!](http://jsfiddle.net/ckihneman/9E27T/)
# Event delegation
Leverage event bubbling! Event bubbling? Yup!
Allows us to catch events at a higher lever in the dom than where they occurred...
[mmm fiddles...](http://jsfiddle.net/ckihneman/BJcHn/1/)
# Don't use `.live`...
Just be more specific...
$( document ).on( 'click', 'a', function( e ) {
console.log( $(this).attr( 'href' ) );
});
But only do that if you really have to...it's going to always be better to delegate to the closest element possible.
## Getting `this`
What is `this`?
$( '.box' ).on( 'click', function() {
// `this` vs $( this )
var $this = $( this );
console.log( 'this', this );
console.log( '$( this )', $this );
console.dir( this );
console.dir( $this );
});
In event callbacks, `this` is the native dom element being acted on. That's why if you want to do jQuery operations you have to do `$( this )`, then you can [have your way with the element](blank.html).
# Don't call jQuery unless you have to.
Bad
$( '.box' ).text( 'awesome box' );
$( '.box' ).css( 'color', 'blue' );
$( '.box' ).addClass( 'visible' );
Good
var $box = $( 'box' );
$box.text( 'awesome box' );
$box.css( 'color', 'blue' );
$box.addClass( 'visible' );
# Even better...
var $box = $( 'box' );
$box
.text( 'awesome box' )
.css( 'color', 'blue' )
.addClass( 'visible' );
Remember, jQuery methods always (almost always) return themselves...chain it!
### Don't make sizzle work harder than it needs to!
Sizzle is the dom query engine in jQuery, it's great and all, but dont overwork it if you don't have to.
Instead of just `$( '.box' )` ...which searches your entire page...
Be more specific...
$( '#content' ).find( '.box' );
// or
$( '#content .box' );
// or
$( '.box', $('#content') );
But just use `$( '#content' ).find( '.box' );`. Its readable, and a lot of the time you might need to cache `#content` anyways...
# Getting started...but where?
I've started calling my main javascript page `index.js` ... or `app.js` if im working with the concept of "modules".
Decide on something and go with it.
# The closure ... or IIFE
IIFE? Yup, Immediately-Invoked Function Expression. What dat?
( function( $ ) {
// setup functions to be used
$( function() {
// execute ready code here
});
})( jQuery );
# The closure ... or IIFE
IIFE? Yup, Immediately-Invoked Function Expression. What dat?
( function( $ ) {
// setup functions to be used
$( function() {
// execute ready code here
});
})( jQuery );
# Wrapping functionality in a "jQuery plugin"
$.fn.pluginName = function() {
// `this` is the jQuery object, not a native dom element
};
# A real example
( function( $ ) {
// Set all elements to the height of the tallest element.
$.fn.setMaxHeight = function() {
return this.length < 2 ? this : this.height(
Math.max.apply( this,
$.map( this , function( e ) {
return $( e ).height();
});
);
);
};
})( jQuery );
## Know your plugins...
### do your research before using one or the other.
* bValidator is our goto for form validation
* AnythingSlider is our goto for sliding...anything!
* Can't find a plugin? Time to make one!
## thanks!
# questions?
### [feel free to drop me a line](mailto:ckihneman@mindgruve.com)


--- layout: post title: Django ImageFields in forms date: 2009-07-19 12:00:24.000000000 +01:00 type: post parent_id: '0' published: true password: '' status: publish categories: - python tags: [] meta: _edit_last: '1' author: Noel permalink: "/django-imagefields-in-forms/" ---
Until recently, I'd swerved the image parts of my Django web app as it seemed it would be as much effort customising the field for the development server as it would for a full apache instance. (However with hindsight, I'm not so sure). Here are my steps to get a model / view and templates working with an ImageField.
First you need the right configs in settings.py:
MEDIA_ROOT = '/home/username/webapps/media' MEDIA_URL = 'http://username.hosting.com/media/'
The root setting is where on the filesystem the base directory where the images/files will be uploaded to. media_url is the corresponding url where a client can request the files from.
In the model to store the image, you need some field
picture = models.ImageField(upload_to='userpics/')
The upload_to value will be a sub-directory of /home/username/webapps/media
To capture an image from user input, the form's attribute just needs a
picture = forms.ImageField()
The form in a template is a little different from other forms as it needs an additional attribute to cope with the file being uploaded:
<form action="." method="POST" enctype="multipart/form-data">

 Picture	 {{ form.picture }}

 <input type="submit" value="Submit"/> </form>
The final part is the view which changes slightly to accept a dictionary of files
def photo_input(request): if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): profile = User.objects.get('noel').get_profile() profile.picture = request.FILES['picture'] profile.save() return HttpResponseRedirect('/next/page/') form = PhotoForm() return render_to_response( 'photo_adder.html', {'form': form }, RequestContext(request))
And now the user-profile object has an image or file referenced to it, stored on the filesystem under
/home/username/webapps/media/userpics/
This file can then be used in a template:
{{ user.get_profile.picture.url }}
Hope this helps someone. If you have any feedback, please let me know.


Recipe 6.1. Converting Among Temperature Scales
Credit: Artur de Sousa Rocha, Adde Nilsson
Problem
You want to convert easily among Kelvin,
Celsius, Fahrenheit, and Rankine scales of
temperature.
Solution
Rather than having a dozen functions to do all possible conversions,
we can more elegantly package this functionality into a class:
class Temperature(object):
coefficients = {'c': (1.0, 0.0, -273.15), 'f': (1.8, -273.15, 32.0),
'r': (1.8, 0.0, 0.0)}
def _ _init_ _(self, **kwargs):
# default to absolute (Kelvin) 0, but allow one named argument,
# with name being k, c, f or r, to use any of the scales
try:
name, value = kwargs.popitem( )
except KeyError:
# no arguments, so default to k=0
name, value = 'k', 0
# error if there are more arguments, or the arg's name is unknown
if kwargs or name not in 'kcfr':
kwargs[name] = value # put it back for diagnosis
raise TypeError, 'invalid arguments %r' % kwargs
setattr(self, name, float(value))
def _ _getattr_ _(self, name):
# maps getting of c, f, r, to computation from k
try:
eq = self.coefficients[name]
except KeyError:
# unknown name, give error message
raise AttributeError, name
return (self.k + eq[1]) * eq[0] + eq[2]
def _ _setattr_ _(self, name, value):
# maps settings of k, c, f, r, to setting of k; forbids others
if name in self.coefficients:
# name is c, f or r -- compute and set k
eq = self.coefficients[name]
self.k = (value - eq[2]) / eq[0] - eq[1]
elif name == 'k':
# name is k, just set it
object._ _setattr_ _(self, name, value)
else:
# unknown name, give error message
raise AttributeError, name
def _ _str_ _(self):
# readable, concise representation as string
return "%s K" % self.k
def _ _repr_ _(self):
# detailed, precise representation as string
return "Temperature(k=%r)" % self.k
Discussion
Converting between several different scales or units of measure is a
task that's subject to a
"combinatorial explosion": if we
tackle it in the apparently obvious way, by providing a function for
each conversion, then, to deal with n
different units, we will have to write n *
(n-1) functions.
A Python class can intercept attribute setting and getting, and
perform computation on the fly in response. This power enables a much
handier and more elegant architecture, as shown in this recipe for
the specific case of temperatures.
Inside the class, we always hold the measurement in one reference
unit or scale, Kelvin (absolute) degrees in the case of this recipe.
We allow the setting of the value to happen through any of four
attribute names ('k', 'r', 'c', 'f', abbreviations
of the scales' names), and compute and set the
Kelvin-scale value appropriately. Vice versa, we also allow the
"getting" of the value in any
scale, through the same attribute names, computing the result on the
fly. (Assuming you have saved the code in this recipe as
te.py somewhere on your Python
sys.path, you can import it as a module.) For
example:
>>> from te import Temperature
>>> t = Temperature(f=70) # 70 F is...
>>> print t.c # ...a bit over 21 C
21.1111111111
>>> t.c = 23 # 23 C is...
>>> print t.f # ...a bit over 73 F
73.4
_ _getattr_ _
and _ _setattr_ _
work better than named properties would in this case, since the form
of the computation is the same for every attribute (except the
reference 'k' one), and we only need to use
different coefficients that we can most handily keep in a per-class
dictionary, the one we name self.coefficients.
It's important to remember that _ _setattr_
_ is called on every setting of any
attribute, so it must delegate to object the
setting of attributes, which need to be recorded in the instance (the
_ _setattr_ _ implementation in this recipe does
just such a delegation for attribute k) and must
raise an AttributeError exception for attributes
that can't be set. _ _getattr_ _,
on the other hand, is called only upon the
"getting" of an attribute that
can't be found by other,
"normal" means (e.g., in the case
of this recipe's class, _ _getattr_
_ is not called for accesses to
attribute k, which is recorded in the instance and
thus gets found by normal means). _ _getattr_ _
must also raise an AttributeError exception for
attributes that can't be accessed.
See Also
Library Reference and Python in a
Nutshell documentation on attributes and on special
methods _ _getattr_ _ and _ _setattr_
_.
|


JSON Tabulator
Table 1
Table 2
You can also tabulate your own data by pasting your JSON Object in the space provided
Select table to display
Table 1&2
Table 1
Table 2
clicking me
For any errors, please check your JSON input


312 Chinese in telco fraud deported by BI
by Itchie G. CabayanA TOTAL of 312 Chinese nationals reportedly involved in telco fraud were deported by the Bureau of Immigration (BI).
Spokesperson Dana Sandoval said the 312 is part of the 512 arrested by the BI last month in a massive raid of a Business Processing Outsourcing office in Pasay City. Also leaving with the 312 are 21 minors whose custody were turned over to the Chinese embassy upon determination of their age.
It can be recalled that last October 9, the BI conducted a raid in an office in the Millenium Building, Pasay City and hauled 512 aliens found to be reportedly conducting scamming operations. Those arrested consisted of Chinese, Burmese, Malaysians, Vietnamese, Taiwanese, and Indonesians.
According to BI Intelligence chief Fortunato Manahan, Jr. the operation was a success after the implementation of the mass deportation and said they are thankful to the NCRPO (National Capital Region Police Office) for assisting the BI in the operation.


Encryption: It is the process of encoding messages or information in such a way that only authorized access is possible
Decryption: It is the process of converting encrypted data back into its original form, so it can be understood