text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ !+--------------------------------+! !|ROBYRT'S GOD OF WAR 2 COMBAT FAQ|! !| VERSION 1.0 |! !+--------------------------------+! \~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/ ------------ INTRODUCTION ------------ There are many guides out there on how to get through God of War - how to finish the puzzles, how to read the bosses' attacks, how to Plume of Prometheus your way through the entire game, etc. This is not one of them. This is a guide that provides in-depth information on the combat mechanics of the game. What attacks can I chain into other attacks? What moves do all the normal enemies have and how can I avoid them? What effect do my moves have on various enemies? How can I do three of the same move in a row with the Blades of Olympus, but not four? That's what you'll find here. You can use this information to fight This FAQ is copyright (c) 2007, Robert Marney. All rights reserved. VERSION HISTORY: 0.1: Weapons started, 3/27/07 0.2: Original templating, 3/28/07 0.3: Light enemies, 3/28/07 0.5: Weapons finished, 3/28/07 0.8: Enemies finished, 3/29/07 0.9: Magic finished, 3/29/07 1.0: Pegasus finished, 3/29/07 CONTROLS AND ABBREVIATIONS: Left analog stick = Move Right analog stick = Roll X = X face button = Jump S = Square face button = Light attack T = Triangle face button = Heavy attack O = Circle face button = Grab L1 = Top left trigger = Block L1+R1 = Amulet of the Fates L2 = Bottom left trigger = Use selected magic R1 = Top right trigger = Interact with environment R2 = Bottom right trigger = Toggle selected subweapon D-Pad = Choose Magic L3+R3 = Press down on both analog sticks = Toggle Rage of the Titans TABLE OF CONTENTS: 1. Weapons 1.1. Basic Attacks 1.2. Athena's Blades 1.2.1. Basic Attacks 1.2.2. Special Attacks 1.2.3. Rage of the Titans Attacks 1.3. Barbarian Hammer 1.4. Spear of Destiny 1.5. Blade of Olympus 2. Magic 2.1. Typhon's Bane 2.2. Cronos' Rage 2.3. Head of Euryale 2.4. Atlas Quake 2.5. Poseidon's Rage 3. Enemies 3.1. Light Enemies 3.2. Medium Enemies 3.3. Heavy Enemies 4. Pegasus 4.1. Pegasus Attacks 4.2. Pegasus Enemies 5. Credits ========== 1. WEAPONS ========== Attacks are templated like this: Attack Name Command Requirements (if any) Comments Chains to: (list of other moves, or None) Effect on light enemies: Effect on medium enemies: Effect on heavy enemies: Here are the different attack effects: None: No effect on the enemy except for doing damage. Stun: The enemy staggers briefly and stops its attack. Knockdown: The enemy bounces off the floor for a second. Launch: The enemy is thrown high into the air. Scatter: The enemy is flung backward a large distance. Guard Break: The enemy will not block the next attack. All attacks will at least Stun an enemy who has been launched airborne. All basic attacks can be cancelled into other basic actions: -> X: Jump straight up -> O: Grab the current target -> L1: Block -> L2: Use Magic on current target To perform basic attack chains, press the buttons in a regular rhythm - you can input the next command very early in the animation of the previous move, or even queue up a couple commands, or you can wait until the last second and delay the next attack a little bit. ------------------ 1.1. BASIC ATTACKS ------------------ These attacks can be used regardless of your current weapon. Icarus Lift X,X Standard double jump. This isn't technically an attack, but it's useful during combat to gain extra air time if you want to use good air attacks like L1+X or L1+T without getting hit by grounded opponents before they connect. Grab O Kratos' grabs are different for each enemy. In general, light enemies can always be grabbed and medium or strong enemies can be grabbed when the O button appears above their heads. Some grabs require minigames to complete. While doing a grab animation, Kratos is invincible. This is extremely useful. When you grab a Fates or Undead soldier, you have a choice of grabs; in this case, until you start the animation of your chosen grab, Kratos is not invincible. Air Grab O in air Kratos has different air grabs for each enemy; all require him to be fairly close to the enemy, and they're usually quite powerful. Whether Kratos and/or his opponent are left airborne depends on the individual grab. Athena's Reverse L1 just before an attack lands Kratos can actually parry attacks even before he gets the Golden Fleece. You'll know you did it correctly when he spreads both his arms wide. This slows down time for a split second, can interrupt some enemies' attacks (without doing damage), and can block some normally unblockable attacks, like the Cerberus' fireballs. Unlike God of War 1, you can't follow this up with extra attacks. Chains to: None Effect on light or medium enemies: Stun Effect on heavy enemies: None Golden Fleece Parry L1 just before an attack lands, when you have the Golden Fleece The Athena's Reverse animation is replaced by a golden flash around Kratos. The only downside to this is that there is a small but finite minimum amount of time you are required to block (the length of the Fleece animation). If you parry a Gorgon's gaze, you'll need a minigame button press to turn nearby enemies into stone. The parry itself does no damage. Chains to: Argo's Revenge, Argo's Return Effect on light or medium enemies: Stun Effect on heavy enemies: None Argo's Revenge S while parrying a physical attack with Golden Fleece Kratos thrusts both his blades into the ground, causing a golden plume of energy that knocks enemies away from you. Kratos is invulnerable during the Argo's Revenge animation, and its recovery time is minimal. Argo's Revenge is not unblockable, but it's always good for some free damage. Chains to: None Effect on light enemies: Scatter Effect on medium or heavy enemies: None Argo's Return Parry a projectile attack with Golden Fleece Kratos winds up, then fires a bolt of golden energy back at the projectile's caster. Kratos is invulnerable during this animation. Chains to: None Effect on light or medium enemies: Knockdown Effect on heavy enemies: None Icarus Ascension L1+X while you have Icarus Wings Kratos unfurls his wings and leaps upward, taking any enemies in a small radius around him upwards as well. It's just as powerful as your other launching moves, and it's faster and offers protection by launching multiple foes at once. Very handy for dealing with foes who tend to block, or for completing the Challenge of the Titans. Chains to: None (follow with air attacks) Effect on light or medium enemies: Launch Effect on heavy enemies: None Orion's Harpoon O targetting an airborne enemy Kratos sends a blade upward, impales the enemy with it, then whips them around and slams them back down into the ground. Unlike your other grab attacks, this one is NOT invulnerable; in exchange, it does a huge amount of damage. Some enemies bounce upward afterwards, allowing you to tack on another Orion's Harpoon. Depending on the enemy, Orion's Harpoon may do 1 or 2 hits. Chains to: None Effect on all enemies: Knockdown -------------------- 1.2. ATHENA'S BLADES -------------------- Athena's Blades are your default weapon for the entire game, but they're also probably the most useful weapon. They have a range advantage over your subweapons and most enemy weapons as well, they can be upgraded to contain a toolbox of new moves for all situations, and they're extremely fast and safe while doing weaker moves. You'll want fully upgraded Blades by the end of the game because of their capability to do damage on the ground and in the air. 1.2.1. BASIC ATTACKS ~~~~~~~~~~~~~~~~~~~~ Jab S Single weak attack straight forward with the left-hand blade. Can be aimed with the analog stick; usually the auto-aim takes care of this so you don't need to aim. Use this to start your attack chains and interrupt light enemies. Chains to: Double Jab, Overhead Strike Effect on light enemies: Hit Effect on medium or strong enemies: None Double Jab SS Kratos does another weak attack swinging forward and to the right. The same great range as the original S. Chains to: Weak Combo, Plume of Prometheus, Hyperion Charge Effect on light enemies: Hit Effect on medium or strong enemies: None Overhead Strike T or ST Kratos slams first one blade and then the other down onto the enemy. Because of the hit stun caused by the S attack and the shortened startup animation from being chained, ST is usually better than just pressing T. Until you can afford TTT, this is your best way of doing damage to strong enemies. Chains to: Double Jab, Olympic Ascension, Strong Combo Effect on light enemies: Launch Effect on medium enemies: Knockdown Effect on heavy enemies: None Weak Combo SSSSSS Kratos does in order: a sideways swipe, an upwards swipe, two swipes in an X shape, and two upwards swipes in an X shape. These all do low damage, and have lower range than your Double Jab, but you can walk forward slightly to increase the range a bit, and the whirling motion means it's easy to hit and stun multiple weak enemies at the same time with this combo. Mostly used to build up to your powerful finishers. Chains to: Spirit of Hercules, Valor of Hercules Interrupt combo with: Plume of Prometheus (press T) Effect on light enemies: Stun Effect on medium or strong enemies: None Plume of Prometheus T after Double Jab (SST) or during a Weak Combo Kratos slams both his blades into the ground as far forward as they can reach, sending a plume of energy with deceptively good area of effect that can launch or stagger a group of enemies. Your best defensive move because of its great range and ability to clear the area of weak enemies while you make your escape. Use this during a Weak Combo if you don't think you'll have enough time to connect a full Spirit/Valor of Hercules combo. Chains to: Olympic Ascension Effect on light enemies: Launch Effect on medium or strong enemies: Stun Olympic Ascension Hold T Kratos whips both his blades into the air after a long windup, sending enemies far into the air. If you continue to hold T, Kratos will follow them skyward. While you will get better launching attacks later in the game, this comes in very handy to separate yourself from a crowd and concentrate fire on a single, helpless opponent. Chains to: None (follow with air attacks) Effect on light or medium enemies: Launch Effect on heavy enemies: None Spirit of Hercules T after Weak Combo (SSSSSST) or Strong Combo (TTT) Kratos whips his blades up (1 strong hit), jumps up (freezing time for a split second), and slams them back down into the ground for 2 more hits, each one as powerful as the Plume of Prometheus. This move CANNOT be cancelled into a block, grab or jump like your other basic moves, and so you shouldn't use it unless you're sure it won't be interrupted. That said, it does a lot of damage, so it's still worth trying for every once in a while. In God of War 1, this move chained to Olympic Ascension, but it doesn't anymore. Chains to: None Effect on light or medium enemies: Launch Effect on heavy enemies: Stun Valor of Hercules S after Weak Combo (SSSSSSS) or Strong Combo (TTS) Kratos whips his blades in a 270-degree arc covering his front and both sides, sending enemies flying out to the sides. An extremely useful attack because it gives you some breathing room, will almost always hit multiple enemies, and does plenty of damage unlike your other weak attacks. Chains to: None Effect on light or medium enemies: Scatter Effect on heavy enemies: None Air Weak Combo SSS in air Kratos does three weak swipes: first right, then left, then upwards. The main use of this move is the first swipe, which is fast enough to come out even if you've almost hit the ground, allowing you to continue a combo on an enemy who's been knocked to the ground and you're still airborne. Otherwise, however, you're better off with air combos that are more powerful and just as quick. Chains to: Any air attack, during any hit Effect on light or medium enemies: Stun Effect on heavy enemies: None Air Overhead Strike T in air Kratos does his Overhead Strike with a quicker startup time. This has the exact same properties as the ground version of the move, leading to the wonderful ability to Overhead Strike a light enemy you've launched, then do another air move on them, usually an air grab, after it re-launches them. Chains to: Any air attack Effect on light enemies: Launch Effect on medium enemies: Knockdown Effect on heavy enemies: None 1.2.2. SPECIAL ATTACKS ~~~~~~~~~~~~~~~~~~~~~~ Rampage of the Furies L1+O Requires Athena's Blades level 2 Kratos does a few spinning hits closely around him, several rapid-fire forward strikes, and finishes with a tiny energy plume ahead of him. Useful mainly for its looks, as it's very difficult to aim all the hits correctly and you can't block or cancel the move before it's finished. Most medium or strong enemies will block and counterattack before you're done, and most weak enemies will already be dead - so use it at the beginning of the game, when your Blades aren't powerful enough to kill enemies without this move. Chains to: None Effect on light enemies: Stun, then Scatter on last hit Effect on medium enemies: None, then Scatter on last hit Effect on heavy enemies: None Rampage of the Furies (Air) L1+O in air, then mash O Requires Athena's Blades level 2 Kratos spins his blades in tiny circles all around him (except to the back and below). Except for the small range, this attack is fearsome, your main followup to a launching move from Typhon's Cavern all the way to Lahkesis. It does plenty of damage, racks up hits for your combo meter, and can be done multiple times before you hit the ground or even followed up with an air throw. Chains to: None Effect on light or medium enemies: Stun Effect on heavy enemies: None Cyclone of Chaos L1+Square Requires Athena's Blades level 3 Kratos spins both his blades in quick circles around him - just like the attack from God of War 1, except he moves slightly forward and the hits are more powerful. This move doesn't do much damage, but it's great for clearing out swarms of weak enemies. If you attack immediately afterward, you can keep your combo, but it can be difficult. On lower difficulty levels, this is basically the only move you'll ever use. Chains to: None Effect on light or medium enemies: Stun Effect on heavy enemies: None Cyclone of Chaos (Air) L1+Square in air Requires Athena's Blades level 3 Kratos whirls his blades around quickly at a slightly downward angle. Unlike the first game, there's really no reason to use this attack, unless you've launched multiple opponents with the Icarus Wings and need to hit them all at once. You're usually better off sticking with the Rampage of the Furies. Chains to: None Effect on light enemies: Stun Effect on medium or heavy enemies: None Strong Combo T after Overhead Strike (TT or STT) Requires Athena's Blades level 3 Kratos follows up his Overhead Strike with two more heavy hits swinging forward and upward. Great for killing single enemies, as it will combo even if the Overhead Strike launched your opponent. Also your fastest way of getting to the Spirit of Hercules and Valor of Hercules attacks. Unlike your other special moves, this one can be interrupted with a block. Chains to: Olympic Ascension, Spirit of Hercules, Valor of Hercules Effect on light or medium enemies: Stun Effect on heavy enemies: None Hyperion Charge Hold S during Double Jab or Weak Combo Requires Athena's Blades level 4 Kratos spins both his blades in a quick 360-degree circle. If you keep holding S, he will run straight forward extremely quickly for a few seconds. While Kratos is running, he's vulnerable, but you can control the direction he runs with the left analog stick. Not a terribly useful move. Chains to: Hyperion Rush, Hyperion Rise Effect on light enemies: Stun Effect on medium or heavy enemies: None Hyperion Rush S during Hyperion Charge Kratos does a powerful shoulder charge - a souped-up version of his R1 attack from God of War 1. This will send enemies flying sideways, and is lots of fun to use, but really isn't terribly useful because the Hyperion Charge's windup is so long that anyone you needed to knock down at a distance (like archers) is already shooting at you by this time. Chains to: None Effect on light or medium enemies: Scatter Effect on heavy enemies: None Hyperion Rise T during Hyperion Charge Kratos lifts an enemy into the air with an uppercut and follows them skyward, just like his L1+X attack from God of War 1. This is much more useful, since you can then wail on the enemy you attacked, but unless there is an extremely high-priority target (like a priest) somewhere you need to run to, you're better off not using the Charge at all. Chains to: None (follow with air moves) Effect on light or medium enemies: Launch Effect on heavy enemies: None Athena's Wrath T after rolling Requires Athena's Blades level 4 Kratos sends a shockwave along the ground which launches enemies. While this can occasionally be a useful counterattack, you'll more often do it accidentally while trying to roll away and start your Overhead Strike on vulnerable enemies. To solve this problem, just do S before your Strong Combos and reserve T for Athena's Wrath. Chains to: None Effect on light enemies: Launch Effect on medium enemies: Stun Effect on heavy enemies: None Tartarus Rage L1+T Requires Athena's Blades level 5 Kratos slams his blades into the ground in front of him 3 times: first left, then right, then both at once. You can change the direction of the last strike with the analog stick in case you missed. This attack is slow but extremely powerful, and is great for use against enemies who are tied up doing a move that isn't "hitting you out of the last strike". Chains to: None Effect on light enemies: Launch Effect on medium enemies: Knockdown Effect on heavy enemies: Stun Icarus Strike L1+X in the air after you acquire Icarus Wings Kratos unfurls his wings for a quick blow in front of him that has a good area of effect and knocks enemies sideways. One of the few moves fast enough to be used during a single jump as opposed to a double jump. Of course, the actual uses for this move are low, as you'll never want to get an airborne enemy away from you, and you'll rarely be attacking the ground from the air, but if you feel adventurous and want to scatter enemies ASAP, this is it. Chains to: None Effect on light or medium enemies: Scatter Effect on heavy enemies: None 1.2.3. RAGE OF THE TITANS ATTACKS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Rage Weak Combo Mash S while in Rage of the Titans Kratos does several spinning attacks all around him, finishing with a double strike in an X pattern in front of him. This is a very versatile attack, as it does good damage, knocks away enemies, and unlike the Rage Strong Combo, doesn't miss very often even if you're bad at aiming. Chains to: None Effect on light or medium enemies: Stun, then Scatter on last hit Effect on heavy enemies: None Rage Strong Combo TTT while in Rage of the Titans Kratos does a few swipes forward and upward, then jumps forward spinning, finishing with a plume forward. This move does loads of damage but is very difficult to target on a single enemy; thankfully, your immunity to being stunned during Rage of the Titans means it'll almost always at least finish the move. Generally, unless you've got an enemy backed up against a wall, it's safer to stick with the Rage Weak Combo. Chains to: None Effect on light or medium enemies: Stun, then Knockdown on last hit Effect on heavy enemies: None, then Stun on last hit Prometheus' Flare Press L1 while in Rage of the Titans Kratos knocks back nearby enemies. You'll never need to use this, as you'd rather have enemies hit by your Rage Weak Combo than be pushed away from it. This is what you get when Prometheus' Inferno fizzles. Effect on light or medium enemies: Stun Effect on heavy enemies: None Prometheus' Torment Hold S while in Rage of the Titans Requires Athena's Blades level 4 Much like the Cyclone of Chaos, Kratos will spin his blades in a wide circle. They will continue until you stop holding S, and they do very little damage. Mostly they're useful for racking up your combo count while keeping you safe from enemy attack - usually, only strong enemies can get through this "shield" of hits, since the Rage of the Titans prevents archery shots from stopping you. Once you have Prometheus' Inferno, it becomes part 1 of a deadly 1-2 combination. Chains to: Rage Weak Combo Effect on light or medium enemies: Stun Effect on heavy enemies: None Prometheus' Inferno Hold L1 while in Rage of the Titans with a combo meter of at least 25 Requires Athena's Blades level 5 A very odd move but a very powerful one: Kratos causes an enormous whirlwind of fire to appear around himself. It drains your COMBO METER to inflict damage on the enemy, so don't use it until you have 100+ hits. The easiest way to get hits is to use Prometheus' Torment or Cronos' Rage; if both are used in tandem, you can get 200-300 hits for the Inferno while draining only half of your Rage of the Titans meter for later use. Since you're in Rage of the Titans and the Inferno stuns all enemies, you're essentially invincible. Chains to: None Effect on all enemies: Stun --------------------- 1.3. BARBARIAN HAMMER --------------------- The Hammer is the most underwhelming of Kratos' weapons. It's wonderful against groups of soldiers, but the severe maneuverability, range and speed limits it imposes make it unwieldy against any larger enemies or bosses with attacks you need to dodge. It's expensive to upgrade and the additional moves are more for the purpose of making up for the Hammer's deficiencies rather than making it absurdly powerful like the other weapons' upgrades. Still, it's a lot of fun when it works. When the Hammer is active, you cannot roll; instead, pressing the right analog stick will add a Soul Summon to your current move (except blocking). Double Swing - Spin SSS Kratos does three successive swings with the hammer, each more powerful and slower than the last. This is your main hammer move, as most enemies are quick enough to dodge or interrupt the Double Pound, and the Spin is a very powerful attack that can clear groups of enemies quickly. Chains to: None Effect on light or medium enemies: Scatter Effect on heavy enemies: None Double Swing - Pound SST Kratos does two hammer swings and finishes with a powerful attack making sparks fly up from the ground where the hammer hits it. If you're sure your enemy won't move from that spot, use this. It's slightly faster than the Spin, but still quite likely to be interrupted by enemies who are near you at the time. Chains to: None Effect on light or medium enemies: Knockdown Effect on heavy enemies: None Double Pound TT Kratos pounds twice, moving forward slightly between the two attacks. The long windup on this move makes it useful only against largely sedentary enemies like a Cyclops; you'll usually end up annihilating one random soldier and getting attacked by the others if you try to use this against more than one opponent. Chains to: None Effect on light or medium enemies: Knockdown Effect on heavy enemies: None Crushing Defeat L1+S Kratos does a slow hammer spin like his second Swing, then picks up speed while whirling forward to a final Spin attack. Like your L1+S attack with the Blades, it's more for crowd control than dealing damage, but it's so slow and tends to miss with the middle hits so often that it'll rarely be effective even at that. Plus, you can't even block during it, because it's a special move. Chains to: None Effect on light or medium enemies: Scatter Effect on heavy enemies: None Might of the King L1+T Kratos slams his hammer down in front of him, creating a shockwave that launches opponents. Unsafe and gimmicky, but it looks great. The only enemies likely to fall for this are soldiers, who you can proceed to demolish with your regular hammer strikes while they're knocked down. Chains to: None Effect on light or medium enemies: Launch Effect on heavy enemies: None Might of the King (Air) L1 in air Kratos drops to the ground with his hammer sideways, emitting a wave of energy that launches opponents. This is actually much safer and more effective than the ground Might of the King, as it'll still hit enemies below you with the hammer, and jumping is your only real way to "evade" attacks with the hammer. Unfortunately, the hammer has no way to take advantage of all the enemies you're launching so easily with this move. Chains to: None Effect on light or medium enemies: Launch Effect on heavy enemies: None Air Swing S in air Kratos takes a single swipe from side to side. Since you'll rarely be jumping with the Hammer anyway, it's OK that this move is lackluster. Chains to: None Effect on light or medium enemies: Stun Effect on heavy enemies: None Air Pound T in air Kratos swipes quickly downward with his hammer. This is a fun move, actually, and great for defending yourself. Think of it like a single-hit version of Kratos' Air Overhead Strike with Athena's Blades. It's also a lot faster than the Air Might of the King, so you'll often need it. Chains to: None Effect on light or medium enemies: Knockdown Effect on heavy enemies: None Soul Summon Tap the right analog stick in any direction Requires Barbarian Hammer level 2 A small soul comes out of the Hammer which will automatically attack enemies for up to 3 hits. The soul does next to no damage, but Soul Summon can be used during any of Kratos' attacks, so just keep doing it while you're fighting. The main purpose of Soul Summon is to be able to rack up a combo count with the Hammer, although you'll still be hard-pressed to get any significant bonus from it. It can also deal with Harpies or Nymphs on lower difficulty levels. Chains to or from any other move Effect on grounded enemies: None Effect on airborne enemies: Knockdown Legion of Souls L1+O Requires Barbarian Hammer level 3 Kratos jumps up and slams his hammer down on the ground, causing 3 souls to come out; each one does up to 4 hits and launches enemies. The hammer strike is slow but powerful, but the real benefit is tying up enemies so that you can use your hammer without being interrupted. If the hammer had this attack by default, it could legitimately deal with groups of enemies who weren't basic soldiers - but that's just wishful thinking. Chains to: None Effect on light or medium enemies: Knockdown Effect on heavy enemies: None --------------------- 1.4. SPEAR OF DESTINY --------------------- The Spear of Destiny appears midway through the game just before the Crossing of the Lowlands, and it makes a great subweapon but not a complete Blades replacement. The Spear focuses on quick, versatile strikes against single enemies, making it ideal against medium-sized enemies; the upgrades allow it to effectively fight heavy enemies as well. While most of its strikes have short range, some moves magically extend the spear - these are always useful. Double Slash SS Kratos does two small sideways slashes. They have bad damage and range but start quickly. This is your safest combo starter, as it doesn't leave you hanging like the Uppercut Stabs. You can follow up either the single or double slash with the Uppercut Stabs if you successfully connect. Chains to: Forward Stabs, Uppercut Stabs Effect on light or medium enemies: Stun Effect on heavy enemies: None Uppercut Stabs TT Kratos does an uppercut that launches enemies (the fastest in the game) followed by five upward stabs. The stabs will almost always connect if you hit with the uppercut, and sometimes even if the uppercut is blocked. If you hold T after the launcher, Kratos will follow the opponent upward, but realistically, the stabs do more damage than the Spear's air moves, so this option is merely for defensive purposes to avoid enemy attacks. This move is mainly useful against enemies that like to block, because if they don't block the opening launcher, they're stuck with the duration of your combo. Chains to: Spear Swipe, Upwards Shards Effect on light or medium enemies: Launch on first hit, then Stun Effect on heavy enemies: None Forward Stabs SS after Double Slash (SSSS) Kratos does an uppercut with the Spear, then a 4-hit forward stabbing attack. Good for closing distance without being as vulnerable as the special moves - since it counts as a normal attack, you can block during the stabs. Chains to: Spear Swipe, Upwards Shards Effect on light or medium enemies: Stun Effect on heavy enemies: None Spear Swipe S after Forward Stabs (SSSSS) or Upward Stabs (TTS) Kratos does a slow counterclockwise spear swipe accompanied by a small explosion of purple energy which sends enemies flying. While this move does what it's designed to do, it'll often be interrupted when fighting against more adept enemies. Although it looks like it hits behind Kratos, it doesn't, so its main purpose is to recover from missing with the Forward or Upward Stabs. Chains to: None Effect on light or medium enemies: Scatter Effect on heavy enemies: None Upward Piercing Shards T after Weak Combo (SSSST) or Strong Combo (TTT) Kratos shoots several tiny projectiles out of his spear forward and upward. Like a weak shotgun blast, it doesn't do much damage, but it knocks enemies back a good deal, and breaks the guard of anyone who managed to block the rest of your hits, allowing you to follow up with more moves. It only hits once. Be careful in the Challenge of the Titans, as this move will still connect if you launched an enemy badly with the Upward Stabs, but unless you're right underneath them, it'll hit them on the ground and won't count as an air kill. Chains to: None Effect on light or medium enemies: Guard Break Effect on heavy enemies: None Deadly Slash L1+S Kratos winds up, then extends his spear and slashes across an arc to his front and sides. The move isn't terribly powerful, but it does hit everyone, so it provides a small measure of crowd control. Since it's slow to start, it's best used after a Piercing Shards or Spear Swipe to get yourself some distance. Chains to: None Effect on light enemies: Stun Effect on medium or heavy enemies: None Piercing Shards L1+T Kratos fires a quick blast of purple energy shards in front of him. Like a weak shotgun blast, it doesn't do much damage, but it knocks enemies back a good deal, and breaks the guard of anyone who managed to block the rest of your hits, allowing you to follow up with more moves. It only hits once. You shouldn't just use this indiscriminately, as it's much less powerful than your regular suite of spear attacks, but it can give you some breathing room or reduce a 2-enemy fight to a 1-enemy fight. Chains to: None Effect on light or medium enemies: Scatter, Guard Break Effect on heavy enemies: None Air Double Slash SS while jumping Kratos slices left and right with his Spear. This makes a good starting air attack if you've launched an opponent, as it comfortably combos into your other air moves or an air grab, and the damage is decent. Chains to: Any air attack, during either hit Effect on light or medium enemies: Stun Effect on heavy enemies: None Air Up-Down Slash T while jumping Kratos does a 2-hit heavy combo on the airborne opponent that knocks them back down to the ground. Never do this move while actually jumping, only while launching an opponent - otherwise you won't have enough time to follow up with another attack. If you really need to put an enemy out of commission (if not dead), launch them, then Up-Down Slash into Air Piercing Shards to send them all the way to the other side of the room. Icarus Wings, then a pair of Up- Down Slashes also works if you absolutely need to kill them while airborne. Chains to: Any air attack Effect on light or medium enemies: Knockdown Effect on heavy enemies: None Piercing Shards (Air) L1 while jumping Kratos blasts the Shards out in front of him. If his nearest opponent is on the ground, it'll angle slightly down to hit them. This isn't very powerful, but it'll scatter an airborne opponent while doing exactly the same thing as your regular Shards against a grounded opponent. Unfortunately, it causes Kratos to hang in the air for a while, negating its usefulness as a guard break, so stick to using it as the game's only air scattering attack. Chains to: None Effect on light, medium or airborne enemies: Scatter, Guard Break Effect on heavy enemies: None Unfortunate Remains L1+O Requires Spear of Destiny Level 2 Kratos slams his spear down in front of him, laying a purple crystal mine that explodes after a couple seconds. If the spear hits someone, it'll do 2 hits and won't lay a mine. The mine is surprisingly effective, keeping enemies knocked around instead of attacking you - just make sure no one wanders around to the side where your mines aren't hitting. It also does a fair amount of damage, unlike most other gimmicky special attacks. Effect on light enemies: Knockdown Effect on medium enemies: Stun Effect on heavy enemies: None Altering Slash L1+S Requires Spear of Destiny Level 3 Kratos does a Deadly Slash, but one enemy it hits (usually the first one it hits) will slowly glow purple and eventually explode in a powerful crystal blast. Since the Spear isn't good at handling groups unless you've created some space for yourself, this move is invaluable - you can simply block and wait for your enemy to do the work for you. It also helps against larger enemies when you need to stay on the defensive - during pauses in an enemy's attack pattern, simply Altering Slash and run away. The bomb blast will keep going even if Kratos is currently killing the enemy with a grab - it'll simply damage all nearby enemies except the enemy being grabbed. Plus, turning enemies into bombs is hilarious! Effect on light or medium enemies: Stun (spear), Scatter (bomb) Effect on heavy enemies: None (spear), None (bomb) --------------------- 1.5. BLADE OF OLYMPUS --------------------- The Blade of Olympus is a very powerful sword when you first get it and utterly ridiculous once it's upgraded. Except for specific single-purpose moves like Altering Slash, Plume of Prometheus and Air Cyclone of Chaos, the Blade is the last weapon you'll ever need. Left Slice S Kratos slashes once to his left. Your main Blade move starter, as it can flow quickly into either light or heavy attacks, and it's quite fast. Chains to: Right Slice, Upward Slice Effect on light or medium enemies: Stun Effect on heavy enemies: None Downward Slice Kratos brings the blade straight down to the ground. It's slower but more powerful than the Left Slice. Generally not as useful, except against bosses and Titan Minotaurs where a few powerful hits mean more than several quicker strikes. Like your Athena's Blades, you can switch back to Square-button attacks after this move. T Chains to: Right Slice, Upward Slice Effect on light or medium enemies: Stun Effect on heavy enemies: None Right Slice S after Left Slice (SS) or Downward Slice (TS) A single slash to the right, basically identical to the Left Slice. Just like Athena's Blades' Double Jab move, you can move to more powerful attacks or continue doing weak horizontal attacks after the Right Slice. Chains to: Left-Right Slice, Up-Down Slice Effect on light or medium enemies: Stun Effect on heavy enemies: None Upward Slice T after Left Slice (ST) or Downward Slice (TT) Kratos slices upward once, in a move identical to the first hit of the Up-Down Slice, which is really your only option at this point (besides an Uppercut Combo, of course). Really, this move is just there to let you mash TTTT with the Blades of Olympus. Oddly enough, pressing S instead of T will still combo into an Up-Down Slice. Chains to: Up-Down Slice Effect on light or medium enemies: Stun Effect on heavy enemies: None Left-Right Slice SS after Right Slice (SSSS or TSSS) An exact copy of the SS Left Slice, Right Slice combo, except that you don't have the same branching options - you can pick Up-Down or go for the big Scatter Slice afterward, and that's it. Oddly enough, pressing T instead of S for the 4th hit will still do the second hit (the right slice) as normal. Chains to: Scatter Slice, Up-Down Slice Effect on light or medium enemies: Stun Effect on heavy enemies: None Up-Down Slice TT after Upward Slice (TTTT or STTT) or Left-Right Slice (SSSSTT or TSSSTT) Kratos does a copy of his Upward Slice, then a slower, powerful strike slamming his blade into the ground. The second hit isn't affected by Anger of the Gods, and can't be cancelled by blocking. Chains to: None Effect on light or medium enemies: Stun (up), Scatter (down) Effect on heavy enemies: None Scatter Slice S after Left-Right Slice (SSSSS or TSSSS) Kratos does a slow whirling attack to the left with good range that scatters enemies. It's great for button-mashing and does lots of damage, but is likely to be interrupted if you're right next to an enemy (which happens quite often with the Blade of Olympus). To prevent doing this accidentally when you're just trying to shoot an enemy with Anger of the Gods, do an Up-Down Slice after your Left-Right Slice instead to get the same 5 laser shots more quickly. You can't cancel this slice by blocking, so be careful. Chains to: None Effect on light or medium enemies: Scatter Effect on heavy enemies: None Uppercut Combo Hold T after ANY hit with the Blade of Olympus Kratos does an upwards slash, a huge uppercut, then jumps upward and delivers an automatic downwards strike to his enemy. None of the hits are affected by Anger of the Gods. Unlike its Olympic Ascension counterpart, you CANNOT do the Uppercut Combo by itself simply by holding T; this will do a Downward Slice and then an Uppercut Combo. Chains to: None (follow with air attacks) Effect on light or medium enemies: Launch, then Knockdown Effect on heavy enemies: None Air Left-Right Slice SS or ST in air Kratos does two quick slashes, first to the left and then to the right. Great for lasering things or following up on the Icarus Wings (the Uppercut Combo is unlikely to let you follow up with these). Chains to: Any air move Effect on light or medium enemies: Stun Effect on heavy enemies: None Air Up-Down Slice TS or TT in air Kratos does two quick slashes, first upward and then downward. Quite serviceable, and the same speed as the Left-Right Slice for quick laser purposes. Chains to: Any air move Effect on light or medium enemies: Stun Effect on heavy enemies: None Air Divine Retribution L1 in air Kratos sends out a laser beam forward. Unlike other air ranged attacks, this one won't angle downwards, so it's only useful for airborne or tall enemies. Chains to: None Effect on light or medium enemies: Stun Effect on heavy enemies: None Divine Absolution L1+S Kratos does a slice to the left, then an 8-hit stabbing attack, finishing with a powerful stab with a flare of energy around it. None of the hits are affected by Anger of the Gods. A very lackluster special move, as you're better off just swinging your complicated Blade combos that allow you to block and still move forward a good deal. Chains to: None Effect on light or medium enemies: Stun Effect on heavy enemies: None Divine Retribution L1+T Kratos sends a laser beam straight forward. The sword can also hit on its way down to good effect. During the normal game where you get the Blade, this will be a key move, as it strikes from a distance without leaving you hideously vulnerable. Effect on light enemies: Scatter (blade), Stun (laser) Effect on medium enemies: Scatter (blade), None (laser) Effect on heavy enemies: None Divine Sacrifice L1+O Requires Blade of Olympus level 2 Kratos creates a globe of energy around him, draining red orbs from nearby enemies. It doesn't do any damage, but if you're in Bonus Play and want to grab extra orbs without turning on the Urn of the Fates, feel free to loiter around weak enemies with this for free money. It also comes in very handy during the Reap the Rewards part of Challenge of the Titans. Chains to: None Effect on light or medium enemies: Knockdown Effect on heavy enemies: None Anger of the Gods Requires Blade of Olympus level 3 All your attacks, except Divine Absolution, Uppercut Combo and the final hit of the Up-Down Slice, will have an additional laser beam attack, just like the Divine Retribution. This makes the Blade the ultimate weapon, able to deliver damage from afar and essentially double damage up close. Effect on light enemies: Stun Effect on medium or heavy enemies: None ======== 2. MAGIC ======== Unlike the weapons, you'll need all the different magic spells in your way through the game, and upgrading more than one of them is worthwhile even on Titan Mode. As a general rule, you'll need ------------------ 2.1. TYPHON'S BANE ------------------ Upgrade cost: 2500, 12500 Typhon's Bane is a fairly standard long-ranged bow attack. Hold L2 to pull out the bow, then press the various buttons to do your different attacks. While you can move using Typhon's Bane, it's quite slow, so only use it to dodge things you know you can avoid, like Theseus' fast ice blasts. To change targets, tap the right analog stick; you should rarely need to do this, since it'll autotarget on the strongest enemy, and why waste arrows on lesser ones? You can fire bow shots in the air; to fire a special bow attack in the air, tap T or O, then keep holding L2 until you reach the ground, at which point you'll do your attack. Typhon's Bane is useful mainly in the early game, when you can unload a full magic meter's worth of arrows into a boss or heavy enemy without leaving yourself open to an attack. At level 3, you can use the charged blast to rack up a big combo, but at that point it's a much slower way to kill enemies than a well-placed Cronos' Rage or Atlas Quake. On Titan Mode, even level 2 isn't worth it, because some enemies are too fast or too likely to guard the rapid-fire shots. Wind Blast Hold L2, tap S Kratos fires a single wind arrow at the selected target. Keep mashing S to fire arrows at a decent pace. These aren't very powerful and they don't get more powerful with upgrades, but get used to shooting them anyway, whether to uncover hidden grapple points, take down inaccessible bosses, or simply deal damage to a big enemy when you're low on health. Wind Blast (Air) Hold L2 in air, tap S While Kratos can fire bow shots in the air, he's not really harder to hit since he floats down slowly while shooting. You shouldn't really ever need this particular feature. Effect on light or medium enemies: Stun Effect on heavy enemies: None Rapid Fire Wind Blast Requires Typhon's Bane level 2 Typhon's Bane can now be fired extremely quickly. This will actually backfire against Theseus, as he will start blocking the shots instead of being surprised by them, but comes in very handy elsewhere in the game when you need to deal with enemies or bosses from afar. Lethal Vortex Hold L2, tap T Requires Typhon's Bane level 2 The Vortex is simply there to get you out of trouble when you're trying to shoot something and other enemies swarm you. The Vortex costs considerably more magic than an arrow shot and is chiefly valuable for its ability to launch enemies at a distance, buying you some precious seconds to resume shooting or pound them with your Blades. Largely a luxury At Typhon's Bane level 3, the Lethal Vortex gains damage; it now does 5x the damage of a regular arrow, making it just as cost-effective (or rather, cost-ineffective) as your arrows. Of course, by then you need it more, since you're using your charged Wind Blast instead. The Lethal Vortex costs 1/8 of a full magic meter - a high price to pay for something that just isn't as powerful as your charged blast at level 3, or simply shooting 8 arrows at level 2. Effect on light or medium enemies: Launch Effect on heavy enemies: None Wind Blast (Charged) Hold L2+S, release S Requires Typhon's Bane level 3 The charged shot (you have to hold S down for a little while after the animation finishes) releases six tracking projectiles, each of which circle back around 4 times. Each hit does only 1/6 the damage of a single arrow, and you're only guaranteed to get the first 6 shots on the original target before they split up to attack any other enemies they find, but it's overall more damage per shot than uncharged arrows. Because they tend to flail around ineffectively and spread their damage across the entire screen's worth of enemies, you should wait until there are only 1-2 enemies left, then start releasing charged blasts at them. (Since they track, no amount of dodging will save a Satyr or Cerberus from taking this damage, unless they hit you out of the charging animation.) Each charged Wind Blast takes 1/8 of a full magic meter. Effect on light or medium enemies: Stun Effect on heavy enemies: None Titan Storm Hold L2, tap O Requires Typhon's Bane level 3 Kratos does an invincible windup animation, then releases an enormous tornado (think Prometheus' Inferno) at the target. It only does one hit and you have to wait until the tornado has totally disappeared before firing another, so it's basically a desperation attack to do 15 times the damage of a single arrow on an enemy and anyone anywhere near him. The problem is, 15 times the damage of an arrow shot isn't enough to really kill anyone on higher difficulty levels, so it's just a panic button when you're swarmed with enemies and need to fire your bow at an important target. Each Titan Storm takes 1/4 of a full magic meter. Effect on light or medium enemies: Scatter Effect on heavy enemies: None ----------------- 2.2. CRONOS' RAGE ----------------- Upgrade cost: 3350, 15000 Cronos' Rage is a lightning attack that hits several enemies at once, gaining power, range, and the ability to target more enemies as you upgrade it further. Although it's expensive to upgrade, it's worth it by the end of the game because of its ability to tie up enemies with lightning bolts while you combo them yourself or move elsewhere to accomplish your objective. Laying a Cronos' Rage and continuing to turn a crank or move an object is a very effective strategy. Plus, you can use it effectively on pretty much every boss from the time you get it except for Perseus and Zeus (who tend to block or dodge it too often). Get used to learning when and where to release Cronos' Rage balls. Cronos' Rage L2 or L2 in air At Cronos' Rage level 2, gains range and power At Cronos' Rage level 3, gains range and power and adds a scattering hit at the end ("core explodes") Kratos places a ball of lightning at his position, with up to 3 available at once. (This means there's only a slight delay between placing more than 3.) The ball will continuously stun multiple opponents and is especially useful at higher levels for building your combo count and keeping enemies occupied while you take on the ones that need the most attention. It's quite cheap in magic cost as well - even a level 3 Cronos' Rage Core costs 1/12 of a full magic meter. You'll want this at level 3 by the end of the game, because it comes in extremely handy against bosses and Titan Minotaurs. -------------------- 2.3. HEAD OF EURYALE -------------------- Upgrade cost: 4000, 8000 Like Medusa's Gaze from God of War 1, this weapon allows you to turn your enemies to stone, then shatter them for a considerable orb bonus and instant death. This time, however, it's virtually useless at level 1 and keeps getting better as you upgrade it, until at level 3 it can reasonably freeze several entire waves of enemies without putting you at unnecessary risk. On lower difficulties, you'll never really need this power, but as the enemies' health goes up, the ability to kill them instantly gets much better. Bosses and the Titan Minotaur can't be turned to stone. Gorgon Stare Hold L2+S At Head of Euryale level 2 and 3: gains power (freezes things faster) The default Gorgon Stare will continually drain your magic to attempt to freeze the target and anyone else standing in that cone. More robust targets take longer to freeze, but at level 1, even the weakest of soldiers takes a couple seconds to turn to stone. Remember how easy it was to avoid the basic Gorgons in Typhon's Cavern? That's about how good you are with the Stare at level 1. At higher levels, a judicious use of the Gorgon Stare lets you turn single enemies to stone relatively quickly, but it's still only cost-effective if you're targeting multiple enemies. Stick to your fancier powers instead - except against harpies and nymphs, who can be frozen and will immediately shatter for a big orb bonus. Gorgon Stare (Air) Hold L2+S in air While you can use the Gorgon Stare in the air, there's never a reason to do this, ever. Now Gorgon Flash or Blast in the air, that I can see. You'll just land and remain vulnerable before you've stoned anyone with the Gorgon Stare. Gorgon Flash Hold L2 and tap T Requires Head of Euryale level 2 The Gorgon Flash will freeze an enemy instantly at the cost of 1/8 of a full magic meter. Because it costs more than Cronos' Rage, it's only worthwhile against enemies with so much health that a Cronos' Rage and accompanying combo wouldn't kill them. Fortunately, all heavy enemies fit this bill. Remember, don't use the Flash until you know you'll have an opening to actually break the enemy - if they struggle free, you're back to square one. I think it's more effective at level 3, but I'm not sure. Also note that if you Gorgon Flash an airborne enemy, they're dead instantly, and you get a nice orb bonus. Gorgon Flash (Air) Hold L2 and tap T in air Requires Head of Euryale level 2 In air, you can Gorgon Flash just as well as you can on the ground. This comes in handy after, say, you've finished launching and killing an opponent and want to retaliate against that one satyr waiting for you below - but since the Flash is almost instantaneous, don't feel like you have to jump for your Gorgon Flash to be safe. Gorgon Blast Hold L2 and tap O; can also be used in air Requires Head of Euryale level 3 The Gorgon Queen and Euryale herself will fire Gorgon Blasts at you. This is an area-of-effect stone gaze that costs as much as a Gorgon Flash and instead of turning an enemy to stone, has a chance of turning everyone in the area to stone. This is a really bad idea for an attack, because for the cost of a Gorgon Blast, you could turn a couple light enemies of your choice to stone with the Gaze, or make sure to turn your biggest threat to stone with the Flash. To ensure that everyone there is stunned, you'll need two Gorgon Blasts, which is just as expensive and unsafe as the Gorgon Rage but much less effective. In the air, it will hit grounded opponents beneath you, but this is generally overthinking the problem and you should just block as you come down instead. Gorgon Rage Hold L2+O, then release O Requires Head of Euryale level 3 Your most expensive magic attack - it takes 1/4 of a full magic bar - is also your most brutally effective. Charge up Euryale's head until her tentacles start wiggling, then release to turn everyone around you into stone. Since you've been charging up, virtually the entire room will be close enough to be hit by the Gorgon Rage, meaning you can demolish all the enemies on lower difficulty levels or pick an enemy to shatter without risk on higher difficulty levels. If you ever manage to shatter two medium or heavy enemies (not hard, even on Titan Mode), the Gorgon Rage has paid for itself in terms of Euryale's Head's other powers. If you break a soldier or two along the way, well, that's what you paid 12000 orbs to fully upgrade Euryale's Head for. ---------------- 2.4. ATLAS QUAKE ---------------- Upgrade cost: 4500, 10000 You won't get this magic until late in the game, but it's very effective right up until the final battle due to its ability to randomly do insane amounts of damage with Destructive Earth, and the fact that you're totally invincible while performing the Atlas Quake. It's definitely worth upgrading. Trembling Earth L2 or L2 in air At Atlas Quake level 2, adds extra rock hits for more damage Your basic quake attack does 2 hits to everyone on the floor at the time. At level 2, rocks fly out of the ground in random directions that may do extra damage. It's a "get out of jail free" card to give you temporary invincibility, like Poseidon's Rage in the previous game, that also happens to do damage to and stun even the most ironclad of enemies. It's slightly more expensive than a Charged Wind Blast, Gorgon Flash or Lethal Vortex - you can only use it 7 times with a full magic meter, I think. Effect on light or medium enemies: Knockdown Effect on heavy enemies: Stun Destructive Earth L2 or L2 in air, then mash O Requires Atlas Quake level 3 This is where the real power lies. You'll release huge rocks for several seconds in between the two Trembling Earth hits. The closer you are to the enemy, the more likely it is that it'll get hit by the rocks. Because you don't have to aim it, it remains useful against teleporting enemies - just don't try it if they're flying, because the chance of a rock hitting them is very, very low. Best of all, it doesn't cost any more than the regular Atlas Quake - so if you need to use all your magic on something (like a boss or the interminable ramp battle before Klotho), this is the most damage you can do. -------------------- 2.5. POSEIDON'S RAGE -------------------- POSEIDON'S RAGE L2 or L2 in air (replaces Cronos' Rage) Upgrade cost: n/a Requires Urn of Poseidon to be turned on This urn replaces Cronos' Rage with Poseidon's Rage, the magic you had when fighting the Colossus. Like Cronos' Rage, it's a lightning attack capable of hitting several enemies at once - but it has no maximum number of enemies, it has a much wider area, and it causes Kratos to become invincible and spin around in the air instead of allowing him to continue attacking. When you give yourself this magic, you'll realize just how cheesy it was in God of War 1, as it utterly demolishes your opponents while leaving you invincible. Its only downside is that it doesn't stun heavy enemies like the Atlas Quake - but it does damage on par with the Quake anyway, and you can hit flying enemies too. Each use of Poseidon's Rage costs 1/8 of a full magic meter - so slightly more than Cronos' Rage. It's a small price to pay. ========== 3. ENEMIES ========== Enemies are described like this: ENEMY NAME Class (Weight class: Light, Medium or Heavy) Description (Physical description of the enemy) First appearance Offense (Each attack has its own line) UB = Unblockable UP = Unparryable GB = Guard Break Projectile = Uses Argo's Reflect when parried Defense (Available types: Guard, Dodge, Teleport, None) Grabs (When you can grab this enemy and what the grabs do) Comments (How to fight this enemy effectively) ------------------ 3.1. LIGHT ENEMIES ------------------ LIGHT Dogs: Wild Boar / Rabid Hound / Cerberus Seed Harpies: Harpy / Hades Harpy / Cursed Harpy Nymphs: Nymph / Hades Nymph Archers: Rhodes Archer / Undead Archer / Cursed Archer Cursed Remains Beast Lord Soldiers: Rhodes Soldier / Undead Legionnaire / Cursed Legionnaire / Fates Sentry / Fates Guardian Wraiths: Wraith of Athens / Wraith of Asphodel Hades Fiend MEDIUM Legionnaire Captain / Hades Legionnaire Satyr / Satyr Champion Siren / Siren Widow (Temple of Lahkesis) Gorgon (Typhon's Cavern) / Gorgon Assassin (Temple of Euryale) / Gorgon Queen Minotaur Grunt (Typhon's Cavern?) / Hades Minotaur (Temple of Euryale) / Erebus Minotaur (Typhon's Cavern) High Priest of the Fates HEAVY Fates Juggernaut / Hades Juggernaut Cyclops Brute / Cyclops Tyrant (Destiny's Atrium 1) / Cyclops Berserker (Bog of the Forgotten) Cerberus (Temple of Lahkesis) / Cerberus Breeder Titan Minotaur (Bog of the Forgotten) BOSSES Colossus of Rhodes Theseus Barbarian King Hairy Cerberus Euryale Perseus The Last Spartan Kraken Lahkesis & Atropos Klotho Zeus WILD BOAR Class: Dog (Light) Description: Large brown boar with tusks and spines. First appearance: Destiny's Atrium (1st time) Offense: Tusk attack (1 hit) Defense: None Grabs: Air: Stabs and throws down (2 hits, repeatable) Ground: (Always Finisher) Finisher: Slices in half (3 hits) - 1 Rage orb Comments: The dog version of a Rhodes soldier, with extremely low health and an instant-kill grab. Never a problem, even if you let their cyclops friends grab them and throw them at you. RABID HOUND Class: Dog (Light) Description: Small silver dog that makes whimpering sounds when hit. First appearance: Temple of Lahkesis Offense: Bite attack (1 hit) Defense: None Grabs: Air: Throws down (1 hit, repeatable) Ground: Kicks at target (2 hits, causes Stun) Finisher: Breaks neck (2 hits) Comments: Grab these to make effective use of them by using them to damage other opponents as well as themselves. CERBERUS SEED Class: Dog (Light) Description: Small greenish wolf with a long tail. First appearance: Offense: Bite attack (1 hit) Rolling flame attack (1 hit) Defense: None Grabs: Air: Throws down (1 hit, repeatable) Ground: Throws down (1 hit, repeatable, causes Stun) Finisher: Breaks back (1 hit) Comments: If left alone for too long, these will transform into Cerberus Breeders, so don't let them live. They have significantly more health than Hounds, but are still vulnerable to repeated throws into each other, or a throw and a few Orion's Harpoons. Their flame attack is telegraphed by igniting themselves. HARPY Class: Harpy (Light) Description: Batlike creature with brown wings. First appearance: Typhon's Cavern Offense: Glowing red claw attack Minigame grab - UB,UP (shake to counterattack) Defense: Flying; grounded on Scatter/Knockdown Grabs: Air: Slams downward (1 hit, repeatable) Ground: (Always Finisher) Finisher: Rips off wings (2 hits) Comments: Basic harpies are only a problem on Titan Mode, and even then they can come in handy if you grab them to avoid damage. Use air attacks to kill them, and never just sit there blocking, because their grab hurts. HADES HARPY Class: Harpy (Light) Description: A flaming version of the regular harpy. First appearance: Atlas Offense: Ram attack Flaming divebomb (avoid red circle on floor to escape) Defense: Flying; grounded on Scatter/Knockdown Grabs: Air: Slams downward (1 hit, repeatable) Ground: (Always Finisher) Finisher: Rips off wings (2 hits) Comments: Hades harpies have more health than regular harpies, and their unblockable divebomb attack is easy to roll away from - once you see the circle, roll twice and they'll miss you. Simply watch the floor around them. CURSED HARPY Class: Harpy (Light) Description: A dark gray version of the regular harpy. First appearance: Offense: Glowing red claw attack Diving minigame grab - UB,UP (shake to counterattack) Flaming divebomb (avoid red circle on floor to escape) Defense: Flying; grounded on Scatter/Knockdown Grabs: Air: Slams downward (1 hit, repeatable) Ground: (Always Finisher) Finisher: Rips off wings (2 hits) Comments: Cursed harpies still have very low health, but they'll do their grab much more often than regular harpies. If you're watching them, you can tell they're going to swoop in for a grab by the somersault they make beforehand, but really just try to keep moving to avoid them. NYMPH Class: Harpy (Light) Description: Small purple flying creatures with 4 wings. First appearance: Destiny's Atrium Offense: Green projectile attack Jet of webbing - UB,UP (shake to escape) Defense: Flying; grounded on Scatter/Knockdown Grabs: Air: Slams downward (1 hit, repeatable) Ground: (Always Finisher) Finisher: Rips off wings (2 hits) Comments: Nymphs aren't dangerous alone, but their webbing attack (which they use only when you aren't moving around quickly) makes you vulnerable to other enemies' attacks. They'll often appear in packs, or with nests spawning them. HADES NYMPH Class: Harpy (Light) Description: Small orange flying creatures with 4 wings. First appearance: Temple of Lahkesis Offense: Flaming projectile attack - UB Death explosion - UB,UP Defense: Flying; grounded on Scatter/Knockdown Grabs: Air: Slams downward (1 hit, repeatable) Ground: (Always Finisher) Finisher: Ignites and throws at target (1 hit, causes Stun) Comments: These are the flying enemies to watch out for, as the timing to Fleece their attacks is very difficult. Instead, grab and throw them at each other if possible, like flying Rabid Hounds, and make sure to attack the ones that are igniting to throw their projectiles. CURSED REMAINS Class: Soldier (Light) Description: Skeletons with swords. First appearance: Temple of Euryale Offense: Spinning attack (2 hits) Defense: None Grabs: Air: Breaks against ground (1 hit, causes "death") Ground: n/a Finisher: Dismembers (2 hits) Comments: Skeletons will break into a pile of bones when they "die", then regenerate and immediately attack. To kill them, either grab them when the Finisher prompt appears, or destroy them with a high-damage attack. These guys are mostly there as puzzles rather than as legitimate enemies, as you have to be careful to get rid of them with grabs instead of just randomly hacking away. RHODES ARCHER Class: Archer (Light) Description: Human with silver recurve bow and golden armor First appearance: Rhodes Battlements Offense: Red arrow projectile (1 hit) Defense: None Grabs: Air: Throws down (1 hit, instant kill) Ground: (Always Finisher) Finisher: Triple stab (3 hits) Comments: The first archers you meet are just as big a pushover as Rhodes Soldiers. Block their arrows, then move in to kill them any way you like. UNDEAD ARCHER Class: Archer (Light) Description: Undead with gray body and partial copper armor First appearance: Temple of Lahkesis Offense: Red arrow projectile (1 hit) Bow swipe, then arrow (2 hits) Defense: None Grabs: Air: Impales, extends and punches (1 hit, instant kill) Ground: (Always Finisher) Finisher, press S: Throws at target (2 hits) Finisher, press T: Rips in half (1 hit) Finisher, press O: Punch, then triple stab (3-4 hits) Comments: The basic archers from the first game are back, and just as easy to kill. Head for these guys first, as you can throw them into each other with the O,S grab and kill lots of them at once, even on Titan Mode. They won't take you long to kill, and you don't want them interrupting your attacks. Note that in this game, it IS possible to block the arrow after their bow swipe. CURSED ARCHER Class: Archer (Light) Description: Undead with partial silver armor and red plumed helmet First appearance: Euryale's Defeat Offense: Exploding arrow - GB (1 hit) Bow swipe, then arrow (2 hits, 2nd hit does not GB) Defense: None Grabs: Air: Impales, extends and punches (1 hit, instant kill) Ground: (Always Finisher) Finisher, press S: Throws at target (2 hits, causes Scatter) Finisher, press T: Rips in half (1 hit) Finisher, press O: Punch, then triple stab (3-4 hits) Comments: Cursed archers are easily identifiable by their exploding arrows, which will stick in the ground if they miss or are blocked and still explode. They aren't here in huge droves like the previous game, and they give magic orbs when they die, so they're an even bigger target. Grab them or fight back with your own magic arrows to kill them before their arrows stun you. RHODES SOLDIER Class: Soldier (Light) Description: Human with golden shield and armor First appearance: City of Rhodes Offense: Shield and sword strike (2 hits) Defense: Occasional blocking Grabs: Air: Throws down (1 hit, instant kill) Ground: (Always Finisher) Finisher 1: Throws over shoulder (1 hit) Finisher 2: Triple stab (3 hits) Comments: The game's first enemy is also possibly its easiest, except for wild boars. Plow through these guys as fast as possible; on Bonus Play, grab them for extra orbs and invincibility during the first Colossus fight. Each of the finishers has a 50% chance of occurring. BEAST LORD Class: Soldier (Light) Description: Tiny pig with full armor First appearance: Bog of the Forgotten, by Euryale's Key Offense: Blue triple blade strike (2 hits GB + 1 hit) Blue blade spin (1 hit + 4 hits + 1 hit) Defense: Grabs: Air: Impale, extend and punch (1 hit, repeatable) Ground: Stomp (2 hits, repeatable) Finisher: Kill with own blades (4 hits) Comments: It's very fortunate that these guys can be killed with grabs at no risk to you, because they are almost always your first priority. They're relatively weak but still pose threats to you with a guard-breaking attack and their potential to become dangerous combined with a Cyclops Berserker. UNDEAD LEGIONNAIRE Class: Soldier (Light) Description: Undead with gray body and single sword First appearance: Offense: Slow double sword strike (2 hits) Grab - UB,UP (1 hit, shake to escape and counter) Defense: None Grabs: Air: Impales, extends and punches (1 hit, repeatable) Ground: (Always Finisher) Finisher, press S: Throws at target (2 hits, causes Scatter) Finisher, press T: Rips in half (1 hit) Finisher, press O: Punch, then triple stab (3-6 hits) Comments: The basic soldiers from the first game are mostly there for nostalgia value, as most of the time you'll be fighting the Fates' soldiers instead. These guys are very easy to kill, and their grab comes in handy for clearing space. CURSED LEGIONNAIRE Class: Soldier (Light) Description: Undead with gold armor First appearance: Offense: Blue overhead strike (1 hit) Spinning counterattack (1 hit) Grab - UB,UP (1 hit, shake to escape and counter) Defense: Guard Grabs: Air: Impales, extends and punches (1 hit, repeatable) Ground: n/a Finisher, press S: Throws at target (2 hits, causes Scatter) Finisher, press T: Rips in half (1 hit) Finisher, press O: Punch (1 rage orb), then triple stab (3-4 hits) Comments: Become intimately familiar with these guys' blue flashes before their most common attack, because if you can use the Fleece on them, they become significantly easier. These are the weakest enemies you face (besides Cursed Remains) that can't immediately be thrown, but when you can, take advantage of their excellent O,S finisher to give yourself space to destroy them. Although they can guard, they usually will only guard at the end of long combos. WRAITH OF ATHENS Class: Wraith (Light) Description: Undead with blades for hands and no legs First appearance: Temple of Lahkesis (before Destiny's Atrium) Offense: Blade spin Melee attack (3 slow hits) Underground attack - (3-4 hits + 1 hit) Defense: Guard; invulnerable while doing underground attack Grabs: Air: Knee break (2 hits, always goes underground after) Ground: Launch (1 hit, hold X to jump with them) Finisher: Kill with own blades (3 hits) Comments: These guys are very scary until you learn how to deal with them - block whenever you see their underground attack coming, then grab the closest one and start pounding him. You can block immediately on recovery from the air throw, but it's not terribly useful except as a way to get down to the ground without taking damage from another wraith's underground attack. Beware of their normal melee attacks as well! WRAITH OF ASPHODEL Class: Wraith (Light) Description: Undead with blades for hands and blue leg shrouds First appearance: Euryale's Defeat Offense: Green boomerang hands (1-4 hits) Green grounded boomerang (1-4 hits) Underground attack - (3-4 hits + 1 hit) Fake underground and lunge (1 hit) Defense: Guard; invulnerable while doing underground attack Grabs: Air: Knee break (2 hits, always goes underground after) Ground: Launch (1 hit, hold X to jump with them) Finisher: Kill with own blades (3 hits) Comments: These wraiths will never use their real underground attack unless provoked by you air throwing them, so use the same strategy but be much more vigilant about random boomerangs catching you during your attacks. Although the boomerangs look like projectiles, they can't be caught by Argo's Return. Since they can block or interrupt you, use the Fleece and grabs often - you're very unlikely to get hit by a wraith while airborne killing another one. HADES FIEND Class: Archer (Light) Description: Soldier of ambiguous gender with flame in one hand First appearance: Bog of the Forgotten Offense: Flaming projectile - UB (1 hit) Flaming sword strike (1 hit) Defense: Guard Grabs: Air: Slam together to ground (2 hits, always goes underground after) Ground: Bounce off ground (2 hits, causes Knockdown) Finisher: Kill with own sword (3 hits) Comments: Basically, they're archers with an unblockable projectile who don't die so easily. Grab them to keep them from shooting you for a while, or just use your more powerful attacks on them to kill them quickly. Like all ranged enemies, take care of these first - they can ruin your day by leaving you open to melee enemies. FATES SENTRY Class: Soldier (Light) Description: Monster with gold helmet, one sword and one arm blade First appearance: Typhon's Cavern Offense: Arm blade, then red sword strike (2 hits) Defense: None Grabs: Air: Ground: (Always Finisher) Finisher, press S: Flings at target (2 hits) Finisher, press T: Breaks neck (2 hits) Finisher, press O: Slash, then kill with arm blade (2-8 hits) Comments: These guys are abundant throughout the game, but fortunately they can easily be grabbed and taken care of. Be careful: while you're slashing with the O,O finisher, you're NOT invincible. Their attacks are frequent but easy to defeat. FATES GUARDIAN Class: Soldier (Light) Description: Monster with red armor and a double-headed axe First appearance: Steeds of Time Offense: Double axe strike (2 hits) Defense: Guard Grabs: Air: Impale and swing downward (2 hits, repeatable) Ground: n/a Finisher, press S: Flings at target (2 hits) Finisher, press T: Breaks neck (2 hits) Finisher, press O: Slash, then kill with arm blade (2-8 hits) Comments: Although these guys only have one attack, they love to get in your face and keep up the pressure. They'll occasionally guard, but you should be able to get in some hits as long as you keep them stunned - even a Weak Combo will do the trick. Be careful when fighting them, as they're harder to defeat than your normal soldiers because you can't just grab one to get out of trouble. While starting their "finisher available" animation they are totally invincible. ------------------- 3.2. MEDIUM ENEMIES ------------------- LEGIONNAIRE CAPTAIN Class: Captain (Medium) Description: Tall armored warrior with sword and scythe First appearance: Euryale's Defeat: These enemies are much, much better versions of enemy soldiers. Their status as medium enemies means that it's very difficult to interrupt their long attack combos, they block an awful lot (or will simply attack right through your moves), and they can only be grabbed with a button-press minigame. Keep on the defensive against them and try to launch them or pound them from a distance if possible. If you try to grab them at the wrong moment, they'll counter-grab you, but they don't have any way to break through your guard otherwise. HADES LEGIONNAIRE Class: Captain (Medium) Description: Tall flaming warrior with sword and scythe First appearance: Atlas: Just like a Legionnaire Captain but with much more health, the Hades Legionnaire was entirely avoidable in God of War 1 but is a fact of life in this game. Be very careful, as it's easy for them to wear down your health when you're not watching them. The strategy is identical: stay defensive, use distance to set up bigger attacks, and grab them only when you have the chance. SATYR Class: Satyr (Medium) Description: Goat-like monster with blue eyes and a bladed staff First appearance: Crossing of the Lowlands Offense: Twirling staff combo (1 hit + 2 hits in an X + 5 hits twirl) Sitting-on-staff stance (5 hits twirl when attacked) Staff vault combo (2 hits with legs + 1 hit + 1 hit uppercut) Staff grab (1 hit, knocks you down) Getting up counterattack (1 hit with legs) Defense: Dodge Grabs: Air: Slow-motion ground slam (2 hits) Ground: Minigame mouth cut (2 hits, mash O to complete) Finisher: Stylish mouth cut and staff kill (3 hits, mash O to complete) Comments: To fight satyrs, you must figure out their attack patterns - when you can Fleece or simply block their attacks, when you can expect them to dodge, and when it's safe to launch them (hint: whenever they sit on their staff, they can easily be launched). Otherwise, they'll just destroy you with their dodge-and-counterattack pattern and the surprisingly good range of their attacks. Fortunately, they don't block (except while they're already dodging), so if you can catch them doing something that isn't interrupting you, unload as much damage on them as possible. Since they can't block, they'll always get scattered by Argo's Revenge, so use it as much as possible. Note that while you're attempting to grab them, you are NOT invincible, so don't try it unless you're alone with him, and probably not even then - it does very little damage. SATYR CHAMPION Class: Satyr (Medium) Description: Goat-like monster with two small blades First appearance: Euryale's Defeat Offense: Backflip combo (1 hit + 1 hit + 3 hits) Forward flip combo (1 hit + 3 hits twirl) Defense: Dodge Grabs: Air: Slow-motion ground slam (2 hits) Ground: Minigame mouth cut (2 hits, mash O to complete) Finisher: Stylish impale and return (4 hits, mash O to complete) Comments: See the comments above for regular satyrs (except that champions have more health and no stance for you to capitalize on, but also no painful staff grab). I personally find champions to be less threatening than regular satyrs because they're more predictable; both have extremely fast attacks, though, so watch your back. SIREN Class: Siren (Medium) Description: Brunette in a blue dress First appearance: Crossing of the Lowlands Offense: Small blue projectile (1 hit) Ground spike (1 hit) Defense: Dodge Grabs: Air: Twirl and slam (1 hit, repeatable) Ground: Repeated head slam (4 hits, only possible when O prompt appears) Finisher: Double impale and slam (4 hits) Comments: The sirens no longer have their "suck you in" scream attack from God of War 1, but their ground grab no longer gives you health, so they're still annoying to deal with. The ground spike is telegraphed by energy gathering around their midsection and a flare underneath where you're standing, and it can be blocked or parried as long as you're standing near it when it starts. They're more of a pain than a serious threat to your health bar - just don't randomly flail around with your blades and get shot by their projectiles, keep your cool and you should do fine. SIREN WIDOW Class: Siren (Medium) Description: Woman with white hair and long claws First appearance: Temple of Lahkesis Offense: Lunge and blue claw attack (1 hit) Blue claw combo (2 hits) Sonic scream - UB,UP (shake to escape) Defense: Dodge Grabs: Air: Twirl and slam (1 hit) Ground: n/a Finisher: Neck break (0 hits, damages all surrounding enemies) Comments: Siren Widows are easier to kill than normal sirens, thankfully, because they'll often rush up and attack you, putting themselves in range instead of dodging away. Unfortunately, their scream attack (which has no maximum duration, and good range) makes them quite a threat if you're also trying to avoid other enemies - and there's always more than one siren. Become adept at grabbing these when you have to - you'll need to use their sonic death blast for multiple purposes. GORGON Class: Gorgon (Medium) Description: Half woman, half snake, all green First appearance: Typhon's Cavern Offense: Gorgon Stare - UB (turns gradually to stone, shake to escape, minigame to parry) Claw Rush (1 hit) Tail Strike (1 hit) Defense: Dodge Grabs: Air: Slam downward (1 hit) Ground: n/a Finisher: Rip off head (4 hits, minigame to complete, gives magic) Comments: Gorgons come in all flavors in this game. These are the traditional ones that can only stone you if you stay in one place - roll around to avoid their gaze if you don't have the Golden Fleece to parry it. Be careful of their high speed and penchant for dodging, and NEVER let one turn you to stone while you're airborne, as you'll die instantly. Basic Gorgons aren't much of a problem if you keep moving - just hit them and be sure to block whenever you see a dodge, as they'll always counterattack. If you have the Fleece and want to bait them into stoning you, try to grab them. GORGON ASSASSIN Class: Gorgon (Medium) Description: Half woman, half snake, blue and white First appearance: Temple of Euryale Offense: Gorgon Flash - UB (turns to stone, shake to escape, minigame to parry) Claw Rush (1 hit) Tail Strike (1 hit) Defense: Dodge Grabs: Air: Slam downward (1 hit) Ground: n/a Finisher: Rip off head (4 hits, minigame to complete, gives magic) Comments: Gorgon Assassins are more common toward the middle levels of the game. You absolutely must use the Golden Fleece on them; fortunately, they telegraph all their attacks - the Stare lets you parry it very late in its animation, and the Assassin will wind up with a green charge on her mouth beforehand. Be careful of their high speed and penchant for dodging, and NEVER let one turn you to stone while you're airborne, as you'll die instantly. If you have the Fleece and want to bait them into stoning you, try to grab them, but be careful, as they shake out of turning into stone quite quickly. Gorgons love to counterattack, so be ready with your block button if you miss anything, but their dodging isn't as effective as satyrs' or sirens' dodges. GORGON QUEEN Class: Gorgon (Medium) Description: Half woman, half snake, brown and red First appearance: Offense: Gorgon Stare - UB (turns to stone gradually, shake to escape, minigame to parry) Gorgon Rage - UB (randomly turns to stone, shake to escape, minigame to parry) Claw Rush (2 hits) Tail Strike (1 hit) Defense: Dodge Grabs: Air: Slam downward (1 hit) Ground: n/a Finisher: Rip off head (4 hits, minigame to complete, gives magic) Comments: Gorgon Queens are reserved for the end of the game, because they are very scary targets. Their Stare lasts longer than the Gorgon's regular stare so you're more vulnerable while dodging it, they have area-effect Gorgon Rage attacks (which they'll always do if you grab them without the O prompt) that are difficult to parry and have a chance of turning you to stone, and they have so much resistance to Head of Euryale that they can only be broken by your subweapons. Not to mention they have an awful lot of health. A good strategy against them is to parry their stone attacks, then take out the other enemies before you deal with the Queen alone. MINOTAUR GRUNT Class: Minotaur (Medium) Description: Minotaur with exaggerated upper body and large axe First appearance: Offense: Overhead axe attack (mash O to counter) Glowing overhead axe attack (1 hit, knocks you down) Counterattack (1 hit, only after blocking) Defense: Guard Grabs: Air: Slam down (1 hit) Ground: n/a Finisher: Blades into mouth (3 hits, mash O to complete, gives health) Comments: Basic minotaurs aren't a big threat in this game, unless you get hit by their glowing axe strike, which can be avoided if you're attentive or simply blocked if you aren't. Just remember: when a minotaur blocks a few hits, he'll counterattack, which you can block or parry. Plus, half the time this grunt hits you, it'll be a minigame you can use to counterattack HIM (although he's invincible while regaining his axe). HADES MINOTAUR Class: Minotaur (Medium) Description: Fatter minotaur with flaming spiked club First appearance: Offense: Slow club combo (2 hits + 1 hit) Downwards stab and swipe (2 hits) Big club pound (1 hit, knocks you down) Defense: Guard Grabs: Air: Slam down (1 hit) Ground: n/a Finisher: Force onto club (3 hits, minigame to complete) Comments: This minotaur is common throughout the game and very useful because of his penchant to block rarely and the lengthy invincibility his finisher affords you. You can't dodge his attacks like the other minotaurs' attacks, but he's not super-powerful and you can still see all his moves coming. Remember: when this minotaur blocks a few hits, he'll counterattack (in this case, with the downwards stab and swipe), which you can block or parry. EREBUS MINOTAUR Class: Minotaur (Medium) Description: Minotaur with blue spikes on arms and back First appearance: Steeds of Time Offense: Double axe swipe (2 hits) Horn charge (1 hit) Overhead slam (1 hit, knocks you down) Defense: Guard Grabs: Air: Slam down (1 hit) Ground: n/a Finisher: Blades into mouth (3 hits, mash O to complete, gives health) Comments: Theseus summons these minotaurs against you, which are simply beefier versions of Minotaur Grunts. Their overhead slam is very difficult to evade unless you are watching closely, and after they block or you fail to grab them they'll counterattack with a horn charge and then an overhead slam; parry the slam to stun them and follow up with a combo. You don't really need to keep your distance from them, and they'll charge forward anyway, so just keep blocking and try to parry them so that you can catch one alone and launch it for massive damage. Sometimes you can block the 2nd hit of the double axe swipe if you were hit by the first one. HIGH PRIEST OF THE FATES Class: Priest (Medium) Description: Human with a blue toga and a big scroll First appearance: Euryale's Defeat Offense: Green scroll strike (2 hits) White energy grab - UB (drains magic + 1 hit, shake to counter) Green curse tornado (1 hit, reduces speed, not a projectile) Green energy trap (1 hit on ground, UB if not underneath you) Summon (generates an enemy) Defense: Teleport, Guard Grabs: Air: Punch and fling downward (2 hits, leaves you airborne) Ground: Minigame (mash O), Uppercut (4 hits, hold X to go up with him) Finisher: Minigame (mash O), Execution (5 hits) Comments: High Priests are fearsome. They have a wide variety of attacks, including an unblockable grab, they teleport often when you try to attack them, and their summon spell can cause you to lose an otherwise winning battle by adding a backbreaking new enemy. In the Arena of the Fates, the Priest always summons a Fates Guardian, but elsewhere in the game it can be anything from a Minotaur Grunt to a Cyclops Berserker. Their major weakness is grabs - but unfortunately, those require you to get close to a teleporting enemy. If you're not sure you're near him, he only rarely guards attacks, so your long- range Blades of Chaos should be able to at least make him teleport and get out of your hair for a while. Although you're invincible while grabbing him, remember that time doesn't stop, so this might not be a wise idea in the Protect the Translator battle. ------------------ 3.3. HEAVY ENEMIES ------------------ FATES JUGGERNAUT Class: Juggernaut (Heavy) Description: Bulky warrior with golden armor and a mace First appearance: Euryale's Defeat? Offense: Double mace swing (2 hits) Running shoulder and mace swing (2 hits) Defense: None Grabs: Air: n/a Ground: n/a Finisher: Decapitation (3 hits) Comments: Although Juggernauts are the least fearsome of your heavy opponents, their inability to be slowed down in any way still makes them very dangerous.. HADES JUGGERNAUT Class: Juggernaut (Heavy) Description: Bulky warrior with brown armor and a flaming morningstar First appearance: Just before Perseus Offense: Upwards swipe (1 hit) Long-ranged ground pound (1 hit) Ground pound followup (1 hit) Defense: None Grabs: Air: n/a Ground: n/a Finisher: Decapitation (3 hits) Comments: Hades Juggernauts are easier to deal with than the Fates Juggernauts on their own, because you can literally run circles around them, but their extra range, damage and armor makes them even more potent in groups - and you'll almost never be fighting them alone.. CYCLOPS BRUTE Class: Cyclops (Heavy) Description: Enormous green cyclops with a club First appearance: Offense: Club left/right swing - UB,UP (4 hits) Stomp and smash - UB,UP (1 hit + 1 hit knocks you down) Defense: None Grabs: Air: n/a Ground: n/a Finisher: Climb up and stab (4 hits) Comments: These guys are very dangerous because of their range. When the stomp hits, you have just enough time to roll out of the way of the smash. Always keep these guys in mind, as their big club swing is very difficult to avoid unless you're airborne at the time. Keep rolling around them to avoid their attacks and try to stun them with your Blades' plume attacks when possible. CYCLOPS TYRANT Class: Cyclops (Heavy) Description: Enormous gray cyclops with no weapon First appearance: Destiny's Atrium Offense: Grab and throw Wild Boar (1 hit, not a projectile) Stomp - UB,UP (1 hit) Ground pound - UB,UP (1 hit, knocks you down) Grab - UB,UP (1 hit, knocks you down) Defense: None Grabs: Air: n/a Ground: Orion's Harpoon the eye (2 hits, prompt will appear twice) Finisher: n/a Comments: Although the Cyclops Tyrant has an awful lot of health, this is mitigated by the ability to do intermediate grabs on them. Be careful about this - Kratos will do a harpoon animation, which is slower and less ranged than his regular grab animation, when trying to grab them. They don't have the same reach as the Brute, so you can pound them from afar, but be wary of their grab - if you see one reach his arm back, roll backwards immediately. The grabs release green orbs, so do them as quickly as possible. Stay away and you should be fine. CYCLOPS BERSERKER Class: Cyclops (Heavy) Description: Enormous gray cyclops with a tree trunk First appearance: Destiny's Atrium Offense: Stomp - UB,UP (1 hit) Ground punch - UB,UP (1 hit, scatters you) Defense: None Grabs: Air: n/a Ground: n/a Finisher: Rip out eye (6 hits, minigame to finish, +1 Cyclops Eye) Comments: Unfortunately, these guys rarely appear alone. When they do, they're just like Cyclops Tyrants without any way to attack you if you roll out of the way of their slow ground punches. Plus, their finisher gives you a Cyclops Eye, which is one less time you have to replay Challenge of the Titans #1 to get 20 Cyclops Eyes. It's like they've given you a minute of your life back for doing the finisher correctly. The real danger is when they get a Beast Lord to ride them - see below for details. CYCLOPS BERSERKER WITH BEAST LORD Class: Cyclops (Heavy) Description: Enormous gray cyclops with a tree trunk First appearance: Destiny's Atrium Offense: Club and ground punch combo - UB,UP (3 hits, rollable after 1st hit) Tree slam and grab - UB,UP (4 hits, knocks you down) Fiery tree spin - UB,UP (2 hits) Defense: None Grabs: Air: n/a Ground: Remove Beast Lord (2 hits) Finisher: n/a Comments: These guys are ALWAYS the first priority. Grab them immediately, or you will suffer the painful consequences. Afterwards, if you avoid the likely berserker counterattack, you can repeatedly grab the Beast Lord and kill it, then deal with the berserker at your leisure. Your only objective against these enemies is to grab them without getting hit by their attacks. Watch the Beast Lord - if its blades flash blue, it's about to do the club combo or the tree spin. If the Berserker moves its arms upwards without the Beast Lord's urging, it'll slam the tree down in front of it; walk or roll back and get in some free hits before you grab it. CERBERUS Class: Cerberus (Heavy) Description: Big three-headed gray dog with minotaur horns First appearance: Temple of Lahkesis Offense: Paw swipe (1 hit) Charging head attack (1 hit) Pounce and grab - UB,UP (6 hits, knocks you down, shake to escape) Triple fireball projectile - UB (3 hits, any can be parried) Defense: None Grabs: Air: n/a Ground: Rip off one head (prompt appears twice, 4 hits, mash O to finish, gives Rage orbs) Finisher: Impale middle head (3 hits, gives Rage orbs) Comments: The Cerberus' attacks can be blocked and parried, but in exchange it is very mobile and has a lot of health. Take down the heads to give yourself a visual indicator and get some free Rage orbs (since the Cerberus often stays in one place long enough to get hit by a Rage Weak Combo). The Cerberus is also invulnerable for a short period while it starts its "ready to be thrown" O prompt, so just go ahead and grab it. The best way to ensure it doesn't grab you is to keep moving yourself. CERBERUS BREEDER Class: Cerberus (Heavy) Description: Big three-headed green dog with flaming mouths First appearance: Offense: Paw swipes (2 hits) Summon Cerberus Seed Triple fireball projectile (3 hits, any can be parried) Defense: None Grabs: Air: n/a Ground: Slice middle head (1 hit, gives Rage orbs, prompt appears once) Finisher: Impale middle head (4 hits, gives Rage orbs) Comments: The Cerberus Breeder only has one intermediate grab, and if you don't watch the Cerberus Seeds it spits out, they'll transform into new Breeders. Generally a more dangerous version of the regular Cerberus, generally less prone to jump around but more likely to be throwing fireballs as a result. It can't pounce on you, but if it hits you while you're trying to kill those Seeds, that's just as good. TITAN MINOTAUR Class: Mini-Boss (Heavy) Description: Huge stone-and-lava creature that sleeps when you're far away First appearance: Bog of the Forgotten Offense: Throw rock - UB (1 hit, scatters you, not a projectile) Ground spin (5 hits) Ground pound (1-5 hits + zero-damage "return to resting" hit) Sink floor (3rd form only, 0 hits, gives magic orbs) Defense: None Grabs: Air: n/a Ground: n/a Finisher: Puncture lava core (4 hits, minigame to complete) Comments: You'll only fight this guy 3 times in the game and once in the Challenge of the Titans, and he can't even move the first two times. His attacks are predictable, but he's so resilient that defeating him can still be tricky. If you get far away, he'll always throw rocks at you - these are tough to dodge because of their big area of effect, so parry them but don't use Argo's Revenge, because it just wastes time and usually won't hit him. When he wakes up or when you're in front of him, he'll pound the ground to his front; move to his back for free hits while he's doing this. When you get too close, he'll turn his back to you and start spinning; roll away immediately to avoid it and hit him with a ranged attack (Plume of Prometheus, Altering Slash, Anger of the Gods). Repeat ad nauseam. If he tries to throw a rock and you're close, you can go right under the rock. ========== 4. PEGASUS ========== Although there are only two Pegasus levels in the game, they can be more difficult than they appear, especially on Titan Mode. There are also various nuances to getting a decent combo going and making sure you get the Brutal Kills for valuable orbs. All Pegasus attacks chain into each other or themselves. -------------------- 4.1. PEGASUS ATTACKS -------------------- Circular Blade Slashes SSS on Pegasus Kratos whirls his blade upward, downward, and to the sides, hitting everything anywhere around him much like his attacks on ceilings. This is rather weak, but is useful for getting below enemies where they can't hit you while you avoid their shots. Of course, this is only really an issue when you're fighting the Spear of Destiny, or if you want to kill harpies in Typhon's Cavern. Sideways Blade Spin T on Pegasus Kratos spins his blade to the left and right for a 5-hit combo. Much more powerful than the Circular Blade Slashes, and generally the fastest repeatable way to deal damage. Of course, other enemies have sideways attacks too, so be careful you don't take too much damage. You should also be careful not to KILL enemies with this move, because grabbing them gets you more orbs. Sideways Blade Grab O on Pegasus Kratos does a small left-and-right circle with a blade; if successful, he begins a minigame versus Gryphons or Gryphon Riders. It has no effect on the Ravens or Spear Rider. Especially on Titan Mode, where orbs are few and far between, you'll want to do this every chance you get. Side Dash Slam L1 or R1 on Pegasus L1 dodges Pegasus left; if you hit an enemy, Pegasus will rebound and do a lot of damage. R1 is the same, but dodges right. These are great tools for avoiding projectiles, finishing up attacks (T,R1,dodge,X is a great repeatable pattern against the Spear Rider) and generally keeping you mobile, which is the key when using Pegasus. Forward Dash Slam X on Pegasus Requires a small amount of magic Pegasus will rocket forward towards the enemy fliers, automatically tracking and hitting the closest one. This does good damage, and since your magic recharges on Pegasus, there's no reason not to use this whenever you're unable to use your regular attacks. It'll speed things up considerably, and Pegasus is much better at dodging projectiles when doing it, too. The Forward Dash Slam is the only way to kill the Raven. Wind Blast Hold L2 and press S on Pegasus You can use Typhon's Bane to fire back at enemy Gryphon Riders, but your maneuverability is limited and most enemies will simply swoop back towards you where you can't shoot them anymore. You're better off saving your magic for a Forward Dash Slam. -------------------- 4.2. PEGASUS ENEMIES -------------------- Gryphon The main enemy in the first Pegasus level, Gryphons can shoot wind projectiles at you from up ahead, or use their tail to attack you. However, their health is relatively low, so you can simply keep them occupied with a constant barrage of attacks while avoiding their projectiles. When you grab them, you'll need a minigame to kill them. Raven The final enemy in the first Pegasus level, the Raven will swoop at you from straight ahead. If you don't Forward Dash Slam him correctly (wait until you see his body appear, then hit X), he'll knock you into a tailspin (shake to escape) and do damage. This can be difficult to time, so watch out; if you connect, you'll have to do one minigame button press and then mash O to kill this bird. Spear Rider (Jet Stream) At the end of each Pegasus level, you'll be sucked up into the upper atmosphere with the head rider, wielding the Spear of Destiny. You have no magic or attacks for this fight and can only try to avoid his purple energy bolts. They're always in a pattern of 3, so you can dodge to one side if you see it coming; try to stay close to the center so you can move in any direction when the bolts come at you. At the end, he'll fire an unavoidable pattern of bolts; just get hit by it and do the minigame to finish the level. Gryphon Rider The second Pegasus level features Gryphons with more health and the ability to Side Dash Slam you. Stay offensive and use your own Side Dash Slam to gain a little distance so you don't accidentally get hit by them. Try to use your range to your advantage. When you grab them, you'll need a longer minigame to kill them. Spear Rider (Fight) The second Pegasus level, after another Raven, throws the Spear Rider himself at you; he's basically a copy of you, except that instead of his T attack he fires Piercing Shards from the Spear of Destiny left or right. Try to avoid these (watch for him bringing up his spear like a gun) to his top or bottom. He'll often race back forward; immediately counter with a Forward Dash Slam and resume the offensive. Don't let him start firing projectiles at you, as you can't afford to lose any health before the Jet Stream stage. ========== 5. CREDITS ========== This FAQ is copyright (c) 2007, Robert Marney (aka Robyrt). All rights reserved. Use of this file or any portion thereof is permitted for personal use only; do not republish or duplicate without explicit permission of the author. Unlike my other FAQs, this one was written solely by me, without even consulting the official strategy guide or competing FAQs. This is why there aren't official HP numbers yet - wait for a later release. | http://www.gamefaqs.com/console/ps2/file/932295/47625 | crawl-002 | refinedweb | 16,986 | 59.47 |
Scientists often encounter extraordinarily large data sets. This happens for a very good reason: more data provides a more thorough understanding of the phenomenon they’re studying. But it also creates a problem. As data sets get larger they become harder to understand and use.
One solution is learning how to automatically split your data sets into separate files so each data file becomes a manageable amount of information to explain a single of the phenomenon. The data becomes much easier to work with and, by splitting your data sets automatically, you make your work much easier with very little effort.
What Should I Expect?
In this portion of the tutorial we’ll cover the process of splitting a data set containing results from multiple laboratory tests into individual files. Those files will each contain the results of a single test and will have descriptive file names stating what data is contained within them.
Let’s focus on a real life problem often encountered in science and engineering. To understand the foundational concepts, make sure to check out part one of this series. If you want to go even deeper and leave the tutorial with confidence in your skills and new tools, you can download the companion data set, which will allow you to test your code and check your results to ensure you’re learning this process correctly.
Steps to Split Your Data Set
- Import Python packages.
- Identify the end of each test.
- Save each test as a new file.
- Run the script to confirm each new file holds the relevant data.
Let’s get started. First, import the Python packages that will enable the data analysis process.
How Do I Import Packages in Python?
Each Python script needs to start with statements importing the required packages and capabilities. In this data file splitting script we’ll need:
Pandas: This package is the premier option for data analysis in Python. Pandas will allow you to read your data into DataFrames (essentially tables) and provides a vast array of tools for manipulating that data.
os: This Python package enables you to use commands from the computer’s operating system, which impact the computer outside of the data analysis process. In this case we’ll use it to create new folders.
Bokeh: Bokeh is an interactive plotting tool in Python. It enables you to write code that automatically generates plots while analyzing your data and gives options for the user to interact with them.
For our purposes, we’ll pull in the entirety of both Pandas and os, but only specific functions from Bokeh. To do that, add the following code to the start of your program.
import pandas as pd import os from bokeh.plotting import figure, save, gridplot, output_file, ColumnDataSource from bokeh.models import HoverTool
You can see those four lines importing the stated packages. Note the line to import Pandas also specifies we’ve imported Pandas as pd, meaning we can refer to Pandas as “pd” in the rest of the code. Also note that ColumnDataSource is on the code line that starts with from bokeh.plotting.
Now that we’ve imported our packages, the next step is to read the necessary data so the script can work with it.
How Do I Read the Data Files?
Pandas has a fantastic tool for importing data sets: the read_csv function. In order to read a file, you call the pandas.read_csv function, specify the location of the file and set it to a variable. (There are several other modifiers you can use to customize the import if desired, but we won’t be using them here.)
We’ll use this command to import two files. The first file is the data set itself. If you downloaded the companion data set, it’s titled COP_HPWH_f_Tamb&Tavg.csv.
If we imagine that you saved the file in the folder C:\Users\YourName\Documents\AutomatedDataAnalysis, then we can import the data with the following code. (You’ll need to change “YourName” to your user profile name.)
Data = pd.read_csv(r’C:\Users\YourName\Documents\AutomatedDataAnalysis\COP_HPWH_f_Tamb&Tavg.csv’)
Executing that code will save the data set to the variable “Data.” This means you can use all the Pandas data analysis capabilities on the data set by referencing Data.
The second file we’ll need is a table describing the tests contained in the file. For the sake of practice, it’s helpful if you create the table yourself.
The data set contains the results from three tests, with different ambient temperatures (the temperature of air around the tested device). To create this data set, generate a table with the following information and save it as “Test_Plan.csv” in the same folder as your data set.
Later you’ll reference the names of the columns, so it’s important to make sure you use the same text as in the example data.
Now that you’ve created and saved the table, you can read it into Python by writing:
Test_Plan = pd.read_csv(r’C:\Users\YourName\Documents\AutomatedDataAnalysis\Test_Plan.csv’)
Next you’ll identify the rows where each test ends and the next test begins.
How Do I Identify Where Each Test Ends?
First things first: you’ll need some knowledge about the tests themselves. Think about the project’s test procedure and identify a condition that would indicate that one test is ending.
In this case we’re analyzing data from tests studying heat pump water heaters (HPWH), which use electricity to heat water. Since we’re looking at how much electricity the HPWH consumes to heat the water, we can know it’s consuming electricity during each test. This means that each test ends when the device stops using electricity.
We need to identify rows where the device stops using electricity, which we can do by subtracting the electricity consumption in each row from the electricity consumption in the previous row. If the result is negative, that means the HPWH is consuming less electricity than it previously had, which indicates the test ended.
We accomplish this by using the .shift() function on our data set. This function does what it sounds like; it shifts the data by a specified number of rows. We can use .shift() to create a new row in the data frame that contains electricity consumption, P_Elec (W), data that has been shifted by one row. We can do this with the following line of code:
Data[‘P_Elec_Shift (W)’] = Data[‘P_Elec (W)’].shift(periods = -1)
This leads to two different columns in the data frame describing the HPWHs electricity consumption. P_Elec (W) states the electricity consumption, in Watts, in each row. P_Elec_Shift (W) states the electricity consumption, in Watts, of the next row. If we subtract P_Elec (W) from P_Elec_Shift (W), rows with negative values will indicate the HPWH has stopped heating. Let’s use the following code:
Data[‘P_Elec_Shift (W)’] = Data[‘P_Elec_Shift (W)’] — Data[‘P_Elec (W)’]
At this point we have a data frame with a row that contains zero in every row except rows where each test ended. We can use that information to create a list that tells us when each test ended. We’ll call that list End_Of_Tests, to clearly signify the information contained within it. We’ll then use the .index.tolist() function to populate that list. We can do this with the following code:
End_Of_Tests = [] End_Of_Tests = End_Of_Tests + Data[Data[‘P_Elec_Shift (W)’] < 0].index.tolist()
The first line creates the empty list End_Of_Tests. While it originally holds no data, it’s ready to accept data from other commands. The second line adds data to End_Of_Tests. It says to look through Data to identify rows where P_Elec_Shift (W) is negative, identify the index of those rows, and add them to the End_Of_Tests list.
Now that we’ve identified the rows that correspond to the end of each test we can split the data set into separate data sets, one for each test.
How Do I Split the Data File?
We can split the data file into more manageable files using the following steps:
- Repeat the process once for each test. This means we need to iterate through it once for each entry in End_Of_Tests.
- Create a new data frame that is a subset of the original data frame containing only data from a single test.
- Use the conditions of the test to identify the test in the test plan that this data represents.
- Save the data to a new file with a file name that states what data is contained in the file.
1. IteratE through End_Of_Tests
We accomplish this first step with a simple for loop that iterates through the End_Of_Tests list. You can do this with the following code:
for i in range(len(End_Of_Tests)):
This creates a loop that runs x times, where x is the number of rows in End_Of_Tests/the number of tests contained in the file. Note that i will be an increasing integer (0, 1, 2, and so on) and can be used as an index. Also note that we now have an active for loop, so all future code will need to be indented until we leave the for loop.
2. CreatE New Data Frames With Subsets of the Data
We do this by using the values of End_Of_Tests to identify the rows of Data corresponding to each test. In the first test, this means we need to select the data between the first row and the first value in End_Of_Tests. In the second test, this means we need to select the data between the first value in End_Of_Tests and the second value in End_Of_Tests. (We’d do the same for the third and so on if we have more than three tests in this data set.)
The difference in handling between the first test (which starts at hard-coded row zero) and the future tests (which start at an entry in End_Of_Tests) requires an if statement that changes the code based on whether or not we’re pulling out the first test.
The code then needs to use the End_Of_Test values to identify the section of Data that we want, and save it to a new data frame.
We do this with the following code:
if i == 0: File_SingleTest = Data[0:End_Of_Tests[i]] else: File_SingleTest = Data[End_Of_Tests[i-1]:End_Of_Tests[i]]
The first line checks to see if this code is being executed for the first time. If it is, that means it’s the first time through the loop and we’re extracting the first test. If this is the code’s first time through the loop, the code pulls the first row of Data (Index 0) through the first entry in End_Of_Tests (Denoted with End_Of_Tests[i], which is currently End_Of_Tests[0]) and stores it in a new data frame called File_SingleTest.
If this isn’t the first time through the code, that means we need to extract data from a test that’s not the first. In that case we extract data from when the previous test ended (End_Of_Tests[i-1]) to when the current test ends (End_Of_Tests[i]) and save it to File_SingleTest.
Note that the data is always saved to File_SingleTest. This means that the data frame containing data from a single test will always be overwritten in the next iteration. It’s important to save the data before that happens!
3. Identify the Conditions of Each Test
Now we have a data frame containing the data of a specific test, but which test is it? We need to read the data to understand what happens in that test and compare it to the specifications in the test plan. In that way we can identify which test is in the data frame and give the data frame a descriptive name.
Looking at the test plan, we see the ambient temperature changes in each test. Test number one has an ambient temperature of 55 degrees Fahrenheit, test two has 70 degrees Fahrenheit, and test three has 95 degrees Fahrenheit. This means that ambient temperature is our descriptor here.
We can identify the ambient temperature during a test with the following code:
Temperature_Ambient = File_SingleTest[‘T_Amb (deg F)’][-50:].mean()
This line reads the last 50 entries ([-50:]) of the column representing ambient temperature (‘T_Amb (deg F)’) in the File_SingleTest data frame and calculates the average (.mean()). The code then stores that value in Temperature_Ambient. This means we have the ambient temperature for the last few minutes of the test stored in a variable.
The second step is to compare this value to the test plan and identify which test the code performed. This is important because no test data will ever be perfect and the average ambient temperature will not perfectly match the specification in the test plan.
For example, a test with a 55 degree ambient temperature specified may actually have a 53.95 degree ambient temperature. Identifying the corresponding test makes file management easier.
We can identify the corresponding test by both calculating the difference between the average temperature in the test and the ambient temperature called for in each test, and identifying the test with the minimum difference. Do this with the following two lines of code:
Test_Plan[‘Error_Temperature_Ambient’] = abs(Test_Plan[‘Ambient Temperature (deg F)’] — Temperature_Ambient) Temperature_Ambient = Test_Plan.loc[Test_Plan[‘Error_Temperature_Ambient’].idxmin(), ‘Ambient Temperature (deg F)’]
The first line adds a new column to the Test_Plan data frame that states the absolute value of the difference between the ambient temperature called for in that test and the average ambient temperature in the active test. The second line uses the .loc() and .idxmin() functions to identify the ambient temperature specified in the test with the least error and set that ambient temperature to our Temperature_Ambient variable.
Now we’re ready to save the data in a new file.
4. SavE the Data to a New File
With a data frame containing the results from a single test, and knowledge of the conditions of that test, we can now save the results to a new file.
First, ensure the folder in which we want to save the data actually exists. We could do that manually, but this is an article about automating things! Let’s program the script to do it for us.
Let’s say we want the data to be stored in the file C:\Users\YourName\Documents\AutomatingDataAnalysis\Files_IndividualTests. To make sure that folder exists we can use the following code:
Folder = ‘C:\Users\YourName\Documents\AutomatingDataAnalysis\Files_IndividualTests’ if not os.path.exists(Folder): os.makedirs(Folder)
The first line sets the path of our desired folder to the variable Folder. The second line uses the os function .path.exists() to check and see if that folder exists. If it doesn’t exist, it executes the third line of code to create the folder.
Once the folder exists, we can use the same approach to save the data file into that folder. We specify the file name we want to use, using variables to contain data about the ambient temperature, and use the pandas.to_csv() function to save the file where we desire. You can do this with the following code:
Filename_SingleTest = “\PerformanceMap_HPWH_” + str(int(Temperature_Ambient)) + “.csv” File_SingleTest.to_csv(Folder + Filename_SingleTest, index = False)
The first line creates the file name we want to use. It descriptively states it’s a file containing data from testing used to create a performance map of a HPWH. The second part is more important. It takes the ambient temperature that we identified in the test plan as a variable, converts it to an integer, converts it to a string and adds it to the file name. Now the file name contains the conditions of the test and tells you exactly what the file contains before you even open it.
The second line does the grunt work. It combines the folder specified previously with the file name for the current data frame and saves it. Note it also removes the index because saving that isn’t important and helps keep files cleaner.
What’s the Final Step?
Now you’re at the fun part of writing this script: you get to run it! You also get to watch the program generate the results you need for you.
(Note this process is a bit overkill in this instance. The companion data set has results from three fabricated tests. It wouldn’t be very difficult, time consuming or tedious to do this manually in a project with three tests. But what if you had 1,000 tests? That’s when this process becomes extremely valuable.)
How Do I Check my Results?
Checking your results is a two-step process.
First, ensure you got the right files as outputs. To do that, you compare the files in your new folder to the tests called for in the test plan. There should be one file for each test, with the conditions in the file name matching the conditions called for in the test plan.
In this process, you should see the following files in your folder:
Notice how there are three files in that folder, and three tests specified in the test plan. Also notice how the test plan calls for tests at 55, 70 and 95 degrees, and those three temperatures are specified in the three file names. So far, it looks like everything worked correctly.
Next, examine the data contained in each file. The easiest way to do that is by plotting the data and visually examining it (we’ll discuss ways to automate this process later).
A quick check you can do is to create a plot showing the ambient temperature from each data file, which you can do with Bokeh.
First, we need to create a new column in the data frame that gives us the test time in user-friendly terms (minutes since the test started). We do this by adding the following line to our program (if we assume that the time between measurements is five seconds):
File_SingleTest[‘Time_SinceStart (min)’] = File_SingleTest.index * 10./60.
That gives us a user-friendly time interval to use as the x-axis in our plot. Then we can use Bokeh to create and save the plot. We do that with the following code:
p1 = figure(width=800, height=400, x_axis_label=’Time (min)’, y_axis_label = ‘Temperature (deg F)’) p1.circle(File_SingleTest[‘Time_SinceStart (min), File_SingleTest[‘T_Amb (deg F)’], legend=’Ambient Temperature’, color = ‘red’, source = source_temps)
The first line creates a figure called p1 and specifies both the size and axis labels for the plot. The second line adds red circles to the plot with the x-values specified by Time_Since Start (min) and the y-values specified by T_Amb (deg F). The first line also states the legend reading should be Ambient Temperature.
You can save the plot using the gridplot and output file features.
p=gridplot([[p1]]) output_file(Folder + '\PerformanceMap_HPWH_T_Amb=’ + str(int(Temperature_Ambient)) + ‘.html’, title = ‘Temperatures’) save(p)
Pro tip: Bokeh has a handy feature called gridplot that enables you to store multiple plots in a single file. This makes it convenient to look at related plots next to each other and compare the data in them. This feature is not necessary for this tutorial, so we only entered our current plot (p1) in the grid. But you should know about it in case you want it in the future.
The second line specifies where the file should be saved. It goes in the same folder where we saved the .csv files of the data, and uses the same file name convention as before. The difference is that the data was saved in .csv files and this is saved in an .html file.
The third line finally saves the data.
If you re-run the code, you’ll see the same .csv files in your results folder. Additionally, you’ll now find new .html files. These .html files contain the data sets’ plots.
What would you expect to see if you open the plots?
First, you’d expect the ambient temperature recorded during the tests to be similar to the values specified in the test plan and file name. The tests at 55 degrees should have ambient temperatures around 55 degrees, and so on.
Second, with this being real world data you shouldn’t expect it to be perfect. Some values will be 54.5, others will be 55.2 and so on. Don’t freak out about that.
Third, you should expect to see the temperature adjusting at the start of the test. The original values will be at the temperature from the previous test, then the lab will need to gradually change the temperature to the new setting.
If we open the plot from the 55 degree test, we should see exactly that. Here’s what your result should look like:
Notice how the temperature starts at 75 degrees, then rapidly decreases to 55 degrees, as expected. Notice how the average temperature throughout the test is clearly 55 degrees, also as expected. Finally, notice how the data bounces around 55 degrees...just as we expected.
This file implies our code performed the test correctly and the data file split as we hoped.
What’s Next?
Now that the overwhelmingly large data file is split into three separate files, one for each test, we can begin to make use of those data files. The next step is to check the process of the data files so we can perform our analysis. When we finish the analysis, we can then check the results to ensure that the test and calculations are correct.
* * *
This multi-part tutorial will teach you all the skills you need to automate your laboratory data analysis and develop a performance map of heat pump water heaters. You can find the rest of the series here:
Need to Automate Your Data Analysis? Here’s How to Get Started.
These Python Scripts Will Automate Your Data Analysis
How to Check Your Data Analysis for Errors
Don't DIY. Write Python Scripts to Check Data Quality for You.
Generate Regressions in Python — Automatically! | https://builtin.com/data-science/split-data-sets?utm_campaign=&utm_source=&utm_medium=&utm_content= | CC-MAIN-2022-40 | refinedweb | 3,686 | 63.59 |
There:
I'm running Intellij 8.1.3, build 9886, the code that I'm testing can be found below.I have two Open Suse Linux boxs (11.1). Machine one is runnign IntelliJ and the other is running Eclipse with the old, unsupported Adobe FlexBuilder plugin.
On machine 1(IntelliJ).
What I did is I built the swf (HttpTestIntelliJ.swf) and tried to run it. I go an error where the event.fault.faultString was equal to "Security error accessing url". I ran the swf by opening Firefox browser (running FlashPlayer 9.0.128) and giving the URL
On machine 2(Eclipse)
I build the swf HttpTestEclipse.swf and tried to run it. I ran it using the the URL and it works. i.e. I get a response back from Google.
I moved the HttpTestEclipse.swf from machine 1 to machine 2 and ran it using theURL and it does not work with the same error message "Security error accessing url"
There is something fundamental that I'm missing here and I would really appreciate a pointer to what it is that makes one swf work in one directory and not in the other. Here is what I"ve tried or looked at
- md5sum of all copied files are the same
- any configuration files in the eclipse directory (there were none, but I removed all the other files anyway and it still works)
- both are compiled with -use-network=true
- all the compile flags seem to be the same.
- there are no hidden directories (.xx)
- there is no crossdomain.xml file on either machine (I'm not sure how it would be served anyway since no webservers are running).
Anyhelp would be appreciated.
Cheers
Cam
<?xml version="1.0" ?>
<mx:Application xmlns:
<mx:Label
<mx:HTTPService
<mx:Button
<mx:Label
<mx:Button
<mx:Script><![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
private function faultHandler(event:FaultEvent):void
{
var faultInfo:String = "fault description: " + event.fault.faultDetail + "\n\n";
faultInfo += "fault faultstring: " + event.fault.faultString + "\n\n";
Alert.show(faultInfo, "Fault Information");
}
]]></mx:Script>
</mx:Application>
There:
Hi Cam!
The short answer for you:
(usually it is like /Users/[user-name]/Library/Preferences/Macromedia/Flash Player/#Security/FlashPlayerTrust).
In case of Windows XP it is like C:\Documents and Settings\[user-name]\Application Data\Macromedia\Flash Player\#Security\FlashPlayerTrust.
For Vista: C:\Users\[user-name]\AppData\Roaming\Macromedia\Flash Player\#Security\FlashPlayerTrust
The long answer is: "Flash Player Security" | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206962065-Security-error-accessing-url | CC-MAIN-2020-05 | refinedweb | 412 | 60.51 |
The ultimate goal of the project I'm currently working on is to create a Swing command prompt which uses Window's Cmd prompt to execute commands. I have the swing portion finished, now I just need to stream input/output between my Java program and the command prompt.
Now I want the underlying functionality of this command prompt to be fairly similar to what the real thing will do (granted with a few exceptions, these are kind of irrelevant in this topic), which involves supporting stuff like batch files and the set command.
It isn't a problem to get one single command to work (or even running a bunch of commands in a batch file), but I'm having problems getting multiple user-entered commands to work.
For example:
SET IS_OK=1 IF IS_OK EQU 1 (ECHO "It is ok.") ECHO "DONE"
The expected output if a user were to type this into a real command prompt would be to print out "It is ok.", followed by "DONE" (without quotes)
The way I currently have it setup is to run a new command prompt for every command. This automatically dis-allows the above from working because set only works in an individual's environment variable.
Here's a short example of what I'm doing:
import java.io.IOException; import java.util.Scanner; public class Test { public static void main(String[] args) throws IOException, InterruptedException { runWndCommand("SET IS_OK=1"); runWndCommand("IF IS_OK EQU 1 (ECHO It is ok.)"); runWndCommand("ECHO DONE"); } /** * runs a Windows command prompt with the given command. Output is printed * out to System.out. Not entirely robust, but it demonstrates the point. * * @param cmd * @throws IOException * @throws InterruptedException */ public static void runWndCommand(String cmd) throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec(new String[] { "cmd.exe", "/C", cmd }); Scanner reader = new Scanner(p.getInputStream()); while (reader.hasNext()) { System.out.println(reader.nextLine()); } p.waitFor(); } }
The output of this code is to only print out "DONE"
Before you start saying that I could pass multiple commands in the runtime.exec() call, remember that this is for a command prompt. As such, individual calls are very likely to be executed before the next command would even be entered.
Is something like this even possible to do (without resorting to JNI, JVM mods, etc.)?
I've tried piping input to the command process using p.getOutputStream() (and running the command prompt without the /C flag), but the command prompt doesn't seem to respond to any inputs I put through this stream.
Oh, and I would really prefer not to re-write the windows command prompt functionality all in Java.
cross-posted at Cmd process streams - Java Forums. | http://www.javaprogrammingforums.com/file-i-o-other-i-o-streams/5734-windows-cmd-prompt-streams.html | CC-MAIN-2014-35 | refinedweb | 453 | 55.95 |
!.)
This free ebook provides comprehensive coverage of the platform for Windows Store apps. Since its second preview in August, we’ve added the remaining!!
Introduction
Welcome, my friends, to Windows 8! On behalf of the thousands of designers, program managers, developers, test engineers, and writers who have brought the product to life, I'm delighted to welcome you into a world of Windows Reimagined.
This theme is no mere sentimental marketing ploy, intended to bestow an aura of newness to something that is essentially unchanged, like those household products that make a big splash on the idea of "New and Improved Packaging!" No, Microsoft Windows truly has been reborn—after more than a quarter-century, something genuinely new has emerged.
I suspect—indeed expect—that you're already somewhat familiar with the reimagined user experience of Windows 8. You're probably reading this book, in fact, because you know that the ability of Windows 8 to reach across desktop, laptop, and tablet devices, along with the global reach of the Windows Store, will provide you with tremendous business opportunities, whether you're in business, as I like to say, for fame, fortune, fun, or philanthropy.
We'll certainly see many facets of this new user experience throughout the course of this book. Our primary focus, however, will be on the reimagined developer experience.
I don't say this lightly. When I first began giving presentations within Microsoft about building Windows Store apps, I liked to show a slide of what the world was like in the year 1985. It was the time of Ronald Reagan, Margaret Thatcher, and Cold War tensions. It was the time of VCRs and the discovery of AIDS. It was when Back to the Future was first released, Michael Jackson topped the charts with Thriller, and Steve Jobs was kicked out of Apple. And it was when software developers got their first taste of the original Windows API and the programming model for desktop applications.
The longevity of that programming model has been impressive. It's been in place for over a quarter-century now and has grown to become the heart of the largest business ecosystem on the planet. The API itself, known today as Win32, has also grown to become the largest on the planet! What started out on the order of about 300 callable methods has expanded three orders of magnitude, well beyond the point that any one individual could even hope to understand a fraction of it. I'd certainly given up such futile efforts myself.
So when I bumped into my old friend Kyle Marsh in the fall of 2009 just after Windows 7 had been released and heard from him that Microsoft was planning to reinvigorate native app development for Windows 8, my ears were keen to listen. In the months that followed I learned that Microsoft was introducing a completely new API called the Windows Runtime (or WinRT). This wasn't meant to replace Win32, mind you; desktop applications would still be supported. No, this was a programming model built from the ground up for a new breed of touch-centric, immersive apps that could compete with those emerging on various mobile platforms. It would be designed from the app developer's point of view, rather than the system's, so that key features would take only a few lines of code to implement rather than hundreds or thousands. It would also enable direct native app development in multiple programming languages. This meant that new operating system capabilities would surface to those developers without having to wait for an update to some intermediate framework. It also meant that developers who had experience in any one of those language choices would find a natural home when writing apps for Windows 8.
This was very exciting news to me because the last time that Microsoft did anything significant to the Windows programming model was in the early 1990s with a technology called the Component Object Model (COM), which is exactly what allowed the Win32 API to explode as it did. Ironically, it was my role at that time to introduce COM to the developer community, which I did through two editions of Inside OLE (Microsoft Press, 1993 and 1995) and seemingly endless travel to speak at conferences and visit partner companies. History, indeed, does tend to repeat itself, for here I am again!
In December 2010, I was part of the small team who set out to write the very first Windows Store apps using what parts of the new WinRT API had become available. Notepad was the text editor of choice, we built and ran apps on the command line by using abstruse Powershell scripts that required us to manually type out ungodly hash strings, we had no documentation other than oft-incomplete functional specifications, and we basically had no debugger to speak of other than the tried and true window.alert and document.writeln. Indeed, we generally worked out as much HTML, CSS, and JavaScript as we could inside a browser with F12 debugging tools, only adding WinRT-specific code at the end because browsers couldn't resolve those APIs. You can imagine how we celebrated when we got anything to work at all!
Fortunately, it wasn't long before tools like Visual Studio Express and Blend for Visual Studio became available. By the spring of 2011, when I was giving many training sessions to people inside Microsoft on building apps for Windows 8, the process was becoming far more enjoyable and exceedingly more productive. Indeed, while it took us some weeks in late 2010 to get even Hello World to show up on the screen, by the fall of 2011 we were working with partner companies who pulled together complete Store-ready apps in roughly the same amount of time.
As we've seen—thankfully fulfilling our expectations—it's possible to build a great app in a matter of weeks. I'm hoping that this ebook, along with the extensive resources on, will help you to accomplish exactly that and to reimagine your own designs.. . For this reason I’ve..
Throughout this book, identifiers that appear in code, such as variable names, property names, and API functions and namespaces, are formatted with a color and a fixed-point font. Here’s an example: Windows.Storage.ApplicationData.current. At times these fully qualified names—those that that include the entire namespace—can become quite long, for Windows 8. I'm serving more as a storyteller, where the story itself has been written by the thousands of people in the Windows team whose passion and dedication have been a constant source of inspiration. Writing a book like this wouldn't be possible without all the work that's gone into customer research; writing specs; implementing, testing, and documenting all the details; managing daily builds and public releases; and writing again the best set of samples I've ever seen for a platform. Indeed, the words in some sections come directly from conversations I've had with the people who designed and developed a particular feature. I'm grateful for their time, and I’m delighted to give them a voice through which they can share their passion for excellence with you.
A number of individuals deserve special mention for their long-standing support of this project. First to Chris Sells, with whom I co-authored the earliest versions of this book and who is now leading development efforts at Telerik. To Mahesh Prakriya, Ian LeGrow, Anantha Kancherla, Keith Boyd and their respective teams, with whom I've worked closely, and to Keith Rowe, Dennis Flanagan, and Ulf Schoo, under whom I've had the pleasure of serving.
Thanks also to Devon Musgrave at Microsoft Press,:.
Well done Kraig! Parts of your preview book have been very helpful to us.
Really helpful... Going through it now!!!
Thank you all very much. This (W8 development) is something I need to get started with.
Thank you very much!
Thanks for this.
Thanks for the ebook! Looking forward to the ePub version
The best book on the subject, so far!
Your O'Reilly ad on the right-hand side of this page needs a target="_blank" attribute or it doesn't open in a new window.
Kraig,
Great book!
How about a C# version?
Cheers,
--rj
non.o.i.crediti.me.li.ridai.o.due.carte.di.credito.dove.sono.sconparse.dove.stanno.i.miei.redditi.non.li.trovo.o.delle.email.mi.cerchi.i.soldi.grazie
The PDF link doesn't work. I was able to download the companion content zip file, but the PDF will not download. Any help?
Grant, we've had many thousands of downloads already and yours is the first mention of any trouble. Give it a few minutes and try again?
Devon, I've just tried again and it worked. Odd. I'm on the same laptop now at home. That link just wasn't doing anything then. I've got it now anyway, looks a bit imposing!
Very good. Imposingly informative -- enjoy, Grant!
Hi guys, thanks for the great book. Mobi & Epub versions would be much appreciated! Any idea when those will be ready? | http://blogs.msdn.com/b/microsoft_press/archive/2012/10/29/free-ebook-programming-windows-8-apps-with-html-css-and-javascript.aspx?Redirected=true&title=Free%20ebook:%20Programming%20Windows%208%20Apps%20with%20HTML,%20CSS,%20and%20JavaScript | CC-MAIN-2015-32 | refinedweb | 1,538 | 61.36 |
Data Communications Equipment. Term ITU protocol standards apply to switching equipment that forms a PSN, or packet switched network, to distinguish it from the computers or terminals that connect to the network. Usually located at the service provider.
Distributed Computing Environment. Created by the Open Software Foundation as an alternative to Sun's ONC stack. DCE includes an RPC layer, Kerberos authentication, and directory services. The Distributed File Service (DFS) is built on top of DCE and provides a networked filesystem with the same namespace on all computers.
Log in or register to write something here or to contact authors.
Need help? accounthelp@everything2.com | https://everything2.com/title/DCE | CC-MAIN-2018-39 | refinedweb | 105 | 50.02 |
Search Type: Posts; User: petko.ivanov
Search: Search took 0.02 seconds.
- 7 Jul 2011 6:39 AM
- Replies
- 0
- Views
- 433
hi
is there a way to put a simple separator or emphasize HeaderGroups in a Grid?
All i want is to add effectively a border around Groups so they stand out.
I can the same thing by doing separate...
- 13 Jan 2011 11:52 AM
- Replies
- 0
- Views
- 566
hi,
assume i have a chart with values in the range of 100 to 110 with 5 DataProviders. Scales fine between 100 and 110.
Occasionally 1 of them gets bad data and calculations fail, so it contains...
- 23 Dec 2010 11:54 AM
so the final fix i am going in as as bizarre as the issue. Here is what the gui setup :
VerticalPanel (A) contains HorizontalPanel(B) which contains Chart and CheckBoxGroup.
The fix is to put...
- 23 Dec 2010 8:27 AM
well, in debug mode everything works.
with compiled code, what i see is that CheckboxGroup seems to be shown correct, when i select/ deselect the check mark changes accordingly but the Chart does...
- 23 Dec 2010 8:24 AM
spoke too soon.
in addition, sometimes when i shift+reload it just works, so i guess was working because of that.
just loading the URL again does not seem to work.
- 23 Dec 2010 8:21 AM
yes, i was trying that (i think). calling chart.refresh() did not make a difference.
it just struck me that the problem may not be the chart but the CheckBoxGroup.
So for kicks i added the line :...
- 23 Dec 2010 8:11 AM
writing a small scale code that illustrates the problem may be harder than the problem itself.
it is just very involved.
at this point i will take any speculation ...
the CheckBoxGroup and Chart...
- 23 Dec 2010 8:02 AM
hi,
have the following weird problem.
I have a chart controlled with a CheckBoxGroup. When a data update comes, the CheckBoxGroup need to be updated. So i am constructing a new group, and...
- 7 Dec 2010 11:13 AM
- Replies
- 1
- Views
- 609
hi,
i think this is not possible - but just in case :
is there a way to accomplish the menu as described here?
thanks
- 30 Nov 2010 9:51 AM
thanks Sven, was just realizing that ! cheers
- 30 Nov 2010 9:51 AM
bah, seems like tooltips are weirdly implemented , judging on this discussion :
I will have to play with...
- 30 Nov 2010 9:38 AM
hi,
i am trying to override the default tooltip using this :
ChartConfig.setTooltip("aaa");
which worked as i can see the jsonData that is created is :
{"title":{"text":"foo"},...
- 20 Sep 2010 8:22 AM
here is the final version of the code i am going with :
public class ChartModel2 extends ChartModel{
private static final long serialVersionUID = 1L;
private static final String EMPTY...
- 18 Sep 2010 8:39 AM
- Replies
- 4
- Views
- 1,732
you serialize the map that is constructed from the properties of the main object. as my pseudo code shows. regardless , it will not work for submaps (i am guessing you mean BaseTreeModel).
- 17 Sep 2010 9:12 AM
ah, one moment. fix is good, but more tests revealed a big flaw in my understanding of that method.
the correct usage is :
xa.setRange(0, labels.size()-1);
that tells it to display everything...
- 17 Sep 2010 8:27 AM
i can confirm that the suggested work-around works.
Here is what i did :
1. create Chart2 extending Chart which in the processModel method, right after the call to updateYScale to updateXScale as...
- 17 Sep 2010 6:03 AM
- 16 Sep 2010 2:19 PM
hi,
i have the following seemingly simple test case:
* first 10 points as null
* next 15 with valid data
I get 10 nulls plotted and only 5 of data ie looks like the chart...
- 16 Sep 2010 2:12 PM
- Replies
- 4
- Views
- 1,732
i hit the same problem and used a Map to get around it.
Dont recall exactly why now but the solution was simply to do
map = new HashMap(BaseModel.getProperties());
this now you can serialize back...
- 3 Jun 2010 9:57 AM
i was using the terms collapse/ expand to describe the visual state of the tree.
I _HAVE_ fix the problem for myself, confirmed by me and users in multiple browsers. My secondary hope was to share...
- 3 Jun 2010 9:36 AM
in the terminology of that method call: When children (1) are added, they will actually become visible immediately after the add (so events are needed). Their children(2) however are still invisible...
- 3 Jun 2010 8:25 AM
the rationale for my fix is as follows:
1. when nodes are inserted, their children are added with suppressEvents flag = false (hardcoded). at a minimum it should be the value of the suppressEvents...
- 3 Jun 2010 7:55 AM
ok, i can retest my use case as soon as 2.2 is out.
However, my code needs to be deployed asap (as usual) so the patch i posted is the only solution i have at the moment. If u can propose anything...
- 3 Jun 2010 7:46 AM
i did search - could not find anything relevant. Also the fasttree is not really relevant to me as i am interested in the TreeGrid component. The above is the only way i could get TreeGrid to be...
- 3 Jun 2010 7:20 AM
i just saw :
so will try this next and report results.
btw for comparison - my tree size is about 450 leaf nodes.
Results 1 to 25 of 54 | http://www.sencha.com/forum/search.php?s=bcda365a2468a2598b49548cf2b346d0&searchid=5033318 | CC-MAIN-2014-15 | refinedweb | 945 | 83.05 |
Accessing sub viewsview1?
import ui
view1 = ui.load_view()
w1 = view1['webview1']
w1.load_url('')
view1.present()
All subviews are accessed in the same way, no matter if it's a normal View, a ScrollView, or something else. In your case that would be
view1['scrollview1']['webview1'].
(I'm not sure why you'd want to place a WebView inside a ScrollView... the WebView is already scrollable on its own.)
Thank you. Worked good. I appreciate the quick response.
Yes your right, dgelessus. You normally wouldn't want a web view inside a scroll view. For my I app I am doing so. I want a few small web views running at once that can be scrolled. This is productivity web browsing app. Think of how You Tube has it's videos listed in a scroll view. | https://forum.omz-software.com/topic/1472/accessing-sub-views | CC-MAIN-2017-47 | refinedweb | 135 | 87.82 |
Hi again, devs.
Are you having a nice weekend there? I really hope so. 🙏
I should have released this final part yesterday, and my apologies for being late, but finally and after almost 3 months of coldness and darkness we have had few hours of sun shinning here so I decided to enjoy it. ☀️
If you are new here and have no idea what Trash Course means, please check 👇:
HINT: I am not ditching
Next.js or anything.
But if you have been following along until here, please receive all my thankfulness. 🏆 So glad in having you aboard.
What will be covered in this part 3/3? 🤩
- Static Assets, Custom Page Title and Metadata
- Fetching Data
- Dynamic Routes
Part 9 - Static assets, custom page title and metadata 📕
We are likely use to static assets (e.g. favicons, images etc.) in web applications. In
Next.js we can achieve it by placing them in the
public folder.
I grab from the internet an Ash Ketchum image just to use as an example and placed it on the public folder (
public/ash.png). We will use it as our logo in the
Navbar component.
import Link from 'next/link'; import Image from 'next/image'; // we import it and use below as following export const Navbar = () => { return ( <nav> <div className="brand"> {/** Here 👇 */} <Image src="/ash.png" width={60} height={60} /> </div> <Link href="/">Home</Link> <Link href="/about">About</Link> <Link href="/dev/">Dev</Link> </nav> ); };
We could also have used the classic
img tag if we want to:
<img src="/ash.png" alt="ash ket" />.
Some points to consider when using the
Next.js Image component are described below:
- We need to specify its
widthand
heightproperties explicitly otherwise an error will be thrown.
- It automatically makes the image responsive based on the properties provided.
- It utilizes the lazy loading design pattern. it is only loaded when it needs to be rendered, for example, if the image is placed in our footer,
Next.jswould only load it when scrolling down the page reaches the footer.
Talking about adding
metadata and
customized title to different pages it can be as simple as the following example in our
import Link from 'next/link'; import Head from 'next/head'; // We import the Next.js' Head component export default function Home() { return ( <> {/** 👇👇👇 */} <Head> {/** Add the title and metadata for the page as shown below*/} <title>Creep Home Page</title> <meta name="keywords" content="next,random design,trash course" /> </Head> {/** 👆👆👆 */} <div className="container"> <h1>Hello Next.js</h1> <div> <Link href="/about">About</Link> </div> </div> </> ); }
Remember to wrap all the components using only one parent element otherwise an error about having multiple parent elements will be thrown. I have used empty tags
<></> but it could be a
React Fragment, a
<div> etc.
Part 10 - Fetching Data ⬇️ 💽
Normally in an application the data we fetch comes from the server-side, for example, a database, a web server and so on.
In order to make it simple, let's fetch some mock data from JSON API Placeholder
In a
React application we would fetch data using the
useEffect hook and the request would be made in the browser.
In
Next.js it differs a little bit because all the components are first pre-rendered by the time they reach the browser. In other words we need to fetch the data in advance so the rendered components will have already the data in their templates.
Here is where the
Next.js'
getStaticProps function comes to the stage. I will use our dev's homepage (
pages/dev/index.js) to fetch data from.
In our
dev's index page (
pages/dev/index.js) we must create the
getStaticProps function and
export it.
export const getStaticProps = async () => { const response = await fetch(''); const data = await response.json(); return { props: { users: data } }; };
⚠️ DON'T write any code inside of the
getStaticProps function that you expect to run in the browser. ⚠️
getStaticPropsis a special
async functionbecause it runs at build time. Inside of this function we add our
fetch requestsin order to, guess what?, fetch any data we want to render in our component. 😉
The data we have fetched from the API endpoint is now attached to the props (
{ users }) of our component:
export default function Home({ users }) { return ( <div> <h1>Hello Devs</h1> <ul> {users.map((user) => ( <li key={user.id}> <p>{user.username}</p> <p>{user.email}</p> </li> ))} </ul> <Button>Dev Button</Button> </div> ); }
And that's it. Of course it is just a basic implementation but as a starting point it works pretty well.
I also know I should add some styles to it but this article is becoming longer than I thought so see it as a homework for you. 🤜 🤛
Part 11 - Dynamic Routes 🛣️ 🛣️
It would be nice if from the users list we fetched data we could see more information about a specific user when clicking on it. There are some steps to be followed in order to achieve that but nothing complicated at all.
We need to: ✏️
- Generate dynamic routes for each user,
- Create a component to hold the user details.
Inside of
pages/dev folder we will create a file called
[id].js so we can have routes at
/dev/id where the
id is whatever user's id we pass to the component.
The
[id] syntax you saw before is a way to tell: " - Hey
Next.js, I will be passing some route parameters to this component so be aware of that.".
Our
pages/dev/[id].js component initially will look like the following:
import React from 'react'; const UserInfo = () => { return <div>Boom!</div>; }; export default UserInfo;
If now you go to the route or whatever value you pass as a route parameter you should see
Boom! rendered there. It is not dynamic yet so let´s make some changes to make it happen.
- Let's create a link in every user in the list so when we click on it we use its id as a parameter to fetch his / her individual data. (
dev/index.js).
import { Button } from '../../components/Button'; import Link from 'next/link'; export const getStaticProps = async () => { const response = await fetch(''); const data = await response.json(); return { props: { users: data } }; }; export default function Home({ users }) { return ( <div> <h1>Hello Devs</h1> <ul> {users.map((user) => ( {/** 👇👇👇 */} <Link href={`/dev/${user.id}`} key={user.id}> {/** LAZY styling 😅 🙈 */} <li style={{ cursor: 'pointer' }}> <p>{user.username}</p> <p>{user.email}</p> </li> </Link> ))} </ul> <Button>Dev Button</Button> </div> ); }
And finally we need to make a call to the endpoint using the
user's id in order to fetch a user's individual info. (
pages/dev/[id].js).
export const getStaticPaths = async () => { const response = await fetch(''); const data = await response.json(); const userPaths = data.map((user) => { return { params: { id: user.id.toString() } }; }); return { paths: userPaths, fallback: false, }; }; export const getStaticProps = async (context) => { const userID = context.params.id; const response = await fetch( `{userID}` ); const data = await response.json(); return { props: { user: data } }; }; const UserInfo = ({ user }) => { return ( <div> <h2>User Info</h2> <p>username: {user.username}</p> <p>email: {user.email}</p> <p> address: {user.address.street} - {user.address.city} </p> <p>phone: {user.phone}</p> <p>website: {user.website}</p> </div> ); }; export default UserInfo;
Don't be scary! Most of the content there we are already familiar with. The new concepts I am going to try to explain now.
- The
getStaticPathsfunction: ✔️
export const getStaticPaths = async () => { const response = await fetch(''); const data = await response.json(); const userPaths = data.map((user) => { return { params: { id: user.id.toString() } }; }); return { paths: userPaths, fallback: false, }; };
It is also a special function. It fetches the data and returns an array containing all the static paths of every single user as shown below.
//... const userPaths = data.map((user) => { return { params: { id: user.id.toString() } }; }); return { paths: userPaths, fallback: false, }; //...
Remember that all the pages are build at run time. Think that it returns an array like this:
[{ /dev/1 }, { /dev/2}, ... , { /dev/10 }].
The
fallback: false option, is out of scope for now, but if you remove it will throw an error.
- The
getStaticPropsfunction (same as before but slightly different): ✔️
export const getStaticProps = async (context) => { const userID = context.params.id; const response = await fetch( `{userID}` ); const data = await response.json(); return { props: { user: data } }; };
It has now access to the
props returned from the
getStaticPaths function through the
context object.
From this object it can access the id of each user, fetch their individual information and send it to the
UserInfo component (
/pages/dev/[1].js).
And that's all, devs! I think we made it, guys! 🏅 🥇 🎉 🍾
Indeed, there is a lot of stuff to be explored but my aim was just to make a quick introduction to
Next.js.
I am planning to release an extra post introducing the
api folder (
pages/api) and also how to deploy our application on
Vercel but it depends a lot of how my week goes so I cannot promise anything, unfortunately. 😓
I hope you guys have enjoyed our time together and also have learned something from it. 😃 If you have created your own version using the content of this series, please share with us.
We would be glad to see the results of your hard work. 💪 💎
Thanks a ton and be safe everybody! 🙇♂️
Discussion (5)
There's some mismatch. You said:
«At the top of the file (pages/dev/index.js) we must import it.»
And then just create this function in the same file.
I think these "special" function need a bit more explanation. As I can understand, is fired just before rendering component, and - before that call.
Are there any rules in syntax, props, return values, ordering them in file? I guess only the name is important? And how is passed from one to another? Any other similar functions exist?
Thanks for the course, though)
Good catch, Макс! Thanks for pointing it out.
I have just correct that. I meant
exportinstead
importsince ´Next.js´ uses those function internally. :) But indeed, the sentence was a little bit confusing and mismatching, sorry for that.
Answering (Or trying to )
"... As I can understand, is fired just before rendering component, and - before that call ..."
If you export an async function called getStaticProps from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.
Source: Next.js Docs
"... I think these "special" function need a bit more explanation ..."
I totally agree with you. I really tried hard to fit all the basics concepts in only three posts but as I have mentioned before unfortunately it was not enough.
I am planning to release one or two more extra posts to explain things more in deep. 🙏🏻
Are there any rules in syntax, props, return values, ordering them in file? I guess only the name is important? And how is passed from one to another?
Yes, there are some rules, for example:
getStaticPropson a page with dynamic route parameters, you must use
getStaticPaths;
getStaticPathsshould be used together with
getStaticProps;
getStaticPathswith
getServerSideProps.
As you have pointed out previously, the function name is also important because
Next.jswill define the order of each function call based on their names. Where they are placed inside of the file doesn't matter for that reason.
"... Any other similar functions exist? ..."Yes, e.g.
getInitialPropsand
getServerSideProps.
I really hope I could clarify some of your doubts, Макс.
I am not an expert in
Next.jsby any means.
The concepts I brought in this series are from the Next.js Official Documentation . I would really recommend you to give a glance there. 😎
Again, thanks for participating.
Thanks for the reply, Vinicius. I will definitely try Next.js out with one of next projects.
Nice topic !
Nice to see you again, Kevin. 👍 | https://dev.to/vinicius77/next-js-trash-course-part-3-3-3igc | CC-MAIN-2021-17 | refinedweb | 1,962 | 67.35 |
How Washington Will Shape the Internet 373
WebHostingGuy writes "As reported by MSNBC, .' The article examines several pieces of legislation and lobbying initiatives which are poised to affect you and your rights online. Topics covered include Net Neutrality, fiber to the home, the Universal Service Fund, codecs, and WiFi bandwidth usage." From the article: ."
Let me hazard a wild wild guess... (Score:5, Insightful)
Here comes the internet license. (Score:5, Insightful)
Honestly, I don't understand how a conservative government can increase the size of government this much, and ask for internet regulations, I mean it does not follow the philosophy at all. Am I the only libertarian here?
When law making comes to the internet, another internet will be invented, just not anytime soon. My advice is, start the planning stages for the next internet, and then when there is the will to bring it forward, bring it forward. Let's just admit once and for all that it must have been Al Gore who gave us the internet, he did not invent it, but he handed it so us. Before that, the masses didnt know what the internet is, and the masses won't know what the next internet us when us geeks invent or find it, hey we mmight already have it.
Re:Here comes the internet license. (Score:5, Insightful)
The richer, more powerful libertarians get to decide policy. Big companies have more resources than almost any human will ever have and they protect their interests.
I was a libertarian until I realized the philosophy breaks down in the face of concentrated wealth and power. If we had lots of people with ten million dollars it would probably work. When we have a few hundred "people" (some human, some corporate) with billions of dollars, it doesn't work.
You can't even have a fair court system when the power/money becomes too unequal. One person gets the public defender who is falling asleep in court while the other side gets a team of top-notch, well connected lawyers backed up by a firm of bright assistants.
Re:Here comes the internet license. (Score:2, Interesting)
Why/How would a change towards civil liberties and personal freedoms make things worse? We've been failing with the two party system for quite some time now, why can't we just try something different? It can't get much worse at this point.
I feel wierd saying it, but I'm not proud to be an American right now, I'm embarassed. I love this country and its people
Re:Here comes the internet license. (Score:3, Interesting)
Yes, yes and yes.
Why/How would a change towards civil liberties and personal freedoms make things worse? We've been failing with the two party system for quite some time now, why can't we just try something different? It can't get much worse at this point.
I apologize to the poster for speaking for them, but I believe their point was there was no way to m
Re:Here comes the internet license. (Score:5, Interesting)
Greens share those values. Without throwing us all to the wolves for the sake of "indvidual freedom".
You may not like the idea, but you don't get to just do whatever you feel like because, believe or not, your actions do sometimes affect other people. EVEN MORE SO, if you're rich and powerful. Then we REALLY need to watch you. Because then, as a private individual, you have the ability to do a whole lot of damage to people in all kinds of ways that are not "direct victim crimes". Say, buying all the companies in an area and dropping wages. Sure, some might move. But many won't. And you win.
People have only two possibilities for fighting power if they themselves don't have the resources. Democratic rule, or revolution.
If you cripple democratic rule to dissallow the right of a community to establish its own codes of conduct, including some encroachments into your personal freedoms, then eventually, people have to take option number two.
I'm all about civil liberties. Do what you wilt and all that. But, sometimes there do have to be limits. I'm personally pretty glad that you have to learn a few things to drive a car, for example. It may not be ultimate freedom, but it's pretty freaking prudent.
Re:Here comes the internet license. (Score:4, Insightful)
You should have continue following the money as it were. How did htese people get the money? By government. Government provided them with special protections no normal person has. Hiding behind the wall of a corproation is a protection/benefit system designed to produce exactly what you correctly identify as a problem. With these "protections" in place both people and companies who become "corporate entities" become an arm of the government (that is what a Charter effectively does - and it is a Corporate Charter) and gain all manner of advantages an otherwise free market system does not provide.
Whether that be the ability to pollute w/o risk of penalty, or deploy anti-competition tactics that would otherwise be illegal, or to use the corporation as a source of money and legal defense funding, it is done so by threat of force (death) by the government. As much as many people like to believe otherwise, libertarian principles did not provide for the wealth of Bill Gates or Larry Ellison. To the contrary it was anti-libertarian (i.e. statist) principles that did so.
Re:Here comes the internet license. (Score:5, Insightful)
Companies fit this bill by their very nature. People, in groups.. not so well. That's why we have government. It's the organization of the people without regard for money, where your power comes from your existence as a human being.
Or, more accurately, it should be.
Unless, of course, you advocate for plutocracy, which is where libertarianism leads
Re:Here comes the internet license. (Score:3, Insightful)
You really havn't read much Ayn Rand and then looked at how she led her private life.
Libertarian is about the strong doing what they want while the weak try to get by.
It is a *wonderful* philosophy if you are strong, healthy, well off, powerful, wealthy, etc.
Otherwise... not so good.
Re:Here comes the internet license. (Score:5, Insightful)
However, with respect to other things like unenforcable legislation utterly contrary to international law over internet gambling, etc., they need to get a damn clue, or they will screw things up.
I know that I personally have left the Republican party over the idiotic crap they've been pulling for the last eight years or so. They've made it abundantly clear that the law doesn't apply to them, that they're more than willing to rush blindly ahead when sensible people have doubts, and that they're willing to help screw up things like the internet that they have absolutely no understanding of.
Re:Here comes the internet license. (Score:3, Insightful)
That's just silly. There is a reason it happened with roads! The government did not build the internet infastructure, and taxes did not fund it. At least not wholly. The road infastructure, however, is funded by taxes and built by the local, state, and federal governments and/or they contract a comp
Re:Here comes the internet license. (Score:2)
I've been saying that we need an internet license for years. The problem with a gov't regulated internet license, is that they haven't the infrastructure to enforce the license. I'm certain that the actual policing will be left up to the select few providers that are pushing for these new laws.
It doesn't matter anyway....at least, not to me. If a license is required to connect, I can happily submit to that requirement and find ways around the limitations. Th
Re:Here comes the internet license. (Score:5, Insightful)
It's not just a conservative government, it's compassionately conservative. Let me point out charitably that Karl Rove has got your number if you think Bush II's government is conservative. You were snookered.
The truth is that this "conservative" government is crowing today about enormous budget deficits coming down a fraction (when we were balanced under Clinton), while ignoring long-term structural deficits caused by tax cuts for the richest Americans that have only increased the wage gap over the last several years. Throwing cash around like water, paying off Halliburton and Big Pharma and scumbags like Abramoff and on and on... how much evidence do you need of the mendacity involved in labeling the profligate Bush government "fiscally conservative"?
I will point out, however, that the conservative movement has had free rein to choose its policies. If the ship has run aground, we know who has been at the wheel.
If you want a fiscally conservative government, kick out the neocons and vote for some Democrats. Or you could vote for the Greens, it worked in 2000.
Re:Here comes the internet license. (Score:5, Insightful)
The republican party hasn't been fiscally conservative since Nixon. Look at the debt Reagan and Bush 1 drove up. Look at Bush 2. Fiscal conservative is now democratic property- you know, the guys who balanced the budget in the 90s. It hasn't been anything approaching Libertarian since Hoover in the 20s and 30s. It got co-opted by the religious right in the 80s, the cumulation of a slide starting in the 60s (when the formerly democratic southern US switched republican once democrats started supporting civil rights).
Wake up and face reality- the republican party has *never* been what it claimed it was. For most of this century its been living a lie. You really have two options:
1)A party run by corrupt rich buisnessmen who use passionate bigoted fringe groups to get into office, then run the country for their own benefit. You can tell this party by its election year tactics- rather than debating real issues it tries to raise emotional issues with those fringe groups- gay marriage, flag burning, "under god" in the pledge of alliegence. This is the republicans.
2)A coalition of every other group. Some who are just flat out bought by other interests than the republicans, some who are very passioate about specific issues (environment, anti-war, even a few free speachers). THe portion that aren't owned by the big corps do try and look out for their constituents. They typically try to bring out actual issues, rather than rely on flag waving. What you actually get depends on your luck, but you're pretty much garunteed to do no worse than the first party, and perhaps quite a bit better. This is the democrats.
Until we have some real third parties (which will require changes in how voting is done), these are our choices. Not much to choose from, but option 2 gives you at least a chance.
"Conservative" (Score:3, Interesting)
What is our "conservative government" conserving?
Certainly not conserving natural resources - nothing conservationist about them.
Certainly not "sound fiscal policy" or keeping a balanced budget.
Certainly not conservative, in the sense of tried-and-true, time tested policies and practices that work.
As far as I can see, todays "conservatives" are really conserving a few key things:
Their we
Isn't just the nature of legislation? (Score:2)
Re:Let me hazard a wild wild guess... (Score:3, Interesting)
Washington can do whatever it wants to servers, bandwidth, and access within the USA. I don't give a shit, because -- like most of the human race -- I don't live there.
Slashdot focuses too much on national poltiics. (Score:2, Insightful)
If you don't want big federal government, why did you vote for it? This goes for Democrats and Republicans. Federal government is big under EITHER party. Most of us internet geeks seem to be libertarians, and as a result we can't feel comfortable in either party.
In the Democratic party of old ideas, we hear them discussing going back to the days of FDR, and that is completely unreali
Re:Slashdot focuses too much on national poltiics. (Score:2)
Politics is truly local in scope, but the Internet is global in scope. Of course, you know what they say about global variables... [programming reference thrown in for obfuscatory purposes only]
I don't think the solution to Internet regulation is inherently a local issue, exept maybe where access is concerned. It will take local groups uniting to apply sufficient pressure to Co
Re:Let me hazard a wild wild guess... (Score:3, Insightful)
Currently video franchising is done through local municipalities, except in the few states that h
First (Score:3, Insightful)
Re:First (Score:2, Insightful)
Copper really can't stand up to fiber optics, especially in the long term. Even the cable companies are starting to use fiber optics to a certain extent in their netw
Re:First (Score:3, Informative)
Re:Let me hazard a wild wild guess... (Score:5, Funny)
I appreciate the fact that many have come from many different faiths and traditions. The faith-based innnernet is not about a single faith. In this country we're great because we've got many faiths, and we're great because you can choose whatever faith you choose, or if you choose no faith at all, you're still equally American. It's the same with those gushing tubes on the innernets.
Corollary #14 to Clarke's Law (Score:4, Funny)
Re:Corollary #14 to Clarke's Law (Score:3, Insightful)
Any sufficiently advanced technology is subject to Bigguv'ment trying to screw it up.
Any technology vulnerable to governmental and corporate interference is insufficiently advanced.
Re:Corollary #14 to Clarke's Law (Score:4, Interesting)
Can you please give me an example of a technology NOT vulnerable to governmental interference? It's nice to drop out one liners like that, except when they have no cover whatsoever. If government wants to get involved and regulate a tech field, chance are it will. On my side, I'd rather see a split internet then face regulations imposed by the US on a global network.
Re:Corollary #14 to Clarke's Law (Score:2)
Tinker Toys.
Re:Corollary #14 to Clarke's Law (Score:2)
Yeah, that's what Logs thought too until that damn meddling Lincoln came around....
=tkk
Re:Corollary #14 to Clarke's Law (Score:2)
Tor comes close. It provides not only the ability to anonymously access services, but also the ability to anonymously offer them. A VOIP design built on top of it, for example, could allow two people to contact each other without either party or any observer knowing who the two people are. Add port hopping to the protocol to prevent port blocks and you have yourselves a very, very good start at a networking technology that isn't vulnerable to governmental interference.
Re:Corollary #14 to Clarke's Law (Score:2)
Beware government contracts (Score:2)
You may wish to compare and contrast the evolution of the domain namespace and the usenet namespace.
Flag Burning (Score:5, Interesting)
I don't think it's too cynical to say that's probably intentional. Flag burning seems to be one of those hot-button issues that conservative politicians trot out when they want to (a) drum up votes or (b) distract people from other issues. (Liberals have their own hot-button issues, though these days the conservatives seem to be punching them just fine from the other side.)
Re:Flag Burning (Score:4, Insightful)
"Family Values" comes to mind... as does embryonic stem-cell research, etc.
*Meaningless as in politically meaningless -- I don't mean to deride the value of a lot of these issues on a personal or even local level. When the nuts and bolts are counted, these wedge issues mean nothing in the big picture of what it is that Congress/POTUS actually does.
Re:Flag Burning (Score:3, Insightful)
To bring this back OT, let's not forget it was President Clinton who signed CIPA into law imposing on libraries and schools the duty to block "obscene material," which for some years helped fuel widespread use of censorware. The idea of a free Net has much to fear from all American p
Intarwebs (Score:2, Offtopic)
Re:Intarwebs (Score:3, Interesting)
Well, the government can't allow just anyone to use the Internet's "tubes" now can they? They might put yucky things like real news and detailed information about the behind-the-scenes fleecing of American citizens by Congress in the "tubes" and then where would we be?
Hate to break it to you... (Score:5, Insightful)
Re:Hate to break it to you... (Score:2)
Re:Hate to break it to you... (Score:2, Insightful)
The rest of the world has no choice. (Score:3, Insightful)
I'm not saying the world population will go along with it, but the decision makers are all on the same team, and all profit together. Do you really
Re:The rest of the world has no choice. (Score:3, Informative)
Wow, I think you should have a look at the rest of the world and realize that we don't "import" laws from the US. Most of Europe and Canada are Socialist countries... you don't see us adapting US education and healthcare do you?
The Canadian Privacy Commissioner is currently reviewing cross-border data flow because Canadians' privacy is being compromised by the Patriot Act. If anything, we're seperating ourselves from the US, not the other way around.
Inside perspective (Score:5, Interesting)
Re:Inside perspective (Score:2)
Re:Inside perspective (Score:2)
Here is a philosophical question (Score:2)
Re:Here is a philosophical question (Score:2)
Consumers only have a right to consume. (Score:5, Insightful)
If you really worked for a politician like you say, you'd know that the average voter has little to no influence on what deals are made between leaders. If you want in, then get in, join the club, work for the company, invest! If you want, start an investment club.
Just talking about politics will change absolutely nothing. Politicians do not care about our opinions. The have experts to tell them what to care about, they have pollsters to tell them what our opinions are, and they can shape our opinions when they don't like what our opinions are. In the end, it's ultimately just about money. You can buy influence, you can buy politicians, you can buy just about any favor. It's about favors.
Teleco companies are VERY VERY powerful, they have infinite leverage over any politician. The telecos know everything, and had these abilities before the whole NSA wiretap scandal, so what politician is going to challenge the big telcos, or big oil? I wouldnt, you wouldnt, and a politician wouldnt for the same reasons we wont.
The best thing you can do is work with these big powerful corporate entities, and try to make policies which in a give and take fashion, where you make deals. If you expect to be a politician, it's a dirty business, it's a VERY dirty business, but ultimately it is a business, and the way to be successful is to do business with big business.
If you actually think you can be involved in politics, and that Google has more influence than telephone and oil companies, you are insane. The hardware companies have more influence than the software companies. The phone companies have more influence than the hardware companies. The energy companies have influence over ALL companies.
If you were smart, take an economics class and see how society is organized.
Re:Consumers only have a right to consume. (Score:2)
Down the Tubes (Score:4, Informative)
Washington's K Street?? (Score:2)
That's what the EFF told me...
Hey, wait a minute! Didn't the EFF *used* to be based in DC, but then moved to the west coast? That can't be right, makes no sense, I must be confused...
Anways, I guess we're all lucky these guys [cdt.org] stayed behind.
They hate us for our freedom. (Score:3, Funny)
But they also hate us for our Internets.
"The ministry of communication is duty-bound to make the use of the Internet impossible."
- Taliban official [totalobscurity.com], less than three weeks before 9/11.
Hey, be thankful that Congress doesn't exactly turn on a dime. We got to keep sending Internets to each other for another 5 years before they pulled the plug.
Broadcasting over Fibre... (Score:2)
Re:Broadcasting over Fibre... (Score:3, Insightful)
Now, If verizon is allowed to start sending media down that fibre line, I think it should be fair that any other Company or Startup (new Media Broadcaster??) should be allowed to do the same to complete
Theoretically that is the case now. It is one of the things that they are trying hard to change. Realistically, unless you have big bucks to fight it out in court, the phone company will refuse to comply with smaller businesses requests to use the lines. After much work I had the provider I chose for DSL t
Re:Broadcasting over Fibre... (Score:4, Insightful)
It's one thing to pay for the infrastructure out of tax dollars. It's quite another to then have no choice of who uses that publically-financed infrastructure.
Re:Broadcasting over Fibre... (Score:2)
Which is why my contention has been all along to nationalize the communications infrastructure of the country, mark it a national resource, then force the telecoms (or anyone else) to play by one set of rules. Mind you, I know this means letting the Federal Government run the nation's communication systems, but despite partisan politics and big mo
Re:Broadcasting over Fibre... (Score:2)
I haven't yet seen a good proposal that would incorporate both government control of the pipes and opportunity for multiple providers to compete to offer services on the same pipes.
The other big problem I see is potential for abuse. It's hard enough keeping my packets private with a layer of separation betwe
Re:Broadcasting over Fibre... (Score:2)
In addition, have you seen the numerous articles on slashdot in the past year discussing how Verizon wants to have tiered pricing for different priorities for packets? This WILL have a direct effect on how we experience the internet.
Finally,
Shallow (Score:5, Insightful)
This article was broad, but shallow. It buys into and repeats a whole lot of common misconceptions. For example, it phrases the net neutrality debate as wanting to charge different prices for "complex" and "simple" data, using VoIP and e-mail as examples. This is completely wrong. This is about charging money to people who are not your network peers for not intentionally slowing down traffic from particular, wealthy, people, groups, or organizations despite the fact that that traffic is otherwise identical to other traffic. Networks 5 peers away want to extort money from google for not intentionally crippling traffic to them and not to MSN search or Yahoo.
They also parrot the whole DRM as an anti-piracy measure. Everyone knows it fails miserably in that area. It is a content access control, so they can use differential pricing using regions and so they can charge you for the same content for different locations and devices. Anyone can point a camcorder at a TV screen and then upload it to the Web or make DVDs. Then, the masses can download it or buy it. What they can't do is easily move music they paid for from their Creative player to their iPod, car stereo, and CD player.
It is pretty sad that marketing dollars can speak loudly enough that even supposed technically competent reporters just spew out the same crap that they have heard over and over again. What ever happened to critical thinking and investigation?
Re:Shallow (Score:2)
It's pretty simple, journalists are being lobbied the same as congresscritters. Some of them begin to repeat sensationalist claims about hundreds of billions of lost dollars (from the industry that barely gets 10b a year in total) or starving artists robbed by thievi
Let me be the first to say... (Score:4, Funny)
"After years of benign neglect, the Federal government is finally involved in the Internet -- big time."
Re:Let me be the first to say... (Score:3, Insightful)
Question... (Score:4, Insightful).
My question is this, if it's simply about building and upgrading networks and the costs will be ultimately be passed on to the customer, why not just raise rates to those that purchase bandwidth accross the board? Why add the overhead of lobbying Congress to COMPLICATE the process of selling bandwidth?
Re:Question... (Score:2)
My question is this, if it's simply about building and upgrading networks and the costs will be ultimately be passed on to the customer, why not just raise rates to those that purchase bandwidth accross the board?
The network market has two components. The core is a free market with a lot of competition, although heavily government subsidized. The edge is government enforced local monopolies and in no way a free market. The edge does not really compete so they charge very high rates compared to their cost
Re:Question... (Score:5, Informative)
Not at all. The market has three components. The core is an oligopoly with only a couple of major players. They get paid either way. The end user edge is a bunch of local or regional monopolies or oligopolies with millions of users. The content provider edge is a bunch of local or regional oligopolies that rarely overlap with the end user edge.
As I understand it, traffic billing from one backbone to another is based on the balance of incoming versus outgoing connections. Making an outgoing connection costs money, while receiving a connection gets money back. The theory is that the content provider is not the one benefitting from the content. With advertising, that's not always the case, but it certainly makes sense from a network utilization perspective that the party that causes the traffic to be introduced into the network should pay for it.
If two networks are fairly comparable in terms of how many outbound requests they spew into the other network, they set up an unmetered peering agreement in which the two parties don't bother keeping up with who makes more requests. It's just easier that way. If the two networks are imbalanced, the larger (generally more backbone-ish) network generally gets more requests from the smaller one than it sends to it, and thus, the other network ends up having to enter into a metered peering agreement.
Now the problem is this: most content providers do not introduce a large amount of traffic into the backbones. With the exception of outbound email, almost all content providers return data in response to a request. Thus, ISPs with a higher percentage of content providers tend to have more favorable peering arrangements, while ISPs with a higher percentage of end users tend to have less favorable peering arrangements, since they generally produce the vast majority of requests. The ISPs that have a greater percentage of end users don't like this arrangement.
The solution proposed by largely end-user ISPs is that they should be able to charge the content providers themselves for preferential access to their users, and that companies that didn't pay would get lower speed access. You will note that those content providers are not customers of those ISPs. They are customers of a different ISP that peers with a backbone provider, which in turn peers with those ISPs. You should quickly see why this is silly.
A more fair solution would be for both ends of the communication to pay equally, as both are equal parties in the communication. In such a scheme, an ISP pays if either endpoint of a connection is within their network. This money is paid to the first backbone. Because the backbones are all considered somewhat equal and all pass traffic for each other, no additional transfers are needed. In effect, this would work the same way as the internet does now, only the backbone providers would get paid in part by both ends.
The net effect of such a design would be that content providers would pay more of their fair share of the cost of operating the backbones, while end users would pay a less disproportionately large share of the cost. The most important part of my suggestion here, however, is that ISPs should only be allowed to bill their customers and peers, not the customers and peers of other ISPs. In other words, I am in favor of net neutrality laws, albeit laws that are more carefully crafted not only to prevent the end user ISPs from following through on their threat but also to reduce the disparity between the proportion of costs paid by end users and those paid by content providers.
Re:Question... (Score:3, Informative)
Slight correction: the content provider edge does overlap significantly with the end user edge, but most ISPs tend to heavily favor either end users or content providers, depending on which market they primarily cater to. For example, Comcast is heavily biased towards end users, while AT&T is probably biased more heavily towards business (though admittedly less so since the merger with SBC).
Re:Question... (Score:3, Interesting)
Not at all. The market has three components.
Well, I suppose we could break this up any number of ways, and there is a lot of overlap in any classification. Lets just agree that some of the market (peering arrangements) looks like a poster child for free markets, while others, customer edge, are monopolized all to hell.
As I understand it, traffic billing from one backbone to another is based on the balance of incoming versus outgoing connections.
Actually is priced by transit (traffic from a peer goi
Perrilous time... (Score:5, Insightful)
What astounds me is how bad google, MS, etc. are at lobbying. It seems like google and MS should be winning and not losing (as my current perception leads me to believe).
Re:Perrilous time... (Score:2)
True dat! This very thought has been disturbing me for a while now. Exactly how messed up does the government have to be if the bald, pigheaded ignorance of a guy like Senator Ted Stevens seems do be winning out over the piles and piles of money of the likes of Amazon, Google, and Microsoft combined?
I am only half joking here. A lot o
Re:Perrilous time... (Score:2)
A cushy consultant job with the telecos after he retires from the Senate?
This is the part where....... (Score:2, Insightful)
Un huh (Score:5, Interesting)
Congratulations, this is the single most useless comment in a
Yes, more people should be aware of and care about this, but this is a ridiculous way to word it. Also in the news, more people have opinions on school choice than IPv6 adoption. Shocking!
Back to the issue at hand. Let's not delude ourselves into thinking that our elected representatives will have a say in this any more than any other issue. The reshaping of the internet will be done SOLELY by Microsoft, AT&T/SBC, Verizon, Google, Cisco, Amazon, Hollywood, and the usual suspects. They will be writing the laws and casting the votes. There is no reason to even pretend otherwise anymore. Sure they will be be doing this via proxy with the elected representatives, but those reps (almost without exception) have no clue what they are talking about and just repeat the talking points given to them by their corporate masters. These issues will be determined exclusively by how money and favors are allocated.
I know as Americans it feels better to pretend that corruption and corporate ownership are the exceptions in government, but to do so hurts as a nation. EVERY person currently in congress has been bought and sold to a special interest or company (no expections, don't even try to parade your favorite one out and claim them to be virtuous and pure, you are wrong). When it comes down to it, they will ALL vote they way they are told and the opinion of the voters matters not one bit.
Finkployd
Re:Un huh (Score:2, Insightful)
Welcome to America... the
Re:Un huh (Score:2)
Number of people who will be directly affected by a flagburning amendment in their day-to-day activities: roughly 0.
(note that I'll be seriously tempted to do the civil disobedience thing if such a stupid amendment was passed)
Number of people who may be directly affected by internet laws: roughly 50% of the US
Internet Regulation? (Score:3, Funny)
PLEASE LEAVE THE INTERNET ALONE. You will only screw it up, if you start messing with it.
Thanks,
Archangel Michael (on behalf of most of the Slashdot crowd)
AN URGENT TELEGRAM: (Score:2)
WORRY. DETAILS IN LETTER
Or so the introduction appears. The Gucci-clad evil people our out to steal the Internet (and Christmas).
"Reshape the Internet" sounds much like the recent "Great Internet plug-pulling by Congress" and the not so recent "Vote or Die!" attempts at fear-mongering.
Civilization Marches On (Score:3, Insightful)
We need more competition (Score:2)
Telcos are pushing hard (Score:2, Insightful)
And don't try to blame the Democrats. This is bought and paid for with large cash donations, the vast bulk of which go to Republican lawmakers, who close the loop by hiring K Street lobbyists as staff. You can try to deflect blame by suggesting that if Dems were in power they'd be
Mod parent up. (Score:3, Insightful)
Armies of lobbyists and lawyers go into the Rayburn building and across the hill to cow legislators. It's not a partisan issue-- it's a Jack Welch/We're Big And Here's Our Army To Prove It posture.
Look at where the lobbying dollars and perks are spent, and by whom. Then mod the parent up as he/she's absolutely on target. This isn't about common sense, this is about re-writing the Telecom Act of 1935 (as amended) and pulling back decades of consumer-focused legal decisions and legislation
Congress...peh.. (Score:2)
The solution is to remove them from the picture. Vote them out.
If they won't let themselves be voted out, kill them.
You think I'm kidding, what do YOU call someone who won't leave power?
A tyrant
Re:Congress...peh.. (Score:5, Interesting)
So, who do we have to vote in? (That are actually any better, that is.)
Different opinions, different priorities (Score:2)
Unfortunately, as long as there are more flag-wavers than geeks, the world will continue to spin the way it does.
REALITY: The Net Will Reroute (Score:3, Insightful)
In an interconnected world where China has more Net users than the US, and so does the EU, one country standing in defiance of the Net is like a small earthen dam trying to constrain the massive tsunami that will either go around it, go over it, or crush it beneath its massive weight of inevitability.
Only One Kind of Regulation/Enforcement Is Needed (Score:3, Insightful)
Oh, look. Online fraud is the only thing they're not planning on strangling in the crib. Shock, surprise...
Schwab
Name me one representative or senator with a clue. (Score:2)
The Internet's New Shape (Score:2)
One word: pretzel
Crap attempt to change the world. "No Limit" Label (Score:2, Interesting)
Smell this coming for years now (Score:5, Insightful)
It is about inevitable they will slice it up into something that looks like a combo of your cellphone bill and cable TV bill. You'll be seeing a large number of "nets" and be forced into "subscribing" to one or another-think a lot of different closed up walled garden type AOL experiences. And be paying through the nose to go outside that area-or be denied totally. And they'll be completely happy if 95% get herded into their control more, they'll pick off the other 5% at their leisure and when it suits their purposes. No one is completely leet enough to avoid it if they get a notion to mess up your day. No one.
Re:Smell this coming for years now (Score:3, Interesting)
Do the telcos want legislation from the bench? (Score:3, Insightful)
If Net Neutrality isn't addressed proactively then we will see it end up in the courts where some activist judge could potentially really mess up the internet.
The best thing that could happen at this point would be for the telcos to come out and openly debate the merits of their Tiering plans instead of using front groups and lobbyist, short of that the next best thing might be some form of legislation.
But the worst thing to do would be to do nothing and wait for lawsuits.
Washington? (Score:2)
Business (particularly, well-funded business) has always had the ear of our bureaucrats - they're called lobbyists. In general, the Telcos (and other communications giants) are very good at lobbying. As with any business, they are looking
You all do realize.... (Score:3, Insightful)
As important an issue as net nutrality is, and as much as is will affect the internet, it will hardly matter to people in say, the EU, where many lawmakers are moving away from internet regulation.
Just a point, is all.
The $200 Billion Broadband Scandal.. (Score:3, Interesting)
what we really need (Score:3, Informative)
I would like to see our government completely wiped out from top to bottom and start from a bunch of young people who actually do give a shit about our country and our future. There is a huge damn generational gap that is happening. All the old people are making decisions that they have no idea what the consequences will be or they just don't care completely because they will be dead by the time those consequences happen (ie. global warming, internet, pirating, etc.)
The problem with America is that there is too much business. Because people are rich, they seem to have the most pull, which is bullshit because being rich doesn't make you intelligent. Too many things get passed through our congress and our senate because these assholes don't read anything, why? because they are on their damn big ass boats fishing or doing something other than coming up with new ways to help society. I hope all of our politicians burn in hell if there is one...because they are all evil....every single one of them. No one has the balls to stick up for what is right any more.
You know, we could of have been atleast one step closer to getting a better energy source. You take the worlds top scientists and stick them in a lab and give them whatever they want, and you will have your new, cleaner, better energy. How do you think the atom bomb was made? exactly the same way. We could of spent that $300 billion it is costing us for the fuckin retarded ass war in Iraq for R&D of new technology to HELP society on a global level instead of hurting society. I will be damn surprise if humans will make it another 100 years because of the retarded people in high up places will do something like nuke another country, which will set off a huge train wreck through out the world. How do we have the power to wipe the human race over and over again, and the person at the helm is no other than the guy who choked on a pretzel, the guy who fumbles words constantly, the guy who says he will not change his path even though everyone says he is a moron and he is wrong, the guy who probably doesn't know what 10 x 10 is?
Something needs to be done. We really need a good revolution of our government. Even though it won't happen, we really need one. This is what our second amendment right is for, to stand up against this bullshit when our government gets out of hand. Hell I am sure some of our military would even fight for the people, well whats left of it here in the US. I honestly don't think America could take another huge attack on American soil, and it shouldn't. Too many people in America are comfortable in their life driving their damn H3 hummers and as long as they can have their gas we are alright. I won't even go into all the BS oil and how that is going to end. America better get its act together or it will end up a 3rd world country in no time. And it all starts now with this damn goverment we have. This government has shifted America in a dir
The article is full of telco propaganda (Score:4, Informative)
Yes, and if Lucy holds the football I can come running up to kick it. Telcos have spent *decades* saying "give us this break and we'll lay fiber', "give us that break and we'll lay fiber", then taking the money and doing nothing.
>abolition of the USF altogether -- but that seems unlikely, as that would impose an immediate and costly burden on many rural Americans.
The USF money is not accounted for and when rural areas get service the telcos raise the rates by the amount of the subsidy [pulver.com].
At least this one isn't telco propaganda:
>electronic versions of anonymous cash
That was the cypherpunk dream from the previous millenium, but if you look around at all the anonymous payment systems that used to exist they've all been shut down by the requirements of USAPATRIOT.
Re:You have to remember... (Score:2)
Wait, was that inartweb or intraweb? I know one has pictures of cats and Amazons, and the other is what you log into at work, but I always get them confused...
Re:Is it techically possbly . . . (Score:2)
Even if it were sensible, there is a lot hosted inside the US (e.g. Slashdot) that you might still want to access.
Who is John Galt? (Score:2)
(When you find him, let me know...)
Re:So what's the next wild frontier? (Score:2) | https://slashdot.org/story/06/07/11/1557214/how-washington-will-shape-the-internet | CC-MAIN-2016-44 | refinedweb | 7,168 | 62.78 |
RubyRdf
RubyRDF was an experimental bundle of RDF-related tools written for the Ruby programming language.
The project is now finished, unlike the code. There are now a number of other (more complete) Ruby RDF implementations. RubyRdf shouldn't be considered to compete with these. See the public-rdf-ruby list at W3C for discussions.
RubyRDF includes a parser (using either Expat or REXML XML parser), storage (via PostgreSQL or MySQL), manipulation and query (Squish2SQL rewriter or generic / in-memory query engine).
- Overview
- RDF database
- RDF query
- RDF parser
- Testing and Bugs
Nearby: RubyRdfDatabaseSetup, RubyRdfInstallationLog, WebDataInterfaceDesign, RdfPerlLib
Topics being explored with this codebase: EventDiscovery, RestaurantRecommendation, ThingsVersusTheirNames, PersonsVersusTheirDescriptions, RdfCalendar, FaqIdeas, JabberChickenEgg, SemanticWeb4ContentFiltering
What is RubyRdf?
This is a simple, experimental RDF system implemented in the Ruby programming language. It serves three purposes: to help me learn Ruby, to support an RDFWeb idea I'm prototyping, and to explore some design options for RDF APIs. This is not production-grade stuff. --DanBri
NOTE: This Wiki site is something of a ProxyTopic shadowing the 'real' RubyRDF page. But it's easier to edit and to involve collaborators with, so it is likely that the RubyRDF website will be slimmed down in favour of Wiki-based documentation. Hmm, I just coped the RubyRDF home page into this wiki. reworking now. --DanBri
The Resource Description Framework (RDF) provides conventions for data mixing and sharing using XML (document format) and URI (naming) technologies. RubyRDF in turn provides some utilities for reading, storing, querying and merging RDF/XML data. It uses SQL-backed storage systems (PostgreSQL and MySQL), includes a parser (for interpreting RDF's XML syntax) and interfaces for accessing parsed, stored and queried RDF data.
OK, how do I download RubyRdf?
Pretty rough, but available for the curious:
- pre-release tarball in progress
- work towards debian package.
- browse sources online.
What's new with RubyRdf?
Recent changes that may be of interest...
April 2003
- documentation cleanup (moving to Wiki for most of it)
- integrating RDF core tests for parser
- integrating RDF query test case machinery
- added rdf:nodeID support, see tests.
The rdf:nodeID fix is necessary background to hooking up the query components to the rdf query testcases being developed in the RDF Interest Group.
Any old news worth remembering?
News: 2002-03-20 - These tools were spotted on ruby-talk so I've created a RubyRDF entry in the Ruby Application Archive (RAA).
I've also been learning a bit more about the RAA data, the Rdoc ruby documentation tool (helped add RDF support into it) and other software description apps from the Ruby community ([swdoc/ rough notes and experiments]). A mini victory was getting Rdoc-based RDF queriable via PostgreSQL (see successlog). Nearby in the Web: a note I'm writing on Web services and RDF: 'Techniques for SOAP data aggregation and testing' uses these tools and SOAP4R to (eventually) show RDF query of data from the RAA SOAP service, merged with Rdoc. I've also downloaded and Rdoc'd 187 Ruby packages to see if we can do queries on things like "who has subclassed this class" across the entire Ruby community. In progress. (If we had unique identifiers for Ruby classes this would be pretty easy...).
News: 2002-02-27 - I did some more work on this! See [dataquery.html database and query support] document for details. This includes a re-coding of an RDF query to SQL filter from Libby Miller, so Ruby-RDF now has basic RDF query support (requires PostgreSQL database).
What is Ruby?
Ruby is an object-oriented scripting language that I finally got around to investigating this week. More information is available from the Ruby home page, as well as from sites like Ruby Central, where you can find an online book Programming Ruby and other introductory and reference material.
How do I use RubyRdf?
First bewarned this is a work in progress. Don't go flying spaceships with it...
To summarise. In Ruby-RDF you can:
- load RDF from documents in RDF/XML or NTriples syntax
- create, merge and query RDF graphs from within Ruby
- export RDF data as text documents in NTriples syntax
- more things I've not summarised here yet
Can you summarise the features without boring me?
(@@this needs update)
The API features the usual notions of Graph, Statement and Node based on the corresponding structures in W3C's RDF information model. A {[Graph } is an object that encapsulates some data, conceived of as RDF
statements, which we think of as the directed labeled arcs in our graph. A
Nodeis an object representing a 'resource' or 'literal' content in the RDF graph. Resource nodes may be blank or named with a URI; literal nodes have data content (text etc.).
There is also a simple XSLT-based RDF import facility, using Jason Diamond's XSLT RDF parser and the Template: Sabletron library]. It doesn't derference URIs or understand notion of a base URI yet, nor behave well if the support library is missing (todo: find out about exception handling in Ruby).
The basic idea with this API was to offer several flavours of interface, to see how they compare for application use.
- "statements matching" interface (Graph.ask)
- "graph navigation metaphor" interface (as per Mozilla)
- "node centric" interface (based on asking questions of nodes not graphs)
- Query language interfaces (SquishQL etc) and Web Services
Show me some example code! Something easy and useful please...
Removed (as was out of date) the example
todo: add RSS example here.
Status? What can I do with this thing now?
(WriteMe -- update this! point to tests as examples?)
There is a simple in-memory Graph implementation now. You can add data using tell() or query data using ask(). Not all of ask() is implemented yet. I've not started on the Mozilla-like API. There is not much by way of distinction between interface and implementation. The node-centric API works at a proof of concept level, but needs serious attention.
Any known bugs?
(update this / merge with stuff below)
There are more bugs than I can list here. Known problems:
- NTriple import doesn't deal with 'blank' nodes, ie. those without URI labels
- ...or even with literal text properly
- character encoding and internationalization issues haven't been explored
- The ask() basic query functionality is only halfway implemented (the useful half ;-)
- There is no error handling. None!
- There are no formal tests yet (except the NTriples roundtrip)
What're the plans for this package? It's gonna last forever and take over the world, right?
I might not do any more work on this. If I do, I'll be fixing up basic facilities (so it can be used) before worrying about efficiency, scalability, beauty or even full compliance with the specs. I might finish reading the Ruby docs first; if the current code looks like Perl, there's a reason for that...
All that said, the package is maturing nicely, 2001-2003, and the tests + debian packaging are giving me some confidence of its creeping utility. --DanBri
How does this compare to other node-oriented RDF APIs?
Other node-oriented RDF API experiments...
- Perl RDF::RDFWeb package
- plex rdfapi.py
- mnot's Sparta experiment
- orchard (@@ref)
What support does RubyRdf offer for database access and persistence of RDF data?
- in memory implementation (efficiency? lack thereof...)
- SQL-backed version(s)
- sha1 hashing of uris; is this a dodgy hack? probability of collisions w/ cut down sha1?
- RDBMS schemas
- PostgreSQL vs MySQL issues
- related work, swad-e report etc.
- sample code / tests
- RDF4R RDF/XML serializer (more info needed. API?)
Does RubyRdf support any RDF query languages? What support is offered? How is it tested?
RubyRDF offers facilities for querying RDF data using Squish, a simple RDF query language. Squish corresponds to a subset of the RDQL language, and was based on R.V.Guha's RDFdb query language as refined in Libby Miller's Inkling implementation. The general approach is described in the 'Enabling Inference' paper proposed to W3C at the Query Languages '98 workshop in Boston.
RubyRDF includes a parser for a textual representation of Squish queries, but also allows for queries to be composed through an API (and hence could support alternate representations of a query). Queries in RubyRDF, following the Squish approach, can be thought of as simply RDF graphs "with bits missing". The missing bits are annotated with variable names, giving the familiarly SQL-ish "SELECT ?age, ?name, ?height ..." that gave rise to the name "Squish". The results of such a query can be treated as either an RDF graph (the subgraph of the original which matched), or as a set of variable-to-value bindings. Both perspectives have their uses.
There are two query implementations in RubyRDF. The generic implementation can implement Squish against any RDF datasource that implements the most basic 'triples matching' API. There is also a more optimised SQL-backed implementation which (credits due here to Matt Biddulph and Libby Miller) rewrite a Squish query into a self-joining SQL query. This assumes of course a certain strategy for SQL RDF storage (see RDF database below).
rdf query testing
Aee #rdfig chat with libby. gqt.rb generates _genq.rb.
Work is on progress to use a common framework for RDFQueryTestCases in RubyRDF. In the meantime, we have:
Query tests have output like this:
ruby ./gqt.rb > ./_genq.rb ruby ./_genq.rb Loaded suite ./_genq Started ........F Finished in 0.016589 seconds. 1) Failure!!! test_query_8(TC_QueryTest) [./_genq.rb:311]: The actual (7) and expected (9 number of variables should agree 9 tests, 26 assertions, 1 failures, 0 errors
To do:
- need framework for comparing actual and expected query resultsets (including bnode issues)
What RDF/XML parser support is there in RubyRdf? What's the deal with plugging in an XML parser?
RubyRDF includes an RDF parser, written originally by Brandt Kurowski. This has been reworked a little by DanBri in pursuit of XML parser independence (it previously assumed Expat, can now run with REXML) and RDF Core spec compliance (now handles the rdf:nodeID construct).
Parser testing is based on the RDF Core test cases collection.
- expected.txt and .sh extract (from counting lines in the ntriple output files) the expected number of triples. we don't currently use these in our tests.
What's the status of SAX and SAX2 in Ruby? Surely that'd make your life easier here?
Very likely it would. There are efforts to wrap Ruby XML parsers in a common SAX/SAX2 interface. More information on this would be handy. (LinkMe/WriteMe)
How do I use Expat as the underling XML parser?
This is the default for RubyRdf's built-in RDF parser.
For XML parsing in Ruby, one uses either Expat, wrapped using xmlparser or the pure Ruby rexml package.
XMLParser is packaged for Debian as 'libxml-parser-ruby'. There is no MacOS X Fink package for yet, however it does install smoothly, and the underlying Expat parser is packaged in Fink (as 'expat').
Can I use REXML, the pure Ruby XML parser that's being bundled with Ruby 1.8+?
Sorta. RubyRdf contains some code for wiring it in, but the namespace support DanBri added is rough (ie. broken) and (worse) no tests are written to show up the problem. This was a train-journey hack.
The pure Ruby REXML parser is available as the Debian package 'librexml-ruby'. See pack/tests/syntax/ for experiments in using this instead of Expat: see rexmltest.rb
What I tried to do here, was rig things so that we use rexml instead of expat to generate SAX2 events. It is architected all wrong, and doesn't even keep namespace-context state properly. But the potential is there. I'm cleaning things up a bit. There is now RDFParser, REXRDFParser, and XMLParser. The latter subclasses the Expat XML code, and mixes-in generic RDF parsing functionality from RDFParser (see ruby mix-ins for context).
Can I use the xmlscan pure-ruby XML parser?
Not yet.
Another pure-ruby XML parser, claiming XML 1.0 compliance, multi-charset abilities, speediness, and tentative XML namespaces support. As of April 2003 it appears to be under active development.
I downloaded it but didn't quite get it working, error msg below. Could be a trivial mistake. --DanBri
lib/xmlscan/scanner.rb:487:in `initialize': failed to convert nil into String (TypeError)
How do I get PostgreSQL up and running?
You'll need Ruby's [DBI package] and the PostgreSQL extension library.
- in debian these are ...
- or build/install yourself
Something like this is needed on a Debian box using Ruby>1.6, since DBI etc aren't packaged yet:
ruby1.8 extconf.rb --with-pgsql-include-dir=/usr/include/postgresql/ --with-pgsql-lib-dir=/usr/lib/postgresq/l
Bugs, there must be bugs. Where's the bug list? tests? issue tracker?
See the bugzilla issue list for known problems. Or leave a scribble here.
A testing gotcha that got me: If we write "$:.unshift '../../lib/'" at the top of tests, so the local copy gets precdence, make sure to have the right number of ../../ in the path, else it may silently fail and test an older system-wide installation instead. Not sure how best to watch out for this.
what I'm currently doing is a bit of a hack:
$:.unshift '../lib/' $:.unshift '../../lib/'
...but seems to cover the common case of running it from from of two dirs.
This is all thoroughly tested, right?
Uhm, we're in a creeping professionalism situation.
RubyRDF uses TestUnit for tests, driven from RDF-described test case descriptions. Also UsingTestUnit in the Ruby wiki (for test/unit), and (very useful!) Ruby Specific Techniques for Testing by Hugh Sasse (based around TestUnit).
See also: Test First, by Intention- A code and culture translation from the original Smalltalk to Ruby, original by Ronald Jeffries, translation by Aleksi Niemela and Dave Thomas
A question from DanBri: If I anticipate many of these tests will fail, can I indicate this somehow? So that the really exceptional/worrying failures stand out...?
cout in irc writes, danbri: what we do is make sure all our bugs are entered into a bug database (such as bugzilla), and all our bugs have a bug number. if the test checks for a known bug, then the assertion message should include that bug number. if we fix a bug, then the assertion message includes the bug number, but also indicates that the bug is already fixed (so if it shows up again, we'll know).
How does RubyRdf's test machinery work? Any design issues to work out?
Current approach in RubyRDF is to generate (from source RDF/XML test data) some Ruby test scripts, and run those. It would be interesting to learn more about testing frameworks that were designed with data-driven tests in mind; doing code-generation for this seems like overkill.
See #rdfig notes on testing design: whether to do code-generation or not. I'm inclined not to, now, but unsure how to avoid having one large test() method. I guess one test, and lots of assertions, one or several per test in the manifest, might work. (...) Time passes, mind changes. After discussion on #ruby-lang, and experience with non-generated approach, I'm now more inclined towards generating Ruby test scripts automatically. It will allow the test machinery of RubyUnit to offer finer-grained statistics on pass/fail performance. --DanBri
Also in progress, same thing for RDF Core syntax tests: gcore.rb, re-written in codegeneration style. See output from tests. Todo: add more helpful output, eg text associated with tests.
More detail on tests is included alongside documentation for the relevant parts of RubyRDF.
Has RubyRdf this been packaged for Debian? for Fink?
RubyRDF is packaged for Debian (tentatively) but not distributed through the main Debian distribution.
see the debian maintainers guide for advice on files that belong in debian/ directory. Also the debian policy documentation.
There is an experimental Debian package. See notes and files for more info. There is also an attempt at fink packaging. The former pre-decides which directories to put its files into; the latter runs a configure/install script on the target box. Neither is well tested.
Here is where files get stashed by debian installer, as of Mar 20 2003
/usr/lib/ruby/1.6/RDF4R.rb /usr/lib/ruby/1.6/RDF4R.txt /usr/lib/ruby/1.6/basicrdf.rb /usr/lib/ruby/1.6/RDF4R /usr/lib/ruby/1.6/RDF4R/Consumer /usr/lib/ruby/1.6/RDF4R/Consumer/Simple.rb /usr/lib/ruby/1.6/RDF4R/Consumer/Standard.rb /usr/lib/ruby/1.6/RDF4R/Driver /usr/lib/ruby/1.6/RDF4R/Driver/RDFParser.rb /usr/lib/ruby/1.6/RDF4R/Driver/REXRDFParser.rb /usr/lib/ruby/1.6/RDF4R/Driver/SimpleData.rb /usr/lib/ruby/1.6/RDF4R/Driver/XMLParser.rb /usr/lib/ruby/1.6/RDF4R/Model /usr/lib/ruby/1.6/RDF4R/Model/Standard.rb
Here's how debian packages the rexml parser we use as a pure-ruby alternative to expat: apt-get install librexml-ruby ...should add this to our deb package metadata as useful optional package to accompany ours.
How do I use your experimental debian apt-source setup?
A quick howto:
Add the 'deb' line to /etc/apt/sources, ie.:
deb ./
Note that this is AT YOUR OWN RISK! I'm new to debian packaging. It may make a mess (but I don't believe it will). --DanBri
apt-get update apt-get install rubyrdf-ruby
...also grab these xml parser packages (not sure if they'll be auto-included)
apt-get install librexml-ruby apt-get install libxml-parser-ruby apt-get install libdbi-ruby apt-get install libdbd-pg-ruby libdbd-mysql-ruby
after which rdftest.rb should work on .rdf files. Tell it which file you want using --rdf= commandline switch. (hmm I think I broke this under Ruby 1.8, but we didn't package this for 1.8 anyways...)
Another test app to try: ayftest.rb, a tiny RDF harvester.
...you need to install one of the xml parser packages by hand too: (try both, you can choose which with --parser=rubyexpat or --parser=rexml). The apt-get lines above do that. At some point I'll fix the dependencies so this happens automatically.
How would I go about testing your early Debian packaging attempts?
for alpha-test 'volunteers', ie. Libby.
help needed:
nearby: RubyRDF homepage | Debian info
Alpha Tester notes and scribbles: If you try it, leave notes or links to more info here. thanks --DanBri
trying to build packages on other machine, remembered that hard codes a full path on my machine. The makefile should generate config.save instead. TODO. DONE! I think. Some ruby script spits it out now. See Makefile.
Libby's notes: rubyrdf alpha - debian install notes
Testing / installation hint: if I rebuild the .deb but don't change the version numbers etc., it is not enough to apt-get remove and then apt-get install the package. I need to do 'apt-get update' otherwise Debian may used a cached copy of the older .deb file.
TODO: find out where test cases should live, in Debian filetree layout. This also useful for Cwm, see CwmTips.
How do I install RubyRdf?
If you have a working Ruby interpreter, this should just work. Watch out for usual things; for example, you may need to edit
#!/usr/local/bin/ruby at the top of any scripts. Also, the require() call may need the directory path to {[basicrdf.rb }.
Nearby: Template: for Win32] (includes Expat and xmlparser)
You can grab a recent tarball from the Web and install at your own risk, see RubyRdfInstallationLog. Note that it fails a bunch of tests. It would be good if we could indicate which failures were (sadly) normal, versus which are signs of something bad. Maybe RubyUnit can do this? Advice welcomed!
So, er, what exactly is an RDF API?
(see also WebDataInterfaceDesign)
The code here implements some parts of a a basic RDF API and in-memory store for the Ruby programming language. It is a rewrite of a similar system I worked on in Perl. To understand what an RDF API is for, you probably need a little background on RDF and its relationship to XML and the Web, more than can be provided here. The [/RDF/ RDF home page] and [/2001/sw/ Semantic Web activity] provide some useful links. This brief document on RDF "striped" syntax may help, as might Tim Bray's excellent What is RDF? article. Assuming some basic familiarity with RDF, we still need to know what an RDF API might do...
So what is an RDF API? How does it differ from XML's SAX and DOM interfaces? RDF, after all, is written in XML syntax...
An RDF API provides a way for application authors to access data that is structured according to the W3C RDF information model, that is, as a directed labeled graph of "nodes and arcs". Each
Noderepresents something, either a "resource" (some identifiable thing, whether conceptual, physical or digital) or a "literal" chunk of data such as a string or number. Ruby fans, for whom (I'm told) numbers and strings are objects might wonder why RDF makes such a distinction. But it does, and RDF implementations consequently distinguish between nodes that are "resources" and nodes that are "literals".
The connections between these things, in RDF, are called "properties". They correspond to (binary) relations between nodes in the graph, and to the notion of attributes. In RDF we identify properties using Web identifiers, URIs. A URI (Uniform Resource Identifier) is a simple textual string (such as a URL), and provides a useful decentralised convention for naming things on the Internet. The neat idea in RDF is to use URIs to identify not just the things that we might want to describe using RDF, but also to identify the classes and properties that we use to describe them. So in RDF, each "arc" (or edge, or connection, or link) in the graph is named with a URI, and each "node" has a "type" which is some (URI-named) class.
So the RDF information model amounts to little more than a collection of triples (we call them "statements") consisting of nodes and (URI-named) arc labels. These are usefully thought of as forming a graph data structure, and most RDF APIs present themselves as interfaces to this graph.
We call these triples "statements" in acknowledgement that RDF content is supposed to be meaningful, to say something about the world. RDF data corresponds to a set of claims, ie. statements, about the named properties of named objects, where the names are written using URI syntax. An RDF API will offer applications an interface to objects that model the world in these terms, typically allowing data to be added, or questions to be asked of the Graph and Node objects.
So the reason we have RDF APIs, in addition to pure XML interfaces such as SAX and DOM, is that there are many mappings of RDF graphs into XML documents. By coding to an RDF API instead of to an XML API, we can set aside the detail of how our RDF is written, and deal directly with interfaces that care about the content of the RDF. In other words, we can have APIs that load XML/RDF data, and expose an interface couched in terms of "nodes and arcs" (objects and their relationships), rather than in terms of the XML document structures that encode this data.
It should be clear by now that the notion of 'object' is serving at least two purposes. Ruby (and other programming languages) present programmers with objects (that have properties and methods that receive messages). RDF presents programmers with a network of objects (nodes in a graph, each node representing some "resource" or thing), connected by directed, labeled arcs. Somehow we need to represent the latter using the former. This becomes interesting, since both Ruby and RDF have the notion of a class hierarchy, and ways of representing things with properties. The Node-centric RDF API outlined below explores one trick for reflecting RDF's notion of property into Ruby's notion of (missing) methods.
There is a third sense of the word 'object' that should be mentioned at this point: in RDF, the three parts of an RDF statement are called the "subject", "predicate" and "object". The subject is the node whose property is being described, the predicate is the type of property, and the object is the value of the property. To complicate things further, there are sometimes nodes in the graph corresponding to the types of property (such as 'worksFor') and sometimes even for so-called "reified" RDF statements, representations of statements and their component parts, ie the subject, predicate and object. Such complexities can largely be ignored for now; but they're worth mentioning as they are reflected in the basic RDF API. For example, our Graph object allows you to list all the subjects, predicates or objects in the graph. More details on this to follow.
In Ruby, everything is an object. In RDF, everything is a "resource", and is described using the RDF information model. This simplifies the world of Ruby programmers, and simplifiers the world of RDF programmers too. RDF offers a consistent approach to representing a lot of different kinds of data. Our goal here is to find some practical conventions for exposing that data to Ruby applications.
What RDF API design issues need more attention here?
A bunch. It'd be good to sync with the Cwm/SWAP and rdflib designs, since Ruby and Python are close enough... and many of the same issues have cropped up.
I like having nodes and graphs loosly coupled: you can change the graph that a node is attached to. I like the current (intended if not yet verified -- I think there may be a bug here) behaviour of only having one node object exist per URI or literal. But I don't think these two approaches are working well together. The nodes that come back from querying a graph, when new, are attached to that graph. When they're not new, we get counter-intuitive behavour.
The ask() facility on a Graph (and possibly on remote web services, which may share this interface) currently takes only a simple 'match this triple' argument. I'd like to be able to ask a Graph a more sophisticated query, eg. pass in SquishQL expressions and get back a table of bindings. Should the name
ask()be reserved for this more ambitious use? How to offer multiple ways of querying the graph?
It's handy having Node, Statement etc., but sometimes these are overkill. We should be able to use simple string URIs and literals in a number of places that currently expect structured objects, eg. adding triples into a graph.
Indexing: the Graph object currently maintains a couple of indexes (@fp and @bp). Since the ask() method returns a graph (basically a collection of statements) as the result of a query, concern is that we're going to a lot of expense creating a rather transient graph object, indexing its contents etc.
Provenance: I want to keep track of where statements came from, implement aggregation of multiple graphs into a virtual database etc.
Query interface: should be able to add a SquishQL query interface easily enough, though only implementation currently will be remote SOAP web services.
Got any hand links to more Ruby resources / background materials?
Sure. These are handy...
- Ruby home page
- Write Ruby, Be Happy!- A Language to Bring Back the "Joy of Programming", by Dave Thomas and Andy Hunt
- RubyUnit, a simple testing framework for Ruby.
- Ruby FAQ (method invocation question), used for Node API
- "DaveRamblings" wiki-post, on Ruby, metadata, RDF, P2P etc (RubyGarden)
- Liber, another RDF system in Ruby. Looks interesting, especially the portal-like Web interface layer (see also SourceForge project page)
- Ruby XML site
- IBM developerworks article on Ruby
- A Japanese translation of the RDF Model and Syntax spec is available; note that the RDF Core Working Group are fixing some bugs in the spec, so check the RDF Core pages too. ([/RDF/translations RDF translations page])
- SOAP4R is a SOAP implementation for Ruby (useful for talking to remote RDF services)
- Sablotron Module for Ruby (the XSLT processor developed by Ginger Alliance)
- Ruby QuickRef
Realtime chat interfaces? What's available?
- for IRC, there is rbot, but that's more of an application with plugin framework than a library (LinkMe)
- for Jabber, the Jabber4R library is wonderful. (I'm up and running in seconds, with no problem. --DanBri)
Ruby Debugger
- see the pragmatic programmer guide
- and the ruby quick reference.
- faq entry
- wiki notes on debugger use in emacs
M-x load-library rubydb3x.el M-x rubydb
Troubleshooting
The xmlparser/sax library needs patching to work in Ruby 1.8. From Yoshida Masato:
Dan Brickley <danbri@w3.org> writes: > /usr/local/lib/ruby/site_ruby/1.8/xml/sax.rb:343: warning: undefining `initialize' may cause serious problem Apply the following patch: RCS file: /Users/yoshidam/.cvs/xmlparser/lib/xml/sax.rb,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -u -r1.1.1.1 -r1.2 --- sax.rb 2003/03/12 05:54:42 1.1.1.1 +++ sax.rb 2003/03/12 06:38:21 1.2 @@ -339,9 +339,7 @@ end module Helpers - class ParserFactory - undef initialize - + module ParserFactory def ParserFactory::makeParser(klass) if klass.kind_of?(Class) klass.new | https://www.w3.org/wiki/RubyRdf | CC-MAIN-2016-36 | refinedweb | 4,945 | 65.22 |
Now we're going to use a large and messy data set from a familiar source object and then prepare it for analysis using Random Forests. Why do we want to use Random Forests? This will become clear very shortly.
We will use a data set of mobile phone accelerometer and gyroscope readings to create a predictive model. The data set is found in R Data form [1] on Amazon S3 and raw form at the UCI Repository [2] The data set readings encode data on mobile phone orientation and motion of the wearer of the phone.
The subject is known to be doing one of six activities - sitting, standing, lying down, walking, walking up, and walking down.
Our goal is to predict, given one data point, which activity they are doing. We set ourself a goal of creating a model with understandable variables rather than a black box model. We have the choice of creating a black box model that just has variables and coefficients. When given a data point we feed it to the model and out pops an answer. This generally works but is simply too much "magic" to give us any help in building our intuition or giving us any opportunity to use our domain knowledge.
So we are going to open the box a bit and we are going to use domain knowledge combined with the massive power of Random Forests once we have some intuition going. We find that in the long run this is a much more satisfying approach and also, it appears, a much more powerful one.
We will reduce the independent variable set to 36 variables using domain knowledge alone and then use Random Forests to predict the variable ‘activity’. This may not be the best model from the point of view of accuracy, but we want to understand what is going on and from that perspective it turns out to be much better.
We use accuracy measures Positive and Negative Prediction Value, Sensitivity and Specificity to rate our model.
Since we have 563 total columns we will dispense with the step of creating a formal data dictionary and refer to feature_info.txt instead
Initial exploration of the data shows it has dirty column name text with a number of problems:
%pylab inline import pandas as pd df = pd.read_csv('../datasets/samsung/samsungdata.csv')
Populating the interactive namespace from numpy and matplotlib
We want to create an interpretable model rather than use Random Forests as a black box. So we will need to understand our variables and leverage our intuition about them.
To plan the data exploration, the documentation of the data set from the UCI website [2] is very useful and we study it in detail. Especially the file feature_info.txt is very important in understanding our variables. It is, in effect, the data dictionary which we have avoided listing here. Also the explanation for terminology which we use is in feature_info.txt. So going through it in some detail is critical.
Do each of the above data cleanup activities on the data set. i.e.
The major value of this data set is as follows
It teaches the implicit lesson that
So this particular data set may seem a little techy but it could easily be in the direction of bio, or finance or mechanics of fractures or sports analytics or whatever - a data scientist should be willing to get hands and mind dirty. The most successful ones are/will be the ones that are willing to be interdisciplinary.
That's the implicit lesson here.
Aside from understanding what each variable represents, we also want to get some technical background about the meaning of each variable.
So we use the Android Developer Reference [3] to educate ourselves about each of the physical parameters that are important. In this way we extend our domain knowledge so that we understand the language of the data - we allow it to come alive and figuratively speak to us and reveal it's secrets. The more we learn about the background context from which the data comes, the better, faster, and deeper our exploration of the data will be.
In this case see that the variables have X, Y, Z prefixes/suffixes and the Android Developer Reference [3] gives us the specific reference frame with which these are measured. They are vector components of jerk and acceleration, the angles are measured with respect to the direction of gravity or more precisely the vector acceleration due to gravity. We use this information and combine it with some intuition about motion, velocity, acceleration etc.
So we dig into the variables and make some quick notes.
Before we go further, you'll need to open a file in the dataset directory for the HAR data set. There is a file called feature_info.txt. This file describes each feature, it's physical significance and also describes features that are derived from raw data by doing some averaging, or sampling or some operation that gives a numerical results.
We want to look at
a) all the variable names
b) physical quantities
and take some time to understand these.
Once we spend some time doing all that, we can extract some useful guidelines using physical understanding and common sense.
Figure 1. Using a histogram of Body Acceleration Magnitude to evaluate that variable as a predictor of static vs dynamic activities. This is an example of data exploration in support of our heuristic variable selection using domain knowledge.
In dropping the -X -Y -Z variables (cartesian coordinates) we removed a large number of confounding variables as these have information strongly correlated with Magnitude + Angle (polar coordinates). There may still be some confounding influences but the remaining effects are hard to interpret.
From common sense we see other variables -min, -max, -mad have correlations with mean/std so we drop all these confounders also. The number of variables is now reduced to 37 as below.
Note to reviewers - we do some tedious name mapping to keep the semantics intact since we want to have a "white box" like model. If we don't we can just take the remaining variables and map them to v1, v2 ..... v37. This would be a couple of lines of code and explanation but we would lose a lot of the value we derived from retaining interpretability using domain knowledge. So we soldier on for just one last step and then we are into the happy land of analysis
To be able to explore the data easily we rename variables and simplify them for readability as follows.
We drop the "Body" and "Mag" wherever they occur as these are common to all our remaining variables. We map ‘mean’ to Mean and ‘std’ to SD
So e.g.
tAccBodyMag-mean -> tAccMean
fAccBodyMag-std -> fAccSD
etc.
The reduced set of selected variables with transformed names is now (with meaningful groupings):
Now after all these data cleanup calisthenics we raise our weary heads and notice something pleasantly surprising and positively encouraging.
These variables are primarily magnitudes of acceleration and jerk with their statistics, along with angle variables. This encourages us to think that our approach of focusing on domain knowledge, doing some extra reading and research and using some elementary physical intuition seems to be bearing fruit.
This is a set of variables that is semantically compact, interpretable and relatively easy to reason about.
We can do another round of winnowing down the variables, because we might have a feeling that 37 variables is too many to hold in our mind at one time - and we would be right. But at this point we bring in the heavy artillery and let the modeling software do the work, using Random Forests on this variable set.
[1]
[2] Human Activity Recognition Using Smartphones <
[3] Android Developer Reference
[4] Random Forests
[5] Code for computation of error measures
from IPython.core.display import HTML def css_styling(): styles = open("../styles/custom.css", "r").read() return HTML(styles) css_styling() | http://nbviewer.jupyter.org/github/nborwankar/LearnDataScience/blob/master/notebooks/C2.%20Random%20Forests%20-%20Data%20Exploration.ipynb | CC-MAIN-2018-26 | refinedweb | 1,334 | 59.53 |
ImpWiz-UserDefined-File
If the data files you wish to import cannot be imported via the Import Filters ASCII or Binary files options, you can write your own Python or Origin C function to import the files.
Python code can be used to import a user-defined data file. A rough example of such code is presented below. The most important point about this code is that the target worksheet will be activated prior to the code being called by Origin. Additionally, the fname$ LabTalk variable will be populated with the full path and file name of the current file to import. Please read the code comments to better understand what needs to be done in the Python code.
import originpro as op
import pandas as pd
# Function reads file into a pandas DataFrame.
def read_file(file):
df = pd.DataFrame()
with open(file, 'r') as f:
line = f.readline()
while line:
# Put your code here to parse the line in the file
# and then append it to the DataFrame.
return df
# The file chosen by Origin import filter is placed into the fname$
# LabTalk variable. Must bring it into Python. Don't specify $ in name!
fname = op.get_lt_str('fname')
# Read the file into a pandas DataFrame.
data = read_file(fname)
# Returns the active sheet.
wks = op.find_sheet()
# Add DataFrame to sheet starting at first column.
# DataFrame column labels will become worksheet column long names.
# Origin automagically sets column format based on DataFrame data types.
wks.from_df(data)
After creating the code to handle the importing, you can use it as follows:
You can develop your own Origin C function to handle the importing user-defined data files by creating an Origin C function in an Origin C file.
The prototype of Origin C the function must be either one of the following:
After writing a function to handle the importing and saving it to an Origin C file, you can use it as follows: | https://www.originlab.com/doc/Origin-Help/ImpWiz-UserDefined-File | CC-MAIN-2021-25 | refinedweb | 323 | 64.3 |
React Native Animation Tutorial With Example
React Native Animation Tutorial With Example is the today’s leading topic. The recommended way to animate in React Native for most cases is by using the Animated API. It is a basic demo app. in which we move the square from top to bottom with animation. This example is Kickstarter for React Native Animation, and complex cases will be covered in the future. But right now, we start our project by installing the React Native using Expo.
If you are not familiar with the expo, then I am suggesting you that first check this tutorial on How To Setup React Native Using Expo. It will help you to set up expo and you will up and running with React Native on your physical device.
React Native – The Practical Guide
Content Overview
React Native Animation Tutorial With Example
Now, if you do not want to use expo and you have to create a project and test in Simulator or Emulator, then you can type the following command to install React Native on Mac. If you are using Expo, then you can skip the first step.
#1: Install React Native.
Type the following command.
react-native init AnimationApp
Go into the project.
cd AnimationApp
Now to open the app inside our iOS Simulator, type the following command.
react-native run-ios --simulator="iPhone X"
#2: Animations With React Native.
There are two kinds of Animation system in React Native.
- Layout Animations
- Animated
#Layout Animations
In Layout Animations system, it is easy to set up, and we do not have much control. Some parts of our application will also be animated, whether we have intended or not. So there is not much control over all of our components. So we do not use this kind of Animation.
#Animated
It is more complicated to set up, but it is perfect to create complex animations, and it allows us to handle the Gesture animations. The Animated library is designed to make animations fluid, powerful, and easy to build and maintain. Animated focuses on declarative relationships between the inputs and outputs, with configurable transforms in between, and simple start/stop methods to control time-based animation execution.
Three questions describe the whole animation system.
- Where is our primary object or item right now? So it’s X and Y position in the current scenario.
- Where is the Element moving to? So the place where we need to shift our element.
- Which element is we are going to move?
The answers to all above questions define the Animation system.
So the Animated Module consists of three things.
- Values: The Current XY values of an element
- Types: Which type of animation we will use like Spring, Timing, Decay
- Components: On which components like Text, View, Image.
#3: Create Square Animation.
Now, open the project folder inside your favorite editor. I am recommending that you should start using VSCode if you are not using already. For JavaScript development, it is the best open source and free editor out there.
Okay, now, create one folder in root called components and inside this folder, create a component called SquareAnimation.js and add the following code in it.
// SquareAnimation.js import React, { Component } from 'react'; import { View, Animated } from 'react-native'; class SquareAnimation extends Component { componentWillMount() { this.position = new Animated.ValueXY(0, 0); Animated.spring(this.position, { toValue: { x: 225, y: 575 } }).start(); } render() { return ( <Animated.View style={ this.position.getLayout() }> <View style={ styles.square } /> </Animated.View> ); } } const styles = { square: { width: 120, height: 120, backgroundColor: '#00BCD4' } } export default SquareAnimation;
So, here, First I have defined the View, and that view’s shape is Square based on its styles. So we are moving the square from top to bottom and see how basic animation works in React Native.
On componentWillMount() lifecycle method, we have set the Square position to 0, and then we start immediately moving our object to values of X = 225 and Y = 575.
Also, we have wrapped the View with the Animated.View. So we can see the animation from (0, 0) to (225, 575).
Animated.spring() function will take the first argument as an initial position and then takes the second argument to how far we need to move that object, and then we are called the start function().
Here, we are moving the Square View. So we have wrapped Squared View (View which has style square)with the Animated.View.
So, with the help of this.position.getLayout(), we can fetch the style of the previous and current location of the object, and we can see a complete animation.
We take as many elements inside <Animated.view>. As of right now, we have just picked the Square. But you can add as many items as you want.
Now, finally Add the SquareAnimation.js component inside App.js file.
// App.js import React, { Component } from 'react'; import { View } from 'react-native'; import SquareAnimation from './components/SquareAnimation'; export default class App extends Component { render() { return ( <View> <SquareAnimation /> </View> ); } }
Save the file and see the iPhone X Simulator. Refresh the Simulator again and again, and you can see that the Square is moving from top to bottom as per defined positions.
So this example is the Very Easy Implementation of React Native Animation Tutorial. We will create a Gesture based animation in the future post. So right now that is it for the React Native Animation Tutorial. | https://appdividend.com/2018/07/23/react-native-animation-tutorial-with-example/ | CC-MAIN-2019-18 | refinedweb | 903 | 58.08 |
exciting]
WILL THE PUBLIC BUG TRACKING GO OFFLINE?
If the plan is to kill it after IE8 goes RTM then I'm not submitting a darn thing.
WE WERE P*$$ED LAST TIME THIS HAPPENED!
Waiting on an [MSFT] official response before entering ANY bugs/issues.
Honestly, we're not sure yet what we'll do with the bug tracking after RTM. We want to make sure that any feedback channels we have that we keep alive are ones we can continue to respond to, so we'll see how well the system works before we decide. We've definitely heard the feedback that people want us to keep it alive.
Looks like the first beta of IE8 has just been announced . Download it here . There's a fact sheet too
Hey IE Team, I just installed IE8... very impressed so far! Just some observations:
1. Favorites Bar... when you hover over multiple folders on the favorites bar, you shouldn't have to click each folder to make them drop down... hovering should be sufficient if you've clicked on a folder already.
2. What is the "grayed out" effect of web addresses meant to serve?
3. When you use the "Add to Favorites" option within the Favorites menu, it would be more intuitive if it were like the "Pin to Start Menu" option rather than duplicating the folder.
4. Not sure if it was possible in IE7, but very awesome on changing the View for the History listing!
5. Love the "Activities" option and can't wait to see more!
6. WebSlices are a cool idea, so again I can't wait to see more!
7. Crash recovery seems to be working well too... I've had it crash twice, but always at times where I was mucking about with a lot of things at once.
8. Please give us a Download Manager!
9. NICE!!! at the bold RSS Feeds that are unread.
Performance does seem pretty decent so far, so I look forward to seeing the progression to the final product.
I'm sure I'll post more things as I continue to play.
I know it's policy to only release a few betas over a long period of time, but in the spirit of change, can we expect more betas more often? Like monthly?
GoodThings2Life,
Thanks! Re: web addresses, we'll blog more about that later too, but briefly, we highlight the domain name and dim everything else back to help users know where they are on the web. A common ploy for phishing attacks is to spoof the URL so it looks like a legit domain; this feature makes those kinds of attacks more difficult.
The release notes link does not work (redirects to;[ln];kberror&style=error&errurl=%2fdefault.aspx%2fkb%2f949800 )
Thanks, Rag. We're checking on it now.
Wait... you want to say there's now TWO iexplore.exe's MIRRORING EACH OTHER?!
I thought even dirtiest malware stopped using tactic long time ago... 0_o
Just a few minor things I'd like to note...
Why does ctrl+l open a dialog box when the address bar is all that's needed?
The "second" menu bar on the tab bar wastes a lot of space I think. A help button when there's already a help menu, a 2nd Tools, which is ??almost redundant with the 1st... Speaking of which, why is it that the 1st menu bar doesn't have icons next to listed items but the 2nd one does?
Also, that new mail button, if it could be configured with webmail that'd be nice.
Thanks guys for keeping the progress up.
"Real browsers work on any platform" - adding W2K could help you to find obscure issues with seriously limited memory and bandwidth. Just an idea.
Nice beta, but I already found something:
The text selection tool is very buggy.
Examples:
If you select some text and drag the cursor over some whitespace the selection is inversed.
If you select some text with list elements (e.g the article on this page) the elements disappear (or is this a feature?)
Text selection is generally slowish and flickers.
Anyways, can't wait for the final
Just wanted to congratulate you guys on this beta release. Time to make a fine browser - together!
Keet it up!
~
Hi, I just fixed the link to the release notes. Thanks for letting us know.
Kay, text selection and editing are definitely works in progress in the new engine.
Great work guys, I'll bet you $100 that Mozilla rips the domain syntax coloring.
I like IE8 so far. Problems I noticed:
- PNG gamma correction / color correction is still not supported. As a result, png graphics display darker then they normally are. Simple test case: make a html page that displays color #123456 as the background, make a 100x100 png image of the same color, and put it on the webpage: the difference between the two should be clearly visible.
This has been an issue since IE6. Supporting all these web standards is awesome but a simple png file can break the graphics on your site because of incomplete support.
- memory usage. When closing a tab, IE8 does not release the RAM used by a tab. Or if it does, it doesn't do it properly. Eventually, after extended use, the process iexplore.exe racks up absurd amounts of memory usage.
This happened in IE7 as well, although it wasnt this extreme (got 110mb usage after 5-6 minutes of browsing - only checking 4chan, a few rss links and googling for acid2, closing the links thereafter only freed up a few megs from the 110).
- huge TABLEs. These loaded slowly in earlier IE versions, because they were only displayed once the whole table was downloaded in the source (it was a nag when loading 500k tables back on dialup). This still happens in IE8. Of course its not much of a problem given that I'm running a 10mbit cable connection, but, with IE8 these tables not just load slowly, but scroll and display with extreme cpu usage as well. This is very, very annoying.
A simple test case:
John: ALT-D moves to the address bar like you want. In all the versions of IE I remember and in Firefox.
To the IE Team:
The other Acid2 site came back up, so when I attempted to test it with IE8 Beta 1, the face does render correctly, but highlighting the nose makes it turn blue. Is that supposed to happen or no?
I'm guessing this item installs over IE 7 and 6 ... and I just wanted to suggest that you give the users the option to install IE8 beta in a different directory from their current IE install.
Its important, because this is a no-risk strategy.
The user's current IE browser remains untouched and that gives users like me the confidence to take IE8 for a test drive, without worrying about the stress of uninstalling it and reinstalling IE-whatever if it doesn't run the way we like.
Very impressive guys. While IE7 was an OK release (I did like the streamlined UI), IE8 really looks promising already.
I noticed how Activities has been something you've guys developed for a long time. :)
And all the other latest goodies sound awesome too. But I'm still waiting to hear:
1. Skins support
2. Easier to make add-ons
3. Support for other OS's
4. Fancier looking zoom control (like Office 07')
5. Rendering on mobile devices (WinMo?)
6. Live "Tab" Thumbnails
7. Most of the goodies that's been available in IE7 Pro for a long time already.
8. Tabbing history.
9. Better inline search
10. View web page source code.
Still waiting. Keep up on the good work guys.
I have not been able to try IE8 because of an error being given one to two minutes after opening the application that says "Internet Explorer has encountered a problem and needs to close..."
The issue is with the "tfswshx.dll" component which isn't even present on my computer, which runs on Windows XP SP2.
Urgent help would be appreciated and prefered.
Thanks in advance.
@sonicdoommario: Yes, the "blue" nose is a feature of the test.
Hey IE team,seems that IE* has problems with 3 of my most frequently visited sites:
Neowin
El tiempo
and Facebook fo course
Good luck fixing this,but i see that it's a width issue.
why IE8 doesn't turn to standarts mode when xml proglog + xhtml 1.1 ?
@doug
tfswshx.dll is not an IE component. It's most likely an add-on that's causing the problem. Try running Start > All Programs > Accessories > System Tools > Internet Explorer (No Add-ons) and see if you still encounter this issue.
The nose is supposed to turn blue on hover to pass the test.
Bugs:
1.) New Tab (stop telling me its a new tab!)
2.) Prompt dialog:
a.) Not fixed (bug 109, bug 139)
b.) Now triggers a security toolbar and returns null because the dialog was supressed.
3.) CSS overflow-y - yikes! what happened there!
4.) Checkbox bug (bug 132) still broken
5.) Still can't drag a link to a new tab properly
6.) Still no option to open *ALL* new tabs at the *END* of my tab bar
7.) WinXP chrome/theme issues on select lists
8.) JavaScript Console... well, not quite, but at least the content is VIEWABLE now!
9.) javascript: urls on about:Tabs work (yeah!), but still broken on about:blank, or when using CTRL+L (new location)
10.) Still hidden options in IE status bar
11.) PNG favicons render pink background where ALPHA 100% transparency should be
12.) Scolling with mouse wheel causes some page content to flicker/hide.
13.) window has new global object/method "XDomainRequest" (is this an X-Domain XMLHTTPRequest object?
14.) Ditto for "globalStorage" ? does this cross domains? or pages within a site?
15.) Hmmm, "sessionStorage" ? can you clarify the difference between 14/15?
16.) document.compatible ? what is this property?
17.) document.onstorage ?
18.) document.onstoragecommit ?
19.) document.documentMode = 5 ?
20.) window.maxConnectionsPer1_0Server: 6 ?
21.) window.maxConnectionsPerServer: 6 ?
22.) A Whole whack of new properties on a FORM:
ariaBusy:
ariaChecked:
ariaDisabled:
ariaExpanded:
ariaHaspopup:
ariaHidden:
ariaInvalid:
ariaLevel: 0
ariaMultiselect:
ariaPosinset: 0
ariaPressed:
ariaReadonly:
ariaRequired:
ariaSecret:
ariaSelected:
ariaSetsize: 0
ariaValuenow:
More details on these new properties/methods please.
- application/xhtml+xml still not accepted
- acid2 test works on but not on
(firefox 3 pass it on both)
What happend to the option to Open tabs when IE starts again when you go to close it with open tabs?
I loved that option in IE7, but it seems to be gone in IE8 now.
That component is a Sonic BHO that is part of IE. It might be an IE8 issue hosting an old control, which is why we beta.
Start | Control Panel | Internet Options | Programs | Manage Add-ons and disable that particular BHO.
Restart IE and try it out. Thanks.
AlexGL, the issue's been fixed. I disabled the add-on after getting IE8 started without any add-ons present, and it works fine.
Is there on easy way to switch the version targeting on website that IE8 break? I mean if you don't have any control on the website.
I would like to see how much it can help. If there's no option in IE8 for thatr, how can I can do that with something like the Fiddler.
Looks good so far. Just curious. Are there any news regarding JavaScript events (e.g. addEventListener, capturing phase, domready, ...)? What's about things like getComputedStyle? HTML5 activeElement would also be great for web applications.
And yes, as mentioned somewhere above. PNG gamma correction is a must. Also in IE7, it was not possible to combine CSS filters e.g. grey() with PNG images. Same effects like using AlphaImageLoader in IE6 before. Any news on this?
Anything planned for the final?
Am I the only person interested in knowing why we can't write add-ons for Internet Explorer in .Net yet? It's 2008, I figured (incorrectly) that this would have been remedied years ago. Any target date/version for this ability?
Why is there a horizontal scrollbar on every single page I visit? That is really annoying. Also I tried out the meta switch at that works really slick. I will be using that on my site from now on until I can get the site working properly in IE8.
Oh also yahoo mail sniffs out the browser and rejects me from using IE8.....you might want to contact them, i mean they only have millions of users.
Just wondering where a Weather WebSlice is available at ... thank you.
Is side by side install available or will we have to go thru the Virtual PC process to run side by side installs. The beta of the "other" browser installs side by side without issue.
Would be great if tabs can be moved in "quick tabs" view...
I know it was never a supported control, and I know ASP.NET 2.0 replaces it with a better version, but many sites use the IE Web Controls () it seems the TreeView control screws up IE8 royally. In fact, it isn't rendered at all, and it seems to clear almost all of the page content! Sorry, I really don't feel like using the newsgroups to report this. Please allow us to post bugs on the connect site!
At first review, compat with our products looks refreshingly free of significant issues. THANK you.
An update to Windows Update to recognise this beta would be useful.
@Marshall
aria-* properties are new properties that allow the author to provide accessibility information. More info at
@Dinoboff:
If you want to do this on only one site
You can do this by use the IE Developer Tools.
Enable the developer tools by clocking on the button in the toolbar. Click on View->Change Compatability Mode and choose IE7 mode
In IE7 there was some weird behaviour with the cursor which would almost always display the text icon even where the cursor wasn't near any text, is that why the text cursor has been 'removed' in IE8?
Loving what I am seeing in IE8. The favorites bar available in full screen mode - awesome thank you!!!! I can finally use full screen mode!
Launching an entire folder from the favorites bar - again another request of mine making my life soooo much easier!
The new "blank tab" appearance -> Very nice, it actually has a finished look now.
Now I just have to figure out why Ctrl-Alt-Del's page doesn't render right so I can tell the right person the right thing. Works fine in IE7 emulation mode tho (which is also a nice new feature)
I'm liking IE8...
I'm having problems with the positioning of background images on anchor elements. It worked previously in IE6, IE7, Firefox, Opera, and Safari. I'm at a loss. It has to be something different with IE8. I'm using a valid doctype as well.
I'm impressed with the direction you guys are going. Great work so far.
REQUEST: Can you include subdomains in the address bar highlighting? A lot of sites include the subdomain as part of the site's branding ( for example: del.icio.us, script.aculo.us... )
Seems to be some funky floating div handling at and
and the emulate IE7 button doesn't seem to force emulation here lol
You guys are awesome. I surprised at how fast IE8 beta was released.
One feature that I had asked for when IE7 was released was the ability to middle click on the folders that are included in the Links toolbar and have them open in tabs.
You guys FINALLY added this and I thank you!
I've always been an IE fan and will continue to do so.
You guys are great!!!!!!!!!!!!
Woo Hoo!
Double Clicking in the address bar ACTUALLY WORKS NOW!
It correctly selects *JUST* that fragment!
Yahoo!
...but with compliments come complaints...
The developer tools still return (as does .innerHTML) DOM markup in horrible UPPERCASE Tag Soup with quoteless (and misssing) attributes!
I thought IE8 was the release where the DOM was finally fixed?!
Nice:
1. Startup time is good, even on a virtual machine.
2. The revamped addon manager features are nice, and performance on XP of the addon manager is also good.
3. More commands available on toolbar is nice.
4. Icons in search providers and in menus from toolbar buttons is awesome.
5. Delete browsing history box redesign (checkboxes instead of buttons) makes me wanna use IE more and more.
6. Developer tools are nice to begin with but still need to be as powerful as Firebug.
7. It's thrilling to see Acid2 being passed live.
Can be improved:
1. I hope that this being beta, some features are not implemented. I hope the 'Toggle emulation mode' button also stays and is not just during the testing phase.
2. Layout layout layout of the toolbars. Why can't MS offer the flexibility that IE6 provided in adjusting the position and layout of the toolbars?? What's the use of the lock and unlock functionality if users can't move the toolbars? Give us complete flexibility.
3. Increase the limit of the Temporary Internet Files cache to more than 1024 MB. Today's era demands it. Allow us to set it to a reasonable value around the size of a DVD (4-5 GB)
4. Is there some change made in the whole spacing between each and every UI element to make it a bit larger? If so, reduce it. Even when a new tab is opened, the font size there is also way too large.
5. Checking show large icons has no effect on the Favorites bar. Can you fix that?
6. On IE7 in XPSP2 at least, I use "Make available offline" by right clicking or properties. Hope this is not removed and replaced by RSS feeds.
7. Why not implement a resizable/adjustable search box?
8. A separator or more space between "Save as" and "Close" on the File menu would prevent users from accidentally clicking Close when saving. A keyboard shortcut for "Save as" too would be better.
9. Replace the cursor which appears when middle clicking and moving the mouse with a new smooth one, before you forget. Also the icon in the Properties of a web page. And the graphic on the Options tab in the Print dialog.
10. When closing IE when multiple tabs are open, where is the "Open these the next time" option? Hope it's not removed.
11. In the redesigned Page Setup dialog, I can't type a custom header/footer. Also include the editable text box.
12. Make the Save webpage dialog resizable.
13. The "Open new tab next to the current tab" option is gone! PLEASE BRING IT BACK!!
14. On XP, update the modem icon on the connections tab.
15. Document the settings on the Advanced tab in the Help file. Compiled HTML help can also use context sensitive help. If you dont want to use WinHelp, use CHM context sensitive help and add it to at least the advanced tab.
16. Do something to prevent Windows Explorer toolbars from getting listed in the IE toolbars list and vice versa.
17. Properly implement PNG gamma correction.
Wishlist:
1. Add support for embedded ICC V4 color profiles in images. Should be easier on Vista with Windows Color System.
2. Add HD Photo support.
3. Add a MIME type editor (what to do with a particular MIME type-Open/Save/Open with).
4. Even if a download manager is planned later, add the ability to group downloads in the single taskbar button.
5. Advanced JavaScript settings like preventing disabled context menus.
6. Add a password manager protected by the Content Advisor password or another master password.
7. Add a "Dont save now" option to the password saving dialog box or still better make IE check whether the logon was successful and only then save the password.
8. Show comprehensive page info in the properties of the page.
Please check
Safari3Beta: Pass
Firefox3Beta3: When about:config gfx.color_management.enabled = true, Pass
IE8Beta1: Fail
...and...
Can I disale [7] tool button ?
Great job so far. Thanks for really taking the time to listen to the community.
All my favorites do not work anymore. I can not use them and if i import them to another browser they are empty but i can see them in IE.
How can i uninstall the IE 8? How can i rescue my favorites????
Interesting, but there is nothing really within it to bring me away from firefox. The main problem I have with IE is that I can not simply block ads. You need an ad block extentision, but since microsoft makes so much money from advertisers I don't know if we will ever see one. Also not impressed that there are things to make it easier to use face book, windows live, and yet, nothing for myspace. I'll keep using firefox until IE includes in it such things as an ad block, flash block, and hey, how about even the ability to theme the ugly gui
Any chance of getting all betas as a virtual image a la the IE 6 image? I don't have a spare license running around and I'd hate to trash my IE7 to test IE8.
i'd like to see the text on the favorites button change to reflect the tab that's selected. so, if the feeds tab is selected, the button would show feeds, instead of always showing favorites.
Ooops, sorry. There appears to be one in the same place as the IE6 and IE7 images. For anyone else looking, it's at
It's a 438.6 MByte download with no bittorrent download :-)
How many people are in the "IE8 Technical Beta" program?
I checked out the site, and there are only 50 bugs entered so far.
There is definitely lots fixed in IE8 (more than I was expecting) but there are still several bugs from IE7 and before not listed.
Your microsoft connect site is a poor excuse for a bug reporting tool.
I've got you a nice little reduced test case about input type="checkbox" onchange behaviour; but after 37 screens of bullshit, disclosure, and prising into my personal details, I have no will to participate.
Do it better.
Gmail "Send" and "Save now" button makes IE8 crash on Vista
Is there anyway to get rid of the "Emulate IE7" icon from the command bar? Or at least move it to the opposite end of the menu so I can hide it? All the other commands appear to be movable/removable, why isn't it?
Thanks.
"Your microsoft connect site is a poor excuse for a bug reporting tool."
If there is one thing MS are doing very very badly it is this... I respect the IE team for wanting to get this right but they have not learned the most important lesson from IE7.
Please IE team, get a decent bug reporting system up and running ASAP, this ms connect system is as useless as trying to keep track of bugs on a roll of toilet paper with a leaky pen in a hurricane.
There are plenty of "very good" open source options for tracking bugs, swallow your pride and do yourselves a favour, track bugs properly.
Apart from that its nice to get my hands on the browser, so far I can see CSS hasn't been fully implemented, I'd suggest this should be a priority before beta 2, there goes 50% of the bug reports right there.
@lithven, @ST: No, the "Emulate IE7" button cannot be removed or moved in IE7 Beta 1. Configuration of this button will be added in future updates.
@Will Peavy: Stay tuned to the IEBlog for more info about why domain highlighting works the way it does.
@Neal: Yes, Yahoo is aware of their user-agent string issue, and they will address it.
@jessejacob: You've been able to write IE extensions in .NET since .NET 1.1/IE6 or earlier. See for some sample links.
@Marshall: Check out for more info on what's new in IE8 for developers.
Question:
Why is application/xhtml+xml *still* not accepted?
Why is SVG *still* not accepted?
One thing that bothers me are two CSS "errors" I've found that can affect a lot of websites.
The first one regardin negative margins and floats; the second and, I think, the most critical one, regarding links with display: block and parent divs.
Long story short: the first one (negative-margins) is something like: if you have two blocks floating besides each other, then a clearing div below them, but have one of the divs get a negative-margin greater than it's own width which makes it overlap above the other div, the clearing div ignores the div with the negative margin applied; but if the negative margin is less than it's own width, the footer div clears it properly.
The second one involves anchors with display: block on them. If you set an anchor to 100px width, 100px height, display: block and a border, then put the anchor inside a div, the area of the anchor that has no text nor border is NOT clickable... but if it's out of the div, it is. position: relative on either the container div or the anchor itself seems to fix this.
I've described and fixed both problems in my blog () but it's something that should not happen to begin with (having to add position: relative to a link in order for it to be clickable is just unnecessary in my opinion).
You can see both problems here: Negative Margin and float problem link problem showed (try to pass your mouse cursor over here: ) link problem fixed
The domain highlighting doesn't work well on domains like:
...
In the first case, the part to be highlighted should be oakham.rutland.sch.uk.
All sch.uk domains are broken down in this way:
schoolname.region.sch.uk
Thanks!
Nick
Because version of the browser is checked, with IE8, application of the patch cannot be executed in the home page of Windows Update.
Please,fix.
LORP Bug: Literal Overflow Right Position Bug
I have posted this bug here so please vote!
This bug also exists in IE7 though after installing IE8 I am no longer able to use my IE 5.0/5.5 stand alones to confirm how far back this goes. Here is a minimal test case with an explanation...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="" xml:
<head>
<title>LORP Bug: Literal Overflow Right Position Bug: Test Case by John Bilicki III</title>
<style type="text/css">
#body {
background-color: #000;
border: #fff solid 1px;
bottom: 4px;
left: 4px;
overflow: auto;
padding: 0px;
position: absolute;
right: 4px;
top: 4px;
z-index: 1;
}
#child_bug {
background-color: #222;
border: #777 solid 1px;
height: 20px;
right: 22px;
text-align: center;
top: 22px;
width: 200px;
z-index: 2;
#parent_bug {
right: 12px;
top: 12px;
.block {
display: block;
body, html {
color: #a7a68f;
overflow: hidden;
h1 {
font-size: 18px;
</style>
</head>
<body>
<div id="body">
<div>
<h1>LORP Bug: Literal Overflow Right Position Bug: Test Case by John Bilicki III</h1>
<p>Elements positioned from the right side are X pixels short of being correctly positioned, X being whatever the width of the scrollbar is.
The top right element should have 22px of space between it and the scrollbar which would be the exact same amount of space between it and the border of it's parent element.</p>
<div style="height: 2200px;"></div>
</div>
<div id="child_bug"><a href="#">IE8-B1 12-Right Child</a></div>
</div><!-- /#body -->
<div id="parent_bug"><a href="#">IE8-B1 12-Right Parent</a></div>
</body>
</html>
It seems that getting the location of a DOM element does not work (at least the ASP.NET Ajax code):
We want trying to be able to set the setting of the operational mode of IE, per the TAB window. When opening many TAB windows, because it restarts in order to change to the mode of IE7, it is inconvenient.
I got problem with many web pages like google maps or similar mapy.cz - i believe this problem is because theese pages thing that I have stupid old IE rendering so when I switch to IE7 mode it works OK as they got this hacked. The problem is, that this switching need restarting of IE, and this is the reason why i cannot use it as most of the webs are in IE8 mode problematic, and i'm not going to support IE 7 mode.
I wondered how to solve it, it will not be easy, but i would prefer to change the user agent info (and other common ways of browser detection), so it will mask as other browser, so that it can fully show its compatibility with standards without beeing afected by that ones who use e.g. conditional comments for IE => 7
Windows XP x64 SP2: The first level drop down menues (like page and tools) don't show any text. The IE7 emulation does not seem to work... Why no uninstall?
Bring the "Open these the next time" option back when closeing IE8 with tabs open PLEASE!!! I always had 7-8 tabs open in IE7 when for some reason i'd have to close it. That option helps ALOT! And now in IE8b1 I can't see it and it seems like it's gone, why?
Eli said: "Great work guys, I'll bet you $100 that Mozilla rips the domain syntax coloring."
On the contrary, Firefox 3 had this feature during the alphas (last year) but it was removed shortly after.
Hi there! Awesome work you've done.
I found some strange CSS problem:
1. using together the writing-mode: tb-rl; and overflow: auto; properties make the content disappear.
2. in some cases the header counter breaks. I found that this problem is comes up when the :before and :after is set on an other element and placed somewhere after the first <h1> element.
CSS:
h1 { counter-increment: chapter; counter-reset: section -1; }
h2 {counter-increment: section;}
h1:before {content: "Chapter " counter(chapter) ". ";}
h2:before {content: "Section " counter(chapter) "." counter(section) " ";}
span:before, span:after{content:'"';}
Cases:
a) this works well:
<span>Lorem ipsum</span>
<h1>First Chapter</h1>
<h1>Second Chapter</h1>
<h2>First Section of Second Chapter</h2>
<h2>Second Section of Second Chapter</h2>
<h1>Third Chapter</h1>
<h2>First Section of Third Chapter</h2>
b) counter breaks after first:
c) counter breaks after second:
d) etc... :)
e) Without the span:before, span:after{content:'"';} css property, all cases pass.
f) If we use this <span> before we start counting, the counter won't breaks even if we place another <span> after the first <h1> element. So this works well:
--------------------------------------------
wishlist:
- support <q> element :)
- support type="application/x-javascript"
- support border-radius, column-count, column-width, column-gap please please please!
Atta boys and girls!
Negative:
- Those dashed border lines around clicked href's which firefox has and we all hate them. They are also off in some links, like there is minus offset to the actual link.
- Text selection is somehow buggy, and get's inverted for no reason.
- Weird behaviour with floating div's, refreshing results in different positioning.
Positive:
- Well havent used it enough yet to find anything positive :)
Seems a bit scary how many websites are buggy with IE8, designers will have their work cut out for them! :)
I can't view any webpage after install ie8 ...
Very impressed with the beta - thanks!
My request:
Allow selected aspects of browsing hisory to be deleted when the browser closes. Firefox allows all cookies to be accepted, then deletes them on exit. For me, and I dare say most others, this is ideal. It allows privacy without breaking certain sites.
Unfortunately I have not enough time to thank you for the great work in increasing compatibility to web standards :) so I just go on with my request:
Please, *please* fix that odd behavior that the universal selector "*" matches on DOCTYPE and comments. The "*+html"-hack MUST NOT apply to IE 8!
'Always use ClearType for HTML' says you need to restart Internet Explorer. This is no longer needed I noticed.
Having to restart a system on a browser installation is wrong, totally wrong...
With sp3 bld. 3300 installed there are permanent problems. So I uninstalled IE 8 again.
Unfortunately...I could not even get IE8 to open fully without "IE8 has stopped working" error message...
Please, fix that. It's probably one of the most important issues, at least for me.
Most of the DOCTYPEs give a horizontal scrollbar at the bottom, even when it it is not needed.
When a new tab is opened:
The Address shows "about:Tabs".
a.) This Looks Dumb
b.) It isn't pre-selected, so when you type, you end up prefixing it rather than replacing it - Bug!
c.) "You've opened a new tab" in 500% size font is *NOT* required, and after the very first time seeing this, is INSULTING. We've been opening new tabs for years! (well, in other browsers at least)
What exactly triggers (e.g. where is the list) the fallback to Quirks mode from Standards in IE8?
I have a site, that rendered just fine in standards mode in IE7, that now triggers Quirks.
a.) It has a valid Doctype
b.) The HTML markup is well-formed (XSL generated)
c.) No references to document.all or other legacy IE-only JS
This is rather frustration because the rest of the site works fine, it is just 1 or 2 pages that fail.
In IE8, clicking the favorites star crashes the program. I tried doing a system restore to a point before installation and IE7 will not work. This is with XP
have been using it for a day now and our site does not render correctly I know for sure. Other than a slew of sites not displaying properly, no major problems as of yet
Can't wait for you to re-enable the "Open these tabs next time I load Internet Explorer" feature.
Also, along with this feature, Opera does an excellent job with this. When you open up Opera again, not only do you get all of your previous tabs, but you also still retain the history from your last browser session. You can hit the back button and go to a previously viewed page from the last time you used Opera. Brilliant!
The Windows Update site does not recognize this IE8 beta.
@Jeff: Did you try starting IE8 without addons?
In particular, see if you have an add-on called "DriveLetterAccess" enabled.
@Stanley, do you have the URL? Or can you send us a capture ()?
@Nick Lowe: Stay tuned to the IEBlog for more information about why domain highlighting behaves this way.
For the favorites bar, I believe it would be better to separate the favorites drop down and add to favorites icons/buttons onto another section of the page. I personally like it where it's at right now in IE7.
I use the favorites toolbar profusely each and every day and the more real estate I can have, the better.
Also, there is a weird problem with IE8 and Outlook Express 6.
I change the actual default read and compose fonts from Arial to Verdana, size 9 or "smaller."
In doing so, with IE7, every message via the newsgroups that comes through is displayed in the font Verdana, size 9.
Upon installing IE8, immediately I see changes in the font that is displayed within Outlook Express 6.
It is no longer Verdana. It overrides my own setting and changes the font to Times New Roman, size 12.
I have many more bugs. I am asking to be put into the technical beta so I can submit some of these valid bugs that I am finding.
Please consider me!
@John: Yes, WindowsUpdate is updating their site to support IE8. For now, click the Emulate IE7 Button, restart all IE windows, and visit WU. Sorry for the inconvenience.
I have some "autocomplete" like widgets that float a DIV absolutely above a page. This still works in IE8B1, but when I mouseover the DIV, the onmouseover event is triggered on TEXTAREA elements underneath my floating DIV (with 100% opacity, background-color: #ffffff;)
Note, it does not happen on INPUT type="text" elements that lie under the DIV (even though they have the same onmouseover event handlers applied.
I should also note, that it only occurs where whitespace around the nodes in the DIV occur. Thus links, and spans of text in the DIV will not trigger the event, but in the whitespace (margin) between elements it does trigger the event.
I wonder if the fix for Bug 229:
Accidentally exposed (e.g. propagated) additional events to the underlying elements.
PS I would file a proper bug report on Connect and all that, but I have yet to be granted permission to submit bugs.
TIA
Please, please do something to prevent IE to crash!
I use IE7 on Windows 2003 and IE6 on Windows 2000. They get crashed once a while on some web pages. Yesterday, a page even crashed Windows 2003. Could you do somthing to prevent this happen? Why can IE display an error message when something goes wrong instead of crashing itself?
I did a search in Google. I found that Javascript code is the cause in many cases and that Flash is another one. Now Microsoft is pushing very hard on AJAX which reply heavily on Javascript. We plan to implement AJAX .Net soon. Now I need to think about it again. I don't want our websites crash users' browsers.
Please do something!
Thank you
Bob
When you select some text in a webpage, the green arrow for Activities appears. Well, it does so in some webpages.
What makes the arrow appear/disappear?
- Correction on that bug report... it does happen on INPUT type="text" elements too, it is just a bit harder to trigger.
Humm well nice try
but as i was moving towards IE7 for better memory handling then FF2 u guys just messed it up
105 MB fro 5 tabs
and whats the story abt 2 iexplorer.exe
also y cant we move aroung all the toolbars and explorer bars as we like, its lots of space waisting, i guess the ability to arrange everhtign in one line and even pick and chosse what someones preference is will be good
What will be the result if i kill the shadow iexplorer.exe(the on which has less memory)
And please please please make the search(ctrl+f) an in line feature,
why in the world u need a popup and even F3 does not work to find next
will use it more over the week end to see what else is in store but u allready got a big list of issues to work on:) as i read thru this page
Thanks
sandy
Rather than limit new bug-reports and feature requests to a select few individuals, why not at *accepts* reports from other individuals, and make those available either to everyone or to the invited testers to make use of/rate?
Has anyone checked the rendering with right-to-left sites?
IE8 standards mode completely fails to render right-to-left sites. Right alignment sometimes ignored, positioned elements do not appear where they should, floats disappear, etc.... Some text shows squares although the encoding is correct. I use XHTML 1.0 Transitional and IE8 VPC image.
Does not render page just the back ground
Most of the forums on the internet that I visit regularly --- whenever I scrow using the mouse's scrow wheel and my arrow touches a live link, IE8 Beta 1 will automatically goes to the top of the webpage.
First of all, congrats.
IE8 Beta 1 got a serious problems with Arabic text while it doesn't seems to be rendering CSS direction: rtl; at all. i am working on new Arabic/English site and english version is excellent on IE8. are still working on this?
and by the way your Problems report tool is't working with me. (test domain)
The DPI model has changed!! IE8 scales all the images to the DPI settings of Windows. This is undesired, DPI until now was only applied to the fonts, this was OK because that way one could make text easy to read (nowadays displays have too small pixels!) without distorting the images. Is this a bug or is this gonna stay like this? If so is there any workaround or way to get the old behavior?
See screenshot and explanation here:
STACH Bug: Scroll Top Anchor Color Hover Bug
Please vote for the bug here...
Here is the minimal test case with details for those who would like to test the bug...
<title>STACH Bug - Scroll Top Anchor Color Hover Bug</title>
a:hover {
/* add/remove color, background-color, background-image */
color: #f0f;
text-decoration: underline;
<body style="background-color: #000; color: #a7a68f; height: 100%; overflow: hidden;">
<div style="background-color: #000; border: #fff solid; border-width: 1px; left: 40px; bottom: 40px; top: 40px; right: 40px; overflow: auto; position: absolute; z-index: 1; /*width: 90%;height: 90%;*/">
<h1>STACH Bug - scroll top anchor color hover</h1>
<p>This buig requires using <i>background-color</i>, <i>background-image</i>, and <i>color</i> CSS properties on anchor pseudo-elements.
When hovering anchors with these properties in an overflow element IE8B1 will scroll to the top of the overflow element.</p>
<a href="#">link test link test link test link test</a>
Another bug with CSS background images.
I have a DIV, with a background image (top left, no-repeat)... with padding-left to offset the text content away from the "watermark" image.
This works fine (in IE6,7,8B1) However, in IE8B1, when I select the text inside the DIV, the CSS background-image is re-applied (additional) to my selection background, with a new origin at the origin of my text selection.
Again, I would file a bug report, but have thus far been declined an invitation.
On Vista x64 SP1, after installing IE8 the fonts chosen in Windows Mail are no longer respected.
When reading newsgroups, the font is always Times New Roman, regardless of the font chosen in the Tools->Options->Read->Fonts.
I have always set this to Verdana, but now the font is locked to Times New Roman and cannot be changed. Not a big deal, but I hate reading in TNR.
I second the question of javascript events from Sebastian Werner.
I was under the impression that the standard.
@Mohammed: As noted in reply to your other posting, RTL is not yet implemented in standards mode. We're still working on it.
@John: The scrolling bug is known. We're working on it.
I just installed IE8 Beta and have problem with accessing this webpage (Norwegian newspaper). Every time I try to access this webpage IE8 crashes and gives the error message "Internet Explorer not responding". I even tried to disable all add ons to no avail....same problem. Uninstall..reinstall IE8...nothing works. Same problem.
Anyone here with the same problem?
Solution anyone?
@Geir M I just tried to open, and it loads fine for me.
hi again
this one is little strange
the menus in offical Microsoft are all messed up
is it some plugin i am missing it was workign in IE7
every link goes back to
and then evey menu is blank
and atleast in FF3 its atleast rending it as a page
I have found issues regarding IE8, but seeing that most of it are already discussed, I don't think I need to mention it. Let me mention this one again though:
It's such a memory hog!!
I found one VERY nice feature that you improved though: the search (ctrl+f) function.
Before, when I type a keyword and I'm already searching through the middle pages, and I click the page to scroll (review) it a bit then go back to Find and click next, it will start from the top! This is so frustating when there are many instances of the keyword you are searching in that page. I'm happy to see in IE8 that the moment you click next after reviewing (scrolling the page, selecting texts, etc...), it will start from where it left off. Nice! Thanks.
Cutting and pasting (when replying in forum websites) is very difficult. The cursor will not go where I point the mouse to go.
Pfft, not impressed.
IE8B1 crashes when trying to access
Google Toolbar, lastest available download.
Garbage Vista Home Premium.
An error has occurred in the Google Toolbar. Internet Explorer will close.
Location the error gives to find the dump file is empty.
I like my Google toolbar ... this needs to be fixed.
About the dashed border lines out of place bug I mentioned earlier:
If there is a centered div inside a container, the links work but the dashed line for the links are not centering, they are floating at the left. I dont'w know if this is a valid way to center stuff but still it's funny that the actual link is in the right place but the dashed line is not. Imho the dashed line should be removed, makes the browser look very 90'ish.
A sample picture:
live @ for example and everywhere on the internet.
Also as many have mentioned the PNG gamma correction is still missing, scrollbars appear even when not needed and some weird jump-to-top issues when scrolling some pages.
ps. sorry for my bad english!
I agree with pretty much everything above. Also the dropdown's and text inputs look horrible! They were decent in IE7, are the "new ones" temporary or will they actually look so bad in the final release? I also noticed that checkboxes and radio's dont have margin anymore.
The same old search is a big disappointment, just not as near practical as it should be!
Good job with everything else, and for hearing our comments!
Now that the dev preview beta of Internet Explorer 8 is out, you may notice some bugs here and there
Scrolling tables still don't work in IE8 Beta!
See:
Not many people need/use scrolling tables but one of our client abuses it, we are sick of doing Hacks, ie iframe, top.expression... when we could use simple css...
This page works in Opera 9.26, Mozilla Firefox 2 and Apple Safari beta 3.0.4 (for windows)
Css powered icons as per this article doesnt work in ie8 on any site making use of em. is one of many sites having trouble with ie8 and css icons.
Nice work otherwise with ie8, feels like a nice step forward.
I'm quite impressed with IE8b1, especially with the page zooming now working properly. There is however one thing I'd like to request:
- Add a shortcut key to reset zooming to 100%. Most browsers use Ctrl+0 (the number zero) here, and I think it would also be appropriate for IE.
i think Microsoft is making IE8 standards mode not work on purpose to then say "see, we should have defaulted to IE7 standards mode." Nice try guys, but we ain't buying it. Make it work already.
@MPZ: CTRL+0 to reset the zoom to 100% has been supported since IE7.
jun, your conspiracy theory doesn't even make sense. why not consider the far more likely case... they turned on standards mode by default, saw how much broke, and only THEN decided to make IE7 the default?
I installed IE8 beta yesterday, its perfoming really good (I am thinking about swithching back to IE from FF).
some sites did work well:
Gmail chat : wouldn't load (reminded me of Safari) - I hope this will be fixed.
some ADP internal site didn't work.
I've tried IE 8 for a little while now. Seems okay. Hotmail doesn't seem to work though; it hangs after I login. music.yahoo.com also doesn't act properly (rendering issues). IE also seems to use more memory now (though as a beta, I suppose that's not out of the ordinary). I like the auto-recover feature especially.
Feature request for Beta 2: incremental find (like in Firefox). Incremental find and Firefox 2.x's (non-automatic) recovery feature are the two main reasons that I stopped using IE for most purposes.
Pressing ALT + ENTER from the search box no longer opens the search in a new tab :-(
Also, the beta seems to interfere with highlighting of items on the Outlook 2007 Outlook today screen.
Is it true that application/xhtml+xml still doesn't work? I didn't have the chance to test it yet...
If so, then please fix this.
This should take only a minimum amount of time!
Also please make submitting bugs easier.
And thank you again for the great work so far!
Do a google search on MSFT, and then press any of the financial websites (google finance, yahoo finance, MSN money...) --- the webpage link (such as) will show up on the IR8's search pine.
I Installed IE8 in a VM. I was impressed how much works for Beta 1 product. I have had only a few sites that didn't render correctly and that's probably because they don't yet know how to handle an MS browser that's conforming to the web standards.
Reading a lot of those crash 'victims' above, I hate to say it but this is a Beta. And I would not be surprised to learn that they have a gazillion array of add-ons, toolbars and utilities blighting the browser. Those vendors are going to have to shape up and re-tool.
A small wishlist
- A download manager if not a fully implemented one, then at least the ability to resume a previous broken download. Not everyone has super-fast broadband to restart a big file.
- A built-in spell checker. Buyout IEspell if you have to or at least integrate it with the one included with Office if its installed.
- Edit User Agent String from a Toolbar menu or from Internet Options dialog. The IE7 button is fine if that is what you want and the 3 modes available in the Developer toolbar is also acceptable but I don't want to hack the registry to amend the UA string.
- Fully customizable toolbars. Yes I know you fixed the menu and search bars to look like a normal Windows Vista Explorer window but you broke your own design rules on so many of your own dialogs and windows in Vista, the one place where it would be most welcome, you locked it down! If you add the Menu bar and the new Favourites bar (which I like), there's just too much screen wasted.
@Anonymous: Using ALT+Enter to open searches in a new tab seems to work fine for me. How many search providers do you have installed?
@John: What's the URL of the page where you see this behavior in the search box?
@IT_Guy: IE will resume an interrupted download if the server sends the Accept-Ranges: bytes HTTP header. Note that you must ensure that your connection has been restored before re-clicking the download link.
As promised, I released a User-Agent switcher button:
When it's not in use, it consumes no resources. Note that this ONLY affects the User-Agent, and does not directly affect document mode.
>>>@John: What's the URL of the page where you see this behavior in the search box?
When you do a google search of "MSFT", "AAPL", or "RIMM" --- you will see six "little" links to "google finance", "yahoo finance", "msn money" "marketwatch", "cnn money" and "reuters" ABOVE a google-created stock price chart.
When I hit any of the 6 links or the google-created stock price chart, IE8's search pine will go from blank to the website's address.
For example, google search (my IE8's default search)on MSFT (both by google.com or by IE8's search pane) --- the first link above the stock price chart would be "google finance" (which would be).
After I hit the "google finance" link, IE8 goes to --- which is also the address that will show up on the IE8's search pane.
If I hit "MSN Money" (which is), the IE8's search pane will show --- which is different from the actual web address shown ().
@John: Ah, I see.
A bit of background: The IE8 search box will keep track of queries to your installed search providers. By convention, search engines use the URL parameter "Q" for their query.
However, in this case, Google is using "Q" for both the search query parameter, and also as the parameter that keeps track of all of your clicks on search results. They use a redirector () to log all of your clicks, and they put the url to redirect to in the "Q" parameter.
IE unfortunately has no way to distinguish between these two different uses reliably. Google could avoid this problem by using a different URL parameter name when tracking you.
whenever I try to open the favorites, IE8 crashes...
Also Dr. Watson Postmortem Debugger, so I have to log out and back in again
Otherwise, its great!
might want to improve the looks, but acessibility is more important
I still need one thing, for IE Developer Tools to be superior to the FireBug add-in to FireFox...
A Console where you can monitor all HTTP Requests/Responses sent back and forth. This is a huge pain when dealing with big AJAX apps. You need to monitor the requests inside the browser.
March
6th,2008
Ourdayhasfinally
come.CSScodersgotsomelovewithInternetExplorer7-us...
Ummmm - MAJOR PROBLEM
ie8 (vista 32bit edition) crashes every time i rightclick... i guess this isnt supposed to happen... and now i'm stuck on mff till it getz fixed!! PLEASE FIX SOON!!!!
HD photo support would seem a must.
It is a MS created format for god sakes.
Could you tag all your entries with the version of IE they are mostly about? This would show up in the "Tags" box on the right, letting us browse the IE Blog by the version of IE which interests us the most.
For example, all the current IE8 entries would include the tag "IE8". All old entries about IE7 would include the tag "IE7". Comparison articles between IE7 and IE8 include the tags "IE7" and "IE8". Earlier and later versions would include other tags as appropriate.
Another small thing: I tick the "Remember me?" box each time I come here. When I return, my details are correctly presented in the form fields. But the box is unticked again. Would be nice if it stayed ticked when I return to IE Blog.
wow - we've just spent months validating our site code, and going through hell and back trying to get our site to work in IE6 - We designed it for IE7 and IE6 put us through hell with the whitespace bug and other alignment issues because of the margin excess IE ads. Now we've finally got our template to work for IE7, IE6, and all of firefoxes perfectly - THEN out comes IE8 and our site is a mess! IE does not hold our <div> sections or tables in proper placement beacause if there are any images within the <div> tags or tables, IE 8 puts this horrible unwanted padding around EVERY single side of each image - we hate IE 8 already - Please just throw it away.
Asking people to install virtual machines to test different browser versions just makes it costly for us to do properly. I already have one machine for testing IE6 and another for Firefox, IE7, Firefox and Safari. There's no way I'm setting up yet another for IE8, at least until I'm forced to, and I'm not a big fan of being forced to do stuff by monopolists.
The real reason that it's like this is so that Microsoft can claim it's impossible to remove IE from Windows. The practicality of it is that it makes everyone else's lives a nightmare.
Come on guys, there's no non-monopolistic reason for not making browser versions able to install into seperate directories and run side-by-side on the same PC. When I can test at least IE7 and 8 on the same machine, maybe then I'll be happy to help test IE8. If everyone took this stand you'd be forced to do it yourself -- maybe then the costs would force a rethink about forcing stuff on people.
One thing we really need is,
1. "lock tab" so we can close all other tabs apart from the locked ones.
things i would like to see.
1. Better and safer plug ins.
2. Look at maxthon they have got some nice features.
3. Stop the crashes that occur when you have alot of tabs opened in ie7
4. Don't know if this is ie or adobes fault but i have done heaps of installs, and when i hover of flash content the browser just closes.
Asimov wrote:
"Asking people to install virtual machines to test different browser versions just makes it costly for us to do properly."
Microsoft is providing free virtualization software () and free virtual hard drive images () for testing. How exactly is this costly for you? It's not even particularly time consuming.
IE 8 looks great. But found a few issues, hope this may help(I still happen to see the same way as I see some sites on IE8). Whereas while using IE7 they rendered properly.
[quote]
[/quote]
Errrm; isn't it a little arrogant of MSFT to suggest that other websites should change the way they do things in order to fix a problem in a MSFT product?! I realise you guys see Google as a major competitor, but this sort of arrogance results in your customers being caught in the cross-fire.
No; I think you need to fix the issue in your product.
BTW: Don't take this as a 'flame', I'm actually really glad that MSFT are acting to get IE standards compliant - keep up the good work.
WE ARE ALL STILL WAITING FOR AN INVITE TO SUBMIT BUGS!
WAY TO BE TRANSPARENT AND PART OF THE DEVELOPMENT COMMUNITY!
Firefox users always brag about the number of extensions freely available. Why doesn't Microsoft sponsor contest(s) for the best *FREE* extensions with some *worthwhile* cash prizes? You'll throw $200 mil into facebook, why not spend a few hundred grand to create more reasons for people to use IE? It's a win-win situation for everyone.
I would liked to have see the ability to drag a link to an existing tab :/ Opening a new tab is fairly slow and you have to open sidebar again in new tab (I keep sidebar open with Onfolio or other things sometimes). This is one of the things I really like in Firefox.
Thank you.
@SimonL: It would be great if there were a reliable solution that we could undertake on our own.
Unfortunately, the only real alternative to the current heuristic is to invent a proprietary new tag that would allow a page to indicate "hey, this is a search field."
For the Internet Explorer 8 Beta, we’ve added an Emulate IE7 button to the command bar. It will help
Please note that google maps does not display proprly in Internet Explorer 8 Beta
Thanks for IE update.
1. My first feedback is google reader is all screwed up in IE 8. The left frame where folders are organized is distorted.
2. Can't seem to figure out how to repoen last session tabs when IE is re-started. I remember there being an option in IE7, but couldnt find the same in IE8.
Thanks,
Varun
When I use IE8, I can not open mailbox, what's wrong?
its ok but the canvas object support needs to be better
Hey everyone, Christopher here. It’s been a while since I’ve blogged anything here (over a year in fact).
Hey everyone, Christopher here. It’s been a while since I’ve blogged anything here (over a year in fact
Hi there,
I am unable to even get the IE8 beta to work. It installs ok, (or at least doesn't appear to pop up any error messages) but then once installed I am unable to run it, I click on the icon and the IE button starts to be added to the task bar but then stops and disappears and IE doesn't open at all and no error messages come up either, this is after the required reboot and the same happens after a extra reboot or so.
I am running XP Pro SP2 and my machine meets all the requirments!! any ideas???
Cheers
Seb,
What is this, just the same crappy browser that is making us change everything we had to make work specifically for IE7 over IE6? Damn it will be nice when someone makes up their friggin mind what is standard and what is not! Now when this stupid version is released we'll all have to go back and modify everything all over yet again! This is BS!
@Seb: Have you tried running IE without add-ons?
I thought the IE8 beta was a great step in the right direction. I loved that you have implemented standards as a default setting. I also believe the domain highlighting is an excellent idea and could provide a lot of added security.
Unhandled exception at 0x04645418 in iexplore.exe: 0xC0000005: Access violation writing location 0x00000010.
Can't log on to Microsoft Windows Update webpage... It's not work on IE8...
I have installed IE8 Beta on my machine (Win XP SP2). While trying to install March security updates I got error message telling that the browser is not supported and it adviced me to install latest version of IE.
I thought atleast Microsoft websites will recognize the browser.
I had to use 'Emulate IE7' option to install the updates.
Overall browsing experience is good but the browser needs to a bit fast.
Are we planning to add 'Change Browser Skin' feature as available in Opera browser.
The screenshots of IE8 tease the potential users with an MSN Weather Webslice. WHERE IS IT??? *puzzled*
CAN YOU PLEASE ENABLE IT ON WEATHER.MSN.COM???
Downloading it now...
I hope it impresses me as much as the IE7 RC did (stayed with it until IE7 officially came out, I loved it).
I have found that some CSS coded for IE7 to break in IE 8 beta 1.
I have yet to look more into the code though..
Hate to say it,but IE 8 beta 1 for XP SP2 SUCKS!
It effecting the mouse scrolling and curser locations. This program has too many bugs in it than IE 7.
Redo...
Thee CSS3 property "opacity" has yet to be supported.
Where is native SVG?!? (We may have to wait for IE ∞ for that one when IE has a browser share of 10 users.)
-Timothy
# Would like option to reopen open tabs when you close IE. This is a useful feature within IE7.
# Would like text icon back for selection of text within a webpage.
Heres how in #6 easy steps
1.) move the links bar, command bar and file menu bar above the address bar!@
2.) AND Move the command bar OFF the tab bar!
and on to the top left corner....... sharing space with the favorites bar! and add a third bar the- add on's bar .....on the same line
...........and finally maybee a more compact menu like netscape 8.03 standalone here ---->
3.)
Give the user an option to change the skin?
pink , blue , black ...OR....whatever your personality ..it's your IE?
4.) \
Allow an option of tabbrowser settings like in firefox
"it's ok to have tab's bar on top if you like",
but give the user an option to put it on the bottom of the window like in firefox
5.) eliminate the Search box altogether
no need for it you can search from the address bar, just have a button to change search settings next to the go---------->
6.)
Here's a way for microsoft to make $$$ on advertisement like Google--->
Use cute images........ ......like I have for my folders on my favorites toolbar.
... and start out the users with folders named "MyHomepages", "Search" with popular websites in them like myspace, facebook , yahoo, aol. msn. Google and Ask and alta vista
that would be a show of good faith?
****webmasters & websites, they would be lining up to be added links in those set up folders on IE
here's #6 easy steps to take back the internet save microsoft, and make IE the best!
Now I use the new Internet Explorer and I am very happy! Great work!
Not sure if this was an issue in IE7 but I would imagine I would have noticed it if it was...in IE8b if you right-click a link and open in new tab, you lose focus on the primary tab.
If you use your mouse wheel to scroll up and down on the page, then right-click and open in new tab, then try your wheel again and it no longer controls the page, like the focus has been lost.
I'm not sure if this is a bug or just one of those things, but it would sure be nice not to have to execute focus on th page again.
Sure it's not a huge deal, but if you are on a bad page layout where they have links everywhere, it is annoying.
Paul.
I'd like to know why IE developers are spending so much time on petty and irrelevent issues like tab arrangement or skin color choosers, and other worthless junk when they should be focusing solely on security in today's world. If MS is gonna continue to dominate the browsers, then they should be held solely responsible for staying at least one step ahead of hackers and thieves instead of always being 15 or 20 steps behind them!
MS has developed all the most popular and seemingly easily hackable software, but lacks pathetically it protecting the users of it!
aguy: I love flamebait!
I'll play!
<inserts quarter>
IE7 is MUCH more secure than IE6, and IE8 is shaping up to be more secure than both IE7 AND Firefox 3.
So, what exactly do you think is lacking in IE8 security???
Your turn... be specific!
The IE team is pleased to announce the availability of Chinese (Simplified) and German versions of Windows
With the release of IE8 Beta 1, I'm pleased to be able to talk about the first round of improved standards
As previously mentioned in the IE8 Beta Feedback post back in March, we have several ways to submit feedback
For ISVs testing Internet Explorer 8 , the team has set up a way to file bugs directly with the team.
We’re excited to release IE8 Beta 2 today for public download. You can find it at
We’re excited to release IE8 Beta 2 today for public download. You can find it at
In August 2008, Dean announced the release of IE8 Beta 2 in English, Japanese, Chinese (Simplified),
The announcement of IE8 Beta 2 started an important and public phase of the product development cycle
Dean Hachamovitch, General Manager for Internet Explorer, has posted today on the IEBlog about what’s
I guess they took my strident feedback about Beta 2 seriously: IE 8 pretty much breaks the Web at this
The Internet Explorer 8 team has announced that a release candidate (RC) will be available to the public
The Internet Explorer 8 team has announced that a release candidate (RC) will become available to the
The next public update of Internet Explorer 8 includes improvements to Compatibility View that help end-users
We're excited to make the IE8 Release Candidate available today for public download today in 25 languages
Hi Folks. Just got over my "early adopter" nerves and dowloaded IE8 RC1 . It was a pleasant experience
IE8 Release Candidate is available for public download today in 25 languages for Windows Vista, Windows
The first release candidate for Internet Explorer 8 has been released to the web. You can download it
As we've now entered the last major phase of our product cycle, we’d like to thank everyone for their
We wanted to let you know that an update was released earlier today that will improve Internet Explorer’s
We wanted to let you know that an update was released earlier today that will improve Internet Explorer
Thank you to everyone who has provided the IE Team with feedback on IE8. Your dedication to making this
RE: обратная связь в бета-тестировании IE8 Спасибо всем, кто направлял свои отзывы команде разработчиков | http://blogs.msdn.com/ie/archive/2008/03/05/ie8-beta-feedback.aspx | crawl-002 | refinedweb | 11,666 | 72.97 |
Hello, I'm new to both to this site and to C++, I've started reading the book 'C++ Without Fear - 2nd edition' a couple of week ago. when I reached chapter 12 (which is about constructors) I got stuck on the subject of copy constructors, and I seek your help!
(Example 12.3 from page 325 to page 329)
This is the Fraction class declaration.
This is the copy constructor definition.This is the copy constructor definition.Code:class Fraction { private: int num; int den; public: Fraction() {set(0, 1);} // Default constructor. Fraction(int n, int d) {set(n, d);} // (int, int) constructor. Fraction(Fraction const &src); // Copy constructor. void set(int n, int d) {num = n; den = d; normalize();} int get_num() {return num;} int get_den() {return den;} Fraction add(Fraction other); Fraction mult(Fraction other); private: // Member functions (Private). void normalize(); int gcf(int a, int b); int lcm(int a, int b) {return (a * b) / gcf(a, b);} };
Code:Fraction::Fraction(Fraction const &src) { cout << "Now calling copy constructor!" << endl; num = src.num; den = src.den; }
This is the main() function.
In the book it is said that the next line of code should call the copy constructor once (printing the "Now calling copy constructor!") Which it dose!In the book it is said that the next line of code should call the copy constructor once (printing the "Now calling copy constructor!") Which it dose!Code:int main() { Fraction f1(3, 4); Fraction f2(f1); Fraction f3 = f1.add(f2); cout << "The value of f3 is "; cout << f3.get_num() << "/"; cout << f3.get_den() << endl; return 0; }
However the book also say that the next line of code should call the copy constructor three times!However the book also say that the next line of code should call the copy constructor three times!Code:Fraction f2(f1);
first time when the object f2 is passed as an argument,
a second time when a new object is passed back as a return value,
and a third time when that object is copied to the f3 object.
But when I run this program, it prints the above message only twice (instead of 4 times!!).But when I run this program, it prints the above message only twice (instead of 4 times!!).Code:Fraction f3 = f1.add(f2);
I was thinking it must be the compiler optimizing the add member function, making it pass references instead of a copy of the object,
but I don't really have any idea if I'm right.
Am I making any sense or am I way off?
I'd really appreciate if anyone can help me understand how and why the thing I described happens!
(Btw I'm using both Code::Blocks and Dev-C++ IDE)
Thanks ahead C.
P.S. Sorry for my English! | http://cboard.cprogramming.com/cplusplus-programming/144970-copy-constructor-issue.html | CC-MAIN-2015-11 | refinedweb | 470 | 74.49 |
.
/* filename: life.cpp
project: method definitions for Life class */
//#include "util.h"
//#include "life.h"
You cant just comment out the includes of the required headers. They are there for a reason.
This:
// game of life model
# Makefile:
# It uses the C++ Compiler with all warnings and
is the start of a make file. These are instructions to a program called 'make' so that it can build your program for you.
Overall, I suspect that you have copied the correct file for your coursework but you were either instructed or expected to split it out into separate files before attemptimg to build it. If you re-read your notes it should explain how to split this file into its components and build it.
Good luck.
Paul
CPP = cxx
This should be ( i think )
CPP=g++
normally people use the following to denote the c+ compiler
CXX=g++
but in that case yuo have to replace all occurence of CPP to CXX
CFLAGS = -L/usr/lib/cmplrs/cxx -DPOSIX_4D9 -w0 -gall )
as paul said you have to include the util.h and life.h in main.cpp and life.cpp too
you have redefined NULL ( thats okay , its just a warning )
secondly we cant help more as we cant compile as we dont have libtask.a
Note, i recativated all #include "util.h" and #include "life.h"
Also, i added
#ifndef XXXX_H
#define XXXX_H
#endif
to both header files.
/* Filename: util.h
Purpose: header file for VT100 screen functions and useful I/O utils
Note: a VT100 screen is 24 rows and 80 columns in standard mode */
#ifndef UTIL_H
#define UTIL_H
#ifndef __USE_STD_IOSTREAM
#define __USE_STD_IOSTREAM
#endif
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
/* type bool and false & true are already defined in dUNIX C++
typedef int bool;
const bool false = 0;
const bool true = 1; */
/* this is also in /usr/include/stddef.h which is used in <stdlib.h> */
#define NULL 0L
/* some useful definitions for flag and screen operations */
#define STDSCREEN 80
#define DOWN 0
#define UP 1
#define END 0
#define START 1
#define FAIL 0
#define SUCCESS 1
#define MISS -1
#define HIT 1
/* some useful error codes */
enum Error_code { success, fail, range_error, underflow, overflow, fatal,
not_present, duplicate_error, entry_inserted, entry_found,
internal_error };
/* screen functions */
void clearScreen (); // clears all rows of the screen
void clearTop(); // clears top row 0 only
void clearBelowTop(); // clears row 1 down on a vt100 screen
void goTop(); // moves cursor to the top row 0
void topLine(const char * text = " " ); // displays text at row 0
void bottomLine (char * text = " "); // displays text at row 23, column 10
/* I/O functions */
void hitAnyKey (); // "Hit any key to continue..." prompt
void flushInput (); // reads 80 chars from stdin
void Warning(char *); /* writes message to stderr */
void Error(char *); /* writes message to stderr & exits */
bool promptYesNo(char * prompt=""); /* prompts user to enter yes no */
void EatWhiteSpace(void); /* discards white space input */
#endif // UTIL_H
/* filename: life.h
project: class and constant definitions for life class */
#ifndef LIFE_H
#define LIFE_H
static const int maxrow = 20, maxcol = 60;
class Life {
public:
void initialize();
void initializeRandom();
void print();
void update();
void instructions();
private:
int grid[maxrow + 2][maxcol + 2]; // allows for two extra rows and columns
int neighbor_count(int row, int col);
};
#endif // LIFE_H
All cpp files remain unchanged beside of including these header files.
Regards, Alex | https://www.experts-exchange.com/questions/21094830/code-check.html | CC-MAIN-2018-05 | refinedweb | 556 | 65.35 |
But first, let us cover the basics of a web scraper or a web crawler.
Demystifying the terms ‘Web Scraper’ and ‘Web Crawler’
A web crawler, also known as a ‘spider’ has a more generic approach! You can define a web crawler as a bot that systematically scans the Internet for indexing and pulling content/information. It follows internal links on web pages. In general, a “crawler” navigates web pages on its own, at times even without a clearly defined end goal.
Hence, it is more like an exploratory search of the content on the Web. Search engines such as Google, Bing, and others often employ web crawlers to extract content for a URL or for other links, get URLs of these links and other purposes.
However, it is important to note that web scraping and crawling are not mutually exclusive activities. While web crawling creates a copy of the content, web scraping extracts specific data for analysis, or to create something new.
However, in order to scrape data from the web, you would first have to conduct some sort of web crawling to index and find the information you need. On the other hand, data crawling also involves a certain degree of scraping, like saving all the keywords, the images and the URLs of the web page.
More about Web Crawlers
A web crawler is nothing but a few lines of code. This program or code works as an Internet bot. The task is to index the contents of a website on the internet. Now we know that most web pages are made and described using HTML structures and keywords. Thus, if you can specify a category of the content you need, for instance, a particular HTML tag category, the crawler can look for that particular attribute and scan all pieces of information matching that attribute.
You can write this code in any computer language to scrape any information or data from the internet automatically. You can use this bot and even customize the same for multiple pages that allow web crawling. You just need to adhere to the legality of the process.
There are multiple types of web crawlers. These categories are defined by the application scenarios of the web crawlers. Let us go through each of them and cover them in some detail.
1. General Purpose Web Crawler
A general purpose Web crawler, as the name suggests, gathers as many pages as it can from a particular set of URLs to crawl large-scale data and information. You require a high internet speed and large storage space are required for running a general purpose web crawler. Primarily, it is built to scrape massive data for search engines and web service providers.
2. Focused Web Crawler
Focused Web Crawler is characterized by a focused search criterion or a topic. It selectively crawls pages related to pre-defined topics. Hence, while a general purpose web crawler would search and index all the pages and URLs on a site, the focused crawler only needs to crawl the pages related to the pre-defined topics, for instance, the product information on an e-commerce website.
Thus, you can run this crawler with smaller storage space and slower internet speed. Most search engines, such as Google, Yahoo, and Baidu use this kind of web crawler.
3. Incremental Web Crawler
Imagine you have been crawling a particular page regularly and want to search, index and update your existing information repository with the newly updated information on the site. Would you crawl the entire site every time you want to update the information? That sounds unwanted extra cost of computation, time and memory on your machine. The alternative is to use an incremental web crawler.
An incremental web crawler crawls only newly generated information in web pages. They only look for updated information and do not re-download the information that has not changed, or the previously crawled information. Thus it can effectively save crawling time and storage space.
4. Deep Web Crawler
Most of the pages on the internet can be divided into Surface Web and Deep Web (also called Invisible Web Pages or Hidden Web). You can index a surface page with the help of a traditional search engine. It is basically a static page that can be reached using a hyperlink. Web pages in the Deep Web contain content that cannot be obtained through static links. It is hidden behind the search form.
In other words, you cannot simply search for these pages on the web. Users cannot see it without submitting some certain keywords. For instance, some pages are visible to users only after they are registered. Deep web crawler helps us crawl the information from these invisible web pages.
When do you need a web crawler?
From the above sections, we can infer that a web crawler can imitate the human actions to search the web and pull your content from the same. Using a web crawler, you can search for all the possible content you need. You might need to build a web crawler in one of these two scenarios:
1. Replicating the action of a Search Engine- Search Action
Most search engines or the general search function on any portal sites use focused web crawlers for their underlying operations. It helps the search engine locate the web pages that are most relevant to the searched-topics. Here, the crawler visits web sites and reads their pages and other information to create entries for a search engine index. Post that, you can index the data as in the search engine.
To replicate the search function as in the case of a search engine, a web crawler helps:
- Provide users with relevant and valid content
- Create a copy of all the visited pages for further processing
2. Aggregating Data for further actions – Content Monitoring
You can also use a web crawler for content monitoring. You can then use it to aggregate datasets for research, business and other operational purposes. Some obvious use-cases are:
- Collect information about customers, marketing data, campaigns and use this data to make more effective marketing decisions.
- Collect relevant subject information from the web and use it for research and academic study.
- Search information on macro-economic factors and market trends to make effective operational decisions for a company.
- Use a web crawler to extract data on real-time changes and competitor trends.
How can you build a Web Crawler?
There are a lot of open-source and paid subscriptions of competitive web crawlers in the market. You can also write the code in any programming language. Python is one such widely used language. Let us look at a few examples there.
Web Crawler using Python
Python is a computationally efficient language that is often employed to build web scrapers and crawlers. The library, commonly used to perform this action is the ‘scrapy’ package in Python. Let us look at a basic code for the same.
import scrapy class spider1(scrapy.Spider): name = ‘Wikipedia’ start_urls = [‘’] def parse(self, response): pass
The above class consists of the following components:
- a name for identifying the spider or the crawler, “Wikipedia” in the above example.
- a start_urls variable containing a list of URLs to begin crawling from. We are specifying a URL of a Wikipedia page on clustering algorithms.
- a parse() method which will be used to process the webpage to extract the relevant and necessary content.
You can run the spider class using a simple command ‘scrapy runspider spider1.py‘. The output looks something like this.
The above output contains all the links and the information (text content) on the website in a wrapped format. A more focussed web crawler to pull product information and links from an e-commerce website looks something like this:
import requests from bs4 import BeautifulSoup def web(page,WebUrl): if(page>0): url = WebUrl code = requests.get(url) plain = code.text s = BeautifulSoup(plain, “html.parser”) for link in s.findAll(‘a’, {‘class’:’s-access-detail-page’}): tet = link.get(‘title’) print(tet) tet_2 = link.get(‘href’) print(tet_2) web(1,’’)
This snippet gives the output in the following format.
The above output shows that all the product names and their respective links have been enlisted in the output. This is a piece of more specific information pulled by the crawler.
Other crawlers in the market
There are multiple open source crawlers in the market that can help you collect/mine data from the Internet. You can conduct your due research and use the best possible tool for collecting information from the web. A lot of these crawlers are written in different languages like Java, PHP, Node, etc.
You may consider factors like the simplicity of the program, speed of the crawler, ability to crawl over various web sites (flexibility) and memory usage of these tools before you make your final choice.
read original article here | https://coinerblog.com/how-to-build-a-web-crawler-from-scratch-wps32ia/ | CC-MAIN-2020-05 | refinedweb | 1,485 | 63.8 |
The standard way to bin a large array to a smaller one by averaging is to reshape it into a higher dimension and then take the means over the appropriate new axes. The following function does this, assuming that each dimension of the new shape is a factor of the corresponding dimension in the old one.
def rebin(arr, new_shape): shape = (new_shape[0], arr.shape[0] // new_shape[0], new_shape[1], arr.shape[1] // new_shape[1]) return arr.reshape(shape).mean(-1).mean(1)
To see how this works, consider reshaping a $4 \times 6$ array to become $2 \times 3$:
In [x]: arr = np.arange(24).reshape((4,6)) In [x]: arr Out[x]: array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])
We reshape from
(4, 6) to
(2, 4//2, 3, 6//3) = (2, 2, 3, 2):
In [x]: arr.reshape(2, 4//2, 3, 6//3) Out[x]: array([[[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]]], [[[12, 13], [14, 15], [16, 17]], [[18, 19], [20, 21], [22, 23]]]])
This has grouped entries so that each row has become a $3 \times 2$ subarray and these subarrays are arranged as entries in the first $2 \times 2$ dimensions of the new 4D array. Now consider averaging over the last dimension (indexed with
-1):
In [x]: arr.reshape(2, 2, 3, 2).mean(-1) Out[x]: array([[[ 0.5, 2.5, 4.5], [ 6.5, 8.5, 10.5]], [[ 12.5, 14.5, 16.5], [ 18.5, 20.5, 22.5]]])
This has averaged entries along each row to leave an array of shape
(2,2,3) (for example, the first entry is the average of 0 and 1, which is 0.5). Now, averaging over the second dimension of this array (indexed with
1) corresponding to columns of the original array:
In [x]: arr.reshape(2, 2, 3, 2).mean(-1).mean(1) Out[x]: array([[ 3.5, 5.5, 7.5], [ 15.5, 17.5, 19.5]])
This is the $2\times 3$ binned array that we wanted.
Here is an illustration of the technique, based on USGS elevation data for the vicinity of Mt Ranier, which can be obtained from their download service.
import os from osgeo import gdal import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D imgdir = '/Users/christian/temp/mt-ranier' # Mt Ranier spans two IMG files in the USGS data set. imgnameW = 'ned19_n47x00_w122x00_wa_mounttrainier_2008' imgnameE = 'ned19_n47x00_w121x75_wa_mounttrainier_2008' def get_elev_arr(imgname): """Read in the elevation data as a NumPy array.""" imgfile = os.path.join(imgdir, imgname, imgname+'.img') print(imgfile) geo = gdal.Open(imgfile) arr = geo.ReadAsArray() # invalid or missing data is indicated by a large negative value, so # replace these entries with NaN. arr[arr<0] = np.nan return arr # stack the East and West arrays next to each other to give elevation across # the entire area. elev = np.hstack((get_elev_arr(imgnameW), get_elev_arr(imgnameE))) # The latitude and longitude bouhnds of the elevation array N, S = 47.000185185185195, 46.749814814814826 E, W = -121.49981481481484, -122.00018518518522 # The centre of the mountain clat, clong = 46.88, -121.70 # Extract the region in a square centred on the Mt Ranier Ny, Nx = elev.shape icx, icy = int((N-clat)/(N-S) * Nx), int((W-clong)/(W-E) * Ny) Dpx = 3200 ix1, iy1, ix2, iy2 = icx-Dpx, icy-Dpx, icx+Dpx, icy+Dpx nx, ny = ix2-ix1, iy2-iy1 elev = elev[iy1:iy2,ix1:ix2] def rebin(arr, new_shape): """Rebin 2D array arr to shape new_shape by averaging.""" shape = (new_shape[0], arr.shape[0] // new_shape[0], new_shape[1], arr.shape[1] // new_shape[1]) return arr.reshape(shape).mean(-1).mean(1) # Create four surface subplots with different binnings fig, axes = plt.subplots(nrows=2, ncols=2, subplot_kw={'projection': '3d'}) binfacs = (640, 256, 64, 32) for i, binfac in enumerate(binfacs): ax = axes[i // 2, i % 2] bnx, bny = nx//binfac, ny//binfac X, Y = np.linspace(1,bnx,bnx), np.linspace(1,bny,bny) X, Y = np.meshgrid(Y, X) binned_elev = rebin(elev, (bny, bnx)) ax.plot_surface(X, Y, binned_elev, rstride=4, cstride=4, linewidth=0.1, antialiased=True, cmap=cm.plasma) cset = ax.contourf(X, Y, binned_elev, zdir='z', offset=0, cmap=cm.inferno) ax.set_axis_off() ax.dist=12 plt.savefig('ranier-rebinned.png') plt.show()
Comments are pre-moderated. Please be patient and your comment will appear soon.
Steve Boege 2 years, 4 months ago
Thanks for the clear, detailed explanation!Link | Reply
lost_mitten 1 year, 8 months ago
It is about 1.5 times more efficient to use .mean(axis=(-1,1)) instead of .mean(-1).mean(1)Link | Reply
Also setting appropriate dtype will spare some of time, cause default is float64 - .mean(axis=(-1,1), dtype=np.uint16)
christian 1 year, 8 months ago
Hi @lost_mitten,Link | Reply
I don't see any time difference on my system between the two averaging methods. In IPython, for example, compare
%timeit np.random.random(240000).reshape((20,20,30,20)).mean(-1).mean(1)
and
%timeit np.random.random(240000).reshape((20,20,30,20)).mean(axis=(-1,1))
You could use uint16 but I guess you risk losing some resolution from the integer division.
If issues of speed and memory are critically important for your application, you should perhaps consider whether Python is the right language to use.
lost_mitten 1 year, 8 months ago
You're also timing array creation - it takes up most the time.Link | Reply
a = np.random.randint(2, size=(9000,9000))
%timeit a.reshape((3000,3,3000,3)).mean(axis=(-1,1))
%timeit a.reshape((3000,3,3000,3)).mean(-1).mean(1)
532 ms ± 8.15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
757 ms ± 15.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
christian 1 year, 8 months ago
Interesting. The main difference seems to be though that my test array is more nearly square than yours, e.g. reshaping yours to (150,60,150,60) makes the two approaches much more similar in timings.Link | Reply
jaume 1 month, 2 weeks ago
It is very useful. Thanks! I modified a little bit the function to work with a non-divisible factors of the array shape.Link | Reply
if (shape[0]%binY != 0) and (shape[1]%binX == 0):
rest = shape[0]%binY
arr1 = Binning2D(array[:shape[0]-rest], binY, binX)
arr2 = Binning2D(array[shape[0]-rest:], shape[0]%binY, binX)
arr = _numpy.concatenate((arr1,arr2), axis=0)
return arr
if (shape[1]%binX != 0) and (shape[0]%binY == 0):
rest = shape[1]%binX
arr1 = Binning2D(array[:,:shape[1]-rest], binY, binX)
arr2 = Binning2D(array[:,shape[1]-rest:], binY, shape[1]%binX)
arr = _numpy.concatenate((arr1,arr2), axis=1)
return arr
New Comment | https://scipython.com/blog/binning-a-2d-array-in-numpy/ | CC-MAIN-2020-29 | refinedweb | 1,155 | 67.65 |
In this article, we will be discussing a program to find the probability of reaching from the initial state to the final state in a given time period in Markov chain.
Markov chain is a random process that consists of various states and the associated probabilities of going from one state to another. It takes unit time to move from one state to another.
Markov chain can be represented by a directed graph. To solve the problem, we can make a matrix out of the given Markov chain. In that matrix, element at position (a,b) will represent the probability of going from state ‘a’ to state ‘b’.
This would leave to a recursive approach to the probability distribution using the formula
P(t) = Matrix * P(t-1)
#include <bits/stdc++.h> using namespace std; #define float_vec vector<float> //to multiply two given matrix vector<float_vec > multiply(vector<float_vec > A, vector<float_vec > B, int N) { vector<float_vec > C(N, float_vec(N, 0)); for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) C[i][j] += A[i][k] * B[k][j]; return C; } //to calculate power of matrix vector<float_vec > matrix_power(vector<float_vec > M, int p, int n) { vector<float_vec > A(n, float_vec(n, 0)); for (int i = 0; i < n; ++i) A[i][i] = 1; while (p) { if (p % 2) A = multiply(A, M, n); M = multiply(M, M, n); p /= 2; } return A; } //to calculate probability of reaching from initial to final float calc_prob(vector<float_vec > M, int N, int F, int S, int T) { vector<float_vec > matrix_t = matrix_power(M, T, N); return matrix_t[F - 1][S - 1]; } int main() { vector<float_vec > G{ { 0, 0.08, 0, 0, 0, 0 }, { 0.33, 0, 0, 0, 0, 0.62 }, { 0, 0.06, 0, 0, 0, 0 }, { 0.77, 0, 0.63, 0, 0, 0 }, { 0, 0, 0, 0.65, 0, 0.38 }, { 0, 0.85, 0.37, 0.35, 1.0, 0 } }; //number of available states int N = 6; int S = 4, F = 2, T = 100; cout << "Probability of reaching: " << F << " in time " << T << " after starting from: " << S << " is " << calc_prob(G, N, F, S, T); return 0; }
Probability of reaching: 2 in time 100 after starting from: 4 is 0.271464 | https://www.tutorialspoint.com/cplusplus-program-to-find-the-probability-of-a-state-at-a-given-time-in-a-markov-chain | CC-MAIN-2021-49 | refinedweb | 383 | 68.6 |
Spidering an Ajax Website With a Asynchronous Login Form
Introduction: Spidering an Ajax Website With a Asynchronous Login Form
The problem: Spidering tools don't allow AJAX login authentication.
This instructable will show you how to login through an AJAX form using Python and a module called Mechanize.
Spiders are web automation programs that are becoming increasingly popular way for people to gather data online. They creep around the web gathering precious materials to fuel the most powerful web companies around. Others crawl around and gather specific sets of data to improve decision making, or infer what's currently "in", or find the cheapest travel routes.
Spiders (web crawlers, webbots, or screen scrapers) are great for turning HTML goop into some semblance of intelligent data, but we have a problem when it comes to AJAX enabled webpages that have JavaScript and cookie enabled sessions that are not navigable with the normal set of spidering tools. In this instructable we will be accessing our own member page at pubmatic.com. These steps will show you a method to follow, but your page will be different.
Have fun!
Step 1: Gather Materials
You will need to start supplementing your programming resources. You will need the following programs. Use their guides to help you install these...
Install Firebug
It's a Firefox addon
Install Python
Go to: python.orgGo to: python.org
Install the Mechanize Module
Get MechanizeGet Mechanize
Other useful Spidering tools:
BeautifulSoup
Step 2: Find the Headers Necessary to Create a Session.
A well crafted spider will access a webpage as if it were a browser being controlled by a human being keeping clues as to it's true origin hidden. Part of the interaction between browsers and servers happens through GET and POST requests that you can find in the headers (this information is rarely displayed on a browser, but is very important). You can view some this information by pressing Ctrl I (in firefox) to open up the Page Info window. To disguise yourself as a mild mannered browser you must identify yourself using the same credentials.
If you tried to log into pubmatic with javascript disabled in your browser you wouldn't get very far since the redirects are done through javascript. So considering that most spider browsers don't have javascript interpreters we will have to get by the login through an alternative rout.
Let's start by getting the header information sent from the browser when you click submit. If this were an ordinary browser login you would use Mechanize to fill out the form and click submit. Normal login forms are encapsulated within a <form> ... </form> tag and Mechanize would be able to submit this and poll the next page without trouble. Since we don't have a completed form tag, the submitting function is being handled by javascript. Let's check pubmatic's submitForm function. To do this, first open the webpage in firefox and turn on firebug by clicking the firefly in the lower right hand corner. Then click the script tab, copy all the code that appears and paste it into your favorite text editing bit of software. You can then delete all the code except the function submitForm. It starts with function "submitForm(theform) {" and everything in between this and the functions closing curly bracket "}".
On analyzing this function very primitively we notice that some authentication happens bringing back a variable called xmldoc that's being parsed as xml. This is a key feature of AJAX it has polled the server and brought back some XML document that contains a tree of information. The node session_id contains the session_id if the authentication was successful, you can tell this by looking at this bit of code: "if (session_id != null) { //login successful".
Now we want to prevent this bit of javascript from taking us anywhere so we can see what is being posted to the server during authentication. To do this we comment out any window redirects which look like this: "window.location=...". To comment this out add double slashes before them like so: "//window.location..." this prevents the code from being run.
You can download the Javascript file below which has these edits already made.
Copy and paste this edited bit of javascript into the console windows right hand side and click run. This overrides the javascript function already in the page with our new version. Now when you fill out your credentials and click submit you should see POST and GET header information fill the console, but you wont be going anywhere.
The POST information is the information shot to the server by the AJAX functions, you want to be as much like this as possible, copy and paste that information into the a notepad.
Step 3: Prepare the Code
Before we add the new headers we've found let's create a templated Mechanize login python code. We're doing this for two reasons, first so we have a component that works to add new stuff to and second so you see how you would normally login to a non AJAX-y webpage.
Open notepad or equivalent, and copy and paste the following. When you're done save it as youfilename.py somewhere you can find.
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Start with your module imports:
from mechanize import Browser
#Create your browser instance through the Browser() function call;
br = Browser()
#Set the browser so that it ignores the spiders.txt requests
#Do this carefully, if the webpage doesn't like spiders, they might be upset to find you there
br.set_handle_robots(False)
#Open the page you want to login to
br.open("")
#Because I know the form name, I can simply select the form by the name
br.select_form("login")
#Using the names of the form elements I input the names of the form elements
br['email'] = "laser+pubmatic@instructables.com"
br['password'] = "Asquid22"
#br.submit() sends out the form and pulls the resulting page, you create a new browser instance
#response below contains the resulting page
response = br.submit()
#This will print the body of the webpage received
#print response.read()
Step 4: Send the Right Signals.
Mechanize has an easy function to add headers to the headers POST, this will enable us to appear to the same browser that you used to access the page the first time. Open up the file with headers you found using Firebug and edit this text file to match. Replace everything in the quotes with the proper item from the header list:
USER_AGENT = "Mozilla/5.0 (X11; U; Linux i686; tr-TR; rv:1.8.1.9) Gecko/20071102 Pardus/2007 Firefox/2.0.0.9"
HOST = "pubmatic = ""
CONTENT_LENGTH = "60"
COOKIE = "utma=103266945.1970108054.1210113004.1212104087.1212791201.20; KADUSERCOOKIE=EA2C3249-E822-456E-847A-1FF0D4085A85; utmz=103266945.1210113004.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); JSESSIONID=60F194BE2A5D31C3E8618995EB82C3C1.TomcatTwo; utmc=103266945"
PRAGMA = "no-cache"
CACHE_CONTROL ="no-cache"
This creates a set of variables that you can then use to append to the header using this code:
br.add_header = [("Host", HOST)]
br.add_headers = [("User-agent", USER_AGENT)]
br.add_headers = [("Accept", ACCEPT)]
br.add_header = [("Accept-Language", ACCEPT_LANGUAGE)]
br.add_headers = [("Accept-Encoding", ACCEPT_ENCODING)]
br.add_headers = [("Accept-Charset", ACCEPT_CHARSET)]
br.add_header = [("Keep-Alive", KEEP_ALIVE)]
br.add_headers = [("Connection", CONNECTION)]
br.add_header = [("Content-Type", CONTENT_TYPE)]
br.add_header = [("Referer", REFERER)]
br.add_header = [("Content-Length", CONTENT_LENGTH)]
br.add_headers = [("Cookie", COOKIE)]
br.add_headers = [("Pragma", PRAGMA)]
br.add_headers = [("Cache-Control", CACHE_CONTROL)]
Now when we call the page open function the headers will be sent to the server as well.
br.open("")
Step 5: Mechanized Cookies
This step is because mechanize automates cookie handling, but it's important to know what's happening:
When the form is submitted you have the right headers as if you submitted using the javascript function. The server then authenticates this information and generates a session ID and saves it in a cookie if the username and password are correct. The good news is Mechanize automatically eats and regurgitates cookies so you don't need to worry about sending and receiving the cookie. So once you create a session ID that works you can then enter the members only section of the website.
Step 6: Key to the Heart
Now that we've acquired a session ID and Mechanize saved it into it's cookies we can follow the javascript to see where we need to go. Looking inside the "if (session_id != null) { //login successful" to see where to go on success. Looking at the window relocation code: "if (adurlbase.search(/pubmatic.com/) != -1) { window.location="" + "?v=" + Math.random()*10000;" we see that we need to go to a website located at random number. So let's just create a fake random number to enter and create a new browser instance to read the freshly opened page:
response2 = br.open("")
And that should be it. Your code is now complete, by using the proper headers and mechanize cookie handler we can now access the innards of pubmatic.
Open up terminal, load the python package below and login away. To do this type python2.5 and then the filepath to the .py file.
I would love to check this one out more thoroughly when I finish studying ajax programming. Cool, keep the techy Instructables coming!
Maman is wreaking havoc in Washington!! lol :D
Darn. Firebug doesn't work on Firefox 3. Oh well, I've never come across an AJAX website anyways.
Nice choice of pictures. My aunt showed me one of those spider statues a few months ago when I visited her in Ottawa. (the capital of Canada) I'll let you know what I think of your Instructable once I have need for it. At present, it'd be useless to me without also figuring out how to use python-spidermonkey or writing a Javascript parser using regexes, Plex, or PLY. (The guys who run FanFiction.net are either insane, stupid, or hate their users and this extends to treating Javascript as if it's some sort of client-side PHP, so BeautifulSoup and Mechanize on their own are useless)
Cool. It's good to see some more technical programming stuff on the site! Not that everyone will appreciate this Instructable, but hopefully people who can really use this knowledge will find it through a search engine, when they're looking it up. | http://www.instructables.com/id/Spidering-an-Ajax-website-with-a-asynchronous-logi/ | CC-MAIN-2017-30 | refinedweb | 1,726 | 64.91 |
In today’s Programming Praxis, our goal is to print the numbers 1 through 1000 without using loops or conditionals. Let’s get started, shall we?
Some imports:
import Control.Exception import Control.Monad.State
The problem with this question is that it isn’t very well-defined. For example, the idiomatic way of doing this in Haskell would be the following:
loopy1 :: IO () loopy1 = mapM_ print [1..1000]
This has no loops or conditionals in the user’s code. However, the .. construct probably uses a loop and/or conditional internally. So let’s get rid of it:
loopy2 :: IO () loopy2 = f 1 where f 1000 = print 1000 f n = print n >> f (n + 1)
This uses recursion instead of looping and pattern matching instead of conditionals. However, you might consider pattern matching a number to be sufficiently like conditionals to be cheating. Ok, let’s choose another approach.
loopy3 :: IO () loopy3 = handle (\DivideByZero -> return ()) $ f 1 where f n = seq (div n (1001 - n)) print n >> f (n + 1)
Here we still use recursion, but we now end through exception handling rather than pattern matching. The only thing left to do would be to get rid of recursion, since you could consider that a form of looping.
loopy4 :: IO () loopy4 = evalStateT (do10 . do10 . do10 $ next) 1 where next = (liftIO . print =<< get) >> modify succ do10 f = f >> f >> f >> f >> f >> f >> f >> f >> f >> f
And there we go. No conditionals or looping of any kind as far as I can tell. This is probably the closest to the spirit of the exercise.
Tags: bonsai, code, Haskell, kata, loops, loopy, praxis, programming | https://bonsaicode.wordpress.com/2011/03/18/programming-praxis-loopy-loops/ | CC-MAIN-2017-30 | refinedweb | 273 | 74.49 |
I am very new to C++, Ive only been learning it for the last week. Anyway Ive written this simple program that should create a number guessing game with player 1 and 2. The use can input the number of rounds they wish to play then at the end of each guess the winner of that round (the one with the the number closest to the random number) should be displayed. At the end the program should display the winner, how many rounds they won, and how many points they beat the other player by.
It will compile but returns some warnings about variables in the Game function being assigned values and never used.It will compile but returns some warnings about variables in the Game function being assigned values and never used.Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef unsigned short int USHORT;
USHORT Game(USHORT, USHORT);
int main()
{
USHORT rnd_amount;
USHORT P1_guess;
USHORT P2_guess;
USHORT result;
USHORT wincnt_P1;
USHORT wincnt_P2;
USHORT winner;
std::cout << "Welcome to the guess the number game.\n\n";
std::cout << "You can input the number of rounds you wish to play, whoever wins the most rounds wins the game.\n\n";
std::cout << "A random number will be generated by the computer. Each player has attempt to guess the number.\n\n";
std::cout << "The winner of the round is the person with the guess closest to the generated number\n\n";
std::cout << "\n\n\n\nPlease enter the number of rounds you wish to play";
std::cin >> rnd_amount;
std::cout << "\n\nTHE GAME HAS BEGUN";
USHORT rnd_counter;
wincnt_P1 = 0;
wincnt_P2 = 0;
for (rnd_counter = 0; rnd_counter < rnd_amount; rnd_counter++)
{
std::cout << "\n\nThis is round: " << rnd_counter + 1;
std::cout << "\n\nPlease enter your guess Player 1:";
std::cin >> P1_guess;
std::cout << "\n\nPlease enter your guess Player 2:";
std::cin >> P2_guess;
result = Game(P1_guess, P2_guess);
switch (result)
{
case 1:
std::cout << "\n\nThe winner of this round is Player 1";
wincnt_P1++;
break;
case 2:
std::cout << "The winner of this round is Player 2";
wincnt_P2++;
break;
case 3:
std::cout << "This round was a draw";
break;
}
}
std::cout << "\n\nIt is the end of the game!";
std::cout << "\n\nPlayer 1, you won " << wincnt_P1 << "games!";
std::cout << "\n\nPlayer 2, you won " << wincnt_P2 << "games!";
winner = 0;
if (wincnt_P2 < wincnt_P1)
{ winner = 1; }
if (wincnt_P1 < wincnt_P2)
{ winner = 2; }
else
{ winner = 3;}
switch (winner)
{
case 1:
std::cout << "\n\nPlayer 1, you have won this game with " << wincnt_P1 << " points. You beat player 2 by " << (wincnt_P1 - wincnt_P2) << " points";
break;
case 2:
std::cout << "\n\nPlayer 2, you have won this game with " << wincnt_P2 << " points. You beat player 1 by " << (wincnt_P2 - wincnt_P1) << " points";
break;
case 3:
std::cout << "\n\nNeither player won the game, it was a draw.";
break;
}
std::cout << "\n\nThank you for playing the number guessing game! Please play again";
std::cout << "\n\n\n\n\n\nThe Number Guessing Game v1.0. Built by Andrew";
int nil;
std::cout << ". ";
std::cin >> nil;
return 0;
}
USHORT Game(USHORT P1_guess, USHORT P2_guess)
{
srand( (unsigned)time( NULL ) );
USHORT random = (rand() % 10) + 1;
USHORT P1_result;
USHORT P2_result;
USHORT z;
P1_result = 0;
P2_result = 0;
if (P1_guess < random)
{ P1_result = random - P1_guess; }
else
{ P1_result = P1_guess - random; };
if (P2_guess < random)
{ P2_result = random - P2_guess; }
else
{ P2_result = P2_guess - random; };
z = 0;
if (P2_result < P1_result)
{ z = 2; }
if (P1_result < P2_result)
{ z = 1; }
else (P2_result == P1_result);
{ z = 3; };
return z;
}
When I run the program it simply says the round is a draw whatever number is input.
I've been over the code but my skills with C++ are pretty limited and I can't work out where I have gone wrong.
Any help would be much appreciated.
Thanks in advance. | https://cboard.cprogramming.com/cplusplus-programming/71536-problem-simple-program-printable-thread.html | CC-MAIN-2018-05 | refinedweb | 619 | 63.83 |
ARIA: Accessible Rich Internet Applications
From MDC
Firefox's implementation of Accessibility Rich Internet Applications (ARIA) allows desktop-style widgets such as tree views, menu bars and spreadsheets which are accessible both with the keyboard and assistive technologies such as screen readers, screen magnifiers and alternative input devices. It also helps provide accessibility solutions for AJAX-style live updates to regions on a page.
ARIA, formerly known as DHTML accessibility, is a standard being developed at W3C - World Wide Web Consortium. All documents are available on the Protocols and Formats Working Group public page. This includes the ARIA roadmap, the ARIA roles spec and the states module.
The code for ARIA in Firefox has been contributed by IBM.
A new helpful FAQ on ARIA is also available.
ARIA examples which demonstrate the Firefox implementation are available. While the community waits for W3C's Protocols and Formats group to move the ARIA implementation through the various phases of the standardization process, web sites can already be written which take advantage of Firefox's ARIA support today. Bug fixing and small tweaks are still occurring -- there will continue to be evolutionary improvements in Firefox's support for ARIA.
[edit] Keyboard navigation
Keyboard navigation is supported in two ways:
- Via the HTML
tabindexattribute, which allows any HTML element to be made tab navigable or, at least, focusable via script or the mouse. Differentiating between elements that are tab navigable and merely focusable allows the development of container widgets such as tree views and spreadsheets, where the arrow keys are used to navigate between child elements in the container. This currently works in Internet Explorer, Firefox and Opera. It does not work in Safari. Please see Practical documentation on building key navigable custom widgets, which describes how to tabindex to code key navigable DHTML widgets.
- Via the
aria-activedescendantattribute. This can be much simpler, because the container widget (a list, tree or grid for example) can be added to the tab order by putting tabindex="0" on it. Then, point to the currently focused descendant with the aria-activedescendant="[id]" attribute. The keydown handler on the container widget should change which descendant is pointed to, and ensure that the current item is styled (e.g. with a border or background color) to show it is the current one. This technique can be made to work in all browsers. See the source code of the listbox example for a more direct illustration of how this works.
[edit] Basic support for assistive technologies
Assistive technology support requires Firefox 2 or later and content which uses ARIA markup to describe each widget. For example, each widget must use the ARIA role to specify the widget type, e.g. menu, slider or progress bar. Each role may support a small number of additional property attributes such as
checked,
selected,
required,
invalid, and
expanded.
[edit] What does the markup look like?
The ARIA recommendation has now changed so that namespaces are no longer used in the markup. This allows it to be used in HTML.
For example, a checkbox may be specified as:
[edit] In HTML (requires Firefox 3)
<span tabindex="0" role="checkbox" aria- Any checkbox label </span>
[edit] Historical Namespace approach (no longer supported)
For historical purposes, here is the namespaced approach, which required XHTML in order to be used declaratively. This is no longer supported in Firefox 3:
<span tabindex="0" role="wairole:checkbox" aaa: Any checkbox label </span>
The above checkbox is custom built, but acts just like a normal checkbox as far as assistive technologies and the user are concerned. It can have any visual appearance the author wishes to code via CSS. Here is a breakdown of the attributes:
Please see the provided ARIA samples for futher examples how this markup is used. Firefox implements the mapping from these markup roles and properties to MSAA - Microsoft Active Accessibility and ATK - Accessibility Toolkit (from Gnome Accessibility Project), which are the standard accessibility APIs on Windows and Linux. Because the widget information is exposed via standard accessibility APIs, assistive technologies get a large degree of compatibility with these widgets without any new code. The most complete support in screen readers currently requires Window-Eyes 5.5. Screen magnifiers such as ZoomText are also compatible with ARIA.
Internet Explorer support is not currently available for the role and properties pieces. Internet Explorer currently supports only keyboard navigation for these widgets. Assistive technology vendors should be able to support ARIAsemantics without changes in Internet Explorer by looking directly at the DOM and DOM change events.
[edit] Choosing XHTML or HTML dealt with ARIA in the beginning, this is a drastic improvement!
[edit] Sample widgets
[edit] Testing with keyboard and mouse navigation
Keyboard or mouse navigation works in both Internet Explorer and Firefox. Please note that only the HTML versions of the samples have been tested with and made to work in Internet Explorer. The XHTML versions of the samples have not.
[edit] Testing with Firefox Accessibility Extension
The Firefox Accessibility Extension has features to test for the accessibility of ARIA roles.
[edit] Testing with screen readers
Screen reader support is only available in Firefox 1.5 or later. Here are the required components that must be installed:
- Firefox: download and install Firefox.
- Screen reader: for testing with a screen reader, Window-Eyes 5.5 or later is required. In addition, JAWS 7.x or later has partial support for ARIA. Also, Orca 2.20 or later has support for most ARIA widget types for Firefox 3.0.
[edit] Where can I find samples?
Note: examples are also listed by role/property in the next sections.
[edit] Dojo Toolkit
All of the core Dijit widgets from the Dojo 1.0 widget toolkit now support ARIA. For screen reader support, the Dojo examples must be opened with Firefox 2 or Firefox 3.
[edit] University of Illinois
The University of Illinois ARIA test suite requires Firefox 3 for screen reader support.
[edit] Mozilla bare bones examples
The Mozilla.org ARIA test pages provide some examples to learn from. For screen reader support they require Firefox 3:
- Checkbox, Button with description
- Graphical slider, Simple slider, Progress bar
- Alert
- Grid (spreadsheet) with menubar
- Tab panel
- Listbox
- Tree view, Tree view #2
[edit] CLC World: live region examples
The live region examples] currently work in Fire Vox. It does not matter which version of Firefox you are using when running the Fire Vox screen reading extension.
[edit] Supported roles
Here's a table delineating what roles supported by Firefox, which properties each role supports, and which currently have examples. Note that some properties are "universal properties" and work on all elements. See the supported properties section for more information.
Unless otherwise indicated, properties are boolean and support the values
true or
false. In the boolean case, an unset attribute is the equivalent of setting it to
false.
Be aware that the attributes
checked,
selected, and
expanded are special --
false is different from no attribute present in that
false indicates that the widget is checkable/selectable/expandable and no attribute indicates that it isn't.
We also provide the technical details on how Firefox exposes all of this information through the accessibility APIs on Windows (MSAA) and Linux (ATK).
† all elements allow universal properties, which are marked with "all elements" in the applicability column in the property table below.
[edit] Landmark Roles from XHTML role attribute module
The XHTML role attribute module defines the following roles:
banner, contentinfo, definition, main, navigation, note, search, secondary, seealso
In XHTML, these landmark roles can be used without the "wairole:" prefix, e.g.
<div role="main">. Ideally screen readers will provide navigation mechanisms to get to these roles, or automatically start the user user at the main content. Screen magnifiers and cell phones could also default to the main content, or provide special highlighting or navigation mechanisms. However, while these roles are exposed via MSAA string roles, no special support is known to currently exist in assistive technologies.
[edit] Supported properties
[edit] Live regions
Some web pages have live regions which can updated based on user actions or real world events. An example of changes based on user actions is the preferences page for this wiki. Examples of changes based on real-world events include chat regions, live game statistics or live financial information.
Screen reader accessibility for live regions is currently problematic. If a screen reader were to read all live changes on a page, it would be annoying to the user. If a screen reader were to read none of them, the user could miss vital information.
A solution is being developed via ARIA, where web authors can specify what live regions there are, as well as additional useful information about the live region. This will help the screen reader determine what to read and when.
These ARIA properties include aria-live, aria-atomic, aria-relevant, aria-controls, aria-channel, aria-labelledby and aria-describedby. Currently support is being developed in the Fire Vox screen reading extension, in order to help move the standards writing effort forward, to demonstrate the benefits of adopting WAI-ARIA to the web developer community, and to show the screen reader developer community what works as far as an end user experience.
For more information:
- See a full report on the current state of live region markup development at AJAX:WAI_ARIA_Live_Regions. It also provides links to testcases that work with Fire Vox.
- Simple and advanced test cases are provided by Charles Chen, the developer of the Fire Vox extension. These examples all work with Fire Vox.
- Another description of the markup is provided at ARIA live region article on Juicy Studio, by Gez Lemon.
It is not expected that live regions will be supported in all-purpose screen readers until the Firefox 3 timeframe.
[edit] Standards development for ARIA
Inside the W3C's Web Accessibility Initiative is the Protocols and Formats Working Group (PFWG). This group has largely been focusing on what they call the Dynamic Web Content Accessibility Work roadmap, which is both a short term effort of defining basic roles and properties as well as a long term effort of filling in every important gap.
[edit] Open Bugs in Firefox
Here is the complete ARIA bug list for Firefox. You can track progress of Firefox's ARIA support there.
[edit] Future of ARIA
Additional ARIA support is being planned for future releases. This work is dependent on getting a relatively stable standard from the W3C PF group. These changes include support for allowing authors to define new roles via inheritance from known roles, support for describable actions, specifying custom relationships between elements, and semantic access keys that work around today's keyboard conflicts between the browser and a web page's keyboard accelerators.
[edit] ARIA IRC channel and mailing list
Please join the #wai-aria channel (irc.w3.org:6665) for public discussions about WAI-ARIA, Members should keep discussion of internal drafts on #pf.
The mailing list for public dicussions is wai-xtech. People who want to participate in wai-xtech should email the PFWG Chair (wai-pf-call@w3.org) to request a subscription.
Categories: Accessibility | AJAX | DHTML | DOM | http://developer.mozilla.org/en/docs/Accessible_DHTML | crawl-001 | refinedweb | 1,862 | 54.02 |
Asked by:
MDT 2012 Concurrent Deployment?
So i have successfully deploy MDT 2012 , and i tried to deploy to one of my machines, no problem whatsoever.
My concern is that when i tried out multiple deployment concurrently ( 6 concurrent deployment to be specific), the installation gets slowed down horribly. Loading the .wim image during PXE boot requires roughly 5 to 6 minutes, and the installation OS is noticeably longer compared to single deployment (didn't manage to get an exact time reading on this).
Understandably that the deployment will get slower during the concurrent deployment, I'd like to know that if MDT was built this way or is there anyway i could enhance the speed for concurrent deployment? (FYI the MDT server is running on a physical server having all the resources to itself, i.e. 64 GB RAM 24 cores etc.)
Question
All replies
Hi, look at this
If your using Server 2012, there is actually a known issue for this:
And you can try increasing the TFTP block size for PXE:
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”
Im running Windows Server 2008 R2 and after reading Villalobos's threads i only knew that MDT 2010 supports multicast.
That's why there is this slow down because I'm deploying multiple machines on unicast Nick. I'm running the MDT Server with WDS role on VMWare, so I'm not really sure what config there is on the switch. Any particular details you need from it?
After enabling multicast from MDT, MDT namespace is showing up on the WDS's Multicast Transmission Folder, and when i tried deploying on 1 machine to see if it works, it got stucked at "Attempting multicast Transfer". Its not copying anything as i see the status of the client in the Multicast Transmission Folder "waiting" only.
Any specific config on the switch is needed to allow this multicast to work?
Jack,
MDT doesn't itself have any RAM or CPU requirements as it is literally just scripts on a network share. The big limiter will be network and disk
Our deployment solution does about 90-110 concurrent deployments and we notice a 2x slowdown in deployment time. We do not use multicast.
- Proposed as answer by Brian Gonzalez Thursday, September 05, 2013 7:40 PM | http://social.technet.microsoft.com/Forums/en-US/107d4cbd-c40b-4633-aa4f-2600f47c11a5/mdt-2012-concurrent-deployment | CC-MAIN-2014-41 | refinedweb | 417 | 59.33 |
fl ,
I replied to the issue
I think It can help a lot to resolve it
@E-Kalla thanks for really digging into the issue. I'd need to read a bit more to understand everything happening.
If you have an approach in mind, could you clearly state it in the issue? If it's to remove
@cached_property i'm not sure the entire range of effects there, in particular with regards to benchmarking
Hi, hope everyone is having a great Monday. I am currently setting up a POST method redirection using
flask.redirect . For some reason, the redirection does not work and I was not able to get any useful logging even when I set
FLASK_ENV=development. Here is the log I got:
127.0.0.1 - - [16/Aug/2021 16:49:57] "POST /runs HTTP/1.1" 200 - [I 210816 16:49:57 _internal:122] 127.0.0.1 - - [16/Aug/2021 16:49:57] "POST /runs HTTP/1.1" 200 -
It seems this endpoint never got redirected.
Anyone has any insight on debugging this issue ?
Unfortunately, I am not able to provide any code here because the redirection works well when I tried to set up some dummy code, but it did not work with a big project that I am currently working on.
here is the log I got for dummy code that I set up:
127.0.0.1 - - [16/Aug/2021 17:04:51] "POST /todos2/1 HTTP/1.1" 307 - 127.0.0.1 - - [16/Aug/2021 17:04:51] "POST /todos/ HTTP/1.1" 200 -
From this log, the endpoint actually got redirected.
marshal_withwhich seems changed returned redirection:
import flask from flask import Flask from flask_restx import Model, Resource, fields, Namespace, abort, Api from werkzeug.middleware.proxy_fix import ProxyFix app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) api = Api(app, version='1.0', title='TodoMVC API', description='A simple TodoMVC API', ) ns = Namespace('todos', description='TODO operations') ns2 = Namespace('todos2', description='TODO operations') todo = Model('todo', { 'id': fields.Integer(required=True, description='The task unique identifier'), 'task': fields.String(required=True, description='The task details'), 'description': fields.String(required=True, description='Put some description here') }) response = Model('response', { 'id': fields.Integer, 'task': fields.String }) ns.models[todo.name] = todo ns.models[response.name] = response todo2 = Model('todo2', { 'task': fields.String(required=True, description='The task details'), 'todo_description': fields.String(required=True, description='Put some description here') }) response2 = Model('response2', { 'id': fields.Integer, 'task': fields.String }) ns2.models[todo2.name] = todo2 ns2.models[response2.name] = response api.add_namespace(ns) api.add_namespace(ns2) @ns2.route('/<int:id>') @ns2.response(404, 'Todo not found') class Todo(Resource): '''Show a single todo item and lets you delete them''' @ns2.doc('get_todo') def get(self, id): '''Fetch a given resource''' return "get todo 2" @ns2.expect(todo2) @ns2.marshal_with(response) def post(self, id): '''Update a task given its identifier''' if id == 1: redirection = flask.redirect(flask.url_for('todos_todo_list', _method='POST'), code=307) return redirection return {"id": "dummy id", "task": "some dummy task here"} @ns.route('/') class TodoList(Resource): '''Shows a list of all todos, and lets you POST to add new tasks''' @ns.doc('list_todos') def get(self): '''List all tasks''' return "get todo list" @ns.doc('create_todo') @ns2.expect(todo) @ns.marshal_with(response) def post(self): '''Create a new task''' payload = ns.payload return {"id": payload.get("id"), "task": payload.get("task")} if __name__ == '__main__': app.run(debug=True)
so the requirement is:
Given an endpoint with a variable (var == $CONDITION), have a redirect only for $CONDITION, otherwise, return properly
My gut would say, if you want a single endpoint, split by condition, to do 2 redirects. One for $CONDITION, one for everything else. and the resultant endpoints handling the marshalling. Because, in the end, if their responses are going to be different, they should probably be considered separate endpoints. | https://gitter.im/python-restx/community?at=609e2f126a950f3d46e42262 | CC-MAIN-2022-21 | refinedweb | 645 | 52.26 |
On Thu, Sep 01, 2005 at 05:46:36PM +0200, Adeodato Sim? wrote: > > What if you get an Internal Compiler Error > ========================================== > > If your package FTBFS on arm, m68k and hppa due to the following: > "internal compiler error: in cp_expr_size, at cp/cp-objcp-common.c:101", > you are being bit by Bug#323133. This bug will be fixed in GCC 4.1, > so until that version enters unstable, you should build your package > with gcc-3.4 in those three architectures. To do that: > > - add "g++-3.4 [arm m68k hppa]" to your Build-Dependencies > - add the following, or similar, snippet to your debian/rules: > > GCC4_ICES_HERE := arm m68k hppa > DEB_BUILD_ARCH ?= $(shell dpkg-architecture -qDEB_BUILD_ARCH) > > ifneq (,$(findstring $(DEB_BUILD_ARCH),$(GCC4_ICES_HERE))) > export CC=gcc-3.4 > export CPP=cpp-3.4 > export CXX=g++-3.4 > endif This isn't really important in this case, because there are no non-Linux ports of arm, m68k or hppa, but it should be noted that the correct way to do this portably would be: GCC4_ICES_HERE := arm m68k hppa DEB_HOST_ARCH_CPU ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_CPU) ifneq (,$(filter $(DEB_HOST_ARCH_CPU),$(GCC4_ICES_HERE))) export CC=gcc-3.4 export CPP=cpp-3.4 export CXX=g++-3.4 endif Note1: as for Build-Depends line, this can't be done portably as of now, but pending changes in dpkg will allow it soon. Note2: s/BUILD/HOST/g change was done not to break cross buildability Note3: s/findstring/filter/g change prevents unwanted sub-string matching -- Robert Millan | https://lists.debian.org/debian-devel/2005/09/msg00020.html | CC-MAIN-2015-48 | refinedweb | 248 | 59.5 |
Results 1 to 10 of 11
Thread: Java File I/O
- Join Date
- Feb 2005
- Location
- At a rock house in Oak Cliff...
- 87
Java File I/O
I'm kind of rusty with my java and I need some help with reading in values from a file. The file being read from is in the format:
Code:
string string int string string int
- Code:
import java.io.*; BufferedReader bfrRead = new BufferedReader(new FileReader("/home/user/temp/the_file")); try { while(bfrRead.open()) { String theLine = bfrRead.readLine(); // Do Stuff } bfrRead.close(); } // Now catch the FileNotFoundException and IOException
Then, while lines are still there, we read them in, line by line. After all lines are read, we close that BufferedReader.
Make sure to catch your Exceptions. I'm 99% sure that only the two I named need to be caught.
And, of course, be sure to import java.io.*;
The 1.4.2 API is at:
If it helps
You might also want to use the java.util.StringTokenizer class to seperate the tokens on a line. (I'd recommend reading the API for it; it's quite useful)
Javasnob has a good idea.
Definitely check out the API. But as a brief overview:
StringTokenizer takes a String and separates it by whitespace into "Tokens". You can then manipulate the Tokens separately:
Code:
String theString = new String("a b c d e f"); StringTokenizer st = new StringTokenizer(theString); while(st.hasTokens()) { String theToken = st.nextToken(); System.out.println(theToken); }
Unrelated to that, but as I just remembered, remember that I/O is done as Strings. So even though you have a string string int string string int format, you will receive them all as Strings.
To change the Strings to ints, you'll need to do:
Code:
int theNum = Integer.parseInt(theStringWithIntValue);
- Join Date
- Feb 2005
- Location
- At a rock house in Oak Cliff...
- 87
Thank you for all your help. I've implemented your suggestions into my code and all is well with the exception of one: for
Code:
while(bfrRead.open())
Code:
The method open() is undefined for the tyoe BufferedReader
Gadzooks!
It's actually
Code:
while(bfrRead.ready())
I always liked doing this with BufferedReader:
Code:
BufferedReader reader = ...; String line; while((line = reader.readLine()) != null) { ... }
- Join Date
- Feb 2005
- 1,044
I thought Java was supposed to be a good language. It certainly makes a meal of doing something that's trivial in a proper language like C.
J2SE 5.0 makes this easier, actually:
Code:
Scanner in = new Scanner(new FileInputStream(file)); while(in.hasNext()) { String str = in.next(); // Process the string }
- Join Date
- Jul 2005
- Location
- Chd,India
- 135
how about using perl regular expressions?The strong shall live and the weak will die
In the end,only the fittest survive in this world
- Shishio Makoto | http://www.linuxforums.org/forum/programming-scripting/43649-java-file-i-o.html | CC-MAIN-2018-26 | refinedweb | 469 | 75.91 |
In this tutorial we’re going to show you how to build a web server with the ESP32 that controls the shaft’s position of a servo motor using a slider. First, we’ll take a quick look on how to control a servo with the ESP32, and then we’ll build the web server.
Watch the Video Tutorial and Project Demo
This guide is available in video format (watch below) and in written format (continue reading).
Parts Required
For this tutorial we’ll use the following parts:
- ESP32 DOIT DEVKIT V1 Board – read ESP32 Development Boards Review and Comparison
- Micro Servo Motor – S0009 or Servo Motor – S0003
- Jumper wires
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Connecting the Servo Motor to the ESP32
Servo motors have three wires: power, ground, and signal. The power is usually red, the GND is black or brown, and the signal wire is usually yellow, orange, or white.
When using a small servo like the S0009 as shown in the figure below, you can power it directly from the ESP32.
But if you’re using more than one servo or other type, you’ll probably need to power up your servos using an external power supply.
If you’re using a small servo like the S0009, you need to connect:
- GND -> ESP32 GND pin;
- Power -> ESP32 VIN pin;
- Signal -> GPIO 13 (or any PWM pin).
Note: in this case, you can use any ESP32 GPIO, because any GPIO is able to produce a PWM signal. However, we don’t recommend using GPIOs 9, 10, and 11 that are connected to the integrated SPI flash and are not recommend for other uses.
Recommended reading: ESP32 Pinout Reference: Which GPIO pins should you use?
Schematic
In our examples we’ll connect the signal wire to GPIO 13. So, you can follow the next schematic diagram to wire your servo motor.
(This schematic uses the ESP32 DEVKIT V1 module version with 36 GPIOs – if you’re using another model, please check the pinout for the board you’re using.)
How to Control a Servo Motor?
You can position the servo’s shaft in various angles from 0 to 180º. Servos are controlled using a pulse width modulation (PWM) signal. This means that the PWM signal sent to the motor will determine the shaft’s position.
To control the motor you can simply use the PWM capabilities of the ESP32 by sending a 50Hz signal with the appropriate pulse width. Or you can use a library to make this task much simpler.
Preparing the Arduino IDE
There’s an add-on for the Arduino IDE this tutorial.
Installing the ESP32_Arduino_Servo_Library
The ESP32 Arduino Servo Library makes it easier to control a servo motor with your ESP32, using the Arduino IDE. Follow the next steps to install the library in your Arduino IDE:
- Click here to download the ESP32_Arduino_Servo_Library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get ESP32-Arduino-Servo-Library-Master folder
- Rename your folder from
ESP32-Arduino-Servo-Library-Masterto ESP32_Arduino_Servo_Library
- Move the ESP32_Arduino_Servo_Library folder to your Arduino IDE installation libraries folder
- Finally, re-open your Arduino IDE
Testing an Example
After installing the library, go to your Arduino IDE. Make sure you have the ESP32 board selected, and then, go to File > Examples > ServoESP32 > Simple Servo.
/********* Rui Santos Complete project details at Written by BARRAGAN and modified(13); // attaches the servo on pin 13 } }
Understanding the code
This sketch rotates the servo 180 degrees to one side, and 180 degrees to the other. Let’s see how it works.
First, you need to include the Servo library:
#include <Servo.h>
Then, you need to create a servo object. In this case it is called myservo.
Servo myservo;
setup()
In the setup(), you initialize a serial communication for debugging purposes, and attach GPIO 13 to the servo object.
void setup() { myservo.attach(13); }
loop()
In the loop(), we change the motor’s shaft position from 0 to 180 degrees, and then from 180 to 0 degrees. To set the shaft to a particular position, you just need to use the write() method in the servo object. You pass as an argument, an integer number with the position in degrees.
myservo.write(pos);
Testing the Sketch
Upload the code to your ESP32. After uploading the code, you should see the motor’s shaft rotating to one side and then, to the other.
Creating the ESP32 Web Server
Now that you know how to control a servo with the ESP32, let’s create the web server to control it (learn more about building an ESP32 Web Server). The web server we’ll build:
- Contains a slider from 0 to 180, that you can adjust to control the servo’s shaft position;
- The current slider value is automatically updated in the web page, as well as the shaft position, without the need to refresh the web page. For this, we use AJAX to send HTTP requests to the ESP32 on the background;
- Refreshing the web page doesn’t change the slider value, neither the shaft position.
Creating the HTML Page
Let’s start by taking a look at the HTML text the ESP32 needs to send to your browser.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="data:,"> <style> body { text-align: center; font-family: "Trebuchet MS", Arial; margin-left:auto; margin-right:auto; } .slider { width: 300px; } </style> <script src=""></script> </head> <body> <h1>ESP32 with Servo</h1> <p>Position: <span id="servoPos"></span></p> <input type="range" min="0" max="180" class="slider" id="servoSlider" onchange="servo(this.value)"/> <script> var slider = document.getElementById("servoSlider"); var servoP = document.getElementById("servoPos"); servoP.innerHTML = slider.value; slider.oninput = function() { slider.value = this.value; servoP.innerHTML = this.value; } $.ajaxSetup({timeout:1000}); function servo(pos) { $.get("/?value=" + pos + "&"); {Connection: close}; } </script> </body> </html>
Creating a Slider
The HTML page for this project involves creating a slider..
<input type="range" min="0" max="180" class="slider" id="servoSlider" onchange="servo(this.value)"/>
You also need to define other attributes like:
- the class to style the slider
- the id to update the current position displayed on the web page
- And finally, the onchange attribute to call the servo function to send an HTTP request to the ESP32 when the slider moves.
Adding JavaScript to the HTML File
Next, you need to add some JavaScript code to your HTML file using the <script> and </script> tags. This snippet of the code updates the web page with the current slider position:
var slider = document.getElementById("servoSlider"); var servoP = document.getElementById("servoPos"); servoP.innerHTML = slider.value; slider.oninput = function() { slider.value = this.value; servoP.innerHTML = this.value; }
And the next lines make an HTTP GET request on the ESP IP address in this specific URL path /?value=[SLIDER_POSITION]&.
$.ajaxSetup({timeout:1000}); function servo(pos) { $.get("/?value=" + pos + "&"); }
For example, when the slider is at 0, you make an HTTP GET request on the following URL:
And when the slider is at 180 degrees, you’ll have something as follows:
This way, when the ESP32 receives the GET request, it can retrieve the value parameter in the URL and move the servo motor to the right position.
Code
Now, we need to include the previous HTML text in the sketch and rotate the servo accordingly. This next sketch does precisely that.
Note: as we’ve mentioned previously, you need to have the ESP32 add-on installed in your Arduino IDE. Follow one of the following tutorials to install the ESP32 board in the Arduino IDE, if you haven’t already:
- Windows instructions – ESP32 Board in Arduino IDE
- Mac and Linux instructions – ESP32 Board in Arduino IDE
Copy the following code to your Arduino IDE, but don’t upload it yet. First, we’ll take a quick look on how it works.
/********* Rui Santos Complete project details at *********/ #include <WiFi.h> #include <Servo.h> Servo myservo; // create servo object to control a servo // twelve servo objects can be created on most boards // GPIO the servo is attached to static const int servoPin = 13; // Replace with your network credentials const char*</script>"); // Web Page client.println("</head><body><h1>ESP32 with Servo</h1>"); client.println("<p>Position: >"); //GET /?value=180& HTTP/1.1 if(header.indexOf("GET /?value=")>=0) { pos1 = header.indexOf('='); pos2 = header.indexOf('&'); valueString = header.substring(pos1+1, pos2); //Rotate the servo myservo.write(valueString.toInt()); Serial.println(valueString); } //(""); } }
How the Code Works
First, we include the Servo library, and create a servo object called myservo.
#include <Servo.h> Servo myservo; // create servo object to control a servo
We also create a variable to hold the GPIO number the servo is connected to. In this case, GPIO 13.
const int servoPin = 13;
Don’t forget that you need to modify the following two lines to include your network credentials.
// Replace with your network credentials const char* ssid = ""; const char* password = "";
Then, create a couple of variables that will be used to extract the slider position from the HTTP request.
// Decode HTTP GET value String valueString = String(5); int pos1 = 0; int pos2 = 0;
setup()
In the setup(), you need to attach the servo to the GPIO it is connected to, with myservo.attach().
myservo.attach(servoPin); // attaches the servo on the servoPin to the servo object
loop()
The first part of the loop() creates the web server and sends the HTML text to display the web page. We use the same method we’ve used in this web server project.
The following part of the code retrieves the slider value from the HTTP request.
//GET /?value=180& HTTP/1.1 if(header.indexOf("GET /?value=")>=0) { pos1 = header.indexOf('='); pos2 = header.indexOf('&'); valueString = header.substring(pos1+1, pos2);
When you move the slider, you make an HTTP request on the following URL, that contains the slider position between the = and & signs.[SLIDER_POSITION]&
The slider position value is saved in the valueString variable.
Then, we set the servo to that specific position using myservo.write() with the valueString variable as an argument. The valueString variable is a string, so we need to use the toInt() method to convert it into an integer number – the data type accepted by the write() method.
myservo.write(valueString.toInt());
Testing the Web Server
Now you can upload the code to your ESP32 – make sure you have the right board and COM port selected. Also don’t forget to modify the code to include your network credentials.
After uploading the code, open the Serial Monitor at a baud rate of 115200.
Press the ESP32 “Enable” button to restart the board, and copy the ESP32 IP address that shows up on the Serial Monitor.
Open your browser, paste the ESP IP address, and you should see the web page you’ve created previously. Move the slider to control the servo motor.
In the Serial Monitor, you can also see the HTTP requests you’re sending to the ESP32 when you move the slider.
Experiment with your web server for a while to see if it’s working properly.
Wrapping Up
In summary, in this tutorial you’ve learned how to control a servo motor with the ESP32 and how to create a web server with a slider to control its position.
This is just an example on how to control a servo motor. Instead of a slider, you can use a text input field, several buttons with predefined angles, or any other suitable input fields.
This is an excerpt from our course: Learn ESP32 with Arduino IDE. If you like ESP32 and you want to learn more about it, we recommend enrolling in Learn ESP32 with Arduino IDE course.
You might also like reading:
-.
82 thoughts on “ESP32 Servo Motor Web Server with Arduino IDE”
GOOD PL. SEND MORE ARTICALS
Help me.
I can not control several servos.
please tell me.
I don’t have any tutorials on controlling multiple servos…
You have any idea about controlling multiple servos and thnx
It’s possible, but I don’t have any tutorials on that exact subject at the moment.
Cool!
I’ve expanded the program to run two servos, so that I can control a tilt/pan for a camera. Next, I’ll add the shutter release button.
Great! I’m glad you’ve found this tutorial useful! 🙂
exactly what i’ll be working on if you don’t mind would you share your code. It would save me and
probably a lot of others a lot of time
Cool! Exactly what I’m looking for Alan. Woud you please share your code. I’m keenly intrested.
Secondly may I ask for the mechanics you have used.
Thank you!
Hi Alan,
if you don’t mind would you share your code with me too?
Thanks a lot!
Regards,
Antonio
Hi Alan, could you pass me the code?
Can you share the code, I will like to understand it for school project
thank u for this , u are great
Hi
Can you tell how did you manage to get that simple servo example working?
As i try it with my Wemos ESP32 OLED board, it says that
#error “This library only supports boards with an AVR, SAM, SAMD, NRF52 or STM32F4 processor.”
and when i look the examples, the simple servo appears into INCOMPATIBLE folder.
I appreciate if you could help me out.
I am developing a BLE temperature tag to control my servo so that it opens a vent of my room according to the outside temp.
I will be using Ruuvi tags.
Thanks,
Jussi
Hi Jussi.
The example we’re using worked just fine when we tested.
Did you installed the right library? The ESP32-Arduino-Servo-Library?
Hello Sara and Rui,
I too am receiving this same error message. I have downloaded using the link provided and renamed the folder but no joy. I have tried this now on two different Wemos d1 mini ESP32 WRoom boards and on an ESP32 Dev Kit. All give the same error message. I have even loaded the Arduino IDE on newly formatted Win10 machine and installed the esp32 addon to the arduino IDE then downloaded the servo library into that and still get the same error.
Any thoughts would be greatly appreciated.
Brian
Hi Brian.
Please note that we’re using this library:
It may conflict with the Arduino Servo library.
So, remove the arduino servo library out of the libraries folder, and the issue should be resolved.
See my answer here:
Regards,
Sara
how i change slider by button OPEN = 180° CLOSE = 0° thx
Hi Francisco.
Instead of the slider, you need to create two buttons on the HTML page: the OPEN and the CLOSE button.
We have a tutorial that creates two buttons with the ESP32 to turn on an LED:
Then, you just need to change what happens when a button is pressed.
Instead of lighting up the LED, copy the code that turns the motor 0º or 180º.
I hope this helps.
Regards,
Sara 🙂
Hi, Sara Santos.
I do not understand html and it’s hard for me to know that I have to replace
Excellent tutorial, thanks for all the information, please can you tell me, what I have to do to control step motors, using the same principle of this tutorial. Thank you
Hi Victor.
At the moment, I don’t have any tutorial about that subject. I’ll prepare an article about that soon.
Regards,
Sara 🙂
Hello, great tutorial. You shoul add that if the chip you will use is the ESP8266, then you have to use the #include instead of #include .
Anyway your tutorials are the best, thank you.
Yes.
Thank you Javier!
🙂
I can control many of them from difference port but not work separately, and i can’t even add another slide in webpage for other servo
how do i control a 7.4v servo with the esp32 ? i dont know how to connect it to an external powewr supply
Hi.
You should connect your external power supply to the servo power pin.
Then, the GND of the servo should connect to the ESP32 GND and to the external power supply GND.
Before wiring everything, please check all the connections and datasheet of your servo motor.
Regards,
Sara
Is there a quick explanation/separate tutorial explaining how this same project could be done but by uploading the html file via SPIFFS? I’ve tried going through the steps from a different tutorial about SPIFFS and deleting the “display html page” client.println lines from the ino file, but i cannot get it to work
Hi Winston.
We have a tutorial about that. It uses SPIFFS and the asynchronous web server library. I’m not sure if you want to stick with this style of web server, or if you didn’t mind using the asynchronous web server:
We have another tutorial that gets the HTML file via SD card and creates a web server using the same style of this tutorial. You may find something useful on the code of that project:
I hope this helps.
Regards,
Sara
Hi Rui,
thank you for this informative and well dokumented tutorial! It works out of the box! Now, after successfull building my first web-server-ESP based application I’m looking for more. I like to build a pan and tild web-cam stand. May be you can help?
Thank you again
Hi.
Thank you for following our tutorials.
Unfortunately, we don’t have any tutorial for what you are looking for.
But you just need to create another servo object, and another servo slider to control a second servo and control the pan and tilt cam.
Regards,
Sara
Might be a dumb question but…can this be controlled from anywhere or do you have to be on the same local network? If so this could be used as a great way to dispense treats for pets away from home 🙂
Hi Steve.
This example is only accessible on your local network.
Regards,
Sara
Hi,
You can use it from outside your home. Just configure your Router in section PORT FORWARDING.
Richard
Heeeeelp please, I am trying to connect an MG995 to my ESP32, I upload the code and it does not do what it should do and I followed all the steps
Hi.
With those details, it is very difficult to understand what can be wrong.
That servo motor probably needs an external power supply.
Regards,
Sara
Hello,
Thank you for all the information.
Im stuck with a problem . When uploading the code in Arduino it shows an error “Fatal error: waiting for packet content”.
I can only fully upload the code succsefully if the ESP32 doesnt have any signal wire connected.
Do you know why?
Thank you!
Hi.
What do you mean by “doesnt have any signal wire connected”.
Read this tutorial and see if it helps:
Regards,
Sara
There is an initial light when it is at 0 and not maximum light at 180 is it because of the servo library. How can I have a 0% PWM and 100% PWM
Hi James.
What do you mean? I think I didn’t understand your question.
You can read our guide about PWM with the ESP32 here:
I hope this helps.
Regards,
Sara
Hi! I don’t get how the html page is linked with the webserver code in Arduino
could you help me with that!?
Take a look at the second sketch.
Everything is explained in detail in the article.
Regards,
Sara
I have everything working with a 12v stepper motor (external 9v supply).
However, I would like to change the min and max range. I can do this by simply changing the values in the input code but I would like to be able to put variables instead.
For example: String leftMAX = -16; String rightMAX = 16.
This works okay:
client.println(“”);
But this doesn’t work:
client.println(“”);
I’m using this to limit the closing of vertical window blinds.
The code didn’t appear in my comment.
Maybe this will:
This works:
‘min=\”-16\” max=\”16\” ‘
This doesn’t:
‘ min=\leftMAX max=\rightMAX’
If the code doesn’t appear again then this is the problem:
I cannot replace the string in min or max with a String variable.
Hope you understand.
GOT IT! After noticing that you used String valuestring = String(0);
I used:
int MAXright = 16;
int MAXleft = -16;
String rightMAX = String(rightMAX );
String leftMAX = String(leftMAX );
This works perfectly.
This way I can adjust the maximum limits of the blinds by changing MAXright and MAXleft and storing them in EPROM.
Hello,
in a comment above I have read that I have to replace the standard servo -library with yours through deleting.
Take a moment take a few deep breaths and think about it…..
You are offering a tutorial for newbees and make them fiddling deep inside the arduino-IDE????
In my opinion this is a nerdy awful style. Does the ESP32 REALLY need its own servo-library?
If the ESP-board really needs it to get it working you should take the effor that the includename should DIFFER from the standard servo-library-name.
What is so hard about using a different filename?
Your tutorials should be foolproof as possible.
So I renamed the servo.h to ESP32servo.h.
I have done copy&paste with the raw code
from
into the Arduino-IDE. The sourcecode compiles and is beeing uploaded into the ESP32-board. The code starts to work and on the serial monitor I get this output.
I can connect with my webbrowser to the shown IP-adress and get the slider.
I can move the slider but I get no serial-output about the new position.
This is the serial output:
22:42:52.634 -> Connecting to WLANBuero
22:42:53.217 -> …………..
22:42:59.720 -> WiFi connected.
22:42:59.720 -> IP address:
22:42:59.720 -> 192.168.178.43
22:43:09.148 -> New Client.
22:43:09.148 -> GET / HTTP/1.1
22:43:09.148 -> Host: 192.168.178.43
22:43:09.148 -> Connection: keep-alive
22:43:09.148 -> Cache-Control: max-age=0
22:43:09.148 -> Upgrade-Insecure-Requests: 1
22:43:09.148 -> User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.137 Safari/537.36 Vivaldi/2.7.1628.33
22:43:09.182 -> DNT: 1
22:43:09.182 -> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3
22:43:09.182 -> Accept-Encoding: gzip, deflate
22:43:09.182 -> Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
22:43:09.218 ->
22:43:09.218 -> Client disconnected.
22:43:09.218 ->
22:43:09.218 -> New Client.
If I understand right the connection gets immediatly closed. So as the code was inserted by a copy & paste, does compile code starts to work
What is wrong?
best regards
Stefan
Hi Stefan.
Follow the suggestion in this discussion, it should solve your problem:
Regards,
Sara
Hi everyone,
First of all, great project, I love the idea of controlling devices from a web page.
I am trying to adapt the project to a relay, but It doesn’t seem to turn off, It is always on, so the current is always passing…
I tried with a led, and it works.
Have you got an idea of what sould I change?
Thank tou very much, and keep making!
Hi Thomas.
To control a relay, we recommend following this tutorial:
Regards,
Sara
Rui Santos thanks for this tutorial & Sara Santos I LUV U !
Hello Rui / Sara
I see your demo wants internet connectivity :
<
script src=””>
What changes could I make for this app to work in AP (Access Point) mode with no web access ?.
Thanks.
Have you find any solution for that yet?
Hello Rui and Sara – firstly, thanks for your inspirational videos and tutorials. You see to use 2 techniques for your web server apps – either as you have in this tutorial with the web text inside the main loop OR using the AsyncTP and ESPASyncWebServer route like you have on others. When should you use which one?
thanks a lot
Hi.
It is better to use the ESPAsyncWebServer library, because it creates an asynchronous web server.
This means that the ESP32 can do other tasks and still have the ability to handle the web server.
In the other technique, the ESP32 is in a loop constantly checking if there is a new request from a client. It is more difficult to add other tasks and still be able to handle the web server.
All our recent projects use the Asynchronous Web server.
Regards,
Sara
Thanks – thats great! I just came across “web sockets”. Do you guys plan to use these at all – (I don’t know what they are or if they work better)
Hi.
Yes, we plan to start publishing some tutorials about that.
Websockets work better 🙂
And can be implemented using the AsyncWebServer library.
Regards,
Sara
Hi Sara,
Thank you again for the nice tutorial. I works on my ESP Wifi and very happy with your code.
Any chance if you can help me to add a Button functions-
for example Button click to servo pos 10deg and few more set buttons in your code.
Cheers.
Sam
Hi
It works only if you have internet connection. How would you set it up if just on ap without internet?
Thanks
Hi.
You can set the ESP32 as an access point instead of a station:
Regards,
Sara
It is not working in Access point mode due to above script.
is there anybody have any alternative solution to work a servo in access point mode with slide bar control (without internet)?
@RuiSantosdotme
#RuiSantosdotme
Hi.
You can try to use websocket instead to control the motors:
Regards,
Sara
Hi.
I wanted to control a DC motor and a servo motor together using ESP32 however I am unable to do this. Either the dc motor will move with full speed and ignoring the dutycycle value while the servo won’t move at all, OR the servo will move but the DC motor won’t and will keep vibrating. This will happen depending on where I attach the servo in my code. If you can help me I would really appreciate it. Thanks in advanced
Hi.
Make sure you’re using different PWM channels for each motor.
Try with different channels. For example, use channel 0 and channel 4.
Regards,
Sara
Dear Rui and Sarah, thank you so much for your work really help to do a lot of useful things.
I liked your slider in this example but I would like the value entered by it to change not at the end of the movement of the slider, but during movement. That is in real time.
Of course, I do not ask you to rewrite the program for me. I will be glad to have a hint or idea on how to do this, if it is of course possible at all.
Most sincerely,
George
Hi.
Use “oninput” instead of “onchange”.
Regards,
Sara
Hello it sems like my servo, a SG90 model goes only half of its way. So its not doing 0-180°, it makes 45-135°. What could be wrong?
thanks
Hi.
How are you powering your motor?
Regards,
Sara
via the yp-05 usb adapter, it is set to 5v and from there i connect the servo, like in the picture here
You may need to power your servo motor using an external power supply.
Regards,
Sara
but in the picture it is not external why is it working for you!
Your USB ports might not provide enough power.
Regards,
Sara
they adapter i meant
Thanks for the tutorial. To control multiple motors, do i need to create a html id for each and copy paste javascript function for each with their respective id. Thank you
Hi.
Yes. That’s correct!
Regards,
Sara
Hi Sara,
I need some help to add few button to get the servo to move to a specific
pos Forward ++ or Back — and a fix button for example 90 and 180deg, can you help with what to add in your code above. Slider works perfectly. I just need the some additional. thanks.
Hi can this code be modified to be used in an Async Webserver? thank you
Hi.
You can use this tutorial instead:
And modify to control a servo motor.
Regards,
Sara
Ya I saw it already after i researched further and looking at it at the moment already, it’s exactly what i needed. Thank you very much
Hi,
How can I control the Servo Speed in this code? | https://randomnerdtutorials.com/esp32-servo-motor-web-server-arduino-ide/?fbclid=IwAR3AL3NH9fmN9bTHKF8We4VFNgbGM1q1tYUpts_V-29Ri4AaCWSytiOyccI | CC-MAIN-2022-27 | refinedweb | 4,856 | 73.78 |
Implementing.
Whenever someone installs your module into their project, it should just work. Granted, there are instances where your users are required to make minor changes to their project files to get certain features to work. But your module should have an out-of-the-box experience that just works without additional set-up.
Similarly, your module shouldn’t have to edit your project’s
Global.asax file to register its own Web API routes. I don’t know if that’s even possible, but then again I’m still an ASP.NET noob. In any case, we’re kinda stuck. We need the module to register its Web API routes, but we don’t want to have the users manually edit the
Global.asax file.
Enter WebActivator. This module allows you to run start up codes in your web applications. You can even choose to run your start up code before the application starts, or after. Pretty cool, huh?
So on to the code. The following code will allow your NuGet module to register its Web API routes during application start up. Much like how Global.asax works.
[assembly: PostApplicationStartMethod(typeof (StartUp), "PostApplicationStart")] namespace MyModule { public static class StartUp { public static void PostApplicationStart() { RouteTable.Routes.Insert(0, new Route("api/{controller}/{action}/{id}", new RouteValueDictionary(new {id = RouteParameter.Optional}), HttpControllerRouteHandler.Instance)); } } }
That’s it. That’s all it takes to get Web API working in your NuGet module.
It’s worth to mention though, that you should set the appropriate path for your route. You could use something like
mymodule/api as the root path, so you know that requests made to this path are routed to your controller. It helps to avoid any potential conflicts.
I hope this helps someone wanting to do something similar. It’s been an interesting learning experience for an ASP.NET noob such as myself.
Wassalam | https://www.dnasir.com/2012/08/07/implementing-web-api-in-your-nuget-module/index.html | CC-MAIN-2019-18 | refinedweb | 313 | 59.6 |
Cannot get opentk 1.1 beta 2 to work with opengl4Posted Sunday, 15 December, 2013 - 00:01 by rwgames in
I get a crash at game.Run() when I'm using the following.
using OpenTK; using OpenTK.Graphics.OpenGL4;
{)":"OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4"}
I've copied opentk.dll into my project folder from OpenTK/1.1/Release but it's not working.
using OpenTK; using OpenTK.Graphics.OpenGL;
The above works but I want everything to use the opengl4 specs, am I going about this the wrong way?
Re: Cannot get opentk 1.1 beta 2 to work with opengl4
"Could not load file or assembly 'OpenTK, Version=1.0.0.0" means Visual studio is trying to load version 1.0 whereas you are providing it with 1.1.
Remove OpenTK from the project References in the Solution Explorer window and readd the new version.
Re: Cannot get opentk 1.1 beta 2 to work with opengl4
I've already done that several times as well as just now, the output window after build shows:
Copying file from "... OpenTK\1.1\Binaries\OpenTK\Release\OpenTK.dll" to "bin\Debug\OpenTK.dll" but still get the same error, I can go with the workaround of using 1.0 and OpenTK.Graphics.OpenGL instead of OpenTK.Graphics.OpenGL4 but it would be nice to not have the older commands in the mix;
I see that opentk.dll is version 1.1.1434.30013 but the opentk.xml is version 1.0, maybe that's the problem!!
Re: Cannot get opentk 1.1 beta 2 to work with opengl4
That's strange. I routinely use Visual Studio 2010/2012/2013, MonoDevelop 2.8/4.0, Xamarin Studio 4.2 and upgrading OpenTK works across all of those. Which IDE are you using?
If you have multiple projects in your solution, make sure that all of them compile against the *same* version of OpenTK.
If you have ever used NuGet for OpenTK, make sure that the NuGet package is uninstalled - otherwise it will keep overwriting OpenTK.dll.
Conversely, if you are using the .exe installer, try uninstalling OpenTK completely from "Add/Remove Programs". You can then try with the .zip release from here:
Re: Cannot get opentk 1.1 beta 2 to work with opengl4
I'm using Visual Studio 2005 with one project in my solution and am not using NuGet. I also uninstalled OpenTK and used the zip from your link and re-added the reference with no luck, same problem.
I am using Matali Physics and when I disabled all physics code with the #define directive then it works. I tried removing both dll's and adding them in different order but for some reason mataliphysics version 1.8 messes with the new version of OpenTK. For now I'll use older OpenTK until I can figure this out.
Re: Cannot get opentk 1.1 beta 2 to work with opengl4
This means that Matali physics is compiled against an older version of OpenTK.dll. Since it's not possible to mix two different versions of a dll in the same process, you will have to use the old version until Matali physics is updated. (It might be worth it to ask them for an updated version.)
Re: Cannot get opentk 1.1 beta 2 to work with opengl4
I contacted Matali Physics and they said they can update once the final version of OpenTK 1.1 is out.
I'm glad to see OpenTK is alive and advancing, keep up the great work and thanks for your help. | http://www.opentk.com/node/3477 | CC-MAIN-2014-42 | refinedweb | 605 | 78.04 |
IMSC basics
IMSC allows you to add subtitles or captions to your online video. In this article we'll take you through what you need to get started, including basic document structure, and the basics of how to style, time, and position subtitles.
Note: IMSC can be used for any kind of timed text you might want to include on a web document, not just for subtitles and captions. But because subtitles and captions represent the most common use cases for IMSC, we will focus on those. For readability we only use the term subtitles. In the technical context we describe, the term "subtitles" is interchangeable with "captions".
So what is IMSC?
IMSC is a markup language you can use to define timed text for adding subtitles to digital media. It defines the structure of your subtitle content in an XML document. It consists of a series of elements, which you can use to enclose, or wrap, different parts of your subtitle content to make it appear in a certain way or appear at a certain time. Many of these are similar or the same as HTML features.
If you are not already familiar with XML or HTML, read up on them first and then come back here:
Note: If you want to know what you can do with IMSC in real world scenarios have a look at the expanded example at the end of this tutorial.
Minimal IMSC document
IMSC is always specified as a complete XML document. As a file it should have the extension "ttml".
Note: IMSC does not have native support in browsers at this current moment, but the imscJS polyfill can be used to bridge this gap. All the examples below are rendered by using imscJS. It creates dynamically HTML and CSS from an IMSC XML document.
Let's look at a minimal IMSC document and how it is rendered:
The most important features are as follows:
<tt></tt>— You always start an IMSC document with the root element
<tt>. You should also specify the default namespace of the document by using the
xmlnsattribute. Don't worry for now about namespaces. We will come to that in a separate guide.
xml:lang— You must specify the language of your content with the
xml:langattribute. Note that the
langattribute must have the prefix
xml:, unlike HTML. In IMSC
<tt lang="en">is not correct — you always have to write
<tt xml:.
<body></body>— As in HTML, the
<body>element contains all content that you want to show. For IMSC this is typically subtitle content that you want to show at certain time intervals during the playback of a video.
<div></div>— The
<div>element is used as a container for subtitle content; you always need to have at least one of these. The
<p>elements that contain the actual subtitle content always have a
<div>element as their parent.
<p></p>— Text content for subtitles must always be wrapped in a
<p>element. The element describes a paragraph of text, in a similar fashion to HTML. The main difference is that it can be timed.
Timing
The minimal IMSC document from the previous example had no timing. That means that the subtitle content will be shown during the complete duration of the video. Usually this is not what you want. Instead you want subtitles to show up at a certain time and then disappear. You can use a combination of the timing attributes
begin,
end, and
dur to make this happen.
Consider the following editable example:
This includes the following new attributes:
begin— specifies when the subtitle shall start to show (in this case 1s after the video started).
end— specifies when the subtitle shall disappear (in this case 2s after the video started).
Play around with the second values in the code sample and push the reload button when you are ready.
Note: The end times in IMSC are not "inclusive". The subtitle "Hello, I am Mork from Ork." is not shown anymore when it reaches the second value in time.
You can also use the
dur attribute for timing:
This attribute can be used as an alternative to the
end attribute. It defines "how long" the subtitle is shown after the
begin time has elapsed. In the example the second paragraph shall be displayed for 2s. As it starts at second 2 it shall disappear at second 4.
Note what has changed at second 2 compared to the previous example.
Colors
Often subtitles are shown on an opaque or semi-opaque background to improve readability. You can use the
backgroundColor and
color attributes to change the colors, as demonstrated in this editable example:
Here we've introduced the following:
tts:backgroundColor— This attribute sets the background color on the element it is applied to. In this case it is applied to the
<p>element, or more correctly to the area that is generated by the
<p>element. The default background color is
transparent.
tts:color— This attribute sets the text color on the element it is applied to. The default text color is
white.
Try setting some other colors for the text and background colors:
- Try other named colors like
limeor
aqua.
- Use hexadecimal values like
#00ff00or
#00ffff.
- You can use other color schemes like
rgb(0,255,255).
- Finally, try semi-transparent variations, like
rgba(0,0,0, 80).
Note: Don't worry for now about namespaces. We will explain the meaning of
xmlns:tts and
tts:backgroundColor in a separate guide.
As explained in the IMSC Styling guide, it is possible to define a collection of styling properties that can be used any number of times. The style
s1 below is applied three times:
<tt xmlns="" xmlns: <head> <styling> <style xml: </styling> </head> <body> <div> <p> Hello, I am <span style="s1">Mork</span> from <span style="s1">Ork</span>.<br/> I come from another <span style="s1">planet</span>. </p> </div> </body> </tt>
Position, width, and length
If you do not specify a position explicitly, the subtitle shows up by default in the top-left-hand corner of the video. Commonly however you will want to position your subtitle somewhere else, like the bottom center of the video. You need to specify a region to position a subtitle.
See below for a minimal document that uses regions for positioning.
<tt xmlns="" xmlns: <head> <layout> <region tts: <region tts: </layout> </head> <body> <div> <p region="bottom" tts: Hello, I am Mork from Ork. </p> </div> </body> </tt>
This includes the following new features:
<head></head>— As in HTML, the
<head>element acts as a container for all the stuff you want to include in an IMSC document that isn't subtitle content, most commonly metadata about the content or document. You'll use it mostly to store positioning and styling information.
<layout></layout>— This element acts as a wrapper for positioning information. It has
<region>elements as its children.
<region></region>— this element can be used to define
regions, rectangular areas you can place on top of your video. They have a defined position, width, and height, plus an
idto uniquely identify them. You can think of it as being similar to a
<div>element in HTML that is given an absolute position, width, and height via CSS. If subtitle content is "linked" to a region (by specifying the region's
idin its
regionattribute), it will be shown inside the area generated by that region.
xml:id- the
xml:idattribute. The value of the
xml:idattribute is a string that can be used to link subtitle content to a
region.
tts:origin— This attribute defines the position of the top-left corner of the region. It uses the % (percentage) metric. The first value defines how far the top left corner of the region is pushed to the right — in this case the value
10%places the region 10% of the video's width to the right. The second value defines how far the top left corner of the region is placed towards the bottom of the video — in this case the value
80%pushes the top left corner of the region 80% of the video's height towards the bottom of the video.
tts:extent— This attribute defines the width and height of the region. In this case
80%sets the width to 80% of the video's width, and
20%sets the height of the region to 20% of the video's height.
region— setting this on some subtitle content and then giving it a region's
xml:idas its value causes it to reference that region, meaning that at the specified time, it will appear in the area defined by that region. So here, the value
bottomplaces the subtitle content represented by this
<p>element in the region with an
xml:idof
bottom.
This sample will be rendered as shown below. Give it a try and play around with the code in the two boxes. You could for example set the
tts:origin attribute to "0% 0%". Or see what happens when you change the value of the
region attribute of the
<p> element to "top".
Expanded example
The more expanded example below gives you an idea what you can do with IMSC after you worked through our tutorials.
<?xml version="1.0" encoding="UTF-8"?> <tt xmlns="" xmlns: <head> <styling> <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: <style xml: </styling> <layout> <region xml: <region xml: <region xml: </layout> </head> <body style="defaultStyle"> <div> <p xml: <span style="titleHeading">IMSC Demo</span> </p> <p xml: <span style="spanDefaultStyle">You </span><span style="blueText">can</span><span style="yellowText"> apply</span><span style="fuchsiaText"> different</span><span style="limeText"> colors, </span> </p> <p xml: <span style="monoFont">use</span><span style="sansserifFont"> different</span><span style="comicFont"> fonts,</span> </p> <p xml: <span>set </span><span tts:the</span><span tts: font size.</span> </p> <p xml: <span style="spanDefaultStyle">Align at the start, </span><br/> </p> <p xml: <span style="spanDefaultStyle">center and</span> </p> <p xml: <span style="spanDefaultStyle">end</span><br/> </p> <p xml: <span style="spanDefaultStyle">or vertically at the top, </span><br/> </p> <p xml: <span style="spanDefaultStyle">center and </span> </p> <p xml: <span style="spanDefaultStyle">bottom.</span> </p> </div> </body> </tt>
Summary
That's it for your crash course in IMSC code basics! We've only really scratched the surface here, and you'll go much deeper into the above topics in subsequent articles. | https://developer.mozilla.org/en-US/docs/Related/IMSC/Basics | CC-MAIN-2022-27 | refinedweb | 1,769 | 62.27 |
So, you just recorded your script and see a polling request from the browser and if that isn’t painful enough you also notice that the time between requests changes. Never fear, we have a plug-in for that.
First, let’s deal with the pesky polling request by using the built-in loops and extraction rules. This is going to be different depending on your developer’s implementation of the polling, and you should observe the traces you have captured to determine a good way to know when all the data has been returned from the server. In this example the response from the polling request contains a value named Status. When Status = Idle I know that all the data has been returned and I can stop polling.
Let me walk you through an example using the code provided.
We can see that there is a response variable named Status, which we know is Idle when the server is finished executing.
So First let us create an extraction rule for Status. I decided to use Regex, and you can use your favorite extraction method.
Next, we create a loop that terminates when status = Idle. In this case we used the string comparison loop.
From the request we notice there is a polling interval, so during the test in order to simulate the traffic generated we need to closely adhere to this polling interval. Let’s extract that value as well.
Next, we apply some test code that creates a request plugin to dynamically set the think time of a request, and allow it to use a context parameter.
public class ThinkTimeFromPolling:WebTestRequestPlugin { [Description("The context parameter that stores the polling value")] public string TargetParam { get; set; } public override void PreRequestDataBinding(object sender, PreRequestDataBindingEventArgs e) { if(e.WebTest.Context[TargetParam] != null) { double Thinktime = double.Parse(e.WebTest.Context[TargetParam].ToString()); e.Request.ThinkTime = Convert.ToInt32(Thinktime/1000); } } }
Finally, we compile then add the plugin to the request inside the loop, setting the extracted polling interval to the think time.
| https://blogs.msdn.microsoft.com/testingspot/2018/02/22/adjustable-think-time-for-dynamic-polling-requests/ | CC-MAIN-2018-13 | refinedweb | 339 | 62.17 |
ares_gethostbyname_file man page
ares_gethostbyname_file — Lookup a name in the system's hosts file
Synopsis
#include <ares.h> int ares_gethostbyname_file(ares_channel channel, const char *name, int family, struct hostent **host)
Description
The ares_gethostbyname_file function performs a host lookup by name against the system's hosts file (or equivalent local hostname database). The channel parameter is required, but no asynchronous queries are performed. Instead, the lookup is done via the same mechanism used to perform 'f' lookups (see the lookups options field in ares_init_options(3)). The parameter name gives the hostname as a NUL-terminated C string, and family gives the desired type of address for the resulting host entry.
The return value indicates whether the query succeeded and, if not, how it failed. It may have any of the following values:
- ARES_SUCCESS
The host lookup completed successfully and host now points to the result (and must be freed with ares_free_hostent(3)).
- ARES_ENOTFOUND
The hostname name was not found.
- ARES_EFILE
There was a file I/O error while performing the lookup.
- ARES_ENOMEM
Memory was exhausted..
Availability
Added in c-ares 1.5.4
See Also
ares_gethostbyname(3), ares_free_hostent(3), ares_init_options(3)
Author
Brad Spencer | https://www.mankier.com/3/ares_gethostbyname_file | CC-MAIN-2018-51 | refinedweb | 192 | 56.45 |
This action might not be possible to undo. Are you sure you want to continue?
Tax), which is common in West European Countries. Concept of VAT was developed to avoid cascading effect of taxes. VAT was found to be a very good and transparent tax collection system, which reduces tax evasion, ensures better tax compliance and increases tax revenue. Modvat (modified value added tax) was introduced in India in 1986 (Modvat was re-named as Cenvat w.e.f. 1-4-2000). The system was termed as Modvat, as it was restricted upto manufacturing stage and credit of only excise duty paid on manufacturing products (and corresponding CVD paid on imported goods) was available. System of VAT was introduced to service tax w.e.f. 16-8-2002. VAT was not extended to sales tax, as sales tax is under jurisdiction of State Governments. However, State Governments have agreed to introduce sales tax VAT and it is likely to be introduced from April 2005. Haryana Government has introduced sales tax VAT in April 2004 and the experience is reported to be good. Integration of goods and service tax - A task force was formed under Chairmanship of Shri Vijay Kelkar on Implementation of Fiscal Responsibility and Budget Management Act. The Kelkar Committee submitted its report in July 2004. The Committee has strongly recommended ‘Goods and Service Tax’ (GST). Full integration of goods and service tax will take considerable time, as it can be achieved only after political consensus is achieved. However, a beginning has been made by proposing to make credit of service tax and excise duty inter-chargeable. Finance Minister Shri P Chidambaram, in para 148 of his budget speech on 8-7-2004, stated as follows, ‘I propose to take a major step towards integrating the tax on goods and services. Accordingly, I propose to extend credit of service tax and excise duty on goods and services. Accordingly, I propose to extend credit of service tax and excise duty across goods and services’. To give effect to this proposal, Cenvat Credit Rules, 2004 have been issued and made effective from 10-92004. Basic Concept of V. This product then goes to distributor/wholesaler, who sells it to retailer and then it reaches the ultimate consumer. If a tax is based on selling price of a product, the tax burden goes on increasing as raw material and final product passes from one stage to other. For example, let us assume that tax on a product is 10% of selling price. Manufacturer ‘A’ supplies his output to ‘B’ at Rs. 100. Thus, ‘B’ gets the material at Rs. 110, inclusive of tax @ 10%. He carries out further processing and sells his output to ‘C’ at Rs. 150. While calculating his cost, ‘B’ has considered his purchase cost of materials as Rs. 110 and added Rs. 40 as his conversion charges. While selling product to C, B will charge tax again @ 10%. Thus C will get the item at Rs. 165 (150+10% tax). As stages of production and/or sales continue, each subsequent purchaser has to pay tax again and again on the material which has already suffered tax. This is called cascading effect. Cascading effect of conventional system of taxes - A tax purely based on selling price of a product has cascading effect, which has the following disadvantages - (a) Computation of exact tax content difficult (b) Varying Tax Burden as tax burden depends on number of stages through which a product passes (c)
Discourages Ancillarisation (d) Increases cost of production (e) Concessions on basis of use is not possible (f) Exports cannot be made tax free. VAT to avoid the cascading effect – VAT was developed to avoid cascading effect of taxes. In the aforesaid example, ‘value added’ by B is only Rs. 40 (150–110), tax on which would have been only Rs. 4, while the tax paid was Rs. 15. In VAT, the idea is that B will pay tax on only Rs 40 i.e. value added by him. Then, it makes no difference whether a product passes through 5 or 10 stages or even 100 stages, as every person will pay tax only on ‘value added’ by him to the product and not on total selling price. Tax credit system - VAT removes these defects by tax credit system. Under this system, credit is given at each stage of tax paid at earlier stage. Illustration of tax credit system - In the example we saw above,.00 and sell his goods at Rs. 140. He will charge 10% tax and raise invoice of Rs. 154.00 to ‘C’. (140 plus tax @ 10%). In the Invoice prepared by ‘B’, the duty shown will be Rs. 14. However, Cenvat. Thus, in effect, ‘B’ has to pay duty only on Rs 40, which is the value added by him. Following example will illustrate the tax credit method of Cenvat.
Transaction without VAT Transaction With VAT Details A B A B Purchases 110 100 Value Added 100 40 100 40 Sub–Total 100 150 100 140 Add Tax 10% 10 15 10
e.14 Total 110 165 110 154 Note . the scheme remains flexible and hence can be modified quickly as per changing requirements. Advantages of tax credit system .f. effectively he is paying only Rs 4/.e. which are now merged with Cenvat Credit Rules. his purchase price is Rs 100/. 2002. 1.(a) Audit control is much better. which helps in controlling tax evasion. Cenvat was introduced in place of Modvat w.e. which is 10% of Rs 40/-.i. His invoice shows tax paid as Rs 14. the manufacturer has made ‘value addition’ of Rs 40 to the product.e.f.as he is entitled to Cenvat credit of Rs 10/. 10-9-2004. 10% of 'value added' by him. 1-7-2001. ‘value added’ is the difference between selling price and the purchase price. Advantages of VAT . Thus. tax paid on purchases. Simply put.4. Section 94(2) of Finance Act.2000. . These are now replaced by Cenvat Credit Rules. Meaning of ‘Value added’ – In the above illustration.e. Most of the countries have adopted ‘tax credit’ method for implementation of VAT. while ‘value’ of output is Rs 150. 10-9-2004.The ‘Tax Credit Method’ has following advantages . with minimum distortion in tax structure .as there are few variations in tax rates and exemptions from taxation are very few.f.'B' is purchasing goods from 'A'.e. New Cenvat scheme MODVAT credit scheme was introduced in 1986 vide rules 57A to 57U. Since rules can be amended easily by Central Government. separate Cenvat Credit Rules were introduced w. Service Tax Credit Rules. 2004 w. it acts as a self-policing mechanism (e) Neutrality i. However.Advantages of VAT are as follows : (a) Exports can be freed from domestic trade taxes (b) It provides an instrument of taxing consumption of goods and services (c) Interference in market forces is minimal (d) Aids tax enforcement by providing audit trail through different stages of production and trade. Later. These were replaced by Cenvat Credit Rules. It acts as a self-policing mechanism (b) Flexibility in applying varying tax rates to different commodities (c) Useful in giving tax benefits on exports or other preferred end-uses like uses by common man etc. since he has got credit of Rs 10/-. vide new set of rules 57AA to 57AK. 2004 w.as tax. i. the ‘value’ of inputs is Rs 110. The disadvantage is that paper work required increases considerably and it is not as simple as a single point sales tax. Thus. 2002 were issued effective from 16-8-2002.f.e. 1994 empowers Central Government to make rules for – (i) credit of service tax paid on services consumed for providing a taxable service in case where the services consumed and the service provided fall in the same category [clause (ee)] (ii) credit of service tax paid on the services consumed or duties paid or deemed to have been paid on goods used for providing taxable service [clause (eee)] (iii) provisions for determining export of taxable services [clause (f)] (iv) Rebate of service tax paid or payable on taxable services consumed or duties paid or deemed to have been paid on goods used for providing taxable services which are exported out of India [clause (h)]. In second case.
No input credit if final product/output service exempt from duty/ service tax .Credit of duty on inputs can be taken up instantly. Light Diesel Oil (LDO) and motor spirit (petrol). 2) Act.The input may be used directly or indirectly in or in relation to manufacture. except high speed diesel oil (HSD). Light Diesel Oil (LDO) and motor spirit (petrol) is not available as Cenvat credit. In case of capital goods. Input may be used directly or indirectly . i.Merging of Cenvat and Service Tax Rules . 2004 states that any reference in any notification.. some services may be taxable while some services may not be covered. Hence. Credit on basis of specified documents . Inputs goods eligible for Cenvat to service provider . he can utilise Cenvat credit only upto 20% of service tax payable on output service. ‘Amount’ is not ‘duty’. rules etc. education cess is payable only on ‘duties of excise’.As per section 91 read with section 93 of Finance (No. fuel etc. General highlights of Cenvat scheme – General highlights of the scheme (except those related to integration of service tax and excise duty credit) are as follows : Credit of duty paid on input and input services . he gets credit of duty paid on inputs and service tax paid on input services. trade notice. 2002 and Service Tax Credit Rules. education cess is not payable on such ‘amount’.Credit will be available of excise duty paid on (a) raw materials (excluding few items) (b) material used in or in relation to manufacture like consumables etc. 2004. used for any purpose. If a manufacturer manufactures more than one product. it may happen that some of the products are exempt from duty. In case of exempt services.No credit is available if final product is exempt from duty or final service is exempt from service tax. The new rules are effective from 10-92004. Rule 16(2) of Cenvat Credit Rules. duty paid on high speed diesel oil (HSD). he should maintain separate records for inputs/input services used for manufacture of exempted final products and should not avail Cenvat on such inputs/input services. The input need not be present in the final product.Cenvat Credit Rules. 2004 have been issued by superseding Cenvat Credit Rules.Credit is to be availed only on the basis of specified documents as proof of payment of duty on inputs or tax on input services. circular. credit is available only after the amount of Bill is paid to person who had provided the service. 2004. However. (c) Paints.The Cenvat scheme is principally based on system of granting credit of duty paid on inputs and input services. he has to pay an ‘amount’ of 10% of price of exempted goods. as soon as inputs reach the factory is received. . in case of service provider. packing materials. Input goods eligible for Cenvat to manufacturer . shall be construed as reference to Cenvat Credit Rules. . 2002 or Service Tax Credit Rules 2002. Credit available instantly . In case of input services. upto 50% credit is available in current year and balance in subsequent financial year.Credit will be available of excise duty paid on inputs used for providing output services. However. duty paid on inputs and service tax paid on input services used for manufacture of exempted products/services cannot be used for payment of duty or tax on other final products/services which are not exempt from duty/tax. to Cenvat Credit Rules. Similarly. 2002. In such cases. However. If the manufacturer/service provider uses common inputs both for exempted as well as un-exempted goods/services. even if these are used as raw materials or as fuel. A manufacturer or service provider has to pay excise duty and service tax as per normal procedure on the basis of ‘Assessable Value’ (which is mainly based on selling price). if he does not maintain separate records and inventories of inputs/input services used in exempted final products/services.e.
This period can be extended. is available. Even input services relating to setting up a factory will be eligible. provided that he brings them back within 180 days.. upto 50% credit is available in current year and balance in subsequent financial year or years.No cash Refund . It may be noted that as per notification No. In addition to this. services like advertising. Cenvat to manufacturer available only if there is 'manufacture' . Credit of duty paid on capital goods – Capital goods used for manufacture of final product and/or used for providing output taxable service will be available. a service provider is not required to pay service tax on . advertising service. security.The highlights of scheme of integration are as follows – Wide definition of ‘input service’ – A manufacturer/service provider will be entitled to credit of service tax paid by him which are used by him directly or indirectly in or in relation to manufacture of final product/provision of output services. motor vehicle has been defined as ‘capital goods’. construction.In some cases. he cannot use the same and the same will lapse. A service provider will be entitled to credit of excise duty paid on raw materials/consumables used by him while providing output service. auditing. Cenvat credit is indefeasible . [In fact. In such cases. Cenvat credit balance at the year end is not income of assessee – CIT v. Refund may also be granted if assessee could not utilise credit for some other reason. Full credit of tax paid on input services . Other exception is Tribunal can order refund when Cenvat credit could not be availed due to fault / wrong action of the department. It was also observed that co-relation between final product and raw materials is not required in Cenvat scheme.In CCE v. all input services relating to all activities relating to business are eligible for Cenvat credit. i. . Integration of Excise duty and service tax credit . which are not directly related to manufacture/provision of output services but are related to the sale of manufactured goods/provision of output services would also be permitted for credit. 1999(112) ELT 353 = 1999 AIR SCW 3205 = (1999) 7 SCC 448 = AIR 1999 SC 3234 (SC 3 member bench). the only exception is in case of exports where duty paid on input material or services used for exported goods is refundable. Cenvat on Capital Goods . market research etc. 12/2003-ST dated 20-6-2003. A service provider can take out capital goods from his premises. However. It may be noted that in case of some service providers.Cenvat Credit Rules do not require input-output correlation to be established. it was held that Cenvat credit validly taken is indefeasible. Indo Nippon Chemicals (2003) 130 Taxman 179 = 155 ELT 452 = 261 ITR 275 (SC). though the Cenvat credit will be available to the manufacturer/service provider. in such cases. Dai Ichi Karkaria Ltd. This would include even services which are received prior to commencement of manufacture/provision of output services. no duty is payable on the final product and question of Cenvat does not arise at all]. Restriction on credit of capital goods . in case of capital goods.Full credit of service tax on services (such as telephone. In fact. spare parts of machinery. credit of goods as inputs used by service providers – Goods used for provision of output services will be treated as inputs even in respect of service provider. tools.Cenvat on inputs or input services is available only if the process is 'manufacture'. activities relating to business like accounting.. dies. However. storage.Credit of duty paid on machinery.However. Cenvat is not available. transport etc. 50% credit will be available in first year and balance 50% in subsequent year/s. plant.e. One-to-one correlation not required . There is no provision for refund of the excess Cenvat credit. Otherwise. it may happen that duty paid on inputs and service tax paid on input services may be more than duty payable on final products.) which are received in relation to the offices pertaining to a manufacturer or service provider would be allowed. even if these are partly used in exempted final product/output services. etc.The restriction of 50% on credit on capital goods would continue for manufacturers as well as service providers..
Service provider providing exempted as well as un-exempted services – A service provider of exempted and non-exempted services not maintaining separate accounts would be eligible to avail Cenvat credit only to the extent of 20% of service tax payable on output services [Till 10-9-2004. Full credit in case of specified input services .goods and materials used by him for providing output services. such as advertising. rent-a-cab scheme operator. ‘Final Product’ means excisable goods manufactured or produced from inputs. A manufacturer not maintaining separate accounts would pay 10% (increased from 8% as credit of service tax is being allowed) of the price of exempted goods. NCCD. education cess. Final products eligible under the Cenvat scheme . In addition. management consultancy etc. erection/ commissioning/ installation etc. The HO/Regional Office will have to register as ‘Input Service Distributor’ with Excise department. and also service tax paid on input services. To enable the manufacturer/service provider to avail credit of such input services. market research. Thus. AED. Such offices which distribute the credit would have to obtain service tax registration.In case of specified services such as construction. but services are actually received in the factory (or factories) or premises of service provider. Motor vehicle will not be treated as ‘capital goods’ for manufacturers or other service providers. Services Billed/received at Head Office/Regional Offices . tour operator. This notification makes it clear that this exemption is not available if Cenvat credit of duty paid on inputs is taken. but credit on motor vehicles would be allowed as ‘capital goods’ only to the service providers of courier.Manufacturers making both exempted and non-exempted goods can maintain separate account in respect of inputs used in exempted and un-exempted final products. or using input service. special. as discussed later) paid on inputs or capital goods received in the factory or premises of service provider. ‘Manufacture’ or ‘production’ means new and identifiable product known in the market. pandal and shamiana operator and goods transport agency. The factory/service provider can avail credit on basis of such invoice. Bills in respect of such services would be received only in these offices. Otherwise full credit would be allowed Persons eligible for credit Rule 3(1) of Cenvat Credit Rules states that a manufacturer or producer of final products and a provider of output service shall be allowed to take credit (hereinafter referred to as the Cenvat credit). Credit on motor vehicles used to provide output service – Motor vehicles are not ‘capital goods’ for purpose of ‘manufacture’. cargo handling agency.In some cases. As per rule 2(h).. The HO/Regional Office will have to issue Invoice to the factory/office providing service. it should be reversed. . If such credit is taken. it was 35%]. service tax. He has to ensure that the total credit allowed does not exceed the eligible credit amount. the Head Office/Regional Offices receive services which are not specific for any factory/premises or service provider. outdoor caterer. EOU units can also avail Cenvat credit. a concept of “input service distributor” has been introduced. the bill/invoice is raised in the name of head office/regional office etc. The Cenvat Credit is of specified duties (basic. ‘manufacturer’ or ‘producer’ is the person who actually brings the final product into existence. Manufacturer making exempted as well as un-exempted final products . credit would be disallowed only when they are used exclusively in relation to manufacture of exempted goods/ services.Cenvat has been extended to all items included in CETA. It would be left to the assessee to decide as to how he distributes the credit among various factories or service providing units. CVD on imported goods etc. Manufacturer eligible for Cenvat credit – Cenvat credit can be availed by ‘manufacturer or producer’ of final products.
Those words will be applicable for purpose of this definition. within the factory of production. client. or as packing material. used in or in relation to the manufacture of final products whether directly or indirectly and whether contained in the final product or not and includes lubricating oils. if he avails Cenvat credit. metals. However.f. he cannot claim excise portion of All India duty drawback rate. except light diesel oil. greases. chemicals. No Cenvat if goods exported and exporter claims duty drawback – An assessee can get export incentives only once. to a customer. As per rule 2(p). leather and wood articles. Statutory definition –Rule 2(k) defines ‘input’ as follows – Rule 2(k) “Input” means – (i) all goods. plastics and rubber products. by amending rule 17(1) of Central Excise Rules – confirmed in CBE&C Circular Nos. or as fuel. as the case may be. he can avail customs portion of duty drawback rate even if he avails Cenvat.Cenvat scheme has been extended to all manufactured final products. Thus. policy holder or any other person. “output service” means any taxable service provided by the provider of taxable service. provider of output service shall be allowed to take Cenvat credit of specified duties and taxes. textile articles. tobacco products. subscriber. Waste and scrap is final product for Cenvat . EOU are entitled to Cenvat credit – EOU units have been allowed to avail Cenvat credit w. . goods used as paint. commonly known as petrol and motor vehicles. Thus. 799/32/2004-CX dated 23-9-2004 and 54/2004-Cus dated 13-10-2004. only a person who is providing taxable output service will be eligible to take Cenvat credit. high speed diesel oil or motor spirit.. However. electrical and electronic goods and automobile sector. Explanation 1. 6-9-2004. new and identifiable product known in the market emerges.MFDR TRU No. Cenvat provisions are available when there is ‘manufacture’ i. 345/2/2000-TRU dated 29-8-2000. accessories of the final products cleared along with the final product. (ii) all goods.The light diesel oil. paper. textile products. Input Goods for Cenvat Inputs which are goods are eligible for Cenvat credit by both manufacturer as well as service provider. subscriber etc. cutting oils. and the expressions ‘provider’ and ‘provided’ shall be construed accordingly. if the processing does not amount to ‘manufacture’ Cenvat credit on inputs is not available. commonly known as petrol.As per Cenvat provisions. high speed diesel oil and motor spirit. are used in definition of each taxable service under section 65(105) of Finance Act. used for providing any output service. high speed diesel oil. Service Provider eligible for Cenvat credit As per rule 3(1). engineering goods. waste or scrap is treated as a final product within definition of rule 57AA(c) [Now new rule 2(h)] and its clearance is as if it is a final product. matches. customer.e. shall not be treated as an input for any purpose whatsoever. except light diesel oil. These goods cover food products. . commonly known as petrol. 1994. The words client.e. motor spirit. coolants. No Cenvat if no ‘manufacture’ Cenvat credit is available only when 'manufacture' takes place. or for generation of electricity or steam used in or in relation to manufacture of final products or for any other purpose.
mere intention to use is not sufficient to avail Cenvat credit. In other words. This has following implications – (1) Second part of the definition is independent of the first part. (This would be so. Inputs should be ‘used’ – mere intention to use is not sufficient – Rule 2(k)(i) which defines ‘inputs’ for manufacturer states that these should be ‘used in the factory’. Inputs eligible for Cenvat under first part of definition The definition of ‘input’ covers following · All goods [except High Speed Diesel Oil (HSD). In or in relation to manufacture of final product . Thus. it is eligible for claiming Cenvat credit. in respect of inputs which are not covered in second part of the definition of ‘inputs’. or as fuel. Light Diesel Oil (LDO) and petrol] used in. Input for a manufacturer – Definition of ‘input’ as far as manufacturer is concerned. Thus. cutting oils and coolants * accessories of final products cleared along with the final product * Goods used as paint * Packing material * Fuel * Goods used for generation of electricity or steam used in or in relation to manufacture of final products or for any purpose. Once a particular item is covered by the definition of ‘input’. it was observed that inclusive definition expands the scope of the expression and cannot be treated as restrictive in any sense. accessories of the final products cleared along with the final product. The input may be used directly or indirectly in or in relation to manufacture of final product. goods used as paint. or for generation of electricity or steam used in or in relation to manufacture of final products or for any other purpose. The reason is rules do not state the purpose for which these are required to be used in the factory). except light diesel oil. CCE 2000(116) ELT 312 (CEGAT 3 member bench). The input need not be present in the final product (first part of the definition) · Input includes * lubricating oils.Explanation 2. even if it is held that the words ‘for any purpose’ apply only to goods used for generation of electricity or steam. (second part of the definition) · Input also includes goods used in manufacture of capital goods which are further used in the factory of manufacturer (Explanation 2 to the definition). the manufacture of the final products. or in relation to. (b) ‘Input’ includes lubricating oils. In Ballarpur Industries v. . is in two parts – (a) all goods. coolants.Input include goods used in the manufacture of capital goods which are further used in the factory of the manufacturer. greases.. used in or in relation to the manufacture of final products whether directly or indirectly and whether contained in the final product or not. within the factory of production.. one need not proceed further and examine the question as to whether the goods (fuel in this case) are used in or in relation to manufacture of final product. if an input is used ‘in the manufacture’ or ‘in relation to the manufacture’. high speed diesel oil and motor spirit. as obviously. greases. The purpose for which these are used is immaterial. requirement of ‘used in or in relation to manufacture’ is not applicable to ‘inputs’ included in second part of definition.The input must be used in or in relation to the manufacture of final product. or as packing material. cutting oils. commonly known as petrol. . as the words used are ‘or for any other purpose’ (2) ‘Inputs’ as defined in second part of definition will be eligible as long as they are used within the factory of production (except accessories of final products cleared along with the final product.These can be used ‘for any purpose’. these cannot be used within factory of production).
One to one correlation not necessary Rule 3(4)(a) states that Cenvat credit may be utilised for payment of any duty of excise on any final product. UOI 2004 (167) ELT 3 = 135 STC 480 (SC). all goods. The electricity for tube-light in kitchen may facilitate cooking. Dai Ichi Karkaria Ltd. Abdul Azeer Sahib (1967) 1 MLJ 190 = AIR 1968 Mad 79. the term 'in relation to manufacture' is a very wide term and covers all inputs which have direct nexus with the manufacturing process. except light diesel oil. UOI (1988) 2 SCR 962 = 1988 2 SCC 299 = (1989) 65 Comp Cas 1 = 1988 (36) ELT 201 (SC) = AIR 1988 SC 782 * Tamil Nadu Kalyana Mandapam Association v. which pre-supposes another subject matter. used for providing any output service is ‘input’. Steel Authority of India 1999 AIR SCW 4016 = AIR 1999 SC 3923 = 1999 (6) SCC 334. it is not as if credit can be taken only on a final product that is manufactured out of the particular raw material to which the credit is related . oil. v. The input need not form part of final product.‘In the manufacture’ means the input is actually used in the manufacture of finished product. . They are not words of restrictive content. The expression ‘in relation to’ is of widest import. Thus. high speed diesel oil. 'In relation to' are words of comprehensiveness which might have both a direct significance or indirect significance depending on the context.‘Relating to’ is equivalent to or synonymous with as to ‘concerning with’ and ‘pertaining to’. Cooking gas and kerosene can also be said to be ‘used in manufacture’. the vegetables. commonly known as petrol and motor vehicles. As per rule 2(k)(ii). However. there is no requirement of establishing relation between inputs/input services and final product.Doypack Systems P Ltd. the term 'inputs' is much more wider than mere 'raw materials'. -.CCE v. While cooking food. that is to say. The expression ‘pertaining to’ is an expression of expansion and not of contraction . Thus. while sandpaper for polishing the table may be said to be used ‘in relation to manufacture’ of the product. but in a restricted way. 112 ELT 353 = AIR 1999 SC 3234 = 1999 AIR SCW 3205 = (1999) 7 SCC 448 (SC 3 member bench). electricity used in mixer or refrigerator can be said to be used ‘in relation to manufacture’.State Waqf Board v. Small Illustration . Thus. Carpenter’s instruments are ‘capital goods’. the input has been used during a process while manufacturing the product like consumable. Input Service for Cenvat . Input goods in respect of service providers Duty paid on input goods used by service providers is also eligible for Cenvat credit. nails and paints are used ‘in the manufacture’ of table. ‘In relation to the manufacture’ means. It may be present in the ‘final product’ in same or similar or identifiable form or it might have got converted during process and may not be seen or identified in the final product. There is no correlation of the raw material and the final product. are used ‘in the manufacture’. but it cannot be said to be ‘used in or in relation to manufacture’ of food. These are words of comprehension which might both have a direct significance as well as an indirect significance depending on the context. motor spirit. either directly or indirectly. wheat flour etc. 'Manufacture' includes all processes incidental or ancillary to manufacture. While manufacturing wooden table. . wood. The expression ‘in relation to’ (so also ‘pertaining to’) is a very broad expression.A small example will illustrate the position. – Thyssen Stahlunion GMBH v.
However. the words used in definition of input service in rule 2(l)(i) are ‘used by a provider of taxable service for providing output service’. in case of input service. The services may be received at head office/regional office. activities relating to business.Manufacturer as well as service provider will be eligible to get Cenvat credit of ‘input services’. modernization. these will be indirectly used for manufacture or providing output service. Credit only after payment is made to service provider Credit of input services can be availed only after the output service provider makes payment of value of input services and the service tax payable on it. However. Input services Used for providing output services – In case of service provider. The inclusive clause makes it clear that services much earlier to manufacture or even after manufacture will be eligible as service tax credit. there is no such requirement. This appears to limit scope of ‘input service’ in respect of output service providers. recruitment and quality control. even there is no requirement that inputs and capital goods should be received in premises of service provider. share registry and security. auditing. Input Service Distributor A manufacturer or service provider may have head office/regional office at different place/s. [Rule 4(7)]. Rule 2(l) of Cenvat Credit Rules reads as follows – Rule 2(l) . Input service need not be received in factory or premises of service provider. [In case of excise duty. whether directly or indirectly. storage upto the place of removal. There is no condition that credit can be availed only after payment is made to supplier of goods]. coaching and training. Service need not be received in factory or premises from where output service provided – In case of inputs and capital goods. market research. advertisement or sales promotion. Cenvat credit is eligible to manufacturer only if these are received in the factory. credit is available as soon as goods are received in the factory.“Input service” means any service – (i) used by a provider of taxable service for providing an output service.e. as shown in invoice of input service provider. . Such head office/regional office will be registered with central Excise and it will have to issue invoice on the manufacturer or producer or service provider. financing. renovation or repairs of a factory. and includes services used in relation to setting up. such as accounting. i. as discussed later. credit rating. In case of service provider. procurement of inputs. Coverage beyond manufacturing/service provision stage Inclusive definition clause of rule 2(l) extends scope of ‘input services’ even beyond stage of ‘manufacture’ or ‘provision of service’. but ultimately. inward transportation of inputs or capital goods and outward transportation upto the place of removal Wide coverage of input services – The words used in the definition in relation to manufacturer are ‘in relation to’. Provision has been made to avail Cenvat credit of services received and paid for at head office/regional office. in or in relation to the manufacture of final products and clearance of final products from the place of removal. the scope has been further widened by ‘adding ‘inclusive definition’ to the rules. or (ii) used by the manufacturer. even to input services which have only remote or insignificant nexus with output services will get covered as long as these are related to activities of business. computer networking. premises of provider of output service or an office relating to such factory or premises.
knives etc. falling under chapter 90 * Grinding wheels and the like goods falling under sub-heading No 6801. in such case.As per rule 2(m). [Thus. ‘invoice. Capital goods used exclusively for exempted final products and output services not eligible – Capital goods used exclusively for manufacture of exempted goods or providing exempt service are not eligible [rule 6(4)]. Document eligible for Cenvat credit . spares and accessories of the goods specified above.As per rule 9(1)(g). 1994 towards purchases of input services and issues invoice. as the case may be.The capital goods should be used – (a) in the factory of the manufacturer of the final products. (vii) Storage Tank. checking and testing machines etc. hand tools. USE OF CAPITAL GOODS . challan for the purposes of distributing the credit of service tax paid on the said services to such manufacturer or producer or provider. falling under chapter heading 68. Capital Goods Eligible to a manufacturer or service provider – Manufacturers and service providers are eligible to avail Cenvat credit of capital goods used by them. Cenvat credit on capital goods will be allowed]. partial use of capital goods for manufacture of exempted goods or provision of exempt output services is permissible. used in the factory. pipes and fittings thereof. bill or. (vi) Tubes. Capital goods for Cenvat 'Capital Goods' for Cenvat Cenvat credit is available on inputs as well as capital goods. Following are the ‘capital goods’. Some provisions are common while there are some specific provisions in respect of Cenvat on capital goods.Who is ‘input service distributor’ . (v) Refractories and refractory material. (iii) Components. falling under chapter 82 * Machinery covered under chapter 84 * Electrical machinery under chapter 85 * Measuring.10 * Abrasive powder or grain on a base of textile material. “input service distributor” means an office managing the business of manufacturer or producer of final products or provider of output service. bill or challan’ issued by an ‘input service distributor’ under rule 4A of Service Tax Credit Rules is an eligible document for purpose of taking Cenvat credit. vide Rule 2(a)(i) of Cenvat Credit Rules (i) * Tools. but does not include any equipment or appliance used in an office . as the case may be. Use of capital goods by manufacturer Rule 2(a) provides that capital goods should be used – (a) in the factory of manufacturer of the final products or (b) for providing output service. which receives invoices issued under rule 4A of the Service Tax Rules. or (2) for providing output service. (iv) Moulds and dies.e. i. Capital goods manufactured within the factory . (ii) Pollution control equipment.02.
Corresponding CVD on imported goods is allowable.f. ‘input’ includes goods used in manufacture of capital goods which are further used in the factory of manufacturer. Corresponding CVD on imported goods is allowable.one credit as Cenvat and another credit as depreciation) Utilisation of Cenvat Credit Duties eligible for credit Assessee can avail credit of duty/ service tax paid on inputs and input services. .f.e. . 1-3-2005. (d) Additional Excise Duty paid under Additional Duties of Excise (Goods of Special Importance) Act [AED(GSI)].e. This duty will not be charged on information technology software.Rule 3(1) states that following duties/taxes will be available as credit (hereinafter referred as Cenvat Credit). – Rule 4(4) of Cenvat Credit Rules (Otherwise. 2001 and corresponding CVD paid on imported goods. (f) Additional Excise Duties paid on textile and textile articles [AED(TTA)]. This credit will not be available to service providers [This duty is payable @ 4% on imports of ITA (Information technology Agreement) bound items and on specified inputs/raw materials. if a manufacturer manufactures some capital goods within the factory. 100% Cenvat credit will be available in the same financial year]. Meaning of Cenvat Credit . goods used to manufacture such capital goods will be eligible as ‘inputs’. 67/95-CE dated 16-3-1995.It may be noted that capital goods manufactured within the factory and used within the factory are exempt from excise duty vide notification No.f. corresponding CVD paid is also eligible [AED(TTA) has been abolished w. (a) Basic excise duty on indigenous inputs [Paid on goods specified in first schedule to CETA].e. credit of corresponding CVD on imported goods can be availed [AED(GSI) on textile articles has been abolished w. 9-7-2004]. (c) Additional Customs Duty paid u/s 3(5) of Customs Tariff Act w. This credit can be utilised only for payment of education cess on final product or output services. This credit can be used for payment of NCD on outputs only and not for any other duty. If these are imported. which are exempt from customs duty. The term ‘Cenvat Credit’ used in various rules means aggregate of following duties and taxes [Rule 3(1)]. the manufacturer will get double deduction for Income Tax .e. (e) Education cess on manufactured excisable goods and CVD equal to education cess on imported goods. for manufacture of electronic/information technology items. 9-7-2004]. Conditions for availing Credit on Capital Goods The conditions for eligibility of Credit are as follows : · Duty paying documents eligible are same for Cenvat on inputs · Depreciation under section 32 of Income Tax Act should not be claimed on the excise portion of the Capital Goods. (g) National Calamity Contingent Duty (NCCD) leviable under section 136 of Finance Act. Thus. (b) Special excise duty [paid on goods specified in Second Schedule to CETA]. [i. If these are imported..As per Explanation 2 to rule 2(k) of Cenvat Credit Rules. This credit is known as ‘Cenvat Credit’.
. (l) Additional Excise Duty paid under clause 85 of Finance Bill. However. service tax on inputs. 2005 [Credit of Additional Excise Duty paid under clause 85 of Finance Bill can be used for payment of this duty. 2005. service tax. This duty has been abolished w. Credit of duty paid under one head can be utilised for payment of duty under other head.f. 2005 w. for manufacture of electronic/information technology items. Proviso to rule 4(2)(a) of Cenvat Credit Rules makes it clear that even if the goods on which this duty is paid are ‘capital goods’. (k) Education cess paid on service tax. Additional Customs Duty paid u/s 3(5) of Customs Tariff Act and AED(GSI) are inter-changeable. Education Cess paid on goods and paid on services is inter-changeable.f. as specified in seventh schedule to Finance Bill.e. This credit will not be available to service providers. AED(TTW) and NCCD. some exceptions are provided in rule 3(7). Basic duty.Rule 4(1) of Cenvat Credit Rules. Credit of basic duty. special excise duty and service tax can be utilised for payment of basic excise duty on final products and vice versa.e. This duty on imports is payable under clause 72 of Finance Bill. This duty is not levied on information technology software]. 1-3-2005. Restrictions on Cenvat credit in certain cases Credit of any duty can be utilised for payment of any duty on final product. upto 50% credit only can be taken at any point of time in a financial year and in any succeeding year or years. full 100% credit will be available in first year itself [This duty is payable @ 4% on imports of ITA (Information technology Agreement) bound items and on specified inputs/raw materials. Any other credit cannot be utilised and balance amount is required to be paid in case only].e. In case of capital goods. SED. as provided in second proviso to rule 5 of Cenvat Credit Rules. Credit of basic duty. SED. This duty is payable w. (i) Additional Excise Duty (Tea and Tea Waste) levied under section 157 of Finance Act. 1-32005 on pan masala and certain tobacco products.e. 1-3-2005. Payment of duty through Cenvat credit is almost as good as payment of duty through PLA and refund is permissible (if otherwise eligible) even if duty was paid through Cenvat credit. but not vice versa. i. This credit can be utilised only for payment of AED(TTW) on final product. Additional customs Duty paid u/s 3(5) of Customs Tariff Act and AED(GSI) can also be utilised for payment of Education Cess. This credit can be utilised only for payment of education cess on final product or output services. Taking and Utilisation of credit Credit of the duty paid on eligible inputs can be taken by the manufacturer immediately on receipt of inputs in the factory of manufacturer or in the premises of provider of output services .(h) Additional Customs Duty paid u/s 3(5) of Customs Tariff Act. AED(GSI).f. 2003. AED(TTA). (j) Service tax on input services. – Rule 4(2) of Cenvat Credit Rules. which are exempt from customs duty.
if assessee opts out of Cenvat – Rule 11(2) Payment of ‘amount’ if goods sent for job work are not returned within 180 days – Rule 4(5)(a). Duty paying documents for Cenvat As soon as a manufacturer/service provider receives an input. Utilisation of Cenvat credit – The Cenvat Credit [as defined in rule 3(1)] can be utilised for payment of any excise duty on : · · · Any duty on any final product manufactured by manufacturer [Rule 3(4)(a)] Payment of ‘amount’ if inputs are removed as such or after partial processing [Rule 3(4)(b)] Payment of ‘amount’ on capital goods if they are removed as such [Rule 3(4)(c)] · Payment of ‘amount’. he is entitled to service tax credit only when he makes payment to service tax provider. he can avail Cenvat credit of the duty paid on the inputs. in case of input service. scrap or waste is dutiable as ‘excisable goods’. if goods are cleared after repairs under rule 16(2) of Central Excise Rules [Rule 3(4)(d)] · Payment under Cenvat Credit Rule 6 of 10% ‘amount’ on exempted goods or reversal of credit on inputs when common inputs or common input services are used for exempted as well as dutiable final products – Explanation I to Cenvat Credit rule 6(3) · · Reversal of Cenvat credit. duty will be payable on these as if it is a 'final product'. It is not necessary to wait till the inputs / capital goods are actually utilised in production [Rule 4(1) of Cenvat Credit Rules].Credit can be taken as soon as goods are received in the factory or premises of service provider. If by-product. Manufacturer/service provider should maintain record of Cenvat credit availed and of credit utilised. (The record should be similar to PLA where credit is taken of duty paid by Challan in Bank and when finished goods are cleared. debit entry is made in PLA). Rule 9(1) of Cenvat Credit Rules prescribes that Cenvat Credit can be taken on the basis of · · · · · · · Invoice of manufacturer from factory Invoice of manufacturer from his depot or premises of consignment agent Invoice issued by registered importer Invoice issued by importer from his premises or consignment registered with Central Excise Invoice issued by registered first stage or second stage dealer Supplementary Invoice Bill of Entry · Certificate issued by an appraiser of customs in respect of goods imported through foreign post office . However. Documentary evidence is required regarding payment of duty on inputs/tax on input services.
In such cases. – (a) (b) (c) (d) payment of duty or service tax description of goods or taxable service assessable value name and address of the factory or warehouse or provider of input service. It is not necessary to maintain separate account in respect of ‘fuel’ used as inputs. the manufacturer/service provider has two options – Maintain separate inventory . he should not avail Cenvat credit of the inputs and input services which are used in exempted final services at all – Rule 6(2) of Cenvat Credit Rules. Bill or Challan issued by input service provider under rule 4A of Service Tax Rules. Cenvat credit is not admissible on such quantity of input or input service which is used in manufacture of exempted goods or exempted services. Cenvat cannot be denied if the documents contains these details and no permission/condonation is required if the invoice/bill/challan contains these basic details Note that Serial Number or name of user-manufacturer is not a essential detail specified in rule 9(2) of Cenvat Credit Rules. Pay 10% ‘amount’ if separate inventory and records not maintained .· · · Challan of payment of tax where service tax is payable by other than input service provider Invoice. it was held that there is no requirement that these must be stored separately. he has to pay an amount equal to 10% of the ‘price’ of such exempted final products. if inputs and input services are partly used in exempted final product/output service. Padmini Polymers 2003(151) ELT 358 (CEGAT). Cenvat credit cannot be denied as long as the document contains essential aspects of duty/tax payment i. In CCE v.If the manufacturer/service provider opts not to maintain such separate accounts. credit of duty or tax can be availed only for payment of duty on final product or output services. Such payment can be made by debit to Cenvat credit account or PLA [rule 6(3) (b)]. credit of duty/tax paid on inputs or input services cannot be availed. Thus.e. As per Rule 6(1) of Cenvat Credit Rules. Essential requirement of invoice –As per rule 9(2) of Cenvat Credit Rules. if no duty is payable on final product or output services. Thus.Maintain separate inventory and accounts of receipt and use of inputs (except fuel) and input services used for exempted final products/exempted output services. As a natural corollary. bill or challan issued by provider of input service on or after 10-9-2004 Invoice. . In such cases. Partial manufacture/provision of exempted products/services It may happen that same inputs/input services are used partly for manufacture of dutiable goods/taxable services and partly for exempted goods/services. Exempted final products/output services As per basic principle of VAT. Cenvat credit of that portion of input/input service will not be available.
6/2002-CE dated 1-3-2002. services on which no service tax is leviable are also ‘exempted services’. education cess is payable only on ‘duties of excise’. deemed exports or gold manufacture .As per Rule 2(d) of Cenvat Credit Rules.In case of output service. 2) Act. he can avail Cenvat only to the extent of 20% of service tax payable on final product. EHTP or STP. “exempted services” means taxable services which are exempt from the whole of the service tax leviable thereon. 'exempted goods' means goods which are exempt from whole of duty of excise leviable thereon and includes goods which are chargeable to 'Nil' rate of duty. 2004. which are exempt from duty. payment of ‘amount’ or reversal of Cenvat is not required. if a particular service is not taxable under present provisions of Finance Act. Payment of ‘amount’ on exempted final products If assessee opts not to maintain separate accounts in respect of inputs and input services utilised for exempted final products/exempted output services. it will be ‘exempted service’ for purpose of rule 6. Thus. (e) Goods supplied against International Competitive Bidding in terms of Notification No. (c) (d) When final product is exported under bond without payment of duty Gold or silver arising in course of manufacture of copper or zinc by smelting. Meaning of ‘exempted services’ As per rule 2(e). Exempted goods do not mean non-excisable goods .Goods which are not mentioned in Tariff are not ‘exempted goods’ as they are neither ‘goods chargeable to 'Nil' duty as per Tariff’ nor ‘goods which are exempt by a notification issued under section 5A’. . the manufacturer is not entitled to avail Cenvat credit on inputs when final product is cleared without payment of duty. (b) Final product is supplied to United Nations or an international organisation for their official use or supplied to projects funded by them. In other cases. Meaning of 'exempted goods' . and includes services on which no service tax is leviable under section 66 of Finance Act. in following cases – (a) Final product is despatched to SEZ. EOU. if he does not maintain separate accounts. 'exempted goods' for purpose of Cenvat cover (a) Goods chargeable to 'Nil' duty as per Tariff and (b) Goods which are exempt by a notification issued under section 5A.As per section 91 read with 93 of Finance (No. Thus. ‘Amount’ is not ‘duty’. he has to pay ‘amount’ of 10% of total price (excluding taxes) of exempted final product [rule 6(3)(b)]. When payment of ‘amount’ is not required In certain cases. assessee need not reverse Cenvat credit or pay any ‘amount’.For purpose of the definition of ‘exempted services’.. This provision does not apply to service providers. Credit of service tax limited if service provider does not maintain separate accounts . Export of goods. Services on which no tax is payable are also ‘exempt services’ . Hence.As per rule 6(6). See discussions in a subsequent paragraph. education cess is not payable on such ‘amount’. a manufacturer can avail Cenvat credit on inputs when final product is despatched without payment of duty. if such goods are exempt from customs duty when imported in India In such case. 1994.
no duty is payable as per notification No. He should take credit only of inputs and input services intended for use of taxable output service [rule 6(2)]. This view has been confirmed in CBE&C circular No. He can utilise it in future if opportunity arises. However. the intermediate products cleared are not ‘exempted goods’. . Since credit has been taken on the inputs. In such case. if tax paid on input services is Rs 75. Inputs used in manufacture of capital goods used within the factory – Notification No. since the goods are not sold. ‘amount’ is not payable. as he has obtained inputs without payment of excise duty. 785/18/2004-CX dated 17-5-2004. These input services are used both for taxable output services and exempt/non-taxable output services. 67/95-CE exempts capital goods manufactured within the factory and used within the factory. In such case. In such cases. Input/services used for exempted as well as taxable services If input services are partly used for taxable services and partly for exempted services assessee should maintain separate accounts of input and input services meant of exempted services and taxable services. assessee can avail and utilise credit of entire Rs 15. For example. Limit on Cenvat credit if assessee does not maintain separate accounts . then assessee can actually utilise credit of only Rs 20. from factory/premises of service provider after payment of an ‘amount’. He will have to pay balance in cash. but can utilise credit of Rs 20. The balance may remain in his Service Tax Credit Account. It is clarified in the circular that exporter of final product will not be entitled to duty drawback of excise portion. control over their removal is necessary. even if credit of Rs 55 is still available in his books.). [The limit was 35% upto 10-9-2004].If the manufacturer/service provider is not able to use the inputs (on which he has availed Cenvat credit) for any reason (like rejection. there is no question of any ‘price’ and hence no ‘amount’ should be payable.No payment of amount if intermediate product cleared for subsequent export . he can clear the inputs as such or after partial processing or capital goods as such. However. exports etc. He may take credit of Rs 75 in his Service Tax (Receivable) Account. he may have to remove the inputs from his factory or premises of output service provider for (a) (b) sale or disposal if these are not required by him or job work/processing in an outside factory and return (c) rejected inputs for rework and return. excess supply. change in production plan. Removal of inputs / capital goods ‘as such’ for sale/disposal . a view is possible that ‘amount’ is payable on such capital goods. and these are used both for exempted and taxable services. Hence. 43/2001-CE(NT) dated 26-6-2001. occasionally. Service tax paid on input service is Rs 15. Removal of goods ‘as such’ A manufacturer/service provider who obtains the inputs / capital goods gets immediate credit of the duty paid by supplier on the inputs used by him. However.If assessee does not maintain separate accounts.If intermediate products are cleared to another manufacturer for manufacture of final products (and then final products are exported by that another manufacturer). assume that service tax payable on output service is Rs 100. The manufacturer/service provider uses these inputs / capital goods for manufacture of final products. quality problems. he can avail Cenvat only upto 20% of tax payable on taxable output service.
‘as such’ can only mean ‘as it is’. Removal of capital goods after use Provisions of rule 3(5) apply when inputs or capital goods are removed ‘as such’. as ‘amount’ is not ‘excise duty’. In other words. no education cess was paid. Removal for job work/repairs/testing In modern manufacturing technology. and obtain the same back after processing/test/repairs is carried out. Often department insists on payment of ‘amount’ on your selling price or depreciated value. It is observed that some assessees even mention the amount as ‘duty’ in their invoice. equivalent ‘amount’ would be payable. a manufacturer usually does not carry out all the processes himself. it cannot be said that these are removed ‘as such’. Thus. This has no legal basis. neither ‘amount’ nor ‘duty’ is payable. Thus. which is totally incorrect. testing. Similarly. Hence. reconditioning or any other purpose. education cess was paid. question of its payment does not arise even if goods are cleared now. In such cases. Duration is not specified. without payment of duty/amount. If originally. Cenvat eligibility of capital goods is established. the inputs should be recorded as per Cenvat procedures and these can be sent to job work as per usual Cenvat procedures . Hence rule 3(4) cannot apply. This will be particularly so if some parts were replaced during use or the capital goods was removed after dismantling. ‘Duty’ cannot be demanded. he can clear the inputs received by him for further processing/test/repairs etc. a manufacturer or service provider may also have to remove inputs as such or after some processing for test.The inputs / capital goods can be removed as such or after partial processing to job worker for further processing. In the present context.Amount payable equal to Cenvat credit availed – The inputs or capital goods can be removed as such from the factory of manufacturer or premises of service provider on payment of an ‘amount’ equal to Cenvat credit availed when the credit was taken. Selling old machinery cannot by any stretch of imagination be termed as ‘manufacture’ and no excise duty is payable. Provisions for sending inputs / capital goods for job work/testing/repairs . Hence. as assessee has certainly not manufactured the capital goods. Procedure also available for goods under DEEC scheme .Hyderabad Commissionerate Trade Notice No. CVD has been paid on the inputs. He can clear inputs/capital goods as such or after carrying out partial processing. repairs etc. it amounts to reversal of Cenvat credit taken [rule 3(5)]. repairs. If capital goods are used and then sold/cleared. If originally. It is common that some manufacturing processes are carried out by him from other manufacturer or subcontractors on job-work basis. ‘as such’ means ‘in the exact sense of the word’. Rule 2(a)(A) states that capital goods should be ‘used’.Provisions contained in Rule 4(5)(a) of Cenvat Credit Rules for this purpose are as follows : Removal for processing/test . . 71/95 dated 5-7-1997 . even if the capital goods are used for one day. As per Concise Oxford Dictionary. rule 3(5) does not apply and capital goods can be removed without payment of any ‘amount’ after use.In case of inputs received under DEEC scheme. The rules make no provision for removal of capital goods after use.Para 3.
. and the expression ‘job worker’ shall be construed accordingly. . the goods should be returned to the factory or premises of service provider within 180 days.rule 4(5)(a). It is a current account of Cenvat credit received. 214/86-CE dated 25-3-1986] Goods Should be returned to factory/premises of service provider . Record of input services – The manufacturer of final products or the provider of output service shall maintain proper records for receipt and consumption of the input services. If these are not received back within 180 days of their being sent out. This should give details of (a) credit availed against each input / capital goods (b) credit utilised against clearance of final products or removal of input as such or after processing or removal of capital goods as such (c) Balance credit available. Payment can be through Cenvat credit or PLA. credit utilised and credit balance.Cenvat Credit record should be maintained. Procedures and Records for Cenvat The main procedures are— · · Maintaining records of inputs and capital goods Maintaining records of credit received and utilised · Submit returns of details of Cenvat credit availed. Principal Inputs and utilization of Principal Inputs in forms ER-1 to ER-6 (Discussed in earlier chapter) · Returns by dealer/service provider/input service distributor Record of inputs and capital goods . which is similar to PLA. The record should contain relevant information regarding (a) value (b) duty paid (c) the person from whom inputs / capital goods have been procured. Job Work means processing or working upon of raw materials or semi-finished goods supplied to job worker.The manufacturer of final products or provider of output service or input service distributor shall maintain proper records for the receipt.After carrying out the operation/test/repair etc. Burden of proof regarding admissibility of Cenvat credit is on the manufacturer or provider of output service taking the credit – Rule 9(5) of Cenvat Credit Rules. The record should contain relevant information regarding – (a) Value of service (b) Tax paid (c) Cenvat Credit taken and utilised (d) Person from whom input service has been procured The burden of proof regarding the admissibility of Cenvat credit shall lie upon the person taking such credit. manufacturer/service provider should pay an ‘amount’ equivalent to Cenvat credit attributable to inputs / capital goods. [rule 9(6)] Cenvat Credit Record . consumption and inventory of the inputs and capital goods.Job work and job worker – As per rule 2(n) of Cenvat Credit Rules. so as to complete a part or whole of the process resulting in the manufacture or finishing of an article or any operation which is essential for the aforesaid process. disposal. If the inputs / capital goods come back after 180 days (say after 220 days). manufacturer/service provider can take Cenvat credit of duty paid by him . [The definition of ‘job work’ is same as given in Notification No.
Principal Inputs.Returns – A manufacture has to be submit returns to Range Superintendent of Central Excise in the prescribed forms ER-1 to ER-6 in respect of Cenvat Availed.. These are discussed in earlier chapter and hence not reproduced here. utilization of Principal inputs etc. by provider of output services [rule 9(9)] · Half yearly return within one month from close of half year. Others have to submit returns as follows · Quarterly return by first stage/second stage dealer within 15 days from close of quarter [rule 9(8)] · Half yearly return within one month from close of half year. by Input Service Distributor [rule 9(10)] .
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/60573225/CENVAT | CC-MAIN-2017-04 | refinedweb | 10,473 | 58.48 |
Tutorial: Create and configure an Azure Active Directory Domain Services managed domain
Azure Active Directory Domain Services (Azure AD DS) provides managed domain services such as domain join, group policy, LDAP, Kerberos/NTLM authentication that is fully compatible with Windows Server Active Directory. You consume these domain services without deploying, managing, and patching domain controllers yourself. Azure AD DS integrates with your existing Azure AD tenant. This integration lets users sign in using their corporate credentials, and you can use existing groups and user accounts to secure access to resources.
You can create a managed domain using default configuration options for networking and synchronization, or manually define these settings. This tutorial shows you how to use default options to create and configure an Azure AD DS managed domain using the Azure portal.
In this tutorial, you learn how to:
- Understand DNS requirements for a managed domain
- Create a managed domain
- Enable password hash synchronization
If you don't have an Azure subscription, create an account before you begin.
Prerequisites
To complete this tutorial, you need the following resources and privileges:
- An active Azure subscription.
- If you don't have an Azure subscription, create an account.
- An Azure Active Directory tenant associated with your subscription, either synchronized with an on-premises directory or a cloud-only directory.
- You need global administrator privileges in your Azure AD tenant to enable Azure AD DS.
- You need Contributor privileges in your Azure subscription to create the required Azure AD DS resources.
- A virtual network with DNS servers that can query necessary infrastructure such as storage. DNS servers that can't perform general internet queries might prevent the ability to create a managed domain.
Although not required for Azure AD DS, it's recommended to configure self-service password reset (SSPR) for the Azure AD tenant. Users can change their password without SSPR, but SSPR helps if they forget their password and need to reset it.
Important
You can't move the managed domain to a different subscription, resource group, region, virtual network, or subnet after you create it. Take care to select the most appropriate subscription, resource group, region, virtual network, and subnet when you deploy the managed domain.
In this tutorial, you create and configure the managed domain using the Azure portal. To get started, first sign in to the Azure portal.
Create a managed domain
To launch the Enable Azure AD Domain Services wizard, complete the following steps:
- On the Azure portal menu or from the Home page, select Create a resource.
- Enter Domain Services into the search bar, then choose Azure AD Domain Services from the search suggestions.
- On the Azure AD Domain Services page, select Create. The Enable Azure AD Domain Services wizard is launched.
- Select the Azure Subscription in which you would like to create the managed domain.
- Select the Resource group to which the managed domain should belong. Choose to Create new or select an existing resource group.
When you create a managed domain, you specify a DNS name. There are some considerations when you choose this DNS name:
- Built-in domain name: By default, the built-in domain name of the directory is used (a .onmicrosoft.com suffix). If you wish to enable secure LDAP access to the managed domain over the internet, you can't create a digital certificate to secure the connection with this default domain. Microsoft owns the .onmicrosoft.com domain, so a Certificate Authority (CA) won't issue a certificate.
- Custom domain names: The most common approach is to specify a custom domain name, typically one that you already own and is routable. When you use a routable, custom domain, traffic can correctly flow as needed to support your applications.
- Non-routable domain suffixes: We generally recommend that you avoid a non-routable domain name suffix, such as contoso.local. The .local suffix isn't routable and can cause issues with DNS resolution.
Tip
If you create a custom domain name, take care with existing DNS namespaces. It's recommended to use a domain name separate from any existing Azure or on-premises DNS name space.
For example, if you have an existing DNS name space of contoso.com, create a managed domain with the custom domain name of aaddscontoso.com. If you need to use secure LDAP, you must register and own this custom domain name to generate the required certificates.
You may need to create some additional DNS records for other services in your environment, or conditional DNS forwarders between existing DNS name spaces in your environment. For example, if you run a webserver that hosts a site using the root DNS name, there can be naming conflicts that require additional DNS entries.
In these tutorials and how-to articles, the custom domain of aaddscontoso.com is used as a short example. In all commands, specify your own domain name.
The following DNS name restrictions also apply:
- Domain prefix restrictions: You can't create a managed domain with a prefix longer than 15 characters. The prefix of your specified domain name (such as aaddscontoso in the aaddscontoso.com domain name) must contain 15 or fewer characters.
- Network name conflicts: The DNS domain name for your managed domain shouldn't already exist in the virtual network. Specifically, check for the following scenarios that would lead to a name conflict:
- If you already have an Active Directory domain with the same DNS domain name on the Azure virtual network.
- If the virtual network where you plan to enable the managed domain has a VPN connection with your on-premises network. In this scenario, ensure you don't have a domain with the same DNS domain name on your on-premises network.
- If you have an existing Azure cloud service with that name on the Azure virtual network.
Complete the fields in the Basics window of the Azure portal to create a managed domain:
Enter a DNS domain name for your managed domain, taking into consideration the previous points.
Choose the Azure Location in which the managed domain should be created. If you choose a region that supports Azure Availability Zones, the Azure AD DS resources are distributed across zones for additional redundancy.
Tip
Availability Zones are unique physical locations within an Azure region. Each zone is made up of one or more datacenters equipped with independent power, cooling, and networking. To ensure resiliency, there's a minimum of three separate zones in all enabled regions.
There's nothing for you to configure for Azure AD DS to be distributed across zones. The Azure platform automatically handles the zone distribution of resources. For more information and to see region availability, see What are Availability Zones in Azure?
The SKU determines the performance and backup frequency. You can change the SKU after the managed domain has been created if your business demands or requirements change. For more information, see Azure AD DS SKU concepts.
For this tutorial, select the Standard SKU.
A forest is a logical construct used by Active Directory Domain Services to group one or more domains. By default, a managed domain is created as a User forest. This type of forest synchronizes all objects from Azure AD, including any user accounts created in an on-premises AD DS environment.
A Resource forest only synchronizes users and groups created directly in Azure AD. For more information on Resource forests, including why you may use one and how to create forest trusts with on-premises AD DS domains, see Azure AD DS resource forests overview.
For this tutorial, choose to create a User forest.
To quickly create a managed domain, you can select Review + create to accept additional default configuration options. The following defaults are configured when you choose this create option:
- Creates a virtual network named aadds-vnet that uses the IP address range of 10.0.2.0/24.
- Creates a subnet named aadds-subnet using the IP address range of 10.0.2.0/24.
- Synchronizes All users from Azure AD into the managed domain.
Select Review + create to accept these default configuration options.
Deploy the managed domain
On the Summary page of the wizard, review the configuration settings for your managed domain. You can go back to any step of the wizard to make changes. To redeploy a managed domain to a different Azure AD tenant in a consistent way using these configuration options, you can also Download a template for automation.
To create the managed domain, select Create. A note is displayed that certain configuration options such as DNS name or virtual network can't be changed once the Azure AD DS managed has been created. To continue, select OK.
The process of provisioning your managed domain can take up to an hour. A notification is displayed in the portal that shows the progress of your Azure AD DS deployment. Select the notification to see detailed progress for the deployment.
The page will load with updates on the deployment process, including the creation of new resources in your directory.
Select your resource group, such as myResourceGroup, then choose your managed domain from the list of Azure resources, such as aaddscontoso.com. The Overview tab shows that the managed domain is currently Deploying. You can't configure the managed domain until it's fully provisioned.
When the managed domain is fully provisioned, the Overview tab shows the domain status as Running.
Important
The managed domain is associated with your Azure AD tenant. During the provisioning process, Azure AD DS creates two Enterprise Applications named Domain Controller Services and AzureActiveDirectoryDomainControllerServices in the Azure AD tenant. These Enterprise Applications are needed to service your managed domain. Don't delete these applications.
Update DNS settings for the Azure virtual network
With Azure AD DS successfully deployed, now configure the virtual network to allow other connected VMs and applications to use the managed domain. To provide this connectivity, update the DNS server settings for your virtual network to point to the two IP addresses where the managed domain is deployed.
The Overview tab for your managed domain shows some Required configuration steps. The first configuration step is to update DNS server settings for your virtual network. Once the DNS settings are correctly configured, this step is no longer shown.
The addresses listed are the domain controllers for use in the virtual network. In this example, those addresses are 10.0.2.4 and 10.0.2.5. You can later find these IP addresses on the Properties tab.
To update the DNS server settings for the virtual network, select the Configure button. The DNS settings are automatically configured for your virtual network.
Tip
If you selected an existing virtual network in the previous steps, any VMs connected to the network only get the new DNS settings after a restart. You can restart VMs using the Azure portal, Azure PowerShell, or the Azure CLI.
Enable user accounts for Azure AD DS
To authenticate users on the managed domain, Azure AD DS needs password hashes in a format that's suitable for NT LAN Manager (NTLM) and Kerberos authentication. Azure AD doesn't generate or store password hashes in the format that's required for NTLM or Kerberos authentication until you enable Azure AD DS for your tenant. For security reasons, Azure AD also doesn't store any password credentials in clear-text form. Therefore, Azure AD can't automatically generate these NTLM or Kerberos password hashes based on users' existing credentials.
Note
Once appropriately configured, the usable password hashes are stored in the managed domain. If you delete the managed domain, any password hashes stored at that point are also deleted.
Synchronized credential information in Azure AD can't be re-used if you later create a managed domain - you must reconfigure the password hash synchronization to store the password hashes again. Previously domain-joined VMs or users won't be able to immediately authenticate - Azure AD needs to generate and store the password hashes in the new managed domain.
[Azure AD Connect Cloud Sync is not supported with Azure AD DS][/azure/active-directory/cloud-sync/what-is-cloud-sync#comparison-between-azure-ad-connect-and-cloud-sync]. On-premises users need to be synced using Azure AD Connect in order to be able to access domain-joined VMs. For more information, see Password hash sync process for Azure AD DS and Azure AD Connect..
In this tutorial, let's work with a basic cloud-only user account. For more information on the additional steps required to use Azure AD Connect, see Synchronize password hashes for user accounts synced from your on-premises AD to your managed domain.
Tip
If your Azure AD tenant has a combination of cloud-only users and users from your on-premises AD, you need to complete both sets of steps.
For cloud-only user accounts, users must change their passwords before they can use Azure AD DS. This password change process causes the password hashes for Kerberos and NTLM authentication to be generated and stored in Azure AD. The account isn't synchronized from Azure AD to Azure AD DS until the password is changed. Either expire the passwords for all cloud users in the tenant who need to use Azure AD DS, which forces a password change on next sign-in, or instruct cloud users to manually change their passwords. For this tutorial, let's manually change a user password.
Before a user can reset their password, the Azure AD tenant must be configured for self-service password reset.
To change the password for a cloud-only user, the user must complete the following steps:
Go to the Azure AD Access Panel page at.
In the top-right corner, select your name, then choose Profile from the drop-down menu.
On the Profile page, select Change password.
On the Change password page, enter your existing (old) password, then enter and confirm a new password.
Select Submit.
It takes a few minutes after you've changed your password for the new password to be usable in Azure AD DS and to successfully sign in to computers joined to the managed domain.
Next steps
In this tutorial, you learned how to:
- Understand DNS requirements for a managed domain
- Create a managed domain
- Add administrative users to domain management
- Enable user accounts for Azure AD DS and generate password hashes
Before you domain-join VMs and deploy applications that use the managed domain, configure an Azure virtual network for application workloads. | https://docs.microsoft.com/en-us/azure/active-directory-domain-services/tutorial-create-instance | CC-MAIN-2021-43 | refinedweb | 2,411 | 54.12 |
How to pass custom AJAX parameters to handle function in components
2 years ago
So you'd like to pass custom parameters by AJAX (GET/POST) from custom javascript to a handle in your component (maybe nested)? Well, you're in luck. ;)
Sure you could use
$this->getRequest()->getPost(); in a
component handle, but where's the fun in that? Plus, it's ugly.
The cool thing to do is to use one of the following approaches in a latte in which you have your scripts for the mentioned component.
$.post( // or $.get(), it doesn't matter {link MyHandleLink!}, { 'acrProductsControl-datum': $('.someElem').val() // 1 - name the component and param manually {$control->getParameterId('date')}: $('.someElem').val() // or 2 - get existing form element name {$control->name . '-datum'}: $('.someElem').val() // or 3 - get name of the component and add custom param name }, function (payload) { not important now } );
The best option is #3 because you get the component name dynamically, so you
don't need to change it when you move the component under another, e.g. And you
can use custom parameter name in your handle function like this even though the
element's actual name is
date, not
datum.
public function handleMyHandleLink($datum) { // some logic }
The option #2 is fixed to existing element in the component's form.
The option #1 allows creating of custom names but is not dynamic.
How does it work
The automatic
$control variable leads to an instance of your
component to which the template belongs to.
The whole thing depends on proper parameter names. You need to use ‘dash’ notation just like you would when addresing nested components in presenter template when you want to render them. This way Nette knows what component the transfered parameter belongs to.
TODO
Maybe polish this a bit and publish it in the official documentation.
Last edited by meridius (2016-05-18 10:55)
2 years ago
I use
$control->getParameterId('date') in my
applications.
Or I've just wrapped component to namespace.
<section data- ... </section>
At last, you have to figure it out in javascript, maybe by front-end developer in bigger team.
Last edited by Felix (2016-05-18 13:12) | https://forum.nette.org/en/26336-how-to-pass-custom-ajax-parameters-to-handle-function-in-components | CC-MAIN-2017-47 | refinedweb | 362 | 55.44 |
Created on 2013-01-11 14:43 by brett.cannon, last changed 2013-03-01 12:54 by python-dev. This issue is now closed.
For test discovery to work where a dependent module is optional, you end up needing to do something like what is done in:
-crypt = support.import_module('crypt')
+def setUpModule():
+ # this import will raise unittest.SkipTest if _crypt doesn't exist,
+ # so it has to be done in setUpModule for test discovery to work
+ global crypt
+ crypt = support.import_module('crypt')
That's kind of ugly. It would be better if unittest recognized SkipTest at import time during test discovery
Agreed and it should be easy to implement.
FTR there is already an alternative to setupmodule:
try:
import module
except ImportError:
module = None
@unittest.skipUnless(module, 'requires module')
class ModuleTests(unittest.TestCase):
pass
This idiom is more lines than support.import_module, but works for non-stdlib tests too, and is useful when you don’t want the whole file to be skipped if the module is missing (like in distutils’ test_sdist where zlib can be missing).
FWIW the difference between support.import_module and the try/except/skip is that usually the former is used when *all* the tests require the imported module, whereas the latter is used when only some of the tests requires it.
Without the proposed enhancement, you could also combine Éric's approach with the original patch by doing something like:
try:
support.import_module(module)
except SkipTest:
module = None
def setUpModule():
if module is None:
raise SkipTest()
Should be: "module = support.import_module('module')"
Still, raising SkipTest from the toplevel is useful when some toplevel setup code otherwise depends on the missing module.
I agree that raising SkipTest (or subclasses thereof, such as ResourceDenied) at module level should be supported. That would mean no changes would be needed in most of the should-be-skipped-but-fail-instead tests listed in issue 16748 to make test discovery play nicely, and in fact the changes to test_crypt could be mostly reverted.
Personally, I don't find either of the suggestions given as alternates to what I did in test_crypt to be particularly prettier, not that what I did is pretty either.
Here's a patch that I believe nicely handles the raising of unittest.SkipTest at module level while doing test discovery. It adds a _make_skipped_test function to unittest.loader, and an ``except case.SkipTest`` clause to TestLoader._find_tests. For our own test package, this covers non-enabled resources as well.
Here's some example output:
"""
P:\cpython>python -m unittest discover -v Lib/test/ "test_curs*"
test_curses (unittest.loader.ModuleSkipped) ... skipped "Use of the 'curses' res
ource not enabled"
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK (skipped=1)
[102289 refs, 38970 blocks]
"""
The patch looks good - can you add a test and documentation for this?
Sure can. With a little luck, I'll have the patch ready later today; with less luck it'll be sometime later this week.
I think this patch should cover the test and Doc changes necessary. Of course, let me know if it doesn't :)
Thanks for the review, Ezio. I've made some changes and here's the new patch.
LGTM.
New changeset 61ce6deb4577 by Ezio Melotti in branch 'default':
#16935: unittest now counts the module as skipped if it raises SkipTest, instead of counting it as an error. Patch by Zachary Ware.
Applied, thanks for the patch!
SkipTest should probably be documented, but that's a separate issue :)
New changeset 22b6b59c70e6 by Ezio Melotti in branch 'default':
#16935: update test_crypt now that unittest discover understands SkipTest. | http://bugs.python.org/issue16935 | CC-MAIN-2014-52 | refinedweb | 597 | 65.12 |
35079/connect-to-hive-using-pyhive
I have installed HDP 2.5 Sandbox on my windows system. I want to access Hive running on Sandbox using Python (to be specific "pyhive" library).
I am able to login to the HDP. The IP address is 127.0.0.1. I have installed pyhive library. However, I am unable to connect from system to Sandbox from python.
Can you suggest what to do?
Here's how we can connect to Hive using pyhive
from pyhive import hive
import pandas as pd
#Create Hive connection
conn = hive.Connection(host="127.0.0.1", port=10000, username="username")
# Read Hive table and Create pandas dataframe
df = pd.read_sql("SELECT * FROM db_Name.table_Name limit 10", conn)
print(df.head())
The problem is with your hive authentication. ...READ MORE
JDBC is not required here.
Create a hive ...READ MORE
Use org.apache.hive.jdbc.HiveDriver as your driver ...READ MORE
make a dummy table which has at least one row.
INSERT ...READ MORE
Seems like the host IP is not ...READ MORE
Hi,
I am trying to run following things ...READ MORE
Firstly you need to understand the concept ...READ MORE
org.apache.hadoop.mapred is the Old API
org.apache.hadoop.mapreduce is the ...READ MORE
hash_id, COLLECT_LIST(num_of_cats) AS ...READ MORE
You can use the get_json_object function to parse the ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/35079/connect-to-hive-using-pyhive | CC-MAIN-2021-31 | refinedweb | 252 | 71.82 |
Forum:David Bowie move?
From Uncyclopedia, the content-free encyclopedia
Forums: Index > Ministry of Love > David Bowie move?
Note: This topic has been unedited for 3181 days. It is considered archived - the discussion is over. Do not add to unless it really needs a response.
I've been working on a rewrite of David Bowie- however I've doen the rewrite in my namespace, and I feel pretty ready to move it over. I was wondering whether an admin would want to huff the old one and replace it with my one (my preference) or whether I should move the old one to David Bowie/Classic with a link it my one? you can have a look at my one here.--— Sir Sycamore (talk) 11:14, 5 June 2008 (UTC)
- Yeah, the rewrite looks good. I could merge the two histories together if you want, saves having an old less good version lying around in mainspace, and lets you keep both histories intact. • Spang • ☃ • talk • 17:45, 05 Jun 2008
- Whatever you think is best-however I was conerned about reverts by IPs to the old version?--— Sir Sycamore (talk) 17:51, 5 June 2008 (UTC)
- Shouldn't be a problem, if anyone was especially attached to any part of the old one, they could try and work it back in. I don't think anyone will though. • Spang • ☃ • talk • 18:02, 05 Jun 2008
- Cool;) Thanks again--— Sir Sycamore (talk) 18:03, 5 June 2008 (UTC)
- The old one is a big old bag o'shite anyway. Kill it I say. -- Sir Mhaille
(talk to me) | http://uncyclopedia.wikia.com/wiki/Forum:David_Bowie_move%3F | CC-MAIN-2017-09 | refinedweb | 267 | 80.82 |
US6144999A - Method and apparatus for file system disaster recovery - Google PatentsMethod and apparatus for file system disaster recovery Download PDF
Info
- Publication number
- US6144999AUS6144999A US09087261 US8726198A US6144999A US 6144999 A US6144999 A US 6144999A US 09087261 US09087261 US 09087261 US 8726198 A US8726198 A US 8726198A US 6144999 A US6144999 A US 6144999A
- Authority
- US
- Grant status
- Grant
- Patent type
-
- Prior art keywords
- file
- local
- remote
-
Abstract
Description
The present invention relates generally to file system disaster recovery systems and, particularly, to geographical replication systems.
Computer systems are subject to any number of operational and environmental faults, ranging from disk failures and power outages to earthquakes and floods. While repair or replacement of damaged equipment is costly, the interruption of access to critical data may be far more severe. For this reason, businesses are taking great precautions to ensure the availability of their data.
The simplest guard against failure is replication. By replicating a system component, a spare is ready to take over if the primary should fail. Replication can occur at many levels, according to the faults it guards against.
The simplest way to replicate only data is with tape backups. Tape backups are a popular replication strategy because they are simple and inexpensive. They ensure that data is safe if a disk or entire machine is damaged or destroyed. Further, if tapes are taken off-site or stored in a protective vault, tape backups can protect data against site-wide disasters. However, tape backups only guard against the ultimate unavailability--data loss. Restoring data from a tape can take hours, or even days, and all changes since the most recent tape backup are lost.
Replicating disks, through widespread strategies such as RAID, protects against the failure of a single disk. Many vendors offer disk replication solutions that are efficient and easy to manage. With disk replication, recovery from a disk failure can be fast and invisible to applications. However, disk replication does not account for the failure of the host machine or destruction of the entire site. In conjunction with tape backups, data loss can be prevented, but availability will suffer with higher-level failures.
Replication of a server machine protects against hardware and software errors on the data server. Disks can be dual-ported, allowing more than one machine direct access to raw data. Along with disk replication strategies, a replicated server can provide high availability even after single disk and single server failures. Just as with replicated disks, tape backups can guard against data loss in a site-wide failure, but extended downtime will still occur.
Replicating an entire site across extended distances, called "geographic replication," increases data availability by accounting for site-wide faults, such as extended power outages, fires, earthquakes, or even terrorist attacks. In a geographic replication system, normal system operation occurs at a local site. Data is mirrored to a remote site, which can take over system functions if the local site is lost. Geographic replication does not mirror application address spaces or any other volatile memory; only data written to stable storage devices is transmitted to the remote site. Distributing cluster storage across extended distances is complex and time-consuming; consequently, failover to the remote site cannot be performed as efficiently and invisibly as failover to a secondary server or hot-swapping a new disk into a storage array. Geographic replication provides blanket protection for high availability; i.e., when all other techniques fail, a complete site failover can still occur under a geographic replication regime.
A generic geographic replication system 100 is shown in FIG. 1. This system has a local site 102 comprising a file server 104, file storage 106 (e.g., a hard disk drive), and clients 108, 110. Note that the term "local" as used in the present application is relative; i.e., the local site is simply the site whose server normally serves the clients 104. The local site 102 is coupled to a remote site 112, possibly by a wide area network (WAN). The remote site 112 includes a file server 114 and file storage 116. Data is mirrored from the local disk 106 to the remote disk 116 in the course of normal operation of the local server 104 so that, if a failure should occur, the remote server is able to serve file requests from the clients 108 or 110 with minimal or no loss of file system state.
A geographic replication system must be able to capture all state changes (hereafter referred to as writes) to file systems and raw devices. Self-consistency must always be maintained at the remote site. Even if the remote site is not current with the primary site, it must be internally consistent. Geographic replication of data must be invisible to applications. The replication system must support at least two levels of data safety: 1-safe and 2-safe (for more information, see Jim Gray and Andreas Reuter, "Transaction Processing: Concepts and Techniques," Morgan Kaufmann, San Francisco, Calif., 1993, which is entirely incorporated herein by reference).
In 1-safe, or asynchronous, mode, a replication system logs operations at the primary site and periodically replicates the data to the remote site. In 1-safe mode, the log of operations not yet applied to the remote site must be serializable and consistent with the operations applied to the local site. Thus, although the remote site may lag behind the local site, it is almost impossible for an operation to be applied at the remote site that was not applied to the local site, and it is almost impossible for operations to be applied at the remote site in a different order than they were applied at the local site. At start-up, the local and remote must automatically synchronize their data so that any future mutually applied operations result in identical states. The geographic replication system must be compatible with any replication services provided by database (for more information, see Oracle, "Oracle7 Distributed Database Technology and Symmetric Replication," available at:) or other applications. 2-safe, or synchronous, mode copies data to the remote site before an operation on the local site is allowed to complete. The replication system could also support an additional level of data consistency called very safe mode. Very safe mode enhances 2-safe mode, adding a two-phase commit protocol to ensure consistency between the local and remote sites. The synchronization (or resynchronization) of local and remote sites that occurs in very safe mode should not require the local site to be taken off-line. Read-only access to the remote site should be available during normal operation. The replication service should automatically configure and start itself at system boot. This can be accomplished using boot scripts and user-level programs that invoke the replication API. The replication service should provide file deletion protection.
Replicating data across geographically separated sites is not a new idea. Several vendors already offer geographic replication solutions, which are now briefly described.
EMC
EMC supports geographic replication in its Symmetrix product (for more information, see EMC, "Symmetrix 3000 and 5000 ICDA Product Description Guide," available at: and EMC, "SRDF--Symmetrix Remote Data Facility," available at: 2.htm). Symmetrix is a storage hardware unit compatible with Sun servers and the Solaris operating system. The Symmetrix Remote Data Facility (SRDF) provides geographic replication for Symmetrix customers. SRDF requires use of a Symmetrix storage system at both the local and remote sites. The local Symmetrix unit is connected to the remote Symmetrix unit with an ESCON fibre link. Basic ESCON links are limited to 60 kilometers, but with an additional device on the sending and receiving ends, ESCON data can be transmitted over wide area networks.
SRDF is implemented entirely within the Symmetrix unit. Writes are applied to the disk on the local site and transmitted to the remote site along the ESCON link either synchronously or non-synchronously, depending on the mode of operation. SRDF documentation makes no mention of a stable log, meaning that transactions might be lost if a crash occurs before transmission can occur.
Further, SRDF is not well suited for long distances with respect to performance. SRDF supports non-synchronous replication in two ways: semi-synchronous and adaptive copy. In adaptive copy mode, data is transferred from the local site to the remote site with no return acknowledgments. In semi-synchronous mode, an I/O operation is performed at the local site, after which control is returned to the application. The written data is then asynchronously copied to the remote site. No other write requests for the affected logical volume are accepted until the transfer of the initial request has been acknowledged. Since SRDF is implemented in the storage unit, I/O operations are expressed as low-level SCSI or ESCON directives. A write system call could translate to several commands to the storage system, some modifying data and others modifying file system metadata. If each of these individual commands must be acknowledged across a wide area network before the next can proceed, performance at the local site will suffer.
SRDF does include a synchronous mode of operation. Updates are first applied to the local site. The data is then transmitted to the remote site. The operation on the local site cannot return until an acknowledgment has been received from the remote site. This synchronous mode is 2-safe, but not very safe. If the local site were to fail after committing the update but before transmitting it to the remote site, then the two sites would be inconsistent. Further, SRDF provides no log by which to determine the transactions that were lost in a site failure.
Implementing replication at such a low-level has other disadvantages. First, since SRDF connects two Symmetrix storage units, only the storage system is replicated at the remote site. If a disaster incapacitates the local site, a server will have to be bootstrapped at the remote site, reconstructing the file system, before data will be available. A second problem with the low-level approach is that replication occurs on the granularity of entire volumes, rather than files and directories. Also, the hardware for mirrored volumes must be symmetric at the two sites. Finally, SRDF is a mixed hardware and software solution--all components of the storage system must be purchased from EMC.
Uniq
Uniq takes a high-level approach to replication with a new file system called UPFS (for more information, see Uniq Software Services, "UPFS--A Highly Available File System," Jul. 21, 1997, White Paper Available at:). Based on VFS, UPFS does not require specialized hardware. It transparently manages several file systems in parallel, locally using native file systems and remotely using NFS. Thus, geographic replication is performed using NFS protocols over Unix networking protocols.
Unfortunately, NFS may not be ideally suited for geographic replication. NFS protocols do not provide good utilization of a wide area network. For instance, name lookup occurs one component at a time. Opening a file deep in the directory hierarchy requires a large number of RPCs, incurring a significant latency over an extended distance. Also, every successful write operation returns a complete set of file attributes, consuming precious bandwidth (for more information, see Nowicki, Bill, "NFS: Network File System Protocol Specification," RFC 1094, March 1989, available at: 1094.txt). Another potential shortcoming of NFS is that it does not support exporting and mounting of raw devices. For efficiency, many databases operate on raw devices rather than files in a structured file system. Since NFS does not support operations on raw devices UPFS cannot provide geographic replication for these products.
In addition, Uniq makes no mention of 2-safe or very safe capabilities. Replication is performed asynchronously to optimize performance on the local site.
Qualix
Qualix implements geographic replication with its DataStar product (for more information, see Qualix, "Qualix DataStar Primer and Product Overview," April, 1997, White Paper available at:-- wp.html). DataStar uses a special Solaris device driver installed between the file system and regular device drivers to intercept writes to raw and block devices. DataStar logs these writes, and periodically a daemon process transmits the log to the remote site via TCP/IP. The log is chronologically ordered for all disk volumes within user-defined logical groups.
DataStar captures I/O commands below the file system, which controls the layout of data arid metadata on the disk volume. This requires a restriction on the symmetry of the local and remote sites. Specifically, a replicated logical device on the local site must be mapped to a logical device on the remote site, and, of course, the device on the remote site must be at least as big as the device on the local site. The one-to-one mapping is not considerably restrictive until a change is necessary. For instance, enlarging a replicated file system or adding new replicated file systems could require disruptive repartitioning at the backup site.
Qualix makes no mention of 2-safe or very safe modes of operation. However, DataStar logs replicated operations at the local site, allowing a retrieval of the transactions that were lost in a site failure.
DataStar shares another characteristic with other low-level approaches to replication in that decisions must be made on the granularity of entire volumes rather than directories or files.
In summary, the present invention is a file system disaster recovery system that employs geographical replication of data.
In particular, the present invention is a geographical data replication system that enables selected file system data to be replicated from a local site to a remote site such that, when the local site fails, clients of the local site are able to resume file operations at the remote site with little or no loss of file state. Many features of the present invention are embodied in geographical replication software executed on both the local and remote sites. At the local site, the software selects the file system data to be replicated and transfers the data to the remote site according to a particular transfer mode. At the remote site, the software logs and stores the transferred data so that local site operations can be transitioned to the remote site.
Common aspects of preferred embodiments are described in terms of system-topology, functionality, failure characteristics, administration and performance; these terms are defined in the detailed description.
A preferred embodiment of the geographical replication system includes interconnected remote and local file servers, each running the geographical replication software of the present invention, compatible operating systems and respective file systems (the same or different). Each site has associated stable file storage, such as one or more hard disks or tape storage units. The geographical replication software running on the local site intercepts all file system requests issued by local clients. The software determines whether a requested operation will modify the file system (e.g., file writes) and, if so, attempts to replicate the operation to the remote site. The system operates in a particular mode (either 1-safe, 2-safe or very-safe) that determines whether the local site software merely passes the file system request to the local file system following a replication attempt (1-safe mode) or delays handing off the request to the local file system until it has heard from the remote site software that the replication operation was complete (2-safe, very safe).
The replication software transfers only file system data, which includes file system operations, files and partitions and excludes application state. Because the software transfers only file system data, the replication system can be configured to replay file system operations at any level of the file system. For example, in one preferred embodiment the local and remote file systems can include four levels: a distributed/cluster file system (PXFS), a Unix file system (UFS) and device drivers, such as a volume manager (VM) and a SCSI driver (SD). In such a system the PXFS, UFS, VM or SD operations can be replicated to and replayed on the remote site. Moreover, because operations are being replicated and not application state, there is no need for the file storage to be similarly formatted, or the file systems to be identical, or the servers to be similarly configured (e.g., either or both of the servers could be a cluster or a single server).
In a preferred embodiment the file servers typically include a cache where file data in active use is maintained until it is written back to the file storage. The software interacts with the cache so that it replicates file system operations only when those operations are actually being written from the cache to the file storage.
A preferred embodiment can be configured to operate in the context of a high availability file system where a primary server (e.g., the file server mentioned above) operates in cooperation with a secondary server. When configured in this manner, the primary and secondary servers are each coupled to the stable file storage, which is dual ported. The primary server responds to file system (e.g., PXFS) requests from clients and checkpoints all necessary information (including application state) to the secondary so the secondary can take over operations even in the case of a minor failure by the primary server. Both the primary and secondary servers are configured to execute the replication software as described above; however, the software only executes in the server that is online. In the prior art, the primary and the secondary servers communicate using a high availability file system protocol (e.g., Sun HA-PXFS). The present invention modifies the checkpoint information transferred between the primary and secondary under HA-PXFS so the secondary can execute the replication software in case the primary goes down.
In any of the embodiments, the file storage can be distributed or singular. For example, in an embodiment where a file server includes a cluster of personal computers, each with a single ported disk, the file storage can be distributed across any subset of the disks. This is enabled in the present invention by the fact that client requests are made to the file servers using a distributed file system (PXFS).
Additional objects and features of the invention will be more readily apparent from the following detailed description and appended claims when taken in conjunction with the drawings, in which:
FIG. 1 is a block diagram of a generic geographic replication system architecture;
FIG. 2 is a block diagram of a preferred embodiment of a geographic replication system wherein the local and remote sites each employ a single file server;
FIG. 3 is a block diagram of data structures associated with the embodiment of FIG. 2;
FIG. 4 is a diagram illustrating functional relationships between the operating system, file system components and applications that are common to both the prior art and the present invention;
FIG. 5 is a functional flow diagram illustrating transparent file access operations across multiple nodes of a cluster employing a distributed file system, such as PXFS;
FIG. 6 is flow diagram illustrating a first method employed by the present invention to transfer log information from a local site to a remote site;
FIG. 7 is flow diagram illustrating a second method employed by the present invention to transfer log information from a local site to a remote site;
FIG. 8 is a diagram of the log file 264 of a preferred embodiment;
FIG. 9 is a diagram showing the relationship between the log file 264 of FIG. 8 and the log anchor of a preferred embodiment; and
FIG. 10 is a block diagram of a preferred embodiment of a geographic replication system wherein the local and remote sites include primary and secondary file servers configured to be highly available.
Common aspects of preferred embodiments are described in terms of system topology, functionality, failure characteristics, administration and performance; these concepts are now defined.
Topology: The topology of a geographic replication system is the way in which its components are assembled. The topology of preferred embodiments allows arbitrary distance between the remote and local sites. That is, the location of each site is limited only by the reach of the network to which the sites are connected. Additionally, apart from the requirements that there must be sufficient storage space on the remote site for the replicated data and the two sites must be capable of running compatible versions of geographic replication software in which the present invention is embodied, the local and remote sites need not have symmetrical hardware. The present system can also be configured to allow arbitrary groupings of multiple local sites and multiple remote sites. That is, a local site can replicate data to more than one remote site, and a remote site can backup data for more than one local site. Moreover, the geographical replication software can be configured to support a variety of network protocols and to be independent from the type of storage hardware of either site. If running in a cluster with global networking, the server on the local site can be configured to use other than a direct network connection.
Functionality: Functionality refers to the operation of a geographic replication system. The geographic replication system of the present invention captures all state changes (hereafter referred to as writes) to file systems and raw devices. Self-consistency is always maintained at the remote site even if the remote site is not current with the local site. In a preferred embodiment, geographic replication operations are invisible to applications. The replication system of the present invention can be configured to support at least two levels of data safety, including 1-safe and 2-safe modes, which are defined in the background. In 1-safe, or asynchronous, mode, the present invention logs operations at the local site and periodically replicates the data to the remote site. In 2-safe, or synchronous, mode, the present invention copies data to the remote site before an operation on the local site is allowed to complete. Regardless of the mode, at start-up the local and remote sites automatically synchronize their data so that any future, mutually-applied operations result in identical states. Additionally, the geographic replication system can be configured to be compatible with any replication services provided by database (for more information, see Oracle, "Oracle7 Distributed Database Technology and Symmetric Replication," available at:., which is entirely incorporated herein by reference) or other applications running on the local or remote sites.
The replication system of the present invention can also be configured to support an additional level of data consistency called very safe mode. Very safe mode enhances 2-safe mode, adding a two-phase commit protocol to ensure consistency between the local and remote sites. Additionally, the replication system can be configured so that:
1) the synchronization (or resynchronization) of local and remote sites does not require the local site to be taken off-line;
2) read-only access to the remote site is available during normal operation;
3) the replication system automatically configures and starts itself at system boot; and
4) protection is provided against file deletion.
Failure Characteristics: Failure characteristics define the behavior of the geographic replication system in the event of a failure. In 1-safe mode, the local site continues operation after failure of or loss of connection to the remote site. After temporary loss of connection to, or failure of, the remote site, the local and remote sites resynchronize automatically. The present invention is configured so that manual switchover to the remote site is always possible after failure of the local site. That is, the remote site is always ready to perform reading and writing transactions after a local failure. In both 1-safe and 2-safe modes, the amount of data lost in a failure of the local site can be estimated in terms of the time since the previous log flush, the size of the unflushed data, or the number of operations that have not been transmitted to the remote site. No data is lost in very safe mode.
Additionally, the present recovery system can be configured to provide a log of lost transactions to be used by the local site after it has been restored after a failure. Preferably, the remote site takes over automatically after failure of the local site. Also, in a preferred embodiment when the original local site is restored after failing over to the remote site, it can be automatically resynchronized and reinstalled as the local site.
Administration: Ease of administration is critical to the acceptance of the geographic replication system. As the flexibility and number of features increase, administration grows in importance. The geographic replication service of the present invention provides a user-level API to support management programs or applications that need to change replication characteristics. Default values are provided for parameters whenever possible. Alternatively, the present invention provides a wizard to assist in administration of the replication system.
Performance: The critical performance issue is the extent to which the present geographic replication system degrades the performance of local site operations (e.g., reads and writes). When the geographic replication system is in synchronous (2-safe) mode, writes are greatly slowed due to the need to delay writes until the relevant data is replicated on the remote sites. In 1-safe mode, the performance of writes on the local site is degraded by no more than ten percent. In all normal modes of operation, the performance of reads is degraded negligibly or not at all. System write operation for the very safe mode is even slower than in the 2-safe mode due to the 2-phase commit process associated with that mode.
Referring to FIG. 2, there is shown a block diagram of a preferred embodiment 120 of a geographic replication system that can be used to replicate file system data from a local site to a remote site. It is assumed that the operating system running on all sites is Sun Solaris; however, the teachings of the present invention are readily applicable to other network operating systems with only minor, obvious modification. The local site includes a file server 122, clients 124, stable file storage 126, and raw devices 128. The file server includes a fast cache memory 130 and is loaded with file system software 148 that resolves user file system requests (2.1) against data in the cache 130, the stable file storage 126 or the raw devices 128 in the conventional manner. Each of the clients 124 also includes a cache 132 and file system software 150 compatible with the server file system software 148.
The clients 124 issue the requests (2.1) using a distributed file system (DFS) protocol. In Sun Solaris, the DFS is the Proxy File System (PXFS), which is also called Galileo. Accordingly, the server file system 148 includes PXFS server software 134, the client file system 150 includes PXFS client software 136, and the file system requests (2.1) are issued to a PXFS server entry point. The file storage 126 can be one or any combination of a single hard disk, a cluster of hard disks, a dual-ported hard disk, a tape drive or any other type of non-volatile memory device. In a preferred embodiment, the file system 148 accesses the file storage 126 using the Unix File System (UFS) protocol and the raw devices 128 using the Special File System (SpecFS) protocol. Both UFS and SpecFS are part of the Sun Solaris operating system.
The remote site includes a file server 140, stable file storage 142 and optional raw devices (not shown). The file server 140 includes a fast cache memory 152 and is loaded with file system software 154 that resolves file requests against file data in the cache 152, the stable file storage 142 or the raw devices. The file system software 154 also includes PXFS server software 156. The file storage 142, raw devices and cache memory 152 are not necessarily similar to the analogous elements 126, 128 and 130 of the local site. For example, the file storage 126 and 142 can be completely different as long as the remote file storage 142 can accommodate all of the replicated data from the local file storage 126. The remote server 140 is preferably coupled to the local server 122 over a wide area network (WAN) connection, but any type of connection will suffice. As the local server 122 handles file system requests (2.1) it issues remote data facility (RDF) messages (2.2) to the remote server 140. The purpose of the RDF messages (2.2) is to transfer enough information to the remote server 140 to enable the server 140 to handle file requests (2.1) from the clients 124 whenever failover occurs from the local server 122 to the remote server 140.
The RDF process is managed by geographical replication software, called "Telescope" 160, which runs in both the remote and local servers as an extension of PXFS/Galileo. Among other things, the Telescope software 160L on the local server 122 determines what file system data is transferred in the RDF messages (2.2). The Telescope software 160R on the remote server 140 works with its file system 154 to store the RDF data from the local server 122 on the file storage 136 or raw devices and, when failover occurs, determines how to establish a consistent file system state given the transferred RDF data. Once it has established a consistent file system state, the remote server 140 is able to handle file system requests (2.1) transferred from the local site following a failover.
In a preferred embodiment, Telescope 160 is an enhancement of the PXFS cluster file system (for more information on PXFS, refer to Vlada Matena, Yousef A. Khalidi, Ken Shirriff, "Solaris MC File System Framework," Sun Microsystems Laboratories Technical Report SMLI TR-96-57, October 1996, which is entirely incorporated herein by reference). Telescope 160 resides on the server side of PXFS (e.g., on the local server 122), where it captures state changes to the PXFS file system. State changes to the file system 148 at the local site are encoded at the local site by Telescope 160L as operations and their parameters. Telescope 160L transmits the encoded operations to the remote site using generic Unix networking utilities. At the remote site, the Telescope receiver 160R decodes the operations and applies the decoded operations to a copy 154 of the file system 148 running on the remote server 140. By applying the same operations at the remote site that were applied at the local site, Telescope 160 keeps the two sites in the same states.
Telescope 160 incorporates some of the advantages of other geographic replication strategies. Like Uniq UPFS, Telescope 160 is implemented in a file system (e.g., the file systems 148, 154) rather than in a device driver or storage unit. The file system approach allows Telescope 160 flexibility and efficiency in dealing with high-level file and directory operations. Like Qualix DataStar, Telescope 160 incorporates a stable log 162 (FIG. 2) to store operations that have not yet been transmitted to the remote site. In a preferred embodiment, the log 162 is stored on the local disk 126. This increases data safety by making lost transactions recoverable after a system crash. Finally, like EMC SRDF, Telescope provides variable modes of consistency between the local and remote sites.
Telescope 160 has 1-safe, 2-safe, and very safe transmission modes. Very safe mode suffers from poor latency, but it guarantees that transactions are consistent between sites. 2-safe mode improves latency over very safe mode, but it sacrifices consistency guarantees. It keeps the local and remote sites in lockstep, reducing the data that could be lost in a failure. 1-safe mode optimizes performance at the local site, but does not guarantee constant consistency between the local and remote sites.
In a preferred embodiment, failover is a manual operation. A system administrator must decide that the local site is down and then start the PXFS service (i.e., the PXFS server 156) on the remote site. However, the teachings of the present invention are equally applicable to systems having long-distance cluster heartbeat monitors and improved administration tools to automate these failover tasks. Before providing additional details about Telescope 160, the data structures and programs associated with the local and remote sites are now described in reference to FIG. 3.
Referring to FIG. 3, there is shown a block diagram with elements common to both of the servers 122, 140, raw devices 128, 158 and file storage devices 126, 156. The present description is directed to the local site versions of these elements and is generalizable to the remote server 140. The descriptions of these elements are also generally applicable to the clients 126 with obvious exceptions (e.g., a client 126 includes client versions of file system components instead of server versions). The server 122 includes a central processing unit (CPU) 202, a high speed memory 204, a cache memory 130 and a plurality of device interfaces 206 (e.g., busses or other electronic interfaces) that enable the CPU 202 to control and exchange data with the memory 204, raw devices 128 and file storage 126.
The raw devices 128 can include, but are not limited to, high availability devices, printers, kernel memory, communications devices and storage devices (e.g., disk drives). Printers and storage devices are well-known. High availability devices include devices such as storage units or printers that have associated secondary devices. Such devices are highly available as the secondary devices can fill in for their respective primary device upon the primary's failure. Kernel memory is a programmed region of the memory that includes accumulating and reporting system performance statistics. Communications devices include modems, ISDN interface cards, network interface cards and other types of communication devices. The raw devices 128 can also include pseudo devices, which are software devices not associated with an actual physical device.
The memory 204 of the server 122 can store an operating system 210, application programs 212 and data structures 214. The operating system 210 executes in the CPU 202 as long as the computer 122 is operational and provides system services for the applications 212 being executed in the CPU 202. The operating system 210, which is modeled on v. 2.6. of the Solaris™ operating system employed on Sun® workstations, includes a kernel 216 and the file system 148. (Solaris and Sun are trademarks and registered trademarks, respectively, of Sun Microsystems, Inc). The kernel 216 handles system calls from the applications 212, such as requests to access the memory 204, the file system 148 or the devices 128. The file system 148 includes whichever file system components are required by the server 122, including the UFS 220, a Solaris network file system (NFS) 222, the PXFS 224, including the PXFS server 134 and the Telescope software 160, the SpecFS 226 and an optional, high availability cluster file system (HA-PXFS) 228.
The data structures 214 include a log anchor 230, which documents the file operations logged by the local Telescope program 160L, the log records that were transferred to the remote Telescope program 160R and the transfers that were acknowledged by the remote site. The log anchor 230 is preferably stored in the memory 204 for faster access, but can also be stored on the disk 126 or raw devices 128. The log anchor 230 includes the following fields: next-- rec 242, prev-- rec 244, last-- flushed 246, last-- ACK 248, circular 249 and timestamp-- anchor 250. These fields are described below in the context of the flushed log anchor 280, which is a version of the log anchor 230 stored on the disk 136. The data structures also include a system mode 232, which indicates whether Telescope 160 is operating in 1-safe, 2-safe or very-- safe mode.
The disk 126 is a collection of data organized in files 260 and/or partitions 262. A key element of the present invention is the log file 264, which is preferably stored on the disk, but could optionally be stored on one of the raw devices 128. The log file 264 includes a number of records 266, each including enough information about a file system request (2.1) committed to the disk 126 to allow the request (2.1) to be satisfied by the remote server 140 (assuming the data is transferred via an RDF message (2.2)). Each record 266 includes a header 268 and a body 279. The header is used to decode the log data and includes information that indicates:
the relationship of one record 266i ("i" is an integer index) to adjacent records 266i+1, 266i-1 (next-- rec 270, prev-- rec 272);
when the record was written (timestamp 74);
a unique transaction identifier (transaction-- id 276); and
the length of the transaction (transaction-- length 278).
The body 279 contains the logged file information described by the header 268.
The disk 136 also includes a flushed-- log anchor data structure 280, which holds information used to decode the log file 264 and reconstruct the log (e.g., on the remote site). The flushed log-- anchor data structure 280 is formatted identically to the log-- anchor 230 and includes the following fields: next-- rec 282, prev-- rec 284, last-- flushed 286, last-- ACK 288 and timestamp-- anchor 290. The structure 280 is called the flushed log-- anchor because it is written to stable storage 126 only after Telescope 160 has flushed the log 264 to the remote Telescope instance 160R. Before describing the operation of the present invention further, the file system 148 and its relationship to the disk 136 and raw devices 128 are now described in reference to FIG. 4.
Referring to FIG. 4, there is shown a high-level representation of the file system 148 employed by v. 2.6 and previous versions of the Solaris operating system and the present invention. In Solaris, the file system 148 is the medium by which all files, devices and network interfaces are accessed. These three different types of accesses are provided respectively by three components of the file system 148: the UFS 320, the SpecFS 326 and the NFS 322. Each of the constituent file systems is controlled by a top level vnode operating system 298.
In Solaris, an application 212 initially accesses a file, device or network interface (all referred to herein as a target) by issuing an open request for the target to the file system 148 via the kernel 216. The file system 148 then relays the request to the UFS 320, SpecFS 326 or NFS 322, as appropriate. If the target is successfully opened, the UFS, SpecFS or NFS returns to the file system 148 a vnode object 300 that is mapped to the requested file, device or network node. The file system 148 then maps the vnode object 300 to a file descriptor 301, which is returned to the application 212 via the kernel 216. The requesting application 212 subsequently uses the file descriptor 301 to access the corresponding file, device or network node associated with the returned vnode object 300.
The vnode objects 300 provide a generic set of file system services in accordance with the vnode/VFS operating system (VFS) 298 that serves as the interface between the kernel 216 and the file system 148. Solaris also provides inode, snode and rnode objects 300i, 300s, 300r that inherit from the vnode objects 300 and also include methods and data structures customized for the types of targets associated with the UFS, SpecFS and NFS, respectively. These classes 300i, 300s and 300r form the low level interfaces between the vnodes 300 and their respective targets. Thus, when the UFS, SpecFS or NFS returns a vnode object, that object is associated with a corresponding inode, snode or rnode that performs the actual target operations. Similar principles are involved when an application running on one node (e.g, the client 124-1) requests a file operation on a file residing on another node (e.g, the client 124-2), where both nodes are within a cluster under the control of a single PXFS 324. How the PXFS 324 handles such a request is well-known, but is described briefly herein in reference to FIG. 5.
Referring to FIG. 5, there is shown a flow diagram of the steps performed by a computer system similar to that in which the present invention is implemented in response to a request (5-1) from an application 212 executing on a node 332-1 to open a file 324 that resides on a different node 332-2. In this example, the file system 148 resides on the node 332-2. Note that FIG. 5 shows two copies of the node 332-2 to clarify the messages and operations employed. The application 212 issues the open request to the local kernel 242 on the device's logical name. The kernel 242 then queries the file system 148 to procure a handle for the requested file 324. Because the file system 148 is on a different node from the kernel 242, this is a multi-step process that involves the use of the PXFS 224.
An object such as the kernel 242 (on the node 332-1) that needs to access the file system 148 first issues the access request to its local PXFS client 136. The PXFS client 136 holds a reference to the PXFS server 134 co-located with the file system 148. This reference enables the PXFS client 136 to communicate the kernel's request to the file system 148 via the PXFS server 134. The file system 148 performs the requested access, creates a vnode object 300-1 representing the requested file and returns a reference to the vnode object 300-1 to the PXFS server 134. Because the nodes 332-1 and 332-2 are different address spaces, the reference to the vnode 300-1 is useless to the PXFS client 136 and kernel 242 in the node 332-1. Consequently, the PXFS server 134 creates a file implementation (f-- obj) 340 linked to the vnode 252 and returns a reference 342 to the f-- obj 340 to the PXFS client 136. Upon receiving the f-- obj reference 342 the PXFS client 136 creates a proxy vnode (px-- vnode) 344 that is linked to the f-- obj 340 via a f-- obj-- ref (not shown), which is a client side representation of the f-- obj. The kernel 242 can then access the file information represented by the vnode 300-1 by simply accessing the local px-- vnode 344.
Using this mechanism, the kernel 242 issues a lookup message (5-2) on the logical name of the device to be opened to the PXFS client 136, which relays a similar lookup message (5-3) to the PXFS server 134. The PXFS server 134 issues the file system 148 a get-- vnode message (5-4), which asks the file system 148 to map the logical-- name to the corresponding physical-- name and return a reference to a v-- node 300-1 representing the UFS file identified by that physical-- name. As described above, the file system 148 then returns the vnode to the PXFS server 134 (5-5) and the PXFS server 134 creates a corresponding f-- obj 340 and returns the f-- obj reference 342 to the PXFS client 136 (5-6). The PXFS client 136 then creates a px-- vnode 344 and passes the px-- vnode reference 346 to the kernel 242 (5-7). At this point, the kernel 242 issues an open message (5-8) to the PXFS client 136 for the px-- vnode 344. Upon receiving this message, the PXFS client 136 determines from the px-- vnode's attributes how to satisfy the open request and opens the file. This is possible because the px-- vnode 344 references the f-- obj 340-2 on the node 320-3 that is associated with the requested file 324 via a vnode 300 and an inode 300i, as described in reference to FIG. 4. In particular, the kernel 242 issues an open(f-- obj-- ref) request (5-9) to the PXFS server 134-3, where f-- obj-- ref is an object reference to the f-- obj associated with the file 242. After additional steps (not shown) involving both the local copy of UFS 220-3 and the PXFS server 134-3, the PXFS server 134-3 returns (5-10) the file descriptor of the file 242 if the open was successful. A similar process is performed for all file operations, such as writes, deletes and appends, which, in contrast to an open operation, affect the state of the file system.
Having described some of the basic aspects of the PXFS file system, the Telescope geographical replication system 160, which in a preferred embodiment is implemented as an extension to PXFS, is now described in detail.
Referring again to FIG. 2, the Telescope service 160 is spread through many components of the cluster. For instance, the Telescope service 160 intercepts file system updates, records a log, consumes network resources and exports management interfaces, all at different locations. This section focuses on two particular location issues: where file system updates are intercepted and where Telescope implementation objects are located.
In a preferred embodiment, file system updates and requests (2.1) are intercepted in the PXFS server 134. This approach has several advantages:
1) State changes are captured as fairly high-level operations. That is, Telescope 160 records changes to files and directories rather than disk sectors and volumes. Dealing with high-level operations increases flexibility over low-level approaches. For instance, the remote site is not restricted to the same disk geometry as the primary site. Replication can be toggled on a per-directory or per-file basis. Also, the data transmission format can be optimized. Rather than sending entire blocks of data, operations can be encoded to stretch network bandwidth.
2) The PXFS server 134 is below the cache 160. Referring to FIG. 2, caching in PXFS is implemented on the client side 124, with the local server 122 as a data provider. When updates reach the point where the PXFS server 134 delivers them to the underlying file system 148, they are bound for stable storage 126. Trapping updates in the PXFS server 134 allows Telescope 160 to ensure that no cache effects will prevent consistency between the local and remote sites.
3) The PXFS server 134 is instrumented with mechanisms (called HA-PXFS) for high availability. In high availability mode, operations are checkpointed from a primary server machine to a secondary server machine. In an alternative embodiment described in reference to FIG. 10, Telescope 160 is integrated with this high availability checkpointing scheme, which allows geographic replication to persist even if a server 122 is incapacitated.
4) Implementing Telescope 160 in the PXFS server 134 allows for a software-only approach. No special storage devices are required and generic networking utilities can be used for the transmission of data between sites.
Given that the Telescope service 160 is incorporated in the PXFS server 134, there are still several different ways in which the Telescope 160 can be configured to implement the geographic replication service. Specifically, there are several different ways in which the Telescope service 160 maps to clusters, nodes, file systems, directories, and files. A few of these alternative arrangements are now described. Note that a cluster system is not specifically illustrated in FIG. 2. However, it should be assumed that the local server 122 represents one or many cluster nodes and the PXFS server software 134 represents one or more PXFS server instances that can run on the respective cluster nodes.
1) One Telescope service per cluster: In this case, the various PXFS server instances 134 across a cluster replicate through a central Telescope instance 160. This approach simplifies administration, but has disadvantages for high availability (single point of failure) and efficiency (all replicated data may have to be moved multiple-times through the ORB). Note: an ORB, or Object Resource Broker, is a distributed mechanism for handling remote procedure calls generated by users (e.g., of a client) who request execution of methods associated with objects on a different computer (e.g., a server).
2) One Telescope service per node: In this case, the various PXFS server instances 134 on a node replicate through a single Telescope instance 160. This approach is still fairly simple for administration, and it avoids the possibility of excessive inter-machine data transfer through the ORB.
3) One Telescope service per PXFS server instance: In this case, there can be multiple Telescope instances 160 on each node. Each Telescope instance 160 is associated with a PXFS server file system object 134, which is tied to an underlying file system (e.g., the UFS 148). This approach makes administration difficult because the replication instances are potentially numerous and spread out. Moreover, in a transparently global file system, such as PXFS 224 (FIG. 3), the actual location of files should be invisible to applications. However, this configuration ties in well with HA-PXFS, allowing replication and log operations to be checkpointed to a secondary server.
4) One Telescope service per PXFS file system: As the global file system becomes more pervasive in Galileo clusters, providing one Telescope service 160 per PXFS file system 224 is equivalent to providing one Telescope service 160 per cluster. This is the configuration that is specifically illustrated in FIG. 2. This configuration is preferred for administrative reasons because, by associating Telescope 160 with a file system 148, all Telescope instances 160 can be located by iterating through file systems. This configuration is also preferred for management reasons, as it typically employs only a single PXFS file system 224. This configuration also provides technical advantages. For instance, operations on the file system 148 can be serialized by the order in which they are conveyed to the Telescope service 160.
As mentioned above, a preferred embodiment offers three different system modes 232: 1-safe, 2-safe and very-- safe. Each pair of servers in an geographical replication relationship (e.g., the servers 122, 140) can be configured to have a different degree of coherency depending on the system mode 232 selected for that pair. (for more information on coherency modes, see Gray and Reuter). The different modes 232 are now described.
1-safe mode optimizes performance at the local site. Referring again to FIGS. 2 and 3, in this mode, operations intercepted by the Telescope service 160 are applied to the local file system 148 and logged in stable storage 126 (or 128). The I/O call (i.e., the file operation) on the local site is then declared complete, allowing the throughput and latency to be quite close to that of an un-replicated file system. Periodically, the logged operations are batched and transmitted to the remote site, where they are applied to the remote copy of the file system 152. Although the remote site may lag behind the local site, the log 264 on the local site is designed to always hold the difference between the two. Thus, if the local site crashes and the not-yet-transmitted transactions are lost, they can be recovered as soon as the local site log 162 is made available. For 1-safe mode to be effective operations must be recorded in the log pursuant to the requirements specified above, in the summary. The log 264 is described in greater detail below.
2-safe mode improves the consistency between the local and remote sites but sacrifices performance. Operations intercepted by Telescope 160 are first applied to the local file system 148 and then immediately transmitted to the remote site. The I/O operation on the local site cannot return successfully until an acknowledgment is received from the remote site. With respect to the applications 212, I/O operations execute synchronously on the local and remote sites; however, the latency incurred in transmitting the data to the remote site significantly degrades performance.
2-safe mode uses the same method of encoding operations as 1-safe mode. Encoded operations are recorded in a stable log 264, just as in 1-safe mode. Thus, if the local site should crash before the synchronous transmission can occur, the one lost transaction can be recovered. Once an acknowledgment from the remote site is received, the logged operation can be discarded.
Note that even though the Telescope service 160 performs operations synchronously in 2-safe mode, it is possible for the local and remote sites to have different state. For example, if the local site fails after applying the operation locally but before transmitting the RDF message (2.2), the remote site will not receive the operation. Even though the transaction is stored in a log at the local site, the file systems are not synchronized. Very safe mode avoids this problem using a two-phase commit protocol.
According to the two-phase commit protocol an operation intercepted by Telescope 160 is not immediately applied to the local site. Instead, it is logged, just as in 1-safe mode, and transmitted to the remote site. The remote site decodes the operation, logs it, and sends back a "ready to commit" message. Upon receiving the "ready to commit" message, the local site responds with a "commit" message and proceeds to apply the operation to its local file system 148.
The two-phase commit protocol guarantees that the two file systems 148, 154 remain synchronous. Since the extra messages increase the latency over 2-safe mode, it is not likely that very safe mode will be practical for most applications. In fact, Gray and Reuter remark that only a few systems offer very safe mode, and they know of no customers who use it (for more information, see Gray and Reuter).
Naming is an important issue in any project related to file systems. The Telescope service 160 naming scheme meets the following constraints:
1) One identifier can refer to a file at the local site and the remote site.
2) The identifier is small, consuming minimal log space and network bandwidth.
3) A file's identifier translates efficiently to and from its pathname and PXFS file object.
4) A file's identifier should persist through reboot.
A preferred naming scheme that satisfies all of the above constraints is now described. However, this description should not be interpreted to limit the scope of the present invention, which encompasses all possible naming systems used in similar contexts.
A number of techniques already exist for identifying files. Unix file descriptors satisfy the second and third constraints, but are process and machine dependent. File pathnames satisfy the first constraint in replicated file systems, but long character strings consume space, and the pathname is not always accessible (while utilities exist to map pathnames to vnodes, mapping from a vnode to a pathname is far from trivial).
A preferred Telescope naming scheme uses the fobjid-- t type, which is derived from the underlying vnode fid-- t type. An fobjid-- t is a unique and persistent identifier for a file. Files can be mapped to fobjid-- ts and fobjid-- ts can be mapped back to files. Since fobjid-- ts are derived from a file's inode on disk, the fobjid-- t will remain the same even after a reboot. The fobjid-- t and fid-- t types serve the same purpose as the like-named elements of FIG. 5.
However, fobjid-- ts are only unique on a single machine; therefore, the present invention maintains a mapping table that maps local fobjid-- ts to remote fobjid-- ts. (Note: the mapping table can actually map local fobjid-- ts to remote pathnames, remote fobjid-- ts, pointers to fobjs on the remote site, or even pointers to underlying vnodes on the remote site--whichever is most efficient). In a preferred embodiment, the mapping table is stored on the remote site, meaning that entries in the log 264 identify files by their fobjid-- ts on the local site. The rationale for maintaining the mapping table on the remote site is twofold:
1) It decreases I/O latency on the primary site by removing the fobjid-- t translation from the critical path.
2) It allows for greater asynchrony. That is, if entries in the log 264 referred to files by remote site fobjid-- ts, then for each new file accessed on the primary site, a synchronous call to the remote site would be required to determine the appropriate fobjid-- t to identify the file.
Two different mapping schemes from files to fobjid-- ts are now described in reference to FIGS. 6 and 7. Each of these figures shows how mapping is implemented for a write operation, which typifies operations that modify the file system state and therefore are checkpointed and replicated by the Telescope service 160. Both embodiments include a local site with applications 212, Telescope service 160L, files 260L identified by fobjid-- ts 402 of one or more type, and a log file 264. Both embodiments also include a remote site with a Telescope receiver 160R, files 260R identified by remote and local site identifiers 404, 402 (e.g., fobjid-- t and f-- obj, respectively) and a mapping table 408 that defines the mapping between the remote and local site identifiers 404, 402.
Referring to FIG. 6, there is illustrated the steps of a file write and geographical data replication process for a first preferred mapping system. The replication process (i.e., Telescope 160L) is triggered when a file 260L is written (6.1) to the local site file storage 126. Telescope 160L then obtains the fobjid-- t 402 of the file using the getfobjid command (6.2) and checkpoints information about the write operation (e.g., the fobjid-- t) to the log 264 (6.3). Telescope 160L then replicates file state information (e.g., the file 260L contents and logged write information, such as the fobjid-- t) to the remote site in accordance with the selected Telescope mode 232 (6.4).
At the remote site, the Telescope receiver 160R writes the replicated file data to the remote site file storage 142 as a remote file 260R (6.6) and translates the fobjid-- t 402 to a remote site file object 404 (e.g., f-- obj) using the mapping table 408 (6.5). The translation demonstrated in FIG. 6 can only be performed if the mapping table 408 is properly maintained. In particular, there are two preferred approaches to constructing and maintaining the name mapping table 408:
1) Each time a file 260L is accessed on the local site for the first time, Telescope enters a pathname-to-fobjid-- t map entry 402 into the log 264. When the remote site Telescope 160R receives the map entry, it enters it into its primary fobjid-- t-to-remote file mapping table 408.
2) As part of Telescope 160 initialization, a pathname-to-fobjid-- t map entry 402 is entered into the log 264 for every existing file and directory to be replicated. Afterwards, map entries are only logged when a new file 260L is created or its name is changed. In these cases, it is sufficient for Telescope 260L to log the file name, directory fobjid-- t, and file fobjid-- t.
Referring to FIG. 7, the second mapping scheme, in addition to the elements shared with the embodiment of FIG. 6, employs local and replicated directories 410, 412 on the local and remote sites. In another difference from FIG. 6, the information logged for a file 260L includes its "name", a namefobjid 402n and a dirfobjid 402d. The namefobjid and dirfobjid elements 402n, 402d are unique and persistent identifiers for the file "name" and the directory in which the file resides.
This scheme requires more work at initialization time, but it addresses a number of problems with the first scheme. For example, keeping track of the first time a file is accessed, as in the first scheme, can be difficult, especially if a remote site is added to the topology during operation. Also, accessing the complete filename from the PXFS server 134 is not easy from file operations that do not manipulate the name of the file (e.g., the read and write system calls). The only disadvantage of the second approach is the price paid at initialization and initialization will be complex and time-consuming, whether or not naming is involved.
In the embodiment of FIG. 7, when a file is created at the primary site, its corresponding fobjid-- t 402n (shown as namefobjid in FIG. 7) is logged along with its "name" and its parent directory fobjid-- t 402d (shown as dirfobj in FIG. 7). At the remote site, the directory fobjid-- t 402d is mapped to the replicated directory 412 through the mapping table. A copy 260R of the new file is created in this directory, and the returned reference 404n is entered into the mapping table along with the fobjid-- t 402n from the local site. Given this scheme, any time file operations on the local site are not possible, file requests from the local clients are routed via the WAN to the remote Telescope receiver 160R. The requests identify files by their local site dirobjids and nameobjids, which the Telescope receiver 160R, using the mapping table, maps to the corresponding namefobjs and dirfobjs of the replicated directories 412 and files 260R, respectively.
In normal operation, changes to the primary file system are recorded and transmitted to the remote site. This method of transmitting changes is considerably more efficient than periodically transmitting the entire file system; however, it only works if the two sites start in identical states.
Synchronization is a process that brings the remote site file system into the same state as the primary site file system. Synchronization must be performed whenever the primary and remote file systems are not converging upon the same state. Synchronization is required in the following scenarios:
1) When Telescope replication begins on a new file system, the remote replicate must be synchronized with the file system to be replicated.
2) After a primary and remote site lose contact for a period of time, the remote site must be resynchronized with the primary site.
3) If a failover occurs to a remote site and the primary site is later restored, the original primary must be synchronized with changes that have occurred at the post-failover primary.
Conceptually, the simplest method of synchronization involves completely copying the primary file system to the remote file system. In practice, though, the brute force method is not always necessary. For instance, in the replication process described in reference to FIG. 7, if Telescope 160 is functioning in 1-safe mode and the log 264 has sufficient capacity, all changes that must be applied to resynchronize the remote site are conveniently recorded. Re-synchronization is as simple as transmitting and applying the log 264, which is significantly less draining on CPU and network resources than a complete file system copy. Similarly, in the third scenario, if the post-failover primary site can log all changes applied while the original local is off-line, there is always a record of the difference between the two sites. This scenario is more complex than the latter, since one or more transactions may have been applied at the original local site and not transmitted to the post-failover (remote) site before failover. Log requirements dictate that these transactions be available in the local site log (if it can be recovered). In this case, an administrator may have to intervene and choose which transactions exist in the new synchronized state.
Unfortunately, there are cases where a complete copy is the only way to ensure synchronization. The first scenario described, where a file system is first replicated by Telescope 160, is one example. Copying an entire file system over a wide-area network can be a time-consuming process. In order to guarantee the consistency demanded by synchronization, no modifications should occur on the local site file system while it is being copied to the remote site. However, this conflicts with the goal of minimal downtime at the local site during a synchronization.
A number of techniques can be borrowed from other technologies to avoid taking the local site off-line during synchronization. For instance, on-line backup procedures also require a consistent copy of a file system 148 while minimizing downtime. Telescope 160 synchronization off a locally mirrored disk requires extra hardware; the storage system must use mirrored disks to start with. All pending writes to the mirrored disk must be flushed before the synchronization begins, and during synchronization, no writes to the mirror disk can occur. The second technique, file system snapshots, also requires additional hardware, but it can be as simple as extra space on the same disk. Before Telescope 160R synchronization begins, a snapshot of the file system 148 is created. The snapshot initially consists of an empty holding area. During synchronization, writes by other applications will be applied to the file system, but on the first access of each affected block, the block will be copied to the snapshot holding area. Hence, for each block to be copied, Telescope 160 will first look in the snapshot holding area. If the block is not present it has not been modified, and Telescope 160 can copy it from the local file system 148.
Of the two on-line backup strategies, the snapshot method is best suited to Telescope. It is a software approach with minimal overhead and low implementation complexity. The snapshot method is enhanced for use with Telescope 160. The difference between performing backups and synchronizing for Telescope is handling the writes that occur during the file system copy. In a backup process, these writes can be ignored. The backup is deemed to represent the file system before any of these writes occurred. With Telescope 160, however, the local and remote site must be completely synchronized when replication begins. Thus, the writes that occur during the large file system copy must also be conveyed to the remote site. The best method of performing these writes is to add a log step to the snapshot method. When a block is written during the synchronization period, the original block is copied to the holding area and the write operation is logged. After the synchronization is complete, the log can be applied to the remote site. Logging is discussed further below.
Other technologies may also offer solutions for the on-line synchronization problem. Most RAID products can synchronize disks without interrupting normal operations. Investigating algorithms used in these products may provide additional solutions.
The key to capturing data updates is identifying the PXFS server operations that lead to modifications of the underlying file system. These operations fall into three categories: file data methods, file attribute methods, and directory methods. Methods on directory objects deal with creation, deletion, and naming of file and other directory objects. File data methods write file data to the underlying file system. File attribute methods change the attributes of files in the underlying file system. Table 1 lists the PXFS operations that must be replicated to the remote site to ensure that the file state can be recovered after a failover occurs. These are standard PXFS operations and, for this reason, are not defined herein; however Appendix A shows.
TABLE 1______________________________________Directory File FileObject Methods Data Methods Attribute Methods______________________________________create.sub.-- fobj page.sub.-- out set.sub.-- attributesremove.sub.-- fobj write.sub.-- out set.sub.-- secattrcreate.sub.-- symlink sync ioctlrename.sub.-- fobj uiowritelink.sub.-- fobj fsynccreate.sub.-- dirremove.sub.-- dir______________________________________
Once these operations are identified, there are two approaches to capturing state changes and recording them in the log 264 that can be implemented in Telescope 160:
1) Simulate the client call to the PXFS server 134. That is, record the PXFS server method invoked with enough arguments that the same call can be reproduced at the remote site.
2) Record only updates sent to the underlying file system through a vnode operation. PXFS server 134 operations that change the state of the underlying file system must do so through a vnode operation. Invocations of these vnode operations can be recorded and reproduced at the remote site.
The first approach provides a more highly available failover scenario. In this approach PXFS server 134 methods are encoded and transmitted to the remote site. The remote Telescope service 160R decodes the methods and invokes them on a remote instance of a PXFS server 156. In this manner, the remote Telescope service 160R simulates a PXFS client 136. It also happens to be the sole PXFS client 136 that writes to the remote PXFS server 156. Thus, if a failover to the remote site is necessary, a PXFS server instance 156 will already exist on the remote site, and it will be ready to accept requests from the PXFS clients 136. Furthermore, during normal operations, additional PXFS clients 136 can provide read-only access at the remote site. This is useful for CPU and IO-intensive procedures such as on-line backups, which should be avoided at the local site if at all possible.
The downside of the first approach is its complexity. For example, the parameters of vnode methods employed in the second approach are fewer and easier to encode than the parameters of PXFS server 134 methods employed in the first approach. In addition, calls from the PXFS server 134 to the underlying file system 148 on the local site, which are used in the second approach, are simple to isolate. Error conditions can be checked as the vnode methods return, to determine if the operation were successful and should be transmitted to the remote site. At the remote site, decoded operations are applied directly to the underlying file system. In this manner, the remote Telescope service 160R acts as a PXFS server 156 rather than as a PXFS client 136, since it interacts directly with the underlying file system. Although the Telescope service 160R acts as a PXFS server 156 in this regard, it is not capable of any other PXFS server functionality, such as receiving requests from PXFS clients. Hence, in the event of a failover, a PXFS server 156 must be constructed from the underlying file system 154.
However, instantiating the PXFS server 156 does not affect failover too severely as failover is a time-consuming process already. On the other hand, by transmitting vnode methods rather than PXFS server methods, the remote site does not need to be a Galileo cluster. Also, no PXFS software is required at the remote site.
Referring again to FIG. 3, the replication log 264 is one of the most important components of the Telescope service 160. Very safe, 2-safe, and 1-safe modes all use a log to prevent the loss of transactions. The log entry format is also the format in which data is packaged and transmitted to the remote site. This section describes the design of the log, including its format and how logging operations are integrated into file system operations. This information is most appropriate for 1-safe mode, but generally carries over to 2-safe and very safe modes.
The first issue in the design of the log is its location. It is important that the log reside on the same physical machine as the PXFS server 134. This prevents the transmission of all log entries through ORB calls. If the PXFS server 134 is replicated using HA-PXFS, entries to the log 264 should also be replicated. Hence, the log should reside on a dual-ported disk, such as the disk 126.
The log 264 can be implemented as a regular file. The log size is preferably specified at its creation, allowing the log file 264 to be pre-allocated. If the log 264 is placed in the file system being replicated, it is important that replication of the log file be turned off. The log 264 can also be implemented as a raw device 128, somewhat like a swap partition. For simplicity, the remainder of this document will assume that the log 264 is implemented as a regular file accessible from the kernel 216 through the vnode interface 298. This file access method is described in reference to FIGS. 4 and 5.
There are advantages to placing the log 264 in a well-known location, whether in the file system or on a raw device. First, if this well-known location is in the file system being replicated, it would be easy to ensure that Telescope 160 does not attempt to replicate the log. More importantly, though, the log 264 must be retrievable after a system crash. This means its location must either be hard-coded into the retrieval code or recorded in a location hard-coded into the retrieval code. One possible location to record the location of the log file is the log anchor 230 (FIG. 3), which is described below. The log anchor 230 is considerably smaller than the log itself, especially in 1-safe mode.
Log entries are either physical, logical, or a hybrid of the two. A physical entry records the change in data at a certain location on the physical device or in a file. A logical entry records the operation that caused the change. Since PXFS is a high-level file system, it deals mostly in logical operations. That is, rather than specifying the layout of bits on a disk, it invokes operations on underlying file systems. For this reason, a logical logging approach is more appropriate for Telescope 160.
The format of a log entry 266 is shown in FIG. 3 and in FIG. 7. A log entry 266 consists of a header 268 and a body 279. All log entries 266 have headers 268 of identical size and layout, while bodies 279 can vary. Log record headers 268 must contain enough information to enable Telescope 160 to perform the following functions:
1) Traverse the log forward.
2) Traverse the log backward.
3) Find all log entries for a given transaction.
4) Determine the time a transaction started and finished.
Referring to FIG. 3, the headers 268 include the following fields, which enable Telescope 160 to perform the necessary functions:
______________________________________next.sub.-- rec 270 points to the header of the next log entry;prev.sub.-- rec 272 points to the header of the previous log entry;timestamp.sub.-- rec 274 the day and time of the current entry;transaction.sub.-- id 276 an unique id associated with the current;transaction.sub.-- length 278 the length of the current entry.______________________________________
As is apparent from the preceding fields, the log headers 268 organize log data into a linked list. Pointers to other elements in the list are implemented with log sequence numbers (LSNs). An LSN is used to identify a log record header by encoding its location in the log file.
The transaction-- id 276 identifies the transaction the log entry is associated with. It is assigned by the log module when an operation is submitted by the PXFS server 134 to the log 264 for entry. It is returned to the PXFS server 134 as a result of the submission method. After the operation has completed, the PXFS server 134 sends the transaction-- id 276 as an argument to a commit message to the log module. In a preferred embodiment, transaction ids 276 are implemented as monotonically increasing 64-bit integers, ensuring that the same transaction id is not used twice. However, any other type of unique id could also be used.
While log headers allow the next and previous record to be located from the current one, they do not indicate where a log traversal should start. This information is kept in a special data structure called the log anchor 230, which is illustrated in FIG. 3 and FIG. 8 (which shows the relationship between the log anchor 230 and the corresponding log file 264). The log anchor 230 stores the information necessary used to decode the log file and to reconstruct the log in the event of a system failure. For instance, the LSN of the most recently written log record header is stored in the anchor. Also included is the LSN of the most recent entry flushed to the remote site, as well as the most recent entry acknowledged at the remote site. These entries allow Telescope to trace backwards through the log entries, determining which transactions were lost in the system failure. In particular, the log anchor 230 includes the following fields:
______________________________________next.sub.-- rec 242 indicates the next available space for a log entry;prev.sub.-- rec 244 indicates the header of the most recently written entry;last.sub.-- flushed 246 points to the header of the last flushed log entry;last.sub.-- ACK 248 points to the header of last log entry acknowledged by the remote telescope instance 160R;circular 249 a boolean that indicates if the log is circular;timestamp.sub.-- anchor 250 the day and time of the current entry.______________________________________
Referring to FIG. 9, there is depicted the relationship between the log 264 and the log-- anchor fields immediately following a log flush. In this example, all data flushed to the remote site has been acknowledged, since the last-- flushed and last-- ACK pointers 246, 248 point to the same log entry. A flush writes the data from the last-- flushed pointer 246 to the next-- rec pointer 242. The space in the log file 214 after next-- rec 242 is free for new log entries. In addition, if circular 249 is true, the space in the log file before last-- ACK 248 is also free for reuse. If the log file is not restricted to a well-known location, the log anchor can also contain the log file pathname.
The log anchor is a frequently accessed data structure. For each log entry, the next-- rec 242, prev-- rec 244, and timestamp 250 fields are accessed and changed. For efficiency, the log anchor 230 is kept in the memory 204. For protection of log data, the log anchor 230 is periodically flushed to the disk 136, where, for the purposes of this description, it is called the flushed-- log-- anchor 280. Hence, after a system failure, the log anchor accessed by Telescope 160L may not actually represent the most recent state of the log 264. Instead, Telescope 160 traverses the log 264 in the forward direction, starting at the entry indicated by the prev-- rec field 284 of the flushed log anchor 280, until it finds the true last log entry. The last log entry can be marked in several ways. A dummy record header can be written immediately following it with timestamp entry before the current anchor timestamp 290. Alternatively, a special marker can be written at the end of the log that is cleared when a new entry is appended.
The log anchor 230 must be flushed to a well-known location on disk 136 so that it can be retrieved easily after a system crash. If the log file 264 is not in a well-known location, then the flushed log anchor 280 should also hold its pathname. There are a number of techniques to ensure that the log anchor 230, 280 as well as the log file 264, are always left in a consistent state. These techniques are important since writes to these files are not atomic with respect to unpredictable events, such as power failures. For a thorough discussion of logging techniques, see Chapter 9 of Gray and Reuter, which is entirely incorporated herein by reference.
One of the requirements of Telescope 160 is that the local and remote sites reach the same states, even though in 1-safe mode the remote site may lag behind the local site. One way to view this requirement is that the state on the local site equals the composition of the state on the remote site with the operations in the log 264. One scenario in which this requirement is threatened is if a fault at the local site causes downtime that does not last long enough to cause a site failover. In this situation, the log 264 should not fall out of sync with the file system 148, since it would lead to the remote site falling out of sync with the local site. This can be enforced with three rules:
1) On the local site, the order in which operations are recorded in the log must respect any higher-level locking or ordering constraints that controlled the order in which they were applied to the file system. That is, the log may not represent the exact order in which operations were applied to the file system since there is no central file system lock that is grabbed for every operation. On the other hand, the log 264 will be ordered by locks acquired on file systems and directories;
2) Operations must be applied to the remote site file system in the same order that they are recorded in the log;
3) On the local site, an operation is committed to the log if and only if it is committed to the file system.
The first rule does not quite guarantee that operations are recorded in the log in exactly the same order as they are applied to the file system. Operations on different files and directories can be recorded and applied in different orders. Operations on the same file or directory, though, will be guarded by file system or application-level locking. For instance, two threads will not be allowed to modify the same directory concurrently because the file system will impose some kind of locking. Without that locking scheme, the directory could get mangled. As long as the operations are recorded in the log while the directory lock is held, the log will represent the same ordering as the file system.
The ordering imposed by the first rule is worth little if not obeyed at the remote site. The remote site may wish to perform operations asynchronously with several threads to improve efficiency, but rule number two requires that the log ordering be preserved. If not, inconsistencies between the local and remote sites can result.
Ordering is irrelevant if operations are recorded in the log that were not applied to the file system, or vice versa. For instance, if an operation were applied to the file system and the system crashes before it is entered into the log, the log will not represent the difference between the local and remote sites. Similarly, if an operation is recorded in the log but for some reason it fails when applied to the file system, the log entry should be stricken or invalidated.
Preferably, a ready-commit protocol is used to record operations in the log 264. For 1-safe mode, the ready-commit protocol would proceed something like this:
1. Obtain the file system file or directory lock.
2. Record the operation in the log 264.
3. Perform the operation on the file system 148.
4. If the operation was successful, record a commit message in the log 264.
Otherwise, record an invalidate message.
5. Release the file system file or directory lock.
6. Return results.
This protocol guards against failures at any stage of a file system state change. It does make one important assumption: updates to the file system must be either idempotent or testable. Idempotent operations have the same effect if applied one or many times. It can be determined if a testable operation has been performed without re-performing the operation. This assumption is needed to deal with a failure that occurs after step 2 and before step 4. Moreover, as described in reference to FIG. 10, this protocol is consistent with HA-PXFS, which makes the same assumption.
If an operation is recorded into the log 264 and there is no corresponding commit or invalidate message, it is unknown whether the operation was applied to the file system 148. If the operation is testable, whether it was performed can be determined. If it is not testable, rather than guess whether it was performed, the operation is simply applied again. Idempotency guarantees that if it was already applied, the resulting state will not change; however, for some operations an error will be returned from the underlying file system. For instance, if the operation was mkdir and step 3 had already completed, EEXIST will be returned by the file system 148. At this point, Telescope 160 does not know whether the original operation failed or the retry failed; consequently, the operation should also be performed at the remote site. There, if the operation succeeds, then the original operation on the local site had completed. If it fails, then the original operation on the local had not completed, and an error would have been returned if it had. A marker should be placed in the log entry indicating that an operation is a retry and may not have succeeded on the local. If this marker is present, the remote site need not sound any alarms if the operation fails, since it will have remained in a consistent state with the local.
The logging procedure described above differs slightly for 2-safe mode. Recall that in 2-safe mode, the operation must be transmitted and applied at the remote site before it can return on the local site. Hence, rather than write a commit message to the log in step 4 above, the entry recorded in step 2 is transmitted to the remote site. Step 5 is blocked until an acknowledgment is received from the remote site.
The logging procedure for the very safe mode is similar to that for the 2-safe mode except it uses a two-phase commit protocol.
In a preferred embodiment, all operations are encoded into the log 264 with the same format, illustrated in FIG. 8. Log entries/records 266 all begin with a log record header 268, which has been described in reference to FIG. 3. The log record header 268 provides the timestamp 274, the transaction id 276, and the length 278 of the log entry. The body 279 of the entry starts with an opcode 452 that identifies the encoded operation. Next is a retry marker 454 that indicates whether the operation is possibly a retry, and hence whether the error can be disregarded on the remote site. Following the opcode 452 and retry marker 454 is the list of parameters. Each parameter is contained in a structure containing a typecode 456, the length of the parameter 458 and the parameter data 460. With this structure it is easy to efficiently transmit any parameter as long as its typecode 456 is known at both the local and remote sites.
Not all of the parameters of an operation need to be transmitted. Some parameters can be simulated at the remote site. For instance, credobjs do not need to be relayed. (Note: a credobj is an object that contains user credentials; e.g., user id, group id, etc.). This is because the remote Telescope service 160R should be able to produce credobjs to access its local file system 154. Appendix A lists the method prototypes from Table I along with the parameters that must be transmitted for each method. These method prototypes are written in standard C++, whose conventions it is beyond the scope of the present application to describe.
Commit and invalidate messages are also encoded into the log 264 with the format illustrated in FIG. 8. Commit and invalidate messages are each assigned a special opcode 452. They are linked to the log record 266 being committed or invalidated by the transaction id 276 in the log record header 268. In the current design, invalidate messages do not involve any parameters. Commit messages, however, preferably include naming information. As described above, the naming framework is maintained with log messages (FIGS. 2, 6, 7) indicating changes in the file system 148 namespace. Each time an operation is invoked at the local site that changes the name (or state) of a file system object, a name-to-fobjid-- t mapping is entered in the log 264 (presuming that the naming/logging method of FIG. 7 is employed). In the logging procedure described above, the details of the operation (e.g., opcode and parameters) are recorded prior to its completion. Hence, the new fobjid-- t, which must be transmitted to the remote site, is not known at the local site until after the initial log record is written. As an optimization, rather than creating a new log entry, the new fobjid-- t is recorded in the commit message for the transaction that caused it. The operations that require naming data in the commit message are noted in Appendix A. These and similar messages are written to the log file in the methods described in reference to FIGS. 6 or 7 or other, similar, methods.
In an alternate embodiment, the Telescope software 160 is modified to function within the context of HA-PXFS 228 (FIG. 3), which extends the PXFS server 134 to handle failures with a relatively short service interruption. Since Telescope 160 is implemented in the PXFS server 134 it can take advantage of the protection offered by HA-PXFS 228. The Telescope service 160L does not need to deal with some of the complex high availability issues important to HA-PXFS 228. For instance, Telescope 160 does not checkpoint locks to the remote site. The Telescope service 160L replicates data rather than application state; after a site failure, applications will have to be restarted. Since HA-PXFS 228 provides failover that is transparent to clients 124, it does not have the luxury of disregarding these issues. The HA-PXFS architecture and necessary modifications to Telescope 160 are now described in reference to FIG. 10.
Referring to FIG. 10, The HA-PXFS architecture is based on a primary and a secondary server 122p, 122s (not to be confused with Telescope's local and secondary sites) that share a dual-ported disk 126d. This system operates similarly to the preferred embodiment described in reference FIG. 3 except for differences which are now described. PXFS server requests are handled by the primary server 122p. Each request is checkpointed to the secondary server 122s so that it can take over transparently if the primary server fails. When the Galileo cluster membership monitor 480 detects failure of the primary server 122p, the secondary server 122s is notified. The secondary server 122s mounts the file system 148 and obtains PXFS file objects from checkpointed fobjid-- t pointers. If an operation was in progress at the time of the failure, the secondary server 122s completes it. Operations are encapsulated in mini-transactions to guarantee exactly-once semantics. Mini-transactions are described in detail in U.S. patent application Ser. No. 08/829,156, "Method and System for Achieving High Availability in Networked Computer Systems," by Matena et al., filed Mar. 31, 1997, which is entirely incorporated herein by reference.
Integrating Telescope with HA-PXFS focuses on three problems:
1) Checkpointing the proper Telescope state from primary to secondary server.
2) Inserting log entries or transmissions into mini-transactions.
3) Regaining access to the Telescope log from the secondary server after a failure.
The Telescope state checkpointed (messages (8.1)) from the primary 122p to the secondary server 122s includes the transaction id 276 and the log anchor 230. Both checkpointed elements are necessary for efficient recovery of the Telescope log 264. They are both kept in memory on the primary server 122p, and thus a disk read is not necessary to register the checkpoint. The log anchor (described in reference to FIG. 3) contains data to find the log file and to locate the next location for an entry. The transaction id allows the secondary server 122s to track the increase of transaction-- id values, preventing the accidental reuse of a transaction id 276. It also allows Telescope 160L to check if an operation in progress during the primary server failure was committed to the Telescope log 264.
Telescope log entries can be integrated with the operations in HA-PXFS mini-transactions. Without Telescope 160, the sequence of events in HA-PXFS to satisfy a client request is as follows:
1. Client sends request.
2. Primary sends checkpoint with state data.
3. Secondary allocates state object and acknowledges checkpoint.
4. Primary updates storage.
5. Primary returns results.
6. Client sends asynchronous forget message to secondary.
The Telescope logging procedure (described above) enhances this sequence by adding an additional step after steps 1 and 4 as follows (the added steps are bolded):
1. Client sends request.
1.1 Primary 122p enters request into log and receives a transaction id.
2. Primary sends checkpoint with state data.
3. Secondary 122s allocates state object and acknowledges checkpoint.
4. Primary 122p updates storage.
4.1 Primary 122p enters commit or invalidate message into log, depending on whether operation was successful.
5. Primary 122p returns results.
6. Client 126 sends asynchronous forget message to secondary.
This algorithm guarantees that the secondary server 122s is able to restart the Telescope service 160 in a consistent state. Failures can occur in several places relative to the Telescope log operations:
1) If the primary server fails before step 2, there will be no record that the request was ever received. The Galileo replication framework will resend the request to the secondary server.
2) If the primary fails between steps 2 and 3, the request will appear in the log but not in the file system, and no state will be checkpointed to the secondary server. In this case, the secondary server should consult its most recent checkpointed log anchor. If additional log entries have been made but not checkpointed, they will be found at the next-- rec pointer 242 (FIG. 3) in the log anchor. Since the request will be resent by the Galileo replication framework, any such log entries should be nullified by the secondary server with an invalidate log entry.
3) Once the transaction id of the current operation is checkpointed to the secondary server, primary site failures become easier. If the secondary retries the operation, a new log entry need not be recorded since one already exists. A commit or invalidate message is recorded depending on whether the operation is deemed successful or not. If the former primary had recorded a commit message (hence the failure was between steps 6 and 7), an additional commit message will be disregarded.
Consequently, the failover algorithm for restarting Telescope 160 after a failure of the primary 122p is as follows:
1. Perform HA-PXFS failover, including locking out operations, mounting the file system, and obtaining vnode pointers.
2. Locate the log file 214, either from the last checkpointed log anchor 230 or from a wellknown location on the shared disk 126.
3. Using the next-- rec pointer 242 from the last checkpointed log anchor 230, check if additional log entries have been made without being checkpointed. If so, obtain the transaction-- ids 276 from these entries and log invalidate messages (the requests will be retried).
4. Update the log anchor data structure 230.
The algorithms described in this section concentrate on the 1-safe mode of operation. They change little for 2-safe mode. For example, rather than entering a commit message into the log 264 in step 4.1 above, the primary site transmits the log entry 266 created in step 2 to the remote site. The primary 122p does not return results (step 5) until an acknowledgment is received from the remote site. If multiple copies of the log entry 266 are transmitted to the remote site during a failover, they will be identified as duplicates by the transaction id and only the first will be processed. Note that Telescope 160 relies on the Galileo replication framework to direct all messages from the remote site to the new primary server (e.g., the secondary local server 122s) after a failure.
In a preferred embodiment Telescope 160 transmits data using standard Unix socket utilities. Using a high-level interface allows Telescope to function across any number of physical networks via any number of networking protocols. TCP/IP is suggested for its reliability and throughput. If a dedicated link can be established between the local and remote sites, Telescope performance, especially in 2-safe or very safe modes, improves significantly. In any case, it is important to determine in advance that the network bandwidth can match the bandwidth of the storage system in use. Techniques such as data compression can be used to alleviate network bandwidth problems, but at the cost of increased latency.
The details of establishing and maintaining a connection between sites depends on Galileo's global networking capabilities. The present invention does not exclude any manner of establishing and maintaining such a connection.
Setting up a Connection
The connection setup procedure is one that can evolve over successive Telescope versions. The only required capability is some means of establishing a pair of socket connections between the primary and remote sites. Initially, IP addresses and port names can be entered manually at both sites. Over time, an automatic setup protocol can be established.
The automatic setup protocol would likely be based on a well-known Telescope control port. The control port would be used exclusively for establishing connections between primary and remote sites. To enable a remote site, the remote Telescope service (described in Section 4.9) would be started on a Galileo cluster. It would wait for connection requests on the control port. After receiving a connection request, the remote Telescope service would somehow indicate the replication resources it had available--for instance, free disk partitions and their sizes as well as perceived network bandwidth and latency between sites. The primary site would indicate the replication resources it required, and a pair of socket connections would be established for two-way communication between sites.
Transmitting Data to the Remote Site
Replication data is preceded by a Telescope header. The Telescope header indicates the mode of transmission (1-safe, 2-safe, or very-safe) as well as the length of the transmission. The mode of the transmission indicates what action the remote site should take upon receiving the packet. In 2-safe and very safe modes, latency is critical. The remote site should perform the encoded operation and return an acknowledgment as quickly as possible. In 1-safe mode, latency is not as important, and it is sometimes necessary to receive the entire contents of a large transmission before any action can be taken. The length field in the header indicates how many bytes the receiver should expect from the body of the transmission. This simplifies receiving the data from a streams interface.
The header should include two other fields that may not be incorporated into the initial version of Telescope but may be important later. First, in order to conserve network bandwidth, transmitted data may be compressed. If compression algorithms vary, a header field may be necessary to indicate the proper decompression algorithm. Second, Telescope may need to provide its own authentication and encryption services. If this is necessary, a header field may be necessary for an authentication or encryption key.
The body of the transmission consists of log entries. In 2-safe and very safe mode, only one entry should be transmitted at a time, though optimizations might allow concurrent transmissions for concurrent accesses. In 1-safe mode, the contents of the log can be transmitted in large fragments. Telescope places no size limit on the body of the transmission; however, limitations on buffer space on the sending and receiving sides should be considered.
Transmission in 2-safe and very safe modes is governed by their algorithms. 1-safe mode, on the other hand, is much more flexible. The interval at which transmission occurs should be affected by several factors:
The size of the log.
The rate at which entries are recorded in the log.
The rate at which the log can be flushed once transmission begins.
The acceptable consistency lag between the primary and remote sites.
Under normal circumstances, Telescope 160 will use a circular log 264. Circular logs recycle space by reusing parts of the log that are no longer needed. For instance, if the contents of a region of a log file are transmitted to the remote site and acknowledged, then that region of the log file can be reused. There are reasons to not use circular logs. For instance, the contents of the log can be used to audit the operations that were applied to the file system. In this case, the log file 264 must be able to grow indefinitely, or multiple log files should be used. In either the circular or non-circular case, if the log fills up, the transmission parameters were not properly configured. The Telescope management API (which is not described herein) contains methods for setting the I-safe transmission interval.
Transmission in 1-safe mode is based on parameters stored in the log anchor. When a transmission is initiated, a snapshot is taken of the last-- flush and prev-- Isn fields. These LSNs define the region of the log that will be transmitted. Since the transmission does not affect the end of the log, no lock on the log is required to read data from the transmission region. It is recommended that the transmission be performed by a dedicated thread so that file system operations appending new records to the log are not affected.
The dedicated thread transmits the region of the log through the socket connection already established. It waits for acknowledgment of all data transmitted before making itself available for the next log flush. Simple network protocol acknowledgments are not sufficient--an acknowledgment must be received from the remote Telescope service 160R that the transmitted operations have been applied to the file system on the remote site.
This transmission scheme can be enhanced to allow multiple concurrent threads to transmit data to the remote site. While the remote site applies one set of operations to the remote file system, another the next set of operations can be traveling across the network. This scheme is more complicated with respect to identifying lost transmissions. Since the remote Telescope service 160R will preserve the chronological order of the log 264, log regions transmitted by separate threads cannot be allowed to pass each other in transit.
Referring to FIG. 3, during the log flush procedure, the log anchor is updated to reflect the current status of the transmission. The last-- ACK field 248 is written whenever the primary site receives acknowledgment that operations were applied to the remote site. The last-- flush field 246 is written whenever data is transmitted. It is almost impossible for last-- ACK 248 to point to a chronologically later position in the log than the last-- flush field. In the single thread case, a new log flush cannot start until the last-- ACK and last-- flush fields 248, 246 are the same.
Synchronization
Synchronization data can be transmitted in a special protocol, or it can be encoded as log entries. Using log entries should be the easier approach, as it avoids the need for another method of encapsulating data. For instance, to indicate that a file should be copied from the primary site to the remote site, two log entries 266 can be used as follows:
1. A file create entry will indicate the file's pathname and the identifier the primary site will use for future transmissions regarding this file; and
2. A file write entry will can be used to transmit the file's contents to the remote site.
If file timestamps must be preserved, these can be transmitted through attribute log entries. For greater efficiency, multiple encoded entries can be batched and transmitted together.
Most of the Telescope services 160R required at the remote site have already been discussed, but are briefly summarized herein.
The remote site has the following duties:
1) Accept requests for replication;
2) Decode and replay log entries; and
3) Provide a PXFS server for read-only access during normal operation read-write access after failover.
There are several different types of failures that Telescope must account for. One, failure of a PXFS server at the primary site, has already been discussed. Another, failure of the primary site, is the principal reason Telescope exists. Other failures accounted for by Telescope 160 include:
1) Failure of an operation when applied at the remote site that succeeded at the primary site;
2) Failure of the synchronization procedure;
3) Failure of the remote Telescope service (including failure of the node hosting the remote Telescope service);
4) Failure of the remote site; and
5) Failure of the interconnect between the primary and remote sites.
While the present invention does not describe how each of these failures are specifically dealt with by Telescope 160, it should be apparent from the preceding discussion how such failures are accounted for by the Telescope service 160. following lists the C++ prototypes for the checkpointed methods in Table 1 and indicates which parameters must be transmitted to the remote site by the geographical replication software (i.e., the Telescope service 160). All f-- obj and derivative types are sent as fobjid-- ts. Each prototype also indicates the class of which it is a member. The class instance on which the method is invoked is referred to as this. Other terms used in this Appendix include:
sol: the class that defined Solaris errors, types, etc.
dirprov: the class that implements directory operations.
mempager: the class that implements paging operations.
io-- ii: the class that implements i/o (input/output) operations.
fobj-- ii: the class that implements all generic file operations.
A. 1 create-- fobj
sol:: error-- t
dirprov-- ii::create-- fobj(const char *nm, const sol::vattr-- t& attr, sol::vcexcl-- t exciflag,
Long mode, fs::fobj-- out fobj, fs::fobj-- info& fobjinfo, ULong& key, solobj::cred-- ptr credobj, Long flag, Environment&-- environment);
Transmit: this, nm, attr, exclf lag, mode. At commit, transmit f obj.
A. 2 remove-- fobj
sol:: error-- t
dirprov-- ii::remove-- fobj(const char *nary, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, nm.
A. 3 create-- symlink
sol:: error-- t
dirprov-- ii::create-- symlink(const char *nary, const sol::vattr-- t& attr, const char *targetpath, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, nm, attr, targetpath.
A. 4 create-- dir
sol:: error-- t
dirprov-- ii::create-- dir(const char *dirnm, const sol::vattr-- t& attr, fs::unixdir-- out newdir, ULong& key, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, dirnm, attr. At commit, transmit newdir.
A. 5 remove-- dir
sol:: error t
dirprov-- ii::remove-- dir(const char *dirnm, fs::unixdir-- ptr cur-- dir, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, dirnm, cur-- dir.
A. 6 rename-- fObj
sol::error-- t
dirprov-- ii::rename-- fobj(const char *sourcenm, fs::unixdir-- ptr target-- dir, const char *targetnm, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, sourcenm, target-- dir, targetnm.
A. 7 page-- out
void mempager-- ii::page-- out(sol::u-- offset-- t offset, sol::size-- t length, Boolean set-- size, bulkio::in-- pages-- ptr pglobj, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, offset, length, set-- size, extract data from pages.
A. 8 write-- out
void mempager-- ii::write-- out(sol::u-- offset-- t offset, sol::size-- t length, Boolean set-- size, bulkio::in-- pages-- ptr pglobj, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, offset, length, set-- size, extract data from pages.
A. 9 sync
void mempager-- ii::sync(sol::u-- offset-- t offset, sol::size-- t length, Boolean set-- size, Long, bulkio::in-- pages-- ptr pglobj, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, offset, length, set-- size, extract data from pages.
A. 10 uiowrite
sol::error-- t io-- ii::uiowrite(sol::u-- offset-- t off, sol::size-- t& len, bulkio::in-- uio-- ptr uioobj, Long ioflag, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, off, len.
A. 11 fsync
sol::error-- t io-- ii::faync(Long syncflag, solobj::cred-- ptr credobj, Environment&-- environment); Transmit: this, syncflag.
A. 12 set-- attributes
sol::error-- t fobj-- ii::set-- attributes(const sol::vattr-- t& attr, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, attr.
A. 13 set secattributes
sol:: error t fobj-- ii::set-- secattributes(const fs::secattr& sattr, Long secattrflag, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, sattr, secattrflag.
A. 14 write-- all-- attr
void fobjprov-- ii::write-- all-- attr(sol::vattr-- t& attributes, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: this, attributes.
A. 15 ioctl
sol::error-- t fobj-- ii::ioctl(Long nodeid, Long pid, Long iocmd, Long arg, Long flag, Long& result, solobj::cred-- ptr credobj, Environment&-- environment);
Transmit: iocmd, arg, flag | https://patents.google.com/patent/US6144999A/en | CC-MAIN-2018-47 | refinedweb | 18,203 | 52.09 |
While implementing the batched matrix multiplication, i noticed that the batched matrix multiplication is not efficient, see the code below
import torch # Input tensor ## Batch size=8192, dim=512 x = torch.FloatTensor(8192, 512).requires_grad_().cuda() if True: # Batch strategy 1 x1 = x.view(8192, 8, 1, 64) # 512 = 8 * 64 W1 = torch.FloatTensor(8, 64, 64).cuda() out1 = torch.matmul(x1, W1) # out: [8192, 8, 1, 64] print(torch.cuda.memory_allocated()) # 1107427328 if False: # Batch strategy 2 x2 = x.view(8192, 1, 512) # add one dimension for batch matmul W2 = torch.FloatTensor(512, 512).cuda() # larger than W1 # out: [8192, 1, 512] # the same number of elements as out1 out2 = torch.matmul(x2, W2) print(torch.cuda.memory_allocated()) # 34603008
However, it turns out that Batch strategy 2 has less memory cost despite that W2 is larger than Batch strategy 1. And everything else are the same (x1, x2 have same number of elements, also out1, out2).
I also found that by removing the requires_grad_() the memory costs are similar.
What’s the possible reason for that? | https://discuss.pytorch.org/t/memory-inefficient-in-batch-matrix-multiplication-with-autograd/28164 | CC-MAIN-2022-21 | refinedweb | 177 | 60.61 |
sgr eval
sgr eval [OPTIONS] COMMAND
Evaluate a Python snippet using the Splitgraph API.
This is for advanced users only and should be only used if you know what you are doing.
Normal Python statements are supported and the command is evaluated in a namespace where the following is already imported and available:
Repository: class that instantiates a Splitgraph repository and makes API functions like .commit(), .checkout() etc available.
engine: Current local engine
object_manager: an instance of ObjectManager that allows to get information about objects and manage the object cache.
Example:
sgr eval 'import json; print(json.dumps(Repository .from_schema(repo_name) .images["latest"] .get_table(table_name) .table_schema))' -a repo_name my_repo -a table_name my_table
Will dump the schema of table my_table in the most recent image in my_repo in JSON format.
For more information, see the Splitgraph API reference.
Options
--i-know-what-im-doing: Pass this if you're sure that the code you're running is safe and don't want to be prompted.
-a, --arg <TEXT TEXT>...: Make extra variables available in the command's namespace | https://www.splitgraph.com/docs/sgr/versions/v0.1.2/miscellaneous/eval | CC-MAIN-2020-45 | refinedweb | 177 | 56.45 |
by Robin Parma, Alex Martelli, Scott David Daniels, Ben Wolfson, Nick Perkins, Anurag Uniya, Tim Keating, Rael Dornfest and Jeremy Hylton, authors of the Python Cookbook
1. Simple Tests Using Exceptions
Usually Python is straightforward, but there are a few unexpected exceptions.
Credits: Robin Parma
Problem
You want to know if the contents of a string represent an integer, which is not quite the same thing as checking whether the string contains only digits.
Solution
# try/except is generally the best approach to such problems:
def IsInt(str): """Is the given string an integer?""" try:int(str) except ValueError:return 0 else:return 1
Discussion.
2. Constants in Python
Liberal Python lets you rebind any variable; yet, there is an instance where you can protect your variables.
Credits: Alex Martelli
Problem
You need to define module-level variables that client-code cannot accidentally rebind, such as "named constants."
Solution
#
Discussion.
| http://www.oreillynet.com/pub/a/python/2002/07/11/recipes.html | crawl-002 | refinedweb | 150 | 50.87 |
Zed_Oud
@cook.
Zed_Oud
The HTML I'm using works everywhere, but not loaded through in an extension. That's my whole goal, I am trying to replace webbrowser.open("local file") for use in an extension. I haven't tried to load a local image using my HTML doc, I'll try that out.
Here is an example of my HTML when I point it at ""
<html> <body bgcolor="#000000"> <img src="" alt="" ><br><br> <img src="" alt="" ><br><br> <img src="" alt="" ><br><br> <img src="" alt="" > </body> </html>
Here is my full code (cleaned and formatted, but just as dysfunctional when used as an extension):
# coding: utf-8 import appex from urllib2 import urlopen import os, console, requests, urlparse def write_text(name, text, writ='w'): with open(name, writ) as o: o.write(text) def img_page(file_list, link_list=None): if link_list is None: link_list = file_list links = zip(file_list, link_list) x = '<br><br>\n'.join(['<img src="{0}" alt="{1}" >'.format(a,b) for a,b in links]) {0} </body> </html> """.format(x) return y def view_doc(text): import ui w = ui.WebView() w.scales_page_to_fit = False w.load_html(text) w.present() def open_file(file_path): import ui file_path = os.path.abspath(file_path) file_path = urlparse.urljoin('file://', os.path.abspath(file_path)) #v = ui.View() #file_path = '' wv = ui.WebView() #v.add_subview(wv) wv.load_url(file_path) #v.frame = (0,0,320,568) #wv.frame = (0,0,320,568) #v.present() wv.present() def view_temp_index(file_url_list): temp_fn = '__temp.html' write_text(temp_fn, img_page(file_url_list)) open_file(temp_fn) def get_Pic_Links_Content(content,url=None): from bs4 import BeautifulSoup as bs if url is None: url = '' # 'http://' s = bs(content) p = s.findAll('img') pics = [] for x in p: y = urlparse.urljoin(url, x['src']) if y not in pics: pics.append(y) return pics def get_Pic_Links(url): r = requests.get(url) #print 'viewing pics from url:', r.url return get_Pic_Links_Content(r.content, url) def pick(url): choice = console.alert('View:','Pick where to view source:','Make File','View Directly','Console') pics = get_Pic_Links(url) if choice == 1: view_temp_index(pics) elif choice == 2: view_doc(img_page(pics)) else: print '\n'.join(pics) def main(): if not appex.is_running_extension(): print '\nRunning using test data...' url = '' else: url = appex.get_url() if url: pick(url) else: print 'No input URL found.' if __name__ == '__main__': main()```
Zed_Oud
Correct me if I'm wrong, but does the memory limit while running Python as an appex extension prevent us from loading things with WebView.load_url or WebView.load_html ?
I've managed to get a local html file to load, but it will not populate its img tags, images will not load and leave the default blank bar/box ( "<img src=""> ). The same html file will load perfectly using ui.webview or webbrowser NOT running from an extension (the html doc will work anywhere and everywhere else).
import ui def view(text): v = ui.View() wv = ui.WebView() v.add_subview(wv) wv.load_html(text) v.frame = (0,0,320,568) wv.frame = (0,0,320,568) v.present()
There's a cleaned up example of the function called to run my html doc as a string, though I've also tried running as a local file. | https://forum.omz-software.com/user/zed_oud/posts | CC-MAIN-2021-04 | refinedweb | 528 | 69.38 |
XSL Considered Harmful
May 20, 1999
Declaration of War
Two weeks ago
XML.com published an article by G. Ken Holman, What's the Big Deal With
XSL?, in which the author expressed his "perplexity about the perceived controversy
over XSL." I expressed my surprise and disappointment to XML.com that one point of
view
in this "perceived controversy" had been given such a full airing while nothing had
been
heard from the other side. I asked for equal time and I was given it.
I am going to start out with a brief and perhaps stark statement on the subject, my "declaration of war". It is high time we get to the heart of the matter.
XSL, a "sometime in the future" technology, full of beautiful (if vague) prognostications about its "power" and "richness", offers no useful improvement in capability over current and implemented full W3C Recommendations for stylesheets and transformation.
XSL has no role to play in the evolution of web technology into the "new desktop" as it does not support interactive documents.
XSL is a great danger to a major objective of XML, the inclusion of semantic information in Web pages, as it replaces XML elements annotated with formatting information by XSL formatting objects.
XSL is the most hideous and unwieldy language imaginable and stands absolutely no chance of acceptance by the web community.
XSL advocacy has blurred the focus of the W3C, by introducing competing standards for styling and transformation, and set back by at least two years the goal of vendor-independent, semantically rich "open information highway", by undermining support for existing standards such as CSS and the DOM.
This is really all I have to say, but if any one of these points is true, that is a damning case against XSL. I have invited and continue to invite, in good faith and with an open mind, XSL advocates to counter these arguments.
In the remainder of this article I will elaborate on these five fatal flaws of XSL and present an application which will give you the chance to directly compare XSL to the transformation and styling technologies supported by current W3C Recommendations. But first, The Challenge:
The Challenge.
Next we explore the five fatal flaws of XSL.
XSL Has Nothing New for the Web).
When compared to the DOM+CSS, XSL does not solve any Web-related problems that the current W3C Recommendations do not adequately handle. What is the Big Deal indeed?
XSL Does Not Support Interactive Web Documents
With HTML forms included through the HTML namespace, but without CGI, and definitely without XSL, we at CITEC are building the following Web browser-based semantically rich XML applications:
- DocZilla
- Online Books/Manuals with Hypertext TOCs and structured search
- CarZilla
- Web browser designed for a car with simulated feeds to diagnostic and maintenance systems
- LinkManagerZilla
- Manages hyperlinks in document collections, providing interface, maintenance, editing and visualization of a link database and links targets and sources in documents
- StockZilla
- Simulated stock reporting feed, shown in this article
- Interface to email system
- IETMZilla
- Interactive Electronic Technical Manual Interface with special safety features
- AnnotationZilla
- Allows insertion of annotations into documents
- HelpZilla
- WindowsHelp-like system
- SlideZilla
- Does slide shows
- EditorZilla
- DTD-driven XML editor
I showed some of these applications at the XML Europe conference and also delivered my now-standard denunciation of the "XSL conspiracy". The speaker who had the misfortune to follow me was a very knowledgeable gentleman whom I respect very much, Neil Bradley (author of The Concise SGML Companion and The XML Companion), and the topic he had the misfortune to cover was, of course, XSL. And he began by saying that, of course, he would never attempt to create the applications he had just seen with XSL because "XSL is not for interactive documents".
Is there really anything more to say? If XSL is no good for interactive documents what do I need XSL for? Is there anyone out there that is not interested in enabling interactive behavior in a clean, structured, standard, and maintainable way in their web documents? Isn't that what XML on the Web is for, to enable such applications to be built using semantic information from element names, attributes and the document structure? This is what we thought and this is what we have been doing. We think our 'Zillas are the proof that XML on the Web does everything XML on the Web was promised to do. And we do it with XML, CSS, and the DOM and really cannot understand why anyone could, would or should give a damn about XSL.
The whole XSL process, described admirably enough in Mr. Holman's paper, is a static process. Interactive processes are designed around events which have event handlers associated with them. An event could, in principle, occur on any XML element (in fact we have done exactly this in many of our 'Zilla applications) and can invoke a myriad of behaviors which most often involve the modification of some element styling or perhaps the update of a element value. Occasionally, a little reordering of some part of one or more document trees takes place. Much less commonly, all or a large portion of the document is reordered, as in an application which updates a sorted table. The CSS model of attaching formatting to the elements is perfectly adapted to handling events which cause stylistic changes, and the DOM model is very efficient for updates to the document tree contents and local reordering. It is adequate for global reordering. In addition, the document trees often reside in different frames or windows and one must have communication between them. JavaScript provides these kinds of facilities as it is an environment native to the browser environment. When an event occurs you typically want to know what element it occurred on, what its name and attributes are, and most often you will be doing things that will effect its immediate children or parent. This is all elementary stuff if you're using the DOM and JavaScript. Finally, it all has to be very fast.
The XSL folks seem to be about a million miles from this, proposing a horse-and-buggy model in laser-guided precision missile world.
Semantic Information Threatened by XSL
I can understand why overworked undergraduates think FONT is cool, but I'm very disappointed when a group of highly skilled adults tell kids to stop playing, form a committee - and then come out with a set of supercharged FONT tags.
Håkon Lie on XSL Formatting Objects, xsl-list, 28 April 1999
Dear Mr. Lie (co-inventor of CSS) has penetrated once again to the essence of a matter ... and in his inimitable style. If I could only win friends and influence people like that! I highly recommended that you go and get the full story from his paper " Formatting Objects Considered Harmful". A short version of the story is this: XSL proposes the existence of something called a formatting object, XML elements which indeed resemble what Mr. Lie calls a supercharged FONT tag. It is the final result of an XSL transformation which is sent to the rendering engine. If the rendering engine reads formatting objects directly, all the semantic information in the original information may be lost. This is exactly the information we get through element events and the DOM to make all of our 'Zilla applications work. XSL, in this scenario, would destroy XML on the Web.
Among the solutions to this problem is stipulating in the standard that formatting objects must preserve a mapping back to the original XML element. Technically not very elegant and probably unenforcable.
Another solution is to legislate that formatting objects not be allowed to ever physically exist as XML. Not bloody likely, but there is a logical candidate to replace XML formatting objects: CSS! One must ask why don't we just forget about formatting objects and just use CSS in the first place?
XSL is an Ugly, Difficult Language.
XSL has Set Back the Web at least 2 Years
When I have criticized Microsoft for the lack of complete and correct CSS support in IE5, I have found that many are quick to class me among the irrational Microsoft bashers. In fact I am keenly interested in seeing Microsoft create a browser which adheres to Web standards. I want to see this because I believe that to a significant extent it is the character of our new information-based civilization which is at stake. I also happen to believe that we will sell many more of our 'Zillas if the technology we use is also supported by Microsoft and by other browser vendors. Finally, I think that the vendors can be persuaded that it is in their interest to support web standards if consistent pressure is applied to them from the marketplace and from those people who are the catalysts for new technological developments.
Today there is one and only one W3C Recommendation for the formatting of XML documents on the Web, CSS. Today there is one and only one W3C Recommendation for transformation and manipulation of XML documents, DOM. This year we could have had semantic markup on the web, in the major browsers, with support for XML 1.0, CSS and the DOM. This did not happen and I am sorry to say that XSL advocates that did not clearly articulate their support for current Web Recommendations contributed heavily to that state of affairs.
I think it is clear to all that the early implementation of XSL by Microsoft was a disaster. As predicted, the next version of the W3C XSL draft created two XSLs, the W3C's and Microsoft's. But more important than this is the fact that XSL has been a major marketing coup for Microsoft in enabling them to "hide" their deficient implementations of web Recommendations and to force the entire marketplace to postpone XML implementations for another couple of years while we wait for common standards that work in the all the major vendor's products.
The corrective action at this point is to do what we as a community should have done six months ago, to insist on full implementation of CSS, the DOM, and XML. If we clearly articulate this message now we may have XML on the Web in one year instead of two. If we wait for XSL to either flop or succeed it will definitely be two and if it does flop perhaps it will be three. There are also issues far more basic and critical than XSL which the W3C should be addressing with greater attention and priority. These include linking, row and column spanning in CSS-specified XML tables, and inclusion of scripts in XML files possibly followed by query and schema issues. Our first order of business is to create a workable and standard XML environment for the Web. XSL, a standard designed to improve the layout composition of printed documents, should not be in our first order of business.
The second part of this article consists of a comparison of the well-known Microsoft stock-sorting XSL and an enhanced application which uses the DOM and CSS instead of XSL.
XSL vs. the DOM+CSS toe-to-toe
In this section we will compare the effectiveness of XSL to the DOM for transforming XML documents and we'll show where the DOM+CSS approach goes way beyond XSL in enabling the scripting of dynamic, interactive behavior in truly Web-oriented XML applications.
The original
XSL application was developed by Microsoft. It can be run (on IE5 browsers) at A zip file of all
the necessary files is available at. According to
Jonathan Marsh, Program Manager, XSL at Microsoft, the example currently at the above
URLs
expands on the application described in this article with the addition of data-typed
sorting, number formatting, and simple data-driven formatting changes. The author
did not
have a chance to look at these changes before we went to press.
The XSL application can only be run in IE5. It is not W3C Recommendation compliant as XSL is not currently a Recommendation of the W3C. I do not know if this application adheres to the most recent revision of the XSL Working Draft but judging from the comments in Mr. Holman's paper about "msxsl" I gather that this is not likely.
The DOM+CSS application is compliant with current W3C Recommendations and can be run in any browser which supports them. At this moment that includes at least the Gecko builds at and DocZilla at.
The XSL Stock Sorter
This application sorts the rows of a table based on values in any individual column by clicking on the header of the column. The sort is straight ASCII (z comes before A) string sort and it does not handle numeric or other types of values.
The file downloaded to the browser is XML. XSL is used to convert the XML into an HTML table. Each table header has a nested Div tag with an onClick event to invoke the XSL sort, passing the name of the field to be sorted to the routine. The entire document is regenerated in HTML each time the table is sorted.
By the way, the time and date is hard-coded into the demo. I may as well give away now that the JavaScript scripting environment will of course give us many date operations including tricky date conversions (humans like to see dates and times displayed in a variety of ways and computers also have their own ideas about how to represent a date) as well as timer operations which will allow us to trigger our stock updates from the client-side at whatever interval the user desires.
The contents of "sort-stocks.xsl", referenced in the "portfolio.xsl" script, trigger the transformation of the document, I think. It's complicated!
DOM Stock Sorter - Functionality
The functionality is similar to the XSL Stock Sorter - but with some important differences. Type-specific and directional sorting has been implemented, and the default values are actually encoded in the column header (One could imagine being able to change properties of the sort from controls in the page.) There is an XML column header instead of the column headings hard-coded in the script found in the XSL application. Here is a snippet of data showing the header and a row of stock information:
<?xml version="1.0"?> <?xml-stylesheetSymbol</colhead> <colhead field="string/g" direct="asc">Name</colhead> <colhead field="curr" direct="desc">Price</colhead> <colhead field="num" direct="desc">Change</colhead> <colhead field="units" direct="desc">%Change</colhead> <colhead field="units" direct="desc">Volume</colhead> </headrow> </stockhead> <stockbody> <stock> <symbol>LOVE</symbol> <name>Love Corp</name> <price>$18.875</price> <change>-1.250</change> <percent>-6.21%</percent> <volume>0.23M</volume> </stock>
The colhead field attribute allows one to specify case-insensitive string sorting (/g - z comes after A), currency, numeric, and numeric with a units symbol sorts and the direct attribute states whether the sort should be ascending or descending.
The table is formatted in XML using CSS2 table display properties. Hey, you don't need XSL to create HTML tables if your browser is CSS2 compliant! It looks quite good, if I say so myself:
The stylesheet for this application is shown below:
portfolio { display: table; margin-top: 0.5em; margin-bottom: 0.5em; margin-left: 0.5em; } symbol, name, price, change, percent, volume { display: table-cell; font-family: Arial, Helvetica, sans-serif; font-size: x-small; line-height: 1.2; vertical-align: top; padding-left: 0.2em; padding-right: 0.1em; padding-top: 0.1em; border-bottom: 1px solid navy; } colhead { cursor: pointer; display: table-cell; font-family: Arial, Helvetica, sans-serif; font-weight: bolder; font-size: small; text-align: center; line-height: 1.2; vertical-align: top; background: #CCC; color: black; padding-left: 0.2em; padding-right: 0.2em; padding-bottom: 0.05em; border: 2px inset black; } stockhead stock symbol, stockhead stock name { text-align: left; } change, price, percent, volume { text-align:right; padding-right: 0.4em; } stock, headrow { display: table-row; } stockhead { display: table-header-group; } stockbody { display: table-row-group; }
We use the DOM to traverse the elements of the column header and to set an onMouseDown event sort handler for each one. We use DOM operations to also get attribute information to guide the sort and to actually handle the mechanics of rearranging the node.
Of course, we have no need to regenerate the entire document. Another very important point about the DOM approach is that the code is all totally generic - it will work on any table having matrix (no spanned rows or colums) structure and headers.
DOM Stock Sorter - Code
In the main routine four global variables must be declared which are specific to the table markup. An array is created which will hold the table cells and makeSortableTable is called. That is all that is needed to make the table sortable by clicking on column headings. The four global variable which must be declared contain the name of the column header elements, the name of the row container elements and the attribute names used to identify the direction of the sort and the field type.
var gHeaderRowCellGI = "COLHEAD"; var gRowCellGI = "STOCK"; var gSortDirectionAttributeName = "DIRECT"; var gFieldTypeAttributeName = "FIELD"; var gTableCells = new Array(); makeSortableTable(gRowCellGI);
It may be of interest to note that this information could be passed to the application by means of architectural forms, a technique by which any element or attribute can be associated with an abstract element type such as COLHEAD, STOCK or attribute type such as DIRECT or FIELD and thereby entirely avoiding any markup-specific code. (If, of course, the browser has the ability to understand architectural forms.)
Before we go on, I would like to emphasize again - from this point on you are looking at totally generic library functions which can be used with many different XML files and applications - they are library or utility functions. The markup-specific part of our code was the four declarations shown above. An extremely important characteristic of procedural programming languages is that they allow and even strongly encourage reusable module construction.
function makeSortableTable(rowCellGI) {
We will set up sort event handlers on the cell headers. Compare this to the XSL application's technique of using an onClick attribute in the generated markup. This technique allows one or more event handlers to be set on any XML element at any point in the processing without requiring any special attributes in the markup.
setTimeout(SetSortOnCellHeaderEvents,0);
We get all the row elements and store them in global array. Then we call putDOMNodeIntoSortTable to extract the cell elements in the rows and store them in a two dimensional array ready for sorting.
var celllist = document.getElementsByTagName(rowCellGI); for (var i=0; i < celllist.length; i++) { gTableCells[i] = celllist[i]; } putDOMNodesIntoSortTable(gTableCells); } function putDOMNodesIntoSortTable(nodes) { var i, j; var ncount = nodes.length; for (i = 0; i < ncount; i++) { var node = nodes[i]; var childNodes = node.childNodes; var ccount = childNodes.length; for (j = 0; j < ccount; j++) { var child = childNodes[j]; node[j] = child.firstChild.nodeValue; } } }
Here is where we do the actual setting of events on column headers discussed above. We get the column headers by the element name specified in our declaration and set an onmousedown event handler called sortOnColumn on each header cell returned in the headerCells array.
function SetSortOnCellHeaderEvents() { var headerCells = document.getElementsByTagName(gHeaderRowCellGI); for(var i=0; i<headerCells.length;i++) { headerCells[i].onmousedown = sortOnColumn; } }
sortOnColumn is the event handler invoked when the user clicks on a header cell. First it must get the fieldtype and direction attributes from the column header to invoke the proper sorting for the column. Actually we just iterate over the column header cells until we find a node which matches the node on which the event was triggered. Once that node is found all we need to do is invoke the low level sort routine, passing the column number, fieldtype, and direction as arguments.
function sortOnColumn(e) { // node is text, parent is headercell, parentparent is // container for header cols var node = e.target.parentNode.parentNode.firstChild; for (i=0; i<e.target.parentNode.parentNode.childNodes.length; i++) { if (node == e.target.parentNode) { var fieldtype = ""; var direction = ""; for (var j=0; j<node.attributes.length; j++) { var currAttr = node.attributes[j]; if (currAttr.nodeName == gFieldTypeAttributeName) { fieldtype = currAttr.nodeValue; } else if (currAttr.nodeName == gSortDirectionAttributeName) { direction = currAttr.nodeValue; } } sort(gTableCells,i,fieldtype,direction); break; } else { node = node.nextSibling; } } }
This is a really bad sort routine so I should be careful here to blame the folks I stole it from: it was lifted from one of Netscape's demos (my colleague Heikki says it would be good for me to try to be nice from time to time and suggests that I might better say "the routine is simple and more robust things would be used in real-life applications"). I added the nice bits with handling the fieldtypes and direction. The sort is just a bubble sort, the more unsorted the table is the more swapping of nodes takes place. Comparison between nodes is done with compare function which takes into account the fieldtype and direction.
function sort(collection, key, fieldtype, direction) { var i, j; var count = collection.length; var parent, child; for (i = count-1; i <= 0; i--) { for (j = 1; j <= i; j++) { if (compare(collection[j-1][key], collection[j][key], fieldtype, direction)) { // Move the item both in the local array and // in the tree child = collection[j]; parent = child.parentNode; collection[j] = collection[j-1]; collection[j-1] = child; parent.removeChild(child); parent.insertBefore(child, collection[j]); } } } }
compare makes use of JavaScript's decent regular expression, string, and math classes, quite necessary even in a relatively small application such as this one. Let's not kid ourselves, without all of this XSL is out of the running for real world applications and with it XSL will have reinvented the wheel - except that it will be square.
function compare(value1, value2, fieldtype, direction) { var str; if (fieldtype.toUpperCase() == "STRING/G") { value1.toUpperCase(); value2.toUpperCase(); } else if (fieldtype.toUpperCase() == "CURR") { var str = value1.match(/\$\s*(\d*\.\d*)/); value1 = RegExp.$1 * 1.000; var str = value2.match(/\$\s*(\d*\.\d*)/); value2 = RegExp.$1 * 1.000; } else if (fieldtype.toUpperCase() == "NUM") { value1 = value1 * 1.000; value2 = value2 * 1.000; value1 = Math.abs(value1); value2 = Math.abs(value2); } else if (fieldtype.toUpperCase() == "UNITS") { var str = value1.match(/((+|-)?\d*\.\d*)/); value1 = RegExp.$1 * 1.000; var str = value2.match(/((+|-)?\d*\.\d*)/); value2 = RegExp.$1 * 1.000; value1 = Math.abs(value1); value2 = Math.abs(value2); } if (direction.toUpperCase() == "DESC") { return (value1 < value2); } else { return (value1 > value2); } }
Summary
The DOM implementation of the Stock Sorter takes advantage of modular programming techniques to create an application which is generic and organized. The functionality of the application is easily extended to handle a variety of sort field types thanks to the depth of the JavaScript language. Interactivity through events adds the possibility of interesting dynamic behavior through reading the element generic identifiers and attributes directly from the CSS formatted XML. Effected nodes in transformations are manipulated directly in memory rather than reprocessing the entire document. W3C-compliant CSS allows XML markup which is not specifically table or layout oriented to be handled as a table. Numerous JavaScript library functions for date handling, timers, string manipulation, and math aid us to get exactly the results we want.
In fact, we have only lightly touched on the capabilities of the DOM and CSS-compliant browser in this application which already greatly exceeds the set of capabilities that can be achieved with XSL. | http://www.xml.com/pub/a/1999/05/xsl/xslconsidered_1.html | CC-MAIN-2017-22 | refinedweb | 3,958 | 53.21 |
Notes on Managed Debugging, ICorDebug, and random .NET stuff
I was playing around with Live Writer's (WLW) PlugIn API and am really impressed. It's clean, hassle-free, and very easy to write an PlugIn, and WLW appears to export a good set of services for plugins to consume. (Check out the WLW PlugIn gallery for plugins).
The basic gist is you just need to write a single class that derives from WindowsLive.Writer.Api.ContentSource (which is included in the LiveWriter download), and then copy it into the Plugins subdirectory under Live Writer's install.
There are more complete instructions on MSDN at.
But it gets better! The instructions there conclude with:
"7. Build your plugin and then run Windows Live Writer to test and debug."
"7. Build your plugin and then run Windows Live Writer to test and debug."
But you can do the debugging under Visual Studio and fully leverage the VS debugger, including Edit-and-Continue. Just specify Live Writer as the startup project to launch.
Specifically, under "Solution Properties : Debug : Start Action", choose "Start External program" and select WindowsLiveWriter.exe (probably "C:\Program Files\Windows Live Writer\WindowsLiveWriter.exe").
Now if you F5, LiveWriter spins up and loads your extension.
And then you can debug your extension once WLW invokes it, and you can even use Edit-and-Continue to develop and debug your PlugIn.
Note this is the same technique that I mentioned for debugging PowerShell cmdlets under the VS IDE. (see that entry for a screenshot of where the "Start External Program" option is.)
An example:
You can literally write a 20 line plug-in. Here's a really lame example that converts all URLs to uppercase when you paste them into WLW.
using System;
using WindowsLive.Writer.Api;
namespace MyLiveWriterExt
{
// Plugin to take all URLs and convert them to all uppercase.
[WriterPluginAttribute("{5dc7327d-6a8e-4609-aec0-719cb5db79e8}", "Dummy Plugin", PublisherUrl="")]
[UrlContentSource("http://*")]
public class MyExt : ContentSource
{
public override void CreateContentFromUrl(string url, ref string title, ref string newContent)
{
newContent = url.ToUpper();
}
}
}
This also makes me think about Mdbg's (C# command line debugger) plug-in model, and WLW's is definitely cleaner.
So the Live Writer Plugin model is so cool and easy that I had to write a plugin. (and do it with Edit-and-Continue
Here's a WiX install script to build an MSI to install a Windows Live Writer (WLW) plugin dll, by
The first version of Windows Live Writer is now available. I've been using the betas for a long time,
The first version of Windows Live Writer is now available. I've been using the betas for a long time | http://blogs.msdn.com/jmstall/archive/2007/07/26/developing-live-writer-plugins-with-edit-and-continue.aspx | crawl-002 | refinedweb | 446 | 65.62 |
Upside Up
May 27, 2011
[…] today’s Programming Praxis exercise, our task is to write a function to determine if a number remains the […]
My Haskell solution (see for a version with comments):
My Python solution:
I went through at least 3 different versions of
is_upside_up, making my solution less complicated each time; the first version was an imperative-style mess!
My Try in REXX
/*
First No. > 1691 = 1881
there are 12 upside up numbers between 1 and 10000
*/
and the Swap-Routine
Sorry, copied confusing tries, this should be it:
My solution is pretty similar to Graham’s:
An inelegant solution to show them all for validation:
print [i for i in range(10000) if set(str(i)).issubset(‘01689’) and str(i)[::-1].replace(‘6′,’x’).replace(‘9′,’6’).replace(‘x’,’9′)==str(i)]
;;; Common Lisp:
;; 5 and 2 are clearly symetrical, as any 2¢ pocket calculator will
;; show you:
;;
;; _ _
;; |_ _|
;; _| |_
;;
;; But since the concensus seems to be to ignore them:
(defparameter *symetric-digits*
#((#\0) (#\1) () () () () (#\9) () (#\8) (#\6))
“A vector indexed by digits, containing lists of symetrical digits.”)
(defun upside-down-digit-p (a b)
(member a (aref *symetric-digits* (digit-char-p b))))
(defun upside-down-number-p (n &optional (base 10.))
(loop
:with digits = (format nil “~VR” base n)
:with last-index = (1- (length digits))
:for i :from 0 :to (truncate (length digits) 2)
:always (upside-down-digit-p (aref digits i) (aref digits (- last-index i)))))
(defun programming-praxis-2011-05-27 ()
(loop
:with first-upside-down = nil
:with count = 0
:for n :from 1962 :below 10000
:do (when (upside-down-number-p n)
(unless first-upside-down
(setf first-upside-down n))
(incf count))
:finally (return (values first-upside-down count))))
(programming-praxis-2011-05-27)
–> 6009
15
Cheating a bit by looking at the Python programs, but here’s one in Ruby …
Another variant using python:
[…] 출처: […]
Factor Programming language
( scratchpad ) 10000 iota [ upside-up? ] filter length .
39
For grins, here’s a Erlang implementation. I’m new to Erlang, so I’m sure there are other, better, ways to do it.
I don’t understand why, sometimes, even though submission went good, the comment won’t show up…
;; Scheme
(define (upside-char=? x y)
(let ((yy (assoc x
'((#\0 #\0) (#\1 #\1) (#\2 #\5) (#\5 #\2) (#\6 #\9)
(#\8 #\8) (#\2 #\5)))))
(and yy (char=? y (cadr yy)))))
;
(define (upside-down? n)
(let* ((s (number->string n))
(l (string-length s)))
(let loop ((i 0) (j (1- l)))
(if (< i j)
(and
(upside-char=? (string-ref s i)
(string-ref s j))
(loop (1+ i) (1- j)))
(or (and (member (string-ref s i) '(#\0 #\1 #\8)) #t)
(> i j))))))
I went with building upside up numbers instead of looping 10,000 times and checking each one
//C# Solution.
for (int i = 1961; i x == ‘1’ ||x == ‘6’ || x == ‘8’ ||x == ‘9’ ||x == ‘0’);
foreach (var item in j)
{
topupNo += item;
}
if (topupNo == i.ToString())
{
Console.WriteLine(i.ToString());
}
}
//C# Solution
. for (int i = 1961; i <= 10000; i++) {
string topupNo = string.Empty; var j = i.ToString().Replace("6", "T").Replace("9",
"6").Replace("T", "9").Reverse().Where(x => x == '1' ||x == '6' || x == '8' ||x
== '9' ||x == '0');
foreach (var item in j) { topupNo += item; }
if (topupNo == i.ToString()) { Console.WriteLine(i.ToString()); } }
Just cause there isn’t a version in Go yet.. It’s simple, but gets the job done: | https://programmingpraxis.com/2011/05/27/upside-up/?like=1&source=post_flair&_wpnonce=019c5482d9 | CC-MAIN-2017-39 | refinedweb | 575 | 56.59 |
Design Patterns • Posted 6 months ago
Nulls are one of the most common occurences when developing application logic, or when dealing with entities which can have a possibility of having no referenced value. A Null Object implies to no referenced value or a neutral behaviour. While this is no uncommon, but direct references to null objects can result in "code leakage" or "broken ends", where our application program might have a chance to break. A NullObject Pattern is one of the many design patterns which specifically explains about avoiding such situations.
Why direct usage of Nulls can be harmful:
Let's take our example of ReaderFactory class demonstrated while understanding how a Factory pattern works:(); } return reader; } }
The method Create() returns a reference of type IReader derived by many sub types basing on an input selection constraint. Now if we observe, there is an elseif ladder without a possible else statement for the same. Let's put it this way, if there is a scenario wherein the passed input is not matched by any of the if conditions, the return value of reader will be a NULL. Now that's not harmful if we just look at it at this level. Let's look at the client (the caller) implementation where the ReaderFactory method is invoked.
[Route("{tierId}")] public IEnumerable<Reader> Read(int tierId) { var reader = factory.Create(tierId); return reader.ReadContent(); }
At this level, the reader variable has no idea of what is returned by the method Create() of the ReaderFactory when the passed input parameter tierId has no matching condition branch. The resultant would be a NULL and the code breaks here leaving a NullReference Exception. Now this can be avoided by a NULL check at this point, such as below:
[Route("{tierId}")] public IEnumerable<Reader> Read(int tierId) { var reader = factory.Create(tierId); if(reader != null) return reader.ReadContent(); return new List<Reader>(); }
Well this approach is what most of the developers do everyday, but this is not so elegant plus the method Read() is doing a job for which it is not responsible: a violation of the Single Responsibility Principle. Also, the if condition reader != null is against the Liskov Substitution Principle which implies that reader can be compared to against only a suitable type of IReader rather than a NULL which has no meaning.
"We try to encapsulate the absence of an object reference by providing an alternative which offers a suitable default behavior as expected."
The Null Alternative:
Getting back to the above scenario, a simple solution would be to entrust this NULL check activity to the class which is responsible for its instantiation: the ReaderFactory. Let there be a NULL implementation for the base type IReader, and when a NULL scenario occurs, let that implementation act with a suitable action which is expected.
// NoReader is an implementation of IReader // which comes into play when there's a need to use Null public class NoReader : IReader { public IEnumerable<Reader> ReadContent() { return new List<Reader>(); } }
Now the ReaderFactory class can be altered to have an else statement which returns an instance of NoReader when no matching Reader condition branch is found.(); } else { return new NoReader(); } return reader; } }
The ReaderController.Read() method, which is the actual client in this case, is now free of having a Null check and can be simply unvary of the object returned. '
[Route("{tierId}")] public IEnumerable<Reader> Read(int tierId) { IReader reader = factory.Create(tierId); return reader.ReadContent(); }
In this way we can avoid Null object checks and code leakage in our application logic by using a simple NullObject pattern.
Published 6 months ago | https://referbruv.com/blog/posts/exploring-design-patterns-using-nullobject-pattern-in-aspnet-core | CC-MAIN-2020-24 | refinedweb | 603 | 50.67 |
I have a hand full of folders that are showing up tombstoned.
When I run the DFSR Health report I see messages like this:
The DFS Replication service stopped replication on replicated folder xxxxxx at local path xxxxx due to Error ID: 9098 (A tombstoned content set deletion has been scheduled). Event ID: 4004
Is there a way to turn off the tombstone?
No data has been replicated for these folders so only the parent has the data.
I have other folders that are working so I cant just rebuild the DB as most postings suggest.
Thank you,
Adam
9 Replies
If I rebuild the DB then my other already replicated folders will start fresh too right?
And probably zap data.
So I would need to move data out let it rebuilt and sync again, that will set me back weeks.
I can't believe there is not a way to remove the tombstone tag from a set of folders so I don't need to start fresh again.
I restarted all my DFS replication folders just 2 weeks ago I don't want to do that again if possible to avoid.
The way I got around it was Stopping DFS and to remove the DFS folder from the hidden System Volume Information folder.
Let it rebuild the re-add the folders.
That seemed to do it but I could not find a way to clear just the tag on those folders.
I did have to keep an eye on the working folders and in some cases pull data back form the shadow copies.
Not the cleanest way but the only method I could find.
Adam-MKS, Your steps worked for me.
Here are the expanded steps:
Please have a backup of the data before you do this!
Stop DFS Replication Services
Unhide and grant yourself access to the C:\System Volume Information folder
Open a command prompt with elevated privileges.
Change to the System Volume Information directory
Run the following command RMDIR DFSR /S
Choose yes if you are sure to continue.
Once done (this could take several minutes), restart DFS Replication Services
To monitoring DFS Folders, open command prompt with elevated privileges and type: wmic /namespace:\\root\microsoftdfs path dfsrreplicatedfolderinfo get replicatedfoldername,state
Use Event viewer to review other DFS events
You are not alone in thinking this sometimes... Cheers, Rob.You are not alone in thinking this sometimes... Cheers, Rob.
Do you delete the DFSR database from all nodes or just the one reporting the tombstone error?
Thanks, Rob.
A tip here for step 6 - RMDIR DFSR /S - due to Windows (*still*) having path length limitations, this command can fail with long paths. PowerShell won't help you either. Help comes from an unexpected source of the open-source 7-Zip program. Whilst you'd normally associate this with archiving, it also comes with a file manager (7-Zip file manager) which can handle long paths. It'll be using the Windows APIs that can handle long paths. Launch it as administrator and then shift right-click to delete the DFSR folder. | https://community.spiceworks.com/topic/569594-dfsr-tombstoned-folder-s | CC-MAIN-2018-51 | refinedweb | 515 | 70.33 |
Options
-
- Mark Topic as New
- Mark Topic as Read
-
- Float this Topic for Current User
- Bookmark
- Subscribe
-
- Printer Friendly Page
Problem with constants
Problem with constants
2014-09-17 04:50 PM
I have created a workflow that creates shares and sets permissions. As part of that workflow, I have to generate (or find) names using a naming standard. The standard for a vfiler, for example, looks something like this "vfamitusen01" and it decodes something like this:
vf = vfiler, am = Americas region, it = IT department, us = User Share, en = Engineering environment, 01 = sequence number
the workflow has two modes of operation. One in which the user supplies a specific vfiler and volume where the new share will be created, and one in which the location is derived from inputs of the various components that go into the name.
In order to provide friendly names to the users while using a 2-char code in the name, I have some constants that look like
environmentMap = [ 'Engineering' : 'en', 'Production' : 'pr', 'Disaster Recovery' : 'dr' ]
regionMap = [ 'Americas' : 'am', 'EMEA' : 'em', 'APAC' : 'ap' ]
and so on...
I have another constant defined as:
vfilerName = if ( $workflowMethod == 'Specified' ) { return ($INPUT_VfilerName } else { return 'vf' + regionMap[$region] + businessUnitMap[$bu] + useCaseMap[$useCase] + environmentMap[$env] )}
This way, in my commands, I only have to specify the vfilerName constant and it will work regardless which mode of operation the user selected.
My commands are: NoOp (to find the vfiler, volume and array), a couple custom commands to fail if certain conditions aren't met, create qtree, create share, set ACL, remove ACL. A second row is added that has only one command to set a second ACL on the share.
When I preview my workflow in "Specified" mode, everything works as expected. When I preview my workflow in "Derived" mode, the entire first row runs green. On the second row, the last command, the preview fails with a message of 'Illegal expression: useCaseMap'. Note that the use case map constant is not used in the command where the failure is reported. It is only used to generate the volume and vfiler names for the finders in the very first command - the null op command which worked. When I review the logs, the vfiler and volume names are correct. vfilerName constant was evaluated correctly and did what I expected. It's almost as if the failure is taking place after everything else is done. The worst part is, I had this working properly but forgot to save, walked away and WFA timed out losing my work. When I reconnected to the server and re-created it, now I get this error. I've tried a bunch of things to get this working and am at my wits end. I've even gone so far as to hard code one of the two-character values in place of the useCaseMap[$useCase] bit and when I did that, it started complaining about the regionMap instead. Still evaluated properly, still built a correct vfiler name, but now it's complaining about one of the other values in the list and reporting a failure at the end of the workflow.
Honestly, I can't think of anything else I can do here. Can anybody help me with this? Why does WFA interpret the MVEL correctly, populate the constant with the correct values, execute the commands successfully, then right at the end of the workflow fail with this error?
I have attached the server and finder logs and the .dar file in hopes that somebody can spot the problem. Any help would be truly appreciated.
Reply
View By:
10 REPLIES
Thanks for sharing the .dar file.
We will need a backup to look into the issue since it happens during the preview.
I think a case has been raised with NetApp. If the backup is already a part of
the case, then please ignore, else can you please provide the backup.
Regards
Abhi
Re: Problem with constants
Re: Problem with constants
2014-09-30 12:32 PM
I have attached a backup to the case.
Thanks. We will analyze and respond back as soon as possible.
Hi,
You have a couple of syntax errors in your constant values:
volumeName: if ( $workflowMethod == 'Specified' ) { return ($INPUT_Volume ) } else { return 'v' + regionMap[$region] + businessUnitMap[$bu] + useCaseMap[$useCase] }
You seem to have missed a close paranthesis after "($INPUT_Volume"
I have inserted the missing close parenthesis in red.
Same applies to the constant: vfilerName
Can you check again and let me know. I will wait for your response to continue further investigation.
-Anil
Re: Problem with constants
Re: Problem with constants
2014-09-30 12:43 PM
I saw the missed parenthesis right after I posted. I posted after making a bunch of edits trying different punctuation and syntax. I tried:
- With parenthesis
if ($workflowMethod == 'Specified') { return($INPUT_Volume) } else { return('v' + regionMap[$region] + businessUnitMap[$bu] + useCaseMap[$useCase]) }
- Without parenthesis
if ($workflowMethod == 'Specified') { return $INPUT_Volume } else { return 'v' + regionMap[$region] + businessUnitMap[$bu] + useCaseMap[$useCase] }
- Using the ternary operator
$workflowMethod == 'Specified' ? $INPUT_Volume : 'v' + regionMap[$region] + businessUnitMap[$bu] + useCaseMap[$useCase]
Each of these had the same behavior. All the commands in the workflow preview green except the last one, then at the end I get that error message.
I even added a third row so that I could add a null-op at the end as the last command. The command that had failed before then completed and the failure moved to the new null-op. The failure is always on the last command regardless what that command is, regardless if it uses the value from the constant or not. That's got me wondering if it may be something internal to WFA rather than the workflow itself.
This is being actively worked upon.
Expect a reply soon from our side.
Regards
Abhi
Hi,
When a workflow is planned, it happens in various stages:
- Each of the command instances are evaluated
- Return parameters are evaluated
- Workflow constants are also registered in the internal workflow planning result.
During the planning of the attached workflow, it seems to have hit two issues in workflow constants i.e last step above:
a. Maps in constants are not getting evaluated correctly. Please refer to bug #770193 for the case that you have raised.
b. When there is a failure in resolution of the workflow constant, the error is always displayed on the last command, though that is not the location of the error. Please refer to bug #732015 for the case registered with NetApp support.
Though not ideal, instead of using maps, as a workaround I tried using functions for the five maps you had. It seems to work for the "derived" case. I did not try the "specified" case however.
Steps tried out were:
1.. Define 5 functions as follows:
def useCaseMap(useCase) {
return [ "Home": "hd", "User'": "us", "test" : "ts" ].get(useCase);
});
}
def businessUnitMap(businessUnit) {
return ['IT' : 'it', 'IB' : 'ib', 'HR' : 'hr', 'GC' : 'gc', 'CF' : 'cf', 'CFO' : 'co', 'PB' : 'pb', 'Risk' : 'rx'].get(businessunit);
}
def environmentMap(env) {
return ['Production' : 'pr', 'Disaster Recovery' : 'dr', 'UAT' : 'ua', 'Engineering' : 'en'].get(env);
}
2. Changed the value of constants for volumeName and vfilerName as)) }
3. Remove the 5 maps from WorkflowConstants tab
4. Now, try planning for derived case.
Please try the above and let us know if it works out.
Hope this helps.
Others might respond if there is an easier workaround, since you said that it was working once.
Thanks,
Shailaja
Thank you for the workaround. I'll await the customer's feedback.
Can we get public reports for BURTS 732015 and 770193 please?
Customer has no visibility into these right now.
Thanks,
Chris Pozezanac
Technical Account Manager - Credit Suisse
NetApp
Reply | https://community.netapp.com/t5/OnCommand-Storage-Management-Software-Discussions/Problem-with-constants/td-p/13864 | CC-MAIN-2018-47 | refinedweb | 1,280 | 62.58 |
13 May 2016 3 comments Python, Linux, MacOSX
Did you see my blog post about Decorated Concurrency - Python multiprocessing made really really easy? If not, fear not. There, I'm demonstrating how I take a task of creating 100 thumbnails from a large JPG. First in serial, then concurrently, with a library called deco. The total time to get through the work massively reduces when you do it concurrently. No surprise. But what's interesting is that each individual task takes a lot longer. Instead of 0.29 seconds per image it took 0.65 seconds per image (...inside each dedicated processor).
The simple explanation, even from a layman like myself, must be that when doing so much more, concurrently, the whole operating system struggles to keep up with other little subtle tasks.
With
deco you can either let Python's
multiprocessing just use as many CPUs as your computer has (8 in the case of my Macbook Pro) or you can manually set it. E.g.
@concurrent(processes=5) would spread the work across a max of 5 CPUs.
So, I ran my little experiment again for every number from 1 to 8 and plotted the results:
The blue bars is the time it takes, in total, from starting the program till the program ends. The lower the better.
The red bars is the time it takes, in total, to complete each individual task.
Meaning, when the number of CPUs is low you have to wait longer for all the work to finish and when the number of CPUs is high the computer needs more time to finish its work. This is an insight into over-use of operating system resources.
If the work is much much more demanding than this experiment (the JPG is only 3.3Mb and one thumbnail only takes 0.3 seconds to make) you might have a red bar on the far right that is too expensive for your server. Or worse, it might break things so that everything stops.
Choose wisely. Be aware how "bound" the task is.
Also, remember that if the work of each individual task is too "light", the overhead of messing with multprocessing might actually cost more than it's worth.
Here's the messy code I used:
import time from PIL import Image from deco import concurrent, synchronized import sys processes = int(sys.argv[1]) assert processes >= 1 assert processes <= 8 @concurrent(processes=processes)())
I just wanted to verify that the experiment is valid that proves that CPU bound work hogs resources acorss CPUs that affects their individual performance.
Let's try to the similar but totally different workload of a Network bound task. This time, instead of resizing JPEGs, it waits for finishing HTTP GET requests.
So clearly it makes sense. The individual work withing each process is not generally slowed down much. A tiny bit, but not much. Also, I like the smoothness of the curve of the blue bars going from left to right. You can clearly see that it's reverse logarithmic.
Follow @peterbe on Twitter
Using a dict -specialty passing it around- to do the timing bookkeeping can be costly. Possibly that has more effect on the graphs than expected.
Returning the time (as int) and storing it in run function- even in the dict- can speed. And give more objective results.
Does your MacBook have 4 cores with hyperthreading? If so that explains why the effect peters out at 4 processes. If the task is CPU-bound then hyperthreading generally does not offer a big performance boost.
I don't know. It's just a standard Macbook Pro. | https://www-origin.peterbe.com/plog/time-to-do-concurrent-cpu-bound-work | CC-MAIN-2021-04 | refinedweb | 606 | 65.83 |
vPN Network on a cyberghost vpn free premium Windows 10 Computer. Let us take a look at How to. Windows 10 makes it really easy to setup and use VPN Network on your computer. Setup VPN Connection in Windows 10 and How to Connect to.but when we checked our IP address using cyberghost vpn free premium ipMagnet, the results showed signs of potential IP leakage. For our testing, however, we connected to their server in Hong Kong. Our expectations went down the drain when tested it for torrenting.
Cyberghost vpn free premium
breast high. Anchor: #i1009747 parapet A parapet is a wall cyberghost vpn free premium or rampart,the configuration refers to cyberghost vpn free premium a file: /etc/openvpn/auth,
you can contact the support team via email or chat and vpn ssl encryption their response time is pretty fast. If youd like NordVPN to add more features to their software, if you cant find the information cyberghost vpn free premium youre looking for on the website,
Jotunheim, Used PIA for a month and I loved it. The experience was mostly positive with the rare speed hiccups. The client is stupid easy to use as well, both on my PC and Nexus 7. I will buy an 1-yr subscription soon. amarshonarbangla, m.
Autodesk AutoCAD 2013 Full Free Full Version 32 bit 64 bit Sharing World By Sudhir Mishra..
Cyberghost vpn free premium in USA and United Kingdom!
bT Internet Connect gives you: Reduced management complexity We manage every component of all your Internet connections. BT main site. You can remove the headaches of dealing with multiple suppliers in different locations. Improved customer cyberghost vpn free premium experience BT Internet Connect is tuned for performance.alerte nous disant quune configuration est requise afin que le VPN soit oprationnel. Cration d un VPN sous Windows Server 2012 R2.
our healthy living l2tp free vpn and aging philosophy is simple - eat well-balanced meals that include multiple servings of foods high in fiber, exercise regularly and incorporate a nutritional regimen cyberghost vpn free premium that addresses aging at the root of the problem, and bran, vegetables, like fruits, waiora is a world-class company dedicated to helping people maintain their health as they age.
.
you can even pay anonymously using Bitcoin! There is a 7 day money back guarantee if you want to try it out. Also, there are a lot of VPN services out there. Pretty cheap for some cyberghost vpn free premium peace-of-mind privacy.proxifier - The Most Advanced Proxy Client. Key Features Master cyberghost vpn free premium Your Corporate Network Control access to resources. Proxifier allows network applications that do not support working through proxy servers to operate through a SOCKS or HTTPS proxy and chains.
import the.ovpn file in your VPN cyberghost vpn free premium client and change the ip to the local ip of your Raspberry PI. Depending on your network configuration it may be of the form192.168.pPTP, pricing NordVPN has three subscription plans. And OpenVPN. Multiple protocols are available, including. IKEv2/IPsec, l2TP/IPSec, additionally, nord offers users cyberghost vpn free premium an ad-block feature called CyberSec that blocks dangerous websites and allows users to block annoying ads.
a park road (PW)) includes parking lots, etc is not on the state highway system cyberghost vpn free premium and is operated by the Texas Parks and Wild Department and is maintained by TxDOT. Paved proxy list 60000 camping pads,loading.
Vpn service overview!
improved performance with a cyberghost vpn free premium large number of domains. 22 November 2018 Extension Updates Domain Connect.openVPN and the L2TP protocol. This VPN service provider supports the three most significant protocols, the VPN service provider comes with 125 servers in more than 44 countries. GhostPath cyberghost vpn free premium also has more than 4000 IP addresses across the globe. Namely; PPTP, currently,
bitcoin, apple TV, pS3, nOW TV Box, xbox 360, credit Card, view all Offers Supported Devices Android, windows, smart TV, samsung cyberghost vpn free premium Smart TV, pS Vita, mac OS X, iOS, roku, xbox One, money Back Guarantee 15 days Moneyback Guarantee Payment Methods Paypal, pS 4,human Resources Manual Anchor: #i1009863 partial access Partial access means only a portion of a property's total cyberghost vpn free premium frontage has access to a given road, subject to police power restrictions.
we faced a problem. Straightway, to cyberghost vpn free premium test if the service was any good in securing ones privacy while torrenting, we put it to the test. After several attempts, the connections were highly unstable. Would disconnect immediately upon connecting to any server.
excellent proxy switcher add -on Category: Encryption Version: (Mozilla cyberghost vpn free premium Firefox )) Works under: Windows 8.1 / Windows NT / Windows 2000 / Windows 7 / Windows 2003 / Windows Vista / Windows XP / Windows 8.you need to cyberghost vpn free premium provide an email address. Cons Far too many countries aren't supported by this software. Proxies are easy to switch between. Blocked site viewing is a delight and a relief for those in some countries. In order to private browse,
this record for internal l ip address applications will not be announced. Statistics and analysis of cyberghost vpn free premium collected questionnaires, in addition to internal research, statistics or descriptive text of the results will be provided for accurate service. | http://babyonboard.in/the-secret-weapon-to-boost-your-kids-brain-power/cyberghost-vpn-free-premium.html | CC-MAIN-2019-22 | refinedweb | 895 | 55.44 |
In this question you have to write a program consisting of two functions. A string has to be input in the main
function and then a string function, namely shorterString, has to be called to shorten the string by deleting
(“erasing”) every third character of the string. This has to be done repeatedly until the length of the string becomes
less than 6 and then the final string should be displayed by the main function. No global variables may be used.
Suppose, for example, the string
Hello world!
is input. Then
Helowold
should be returned to the main function by shorterString. Then, when the function is called again, the string
Heowld
should be returned. Then, when the function is called again, the string
Hewl
should be returned. This will be the final result (because its length is less than 6) and should be displayed.
Repeat the whole process described above for a number of strings until the string END is input. Use loops as
required. Run your program on the strings below and submit printouts of the program and output.
Cheers!
String manipulation is really not difficult.
Only two questions remain to be done.
Below is my code - but cannot get it to remove every 3rd character in a string - Help Please
using namespace std; void shorterstring(string text) { for(int i =0; i <=0; i++) {text.erase(3,1); } cout<<text<<endl; } int main() { string sentence; cout << " Enter sentence: "; getline(cin,sentence,'\n'); shorterstring(sentence); return 0; } | https://www.daniweb.com/programming/software-development/threads/82493/help-please-with-string-manipulation | CC-MAIN-2017-51 | refinedweb | 248 | 73.37 |
am am trying to write a program that requires me hitting a https web link. However, I can't seem to get it to work. The program works fine when dealing with http sites, however, when I try it with a https site I get
socket.gaierror: [Errno 11001] getaddrinfo failed
It seems like it has something to do with the ssl not working, however, I do have the ssl.py in the python library and I have no problem importing it.
My code is below. Any help would be greatly appreciated.
import urllib.request
auth = urllib.request.HTTPSHandler()
proxy = urllib.request.ProxyHandler({'http':'my proxy'})
opener = urllib.request.build_opener(proxy, auth)
f = opener.open('') | https://www.queryhome.com/tech/77226/error-of-drawing-map-from-shape-file-in-python-3-2-basemap | CC-MAIN-2020-16 | refinedweb | 115 | 62.14 |
Pypolars is an alternative to the Pandas library in Python which is used for working with data while working on a data science task. We use Pandas from reading a dataset to preparing the dataset for a machine learning model. Just like Pandas, Pypolars is another great library that can be used while working with data as it contains most of the functions provided by the Pandas library. In this article, I will introduce you to a tutorial on Pypolars Library in Python.
What is Pypolars in Python?
Pypolars is an alternative to the Pandas library in Python. Without a doubt, the Pandas library is an amazing Python library that we use when working with data. If you come from a non-coding background, you might find Pandas very easy to use because it looks a lot like SQL. It has long been used for working with data. From reading a dataset to analyzing the data, everything can be done using Pandas. So why Pypolars?
Pypolars is just an alternative to the Pandas library in Python. You can use it in almost all the tasks which can be done using Pandas. The best feature about this library is that it is very efficient in terms of memory. So in any case in the future, the industry decided to switch to Pypolars for efficient memory management then you don’t need to worry as this library contains most of the functions in Pandas which works the same way. In the section below, I will take you through a tutorial on the Pypolars library in Python.
Pypolars using Python (Tutorial)
I hope you now know what is Pypolars in Python. In short, it is an alternative to the Pandas library which is more efficient in terms of memory. Now let’s see how to work with this library in Python. If you have never used it before then you can easily install it by using the pip command; pip install py-polars. I will first start by creating a DataFrame:
import pypolars as pl data = pl.DataFrame({"Name" : ["Aman", "Hritika", "Raj", "Simran", "Rahul", "Neha"], "Age" : [22, 21, 25, 23, 30, 27]}) data.head()
The only difference between a DataFrame created using Pandas and Pypolars is that the Pypolars DataFrame shows a datatype of columns at the top before the first row where a Pandas DataFrame lacks this feature. The other feature where I think Pandas is better is that in the above DataFrame you can see the string values in ” ” which looks very Pythonic and generally it doesn’t look good while working with a large dataset.
Now let’s see how to read a dataset with this library:
data = pl.read_csv("class_grades.csv") data.head()
So reading the dataset is very similar in both the libraries. You can also convert the above DataFrame to a Pandas DataFrame by using the code below:
df = data.to_pandas() df.head()
Also, Read – Python Projects with Source Code.
Summary
The Pypolars library is a great alternative to the Pandas library in Python if you want to save memory while working with a large dataset, but still, it lacks some features as compared to the Pandas library in Python. I hope you liked this article on a tutorial on the Pypolars library in Python. Feel free to ask your valuable questions in the comments section below. | https://thecleverprogrammer.com/2021/03/31/pypolars-in-python-tutorial/ | CC-MAIN-2021-43 | refinedweb | 560 | 70.53 |
Core. I hope this will be helpful for both of us. It's also beneficial to practice some programming interview questions because in almost all Java interview, there is at-least 1 or 2 coding questions appear. Please share answers for unanswered Java interview questions and let us know how good these Java interview questions are?
These Java interview questions are mix of easy, tough and tricky Java questions e.g. Why multiple inheritance is not supported in Java is one of the tricky question in java. Most questions are asked on Senior and experienced level i.e. 3, 4, 5 or 6 years of Java experience e.g. How HashMap works in Java, which is most popular on experienced Java interviews. By the way recently I was looking at answers and comments made on Java interview questions given in this post and I found some of them quite useful to include into main post to benefit all. By, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.
6. Where does. See How HashMap works in Java for detailed explanation.
7..
8. What is difference between Executor.submit() and Executer.execute() method ?
This Java interview question is from my list of Top 15 Java multi-threading question answers, Its getting popular day by day because of huge demand of Java developer with good concurrency skill. Answer of this Java interview question is that former returns an object of Future which can be used to find result from worker thread)
By the way @vinit Saini suggested a very good point related to this core Java interview question.
9. What is the difference between factory and abstract factory pattern?
This Java interview question is from my list of 20 Java design pattern interview question and its open for all of you to answer.@Raj suggested.
10..
11. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interview questions on Singleton Pattern in Java for more details and questions answers
12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop..
19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Moh amount of processing
65 comments :
all answers related to singletons in Java seem to ignore the "double-checked locking is broken" problem; it is best to initialize the single instance in the class initializer.
private final SingletonClass INSTANCE = new SingletonClass();
Thanks Job good to know that these java interview questions are useful for you.
Thanks a lot Anonymous for informing us about subtle details about Substring() method , I guess Interviewer was looking for that information in his question "How does substring () inside String works?" because if substring also shares same byte array then its something to be aware of.
Hi Scott,
your solution is correct but with the advent of java 5 and now guarantee of volatile keyword and change in Java memory model guarantees that double checking of singleton will work. another solution is to use Enum Singeton. you can check my post about Singleton here Singleton Pattern in Java
Hi Anand,
Thanks for answering question "How does substring () inside String works?"
Use can use a static holder to handle the singleton creation instead of double checked mechanism.
public class A {
private static class Holder
{
public static A singleton = new A();
}
public static A getInstance()
{
return Holder.singleton;
}
Stored Procedure Error: One way to signal an error is from what is returned.
Factory/Abstract Factory:.
I only see 18 questions and most of them are answered wrong or not at all....
Also, your english is terrible.
Question3 Awnser::::::::
String s = "Test";
Will first look for the String "Test" in the string constant pool. If found s will be made to refer to the found object. If not found, a new String object is created, added to the pool and s is made to refer to the newly created object.
String s = new String("Test");
Will first create a new string object and make s refer to it. Additionally an entry for string "Test" is made in the string constant pool, if its not already there.
So assuming string "Test" is not in the pool, the first declaration will create one object while the second will create two objects.
@Kamal, I don't think
String s = new String("Test");
will put the object in String pool , it it does then why do one need String.intern() method which is used to put Strings into String pool explicitly. its only when you create String objec t as String literal e.g. String s = "Test" it put the String in pool.
Keep up the good work, and a small suggestion,
wrap your code snippets in <pre class="brush: csharp"> code snippet goes here </pre>
it makes your code snippets more readable.
Abstract Factory vs Factory(Factory method)
AF is used to create a GROUP of logically RELATED objects, AF implemented using FM.
Factory just create one of the subclass.
As I remember in GoF:
AF could create widgets for different types of UI (buttons, windows, labels), but we could have windows, unix etc. UI types, created objects are related by domain.
If you want to know the top 50 interview questions in banking plus get word-by-word answers to tough banking interview questions like “Why do you want to do investment banking?”, then check out the Free Tutorials at [www] insideinvesmentbanking [dot] com. It’s a really useful site and it’s made by bankers who know the interview room inside out. PS full disclosure, I am actually a current student of IIB and I do receive help with recruiting (eg mock interview) in exchange for letting other students know about the Free Tutorials.
These Java interview question are equally beneficial for 2 years experience or beginners, 4 years experience Java developers (intermediate) and more than 6 years experience of Java developer i.e. Advanced level. Most of the questions comes under 2 to 4 years but some of them are good for 6 years experience guy as well like questions related to executor framework.
I agree most of these java interview questions asked during experienced developers and senior developers level. though some questions are also good for beginners in Java but most of them are for senior developers in java
Another popular Java interview question is why Java does not support multiple inheritance, passing reference, or operator overloading, can you please provide answers for those questions. these java interview questions are little tough to me.
..after more than 2.5 year break in my software career, your blog refreshed most of my java knowledge..thank u so much..i want u to write more n more for beginners n people like me..all the best
Hi I am looking for some real tough Java interview question which explores some advanced concept and make sense. if you know real tough, challenging and advanced Java interview questions than please post here.
Hi, I am looking for Java interview questions from Investment banks like Nomura, JPMorgan, Morgan Stanly, Goldman Sachs, UBS, Bank of America or Merrylynch etc. If you have Java questions asked in Nomura or any of these banks please share.
Can any one please share core java interview questions from morgan stanley , JP Morgan Chase , Nomura, RBS and Bank of America for experienced professionals of 6 to 7 years experience ? I heard that they mostly asked Garbage Collection, Generics, Design and profiling related questions to senior candidate but some real questions from those companies will really help.
Hi Javarevisited, looking core java interview questions and answers for experienced in pdf format so that I can use if offline, Can you please help to convert these Java questions in pdf ?
@Vineet, few Java programming questions asked in google :
1) Difference between Hashtable and HashMap?
2) difference between final, finalize and finaly?
3) write LRU cache in Java ?
let me know if you get more Java questions from google.
Javin
For question 7 -we usually handle the exception and divert the user to a standard error page with the exception trace as a page variable. The user will have an option to email the support team through a button click and the error trace gets sent to support. This way we can know what went wrong in the application and fix it.
Typically these kind of errors are due to poor data error handling in stored procedure like a missed null check or a char variable of incorrect size etc which are exposed only when I consistent data flows into the app which was never tested during development or uat.
Anand
@Anand, you bring an important point. size and value of variables are major cause of error in Stored procedure and if not handle correctly may break Java application. I guess purpose of that java interview question is to check whether you verify inputs in Java or not before passing to Stored procedure and similarly when you receive response. Thanks for your comment mate.
Javin
1.When we create string with new () it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
2.String s = new String("Test");
will put the object in String pool , it it does then why do one need String.intern() method which is used to put Strings into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" it put the String in pool.
The above 1 & 2 Stmts are contradicting... when it will in pool and when it will be in heap?
...aad here's some more:
+1
0
vote
Answer #1
Hey!
I’ll try to give you some examples, differentiated by the level of the candidate applying:
**UPDATE**: If you are a junior java developer or an aspiring one, I strongly recommend you to take first the OCJP certification before going to an interview. This can increase your chances to succes big time, as well as your entry salary – proven and tested by myself! :)
1) Junior java developer
a) Basic ocjp (former scjp) questions:
– What does static, final mean, purposes;
– How many accesibility modifiers exist? Please describe them.
– Why do you need a main method?
– How many constructors can you have?
– Define overwriting and overloading
– Give java API implementations for overwriting and overloading
– Describe the String class – unique properties
– StringBuilder vs StringBuffer
– Collections : please describe, give some examples and compare them to eachother
– ArrayList vs Vector
– HashMap vs HashTable
– What’s a tree
– What’s a map
– Multithreading: describe the management in java
– What’s a semaphone?
– How many states are there for threads?
– Describe the usage for synchronized word (2)
– Serialization in java – a descrition and usage
– Garbage collection in java – description and usage
– Can you guarantee the garbage collection process?
b) Simple design pattern questions:
– Singleton please describe main features and coding
– Factory please describe main features and coding
– Have you used others? please describe them
2) Intermediate and Senior level – depending on rate of good responses, additional questions to 1):
Thanks dude, most of your Java interview question is asked on Interview on Sapient, Capagemini, Morgan Stanley and Nomura.I was giving interview on HSBC last weekend and they ask me How SubString works in Java :). Infosys, TCS, CTS, Barclays Java interview questions at-least one from your blog. We were giving client side interview for UBS hongkong and they ask How HashMap works in Java, I don't have word to thank you. Please keep us posting some more tough Java interview question from 2011 and 2012 , which is recent.
Can anyone please share Java interview Question asked on Tech Mahindra, Patni, LnT Infotech and Mahindra Satyam. Urgently required, interview scheduled in two days.
Some Java programmer ask for Java questions for 2 years experience, Java questions for 4 years experience, questions for Beginners in Java, questions for experienced Java programmer etc etc. Basically all these are just short cut, you should be good on what are you doing. You automatically gain experience while working in Java and should be able to answer any Java question up-to your level.
Hi Guys, Can some one share Java interview questions from Directi, Thoughtworks, Wipro, TCS and Capegemini for experienced Java programmer 6+ years experience ?
Hi , Does Amazon or Microsoft ask questions on Java ? I am looking for some Java questions asked on Microsoft, Amazon and other technology companies, if you know please share.
You have no control over what questions get asked in job interviews. All you can do is brush up on the key fundamentals.
your questions are good but answers are not satisfactory. we know better than your answer. try to give some new answer so that someone will read with a interest..
It will be nice for others if you can update this in your blog.
Hi Ravi, where did you read that? I have never heard about String object created on both heap and pool. Object is placed into pool when you call intern method on String object.
Can you please suggest some latest Java interview questions from 2012, 2011 and what is trending now days. Questions like Iterator vs Enumeration is way older and I think latest question on Java is more on Concurrency.
Hi Javin,
String s = new String("Test"); // creates two objects and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "Test" will
be placed in the pool.
Although, questions are good, you can add lot more interview questions form Java 5, 6 and Java 7. Even lamda expression from Java 8 can be a nice question. I remember, having interview with Amazon, Google and Microsoft, there were hardly any Java question, but when I interviewed by Nomura, HeadStrong, and Citibank, there are lots of questions from Java, Generics, Enum etc. Lesson learned, always research about what kind of question asked in a company, before going to interview.
Can you please post latest Java Interview Questions from Investment banks like Citibank, Credit Suisse, Barclays, ANZ, Goldman Sachs, Morgan Stanly, CLSA, JP Morgan and some high frequency hedge funds like Millenium? I am preparing for Java interview, and looking for recent questions asked in 2012, 2013 or may be in last couple of month. If you can get question from Singapore, HongKong or London, that would be really helpful, but I don't mind question form Pune, Bangalore or Mumbai even.
Cheers
Dheeraj
Hi, for number 19 it might be better to use System.nanoTime() as currentTimeMillis may have problems with small intervals.
Surprised to See no questions from Java IO or NIO. I think, Investment banks used lot of non blocking I/O code for socket programming, connecting system with TCP/IP. In Exchange Connectivity code, I have seen lot of use ByteBuffer for reading positional protocol. I think, you should also include questions from Garbage Collection tuning, Java concurrency package, very hot at the moment.
q3. What is the difference between creating String as new() and literal?
ans is not correct bcz String x=new String("abc")-
creates two object.one is in heap memory and second is in constant string pool.
Hello, Can some one please share interview questions from ANZ Banglore and Singapore location, I need it urgently.
There is lot more difference in Java Interviews in India and other countries like USA (NewYork), UK(London), Singapore, Hongkong or any other europian counties. India is mostly about theoretical knowledge e.g difference between StringBuffer and StirngBuilder, final, finalize or finally , bla bla bla............
USA in particular is more about Code, they will give you a problem and ask you to code solution , write unit test, produce design document in limited time usually 3 to 4 hours. One of the example is coding solution for Vending Machine, CoffeMaker, ATM Machine, PortfolioManager, etc .
Trends on other countries are also more balanced towards code e.g. writing code to prevent deadlock (that's a tricky one), So be prepare accordingly.
RAJAT
Hi Javin, Can you please share some Core Java questions from Java 6 and Java 7? I heard they are asking new features introduced in Java 6 as well as Java 7. Please help
How HashMap works, this question was asked to me on Barclays Capital Java Interview question, would hae read this article before, surely helped me.
@Ravi,Garima,Javin
its regarding String creation in Pool
I tested a small code and giving results like below:
String s="Test";
String s1=new String("Test");
System.out.println(s==s1);//return false
System.out.print(s==s1.intern()); //retun true
If we go by concept that string creation adds string to pool also then first result should be true as if already same string(mean s) is present in pool then same object is returned back so s1 should point to s but the result is coming as false.
On the contrary,when we invoke intern method on s1 and then compare it returns true as it adds string to pool which is normal working of intern method.
Please correct me if I am wrong.
hi Javin, Can you please share some Citibank Java Interview questions? I have an interview with Citibank Singapore for Algorithmic trading developer position, and expecting few Java questions? Would be great if you could share some questions from Citibank, Credit Suisse, UBS or ANZ, these are my target companies. Cheers
@Anonymous, are you asking for Citigroup Java developer position or Citibank?..
----------------------.
----------------------
These questions are quite basic and only useful for freshers or beginners Java developers. I wouldn't say, you can expect this question as Senior Java developer. Everyone knows answers, there is nothing special about it. definitely not TOP questions in my opinion.
I agree with Xhotery, this questions are from 2012 and 2011 years, now it's 2013. In order to crack Java interview today, you need to focus extensively on JVM internals, deeper knowledge of Java Concurrency, sophisticated open source library and good knowledge of frameworks like Spring, Hibernate, Maven, and even bit of functional programming knowledge is required. In recent Java interviews, peoples are asking about lambdas of Java 8 and How it's going to improve performance, questions about functional interface and new date and time library. Even questions from Java 7 e?
These questions and answers are ok, but they look more suited for junior developers than senior engineers to me.
Just few quick remarks from me:
1. Immutability in Java is not that easy to achieve, as long as we have reflexion. Of course, in theory, reflexion can be disabled from a security provider. But in practice, a Java application uses several technologies that rely on reflexion (anything that does dependency injection (Spring, EJB containers etc.),. Your answer here is absolutely wrong. On one hand, if you just invoke that method for the very first time, you'll not find the net amount of time taken by method execution, but the gross amount of time including method execution plus class loading time for all classes that are referred for the first time inside that method. Second thing, by measuring that way, you completely ignore how java works: all the adaptive optimization the JIT does at runtime dramatically changes the execution time after a number of method calls. Actually, the first call of a method is the wrongest way to measure its execution time..
Reference : Effective Java second edition item 5 or 6
It will be nice for others if you can update this in your blog.
Given it's 2013, Java Interviews has changed a lot with more focus on JVM internals, Garbage Collection tuning and performance improvement. Here is a list of questions, which I have faced recently in Java interviews :
1) What is Composite design pattern?
2) Explain Liskov substitution principle ?
3) Write a Java program to convert bytes to long?
4) What is false sharing in multithreading Java?
5) Can we make an array volatile in Java? What is effect of making it volatile?
6) What is advantage and disadvantage of busy spin waiting strategy?
7) Difference between DOM and SAX parser in Java?
8) Write wait notify code for producer consumer problem?
9) Write code for thread-safe Singleton in Java?
10) What are 4 ways to iterate over Map in Java? Which one is best and why?
11) Write code to remove elements from ArrayList while iterating?
12) is Swing thread-safe?
13) What is thread local variable in Java?
14) How do you convert an String to date in Java?
15) Can we use String in switch case?
16) What is constructor chaining in Java?
17) Explain Java Heap space and Garbage collection?
18) Difference between major and minor GC?
19) Difference between -Xmx and -Xms JVM option?
20) How to check if a String contains only numeric digits?
21) Difference between poll() and remove() method of Queue in Java?
22) Difference between Comparator and Comparable in Java?
23) Why you need to override hashcode, when you override equals in Java?
24) How HashSet works internally in Java?
25) How do you print Array in Java?
All the best for your Java Interviews.
Some exercises for an interview that I had with Morgan Stanley(in 2014):
1. Explain what 'path to root' means in the context of garbage collection. What are roots?
2. Write code for a simple implementation of HashMap/Hashtable
3. Write a short program to illustrate the concept of deadlock
4. Explain why recursive implementation of QuickSort will require O(log n) of additional space
5. Explain the design pattern used in Java and .NET io stream/reader APIs.
6. Create an Iterator filtering framework: an IObjectTest interface with a single boolean test(Object o) method and an Iterator sub-class which is initialized with another Iterator and an IObjectTest instance. Your iterator will then allow iteration over the original, but skipping any objects which don't pass the test. Create a simple unit test for this framework.
Hi,
The Answer to 3. question is wrong. When creating string using new will create two copies one in heap and another in string pool. And the object reference will be initially in heap. Inorder to make the object reference to string pool we need to call intern() on the string.
First of all, thank you so much for putting this page together. It is a great starting point to refresh some concepts before going into an interview. I would also recommend that everyone study the book 'Effective Java' too. I wanted to bring up a point that JCIP discusses in Chapter 16.
"Double checked locking is an anti-pattern..." -Java Concurrency in Practice p. 213
Yes, since Java 5 we can use the volatile keyword for the instance variable and this fixes a rather fatal flaw (explained below), but the need to use this ugly anit-pattern doesn't exist when you can just synchronize the getInstance() method.
//ALL YOU NEED
public static synchronized getInstance() {
if (INSTANCE == null) {
//create instance
}
return INSTANCE;
}
"The real problem with DCL is the assumption that the worst thing that can happen when reading a shared object reference without synchronization is to erroneously see a stale value (in this case, null); in that case the DCL idiom compensates for this risk by trying again with the lock held. But the worst case is actually considerably worse - it is possible to see a current value of the reference but stale values for the object's state, meaning that the object could be seen to be in an invalid or incorrect state." -Java Threads In Practice p. 214.)
Hi all
i have an interview in RAK bank for the post java developer..if anyone know about the interview questions please help | http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html?showComment=1377571280558 | CC-MAIN-2014-42 | refinedweb | 4,086 | 63.09 |
TestNG - Writing Tests
Writing a test in TestNG basically involves the following steps:
Write the business logic of your test and insert TestNG annotations in your code.
Add the information about your test (e.g. the class name, the groups you wish to run, etc.) in a testng.xml file or in build.xml.
Run TestNG.
Here, we will see one complete example of TestNG testing using POJO class, Business logic class and a test xml, which will be run by TestNG.
Create EmployeeDetails.java in C:\>TestNG_WORKSPACE, which is a POJO class.
public class EmployeeDetails { private String name; private double monthlySalary; private int age; // @return the name public String getName() { return name; } // @param name the name to set public void setName(String name) { this.name = name; } // @return the monthlySalary public double getMonthlySalary() { return monthlySalary; } // @param monthlySalary the monthlySalary to set public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary; } // @return the age public int getAge() { return age; } // @param age the age to set public void setAge(int age) { this.age = age; } }
EmployeeDetails class is used to.
- get/set the value of employee's name.
- get/set the value of employee's monthly salary.
- get/set the value of employee's age.
Create an EmpBusinessLogic.java in C:\>TestNG_WORKSPACE, which contains business logic.
public class EmpBusinessLogic { // Calculate the yearly salary of employee public double calculateYearlySalary(EmployeeDetails employeeDetails){ double yearlySalary = 0; yearlySalary = employeeDetails.getMonthlySalary() * 12; return yearlySalary; } // Calculate the appraisal amount of employee public double calculateAppraisal(EmployeeDetails employeeDetails){ double appraisal = 0; if(employeeDetails.getMonthlySalary() < 10000){ appraisal = 500; }else{ appraisal = 1000; } return appraisal; } }
EmpBusinessLogic class is used for calculating:
- the yearly salary of employee.
- the appraisal amount of employee.
Now, let's create a TestNG class called TestEmployeeDetails.java in C:\>TestNG_WORKSPACE. A TestNG class is a Java class that contains at least one TestNG annotation. This class contains test cases to be tested. A TestNG test can be configured by @BeforeXXX and @AfterXXX annotations (we will see this in the chapter TestNG - Execution Procedure), which allows to perform some Java logic before and after a certain point.
import org.testng.Assert; import org.testng.annotations.Test; public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic(); EmployeeDetails employee = new EmployeeDetails(); @Test public void testCalculateAppriasal() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double appraisal = empBusinessLogic.calculateAppraisal(employee); Assert.assertEquals(500, appraisal, 0.0, "500"); } // Test to check yearly salary @Test public void testCalculateYearlySalary() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double salary = empBusinessLogic.calculateYearlySalary(employee); Assert.assertEquals(96000, salary, 0.0, "8000"); } }
TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It does the following:
Tests the yearly salary of the employee.
Tests the appraisal amount of the employee.
Before you can run the tests, you must configure TestNG using a special XML file, conventionally named testng.xml. The syntax for this file is very simple, and its contents are as shown below. Create this file in C:\>TestNG_WORKSPACE.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "" > <suite name="Suite1"> <test name="test1"> <classes> <class name="TestEmployeeDetails"/> </classes> </test> </suite>
Details of the above file are as follows:
A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag.
Tag <test> represents one test and can contain one or more TestNG classes.
<class> tag represents a TestNG class. It is a Java class that contains at least one TestNG annotation. It can contain one or more test methods.
Compile the Test case classes using javac.
C:\TestNG_WORKSPACE>javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java
Now TestNG with the following command:
C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE" org.testng.TestNG testng.xml
If all has been done correctly, you should see the results of your tests in the console. Furthermore, TestNG creates a very nice HTML report in a folder called test-output that is automatically created in the current directory. If you open it and load index.html, you will see a page similar to the one in the image below:
| https://www.tutorialspoint.com/testng/testng_writing_tests.htm | CC-MAIN-2017-09 | refinedweb | 674 | 50.84 |
Given Code Not Working
Hi
The given code is not working .
Give the error:- HTTP Status 404 - Servlet action is not available.
any solution for it??
where to place properties file exactly.
Where i have to place the property file exactly.
i have placed the property file already in two places
1) one in resources folder.
2) second one along with the folders of class files.
But i am getting an exception like
javax.servlet.ServletEx
amaging demos and amaging descriptiuon
i have never come accross like this demos and descriptions .i learned so musch .thanks to roseindia.i hope you people may help us to learn new frameworks technologies and every thing.
thanks
and
regards
santosh
thank you..............
Its works exactly.Thank you Friend
calender working in struts - Struts
calender working in struts when i execute the following code ,that is working properly
if i convert to struts html tags that code is not working
please help me to rectify the problem
LookupDispatchAction
LookupDispatchAction What is LookupDispatchAction
Struts LookupDispatchAction Example
Struts LookupDispatchAction Example
Struts LookupDispatch Action... function. Here in this example you will learn more about Struts LookupDispatchAction
Why is this code working
Why is this code working Looking at this piece of code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef... run it. Shouldn't I get a segfault given I incorrectly do malloc() on sizeof(char
myJSF,Hibernate and Spring integration code is not working. - Hibernate
myJSF,Hibernate and Spring integration code is not working. the code given in this url :
i have tried but it does not work.
when i write | http://roseindia.net/tutorialhelp/allcomments/45184 | CC-MAIN-2014-42 | refinedweb | 267 | 68.16 |
Migrating your Windows Store app to Windows 8.1 (Whitepaper)
This paper provides information about how to migrate a Windows Store app built for Windows 8 to Windows 8.1. It assumes that the reader is familiar with Windows Store app development, the Windows Runtime, and either XAML or the Windows Library for JavaScript (WinJS).
Introduction
Windows 8 introduced the world to the Windows Runtime and WinJS for building Windows Store apps. Windows 8.1 introduces a number of changes and improvements to the Windows Runtime and WinJS to help you make more exciting and better performing apps. This guidance helps you understand the improvements and changes to the platform so you can easily transition your XAML, HTML with JavaScript, or DirectX-based Windows 8 code investments to Windows 8.1.
This topic first introduces basic migration steps, then describes ways to improve your app's performance, and ends with features and controls that are new to Windows 8.1 and might make great additions to your existing app.
The good news is that even if you do nothing, your Windows 8 apps will continue to run on Windows 8.1. However, you won’t be able to take advantage of performance improvements, layout changes, and new controls that make Windows 8.1 apps more responsive and better integrated with Windows. In addition, taking advantage of new platform capabilities makes your apps more desirable to users and can help them stand out in the Windows Store.
Why update to Windows 8.1?
Updating your apps to Windows 8.1 provides significant benefits, including:
- Numerous performance improvements in common scenarios, including app startup time and panning within large data collections
- Improved animation rendering
- New and improved controls
- More flexible app layouts and window states
- Additional tile sizes and templates
- Better integration of contacts and calendar
- More natural in-app search experience.
Retarget your project with Microsoft Visual Studio 2013
The first step to getting your app working with Windows 8.1 is to open your project with Microsoft Visual Studio 2013, which is available as a free download on the Windows Dev Center. Visual Studio 2013 can be run side-by-side with Microsoft Visual Studio 2012. Retargeting your app is comprised of five steps:
- Copy your solution.
- Retarget your projects.
- Fix errors that relate to file paths and extension SDKs.
- Update your code to target new APIs and features.
- Service the Windows 8 verison of your app.
Each step in this process is detailed in Retarget your Windows Store app to Windows 8.1.
Note on extension SDKs: If your Windows Store app uses an extension SDK that was built for Windows 8, it may not work properly with Windows 8.1. For a list of some of the extension SDKs that might not be compatible with Windows 8.1 and the steps to take to resolve issues with incompatible SDKs, see the section on extension SDKs in Retarget your Windows Store app to Windows 8.1.
Consider API changes
Several things have changed in Windows 8.1 that cause apps to behave differently.
In Windows 8.1, some APIs from Windows 8 have undergone functional changes. This can be confusing, because although the API signature is the same, these APIs will behave differently depending on the version of Windows an app is targeted for. Being aware of these changes can help you anticipate and diagnose issues in your retargeted apps.
For a list of the affected APIs, please see API changes for Windows 8.1 (Windows Store apps using C#/VB/C++ and XAML) or API changes for Windows 8.1 (Windows Store apps using JavaScript and HTML).
- Some APIs have been deprecated in favor of newer APIs that provide similar or improved functionality. Deprecated APIs (both in WinJS and Windows Runtime) are detailed in the Deprecated APIs section at the bottom of the page. They will continue to work in Windows 8.1, but update them to the preferred alternatives to ensure future compatibility. The compiler will provide a warning when you invoke a deprecated API.
- Certain Document Object Model (DOM) APIs have been removed in favor of new standards-based APIs that also offer performance advantages. See the list of Deprecated DOM APIs for more information.
Update to support new view states
Windows 8.1 lets users smoothly resize windows within a range of widths enabling greater flexibility, expanded device support, and better multi-window support. As you develop apps for Windows 8.1, keep these main points in mind:
- Windows 8.1 doesn’t have fixed-width view states. Users can now resize apps continuously down to a minimum width. The default minimum width of an app is 500 pixels and the non-default minimum is 320 pixels. Consequently, apps no longer have the snapped and fill view states. Instead, design your app to be functional and appealing at any size down to the minimum.
Note: The snapped view in Windows 8 had a width of 320 pixels. The default minimum width of 500 pixels is larger than the Windows 8 snapped view.
- Users can have more than two apps on the screen at the same replaces the original app on the screen. To change the default behavior, use the DesiredRemainingView property.
Apps must fill the height of the screen, just like in Windows 8. The minimum height of an app is 768 pixels.
Important: Update your apps to support only those states and sizes that you want to support. The platform provides significant new flexibility, but consider the common usage patterns and scenarios for your app and implement the view states that make the most sense for your users.
For a demonstration of new orientation and layout possibilities, see the Application Views Sample for Windows 8.1.
Design guidelines
When you design an app for Windows 8.1:
- Make sure your app layout and controls scale down to the minimum size. In particular, think about how your app's size impacts your UI elements, including:
- Design your app to use the space on a large screen effectively, and with a layout that reflows automatically. Don't leave large empty spaces.
- If you decide to support a minimum width.
- Use the smaller offset values for page transition animations and content transition animations.
Setting minimum width
If you want to change the minimum width of an app from the default of 500 pixels, you specify the MinWidth attribute of the ApplicationView element in the app manifest. You can do this manually, by editing the package.appxmanifest file directly, or update the values using the Manifest Designer within Visual Studio 2013..
Change snapped state code and styles to small state
Windows 8.1 no longer makes use of snapped state. If your Windows 8 app supported snapped view, you’ll need to replace all calls to ApplicationView.Value with calls to query for the window dimensions directly.
In Windows 8.1, the ApplicationView.Value property and ApplicationView.TryUnsnap method are deprecated, so you will receive compiler warnings if your app uses them. An app should register for the window resize event to know when to update the layout. However, instead of calling ApplicationView.Value to find out which view state the app is in, use the Window.Current and Window.Bounds property to get the general window size, or the ApplicationView.GetForCurrentView and ApplicationView.Orientation to get the orientation. In Windows 8.1, it is up to the app designer to decide what window size thresholds and media queries the app makes to update the app layout. Here are some possible ways to update your code.
Viewing general window size
Windows 8 (deprecated)
Windows 8.1
Windows 8 (deprecated) } }
Windows 8.1
Viewing Orientation
Windows 8 (deprecated)
private void WindowSizeChanged(object sender, WindowSizeChangedEventArgs e) { // Get view state ApplicationViewState currentViewState = ApplicationView.Value; if (currentViewState == ApplicationViewState.FullScreenLandscape || currentViewState == ApplicationViewState.Filled) { // Landscape layouts } else if (currentViewState == ApplicationViewState.FullScreenPortrait) { // Portrait layouts } }
Windows 8.1
private void WindowSizeChanged(object sender, WindowSizeChangedEventArgs e) { // Get window orientation ApplicationViewOrientation winOrientation = ApplicationView.GetForCurrentView().Orientation; if (winOrientation == ApplicationViewOrientation.Landscape) { // Landscape layouts } else if (winOrientation == ApplicationViewOrientation.Portrait) { // Portrait layouts } }
Make platform (XAML or HTML) specific changes to UI
Changes to the UI in Windows 8.1 require some minor changes to your code. The following guidance lists changes based on the UI you created when you built your Windows 8 app.
Windows Store apps using JavaScript
There are a number of APIs used to build Windows Store apps with JavaScript that are changed or no longer supported by Windows 8.1. Please use the following resources to update your code.
- Document Object Model (DOM) changes for Windows 8.1
- API changes for Windows 8.1 (Windows Store apps using JavaScript and HTML)
Remove references to –ms-view-state media queries
Replace all –ms-view-state media queries in your app with max-width, min-width, orientation:portrait, and orientation:landscape queries.
Enable a snapped state style experience
All snapped state styles were removed from ui-dark.css and ui-light.css. If you want to re-enable that experience, you must move them to your app style sheets. The following example demonstrates how to do this with Windows 8.1.
Windows 8 (ui-dark.css)
@media (-ms-view-state: snapped) { */ } }
Windows 8.1 (default.css)
@media (min-width: 320px) and (max-width: 500px) { */ } }
For Windows Store apps with XAML
All UIElement objects in the default control templates for GridViewItem and ListViewItem have been removed to significantly improve performance. In Windows 8.1, each item eliminates the entire control template and interfaces directly with the renderer to provide the necessary UI, rather than going through the normal UIElement abstraction. Doing so yields a large improvement in app startup performance. All apps compiled for Windows 8.1 that contain a GridViewItem/ListViewItem item templates will see an improvement in app startup time.
These templates automatically update when you retarget your app for Visual Studio 2013. However, if you created an ItemContainerStyle that re-templated ListViewItem or GridViewItem in your app for Windows 8, you will have to manually update your code to benefit from these performance improvements.
Improve performance with Windows 8.1
Now that you’ve handled the basics, it’s time to tweak your app so it performs even better with Windows 8.1 than it did with Windows 8. There are two steps in this process:
- Eliminate calls to deprecated APIs, and use preferred alternatives instead.
- Take advantage of Windows Library for JavaScript (WinJS) performance improvements in Windows 8.1.
Deprecated APIs for Windows 8.1
The Deprecated APIs section at the end of this topic contains complete lists of APIs that have been deprecated for Windows 8.1, along with the preferred replacement. Apps that use these deprecated APIs will continue to function in Windows 8.1, but there’s no guarantee that they’ll work in future versions. We recommend that you update your code now to remove calls to these APIs and replace them with the suggested alternatives.
WinJS performance improvements in Windows 8.1
Simply porting your project and recompiling your app yield significant performance improvements with Windows 8.1 over Windows 8, regardless of whether you use XAML or HTML. However, if you built a Windows Store app using JavaScript, you can take advantage of the following new APIs and services to further improve the performance of your apps.
WinJS Scheduler
Windows 8.1 and the Windows Library for JavaScript 2.0 introduces the Scheduler, an object/namespace that consolidates all work queues into a single, universal queue. The new queue has a priority-based scheduling policy that lets you to prioritize your work against system work to improve responsiveness. You can schedule tasks and assign priorities so that the right thing gets done at the right time. To learn more about the Scheduler API, WinJS.Utilities.Scheduler, and how it can help you improve the performance of your code, see Asynchronous programming.
WinJS.Binding.Template updates
The Windows Library for JavaScript 2.0 uses a new, more efficient system to process Template objects that significantly improves performance. With the new system, data binding and control instantiation happen in a parallel process rather than in series, as they did in Windows Library for JavaScript 1.0. If your code depends on the legacy serial processing behavior, we recommend making changes to your code to take advantage of faster template processing; however, you can use the disableOptimizedProcessing property to restore the old behavior if you choose not to change your code.
The Dispose Pattern
The dispose model is a new pattern that allows elements and controls to release resources at the end of their lifetime to prevent memory leaks. An element or control can optionally implement it. Windows Library for JavaScript 2.0 controls that have resources to release now implement this API.
To take advantage of the dispose model, call the control's dispose method when the control is no longer needed, such as when you're navigating away from a page or when the app is shutting down.
Take full advantage of new for Windows 8.1 features and controls
Windows 8.1 introduces a host of new layout options and controls to add visual appeal to your apps, enable new functionality, and help your app better integrate with Windows. For a comprehensive review of all new controls in Windows 8.1, see:
This section highlights several controls and UI features that make your app really stand out in Windows 8.1.
In-app search.
For more info about the new SearchBox control in WinJS and XAML, see Search updates.
New tile sizes
Windows 8.1 introduces these changes to tiles and the ways you work with them.x existing tile templates have been renamed.
For compatibility, the older names are still recognized. But use the new names in any new development you do. For more info about updates to tiles in Windows 8.1, see Tile Updates.
Hub control
Windows 8.1 introduces the Hub control, a new control for XAML and WinJS that lets you more easily create the Hub design pattern that exhibits the correct design guidelines and behaviors. Hub pages are the user's entry point to your app. They display content in a rich panning view that lets users get a glimpse of what's new and exciting, and then dig deeper into your app's content. The Hub consists of different categories of content, each of which maps to your app's section pages. Each section should bubble up content or functionality. The Hub should offer a lot of visual variety, engage users, and draw them in to different parts of the app.
For Hub control reference pages, see Hub (XAML) or Hub (WinJS). For additional information on recommendations on Hub use, consider Guidelines for the hub control.
Contacts and Calendar
With Windows 8.1, you get convenient APIs to interact with a user’s contacts and calendar. The Contacts API enables a source app to query the data store by email address or phone number, returning the Contact Card UI for the matching contact. It also defines contact related action types that can be used by apps that handle the target action. The Calendar API allows you to add appointments, replace appointments, remove appointments, and show the user’s default appointment provider app side-by-side with another appointment provider app programmatically.
For more info about Contacts, see Windows.ApplicationModel.Contacts. For more info about Calendar, see Windows.ApplicationModel.Appointments.
MenuFlyout (XAML)
Windows 8.1 introduces a new control for XAML that lets you temporarily show a list of commands or options related to what the user is currently doing: the MenuFlyout control. A MenuFlyout displays lightweight UI that a user can dismiss by tapping or clicking another part of the screen. Use it to let the user choose from a contextual list of simple commands or options. A MenuFlyout should be shown only in response to a user tap or click, and is always dismissed when the user taps away from it.
To download a sample that shows how to use a MenuFlyout, see XAML Flyout and MenuFlyout sample.
SettingsFlyout (XAML)
Windows 8.1 introduces a new control for XAML that lets you more easily create app settings panes that exhibit the correct design guidelines and behaviors: the SettingsFlyout control. Like a Page control, a SettingsFlyout can be declared in XAML as a root element of a document, with an x:Class attribute specified to subclass from SettingsFlyout. You can set the width of the Settings flyout, but the height is always the full height of the screen.
To download a sample that shows how to use a SettingsFlyout, see App settings sample (Windows 8.1).
NavBar (WinJS)
Windows 8.1 and the WinJS introduce a new control to help you provide a consistent and predictable navigation experience: the WinJS.UI.NavBar control. The NavBar is like an AppBar (in fact, the NavBar is a sub-class of the AppBar) that's dedicated to navigation commands. It can contain a simple list of links, and it can contain several levels of links organized into categories. You can populate the NavBar by hard coding entries, programmatically updating it, or by using data binding.
Other new functionality
The Windows Runtime has been greatly expanded for Windows 8.1. The following namespaces have been added to the Windows Runtime.
Additional Resources
The following resources can help you solve specific problems you may encounter while migrating your Windows 8 code investment to Windows 8.1.
- Windows 8.1: New APIs and features for developers
- API Changes for Windows 8.1 (Windows Store apps using C#/VB/C++)
- API Changes for Windows 8.1 (Windows Store apps using Javascript and HTML)
- Retarget your Windows Store app to Windows 8.1
- Controls (HTML with JavaScript)
- Controls (XAML with C#, C++ or VB)
- API Reference
- Your first app
The following support forums have been established to help you migrate your code investments to Windows 8.1.
- Tools for Windows Store apps for Windows 8.1
- Building Windows Store apps with C++ for Windows 8.1
- Building Windows Store apps with C# or VB for Windows 8.1
- Building Windows Store apps with HTML5/JavaScript for Windows 8.1
- Building Windows Store games with DirectX for Windows 8.1
Deprecated APIs
Deprecated WinJS APIs
The following JavaScript API elements are deprecated and may not be available in future versions of Windows. Please refer to the table below for the preferred alternative.
Deprecated Windows Runtime APIs
The following table lists APIs that have been deprecated between Windows 8 and Windows 8.1. The “Replacement API” field indicates a preferred alternative you can use as you upgrade your code to Windows 8.1. For more info about any of these APIs, go to the Windows Dev Center and review the Windows Runtime and WinJS reference documentation.
Build date: 11/16/2013 | http://msdn.microsoft.com/en-us/library/ie/dn376326.aspx | CC-MAIN-2014-23 | refinedweb | 3,157 | 57.27 |
Trie implementation in AS3
In this post, we will implement the Trie data structure in ActionScript 3. Then we will draw it to get a nice picture of this data structure.
What Trie isLet's say, our program gets a thousand words, which we have to store into some data structure. After, we will recieve requests, whether some word is contained in this set. If we store these words in linear array, it will be very unefficient (large memory and long running time when searching for a word). The model of Trie is more efficient. Read more on Wikipedia page.
Class TNode
Whad do I wantI want an ability to easily create a Trie (var trie = new ...), easily add words (trie.AddWord("ahoj");). Easily detect, whether my trie contains some word (if(trie.Contains("hello")) ...).
How to store children in trie nodeEach node can have multiple children, their count is from 0 up to length of an alphabet. Alphabets are often very long (26 - small letters, 256 - ASCII characters, $2^{16}, 2^{24}, 2^{32}$ - Unicode characters). But nodes mostly don't have all the children from an alphabet. I decided to have a fixed-length array and to hash pointers into it. In the example below, I have an array of 4 pointers, I store the pointer on [char code] mod 4. When collision happens, I put pointers into a linked list.
Basic class
package { public class TNode { // the array of 4 children of this node public var cn:Vector.<TNode> = new Vector.<TNode>(4, true); public var c:String; // character stored in the node public var next:TNode; // pointer to the next node (in linked list) public var isEnd:Boolean = false; // whether there is the end of word public function TNode(c:String):void { this.c = c; // assign the parameter to "c" } } }
Searching a child for a characterSince children are in fixed-length array + in linked lists, it is not so easy to get them, so we write this method:
public function GetChild(s:String):TNode { // at first, take a look at the array "cn" var n:TNode = cn[ s.charCodeAt(0)% 4 ]; if ( n == null) return null; // there is no child for "s" else // there is some child, we loop through the linked list while (n.next != null) { if (n.c == s) return n; n = n.next; } if (n.c == s) return n; // it was at the end of LL return null; // it wasn't anywhere }
Adding a word into a TrieAt first, we read the first character of the word. If there already is a child for this charater, we add the rest of the word to this child. If not, we create a new node and add the rest of the word into it.
public function AddWord(s:String):void { // look for child for this char var n:TNode = GetChild(s.charAt(0)); if(n==null) // there is no child { n = new TNode(s.charAt(0)); // we chreate one var pos:int = s.charCodeAt(0)% 4; // where should it be if(cn[pos] == null) cn[pos] = n; // free position else // not free - add it to LL { var no:TNode = cn[ pos ]; while(no.next != null) no = no.next; no.next = n; } } // add the rest of the word to it or set the flag if(s.length>1) n.AddWord(s.substring(1,s.length)); else n.isEnd = true; // end of the word }
Does Trie contain the word
public function Contains(s:String):Boolean { // at the end of recursion we return isEnd if(s.length == 0) return isEnd; // we look at the proper child var n:TNode = GetChild(s.charAt(0)); if(n==null) return false; // no such child else return n.Contains(s.substring(1,s.length)); // ask the child }
Drawing a trieWe draw a Trie using very common code as when I was drawing Binary search tree.
function drawTrie(n:TNode, x:int, y:int, w:int, place:Sprite) { var i:int; // at first, we add chilren to array var nodes:Array = new Array(); for(i = 0; i<4; i++) { var no:TNode = n.cn[i]; if(no == null) continue; while(no != null){ nodes.push(no); no = no.next;} } var sW:int = w/nodes.length; // width for each node for (i = 0; i < nodes.length; i++) { with(place.graphics) // line to child { lineStyle(3,0x00E1FF); moveTo(x, y); lineTo(x-w/2 + i*sW + sW/2, y+60); } // drawing a child drawTrie(nodes[i], x-w/2 + i*sW + sW/2, y+60, sW, place); } // draw a round for this node with(place.graphics) { if(n.isEnd) lineStyle(4, 0x000000); // když je koncový else lineStyle(2, 0x333333); // když není - tenčí okraj beginFill(0x6D00D9); drawEllipse(x-14, y-14, 28, 28); endFill(); } // add text field with character var tf:TextField = new TextField(); tf.text = n.c; tf.x = x-tf.textWidth; tf.y = y-14; place.addChild(tf); }
Thanks for such nice visual presentation. It helps me a lot to understand, and implement a trie.July 4th, 2011
..wowMay 7th, 2012
where’s the download link?May 7th, 2012
kelangan ko nyanMay 7th, 2012
Juan: How can I help you? You can download SWF and use it locally. You can copy the code and use it. If you made a donation, I can give you other things, what exactly do you need?May 7th, 2012
Hi this is too good….August 22nd, 2012
Could u pls give me the confirmation that will i b able to implement the same AC algorithm in verilog code……… pls do reply m waiting..
why does the constructor requires a string value ?May 3rd, 2013
Luis: It is because ActionScript does not have a character type, so I decided to work with one letter strings.May 3rd, 2013 | http://blog.ivank.net/trie-in-as3.html | CC-MAIN-2015-22 | refinedweb | 958 | 83.15 |
[Qt Ambassador] QxOrm 1.1.7 released
Hi,
QxOrm 1.1.7 released :
Changes in version 1.1.7:
- Add soft delete behavior : see the FAQ (How to define a soft delete behavior ?) for more details about this new feature
- Add functions into namespace 'qx::dao' to update an element with a SQL condition : update_by_query, update_optimized_by_query, etc.
- Fix a bug when QVariant type is used for a property of a persistent class : so, it's now possible to insert NULL value into database
For more information about QxOrm library, please visit :.
I had a quick look at the project and I wondered why you decided against code generation (e.g. generation of skeleton classes). Back when I developed PHP, I used the Propel ORM (I don't know if you know that), quite heavily, and I always liked its code generation features. Is is something you plan to add in the feature (judging from your website I'd say you won't) are you conceptually against it (if so, I'm really interested why) or did you just not need it? I'm not doing a lot of database stuff at the moment in desktop development, but I am just curious as to why you made that choice.
I'm not against code generation and I think it would be a good feature to implement in a future release.
But generation from what ? An XML file ?
I don't think it's a good solution : I prefer write directly C++ source code and I think QxOrm library provides an easy interface to implement (you just have to write qx::register_class<T> per persistent class).
A good cross-platorm editor could be a solution with a GUI to define your persistents classes and a command line to generate all classes before building your project.
Moreover, I think code generation must be considered when ORM library starts to be mature : it's a new feature and you have the choice to use it or not. QxOrm library starts to be mature so we can now envisage to write a code generation editor.
It's like inherit from QObject : why QxOrm library doesn't use introspection engine of Qt ? To not add constraint to developers.
With QxOrm library, you just have the choice : you can inherit your persistent class from QObject or not. | https://forum.qt.io/topic/7019/qt-ambassador-qxorm-1-1-7-released | CC-MAIN-2017-34 | refinedweb | 390 | 62.17 |
January 2009
Volume 24 Number 01
Cutting Edge - Managing Dynamic Content Delivery In Silverlight, Part 1
By Dino Esposito | January 2009
Users of any rich Internet application (RIA) have valid concerns about security and download size. Silverlight applications are backed by a subset of the full Microsoft .NET Framework and, as such, have the potential to take harmful actions against the local user machine. For this reason, the Silverlight team developed a new security model that makes it impossible for applications to call into any security-critical class in the Core CLR (the Silverlight edition of the .NET Framework). You can read more about the Silverlight security model in the article " Program Silverlight with the CoreCLR" and more about building Silverlight apps in " Get Started Building a Deeper Experience across the Web."
Downloading the Silverlight plug-in is not really an issue, as it takes just a few seconds and is an operation that you run only once. But what about the size of downloaded applications?
In this month's column, I'll tackle the question of Silverlight application downloads. First, I'll illustrate how you can generate XAML dynamically. Next, I'll discuss how to enable application features dynamically on a strictly per-user request basis. Some application-specific features that are heavy to implement with the main stream of code can then be implemented separately and, more important, downloaded separately and still be easily integrated with the primary user interface.
The Size of Silverlight Applications
Once a user has installed the Silverlight plug-in, he has in place all system assemblies that a Silverlight application may require. This means that the download is limited to the assembly that contains the application, plus any referenced custom assemblies. In the end, the size of the application download is often in the tens of kilobytes. Note that this estimation applies to the RTM version of Silverlight 2 and to code compiled in release mode.
Of course, the application might have a much larger footprint, especially if it contains long algorithms, graphic and media content, or animations. To deal with large applications where the download time becomes a problem, you have two main options. One is to stream the Silverlight content as discussed at silverlight.live.com. The other option is to split the application into independent pieces that can be downloaded separately and on demand.
Dynamically Generated XAML
The Silverlight plug-in is essentially designed to display XAML content. If the XAML comes with some codebehind, then the plug-in processes the code to produce the user interface and support any coded behavior or effects. The XAML can be pointed to directly via a URL if it is all that you want to be downloaded; otherwise, you can reference a Silverlight package through the XAP extension.
A XAP package contains a manifest and one or more assemblies. One of the assemblies contains the entry point of the application; other assemblies are just referenced assemblies. The XAML for the user interface is stored in the resources of the entry point assembly. A XAP package is created by the Visual Studio 2008 extension for Silverlight 2 when you create and build the project.
XAML and XAP streams are all that the Silverlight plug-in knows how to handle. To download such content, though, you don't necessarily have to point the plug-in to a physical XAML or XAP resource on the server. You can, for instance, point the plug-in to a URL that can return dynamically generated XAML or XAP content.
Figure 1shows a sample ASP.NET HTTP handler that returns some XAML created on the fly. The ProcessRequest method sets the content type on the Response object and then writes out some XAML content, such as XAML composed dynamically, based on configuration data, parameters, or runtime conditions. By setting the Expires property on the Response object, you can also prevent caching of the resource on the client. This may be helpful if the content you're serving changes periodically and needs refreshing.
<%@ WebHandler Language="C#" Class="XamlGenHandler" %> using System; using System.Web; public class XamlGenHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { // Prevent caching of the response context.Response.Expires = -1; // Set the type of data we're returning context.Response.ContentType = "text/xaml"; // Create some XAML and return it down the wire context.Response.Write("<Canvas xmlns= '' " + "xmlns:" + "<TextBlock Foreground='black' Padding='10' FontSize='20'> <Run>XAML content</Run><LineBreak/>" + "<Run>[generated " + DateTime.Now.ToLongTimeString() + "]</Run>" + "</TextBlock></Canvas>"); } public bool IsReusable { get {return true;} } }
Dynamically Generated XAP
Returning a dynamically generated XAP package is not much different from returning raw XAML text, except that a XAP package is not a plain text file. A XAP package is a ZIP file that contains an XML manifest and one or more assemblies. By using a package format, the team minimized the number of round-trips necessary to download the entire content required by a Silverlight application. Figure 2shows an ASP.NET HTTP handler that writes the content of a XAP file out to the HTTP response stream.
<%@ WebHandler Language="C#" Class="XapGenHandler" %> using System; using System.Web; public class XapGenHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { // XAP file to return string xapFile = "..."; // Set the type of data we're returning context.Response.ContentType = "application/octet-stream"; // Create some XAML and return it down the wire content.Response.WriteFile(xapFile); } public bool IsReusable { get {return true;} } }
The sample code reads the XAP data from an existing file. It goes without saying that if you embed a ZIP library in your project, you could easily assemble the package on the fly by combining different DLLs and then creating a proper XML manifest file.
If you're returning XAP content, you set the content type of the response to application/octet-stream—the MIME type that commonly identifies generic binary content.
To associate the plug-in with an HTTP handler, or any other endpoint you choose, you use the usual Silverlight programming techniques. For example, you can use the Silverlight server control in an ASP.NET page:
In both examples, the factory for the Silverlight application lives on the Web server. This is an excellent approach if the host page needs to figure out dynamically which content to download.
However, this is just one possible scenario. There's another scenario that is probably more common—the need to download optional components for the current Silverlight application. In this case, the logic to select and download external content is all running on the client in the Silverlight plug-in.
On-Demand Content
Silverlight 2 provides a rich and powerful API to download code and/or XAML on demand that you can use for downloading content and inserting it into the existing XAML document object model.
All visual elements of a XAML tree feature a property called Children that you can use to programmatically add or remove child elements of any size. For example, you can append an entire user control downloaded from the same server or even from a trusted, opt-in remote server. The following line shows an example:
The user control represented by the argument is added to the Children collection of a StackPanel XAML element. The rendering is immediate, and the user interface is updated in real time.
You can do much more than just download content and attach it to the existing document object model. You can, for example, cache it locally in the local storage of the application and check your own cache for on-demand content before you go for a new request to the server.
This approach gives you permanent storage of the downloaded content. However, in some cases this may be overkill. Another, simpler option exists that doesn't require any extra work: letting the browser cache the XAP resource for you.
Caching Downloaded Content
The XAP package that you get from the Web server has no special meaning to the browser. The browser, therefore, will cache it as it caches anything else it gets from a Web server, adhering to the request cache policies determined by the cache-control and "expires" HTTP header in the request or similar meta tags in the host HTML page.
Note that when you have a XAP resource to be downloaded in the browser, you can control caching via the settings in the page that you typically insert using meta tags or ASP.NET directive attributes. If the XAP resource is to be downloaded via an HTTP handler as in the previous example, then you can control caching for the specific request.
Another point that is worth noting is that it is the original XAP content, including assemblies and XAML, that is cached. Therefore, the running application can programmatically modify the original XAML. However, such changes won't be cached automatically, and likewise, any resource you may extract from a XAP package (media, images, and so on) is not cached separately. Thus, whenever the user visits the page, the XAP package is not downloaded again (unless it is expired), but any resources will be extracted again. Furthermore, any changes you may have made to these resources in previous sessions are lost. To persist changes to the XAML document object model, you have to arrange your own tailor-made cache. (This is a cool technique that I will cover in Part 2 of this topic.)
Finally, note that the XAP package saved in the browser's cache is at the mercy of the user. Should the user decide to clear the cache at some time, anything located there will be lost—including your XAP packages. To permanently store Silverlight XAP packages, you have to resort to isolated storage (this topic is also slated for Part 2).
A Tool for Downloads
When you write Silverlight applications, remember that every resource you need that is not already packed in the application's XAP must be explicitly downloaded from the server. The WebClient class is the primary Silverlight tool you want to use to arrange downloads of additional resources. The class provides a few asynchronous methods for sending data to, and receiving data from, a Web resource. Here's how it works:
The DownloadStringAsync method operates an HTTP GET and captures the URL response as a string. The string is received by the associated callback, as shown here:
As you'll see in a moment, this method is perfect for downloading plain XAML with no attached codebehind. To programmatically download binary data, such as a XAP package, you need a stream and a slightly different approach. The WebClient class is still helpful, as it provides an apt method in OpenReadAsync:
The structure of the associated callback is the same in the previous case. In the end, you use the DownloadStringAsync method to get a simple string; you use the OpenReadAsync method to get a stream of any data. Whether you decide to download a string or a stream is mostly a matter of preference and depends essentially on how you plan to use the data you're receiving.
Note also that WebClient provides a pair of methods for writing to a remote URL: UploadStringAsync for posting a string and OpenWriteAsync for uploading any data to a URL using a stream.
You can use the Headers property to specify additional headers because the class, by default, doesn't specify any. You should note, though, that some of the headers you may set are stripped off by the Framework and managed internally. These include Referer, Connection, and User-Agent. The Content-Type header, if set, is preserved.
When it comes to downloading a resource, the WebClient class transparently uses the browser's cache before attempting a connection. If the XAML or XAP resource is not in the cache, then the class proceeds with the download. The process of downloading content from a Silverlight application results from the combined efforts of the Silverlight runtime and the internal API that the host browser exposes to a plug-in. This means that under the hood of WebClient, the Silverlight runtime talks to the browser sandbox to check whether the requested resource is already in the cache. If not, Silverlight proceeds with its own security policies to authorize the request. When data is finally returned from the endpoint, the Silverlight runtime caches it locally through the browser's services and in full respect of ongoing caching policies.
A number of security restrictions apply to the WebClient class and other HTTP classes in the Silverlight System.Net namespace. In particular, the WebClient class supports only HTTP and HTTPS schemes when downloading via stream and the FILE scheme when downloading pure XAML. Cross-scheme access is always prohibited, so you can't point WebClient to, say, an HTTPS resource if the host page downloaded via HTTP (and vice versa). A WebClient request can, in general, reach a URL in a different browser's zone, but not if it attempts to move from an Internet zone to a more restrictive zone. Silverlight currently supports zones only on a Windows operating system.
Finally, cross-domain access is supported only if the remote site opted in by hosting a proper XML file in its root directory. Note also that cross-domain access doesn't work in an HTTPS-to-HTTPS scenario.
The same WebClient object can't handle multiple requests simultaneously. You should check the IsBusy property—a Boolean value—to determine whether it is safe for your code to place a new request via the same WebClient instance. If you use multiple WebClient objects—perhaps on different threads—you can start multiple downloads at the same time.
Downloading XAML-Only Data
Let's see how to use the WebClient to download XAML data and integrate it in the visual tree. In Silverlight 2 applications, the dynamic download of plain XAML data doesn't necessarily give you the programming power you need. The XAML string must be plain XAML with no references to be resolved at run time ,such as bindings or references to styles, resources, and events.
Once the XAML string is downloaded, you use the XamlReader class to turn it into a UI element that can be added to the existing document object model. The following code shows how to programmatically download a XAML string from a URL. Note that you need to provide the URL as a Uri object:
The URL can point to a plain XAML resource or to an endpoint that returns a text/xaml response. Here's the code to process the downloaded XAML and append it to a placeholder in the visual tree:
As mentioned, a placeholder may be any element in the document object model currently rendered in the plug-in. Note that the children of a UI element form a collection, and they are rendered as a sequence. This means that to avoid undesired overlapping of elements, in the case of updates you should first remove elements and then add.
XAML serialization, which is performed through the XamlReader and XamlWriter classes, is based on the principle that extension references are de-referenced and runtime values are saved over design-time settings. What if you want to download XAML content and customize it before display, such as through dynamic data binding? You can't embed bindings in the XAML source, but you can define placeholders in the downloaded XAML, retrieve them with parsing, and set them to any value you want programmatically. However, in Silverlight 2, downloading a XAP package is definitely a better solution.
Working with XAP Packages
A XAP package contains an entire Silverlight application whose user interface consists essentially of a user control, which is really just a container of XAML markup and code.
As mentioned, a XAP package includes one or more assemblies tracked by a manifest file. Processing a XAP package entails two extra steps beyond download. You need to extract the main assembly and then instantiate the entry point class that starts up the downloaded application. Needless to say, in this case you can use binding, styles, events, and whatever else you want in the XAML. When you work with a XAP package, it's the Silverlight runtime—not the serialization API—that processes the XAML and then resolves references. This makes a huge difference in terms of programming power.
Downloading and processing a XAP package requires a bit of more work than just building an object model out of a string. Some of this work—typically the content download and assembly extraction—can be moved to a reusable downloader class (see Figure 3).
public partial class Page : UserControl { private UIElement content = null; private TabItem item = null; public Page() { InitializeComponent(); } private void chkNewContent_Click(object sender, RoutedEventArgs e) { bool shouldDisplay = (sender as CheckBox).IsChecked.Value; if (shouldDisplay) { if (!IsContentAvailable()) DownloadContent(); else ShowContent(); } else { HideContent(); } } private bool IsContentAvailable() { return (content != null); } private void DownloadContent() { Downloader dl = new Downloader(); dl.XapDownloaded += new EventHandler<XapEventArgs>(OnPackageDownload); dl.LoadPackage("more.xap", "more.dll", "More.ExtraTab"); } void OnPackageDownload(object sender, XapEventArgs e) { content = e.DownloadedContent; ShowContent(); } private void HideContent() { this.TabList.Items.Remove(item); } private void ShowContent() { item = new TabItem(); item.Header = "Extra tab"; item.Content = content; this.TabList.Items.Add(item); } }
The code in Figure 3shows a sample tab-based application that loads a new tab the first time the user clicks on a checkbox. In this case, a new XAP package is downloaded, and the user control contained in its user interface is inserted in a newly created TabItem. Hiding the content from the newly downloaded package is a simple client operation. And showing it again doesn't require a second round-trip for two good reasons: the content is cached in memory, and the package from which it was built is cached in the browser's cache.
Figure 4shows the user interface of this sample application. The content inserted in the additional tab comes from a new Silverlight application project. In terms of deployment, all you have to do is store the XAP package in the ClientBin folder of the host Web site (the default location where WebClient looks for relative content) or in any other location that is safe for WebClient to reach.
.gif)
Figure 4 An Application Capable of Downloading Parts of UI Dynamically
Now, let's explore the code of the helper Downloader class. Note that the Downloader class used in this example is an internal class and has nothing to do with the Silverlight Downloader object available to JavaScript callers. The JavaScript downloader object is essentially a script-callable wrapper for WebClient.
Processing XAP Content
The Downloader class uses WebClient to download a XAP package and then extracts the assembly that contains the application from the zipped stream and instantiates the specified root class. All this logic is hidden behind a relatively simple programming facade made of a LoadPackage method and a XapDownloaded event. The method has the following signature:
It receives the URL to the package, the name of the assembly in the package to extract, and the name of the class to instantiate. As mentioned, this class is the codebehind of the XAML interface file.
The XapDownloaded event is fired when the downloader class has finished with the XAP processing and has the user control ready for the client application. Here's the definition of the event:
The event argument class returns the following information:
Let's dig out the logic of the LoadPackage method. The method employs the binary interface of WebClient to point to the XAP package:
void LoadPackage(string package, string asm, string cls) { assemblyName = asm; className = cls; Uri address = new Uri(package, UriKind.RelativeOrAbsolute); WebClient client = new WebClient(); client.OpenReadCompleted += new OpenReadCompletedEventHandler(OnCompleted); client.OpenReadAsync(address); }
The download proceeds asynchronously and fires the OpenReadCompleted event when it is finished. Figure 5shows the implementation for the handler of the event.
void OnCompleted(object sender, OpenReadCompletedEventArgs e) { if (PackageDownloaded == null) return; if (e.Error != null) return; // Load a particular assembly from the XAP package Assembly a = GetAssemblyFromPackage(assemblyName, e.Result); // Get an instance of the XAML object object page = a.CreateInstance(className); // Fire the event XapEventArgs args = new XapEventArgs(); args.DownloadedContent = page as UserControl; XapDownloaded(this, args); }
If no error occurred, a helper function extracts the specified assembly from the package and gets an instance of the user control class in the codebehind of the XAML block to add. Next, a custom event is fired to the caller so that the XAML subtree can be processed. At this point, one thing remains to expand on: the details of how an assembly is extracted from the zipped stream downloaded from the URL. This code is shown in Figure 6. This is boilerplate code you use to extract an assembly from a XAP package. StreamResourceInfo and Application.GetResourceStream are also common tools for extracting resource packages such as images or media content from the current XAP.
Assembly GetAssemblyFromPackage(string assemblyName, Stream xap) { // Local variables Uri assemblyUri = null; StreamResourceInfo resPackage = null; StreamResourceInfo resAssembly = null; AssemblyPart part = null; // Initialize assemblyUri = new Uri(assemblyName, UriKind.Relative); resPackage = new StreamResourceInfo(xap, null); resAssembly = Application.GetResourceStream(resPackage, assemblyUri); // Extract an assembly part = new AssemblyPart(); Assembly a = part.Load(assemblySri.Stream); return a; }
Summing It Up
Silverlight applications are expected to download and install quickly and run fast on the user's machine. Managed code outperforms interpreted JavaScript, so performance will indeed be snappy. But because downloading large Silverlight applications, or applications that require large external graphic and media content, can create undesired latency, breaking the download into steps helps. It is even better if you program these steps to occur on demand.
The WebClient class offers an effective and asynchronous programming API to download any sort of resources you can access over the Internet. The extensible model for the Silverlight object model allows you to incorporate any changes in the existing structure quickly. Finally, the stream-based API centered around the StreamResourceInfo class makes it easy to extract content from the resources of assemblies and XAP packages.
Any downloaded resource is cached by the browser. This sort of caching is not permanent, though. In Part 2 of this column, I'll use isolated storage to make any downloaded content persist longer on the user's machine, thus saving many potential round-trips. For more Silverlight goodies, see Jeff Prosise's Wicked Code column " Silverlight Tips, Tricks, and Best Practices."
Send your questions and comments for Dino to cutting@microsoft.com.
Dino Esposito is an architect at IDesign and the coauthor. | https://msdn.microsoft.com/magazine/dd315412 | CC-MAIN-2019-22 | refinedweb | 3,745 | 52.7 |
This.
As an example, consider an imperative style code fragment that selects only those lines of text that match a criterion isCond():
selected = [] # temp list to hold matches fp = open(filename): for line in fp.readlines(): # Py2.2 -> "for line in fp:" if isCond(line): # (2.2 version reads lazily) selected.append(line) del line # Cleanup transient variable
There is nothing wrong with these few lines (see xreadlines on efficiency issues). But it does take a few seconds to read through them. In my opinion, even this small block of lines does not parse as a single thought, even though its operation really is such. Also the variable line is slightly superfluous (and it retains a value as a side effect after the loop and also could conceivably step on a previously defined value). In FP style, we could write the simpler:
selected = filter(isCond, open(filename).readlines()) # Py2.2 -> filter(isCond, open(filename))
In the concrete, a textual source that one frequently wants to process as a list of lines is a log file. All sorts of applications produce log files, most typically either ones that cause system changes that might need to be examined or long-running applications that perform actions intermittently. For example, the PythonLabs Windows installer for Python 2.2 produces a file called INSTALL.LOG that contains a list of actions taken during the install. Below is a highly abridged copy of this file from one of my computers:
Title: Python 2.2 Source: C:\DOWNLOAD\PYTHON-2.2.EXE | 02-23-2002 | 01:40:54 | 7074248 Made Dir: D:\Python22 File Copy: D:\Python22\UNWISE.EXE | 05-24-2001 | 12:59:30 | | ... RegDB Key: Software\Microsoft\Windows\CurrentVersion\Uninstall\Py... RegDB Val: Python 2.2 File Copy: D:\Python22\w9xpopen.exe | 12-21-2001 | 12:22:34 | | ... Made Dir: D:\PYTHON22\DLLs File Overwrite: C:\WINDOWS\SYSTEM\MSVCRT.DLL | | | | 295000 | 770c8856 RegDB Root: 2 RegDB Key: Software\Microsoft\Windows\CurrentVersion\App Paths\Py... RegDB Val: D:\PYTHON22\Python.exe Shell Link: C:\WINDOWS\Start Menu\Programs\Python 2.2\Uninstall Py... Link Info: D:\Python22\UNWISE.EXE | D:\PYTHON22 | | 0 | 1 | 0 | Shell Link: C:\WINDOWS\Start Menu\Programs\Python 2.2\Python ... Link Info: D:\Python22\python.exe | D:\PYTHON22 | D:\PYTHON22\...
You can see that each action recorded belongs to one of several types. A processing application would presumably handle each type of action differently (especially since each action has different data fields associated with it). It is easy enough to write Boolean functions that identify line types, for example:
def isFileCopy(line): return line[:10]=='File Copy:' # or line.startswith(...) def isFileOverwrite(line): return line[:15]=='File Overwrite:'
The string method "".startswith() is less error prone than an initial slice for recent Python versions, but these examples are compatible with Python 1.5. In a slightly more compact functional programming style, you can also write these like:
isRegDBRoot = lambda line: line[:11]=='RegDB Root:' isRegDBKey = lambda line: line[:10]=='RegDB Key:' isRegDBVal = lambda line: line[:10]=='RegDB Val:'
Selecting lines of a certain type is done exactly as above:
lines = open(r'd:\python22\install.log').readlines() regroot_lines = filter(isRegDBRoot, lines)
But if you want to select upon multiple criteria, an FP style can initially become cumbersome. For example, suppose you are interested in all the "RegDB" lines; you could write a new custom function for this filter:
def isAnyRegDB(line): if line[:11]=='RegDB Root:': return 1 elif line[:10]=='RegDB Key:': return 1 elif line[:10]=='RegDB Val:': return 1 else: return 0 # For recent Pythons, line.startswith(...) is better
Programming a custom function for each combined condition can produce a glut of named functions. More importantly, each such custom function requires a modicum of work to write and has a nonzero chance of introducing a bug. For conditions that should be jointly satisfied, you can either write custom functions or nest several filters within each other. For example:
shortline = lambda line: len(line) < 25 short_regvals = filter(shortline, filter(isRegDBVal, lines))
In this example, we rely on previously defined functions for the filter. Any error in the filters will be in either shortline() or isRegDBVal(), but not independently in some third function isShortRegVal(). Such nested filters, however, are difficult to read?especially if more than two are involved.
Calls to map() are sometimes similarly nested if several operations are to be performed on the same string. For a fairly trivial example, suppose you wished to reverse, capitalize, and normalize whitespace in lines of text. Creating the support functions is straightforward, and they could be nested in map() calls:
from string import upper, join, split def flip(s): a = list(s) a.reverse() return join(a,'') normalize = lambda s: join(split(s),' ') cap_flip_norms = map(upper, map(flip, map(normalize, lines)))
This type of map() or filter() nest is difficult to read, and should be avoided. Moreover, one can sometimes be drawn into nesting alternating map() and filter() calls, making matters still worse. For example, suppose you want to perform several operations on each of the lines that meet several criteria. To avoid this trap, many programmers fall back to a more verbose imperative coding style that simply wraps the lists in a few loops and creates some temporary variables for intermediate results.
Within a functional programming style, it is nonetheless possible to avoid the pitfall of excessive call nesting. The key to doing this is an intelligent selection of a few combinatorial higher-order functions. In general, a higher-order function is one that takes as argument or returns as result a function object. First-order functions just take some data as arguments and produce a datum as an answer (perhaps a data-structure like a list or dictionary). In contrast, the "inputs" and "outputs" of a HOF are more function objects?ones generally intended to be eventually called somewhere later in the program flow.
One example of a higher-order function is a function factory: a function (or class) that returns a function, or collection of functions, that are somehow "configured" at the time of their creation. The "Hello World" of function factories is an "adder" factory. Like "Hello World," an adder factory exists just to show what can be done; it doesn't really do anything useful by itself. Pretty much every explanation of function factories uses an example such as:
>>> def adder_factory(n): ... return lambda m, n=n: m+n ... >>> add10 = adder_factory(10) >>> add10 <function <lambda> at 0x00FB0020> >>> add10(4) 14 >>> add10(20) 30 >>> add5 = adder_factory(5) >>> add5(4) 9
For text processing tasks, simple function factories are of less interest than are combinatorial HOFs. The idea of a combinatorial higher-order function is to take several (usually first-order) functions as arguments and return a new function that somehow synthesizes the operations of the argument functions. Below is a simple library of combinatorial higher-order functions that achieve surprisingly much in a small number of lines:
from operator import mul, add, truth apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns)) bools = lambda 1st: map(truth, 1st) bool_each = lambda fns, args=[]: bools(apply_each(fns, args)) conjoin = lambda fns, args=[]: reduce(mul, bool_each(fns, args)) all = lambda fns: lambda arg, fns=fns: conjoin(fns, (arg,)) both = lambda f,g: all((f,g)) all3 = lambda f,g,h: all((f,g,h)) and_ = lambda f,g: lambda x, f=f, g=g: f(x) and g(x) disjoin = lambda fns, args=[]: reduce(add, bool_each(fns, args)) some = lambda fns: lambda arg, fns=fns: disjoin(fns, (arg,)) either = lambda f,g: some((f,g)) anyof3 = lambda f,g,h: some((f,g,h)) compose = lambda f,g: lambda x, f=f, g=g: f(g(x)) compose3 = lambda f,g,h: lambda x, f=f, g=g, h=h: f(g(h(x))) ident = lambda x: x
Even with just over a dozen lines, many of these combinatorial functions are merely convenience functions that wrap other more general ones. Let us take a look at how we can use these HOFs to simplify some of the earlier examples. The same names are used for results, so look above for comparisons:
# Don't nest filters, just produce func that does both short_regvals = filter(both(shortline, isRegVal), lines) # Don't multiply ad hoc functions, just describe need regroot_lines = \ filter(some([isRegDBRoot, isRegDBKey, isRegDBVal]), lines) # Don't nest transformations, make one combined transform capFlipNorm = compose3(upper, flip, normalize) cap_flip_norms = map(capFlipNorm, lines)
In the example, we bind the composed function capFlipNorm for readability. The corresponding map() line expresses just the single thought of applying a common operation to all the lines. But the binding also illustrates some of the flexibility of combinatorial functions. By condensing the several operations previously nested in several map() calls, we can save the combined operation for reuse elsewhere in the program.
As a rule of thumb, I recommend not using more than one filter() and one map() in any given line of code. If these "list application" functions need to nest more deeply than this, readability is preserved by saving results to intermediate names. Successive lines of such functional programming style calls themselves revert to a more imperative style?but a wonderful thing about Python is the degree to which it allows seamless combinations of different programming styles. For example:
intermed = filter(niceProperty, map(someTransform, lines)) final = map(otherTransform, intermed)
Any nesting of successive filter () or map() calls, however, can be reduced to single functions using the proper combinatorial HOFs. Therefore, the number of procedural steps needed is pretty much always quite small. However, the reduction in total lines-of-code is offset by the lines used for giving names to combinatorial functions. Overall, FP style code is usually about one-half the length of imperative style equivalents (fewer lines generally mean correspondingly fewer bugs).
A nice feature of combinatorial functions is that they can provide a complete Boolean algebra for functions that have not been called yet (the use of operator.add and operator.mul in combinatorial.py is more than accidental, in that sense). For example, with a collection of simple values, you might express a (complex) relation of multiple truth values as:
satisfied = (this or that) and (foo or bar)
In the case of text processing on chunks of text, these truth values are often the results of predicative functions applied to a chunk:
satisfied = (thisP(s) or thatP(s)) and (fooP(s) or barP(s))
In an expression like the above one, several predicative functions are applied to the same string (or other object), and a set of logical relations on the results are evaluated. But this expression is itself a logical predicate of the string. For naming clarity?and especially if you wish to evaluate the same predicate more than once?it is convenient to create an actual function expressing the predicate:
satisfiedP = both(either(thisP,thatP), either(fooP,barP))
Using a predicative function created with combinatorial techniques is the same as using any other function:
selected = filter(satisfiedP, lines)
The module combinatorial.py presented above provides some of the most commonly useful combinatorial higher-order functions. But there is room for enhancement in the brief example. Creating a personal or organization library of useful HOFs is a way to improve the reusability of your current text processing libraries.
Python comes with an excellent collection of standard datatypes?Appendix A discusses each built-in type. At the same time, an important principle of Python programming makes types less important than programmers coming from other languages tend to expect. According to Python's "principle of pervasive polymorphism" (my own coinage), it is more important what an object does than what it is. Another common way of putting the principle is: if it walks like a duck and quacks like a duck, treat it like a duck.
Broadly, the idea behind polymorphism is letting the same function or operator work on things of different types. In C++ or Java, for example, you might use signature-based method overloading to let an operation apply to several types of things (acting differently as needed). For example:
#include <stdio.h> class Print { public: void print(int i) { printf("int %d\n", i); } void print(double d) { printf("double %f\n", d); } void print(float f) { printf("float %f\n", f); } }; main() { Print *p = new Print(); p->print(37); /* --> "int 37" */ p->print(37.0); /* --> "double 37.000000" */ }
The most direct Python translation of signature-based overloading is a function that performs type checks on its argument(s). It is simple to write such functions:
def Print(x): from types import * if type(x) is FloatType: print "float", x elif type(x) is IntType: print "int", x elif type(x) is LongType: print "long", x
Writing signature-based functions, however, is extremely un-Pythonic. If you find yourself performing these sorts of explicit type checks, you have probably not understood the problem you want to solve correctly! What you should (usually) be interested in is not what type x is, but rather whether x can perform the action you need it to perform (regardless of what type of thing it is strictly).
Probably the single most common case where pervasive polymorphism is useful is in identifying "file-like" objects. There are many objects that can do things that files can do, such as those created with urllib, cStringIO, zipfile, and by other means. Various objects can perform only subsets of what actual files can: some can read, others can write, still others can seek, and so on. But for many purposes, you have no need to exercise every "file-like" capability?it is good enough to make sure that a specified object has those capabilities you actually need.
Here is a typical example. I have a module that uses DOM to work with XML documents; I would like users to be able to specify an XML source in any of several ways: using the name of an XML file, passing a file-like object that contains XML, or indicating an already-built DOM object to work with (built with any of several XML libraries). Moreover, future users of my module may get their XML from novel places I have not even thought of (an RDBMS, over sockets, etc.). By looking at what a candidate object can do, I can just utilize whichever capabilities that object has:
def toDOM(xml_src=None): from xml.dom import minidom if hasattr(xml_src, 'documentElement'): return xml_src # it is already a DOM object elif hasattr(xml_src,'read'): # it is something that knows how to read data return minidom.parseString(xml_src.read()) elif type(xml_src) in (StringType, UnicodeType): # it is a filename of an XML document xml = open(xml_src).read() return minidom.parseString(xml) else: raise ValueError, "Must be initialized with " +\ "filename, file-like object, or DOM object"
Even simple-seeming numeric types have varying capabilities. As with other objects, you should not usually care about the internal representation of an object, but rather about what it can do. Of course, as one way to assure that an object has a capability, it is often appropriate to coerce it to a type using the built-in functions complex(), dict(), float(), int(), list(), long(), str(), tuple(), and unicode(). All of these functions make a good effort to transform anything that looks a little bit like the type of thing they name into a true instance of it. It is usually not necessary, however, actually to transform values to prescribed types; again we can just check capabilities.
For example, suppose that you want to remove the "least significant" portion of any number?perhaps because they represent measurements of limited accuracy. For whole numbers?ints or longs?you might mask out some low-order bits; for fractional values you might round to a given precision. Rather than testing value types explicitly, you can look for numeric capabilities. One common way to test a capability in Python is to try to do something, and catch any exceptions that occur (then try something else). Below is a simple example:
def approx(x): # int attributes require 2.2+ if hasattr(x,'__and__'): # supports bitwise-and return x & ~OxOFL try: # supports real/imag return (round(x.real,2)+round(x.imag,2)*1j) except AttributeError: return round(x,2)
The reason that the principle of pervasive polymorphism matters is because Python makes it easy to create new objects that behave mostly?but not exactly?like basic datatypes. File-like objects were already mentioned as examples; you may or may not think of a file object as a datatype precisely. But even basic datatypes like numbers, strings, lists, and dictionaries can be easily specialized and/or emulated.
There are two details to pay attention to when emulating basic datatypes. The most important matter to understand is that the capabilities of an object?even those utilized with syntactic constructs?are generally implemented by its "magic" methods, each named with leading and trailing double underscores. Any object that has the right magic methods can act like a basic datatype in those contexts that use the supplied methods. At heart, a basic datatype is just an object with some well-optimized versions of the right collection of magic methods.
The second detail concerns exactly how you get at the magic methods?or rather, how best to make use of existing implementations. There is nothing stopping you from writing your own version of any basic datatype, except for the piddling details of doing so. However, there are quite a few such details, and the easiest way to get the functionality you want is to specialize an existing class. Under all non-ancient versions of Python, the standard library provides the pure-Python modules UserDict, UserList, and UserString as starting points for custom datatypes. You can inherit from an appropriate parent class and specialize (magic) methods as needed. No sample parents are provided for tuples, ints, floats, and the rest, however.
Under Python 2.2 and above, a better option is available. "New-style" Python classes let you inherit from the underlying C implementations of all the Python basic datatypes. Moreover, these parent classes have become the self-same callable objects that are used to coerce types and construct objects: int(), list(), unicode(), and so on. There is a lot of arcana and subtle profundities that accompany new-style classes, but you generally do not need to worry about these. All you need to know is that a class that inherits from string is faster than one that inherits from UserString; likewise for list versus UserList and dict versus UserDict (assuming your scripts all run on a recent enough version of Python).
Custom datatypes, however, need not specialize full-fledged implementations. You are free to create classes that implement "just enough" of the interface of a basic datatype to be used for a given purpose. Of course, in practice, the reason you would create such custom datatypes is either because you want them to contain non-magic methods of their own or because you want them to implement the magic methods associated with multiple basic datatypes. For example, below is a custom datatype that can be passed to the prior approx() function, and that also provides a (slightly) useful custom method:
>>> class I: # "Fuzzy" integer datatype ... def __init__(self, i): self.i = i ... def __and__(self, i): return self.i & i ... def err_range(self): ... lbound = approx(self.i) ... return "Value: [%d, %d)" % (lbound, lbound+0x0F) ... >>> i1, i2 = I(29), I(20) >>> approx(i1), approx(i2) (16L, 16L) >>> i2.err_range() 'Value: [16, 31)'
Despite supporting an extra method and being able to get passed into the approx() function, I is not a very versatile datatype. If you try to add, or divide, or multiply using "fuzzy integers," you will raise a TypeError. Since there is no module called Userlnt, under an older Python version you would need to implement every needed magic method yourself.
Using new-style classes in Python 2.2+, you could derive a "fuzzy integer" from the underlying int datatype. A partial implementation could look like:
>>> class I2(int): # New-style fuzzy integer ... def __add__(self, j): ... vals = map(int, [approx(self), approx(j)]) ... k = int.__add__(*vals) ... return I2(int.__add__(k, 0x0F)) ... def err_range(self): ... lbound = approx(self) ... return "Value: [%d, %d)" %(lbound,lbound+0x0F) ... >>> i1, i2 = I2(29), I2(20) >>> print "i1 =", i1.err_range(),": i2 =", i2.err_range() i1 = Value: [16, 31) : i2 = Value: [16, 31) >>> i3 = i1 + i2 >>> print i3, type(i3) 47 <class '__main__.I2'>
Since the new-style class int already supports bitwise-and, there is no need to implement it again. With new-style classes, you refer to data values directly with self, rather than as an attribute that holds the data (e.g., self.i in class I). As well, it is generally unsafe to use syntactic operators within magic methods that define their operation; for example, I utilize the .__add__() method of the parent int rather than the + operator in the I2.__add__() method.
In practice, you are less likely to want to create number-like datatypes than you are to emulate container types. But it is worth understanding just how and why even plain integers are a fuzzy concept in Python (the fuzziness of the concepts is of a different sort than the fuzziness of I2 integers, though). Even a function that operates on whole numbers need not operate on objects of IntType or LongType?just on an object that satisfies the desired protocols.
There are several magic methods that are often useful to define for any custom datatype. In fact, these methods are useful even for classes that do not really define datatypes (in some sense, every object is a datatype since it can contain attribute values, but not every object supports special syntax such as arithmetic operators and indexing). Not quite every magic method that you can define is documented in this book, but most are under the parent datatype each is most relevant to. Moreover, each new version of Python has introduced a few additional magic methods; those covered either have been around for a few versions or are particularly important.
In documenting class methods of base classes, the same general conventions are used as for documenting module functions. The one special convention for these base class methods is the use of self as the first argument to all methods. Since the name self is purely arbitrary, this convention is less special than it might appear. For example, both of the following uses of self are equally legal:
>>> import string >>>>> object.__repr__(self) '<str object at 0x12c0a0>' >>> string.upper(self) 'SPAM'
However, there is usually little reason to use class methods in place of perfectly good built-in and module functions with the same purpose. Normally, these methods of datatype classes are used only in child classes that override the base classes, as in:
>>> class UpperObject(object): ... def __repr__(self): ... return object.__repr__(self).upper() ... >>> uo = UpperObject() >>> print uo <__MAIN__.UPPEROBJECT OBJECT AT 0X1C2C6C>
Under Python 2.2+, object has become a base for new-style classes. Inheriting from object enables a custom class to use a few new capabilities, such as slots and properties. But usually if you are interested in creating a custom datatype, it is better to inherit from a child of object, such as list, float, or dict.
Return a Boolean comparison between self and other. Determines how a datatype responds to the == operator. The parent class object does not implement . __eq__() since by default object equality means the same thing as identity (the is operator). A child is free to implement this in order to affect comparisons.
Return a Boolean comparison between self and other. Determines how a datatype responds to the != and <> operators. The parent class object does not implement .__ne__() since by default object inequality means the same thing as nonidentity (the is not operator). Although it might seem that equality and inequality always return opposite values, the methods are not explicitly defined in terms of each other. You could force the relationship with:
>>> class EQ(object): ... # Abstract parent class for equality classes ... def __eq__(self, o): return not self <> o ... def __ne__(self, o): return not self == o ... >>> class Comparable(EQ): ... # By def'ing inequlty, get equlty (or vice versa) ... def __ne__(self, other): ... return someComplexComparison(self, other)
Return a Boolean value for an object. Determines how a datatype responds to the Boolean comparisons or, and, and not, and to if and filter(None,...) tests. An object whose .__nonzero__() method returns a true value is itself treated as a true value.
Return an integer representing the "length" of the object. For collection types, this is fairly straightforward?how many objects are in the collection? Custom types may change the behavior to some other meaningful value.
Return a string representation of the object self. Determines how a datatype responds to the repr() and str() built-in functions, to the print keyword, and to the back-tick operator.
Where feasible, it is desirable to have the .__repr__() method return a representation with sufficient information in it to reconstruct an identical object. The goal here is to fulfill the equality obj==eval(repr(obj)). In many cases, however, you cannot encode sufficient information in a string, and the repr() of an object is either identical to, or slightly more detailed than, the str() representation of the same object.
SEE ALSO: repr 96; operator 47;
Under Python 2.2+, it is possible to create a custom file-like object by inheriting from the built-in class file. In older Python versions you may only create file-like objects by defining the methods that define an object as "file-like." However, even in recent versions of Python, inheritance from file buys you little?if the data contents come from somewhere other than a native filesystem, you will have to reimplement every method you wish to support.
Even more than for other object types, what makes an object file-like is a fuzzy concept. Depending on your purpose you may be happy with an object that can only read, or one that can only write. You may need to seek within the object, or you may be happy with a linear stream. In general, however, file-like objects are expected to read and write strings. Custom classes only need implement those methods that are meaningful to them and should only be used in contexts where their capabilities are sufficient.
In documenting the methods of file-like objects, I adopt a slightly different convention than for other built-in types. Since actually inheriting from file is unusual, I use the capitalized name FILE to indicate a general file-like object. Instances of the actual file class are examples (and implement all the methods named), but other types of objects can be equally good FILE instances.
Return a file object that attaches to the filename fname. The optional argument mode describes the capabilities and access style of the object. An r mode is for reading; w for writing (truncating any existing content); a for appending (writing to the end). Each of these modes may also have the binary flag b for platforms like Windows that distinguish text and binary files. The flag + may be used to allow both reading and writing. The argument buffering may be 0 for none, 1 for line-oriented, a larger integer for number of bytes.
>>> open('tmp','w').write('spam and eggs\n') >>> print open('tmp','r').read(), spam and eggs >>> open('tmp','w').write('this and that\n') >>> print open('tmp','r').read(), this and that >>> open('tmp','a').write('something else\n') >>> print open('tmp','r').read(), this and that something else
Close a file object. Reading and writing are disallowed after a file is closed.
Return a Boolean value indicating whether the file has been closed.
Return a file descriptor number for the file. File-like objects that do not attach to actual files should not implement this method.
Write any pending data to the underlying file. File-like objects that do not cache data can still implement this method as pass.
Return a Boolean value indicating whether the file is a TTY-like device. The standard documentation says that file-like objects that do not attach to actual files should not implement this method, but implementing it to always return 0 is probably a better approach.
Attribute containing the mode of the file, normally identical to the mode argument passed to the object's initializer.
The name of the file. For file-like objects without a filesystem name, some string identifying the object should be put into this attribute.
Return a string containing up to size bytes of content from the file. Stop the read if an EOF is encountered or upon another condition that makes sense for the object type. Move the file position forward immediately past the read in bytes. A negative size argument is treated as the default value.
Return a string containing one line from the file, including the trailing newline, if any. A maximum of size bytes are read. The file position is moved forward past the read. A negative size argument is treated as the default value.
Return a list of lines from the file, each line including its trailing newline. If the argument size is given, limit the read to approximately size bytes worth of lines. The file position is moved forward past the read in bytes. A negative size argument is treated as the default value.
Move the file position by offset bytes (positive or negative). The argument whence specifies where the initial file position is prior to the move: 0 for BOF; 1 for current position; 2 for EOF.
Return the current file position.
Truncate the file contents (it becomes size length).
Write the string s to the file, starting at the current file position. The file position is moved forward past the written bytes.
Write the lines in the sequence lines to the file. No newlines are added during the write. The file position is moved forward past the written bytes.
Memory-efficient iterator over lines in a file. In Python 2.2+, you might implement this as a generator that returns one line per each yield.
SEE ALSO: xreadlines 72;
In Python, there are two standard datatypes for representing integers. Objects of type IntType have a fixed range that depends on the underlying platform?usually between plus and minus 2**31. Objects of type LongType are unbounded in size. In Python 2.2+, operations on integers that exceed the range of an int object results in automatic promotion to long objects. However, no operation on a long will demote the result back to an int object (even if the result is of small magnitude)?with the exception of the int() function, of course.
From a user point of view ints and longs provide exactly the same interface. The difference between them is only in underlying implementation, with ints typically being significantly faster to operate on (since they use raw CPU instructions fairly directly). Most of the magic methods integers have are shared by floating point numbers as well and are discussed below. For example, consult the discussion of float.__mul__() for information on the corresponding int.__mul__() method. The special capability that integers have over floating point numbers is their ability to perform bitwise operations.
Under Python 2.2+, you may create a custom datatype that inherits from int or long; under earlier versions, you would need to manually define all the magic methods you wished to utilize (generally a lot of work, and probably not worth it).
Each binary bit operation has a left-associative and a right-associative version. If you define both versions and perform an operation on two custom objects, the left-associative version is chosen. However, if you perform an operation with a basic int and a custom object, the custom right-associative method will be chosen over the basic operation. For example:
>>> class I(int): ... def __xor__(self, other): ... return "X0R" ... def __rxor__(self, other): ... return "RX0R" ... >>> 0xFF ^ 0xFF 0 >>> 0xFF ^ I(0xFF) 'RXOR' >>> I(0xFF) ^ 0xFF 'XOR' >>> I(0xFF) ^ I(0xFF) 'X0R'
Return a bitwise-and between self and other. Determines how a datatype responds to the & operator.
Return a hex string representing self. Determines how a datatype responds to the built-in hex() function.
Return a bitwise inversion of self. Determines how a datatype responds to the ~ operator.
Return the result of bit-shifting self to the left by other bits. The right-associative version shifts other by self bits. Determines how a datatype responds to the << operator.
Return an octal string representing self. Determines how a datatype responds to the built-in oct() function.
Return a bitwise-or between self and other. Determines how a datatype responds to the | operator.
Return the result of bit-shifting self to the right by other bits. The right-associative version shifts other by self bits. Determines how a datatype responds to the >> operator.
Return a bitwise-xor between self and other. Determines how a datatype responds to the ^ operator.
SEE ALSO: float 19; int 421; long 422; sys.maxint 50; operator 47;
Python floating point numbers are mostly implemented using the underlying C floating point library of your platform; that is, to a greater or lesser degree based on the IEEE 754 standard. A complex number is just a Python object that wraps a pair of floats with a few extra operations on these pairs.
Although the details are far outside the scope of this book, a general warning is in order. Floating point math is harder than you think! If you think you understand just how complex IEEE 754 math is, you are not yet aware of all of the subtleties. By way of indication, Python luminary and erstwhile professor of numeric computing Alex Martelli commented in 2001 (on <comp.lang.python>):
Anybody who thinks he knows what he's doing when floating point is involved IS either naive, or Tim Peters (well, it COULD be W. Kahan I guess, but I don't think he writes here).
Fellow Python guru Tim Peters observed:
I find it's possible to be both (wink). But nothing about fp comes easily to anyone, and even Kahan works his butt off to come up with the amazing things that he does.
Peters illustrated further by way of Donald Knuth (The Art of Computer Programming, Third Edition, Addison-Wesley, 1997; ISBN: 0201896842, vol. 2, p. 229):
Many serious mathematicians have attempted to analyze a sequence of floating point operations rigorously, but found the task so formidable that they have tried to be content with plausibility arguments instead.
In the hierarchy of Python numeric types, floating point numbers are higher up the scale than integers, and complex numbers higher than floats. That is, operations on mixed types get promoted upwards. However, the magic methods that make a datatype "float-like" are strictly a subset of those associated with integers. All of the magic methods listed below for floats apply equally to ints and longs (or integer-like custom datatypes). Complex numbers support a few addition methods.
Under Python 2.2+, you may create a custom datatype that inherits from float or complex; under earlier versions, you would need to manually define all the magic methods you wished to utilize (generally a lot of work, and probably not worth it).
Each binary operation has a left-associative and a right-associative version. If you define both versions and perform an operation on two custom objects, the left-associative version is chosen. However, if you perform an operation with a basic datatype and a custom object, the custom right-associative method will be chosen over the basic operation. See the example under int.
Return the absolute value of self. Determines how a datatype responds to the built-in function abs().
Return the sum of self and other. Determines how a datatype responds to the + operator. the ratio of self and other. Determines how a datatype responds to the / operator. In Python 2.3+, this method will instead determine how a datatype responds to the floor division operator //.
Return the pair (div, remainder). Determines how a datatype responds to the built-in divmod() function.
Return the number of whole times self goes into other. Determines how a datatype responds to the Python 2.2+ floor division operator //.
Return the modulo division of self into other. Determines how a datatype responds to the % operator.
Return the product of self and other. Determines how a datatype responds to the * operator.
Return the negative of self. Determines how a datatype responds to the unary - operator.
Return self raised to the other power. Determines how a datatype responds to the ^ operator.
Return the difference between self and other. Determines how a datatype responds to the binary - operator.
Return the ratio of self and other. Determines how a datatype responds to the Python 2.3+ true division operator /.
SEE ALSO: complex 22; int 18; float 422; operator 47;
Complex numbers implement all the above documented methods of floating point numbers, and a few additional ones.
Inequality operations on complex numbers are not supported in recent versions of Python, even though they were previously. In Python 2.1+, the methods complex.__ge__(), complex.__gt__(), complex.__le__(), and complex.__lt__() all raise TypeError rather than return Boolean values indicating the order. There is a certain logic to this change inasmuch as complex numbers do not have a "natural" ordering. But there is also significant breakage with this change?this is one of the few changes in Python, since version 1.4 when I started using it, that I feel was a real mistake. The important breakage comes when you want to sort a list of various things, some of which might be complex numbers:
>>> lst = ["string", 1.0, 1, 1L, ('t','u' , 'p')] >>> lst.sort() >>> 1st [1.0, 1, 1L, 'string', ('t', 'u', 'p')] >>> lst.append(1j) >>> lst.sort() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >=
It is true that there is no obvious correct ordering between a complex number and another number (complex or otherwise), but there is also no natural ordering between a string, a tuple, and a number. Nonetheless, it is frequently useful to sort a heterogeneous list in order to create a canonical (even if meaningless) order. In Python 2.2+, you can remedy this shortcoming of recent Python versions in the style below (under 2.1 you are largely out of luck):
>>> class C(complex): ... def __lt__(self, o): ... if hasattr(o, 'imag'): ... return (self.real,self.imag) < (o.real,o.imag) ... else: ... return self.real < o ... def __le__(self, o): return self < o or self==o ... def __gt__(self, o): return not (self==o or self < o) ... def __ge__(self, o): return self > o or self==o ... >>> 1st = ["str", 1.0, 1, 1L, (1,2,3), C(1+1j), C(2-2j)] >>> lst.sort() >>> 1st [1.0, 1, 1L, (1+1j), (2-2j), 'str', (1, 2, 3)]
Of course, if you adopt this strategy, you have to create all of your complex values using the custom datatype C. And unfortunately, unless you override arithmetic operations also, a binary operation between a C object and another number reverts to a basic complex datatype. The reader can work out the details of this solution if she needs it.
Return the complex conjugate of self. A quick refresher here: If self is n+mj its conjugate is n-mj.
Imaginary component of a complex number.
Real component of a complex number.
SEE ALSO: float 19; complex 422;
Dictionaries in Python provide a well-optimized mapping between immutable objects and other Python objects (see Glossary entry on "immutable"). You may create custom datatypes that respond to various dictionary operations. There are a few syntactic operations associated with dictionaries, all involving indexing with square braces. But unlike with numeric datatypes, there are several regular methods that are reasonable to consider as part of the general interface for dictionary-like objects.
If you create a dictionary-like datatype by subclassing from UserDict.UserDict, all the special methods defined by the parent are proxies to the true dictionary stored in the object's .data member. If, under Python 2.2+, you subclass from dict itself, the object itself inherits dictionary behaviors. In either case, you may customize whichever methods you wish. Below is an example of the two styles for subclassing a dictionary-like datatype:
>>> from sys import stderr >>> from UserDict import UserDict >>> class LogDictOld(UserDict): ... def __setitem__(self, key, val): ... stderr.write("Set: "+str(key)+"->"+str(val)+"\n") ... self.data[key] = val ... >>> ldo = LogDict0ld() >>> ldo['this'] = 'that' Set: this->that >>> class LogDictNew(dict): ... def __setitem__(self, key, val): ... stderr.write("Set: "+str(key)+"->"+str(val)+"\n") ... dict.__setitem__(self, key, val) ... >>> ldn = LogDict0ld() >>> ldn['this'] = 'that' Set: this->that a Boolean value indicating whether self "contains" the value x. By default, being contained in a dictionary means matching one of its keys, but you can change this behavior by overriding it (e.g., check whether x is in a value rather th | https://etutorials.org/Programming/Python.+Text+processing/Chapter+1.+Python+Basics/1.1+Techniques+and+Patterns/ | CC-MAIN-2022-21 | refinedweb | 6,880 | 56.55 |
Solutions will be available when this assignment is resolved, or after a few failing attempts.
Your first function
Let's start writing a really simple (close to dumb) function. We want you to completely understand the syntax and wrap your mind around them.
At the editor at the right you'll see a simple function defined. That's a valid python function. Now replace the empty string with your name (we'll learn more about strings later). For me, the function looks something like this:
def return_your_name(): return 'Santiago'
Try the function
Now try uncommenting the lines at the bottom of the editor and using the Run Code button to see how it works. You should see your name printed out in the screen. Both examples (1 and 2) are identical. They're doing the same thing. The only difference is that the first one is just storing the value returned by the
return_your_name function in an intermediate variable. | https://learn.rmotr.com/python/free-python-course/functions/your-first-function | CC-MAIN-2018-13 | refinedweb | 159 | 74.19 |
05 August 2010 09:34 [Source: ICIS news]
By Heng Hui
SINGAPORE (ICIS)--Methanol prices in Asia are likely to maintain an uptrend due to tight regional supply and a force majeure at Kharg Petrochemical Co's (KPC) 660,000 tonne/year plant in Iran, industry sources said on Thursday.
KPC declared the force majeure last week for August-September supplies, after its methanol unit was shut on 24 July following a deadly explosion in the plant's central boiler. Four employees were killed by the blast.
The company had informed its contractual customers about the force majeure, said a company source.
KPC sold its product mainly in China, Korea and Europe, according to the source.
A distributor based in Asia confirmed that he had stopped receiving methanol supply from KPC, adding that he was currently supplementing his stock from other sources in the ?xml:namespace>
Methanol supply in Asia had tightened since mid-July, due to the limited availability of cargo from Iran on the back of increased sanctions against the country and also because of recent outages at some plants in southeast Asia, market sources said.
Malaysian state-owned oil major Petronas had declared a force majeure at its 2.36m tonne/year methanol facilities in
The tight supply had led to a $5.00-15.00/tonne (€3.80-11.40/tonne) rise in Asia's methanol prices since mid-July and market players said that they could rise even further. Methanol was trading at $250-255/tonne CFR (cost & freight) China/Korea on 30 July, according to ICIS data.
Traders and distributors had a mixed reaction to the force majeure and its impact on methanol price outlook.
“The impact of [Kharg’s shutdown] was not great, as demand in August was not good," said a distributor.
A major Korea-based distributor said that prices were on an uptrend for reasons other than KPC's force majeure, as the company's capacity was small in comparison to other suppliers.
However, a distributor that dealt in the key.Methanol is used in the production of formaldehyde, methyl tertiary butyl ether, acetic acid, methyl methacrylate and other chemicals.
Other methanol producers in the Middle East include Saudi Basic Industries Corp (SABIC) Sabic and Iran's National Petrochemical Co.
($1= €0.76) | http://www.icis.com/Articles/2010/08/05/9382354/asia-methanol-prices-seen-firm-on-fm-and-tight-supply.html | CC-MAIN-2014-42 | refinedweb | 382 | 59.03 |
Skip to 0 minutes and 8 secondsWIM: Hello everyone. In this short lecture, I want to explain some basics of Haskell through examples from other languages that you might know. I will explain expressions, functions, types, and lists just through example without any deep detail. So first, expressions. In almost any programming language, you can write expressions such as, for example-- and you can bind these to variables so that this expression value is contained in that variable. In Haskell, you can do the same thing, and what is more, in Haskell there are only expressions, whereas in most imperative languages there are statements and expressions. Haskell only has expressions. So the next basic element of Haskell is, of course, functions.
Skip to 1 minute and 0 secondsAnd we can compare functions in Haskell, for instance, with functions in Python. In Python you might write something like-- so you define a function, hello, which takes an argument, name, and you return a string composed of the string, hello, and combined with name. So in Haskell you can do something quite similar, only a bit shorter.
Skip to 1 minute and 42 secondsSo Haskell has very compact syntax where you don't need parentheses to identify function arguments. You just use spaces. And the concatenation operator is separate from the addition operator.
Skip to 2 minutes and 13 secondsThe next basic element of Haskell is types. Types are very important in Haskell, and we will talk a lot about it, but for now we just want to give an example based on types in languages that you might know like C or Java. So for example, in C you could define a function like this.
Skip to 2 minutes and 42 secondsSo we have a function that takes two integers and returns an integer. So in Haskell we can write something similar, but the main difference is that the type declarations and the function definitions are separate. So we start with the type declaration. That would be-- so the double colon indicates that a type declaration follows. And then we have the first argument is an integer. The second argument is an integer. The return value is an integer. Then the function definition.
Skip to 3 minutes and 20 secondsSo again, essentially the same thing but much more compact. So the final basic element of Haskell that I want to discuss is lists. In many languages, such as Ruby, JavaScript, and Python, you can write lists like this.
Skip to 3 minutes and 44 secondsAnd, in fact, in Haskell this is exactly the same. So this is valid Haskell code. So lists are a very important component of the Haskell language. We'll talk a lot more about them in future classes.
Basic Elements By Example
Expressions
In almost all programming languages you can create expressions such as:
(b*b-4*a*c)/2*a
and you can assign these expressions to variables:
v = (b*b-4*a*c)/2*a
In
Haskell, you can do this as well, and what’s more: expressions are really all there is, there are no statements.
Functions
In
Python, you can define a function such as
def hello(name): return "Hello, "+name
In
Haskell you can write this simply as:
hello name = "Hello, "++name
Types
C has types, for example:
int f (int x, int y) { return x*y+x+y; }
Haskell has much more powerful types than
C, and we will talk a lot about types:
f :: Int -> Int -> Int f x y = x*y+x+y
Lists
In many languages, e.g. Python, JavaScript, Ruby, … you can create lists such as:
lst = [ "A", "list", "of", "strings"]
Haskell also uses this syntax for lists.
To join lists, in
Python you could write
lst = [1,2] + [3,4]
In
Haskell this would be very similar:
lst = [1,2] ++ [3,4]
Anonymous functions
In
JavaScript you can define anonymous functions (functions without a name) such as:
var f = function(x,y){return x*y+x+y};
In
Haskell, such anonymous functions are called lambda functions and they are actually the basis of the language. Again, the syntax is very compact:
f = \x y -> x*y+x+y
Higher-order functions
Finally, in many languages, functions can operate on functions. For example, in
Perl you can modify the elements in a list using:
map sub ($x){$x*2+1}, [1..10]
Haskell provides many of these so-called higher-order functions, and lets you define your own.
map (\x -> x*2+1) [1..10]
© Wim Vanderbauwhede | https://www.futurelearn.com/courses/functional-programming-haskell/0/steps/27193 | CC-MAIN-2019-35 | refinedweb | 760 | 70.73 |
Ok, I have had my arduino for a week now, and have been having lots of fun with it. Now I am trying to write a program that will control the temp of a item. The problem that I am having is adjusting the set point up and down. just wont do it. Here is my code so far. I tried to do it from the Java console and I received nothing but errors but here it is.
#include <LiquidCrystal.h>
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7);
int setPup = 3; // setpoint up
int setDown = 10; // setpoint down
int analogPin = 0; // voltage divider network on pin analog 0
// it will become pin 1 for the Thermister.
int val = 0; // where it will store the input
int setpoint = 250; // trying to get a setpoint for temp control
void setup()
{
lcd.begin(20, 2); // this gave me a head ache for a few days, I thought my display was bad lol
Serial.begin(9600); // setup serial, and testing for me.
pinMode (setPup, INPUT); // raise setpoint
pinMode (setDown, INPUT); // lower setpoint
}
void loop()
{
val = analogRead(analogPin); // read the input pin
val = map(val, 0, 1023, 0, 350); // remapped the value for the smokers temp probe
Serial.println(val); // bug checking
lcd.setCursor(0,0); // sets the position of the cursor
lcd.print(“dans smoker”); // it belonges to him
lcd.setCursor(13,0); // this is where the temp goes
lcd.print(val); // mapped version of the temp on screen
lcd.setCursor(13,1); // set the cursor for setpoint display
lcd.print(setpoint); // setpoint display
delay(500); // needs to be removed after it is running
if (setPup > 1) ++ setpoint;
if (setDown > 1) – setpoint;
} | https://forum.arduino.cc/t/trying-to-adjust-a-setpoint/43311 | CC-MAIN-2022-05 | refinedweb | 279 | 74.08 |
china product
US $4-7 / Piece
1 Piece (Min. Order)
China products carbon seamless steel pipe
US $1100-1600 / Ton
10 Tons (Min. Order)
Zhongkuang new product api 5ct L80 steel casing pipe made in china
US $700-800 / Ton
20 Tons (Min. Order)
china products steel square pipes fair price
US $300-500 / Ton
5 Tons (Min. Order)
new products cross-linked polyethylene pipe made in china
US $420.0-420.0 / Tons
20 Tons (Min. Order)
China top ten sale product, flange annular corrugated steel pipe, integrated culvert pipe
US $500-2000 / Meter
10 Meters (Min. Order)
Hot product china supplier led hanging tent bulb, 1SMD work lamp, high power led lamp with battery
US $0.7-2 / Piece
1000 Pieces (Min. Order)
China manufacturing hot housing product bluetooth music color changing E27 china led bulb
US $8-15 / Piece
1 Piece (Min. Order)
china supplier new products 100% biodegradable plastic trash bags
US $0.01-0.1 / Pieces
50000 Pieces (Min. Order)
China New Product Best Selling Non Toxic Package Custom Pineapple Designer Poly Mailer 10X13
US $0.02-0.15 / Piece
20000 Pieces (Min. Order)
China product ningbo C37L E14/E27 6.5W led candle bulb home
US $0.5-1 / Piece
200 Pieces (Min. Order)
New Products China Manufacturer 100% Cotton Hotel Beach Tassel Towels
US $8-16 / Piece
500 Pieces (Min. Order)
New Product China 3.5W Lamp C35 6500K E27 Led Filament Bulb
US $1-5 / Piece
1000000 Pieces (Min. Order)
Made in china products cheap led intelligent emergency bulbs high quality
US $0.82-0.95 / Piece
1000 Pieces (Min. Order)
China products small biodegradable clear plastic packaging bag with window
US $0.01-0.1 / Piece
10000 Pieces (Min. Order)
China factory wholesale new product 2016 fashion microfiber bath dresses for women
US $1.05-1.37 / Piece
1000 Pieces (Min. Order)
China wholesalers new products 220v 3w 5w 7w 9w 12w led bulb lights best-selling all over the world 3w e27 led bulb
US $0.91-0.91 / Pieces
1000 Pieces (Min. Order)
import china goods wholesale cheap products custom logo brand promotional non woven drawstring shoe bag
US $0.09-1.9 / Piece
100 Pieces (Min. Order)
China products vintage cylinder filament bulb led dimmable lamp 2w 4w 6w 8w match dimmer
US $1.5-3.5 / Piece
1 Piece (Min. Order)
Alibaba China New Product Recycle Shopping Paper Bag Rope Handles
US $0.08-0.78 / Piece
1000 Pieces (Min. Order)
New products china express led bulb g95 Sprial/quad/w-cross style decorative lighting
US $3.16-4.94 / Piece
1 Piece (Min. Order)
Customize Any Size LDPE Colored China Supplier New Products Plastic Trash Bag
US $0.025-0.1 / Piece
100000 Pieces (Min. Order)
New product alibaba china Clear / Frosted / Milky White glass cover b22 8w globe led filament bulb
US $1.2-2.8 / Piece
10 Pieces (Min. Order)
china suppliers new innovative products paper bag wholesale
US $0.2-0.76 / Piece
1000 Pieces (Min. Order)
Wholesale New China Products For Sale Coloured Bluetooth Speaker Led Bulb Light Bar
US $13-16 / Piece
1 Piece (Min. Order)
2015 new china supplier best selling product zipper bag for sugar packing
US $0.002-0.06 / Piece
10000 Pieces (Min. Order)
China supplier new products 100% biodegradable plastic bags
US $0.01-0.1 / Piece
10000 Pieces (Min. Order)
2017 hot New Products china supplier 100%cotton velvet towel photo printed round towel beach
US $2.5-6 / Piece
500 Pieces (Min. Order)
China Supplier new products cheap garage door opener, garage door motor, rubber seal for garage door
US $200-500 / Set
1 Set (Min. Order)
Wholesale Fashion China Products 100 Polyester Fabric And Textile
US $0.9-3 / Meter
800 Meters (Min. Order)
China suppliers new products woven sacks 25kg
US $0.05-0.2 / Piece
50000 Pieces (Min. Order)
China Top Ten Selling Products E40 led light bulbs 40w
US $18-20 / Piece
1 Piece (Min. Order)
Good sale quality china factory products of pp woven bags
US $0.05-2 / Piece
50000 Pieces (Min. Order)
2016 china products new steel wooden door, wooden single door/modern wood door designs
US $45-80 / Piece
1 Piece (Min. Order)
china top ten selling products teak wood main models wardrobe designs wood carving door
US $40-80 / Set
1 Set (Min. Order)
China Factory product AS2047 cheap hurricane impact Wood grain Aluminium sliding entry doors wholesale prices
US $80-200 / Square Meter
10 Square Meters (Min. Order)
Cottage plank barn door natural veneer new china products for sale
US $325-375 / Piece
50 Pieces (Min. Order)
Wholesale Products China Used Double Doors
US $40-100 / Piece
50 Pieces (Min. Order)
China Product G45 led bulb 3w,SMD G45 led bulb 3w,E14 SMD G45 led bulb 3w
US $1-4 / Piece
100 Pieces (Min. Order)
China new products 2016 led 7w e27 base lamp bulb cool white
US $2.8-7 / Piece
1 Carton (Min. Order)
2016 new product China supplier A19 A60 A65 A70 led lamp bulb, b22 led bulb light, led light bulb e27
US $0.1-0.98 / Piece
500 Pieces (Min. Order)
Alibaba China new product white recycle printing customized bali paper bag
US $0.35-1 / Piece
1000 Pieces (Min. Order)
new product China supplier g4 Led Bulb Lamp,Bulbs Led g4 1.5w 2w 3w 4W Led Lamp,chandelier pendants lights
US $0.66-0.73 / Piece
1 Piece (Min. Order)
2017 New product economic manufacturer cheap China selling well Led lamp bulb G45 E27 E14
US $0.34-0.88 / Piece
1 Piece (Min. Order)
China G9 LED High Quality product, AC110/220 LED Light Bulbs,G9 led cheap price light
US $0.7-1 / Piece
50 Pieces (Min. Order)
China products CE RoHS SMD2835 Plastsic led light bulb 7w
US $0.5-1.5 / Piece
1000 Pieces (Min. Order)
Portfolio Light Fixtures Replacement Parts, China Products, Lamps For Home
US $1.34-1.51 / Piece
1000 Pieces (Min. Order)
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show china product or other products of your own company? Display your Products FREE now! | http://www.alibaba.com/showroom/china-product.html | CC-MAIN-2017-43 | refinedweb | 1,042 | 77.23 |
I.
This is the schematic of PSL fss servo.
I have to make sure that the modulation voltage will not exceed the controller's limit (0-100V.)..
The maximum power after AOM double pass is 37%, worse than the expected 50% efficiency, but it should be enough.
The good news is, a new mode matching (RefCav and ACav) is calculated, and all positions for the lenses are clear.
I got all the lenses, and borrow one plcx-24.5-51.5-c-1064 from 58C
The problem about the position of the PBS is solved. It will be at the original place, since the clipped beam is the 0th order of the reflected beam which we do not use.
I'll put the lenses in their places and try to lock RefCav again..
Before, when we tried to lock the cavity, it seemed that the gain was too high, and the power output
from RefCav(C3:PSL-FSS_RCTRANSPD) fluctuated when both PC and Fast feedback were connected, and the data was measured when only Fast feedback was on.
So I try to change RF power to reduce the modulation index (hence, the gain.)
The value before was 6.5V, This time I tried 5.5 and 5.8 V.
At each RF power setting, I lock the cavity with
1) Fast feedback alone, and
2) both Fast and PC feedback
and measure the transmitted beam's RIN. The gain for each setup was readjust (see the values for each setup below)
so that the transmitted beam power was most stable as seen on an oscilloscope, then the data was taken.
The results are plotted below. It turns out that
when the PC feedback is connect, RIN becomes noisier. I don't no where
it comes from. It might be that the setting still has too high gain, or RFAM from broadband EOM due to misalignment,
or broken opamp in FSS PC path.
I'm still not sure why there are jumps at 100 Hz and 1k Hz. The sr785 is set at 4 different spans
which are, 0-100Hz, 0-1kHz,0-10kHz, and 0- 100kHz. Each span contains 800 FFT lines. The auto range is on.
The setting are [this will be updated soon]
1)RF5.5
Fast feedback: on
PC feedback: off
CG
FG
2) RF5.5
Fast: on
PC: on
CG:
FG:
3 RF 5.8
Fast: on
PC: off
4 RF 5.8).
After troubleshooting some supply power problems (apparently the top and bottom half of the breadboard power strips aren't connected???), I took some measurements on the following circuit that Andrew suggested, which had the desired properties in simulation. However, AD743's were not really available, so I used LT1012's instead, but it shouldn't make a difference for these measurements.
The output of the AD620 stage (see elog 1749) was as expected (with a .5Vp, .1Hz input, a 5Vp output), and this was used as the input to the buffer circuit:
The output of the buffer circuit was just 0V, so I took some intermediate measurements. The following is at the positive input to the first amplifier (aka after the 100k resistor):
And at the output of the first stage (aka Vout_1st):
From a hand-calculation, the noninverting input should be about 0.85Vin at 0.1Hz, so there's definitely something wrong there.
I tried just connecting Vin straight to a voltage follower, and that actually pulled down Vin:
I'd expect the input resistance to the op amp to be almost infinite, but here it almost looks like it's loading down the input signal, except for the fact that the shape is weird (kind of like clipping).
So, I'm not really sure what's going on. I'll try digging through the datasheet, testing the circuit in isolation (drive it straight from the function generator), and running a simulation that includes the first half of the circuit to see if that provides any insight.
Edit: Fixed hand calculation (used f instead of w earlier), but the gist is the same.
So after testing out the LT1012 op amp in many simple configurations and not having any of them work (and the measurements were the same whether they were powered or not), I decided to dig around for another op amp chip, which did work, so I think all 4 of LT1012 chips that I got from the 40m stock are just faulty (not sure what that means for the rest of the chips there).
After swapping out chips, the circuit worked functionally. Just from playing around with the function generator and oscilloscope, it looks like the gain is 0.5 around 20Hz (should be dropping off faster), but I'll try to get an actual frequency response measurement next time.
Also, the legs on the capacitors are really short and I'm not sure they're all actually making contact, so I'll probably extend them with some wire to be sure, but that might also be part of it.
Here is the data that was taken last week on the driver circuit.
At first there was a LF356 chip instead of the AD743, and it gave the following response:
Which looked reasonable, but it made sense to take noise measurements using 2 AD743s so I swapped it out, but then the response was this:
For some reason, the cutoff frequency moved to close to 100Hz. The noise measurement was:
I also tried replacing the 10uF capacitors with 22uF capacitors to try to move the cutoff frequency back down, and got the following response:
So that worked, but then the noise measurement went up by a lot:
I'm not sure what the noise requirements are, but it looks like using 10uF caps gives a pretty high cutoff frequency, but using 22uF caps increases the noise.
I also put in the BUF634 chip but when I powered it, I smelled something burning, so I'm going to test out that chip in isolation before trying to integrate it with the rest of the circuit.
Edit (11/17/2016): Attached Matlab workspace with relevant data, plotting script, and Andrew's freqStich script (used to combine noise measurements).
%s2-3 old chip tf
%s12-s17 10uF noise
%s18-19 10uF tf
%s20-21 22uF tf
%s23-27 22uF noise
close all
freq_array_1 = [s12_f s13_f s14_f s15_f s16_f s17_f];
data_array_1 = [s12_m s13_m s14_m s15_m s16_m s17_m];
%% This is a module for stiching spans of overlapping PSDs of different frequency bin size from SR785
%
% Assuming a logerithmic scale of frequency, it is desirable to
% stich the smaller frequecy ranges to the bottom of the larger ones
% wilst truncating out bins in the larger span.
%
%Feed in frequency matrix f(n,m) with correesponding floating point
%data(n,m).
%% Synopsis:
% [freqStitch,dataStitch] = freqStitch(freqPoints,dataPoints)
The burning last time came from the load resistor, which wasn't rated for high power. I made a test load from resistive tape that Andrew found and a heatsink, and this worked with the BUF634 output. A picture:.
I tried correcting for this offset in two ways.
1. First I tried to add an inverting input (from a voltage divider on the power rail) to cancel out the offset, adjusting the gain appropriately, but this added an insane amount of noise to the signal. I tried this on both the first and second stage.
2. I then tried the method outlined in the following document:, but this made no difference at all.
I also realized that I had been using the wrong input resistors (1k instead of 100k) before, which is why the cutoff frequency was so high before. I put in the 100k resistors, and with the 10uF capacitors, it gives a response that kind of makes sense (cutoff around 4Hz), except the ridiculously low gain which may be due to the DC offset (which unfortunately persists).
I am thinking about other ways to cancel out the DC offset. I think adding a third stage would be even worse than attempt 1. It's possible to just correct for this offset in software (especially since this offset would probably be different amongst the different circuits), but I don't know if this would be good practice?
I finished up taking frequency response and noise data on the circuit on the breadboard, swapped out the AD743s with OP27s and took data on that as well. The data is included later with the data from the protoboard circuit for comparison.
I built the circuit on the protoboard, and it looks like this:
Here are the frequency response measurements. Andrew took the first one (in blue), and I think I'm somehow misconfiguring the spectrum analyzer, because I took the other two and it looks like I'm measuring the right thing based on the shape, but the magnitude is all shifted down by ~55dB. I know from using the oscilloscope/function generator (see below) that the gain of the circuit is about as expected (definitely not -35dBV). The red blip is from when I accidently pulled out the gain resistor on the AD620. The other thing to note is that there's a lump around 60Hz on the protoboard.
Output shown on oscilloscope with 0.1Vpp input:
I forgot to save the phase measurements of the breadboard circuits, so this is of the protoboard circuit, but they all pretty much looked like this:
Here are noise measurements comparing the breadboard circuit and protoboard circuit (and also the AD743 vs OP27 circuit when applicable). First, at the output of the AD620:
At the output of the LP filter stage (it looks like this stage on the protoboard has the largest increase in noise):
At the output of the buffer stage:
And here's looking at all three points on the protoboard circuit:
Circuit schematic for reference:
I guess if all seems okay, I will just move on the building 2 more channels.
Attached: Matlab workspace with all data, relevant scripts for plotting
So I had a look at your circuit to see what was going on. I found that there was a strange offset at the instrument op amp (AD620) stage AND on your two LP filter buffering op amps.
So with the AD620, it has a dedicated 'ref' pin (pin 5). This sets the offset of the op amps output and can be used to reference the amplified output to whatever voltage you like (to within the range of the voltage rails). When I looked it was connected to ground, so that seemed right. I moved the AD620 to the larger breadboard to make things easier (I moved whatever you had set up with the AD829 one row along, sorry if you needed that). Once moved it worked fine, when I terminated the input (or shorted + and - of the op amp) it gave zero offset voltage. I'm not sure what changed, but it could have been a loose connection somewhere. So that stage seems good now. If you want some offset adjustability, this is the place to add it.
The two AD743 buffers for the active LP filter where introducing an offset of their own. You had all the unused pins connected to ground. This seems sensible most of the time. However, the AD743s have two pins that are dedicated to null function. These are supposed to be tied to the negative rail by an adjustable voltage bridge. If you ground them, they might do strange things as they both have zero voltage instead of some difference between zero and the negative rail. For more info just search for null in the datasheet. I removed the links to ground and the offset went away. If you really want to fine tune the offset you can make a voltage divider there but a potentiometer is highly not recommended for this stuff, it will make noise and pain down the track and not be stable. I think leaving the pins 1 and 5 open should be fine.
I didn't look at the noise, but the transfer function loops fine to me. Its giving about the right corner frequency (0.15 Hz) the 1/f^2 slope and above 320 Hz the attenutation is -100 dB. Looks good. Maybe stick the buffer in there, take some more transfer functions and have a look at the noise, probing at each stage of the current driver circuit (i.e. after the AD620, after the LP filter and after the buffer) with the input shorted with 50Ω.
We need to make a decision in choosing a LP filter stage op amp that isn't the AD743. The frustration is that manufactures don't just quote a common set of frequencies or sets of parameters that you can plot with. Zach Korth has obsessed a lot on this subject and made a really interesting post on the subject in PSL:1752 (see lower half of post). If you read nothing else, this week, read that. Also here is an almost helpful parameter search: . The best metric should be 0.1 to 1 Hz rms noise as that should be indicative of LF performance. However, as you see in Zach's post, the slope of the noise and corner frequency of roll up differs between types and designs of op amps. The opacity of specifications in these components is frustrating. It is almost as if they are obfuscating so they can sell less good components to people who don't know what they are doing.
The function that Zach mentions in PSL:1752 is somewhere on the 40m SVN. I think you'll find it if you poke around in SVN:/trunk/zach/tools/ ..
%2 TF (AD743)
%3-8 noise after buffer (AD743)
%9-12 noise after LP stage (AD743)
%13-16 noise after AD620
%17 TF (OP27)
%18-21 noise after buffer (OP27)
%22-25 noise after LP stage (OP27)
%26 TF on protoboard
%27 phase
%28-31 noise on board after buffer
I finished soldering together the other two channels for temperature control. This is what the board looks like now:
Front
Back
I began troubleshooting the new channels. The second channel (top right) is tentatively working up until the buffer stage, but showed some strange behaviors. When it is working up to the buffer stage, adding the buffer stage drive the output of each stage (and all of the corresponding inputs) to about +12V. When the buffer stage is removed, everything remains at +12V, but this is sometimes fixable by toggling the power, and consistently fixable by just pulling out the OP27 chips and putting them back in. As far as I can tell, everything is powered correctly, and nothing is shorting or disconnected where it shouldn't be.
For the third channel (bottom right), only the AD620 stage is working. Adding the next stage causes both the outputs and the inputs to go to +12V as well. The connections here also seem correct as far as I can tell. I'm thinking it's possibly related to the problems in the 2nd channel, maybe there's some buildup of charge, or other hysteresis, somewhere, that is messing things up. The observed behavior of this third channel is consistent enough that it may just be a connection error somewhere. The inconsistent behavior of the second channel, though, suggests that it probably has to do with something transient.
Will continue troubleshooting when I get back.
Andrew switched out the bypass capacitors to ceramic ones over break. Now all of the channels are functional, so I guess that was the problem (I don't know what the physical problem would have been before, though).
Here are some measurements of the frequency response.
Channel 1
Channel 2
Channel 3
Here's the noise. I don't know why it has the "edges", I'm pretty sure I made the measurements the same way as I was doing before and used the same stiching script... I might repeat these measurements later, but it's at least an idea.
Channel 1 has much higher noise. Possibly because there are power lines that cross over the area, whereas for 2 and 3 the power lines are routed from the side? Could be another reason though...
Data and scripts attached.
%another plotting script
%sorry the numbering is all out of order
%1-2 mag and phase channel 2
%3 - phase channel 3
%4 - phase channel 1
%5 - mag channel 1
%6 - mag channel 3
%7-10 noise channel 3
%11-14 noise channel 2
%15-18 noise channel 1
We did some more hardware integration for the temperature control loop yesterday. We first added a new input channel and a new output channel in the “IOCTEST_BIO_generic.db” file to correspond with one temperature measurement and one control output. We hooked up the driver circuit and confirmed that we could control the output signal from the computer GUI. We also hooked up the RTD sensor and corresponding measurement circuit and confirmed that we could get measurements that made sense. Pictures of the hardware are shown below:
Driver circuit board:
Sensor and measurement circuit:
I then made a couple of software updates to accommodate temperature control:
1. I edited the following GUI to have to appropriate indicators and controls. I left out the control channels that do not have corresponding hardware channels yet to avoid possible confusion. All (? at least most) of the soft channels are mapped.
2. I made a copy of the “IOCTEST_BIO_generic.db” file, “IOCTEST_BIO_generic_20170109_edit.db” and added in all of the soft channels. I also renamed the hardware output channel to follow a more specific naming convention (HEATERN, and later HEATERS and HEATERV (if that’s okay), as opposed to just HEATER1, 2, 3). Once the channels are more finalized, they’ll be put into a separate post for reference.
I also routed the inputs and outputs of the driver circuit to the connectors on the front. A separate post will be made with the pin assignments for reference.
The pin assignments for the heater driver circuit board are as follows:
I started playing around with simulating an attempt to automate PID tuning using the Ziegler Nichols method (using this as a reference:). I'm attaching the code I have been using.
The gist of what I'm trying to simulate:
-Increase Kp by some increment
-Get step response data from closed-loop system
-Fourier transform step response data to see if there are stable oscillations (currently done by comparing to some reference magnitude that I am guesstimating/trying to determine heuristically although once I do that, it might be able to be related to the Kp of the current iteration)
-If there are stable oscillations, log the oscillation period and then calculate PID values
Issues/thoughts:
There's an envelope around 0Hz because of the DC component, and I'm trying to figure out a way to remove it. What I've come up with so far is heuristically determining how wide it is and then just chopping that section off, but if the oscillation frequency is within that envelope (especially since temperature control is really low frequency) then that kind of ruins the whole point. Also I'm relying on heuristically determining a few things that would be specific to each loop, which I'm not super happy about, but even the more optimized (and complicated) approach to PID tuning I found relied on heuristically determining a few things about the system to set up the tuning algorithm. After Googling this for a while, I don't know if/don't think it's even feasible to totally get around tweaking heuristically determined parameters for tuning each system.
Anyway, I'm going to keep poking at this. If anyone sees this and has suggestions, that would be super appreciated.
Edit 2/5/2017: Whelp, realized I should probably be LombScargling? To be continued...
#!/usr/bin/env python
import numpy, time
from control.matlab import *
import matplotlib.pyplot as plt
def simulate_heater(total_time,timestep,Kp,Ki,Kd):
num_steps = numpy.ceil(total_time/timestep)
timestamps = linspace(0,total_time,num=num_steps).
So I put together a little test circuit to test out a NPN BJT buffer circuit with a TIP122 transistor and an OP27 op amp. Power voltages are ~ +-14V, just used the positive rail as V+ for the transistor.
(diagram from)
I verified that the op amp functioned alone in a buffer configuration.
Putting the BJT in the loop added a (negative) offset, though:
WIth a 51ohm load, inputs of 1.5Vpp and 2Vpp respectively:
WIth a 910 ohm load, with inputs of 1.5Vpp and 2Vpp respectively:
I realized afterwards that this circuit theoretically shouldn't be able to go below ground. I'm surprised that the output is basically offset so that the entire output signal is below ground. I guess I will test it again with the input signal being entirely positive, but I'm not sure if this is even related.
Side note: also made measurements of the metal slab (including the tape that is currently around it) to do some calculations later:
34.5mm by 61.5mm (basically flat in the third dimension, plus it's crinkly from tape so hard to measure consistently)
Tried separating the power to the sensor circuit board from the driver circuit board (so the only connection they share is ground). Seemed to work at first:
(The messiness in the first half is before I ground connected other set of power supplies to earth ground).
Close up:
But I tried to insulate it (by wrapping the padded aluminum around it), and then the voltage drop started to show up again (and remained after I took the padding off):
I used to oscilloscope to monitor the power voltage signal while entering commands, and none of them dipped or showed any disturbances.
Andrew suggested that the sallen-key filter on the sensor board could be causing the drop, so I disconnected the filter, but it didn't help. However, as I was using the oscilloscope to probe the driving signal (and sensor signal) at different points, I found that having the oscilloscope parallel to the heater (at the leads) caused the voltage drop to stop (tentatively, only two pulses to go off of):
(Also, noticed loading effects when probing along the signal line)
I thought it might be possible that the metal slab might be adding some stray capacitance or otherwise causing interference between the driving and signal lines, since, other than ground, it's the only place where the two circuits are really close to each other, and that the impedance of the oscilloscope changed the "impedance" of the slab. So I thought I would try to use a 1Mohm resistor in place of the oscilloscope, but when I was trying to attach a 1Mohm resistor, one of the leads to the heater fell off :
I'm not sure how the best way to go about fixing this would be. I think maybe just clamping the leads to the heater for now, since soldering this well would be really hard...
Measured the acromag noise (input and output).
For the input noise, a function generator was set up to input a sin signal of 0.1Vpp at 0.1Hz and connected to an input channel. The time series was recorded for 4 hours (sampled at around 10Hz, but not exactly due to differences in how long each loop took to run), and then the Lomb-Scargle algorithm (Fourier transform with uneven sampling) was applied to obtain a frequency spectrum. The result was then run through Andrew's rms.m script (attached). Both are plotted below:
For the output noise, a script was written to continuously write a 0.1Vpp at 0.1Hz sin signal to an output channel that was connected to the signal analyzer, which was used to take the following data.):
Andrew and I did some stuff in the lab today:
-Taped up the cavity and added some insulation.
-Got the Python version of the PID script running on the acromag computer (including installing the prerequisite libraries epics and cdsutils). The script is attached.
-There were some bursts of noise in the error signal that was messing with the PID loop. Andrew fixed this by increasing the "fast gain" knob on the control box.
-Tuned the PID gains to get the desired response. The gains ended up being Kp = 0, Ki = 0.0021, and Kd = .0014. It seemed like the Kd was acting like how you would expect Kp to, which didn't really make sense to me, but we got a pretty good response from these gains.
Edit: Reattaching script, there was a change in it made on the acromag computer that wasn't reflected in the version I uploaded earlier.
#!/usr/bin/env python
import re
import time
import os
from ezca import Ezca
#A python translation of the RCAV_thermalPID.pl/SLOW_PID.pl script
#translated from perl script | https://nodus.ligo.caltech.edu:8081/CTN/page52?&sort=Author | CC-MAIN-2022-40 | refinedweb | 4,173 | 68.2 |
8 Aug 02:02 2009
pcap_activate can cause pcap_geterr to return a blank string
Dustin Spicuzza <dustin <at> virtualroadside.com>
2009-08-08 00:02:35 GMT
2009-08-08 00:02:35 GMT
On linux using the latest GIT: If you use pcap_create followed by pcap_activate when an interface doesn't actually exist (ie, PCAP_ERROR_IFACE_NOT_UP is returned), then pcap_geterr will return a blank value. I noticed that the documentation does mention all the various error codes that could be returned, and that you should call pcap_statustostr to actually get the string if the error isn't PCAP_ERROR or PCAP_WARNING. However, thats another decision that has to be made by the user, so it seems like it would be nice and simple if pcap_geterr just worked no matter what kind of error was returned. Add two lines to pcap_activate to make pcap_geterr work as expected: int pcap_activate(pcap_t *p) { int status; status = p->activate_op(p); if (status >= 0) p->activated = 1; else if (!p->errbuf[0]) snprintf( p->errbuf, PCAP_ERRBUF_SIZE, "%s: %s", p->opt.source, pcap_statustostr(status) ); return (status); }(Continue reading) | http://blog.gmane.org/gmane.network.tcpdump.devel/month=20090801 | CC-MAIN-2014-15 | refinedweb | 181 | 56.89 |
PNGs and a Sprite to the Rock entity. To add the PNGs:
- Download the following four images:
- Expand the Rock Entity in Glue
- Drag+drop the four files into the Files folder
Now you should have four files in the Rock entity. Like before, the PNG files will be copied into the game project.
To add the Sprite to the Rock entity:
- Select the Rock entity
- Click the Add Object to Rock button in the Quick Actions tab
- Select the Sprite type
- Click OK
To set the Sprite’s Texture:
- Select the newly-added SpriteInstance
- Select the Variables tab
- Use the Texture drop-down to select Rock1
Considering Rock spawning
The next question we are faced with is how to handle spawning of the rocks (spawning also means to create an Entity at runtime:
- Select the Quick Actions tab
- Click the Add Entity button
- Enter the name RockSpawner
- Click OK – we won’t need any collision or visuals in this entity
The RockSpawner is different from our other entities – we only need a single RockSpawner instance. To add an instance to the GameScreen:
- Select the RockSpawner
- Click the Quick Actions tab
- Click the Add RockSpawner Instance to GameScreen button
Next we’ll add four variables to the RockSpawner. These are:
- RocksPerSecond
- SpawnRateIncrease
- MinVelocity
- MaxVelocity
To add RocksPerSecond:
- Select the RockSpawner
- Click the Variables tab
- Click the Add New Variable button
- Enter the name RocksPerSecond
- Click OK
Repeat the steps above for the other three variables.
We’ll set some defaults for our variables as well:
- RocksPerSecond = 0.2
- SpawnRateIncrease = 0.015
- MinVelocity = 50
- MaxVelocity =
- Modify this file so that it contains the following code
public partial class RockSpawner { double lastSpawnTime; bool IsTimeToSpawn { get { float spawnFrequency = 1 / RocksPerSecond; return TimeManager.CurrentScreenSecondsSince(lastSpawnTime) > spawnFrequency; } } private void CustomInitialize() { } private void CustomActivity() { if (IsTimeToSpawn) { PerformSpawn(); } } private void PerformSpawn() { Vector3 position = GetRandomRockPosition(); Vector3 velocity = GetRandomRockVelocity(position); Rock rock = Factories.RockFactory.CreateNew(); rock.Position = position; rock.Velocity = velocity; lastSpawnTime = TimeManager.CurrentScreenTime; } ... }
Vector3 not found?
If Visual Studio draws the red squiggly line underneath Vector3 and complains that it can’t find it, then add the following using statement at the top of the file:
using Microsoft.Xna.Framework;:
public partial class RockSpawner { ... private Vector3 GetRandomRockPosition() { // 1. Pick the top, right, bottom, or left. These values will be 0, 1, 2, 3 respectively // The argument 4 is exclusive, so this will return 0,1,2, or 3 int randomSide = FlatRedBallServices.Random.Next(4); // 2. Pick a random point on the side. We'll do this by getting min and max X and Y values. // Two of the values will always be the same. // In other words, the min and max X on the left side will always be equal. // Let's get the absolute coordinates of the edge of the screen: float topEdge = Camera.Main.AbsoluteTopYEdgeAt(0); float bottomEdge = Camera.Main.AbsoluteBottomYEdgeAt(0); float leftEdge = SpriteManager.Camera.AbsoluteLeftXEdgeAt(0); float rightEdge = SpriteManager.Camera.AbsoluteRightXEdgeAt(0); // Now let's set the values according to randomSide float minX = 0; float maxX = 0; float minY = 0; float maxY = 0; switch (randomSide) { case 0: // top minX = leftEdge; maxX = rightEdge; minY = topEdge; maxY = topEdge; break; case 1: // right minX = rightEdge; maxX = rightEdge; minY = bottomEdge; maxY = topEdge; break; case 2: // bottom minX = leftEdge; maxX = rightEdge; minY = bottomEdge; maxY = bottomEdge; break; case 3: // left minX = leftEdge; maxX = leftEdge; minY = bottomEdge; maxY = topEdge; break; } // Now we can pick our point randomly using the min and max values: float offScreenX = minX + (float)(FlatRedBallServices.Random.NextDouble() * (maxX - minX)); float offScreenY = minY + (float)(FlatRedBallServices.Random.NextDouble() * (maxY - minY)); // 3. Finally we move the point off-screen, since the value right now will be right on the border // Our largest Rock is 128x128. Since rocks are positioned at their center, we only need // to move half of that amount (64) to guarantee that rocks spawn fully off-screen. float amountToMoveBy = 64; switch (randomSide) { case 0: // top offScreenY += amountToMoveBy; break; case 1: // right offScreenX += amountToMoveBy; break; case 2: // bottom offScreenY -= amountToMoveBy; break; case 3: // left offScreenX -= amountToMoveBy; break; } // Now we can return the value return new Vector3(offScreenX, offScreenY, 0); } }
GetRandomRockVelocity
GetRandomRockVelocity will give us the velocity for the new Rock.:
public partial class RockSpawner { ... private Vector3 GetRandomRockVelocity(Vector3 position) { // 1. Find the center of the screen. // First we need to get the direction that we want to move. We can do this // by subtracting the argument position from the very center of our game screen. // We get the center by using the Camera's X and Y, but not its Z, because the camera is // positioned above the game screen looking down at it. Vector3 centerOfGameScreen = new Vector3(Camera.Main.X, Camera.Main.Y, 0); // 2. Get the direction towards the center of the screen Vector3 directionToCenter = centerOfGameScreen - position; // 3. Normalize the direction, then multiply it by the desired speed. // We "normalize" it, which means we make the vector have a length of 1 // Once it is normalized, we can multiply it by the speed that we want // the Rock to move at to get to get the final Velocity value directionToCenter.Normalize(); float speed = MinVelocity + (float)(FlatRedBallServices.Random.NextDouble() * (MaxVelocity - MinVelocity)); return speed * directionToCenter; } }
Increasing the spawn rate
If you run the game at this point you will notice that the RockSpawner spawns rocks, but spawn rate doesn’t increase so the game never gets harder over time. To change this, add the following code to the RockSpawner’s CustomActivity:
public partial class RockSpawner { ... private void CustomActivity() { if (IsTimeToSpawn) { PerformSpawn(); } // new code: this.RocksPerSecond += TimeManager.SecondDifference * this.SpawnRateIncrease; } ... }
Conclusion
Now the game is really making progress. If you run the game now you will be able to fly around and fire bullets at rocks. Of course, we haven’t put collision in just yet. We’ll do that next tutorial.
<- 05. Main Ship Behavior — 06. Collision -> | https://flatredball.com/documentation/tutorials/rock-blaster/tutorials-rock-blaster-rock-entity/ | CC-MAIN-2022-40 | refinedweb | 968 | 53.92 |
This. Unfortunately, the service that we need (NavigationService) is not available in the view model, and the easiest thing to do is to signal MainPage to make the transition.
There is and should be no visibility of a view from a view-model, however, and so we need a mechanism for sending out a message in a bottle to be picked up by anyone who is interested. Specifically, we want the view model to be able to send a message indicating that it’s time to navigate to page 2. Further we want main page to register to receive that message, and on receipt, to invoke the navigation service to effect the transition to page 2.
Messaging
Fortunately, the MVVM Light Toolkit provides extensive support for messaging. To accomplish our goals will require a fairly straightforward three-step process:
- Create a class to contain the message that is to be passed
- In the view model, instantiate the message class and broadcast the message
- Within MainPage.xaml.cs register for the message and handle it when received
Begin by creating a new class in the project in Visual Studio, and call the new class GoToPageMessage.
using System; namespace MvvmLightNavigationBehaviorAndMessages { public class GoToPageMessage { public string PageName { get; set; } } }
Return to MainViewModel.cs and remove the contents of the GoToPage2 method. Create an instance of the GoToPageMessage (initializing the PageName with the name of the page you want to navigate to) and use the Messenger object to broadcast the message, as shown here,
private object GoToPage2() { var msg = new GoToPageMessage() { PageName = "Page2" }; Messenger.Default.Send<GoToPageMessage>( msg ); return null; }
You’ll need to include the supporting library,
using GalaSoft.MvvmLight.Messaging;
This broadcasts the message, all that is left is to register a recipient and to respond to the message. To do that, return to MainPage.xaml.cs, and register for the message in the constructor or in the MainPage_Loaded event handler,
Messenger.Default.Register<GoToPageMessage> ( this, ( action ) => ReceiveMessage( action ) );
ReceiveMessage is a method that you’ll write that will take the PageName and assemble a Navigate statement,
private object ReceiveMessage( GoToPageMessage action ) { StringBuilder sb = new StringBuilder( "/Views/" ); sb.Append( action.PageName ); sb.Append( ".xaml" ); NavigationService.Navigate( new System.Uri( sb.ToString(), System.UriKind.Relative ) ); return null; }
Build and run the application. Clicking on the button on MainPage will now cause the application to navigate to Page 2.
So, Is This Easier??
No one would argue that what I’ve shown here is easier than simply handling the click-event in the code-behind. What I would argue is that this is easier to test because the programmer created logic is now in the view-model rather than in the code behind.
In any case, the use of behaviors and messaging goes well beyond this use-case, as we’ll see in coming tutorials.
You can download the final source code here.
You really make it seem so easy together with your presentation but I find
this matter to be actually something which I think I would
by no means understand. It kind of feels too complicated and extremely vast for me.
I’m having a look forward for your next put up,
I will attempt to get the grasp of it!
Wow, superb weblog format! How long have you been running a blog for?
you make running a blog look easy. The overall look of your web
site is great, let alone the content material!
Pingback: Changing between views using MVVM with prism - Technology
Hello colleagues, how is the whole thing, and what you wish for to say on the topic of this paragraph, in my view
its really remarkable for me.
Hi there! Someone in my Myspace group shared this site with us so
I came to give it a look. I’m definitely loving the information.
I’m book-marking and will be tweeting this to my followers!
Excellent blog and outstanding design.
Here is my website … seo
cool posting
Awesome! Its really awesome post, I have got much clear idea about from
this piece of writing.
Pingback: Win8 (Metro style) app development – getting started « RaSor's Tech Blog
Pingback: Empezando con Windows Phone 7.1 (y XV) – Navegación con MVVM Light « jdmveira
I Have a requirement while navigating.
i want to navigate from one page to the other depending on some intrenal action and not depending on the button click. How can i do this.
This code sample seems to work ok for my WPF app:
NavigationService _service;
_service = NavigationService.GetNavigationService(this);
System.Uri uri = new System.Uri(sb.ToString(), System.UriKind.Relative);
_service.Navigate(uri);
but i can not achieve the effect by using your code. the error is that Object reference not set to an instance of an object.
Your MainWindow will not have a navigation service of it’s own, simply add a frame to your xaml like this:
Then you can use the navigation like this (vb code):
Private Function ReceiveMessage(action As Message.GoToPageMessage) As Object
ContentFrame.NavigationService.Navigate(New Uri(String.Format(“/View/{0}.xaml”, action.PageName), UriKind.Relative))
Return Nothing
End Function
there is no need for a global _Nav or to call NavigationService.GetNavigationService(this).
Hello!
I’m loving your walkthrough!
However I’ve hit a road block.
The NavigationServices doesn’t work for the WPF, which I am using.
Is there another way to switch between views? I’ve looked everywhere for a simple tuturial and was unable to find it.
Any sugestions? BTW, i’m reading about MEF + mvvmlight to see if that combo can help me.
Thanks!!! 🙂
Me too,How to switch between different views in WPF,somebody can give some information about it?
Messaging is cool! however it is suitable for only one receiver exists. When I have multiple objects of the receiver class, all the objects receive the message, which is not correct. How could resolve this problem?
@Jim Boone
Please ignore this post. It was the result of a corrupted test environment. It turns out that you cannot guarentee that the View will exist to hear the message, while the Navigate method will instantiate the view if not already available.
Jim Boone
I’m sure I’ve committed serious violations to the “Software Developer’s Creed”, but I’ve cut out the middle-man from my implementation of this example. As I understand this example, The viewModel messages to it’s view, and in the code-behind for it’s view the message is transformed into a call to NavigationService.Navigate which then changes the displayed view.
In building my test project, I used messages with tokens to provide a smaller scope to my event handlers. I only have one event handler that listens for messages targeted to a specific view. I put this handler on the code-behind of the targeted view where it calls NavigationService.Navigate to itself, and the targeted view is displayed.
The advantage of doing this is I can put a payload in the message and the targeted view/viewModel will receive this payload directly.
I stumbled into this configuration accidently, so there must be lots of reasons that this particular practice will cause problems in the future. Please explain any problems you foresee. I’m very interested in learning any downside, so if anyone is interested, I’ll create a simple test case to review.
Jim Boone
Pingback: Navigation in a #WP7 application with MVVM Light |
I’d just like to validate’s Laurent’s approach to navigation. It’s almost exactly the way we do things in Caliburn.Micro. One thing about messaging is that you can use it for almost anything. That’s an advantage and a disadvantage. In this case, I prefer to use a specific navigation service over messaging because the navigation concept is so central to the architecture of the application. Making that explicit through a service helps to enforce that.
@shoaib
Regarding query strings. One thing we do in Caliburn.Micro, which you could easily adapt into MVVM Light or any solution, is that when a page is navigated to, we parse the query string and see if any of the keys match the properties on the ViewModel. If they do, we use some reflection and type coercion to push the values into the view model. That makes working with query strings really easy.
Thank you so much for this series. I am totally sold on the MVVM concept but have been struggling to get started with MVVM Light. As you noted there are almost no examples that a.) are for Windows Phone 7 rather than WPF or Silverlight proper, b.) aren’t based on the CTP version of the WP7 toolkit, and c.) are simple enough to actually show how MVVM works rather than cluttering the project file with tons of app-specific code like complicated animations and data access and processing.
In a future post, would you address how to trigger an animation in the view from the viewmodel? This seems like it’s one of the tricker aspects of MVVM and I would really like to see how it works.
Thanks Laurent ,
Your post is exactly what i need. Thanks alot.
Shoaib, Navigation is the responsibility of the View and not the ViewModel anyhow, so Code Behind is perfectly fine for handling Naviation requests IMHO.
If you want to pass Querystrings, simply extend the GoToPage with a QueryString property. You can put as much context as you want in there.
Handling the Querystring in another VM is a little trickier … I went the easy way and just get a reference to the current ViewModel of my View by:
MyViewModel vm = this.DataContext as MyViewModel;
I pass all data I need in my VM from my View’s code behind wich processes the Querystring.
But for that point … maybe Laurent or Jesse can come up with a better solution 🙂
One thing I would change is that I don’t register my Messenger handler in MainView.xaml.cs but maybe directly during app startup and attaching an anonymous method or creating a separate class for handling this … as for some reason I don’t like the idea that MainView.xaml.cs handles all Navigation requests from other Views. Not because it’s code behind but I think my MainView is not responsible for other Views. 🙂
While the messaging approach works fine, I find myself using another technique for navigation from a viewmodel. I wrote a quite detailed blog post explaining how I usually do this. See
Cheers and keep up the great work with your articles!!
Laurent
Very nice article really from the scratch, but is this really according to MVVM best practice to have navigation service method in code behind? and what if i need to pass some Querystring parameter while navigation? how to do that? and how to handle that Querystring parameter in another page’s ViewModel?
Pingback: Tweets that mention Windows Phone From Scratch #18 | http://jesseliberty.com/2011/01/06/windows-phone-from-scratch%E2%80%93mvvm-light-toolkit-soup-to-nuts-3/comment-page-1/ | CC-MAIN-2016-26 | refinedweb | 1,826 | 55.54 |
Last Updated on April 27, 2021
Machine learning algorithms are typically evaluated using resampling techniques such as k-fold cross-validation.
During the k-fold cross-validation process, predictions are made on test sets comprised of data not used to train the model. These predictions are referred to as out-of-fold predictions, a type of out-of-sample predictions.
Out-of-fold predictions play an important role in machine learning in both estimating the performance of a model when making predictions on new data in the future, so-called the generalization performance of the model, and in the development of ensemble models.
In this tutorial, you will discover a gentle introduction to out-of-fold predictions in machine learning.
After completing this tutorial, you will know:
-.
Kick-start your project with my new book Ensemble Learning Algorithms With Python, including step-by-step tutorials and the Python source code files for all examples.
Let’s get started.
- Update Jan/2020: Updated for changes in scikit-learn v0.22 API.
How to Use Out-of-Fold Predictions in Machine Learning
Photos by Gael Varoquaux, some rights reserved.
Tutorial Overview
This tutorial is divided into three parts; they are:
- What Are Out-of-Fold Predictions?
- Out-of-Fold Predictions for Evaluation
- Out-of-Fold Predictions for Ensembles
What Are Out-of-Fold Predictions?
It is common to evaluate the performance of a machine learning algorithm on a dataset using a resampling technique such as k-fold cross-validation.
The k-fold cross-validation procedure involves splitting a training dataset into k groups, then using each of the k groups of examples on a test set while the remaining examples are used as a training set.
This means that k different models are trained and evaluated. The performance of the model is estimated using the predictions by the models made across all k-folds.
This procedure can be summarized as follows:
- 1. Shuffle the dataset randomly.
- 2. Split the dataset into k groups.
- 3. For each unique group:
- a. Take the group as a holdout or test data set.
- b. Take the remaining groups as a training data set.
- c. Fit a model on the training set and evaluate it on the test set.
- d. Retain the evaluation score and discard the model.
- 4.out set 1 time and used to train the model k-1 times.
For more on the topic of k-fold cross-validation, see the tutorial:
An out-of-fold prediction is a prediction by the model during the k-fold cross-validation procedure.
That is, out-of-fold predictions are those predictions made on the holdout datasets during the resampling procedure. If performed correctly, there will be one prediction for each example in the training dataset.
Sometimes, out-of-fold is summarized with the acronym OOF.
- Out-of-Fold Predictions: Predictions made by models during the k-fold cross-validation procedure on the holdout examples.
The notion of out-of-fold predictions is directly related to the idea of out-of-sample predictions, as the predictions in both cases are made on examples that were not used during the training of the model and can be used to estimate the performance of the model when used to make predictions on new data.
As such, out-of-fold predictions are a type of out-of-sample prediction, although described in the context of a model evaluated using k-fold cross-validation.
- Out-of-Sample Predictions: Predictions made by a model on data not used during the training of the model.
Out-of-sample predictions may also be referred to as holdout predictions.
There are two main uses for out-of-fold predictions; they are:
- Estimate the performance of the model on unseen data.
- Fit an ensemble model.
Let’s take a closer look at these two cases.
Want to Get Started With Ensemble Learning?
Take my free 7-day email crash course now (with sample code).
Click to sign-up and also get a free PDF Ebook version of the course.
Out-of-Fold Predictions for Evaluation
The most common use for out-of-fold predictions is to estimate the performance of the model.
That is, predictions on data that were not used to train the model can be made and evaluated using a scoring metric such as error or accuracy. This metric provides an estimate of the performance of the model when used to make predictions on new data, such as when the model will be used in practice to make predictions.
Generally, predictions made on data not used to train a model provide insight into how the model will generalize to new situations. As such, scores that evaluate these predictions are referred to as the generalized performance of a machine learning model.
There are two main approaches that these predictions can use to estimate the performance of the model.
The first is to score the model on the predictions made during each fold, then calculate the average of those scores. For example, if we are evaluating a classification model, then classification accuracy can be calculated on each group of out-of-fold predictions, then the mean accuracy can be reported.
- Approach 1: Estimate performance as the mean score estimated on each group of out-of-fold predictions.
The second approach is to consider that each example appears just once in each test set. That is, each example in the training dataset has a single prediction made during the k-fold cross-validation process. As such, we can collect all predictions and compare them to their expected outcome and calculate a score directly across the entire training dataset.
- Approach 2: Estimate performance using the aggregate of all out-of-fold predictions.
Both are reasonable approaches and the scores that result from each procedure should be approximately equivalent.
Calculating the mean from each group of out-of-sample predictions may be the most common approach, as the variance of the estimate can also be calculated as the standard deviation or standard error.
The k resampled estimates of performance are summarized (usually with the mean and standard error) …
— Page 70, Applied Predictive Modeling, 2013.
We can demonstrate the difference between these two approaches to evaluating models using out-of-fold predictions with a small worked example.
We will use the make_blobs() scikit-learn function to create a test binary classification problem with 1,000 examples, two classes, and 100 input features.
The example below prepares a data sample and summarizes the shape of the input and output elements of the dataset.
Running the example prints the shape of the input data showing 1,000 rows of data with 100 columns or input features and the corresponding classification labels.
Next, we can use k-fold cross-validation to evaluate a KNeighborsClassifier model.
We will use k=10 for the KFold object, the sensible default, fit a model on each training dataset, and evaluate it on each holdout fold.
Accuracy scores will be stored in a list across each model evaluation and will report the mean and standard deviation of these scores.
The complete example is listed below.
Running the example reports the model classification accuracy on the holdout fold for each iteration.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
At the end of the run, the mean and standard deviation of the accuracy scores are reported.
We can contrast this with the alternate approach that evaluates all predictions as a single group.
Instead of evaluating the model on each holdout fold, predictions are made and stored in a list. Then, at the end of the run, the predictions are compared to the expected values for each holdout test set and a single accuracy score is reported.
The complete example is listed below.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
Running the example collects all of the expected and predicted values for each holdout dataset and reports a single accuracy score at the end of the run.
Again, both approaches are comparable and it may be a matter of taste as to the method you use on your own predictive modeling problem.
Out-of-Fold Predictions for Ensembles
Another common use for out-of-fold predictions is to use them in the development of an ensemble model.
An ensemble is a machine learning model that combines the predictions from two or more models prepared on the same training dataset.
This is a very common procedure to use when working on a machine learning competition.
The out-of-fold predictions in aggregate provide information about how the model performs on each example in the training dataset when not used to train the model. This information can be used to train a model to correct or improve upon those predictions.
First, the k-fold cross-validation procedure is performed on each base model of interest, and all of the out-of-fold predictions are collected. Importantly, the same split of the training data into k-folds is performed for each model. Now we have one aggregated group of out-of-sample predictions for each model, e.g. predictions for each example in the training dataset.
- Base-Models: Models evaluated using k-fold cross-validation on the training dataset and all out-of-fold predictions are retained.
Next, a second higher-order model, called a meta-model, is trained on the predictions made by the other models. This meta-model may or may not also take the input data for each example as input when making predictions. The job of this model is to learn how to best combine and correct the predictions made by the other models using their out-of-fold predictions.
- Meta-Model: Model that takes the out-of-fold predictions made by one or more models as input and shows how to best combine and correct the predictions.
For example, we may have a two-class classification predictive modeling problem and train a decision tree and a k-nearest neighbor model as the base models. Each model predicts a 0 or 1 for each example in the training dataset via out-of-fold predictions. These predictions, along with the input data, can then form a new input to the meta-model.
- Meta-Model Input: Input portion of a given sample concatenated with the predictions made by each base model.
- Meta-Model Output: Output portion of a given sample.
Why use the out-of-fold predictions to train the meta-model?
We could train each base model on the entire training dataset, then make a prediction for each example in the training dataset and use the predictions as input to the meta-model. The problem is the predictions will be optimistic because the samples were used in the training of each base model. This optimistic bias means that the predictions will be better than normal, and the meta-model will likely not learn what is required to combine and correct the predictions from the base models.
By using out-of-fold predictions from the base model to train the meta-model, the meta-model can see and harness the expected behavior of each base model when operating on unseen data, as will be the case when the ensemble is used in practice to make predictions on new data.
Finally, each of the base models are trained on the entire training dataset and these final models and the meta-model can be used to make predictions on new data. The performance of this ensemble can be evaluated on a separate holdout test dataset not used during training.
This procedure can be summarized as follows:
- 1. For each base model:
- a. Use k-fold cross-validation and collect out-of-fold predictions.
- b.Train meta-model on the out-of-fold predictions from all models.
- c. Train each base model on the entire training dataset.
This procedure is called stacked generalization, or stacking for short. Because it is common to use a linear weighted sum as the meta-model, this procedure is sometimes called blending.
For more on the topic of stacking, see the tutorials:
- How to Develop a Stacking Ensemble for Deep Learning Neural Networks in Python With Keras
- How to Implement Stacked Generalization (Stacking) From Scratch With Python
We can make this procedure concrete with a worked example using the same dataset used in the previous section.
First, we will split the data into training and validation datasets. The training dataset will be used to fit the submodels and meta-model, and the validation dataset will be held back from training and used at the end to evaluate the meta-model and submodels.
In this example, we will use k-fold cross-validation to fit a DecisionTreeClassifier and KNeighborsClassifier model each cross-validation fold, and use the fit models to make out-of-fold predictions.
The models will make predictions of probabilities instead of class labels in an attempt to provide more useful input features for the meta-model. This is a good practice.
We will also keep track of the input data (100 features) and output data (expected label) for the out-of-fold data.
At the end of the run, we can then construct a dataset for a meta classifier comprised of 100 input features for the input data and the two columns of predicted probabilities from the kNN and decision tree models.
The create_meta_dataset() function below implements this, taking the out-of-fold data and predictions across the folds as input and constructs the input dataset for the meta-model.
We can then call this function to prepare data for the meta-model.
We can then fit each of the submodels on the entire training dataset ready for making predictions on the validation dataset.
We can then fit the meta-model on the prepared dataset, in this case, a LogisticRegression model.
Finally, we can use the meta-model to make predictions on the holdout dataset.
This requires that data first pass through the sub models, the outputs used in the construction of a dataset for the meta-model, then the meta-model is used to make a prediction. We will wrap all of this up into a function named stack_prediction() that takes the models and the data for which the prediction will be made.
We can then evaluate the submodels on the holdout dataset for reference, then use the meta-model to make a prediction on the holdout dataset and evaluate it.
We expect that the meta-model would achieve as good or better performance on the holdout dataset than any single submodel. If this is not the case, alternate submodels or meta-models could be used on the problem instead.
Tying this all together, the complete example is listed below.
Running the example first reports the accuracy of the decision tree and kNN model, then the performance of the meta-model on the holdout dataset, not seen during training.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
In this case, we can see that the meta-model has out-performed both submodels.
It might be interesting to try an ablative study to re-run the example with just model1, just model2, and neither model 1 and model 2 as input to the meta-model to confirm that the predictions from the submodels are actually adding value to the meta-model.
Further Reading
This section provides more resources on the topic if you are looking to go deeper.
Tutorials
- A Gentle Introduction to k-fold Cross-Validation
- How to Develop a Stacking Ensemble for Deep Learning Neural Networks in Python With Keras
- How to Implement Stacked Generalization (Stacking) From Scratch With Python
- How to Create a Bagging Ensemble of Deep Learning Models in Keras
- Ensemble Learning Methods for Deep Learning Neural Networks
Books
- Applied Predictive Modeling, 2013.
Articles
APIs
- sklearn.datasets.make_blobs API.
- sklearn.model_selection.KFold API.
- sklearn.neighbors.KNeighborsClassifier API.
- sklearn.tree.DecisionTreeClassifier API.
- sklearn.metrics.accuracy_score API.
- sklearn.linear_model.LogisticRegression API.
- sklearn.model_selection.train_test_split API.
Summary
In this tutorial, you discovered out-of-fold predictions in machine learning.
Specifically, you learned:
-.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
This is just another AWESOME blog post of yours, THANKS!
NIT:
I just noticed that you make use of the numpy array indexing [:, 0] to reduce the dimensions from [LENGTH, 1], to [LENGTH,] and then later in create_meta_dataset function you reshape it back to the dimension [LENGTH, 1].
I removed all the [:, 0] indexing by the complete example as well as the following lines:
yhat1 = array(yhat1).reshape((len(yhat1), 1))
yhat2 = array(yhat2).reshape((len(yhat2), 1))
And the example still works the same.
Thanks, I’m happy it’s fun/helpful.
Very nice! Thanks for sharing.
Thanks for your amazing tutorials. i am interested to implement something similar to this but i get the error
TypeError: array() argument 1 must be a unicode character, not list
when i run the code below , How to fix this
# create a meta dataset
import numpy as np
from array import array
# create a meta dataset
def create_meta_dataset(data_x, yhat1, yhat2):
# convert to columns
yhat1 = array(yhat1).reshape((len(yhat1), 1))
yhat2 = array(yhat2).reshape((len(yhat2), 1))
# stack as separate columns
meta_X = hstack((data_x, yhat1, yhat2))
return meta_X
##Here is where i call the function and it gives that error
# construct meta dataset
meta_X = create_meta_dataset(data_x, knn_yhat, cart_yhat)
Sorry, I am not familiar with this error, perhaps try posting to stackoverflow?
Thank you, i solved the problem , there was a need to add np.array and np.hstack. make sure you import numpy array. Other readers can benefit from it. Its a basic error but can be a bit frustrating
Well done!
Thanks for this tutorial.
Since what I know, when we put “fit method” inside a loop, previous results discard and replace with the new ones after each iteration. It means that the model fit only on the last fold of training data. Is it true? I would grateful if you make it clear for me.
Thanks in advance
We fit and evaluate the model on each loop.
All models prepared during the evaluation process are discarded.
but what should I do if I want to get a model which trained by the result of all previous models? Do I need to use ensemble algorithms or methods such as grid search?
Typically all models from cross validation are discarded and a final model is fit on all data:
You can create an ensemble from the cross-validation models:
Thank you very much!!!!!!
You’re welcome.
Hi Jason,
Love this site, I have learned so much over the past 18 months reading your articles.
I followed your suggestion for further study and modified the example to not include the predictions from the submodels in the metamodel.
After 100 runs each:
No meta features results:
Model1 Accuracy: 0.731, Model2 Accuracy: 0.929
Meta Model Accuracy: 0.955
With meta features results:
Model1 Accuracy: 0.733, Model2 Accuracy: 0.926
Meta Model Accuracy: 0.955
Looking at these results, it seems unlikely to me that these submodel predictions are adding any value at all. The more likely scenario to me is that Logistic Regression is simply a better model for this problem compared to Decision Trees or K-Neighbors.
Nice work!
Hi Jason,
Great tutorial, especially the conceptual generalization! I do have a question about evaluating performance with a stacked model.
Given computational limitations aren’t an issue, would it be reasonable to evaluate a stacked model’s performance using cross validation across the entire training process? That is, keeping a “meta” out-of-fold set of data, training the base models using using the all the “meta” in-fold data broken down with further cross-validation described above, then evaluating the meta model on the meta-out-of-fold, and repeating?
Yes, that sounds reasonable.
Thank you for a clear and insightful tutorial!
Thank you. Glad you like it. | https://machinelearningmastery.com/out-of-fold-predictions-in-machine-learning/ | CC-MAIN-2021-49 | refinedweb | 3,407 | 53.92 |
hash_ring 1.3.1
Implements consistent hashing in Python (using md5 as hashing function).
About hash_ring
Implements consistent hashing that can be used when the number of server nodes can increase or decrease (like in memcached). The hashing ring is built using the same algorithm as libketama.
Consistent hashing is a scheme that provides a hash table functionality in a way that the adding or removing of one slot does not significantly change the mapping of keys to slots.
More about hash_ring can be read in a blog post (that explains the idea in greater details):
- Consistent hashing implemented simply in python <>
More information about consistent hashing can be read in these articles:
- Web Caching with Consistent Hashing <>
- Consistent hashing and random trees <>
There is also a wrapper MemcacheRing that extends python-memcache to use consistent hashing for key distribution.
Example
Basic example of usage (for managing memcached instances):
memcache_servers = ['192.168.0.246:11212', '192.168.0.247:11212', '192.168.0.249:11212'] ring = HashRing(memcache_servers) server = ring.get_node('my_key')
Example using weights:
memcache_servers = ['192.168.0.246:11212', '192.168.0.247:11212', '192.168.0.249:11212'] weights = { '192.168.0.246:11212': 1, '192.168.0.247:11212': 2, '192.168.0.249:11212': 1 } ring = HashRing(memcache_servers, weights) server = ring.get_node('my_key')
How to use MemcacheRing:
from hash_ring import MemcacheRing mc = MemcacheRing(['127.0.0.1:11212']) mc.set('hello', 'world') print mc.get('hello')
The code should be clean and simple. Feel free to concat the author if you detect bugs.
- Author: Amir Salihefendic
- Keywords: memcached hashing hash consistent
- License: BSD
- Platform: Any
- Categories
- Package Index Owner: amix
- DOAP record: hash_ring-1.3.1.xml | https://pypi.python.org/pypi/hash_ring/ | CC-MAIN-2016-30 | refinedweb | 282 | 58.08 |
Difference between revisions of "Buffer overflow attack"
Revision as of 05:28, 6 September 2008
- This is an Attack. To view all attacks, please see the Attack Category page.
Last revision (mm/dd/yy): 09/6
#include <stdio.h> int main(int argc, char **argv) { char buf[8]; // buffer for eight characters gets(buf); // read from stdio (sensitive function!) printf("%s\n", buf); // print out data stored in buf return 0; // 0 as return value }
This very simple application reads from the standard input an array of the characters and copies it into the buffer of the char type. The size of this buffer is eight characters. After that the content of the buffer is displayed and application exits.
Program compilation:
rezos@spin ~/inzynieria $ gcc bo-simple.c -o bo-simple /tmp/ccECXQAX.o: In function `main': bo-simple.c:(.text+0x17): warning: the `gets' function is dangerous and should not be used.
At this stage, even the compiler suggests that the used function gets() isn't safe.
Usage example:
rezos@spin ~/inzynieria $ ./bo-simple // program start 1234 // we eneter "1234" string from the keyboard 1234 // program prints out the conent of the buffer rezos@spin ~/inzynieria $ ./bo-simple // start 123456789012 // we eneter "123456789012" 123456789012 // content of the buffer "buf" ?!?! Segmentation fault // information about memory segmenatation fault process memory organisation. Four characters which overflowed the buffer also overwrite the value stored in one of the registers, which was necessary for the correct function return. Memory continuity resulted in printing out the data stored in this memory area.
Example 2
#include <stdio.h> #include <string.h> void doit(void) { char buf[8]; gets(buf); printf("%s\n", buf); } int main(void) { printf("So... The End...\n"); doit(); printf("or... maybe not?\n"); return 0; }
This example is analogous to the first one. In addition, before and after the doit() function, we have two calls to function printf().
Compilation: rezos@dojo-labs ~/owasp/buffer_overflow $ gcc example02.c -o example02 -ggdb /tmp/cccbMjcN.o: In function `doit': /home/rezos/owasp/buffer_overflow/example02.c:8: warning: the `gets' function is dangerous and should not be used. Usage example: rezos@dojo-labs ~/owasp/buffer_overflow $ ./example02 So... The End... TEST // user data on input TEST // print out stored user data or... maybe is output produced by the objdump. From that output we are able to find addresses, where printf() is called (0x80483d6 and 0x80483e7).
rezos@dojo-labs ~/owasp/buffer_overflow $ objdump -d ./example02 080483be <main>: 80483be: 8d 4c 24 04 lea 0x4(%esp),%ecx 80483c2: 83 e4 f0 and $0xfffffff0,%esp 80483c5: ff 71 fc pushl 0xfffffffc(%ecx) 80483c8: 55 push %ebp 80483c9: 89 e5 mov %esp,%ebp 80483cb: 51 push %ecx 80483cc: 83 ec 04 sub $0x4,%esp 80483cf: c7 04 24 bc 84 04 08 movl $0x80484bc,(%esp) 80483d6: e8 f5 fe ff ff call 80482d0 <puts@plt> 80483db: e8 c0 ff ff ff call 80483a0 <doit> 80483e0: c7 04 24 cd 84 04 08 movl $0x80484cd,(%esp) 80483e7: e8 e4 fe ff ff call 80482d0 <puts@plt> 80483ec: b8 00 00 00 00 mov $0x0,%eax 80483f1: 83 c4 04 add $0x4,%esp 80483f4: 59 pop %ecx 80483f5: 5d pop %ebp 80483f6: 8d 61 fc lea 0xfffffffc(%ecx),%esp 80483f9: c3 ret 80483fa: 90 nop 80483fb: 90 nop
If the second call to printf() would inform application finished its execution with segmentation fault, but the second call to printf() had no place.
A few words of explanation:
perl -e 'print "A"x12 ."\xf9\x83\x04\x08"' - will print out twelve "A" characters and then four characters, which are in fact an address of the instruction we want to execute. Why twelve?
8 // size of buf (char buf[8]) + 4 // four additional bytes for overwriting stack frame pointer ---- 12
Problem analysis:
The issue is the same as in the first example. There is no control over the size of the copied buffer into the previously declared one. In this example we overwrite possible.
Namely:
- gets() -> fgets()
- strcpy() -> strncpy()
- strcat() -> strncat()
- sprintf() -> snprintf()
- These functions which doesn't have. | https://www.owasp.org/index.php?title=Buffer_overflow_attack&diff=38608&oldid=38607 | CC-MAIN-2015-48 | refinedweb | 673 | 64.71 |
Hide Forgot
Description of problem:
A panic is observed upon reboot into the kexec environment on DL platforms:
dl385-01.rhts.boston.redhat.com
dl585-01.rhts.boston.redhat.com
1.)Follow the HOWTO contained int the kexec-tools rpm. With the kexec tools
installed, rebuild the initrd image with `service kdump restart`
2.)Force a panic:
`cat c >/proc/sysrq-trigger`
Version-Release number of selected component (if applicable):
2.6.18-8.el5
1.101-164.el5
How reproducible:
100%
Steps to Reproduce:
1. Explained in Description
2.
3.
Actual results:
Panic
Expected results:
Additional info:
HP CISS Driver (v 3.6.14-RH1)
ACPI: PCI Interrupt 0000:02:04.0[A] -> GSI 18 (level, low) -> IRQ 169
cciss0: <0xb178> at PCI 0000:02:04.0 IRQ 169 using DAC
cciss cciss0: SendCmd Invalid command list address returned! (4)
------------[ cut here ]------------
kernel BUG at drivers/block/cciss.c:2232!
invalid opcode: 0000 [#1]
SMP
last sysfs file:
Modules linked in: cciss sd_mod scsi_mod
CPU: 0
EIP: 0060:[<c9867a7e>] Not tainted VLI
EFLAGS: 00010292 (2.6.18-8.el5 #1)
EIP is at sendcmd+0x263/0x29e [cciss]
eax: 00000044 ebx: c8400000 ecx: c986b5e5 edx: c8dced8c
esi: 00000000 edi: 00004e20 ebp: c8e7b800 esp: c8dced94
ds: 007b es: 007b ss: 0068
Process exe (pid: 464, ti=c8dce000 task=c8dc6000 task.ti=c8dce000)
Stack: 0026bd80 c8e69ac0 00000012 00000000 00000040 00000000 c8e68cc0
c8e69ac0
c9867d62 00000024 00000000 00000000 00000000 00000000 00000000
c10087a7
00000000 c8df2bc0 00000003 00000000 00000040 00000020 c8e69b40
00000000
Call Trace:
[<c9867d62>] cciss_getgeometry+0x9e/0x23f [cciss]
[<c10087a7>] dma_alloc_coherent+0xaa/0xde
[<c986a0a8>] cciss_init_one+0x6be/0xa9e [cciss]
[<c11439eb>] __driver_attach+0x0/0x6b
[<c10e6bf4>] pci_device_probe+0x36/0x57
[<c1143945>] driver_probe_device+0x42/0x8b
[<c1143a2f>] __driver_attach+0x44/0x6b
[<c114344a>] bus_for_each_dev+0x37/0x59
[<c11438af>] driver_attach+0x11/0x13
[<c11439eb>] __driver_attach+0x0/0x6b
[<c1143152>] bus_add_driver+0x64/0xfd
[<c10e6d22>] __pci_register_driver+0x47/0x63
[<c103d0d4>] sys_init_module+0x16e7/0x186a
[<c12f4700>] pcibios_irq_init+0xfe/0x47e
[<c1003eff>] syscall_call+0x7/0xb
=======================
Code: 88 bc 03 00 00 8b 40 24 83 c0 02 39 c7 7c 0f 56 68 2d b6 86 c9 e8
f7 c6 7b f7 58 5a eb 0d 8b 41 04 89 14 b8 ff 01 e9 7
EIP: [<c9867a7e>] sendcmd+0x263/0x29e [cciss] SS:ESP 0068:c8dced94
<0>Kernel panic - not syncing: Fatal exception
Additional Description:
The panic happens upon boot of the kexec environment and before copy of the
vmcore happens; So flow looks like this:
configure kexec/kdump -> Trigger a crash dump (i.e. `cat /proc/sysrq-trigger`)
-> kexec kernel loads from the configured memory spot (kernel cmdline
"crashkernel=128M@16M") storage module (cciss driver) loads and panics the system.
This panic doesn't look unusual. Last year when we started pushing hard to
integrate kdump as our crash analysis tool, we knew there were a lot of drivers
(mainly scsi) that were not kdump friendly.
What that means is they could not handle transactions properly from the previous
running kernel, namely pci responses and dma interrupts. Vivek helped create a
reset mechanism to work around these issues and for the most part any driver
that utilized that mechanism had their issues disappear.
The cciss panic seems to stem from sendcmd() receiving an illegal response.
Again being a scsi device this panic isn't uncommon at all. I presume if we
were to implement the reset mechanisms as described above, this problem can be
solved.
We tested lots of i/o drivers leading up to rhel-5. Apparently the cciss device
wasn't at the top of the food chain.
Vivek,
Does my conclusion from the previously attached panic log seem correct? And do
you have any links to what reset mechanisms this driver may need?
-Don
Created attachment 149128 [details]
console output from the dl360 showing, among other things the panic
Comprehensive test results summary:
x86_64 :
7-8 test runs (trigger dump) on ibm, dl and nec machines
-dl360-01 was the only machine to have a panic
i386:
7-8 test runs (trigger dump) on ibm, dl and nec machines
-dl360-01 was the only machine to have a panic
*Due to the testing done; The likelyhood or reproduceability % should be
something like 50% on dl360-01 and 20% on dl[3-5]85-01
Will attach a csv (openoffice format) spreadsheet.
Created attachment 149208 [details]
csv Openoffice spreadsheet showing test matrix
Vivek, will you be able to help on this?
I'm also adding Mile Miller, the cciss maintainer at HP.
This has been an issue for Smart Array for some time. I'm working with the
firmware team to ensure the reset and abort messages are actually honored by the
controller firmware. The latest firmware reportedly does honor the reset but I
have not yet tested that functionality.
I am out of the office recovering from a motorcycle accident. I do not except to
return before March 19.
Vivek,
Are there any likely work-arounds, based on your experience with other HBAs that
had similar problems?
Some customers will be slow to update HBA firmware.
Tom
Hi Tom,
Can't think of a work-around for this issue. As Mike mentioned, that firmware
team needs to make sure controller responds to RESET and ABORT messages then
only this problem can be solved.
Mike looks like this problem is also related to some pending messages like
megaraid. There we issues some kind of FLUSH meesage to the controller to flush
all the pending meesage in the queue. Does ciss support something like that?
Vivek
Looks like firmware on at least some of our SAS controllers supports the reset
message defined in the cciss specification. If someone knows of a flag for which
I can test during init that tells me this is a kexec'ed kernel the fix should be
fairly simple and straightforward.
I still need to do further testing because the P400 locked up when resetting.
The P800 and E500 controllers seems to wotk OK.
Vivek, we do support cache flush on Smart Array.
If the flag you are looking for is only for testing purposes, then checking to
see if /proc/vmcore is non-zero is one way to do it.
But if you want to use this flag as part of the final solution, I would advise
against it.
Cheers,
Don
(In reply to comment #10)
> Looks like firmware on at least some of our SAS controllers supports the reset
Mike, as we move forward, keep in mind that we will need to write a release note
that clearly states which cciss-based systems work with kdump and which do not.
This will need to refer to customer-consumable model numbers (for systems with
cciss built-in, and add-on cards) and min. fw revs. Maybe your fw guys can help
with that.
I can help with that. As I test the various configs I can make sure our release
notes are updated. I'll also make sure that cciss.txt is updated with accurate
information.
From Vivek Goyal <vgoyal@in.ibm.com>
Mike,
I had added a command line parameter "reset_devices" to give drivers an
indication that they need to first reset their device and then go ahead with
rest of the initializaiton. This is available in upstream kernels. I am not
sure if this is part of RHEL5 kernels or not. If it is not available in RHEL5
kernels, then for testing you can use upstream kernels, pass "reset_devices"
command line option while loading kdump kernel and make use of it for
resetting the cciss controller. Once you are successful in your testing,
we can think of taking this patch in RHEL5.
("reset_devices" is a very non-intrusive patch.)
Regarding flushing the caches, you can try that and see if solves the
problem. There are high chances that it will. It did for megaraid.
Thanks
Vivek
Even with Vivek's patch we still have an issue with msi. When the kernel crashes
we have no way to free our msi-x vectors. So when the dump kernel initializes we
cannot allocate and register new vectors.
I'm not sure how msi determines what resources get which vectors. It seems that
it may be based on the PCI bus address. So that a card in a particular slot will
always be allocated the same vector(s). There was some work going on upstream to
fix that. But a couple of weeks ago I was playing with kdump and still
encountered this issue.
So I think we're a ways out from making this work as designed.
We still have some apparent firmware issues trying to support kdump. After
resetting the controller it will not accept any more commands. I'm working with
the firmware group to resolve this problem. No ETA.
Mike,
We really need to write a release note warning customers that kdump on cciss
does not work, at least on some hw/fw combinations. Please let us know if there
are any cciss models and fw versions that are known to work, and you are willing
to support. Otherwise the release note will just make a blanket statement.
Don, this should go in the 5.1 release note update as soon as Mike replies.
Tomas, please keep an eye on any potential fixese for this from HP during 5.2
development.
Tom
Proposed support statement:
At this time kexec/kdump does not work with any HP Smart Array controller.
Support for kexec/kdump is planned for a future release but no scheduling
information is available.
Is this appropriate for the release notes?
Not for public release: I looked at this issue again with one of our firmware
engineers. It looks like the firmware is completing commands after the reset but
we get stuck in wait for completion in the ioctl path. Right now I'm working 2
critical issues for a new product. When I resolve those I will add debug to
figure out why we're stuck. I suspect a corrupt command tag.
Hrm... I don't think saying it doesn't work with *any* Smart Array controller is
accurate. I've definitely been able to capture a dump on at least one
cciss-equipped box (and one cpqarray-equipped box) while testing our mkdumprd
tweaks to support dumping to manually specified cciss & cpqarray devices (see
bug 228685).
Of course, I don't know how to identify those that work vs. those that don't, so...>
Jarod, If you've been successful I'd like to know which controllers, firmware
version, and driver version have worked. I have had no luck with any of the
controllers I've tested. I've only looked at the newest controllers, though.
Ugh. So the cciss system I swear I was able to capture a dump on previously now
panics. Its an HP DL380 G5 here in our lab, with an HP Smart Array P400
Controller, firmware version 1.18. The cciss driver is 3.6.16-RH1, as found in
kernel-2.6.18-53.el5. From what I can tell, it was mid-August I last actually
tried this, so I can give some kernels from that time frame a go to see if one
of 'em actually works. Not sure if anyone has changed the controller firmware
lately or not though.
(In reply to comment #24)
>>
I would prefer:
Crash dump using kexec/kdump may not function reliably with HP Smart Array
controllers (these adapters use the cciss driver).
I believe the architectures are i686, x86_64, and ia64.
thanks Tom, edited as follows:
<quote>
(x86_64;ia64) Crash dumping through kexec and kdump may not function reliably
with HP Smart Array controllers. This is because these controllers use the cciss
driver.
</quote>
(In reply to comment #28)
> <quote>
> (x86_64;ia64)
Did you overlook x86?
> Crash dumping through kexec and kdump may not function reliably
> with HP Smart Array controllers. This is because these controllers use the
> cciss
> driver.
> </quote>
The problem is with the firmware, not the cciss driver. I wanted to include
"cciss" because that helps prople identify the hw involved, and they may be
searching the docs. on that term. So something like:
"... (These controllers use the cciss driver.) A solutioon to this problem,
which is likely to involve a firmware update to the controller, is being
investigated."
Tom
thanks for clearing that up Tom. release note revised.
Hello - wall street customers are starting to ask about this. Any ETA on the
firmware update? This is definitely going to make RHEL 5 a non-starter for Wall
St until we get it resolved.
-Sam
There is nothing we can do to resolve this without HP fw/driver changes. I have
requested management attention.
We have kdump working on ia32 based systems using a kernel.org 2.6.22.9 kernel.
I'm having problems with rhel5.1 on x86_64. The driver loads and sucessfully
discovers the attached disks but I get the message "unexpected IRQ trap at
vector 82" for each controller in the system. Then the system panics with
"Kernel panic - not syncing: Attempted to kill init!"
According to the kdump doc you must use the uncompressed kernel image on x86_64.
That image doesn't seem to be included on the distribution. Can someone please
explain RH's expectations for kdump support? In other words, how would a
customer set up a crash kernel?
The normal kernel is a relocatable kernel thus allowing kdump to use the same
kernel for its purposes. Installing the kexec-tools package (the init script
takes care of everything) and setting up the correct memory region on the kernel
command line (rebooting to have it take effect) will get you there. This is
also done by the First Boot install scripts.
Disregard the kdump documentation as it is a little out of date.
cc'ing Neil to help you with other little issues.
Mike, don is right, the docs are old, you don't need to used the uncompressed
kernel any more. Regarding comment #35 and your panic, I'll look at your
console logs shortly.
Mike, I've looked over your console logs. do me a favor and try the following:
in /etc/sysconfig/kdump, you'll see a line defining the variable
KDUMP_COMMANDLINE_APPEND. Please add the parameter:
reset_devices
to that variable, along with the others already there. Restart the kdump
service and try again. This looks like an old cciss problem thats fixed in
kernels 2.6.18-26.el5 and later, but requires that reset_devices be passed on
the kernel command line for the kdump kernel. The fix is actually a hack to
work around some firmware issues, IIRC, but should get you going until its
properly repaired.
Neil,
I think that Mike is trying to solve the same issue you've solved in
2.6.18-26.el5 and he is also using the same variable reset_devices as you did.
Could I then, when Mike succeeds remove your patch from cciss driver ?
I mean with that, only that part which is in cciss.c not general handling of
variable reset_devices. This :
@@ -2074,6 +2074,13 @@;
}
Tomas, Yes, you are correct. Assuming that the test that I asked mike to
preform in comment 38 is successful, then he is trying to solve the same problem
I did with the changeset you reference in comment 39. When he manages to fix
it, then yes, you can remove the segment that you reference from the cciss driver.
I'm getting soft lockups on one of the CPUs during driver initialization. For
waht ever reason the stack is not printing on my serial console, but the
interesting part is:
<IRQ> [<ffffffff800b50fa>] softlockup_tick+0xd5/0xe7
[<ffffffff800930e2>] update_process_times+0x42/0x68
[<ffffffff800746e3>] smp_local_timer_interrupt+0x23/0x47
[<ffffffff80074da5>] smp_apic_timer_interrupt+0x41/0x47
[<ffffffff8007bc8e>] apic_timer_interrupt+0x66/0x6c
[<ffffffff8000c505>] __delay+0x8/0x10
[<ffffffff880b8ad4>] :cciss:cciss_init_one+0x295/0x11ed
Everything before this looks like normal init stuff like pci_probe_device, etc.
At this point I've jumped off into the function that resets the controller.
After reset we wait 60 seconds for the controller to become ready. I may be able
to reduce that delay but I know already 20 seconds is not enough. (20 seconds is
our default timeout when polling.)
On my initial development system everything would just stop and wait after the
cciss version printk. Then we did our device discovery and add the disks, etc.
On this 5.1 system (2.6.18-53.el5) after the version printk it halts for a
couple of seconds and then I notice other things like USB initialize. About 10
seconds after the version printk I get the soft lockups. Of course, now we're hosed.
Any thoughts or suggestions?
adding same "Known Issues" release note to RHEL5.2 release note.
Mike,
I don't know, but maybe you could post the current version of your patch so that
we can easily help you with debugging.
Which kernel to want the patch made against? I'm currently using 2.6.18-53.el5.
Created attachment 292178 [details]
kdump support for cciss
Arggggh, now the behavior is different. In the earlier testing I was building
an rpm with the kdump support and then installing it on the system. That's when
I saw the soft lockups I reported.
With the attached patch I used a vanilla 2.6.18-53.el5 kernel, applied the
patch, and built a new kernel and modules. I no longer see the soft lockups but
it almost seems I'm not getting my interrupts. I notice that MSI-X init fails
with a -22. That just means it's an unknown error. At that point I try to get
IOAPIC interrupts. I'm not sure that will work. If I remember correctly you can
go from IOAPIC ----> MSI-X but not the other way around. I tried forcing the
the controllers to IOAPIC mode from the beginning and then crashing the system.
I still get failure trying to mount root and the subsequent panic. I don't see
this problem on my original development box.
Please look at the patch and see if anything stands out. Maybe I'm doing
something wrong.
I managed to capture this dump:
HP CISS Driver (v 3.6.16-RH1)
usb 5-1: new full speed USB device using uhci_hcd and address 2
usb 5-1: configuration #1 chosen from 1 choice
irq 169: nobody cared (try booting with the "irqpoll" option)
Call Trace:
<IRQ> [<ffffffff800b5d60>] __report_bad_irq+0x30/0x7d
[<ffffffff800b5f93>] note_interrupt+0x1e6/0x227
[<ffffffff800b54a5>] __do_IRQ+0xc7/0x105
[<ffffffff8006a3bd>] do_IRQ+0xe7/0xf5
[<ffffffff8005b615>] ret_from_intr+0x0/0xa
[<ffffffff80010792>] handle_IRQ_event+0x1b/0x58
[<ffffffff800b5482>] __do_IRQ+0xa4/0x105
[<ffffffff80011cb4>] __do_softirq+0x5e/0xd5
[<ffffffff8006a3bd>] do_IRQ+0xe7/0xf5
[<ffffffff8005b615>] ret_from_intr+0x0/0xa
<EOI> [<ffffffff801efe01>] input_print_modalias_bits+0x48/0x95
[<ffffffff801efee4>] input_print_modalias+0x96/0x1e4
[<ffffffff801f0bfa>] input_dev_uevent+0x3c4/0x3ff
[<ffffffff801abf87>] class_uevent+0x1b9/0x1c8
[<ffffffff80056069>] kobject_get_path+0x99/0xc1
[<ffffffff80055db8>] kobject_uevent+0x1fb/0x413
[<ffffffff80100854>] sysfs_create_link+0xfe/0x10c
[<ffffffff801ac742>] class_device_add+0x2fb/0x44b
[<ffffffff801f1465>] input_register_device+0xf5/0x271
[<ffffffff801eabc5>] hidinput_connect+0x1bab/0x1bbc
[<ffffffff801e76ff>] hid_probe+0xa7f/0xc38
[<ffffffff801dd94c>] usb_probe_interface+0x6c/0x9e
[<ffffffff801ab876>] driver_probe_device+0x52/0xaa
[<ffffffff801ab8ce>] __device_attach+0x0/0x5
[<ffffffff801ab198>] bus_for_each_drv+0x40/0x72
[<ffffffff801ab925>] device_attach+0x52/0x5f
[<ffffffff801aae64>] bus_attach_device+0x1a/0x35
[<ffffffff801aa247>] device_add+0x24a/0x361
[<ffffffff801dcaac>] usb_set_configuration+0x36b/0x3f1
[<ffffffff801d8754>] usb_new_device+0x253/0x2c4
[<ffffffff801d98b0>] hub_thread+0x74b/0xb10
[<ffffffff8009b446>] autoremove_wake_function+0x0/0x2e
[<ffffffff801d9165>] hub_thread+0x0/0xb10
[<ffffffff8009b283>] keventd_create_kthread+0x0/0x61
[<ffffffff800321d8>] kthread+0xfe/0x132
[<ffffffff8005bfb1>] child_rip+0xa/0x11
[<ffffffff8009b283>] keventd_create_kthread+0x0/0x61
[<ffffffff800320da>] kthread+0x0/0x132
[<ffffffff8005bfa7>] child_rip+0x0/0x11
handlers:
[<ffffffff801dadad>] (usb_hcd_irq+0x0/0x55)
[<ffffffff801dadad>] (usb_hcd_irq+0x0/0x55)
Disabling IRQ #169
Here's the command line I use to load the crash kernel:
kexec -p /boot/vmlinuz-rhel51-kdump \
--initrd=/boot/initrd-rhel51-kdump \
--append="root=/dev/cciss/c0d0p2 reset_devices 3 irqpoll \
maxcpus=1 console=ttyS0,115200 console=tty1"
Does anybody see a problem in the command line? The kernel hints to use irqpoll.
I am using that parameter.
On a maybe more positive note: my kernel.org 2.6.22.9 blows up much the same
same way on this platform.
I am installing rhel5.1 ia32 on the system on which I did the initial
development. I'll post the results when I'm done.
what kexec version are you using mike? A command line length overrun problem
was recently reported to me. I don't have the fixed checked in yet, but I have a
patch floating out there for kexec-tools-1.102pre-<rev> to hopefully fix it.
I have kexec-tools-1.101-194.el5. Send me a link to your patch.
you can find it attached to bz 428310
I don't have access to that BZ.
I found the problem!!!! I was specifying the wrong root= in my command line to
load the crash kernel. I was specifying "root=/dev/cciss/c0d0p2" when it should
have been "root=/dev/VolGroup00/LogVol00."
The only thing that bothers me now is the MSI-X init failing with the unknown
error of -22. I did successfully register for an IOAPIC interrupt but I'm
concerned since this was not what I observed during development. Anyone have any
ideas about that behavior?
Mike Miller indicates this patch can be submitted for RHEL 5.2. The patch
supports all architectures.
Mike,
thanks for the effort and for solving this problem.I'm sorry I couldn't help you
with debugging,because your patch was running on my hw without problems.
Is the problem you mentioned in Comment #51 also successfully solved ?
(In reply to comment #54)
> Mike,
> thanks for the effort and for solving this problem.I'm sorry I couldn't help
you
> with debugging,because your patch was running on my hw without problems.
> Is the problem you mentioned in Comment #51 also successfully solved ?
Tomas,
Mike indicated this was an end-user mistype and did not affect the code. He was
trying to pass an invalid argument.
Thank you.
I'm still working on the MSI-X init failure.
(In reply to comment #56)
Mike,
it seems to me that the problem could be here in pci_enable_msix(msi.c)
pci_read_config_word(dev, msi_control_reg(pos), &control);
if (control & PCI_MSIX_FLAGS_ENABLE)
here -> return -EINVAL; /* Already in MSI-X
mode */
This could mean that the device is still in msi-x mode, so maybe a call to
pci_disable_msix or other clean up when reset_devices is set could help.
I tried adding the code to free_irq and pci_disable_msix but it did not resolve
the issue. When I made the call to free_irq the kernel complained that I was
trying to free an already freed IRQ0.
There are a lot of diffs in the 2.6.22.9 kernel versus the 2.6.18-53.el5.
Glancing thru the code it may be this:
msix_set_enable(dev, 0);/* Ensure msix is disabled as I set it up */
in msix_capability_init() in drivers/pci.msi.c that resolves the issue. I'm
testing again on a 2.6.16-xx kernel as a sanity check.
Tomas, do you see the same MSI-X init failure?
Yes, the test machine which is MSI-X capable I see the same failure and the
pci_disable_msix also didn't help. The kernel 2.6.22.9 is working well with your
patch ?
Mike,
Please let me know how I can help.
I've had a lot of experience with MSI/MSI-X.
Tomas,
Yes, testing with the 2.6.22.9 kernel is going well. I see no failures or errors
while booting the crash kernel. In your testing are you able to successfully
boot to the crash kernel, even though the MSI-X init fails? I guess what I'm
asking is are you able to boot up and save off the vmcore file to another system?
Tony,
If you're in Houston please stop by my office or lab.
Mike,
I was busy with another task,sorry for the late answer.
When the MSI-X init fails the system is hanging then and vmcore is not created.
Tomas,
Can you tell me which kernel, driver, server, and controller you're using? I've
had success on g5 servers using the P400 controller. So I'm a bit stumped on why
your setup is failing. I'm still investigating the initial failure.
Created attachment 293393 [details]
Screenshot
Mike,
I've on my system two boards, maybe this could be the difference ?
# cat /proc/driver/cciss/*
cciss0: HP Smart Array P400 Controller
Board ID: 0x3234103c
Firmware Version: 1.18
IRQ: 130
Logical drives: 1
Sector size: 2048
Current Q depth: 0
Current # commands on controller: 0
Max Q depth since init: 43
Max # commands on controller since init: 159
Max SG entries since init: 31
Sequential access devices: 0
cciss/c0d0: 72.77GB RAID 1(1+0)
cciss1: HP Smart Array P800 Controller
Board ID: 0x3223103c
Firmware Version: 2.08
IRQ: 162
Logical drives: 0
Sector size: 2048
Current Q depth: 0
Current # commands on controller: 0
Max Q depth since init: 0
Max # commands on controller since init: 1
Max SG entries since init: 0
Sequential access devices: 0
------------------------------------------
kernel is RHEL5.1; 2.6.18
In the /etc/sysconfig/kdump this is set : KDUMP_COMMANDLINE_APPEND="irqpoll
maxcpus=1 reset_devices"
Kdump is operational
after echo c > /proc/sysrq-trigger, is the system booting
the new kernel and then it locks - see screenshot in Comment #65
On this system(it's not MIS_X capable) the same procedure works and the vmcore
is created.
# cat /proc/driver/cciss/cciss0
cciss0: HP Smart Array 5i Controller
Board ID: 0x40800e11
Firmware Version: 2.58
IRQ: 169
Logical drives: 1
Sector size: 2048
Current Q depth: 0
Current # commands on controller: 0
Max Q depth since init: 17
Max # commands on controller since init: 122
Max SG entries since init: 31
Sequential access devices: 0
cciss/c0d0: 18.18GB RAID 0
I think the problem is the soft lockup and not the MSI-X failure. I also saw
that in my testing. But now I can't remember how I got past that. Getting old
sucks. I'll add a P800 to my configs and see if I can recreate the soft lockup.
Created attachment 293602 [details]
boot log with p400 and p800 in ML370G5
This boot log shows all of the unexpected IRQ messages during init
Created attachment 293604 [details]
kdump support patch
Tomas,
Are you using this patch? This is the one I'm using in my testing and although
I see some nasty looking messages about unexpected IRQ's I am still able to
boot up and save the vmcore file. I attached a log that shows those messages.
Mike,
yes the latest patch is the same as the one from 2008-01-18,to be sure I'll send
you my cciss.c from the test system.
Created attachment 294226 [details]
working + non working version
Mike, after echo c >/proc/sysrq-trigger with the cciss.c from the attachment
I'm getting softlockup's the cciss.c.orig works. Additionally there is also
difference on line 2136 - the lines
if (reset_devices)
return 0;
are removed.
Thank you, Tomas. I'll check out the diffs.
Are the systems that fail Opteron based? I see at the top of the bug where the
DL385 is listed. I've been doing all my testing on Intel based systems. Do you
have any Intel based HP platforms?
The failing system with the MSI-X capability is Intel based (Intel(R) Xeon(R)
CPU 5160 @ 3.00GHz).
I'm on the road right now returning 20080303. I also have an internal HP
customer seeing the same problems you are. When I get back I'll dig into this
and find the resolution.
HP ProLiant DL365 with Dual-Core AMD Opteron™ Processor 2216 (2.4 GHz)
- Embedded Smart Array SAS Controller P400i
RHEL5.1 (kernel 2.6.18-53.1.13.el5)
# uname -a
Linux dl365g1 2.6.18-53.1.13.el5 #1 SMP Mon Feb 11 13:27:27 EST 2008 x86_64
x86_64 x86_64 GNU/Linux
# modinfo cciss
filename: /lib/modules/2.6.18-53.1.13.el5/kernel/drivers/block/cciss.ko
license: GPL
version: 3.6.16-RH1
description: Driver for HP Controller SA5xxx SA6xxx version 3.6.16-RH1
...
...
# cat /sys/kernel/kexec_crash_loaded
1
# echo c > /proc/sysrq-trigger
...
...
Starting RPC idmapd: [ OK ]
EDAC k8 MC1: GART TLB error: transaction type(generic), cache level(generic)
EDAC k8 MC1: extended error code: GART error
Kernel panic - not syncing: MC1: processort context corrupt
So after having various problems with interrupts that differed from kernel to
kernel I decided to try a polling mode crash driver. The flow of operation is
"identical" to the interrupt driven code except that I do not do a request_irq.
Instead we start up a thread that calls the interrupt handler to complete
commands. If I use an upstream kernel I can successfully boot in a crashkernel.
When I try the 2.6.18-84.elPAE kernel included in the 20080303 5.2 beta it
fails. It fails in fs/blockdev.c in the do_open function. Specifically:
if (!part) {
struct backing_dev_info *bdi;
if (disk->fops->open) {
ret = disk->fops->open(bdev->bd_inode, file);
if (ret)
goto out_first;
}
ret = -16 so we jump to out_first.
We get to do_open via add_disk -> register_disk. In the upstream kernels these
functions are completely different so it's difficult to tell what's broken. I
also don't know where or how to find disk->fops->open(bdev->bd_inode, file). Can
someone at RH help out here?
Created attachment 298090 [details]
polling mode patch for kexec/kdump
Here is my patch for polling mode while in a crashkernel.
In Documentation/pci.txt:
There are (at least) two really good reasons for using MSI:
1) MSI is an exclusive interrupt vector by definition.
This means the interrupt handler doesn't have to verify
its device caused the interrupt.
But I note that
static inline long interrupt_not_for_us(ctlr_info_t *h)
{
#ifdef CONFIG_CISS_SCSI_TAPE
return (((h->access.intr_pending(h) == 0) ||
(h->interrupts_enabled == 0))
&& (h->scsi_rejects.ncompletions == 0));
#else
return (((h->access.intr_pending(h) == 0) ||
(h->interrupts_enabled == 0)));
#endif
}
static irqreturn_t do_cciss_intr(int irq, void *dev_id, struct pt_regs *regs)
{
ctlr_info_t *h = dev_id;
CommandList_struct *c;
unsigned long flags;
__u32 a, a1, a2;
if (interrupt_not_for_us(h))
return IRQ_NONE;
so even if the cciss driver has MSI/-X enabled, it checks the interrupt source
as if it were a shared interrupt vector.
This isn't really the root of the problem, but a micro-optimization that I
thought I would put here so I don't forget ....
Chip
(In reply to comment #80)
> I
> also don't know where or how to find disk->fops->open(bdev->bd_inode, file). Can
> someone at RH help out here?
disk is of type struct gendisk, so fops is of type block_device_operations,
initialized in cciss_init_one to cciss_fops. From
static struct block_device_operations cciss_fops = {
.owner = THIS_MODULE,
.open = cciss_open,
.release = cciss_release,
.ioctl = cciss_ioctl,
.getgeo = cciss_getgeo,
#ifdef CONFIG_COMPAT
.compat_ioctl = cciss_compat_ioctl,
#endif
.revalidate_disk = cciss_revalidate,
};
I would infer that the open method is cciss_open. The return value is -16,
which is -EBUSY, so I would assume you are hitting this
if (host->busy_initializing || drv->busy_configuring)
return -EBUSY;
in cciss_open.
Chip
I've printed out both host->busy_initializing and drv->busy_initializing. Both
are zero. So unless there's some asynch thread checking before they're cleared
that does not seem to be the issue.
Can we skip the MSI issues and try to resolve this polling problem? Different
kernels exhibit different interrupt problems so polling may be the best option.
(In reply to comment #84)
> I've printed out both host->busy_initializing and drv->busy_initializing. Both
> are zero. So unless there's some asynch thread checking before they're cleared
> that does not seem to be the issue.
Were you able to verify that disk->fops->open == cciss_open?
Chip
Not yet. But I think you're right about the busy_initializing. I added a flag to
skip that test in the polling driver and it wants to boot. I need to pull some
more debug out but it looks promising. :)
After I test it a bit more I'll post the latest patch.
-- mikem
Created attachment 298451 [details]
polling mode patch for kexec/kdump redone
This patch enables kdump support for the cciss driver. If we're booting to a
crashkernel we use polling mode in the driver to avoid any interrupt related
issues. Different kernels exhibit different failures when using interrupts
including failing to get an MSI-X vector or interrupt sharing issues when
there are multiple controllers in the system.
The down side about this approach is we must wait approximately 1 minute for
each controller to complete initialization after the reset. This could be
mitigated by initializing only the first controller. That should be adequate
since /proc will only exist on the root filesystem. I'm looking for feedback
on this assumption.
Please review and test this patch in your labs.
NOTE: Since upstream kernels do not exhibit the MSI-X failures the upstream
patch may be significantly different than this patch.
(In reply to comment #88)
> Created an attachment (id=298451) [edit]
> polling mode patch for kexec/kdump redone
A bit of debugging code leaked through; I'm dropping this:
diff --git a/fs/block_dev.c b/fs/block_dev.c
index d7b9a66..a6a06d5 100644
--- a/fs/block_dev.c
+++ b/fs/block_dev.c
@@ -899,6 +899,7 @@ static int do_open(struct block_device *bdev, struct file
*file, int for_part)
struct backing_dev_info *bdi;
if (disk->fops->open) {
ret = disk->fops->open(bdev->bd_inode, file);
+ printk("cciss: do_open: ret = %d\n", ret);
if (ret)
goto out_first;
}
(In reply to comment #88)
> Created an attachment (id=298451) [edit]
> polling mode patch for kexec/kdump redone
-ENOCOMPILE
CC [M] drivers/block/cciss.o
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c: In function
‘cciss_seq_show’:
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c:350: warning: format ‘%d’
expects type ‘int’, but argument 4 has type ‘loff_t’
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c: In function
‘cciss_init_one’:
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c:3444: error: ‘reset_c0’
undeclared (first use in this function)
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c:3444: error: (Each
undeclared identifier is reported only once
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c:3444: error: for each
function it appears in.)
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c: In function
‘cciss_completion_thread’:
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c:3792: warning: unused
variable ‘i’
make[2]: *** [drivers/block/cciss.o] Error 1
make[1]: *** [_module_drivers/block] Error 2
make: *** [modules] Error 2
Created attachment 298533 [details]
updated kdump patch
Sorry, I was doing a little hacking by hand and left a variable that I should
have deleted. I also cleaned up the warnings. This patch has been compile
tested.
I'm wondering if a spinlock around
if (host->busy_initializing || drv->busy_configuring)
return -EBUSY;
may be better than just skipping the test Comments?
A test kernel which includes this patch is available from
Chip
When I tried kexec with this kernel on a DL-585 and it failed. Here's what I did:
# kver=`uname -r`
# kexec -l /boot/vmlinuz-$kver --initrd=/boot/initrd-$kver.img
--command-line="`cat /proc/cmdline`"
# reboot
During the kexec boot, I get this message first
irq 177:11e47>] _6ad51>] default_idle+0x29/0x50
[<ffffffff80048a90>] cpu_idle+0x95/0xb8
[<ffffffff803d9801>] start_kernel+0x220/0x225
[<ffffffff803d922f>] _sinittext+0x22f/0x236
handlers:
[<ffffffff8811ab1b>] (do_cciss_intr+0x0/0x8b7 [cciss])
Disabling IRQ #177
followed by an oops that ends with this:
RBP: ffff8103fe68c7c8 R08: 0000000000000001 R09: ffff8100010503d4
R10: 0000000000000010 R11: ffffffff8015bb8e R12: ffff8103fe0ebae0
R13: ffff8103fe0ebae0 R14: ffff8103fe0ebad8 R15: ffff8103fe68c8c8
FS: 00000000110d98f0(0063) GS:ffff8103ffe6cbc0(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 00000000110ef000 CR3: 00000003ffe1d000 CR4: 00000000000006e0
Process init (pid: 1, threadinfo ffff8103fff18000, task ffff8103fff037a0)
Stack: ffff8103fe68c7c0 ffff8103fdc7e680 ffff8103fe0ebae0 ffffffff8005467b
ffff8103fe6af050 ffffffff80025656 ffff8103fff19f38 ffff8103fdc7e680
00000000fffffffe ffff8103fe6af050 ffff8103fe6af108 ffffffff80025656
Call Trace:
[<ffffffff8005467b>] sysfs_readdir+0x14f/0x171
[<ffffffff80025656>] filldir+0x0/0xb7
[<ffffffff80025656>] filldir+0x0/0xb7
[<ffffffff80034dce>] vfs_readdir+0x77/0xa9
[<ffffffff80038677>] sys_getdents+0x75/0xbd
[<ffffffff8002e55c>] sys_fcntl+0x2d0/0x2dc
[<ffffffff8005d116>] system_call+0x7e/0x83
Code: 0f 0b 68 89 ba 29 80 c2 1a 00 48 8b 55 00 48 39 da 74 1b 48
RIP [<ffffffff801466b6>] __list_add+0x24/0x68
RSP <ffff8103fff19e88>
<0>Kernel panic - not syncing: Fatal exception
Not sure if the oops had anything to do with cciss.
I will try adding "irqpoll" to the command line and see what happens.
Chip
With "irqpoll" I still get the "nobody cared" message, but the kexec kernel does
boot.
Chip
you should always specify irqpoll on the command line when doing a kexec, pretty
well as a rule. kexec has a difficult time quiesing and re-assigning interrupts
during a reboot.
Since we're polling in cciss interrupts are explicitly turned off so I doubt the
spurious interrupt is related to cciss.
Created attachment 298806 [details]
cleanup debug in kdump patch
My testing looks good on both Intel and AMD Proliants.
There was still some debug that bled thru. This patch cleans that up. It also
adds a spin_lock around the busy_initializing test. This approach is safer than
just bypassing the test in a crashkernel.
I built an ia64 kernel with this patch and it resolves the issue we were seeing.
Our problem presented itself as a hang rather than a panic however. With the
patch the kexec'ed kernel runs properly (kdump still broken on ia64 but for
other unrelated reasons).
I built an kernel with combined from patches #98,#92 and removed the part
mentioned in comment #39.
On an i686 everything works well, but on the other machine with MSI capability
(x86-64 system) I'm still getting the softlockup when the cciss.ko is
Would it be possible to upload _one_ patch that is the current version and
obsolete all the others? There are so many patches attached here that I am not
sure if I tested with the right one or not.
Created attachment 299186 [details]
This patch obsoletes all others in this bug
This patch combines the polling patch and the cleanup patch into one. This one
patch obsoletes all others in this bug. Chip, can you build and post a kernel
using this patch?
-- mikem
Created attachment 299200 [details]
My apologies, the last patch had compile warnings.
The last patch generated compile time warnings. This cleans that up and is the
only patch that should be used for testing kdump.
This patch definitely obsoletes all others. Chip, please use this patch to
build and post a new kernel.
If I understand comment #96 and comment #97 correctly, we have implemented a
polling mode in the driver on top of a polling mode in the kernel. Is that correct?
(In reply to comment #103)
> Created an attachment (id=299200) [edit]
> My apologies, the last patch had compile warnings.
I'm still getting them with the current patch:
/usr/src/kernel/rhel5/src/kernel/drivers/block/cciss.c:193: warning: ‘print_cmd’
declared ‘static’ but never defined
Looks like more debugging code that leaked through.
Chip
I don't understand how. The last hunk of the patch:
@@ -293,6 +293,8 @@ print_bytes (unsigned char *c, int len,
}
}
+#endif
+
static void
print_cmd(CommandList_struct *cp)
{
@@ -339,8 +341,6 @@ print_cmd(CommandList_struct *cp)
}
-#endif
-
static int
find_bus_target_lun(int ctlr, int *bus, int *target, int *lun)
{
moves the endif to before print_cmd. Can you ensure you actually have the right
patch? I obsoleted all others with my last post.
For comment #104 the kernel is not polling. All other devices get an interrupt.
We poll in cciss to workaround the various interrupt related issues. For
instance in 2.6.25-rc6 interrupt driven mode works fine even in the crashkernel.
The MSI/MSI-X is so different between -18.xxel5 and .25-rc6 you'd think you were
looking at 2 different OS's.
Fresh kernels here:
Chip
(In reply to comment #107)
> Fresh kernels here:
>
>
>
> Chip
>
Kdump working fine w/cciss using this kernel on ia64.
as per previous comment, release note revised, added to RHEL5.2 "Resolved Issues":
<quote>
(x86;x86_64;ia64) Crash dumping through kexec and kdump now functions reliably
with HP Smart Array controllers. Note that these controllers use the cciss driver.
</quote>
please advise if any further revisions are required. thanks!
Chip, Can you post the kernel-*-devel-2.6.18-86* packages for me? We're trying
to build rpms for the test groups and need those packages for our build environment.
Thanks,
mikem
(In reply to comment #110)
> Chip, Can you post the kernel-*-devel-2.6.18-86* packages for me? We're trying
> to build rpms for the test groups and need those packages for our build
environment.
OK, done.
Chip
Thanks.
We have a system that is exhibiting soft lockups with this latest kernel.
The BIOS banner shows
4096 MB Installed
ProLiant System BIOS - P57 (11/08/2006)
Proc 1: Dual-Core Intel(R) Xeon(TM) Processor (3.00 GHz/1333 MHz, 4MB L2)
Proc 2: Dual-Core Intel(R) Xeon(TM) Processor (3.00 GHz/1333 MHz, 4MB L2)
Power Regulator Mode: Dynamic Power Savings
Advanced Memory Protection Mode: Advanced ECC Support
Redundant ROM Detected - This system contains a valid backup system ROM.
Integrated Lights-Out 2 Advanced
iLO 2 v1.26 Nov 17 2006 192.168.52.196
Slot 1 HP Smart Array P400 Controller (512MB, v1.18) 1 Logical Drive
Slot 7 HP Smart Array P800 Controller (512MB, v2.08) 0 Logical Drives
After bringing up the system, I run
# export kver=`uname -r`
# kexec -l /boot/vmlinuz-$kver --initrd=/boot/initrd-$kver.img
--command-line="`cat /proc/cmdline` irqpoll reset_devices"
# reboot
The kexec kernel does not get beyond loading the cciss driver, and these
messages are displayed on the console every 10 seconds:
BUG: soft lockup - CPU#2 stuck for 10s! [insmod:479]
CPU 2:
Modules linked in: cciss(U) sd_mod(U) scsi_mod(U) ext3(U) jbd(U) ehci_hcd(U)
ohci_hcd(U) uhci_hcd(U)
Pid: 479, comm: insmod Tainted: G 2.6.18-86.el5.bz230717 #1
RIP: 0010:[<ffffffff8000c5f9>] [<ffffffff8000c5f9>] __delay+0xa/0x10
RSP: 0018:ffff81012ea9dd70 EFLAGS: 00000212
RAX: 00000000002d9dda RBX: ffff810037f4c000 RCX: 0000000073c24819
RDX: 0000000000000098 RSI: ffff810037f4c000 RDI: 00000000002dc493
RBP: 0000000000000000 R08: 0000000000000000 R09: ffff81000565cffc
R10: 0000000000008000 R11: ffff81012f9a0000 R12: ffff81012fd35870
R13: ffff81012ff9c000 R14: ffffffff80149d80 R15: 0000000000000202
FS: 0000000016fe8850(0063) GS:ffff81012ff24e40(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 00000000170085df CR3: 000000012e8e5000 CR4: 00000000000006e0
Call Trace:
[<ffffffff880b7bff>] :cciss:cciss_init_one+0x272/0x11d3
[<ffffffff80062efb>] thread_return+0x0/0xdf
[800a3d4d>] sys_init_module+0xaf/0x1e8
[<ffffffff8005d116>] system_call+0x7e/0x83
(In reply to comment #113)
> Call Trace:
> [<ffffffff880b7bff>] :cciss:cciss_init_one+0x272/0x11d3
This corresponds to the function
static int cciss_reset_controller(struct pci_dev *pdev,
int c, ctlr_info_t *hba)
in particular, it is getting stuck in this loop:
/* Wait some time for the scratchpad to be reset. */
do {
mdelay(25);
scratchpad = readl(hba->vaddr + SA5_SCRATCHPAD_OFFSET);
} while (scratchpad == CCISS_FIRMWARE_READY);
Do you see anything like:
ACPI: PCI Interrupt 0000:00:1d.0[A] -> GSI 16 (level, low) -> IRQ 169
uhci_hcd 0000:00:1d.0: UHCI Host Controller
uhci_hcd 0000:00:1d.0: new USB bus registered, assigned bus number 1
uhci_hcd 0000:00:1d.0: irq 169, io base 0x00001000
irq 169:6c3e1>] do_IRQ+0xe7/0xf5
[<ffffffff8005d615>] ret_from_intr+0x0/0xa [<ffffffff80064aa8>]
_spin_unlock_irqrestore+0x8/0x9
[<ffffffff801f12d2>] i8042_interrupt+0x42/0x1ec
[<ffffffff800108f3>] handle_IRQ_event+0x29/0x58
[<ffffffff800b70c2>] __do_IRQ+0xa4/0x103
[<ffffffff8006c3e1>] do_IRQ+0xe7/0xf5
[<ffffffff8005d615>] ret_from_intr+0x0/0xa
[<ffffffff8015bb8e>] vgacon_cursor+0x0/0x1a5
[<ffffffff80011e3c>] __do_softirq+0x53/0xd6
[<ffffffff8005e2fc>] call_softirq+0x1c/0x28
[<ffffffff8006c55e>] do_softirq+0x2c/0x85
[<ffffffff8005dc8e>] apic_timer_interrupt+0x66/0x6c
<EOI> [<ffffffff8015bb8e>] vgacon_cursor+0x0/0x1a5
[<ffffffff8008fd09>] vprintk+0x290/0x2dc
[<ffffffff800fd524>] proc_mkdir_mode+0x4c/0x63
[<ffffffff800b8a66>] register_handler_proc+0x9e/0xb0
[<ffffffff8008fda7>] printk+0x52/0xbd
[<ffffffff800b7681>] setup_irq+0x178/0x1c1
[<ffffffff801de557>] usb_hcd_irq+0x0/0x55
[<ffffffff800b777a>] request_irq+0xb0/0xd6
[<ffffffff801de276>] usb_add_hcd+0x2fc/0x52b
[<ffffffff801e643d>] usb_hcd_pci_probe+0x1e4/0x28b
[88011060>] :uhci_hcd:uhci_hcd_init+0x60/0xa7
[<ffffffff800a3d4d>] sys_init_module+0xaf/0x1e8
[<ffffffff8005d116>] system_call+0x7e/0x83
handlers:
[<ffffffff801de557>] (usb_hcd_irq+0x0/0x55)
Disabling IRQ #169
before you see the cciss driver load?
hmmm... since still unresolved, reverting back to old release note:
<quote>
(x86;x86_64;ia64) Crash dumping through kexec and kdump may not function
reliably with HP Smart Array controllers. Note that these controllers use the
cciss driver.
</quote>
please advise (before April 15) if any further revisions are required. thanks!
I thought this Bugzilla was a "blocker" for RHEL 5.2. If so, we need to allow
for further modifications to the release notes until this issue is resolved.
I can only reproduce this failure on an ML370. From the info in comment #113 it
appears the same is true in Red Hat's lab. I'm working now to determine what's
different on the ML370 from the other systems I've tested. Those systems include
the ML570 G4, DL580 G5, and DL385 G5.
(In reply to comment #120)
> I thought this Bugzilla was a "blocker" for RHEL 5.2. If so, we need to allow
> for further modifications to the release notes until this issue is resolved.
It is a blocker for the release. I am not sure whether we will block the release
notes from going to translation on April 15, though. Instead, maybe we can put
something in the release notes that says "refer to the web-based release note
updates for the latest status on cciss with kdump".
I have been able to determine the problem you're seeing on the ML370 is the old
firmware on the P400. For whatever reason after we issue the reset message the
scratchpad register never gets reset. That's why we loop forever. Please update
the firmware using the iso image available at:
Unzip the image, burn a CD, boot to the CD, click on the Firmware Update tab,
then click install.
Please update the firmware on both controllers and re-run your test.
Hi,
I had problems with the remote fw update, good news is that now is kexec+kdump
working for me on the ML370.
Chip, are you also satisfied with patch now ?
Latest kernels could be found on
Chip,
We have some testers reporting the /proc/vmcore file is size zero. Any ideas
what may cause this? I have not seen that problem in my testing.
(In reply to comment #127)
> Chip,
> We have some testers reporting the /proc/vmcore file is size zero. Any ideas
> what may cause this? I have not seen that problem in my testing.
Mike,
Was that on ia64? If so that sounds like this issue:
- Doug
(In reply to comment #126)
> Hi,
> I had problems with the remote fw update, good news is that now is kexec+kdump
> working for me on the ML370.
>
> Chip, are you also satisfied with patch now ?
>
> Latest kernels could be found on
>
I can kexec with this kernel, although I still get this message on bootup:
irq 177: nobody cared (try booting with the "irqpoll" option)
Call Trace:
<IRQ> [<ffffffff800b7a5c>] __report_bad_irq+0x30/0x7d
[<ffffffff800b7c8f>] note_interrupt+0x1e6/0x227
[<ffffffff800b7199>] __do_IRQ+0xbd/0x103
[<ffffffff80011ed2>] _d464b>] cache_reap+0x0/0x219
[<ffffffff8006ad51>] default_idle+0x29/0x50
[<ffffffff80048ae4>] cpu_idle+0x95/0xb8
[<ffffffff803d9801>] start_kernel+0x220/0x225
[<ffffffff803d922f>] _sinittext+0x22f/0x236
handlers:
[<ffffffff8812cb1b>] (do_cciss_intr+0x0/0x8b7 [cciss])
Disabling IRQ #177
(I am booting the kexec kernel with the "irqpoll" option.)
For comment #128: this is not ia64.
For comment #129: I sometimes see similar messages such as what I posted in
comment #118. I don't think it has anything to do with cciss. Comments?
I've instrumented the code a little bit and found that the reason we get this error
cciss: MSI-X init failed -22
is because of this test in drivers/pci/msi.c:pci_enable_msix
pci_read_config_word(dev, msi_control_reg(pos), &control);
if (control & PCI_MSIX_FLAGS_ENABLE)
return -EINVAL; /* Already in MSI-X mode */
In the kexec kernel, the value read from the control register is 0x00008003 and
#define PCI_MSIX_FLAGS_ENABLE (1 << 15)
In other words, MSIX was enabled by the pre-kexec kernel, and this state remains
in the PCI configuration memory of the device after the kexec kernel starts. So
this check succeeds, and thus the kexec kernel fails to allocate an MSIX vector
to the CCISS device.
I took a peek upstream, and it appears that the sanity checks in pci_enable_msix
have been consolidated into one function, pci_msi_check_device,
commit 24334a12533e9ac70dcb467ccd629f190afc5361
Author: Brice Goglin <brice@myri.com>
Date: Thu Aug 31 01:55:07 2006 -0400
MSI: Factorize common code in pci_msi_supported()
pci_enable_msi() and pci_enable_msix() use the same code to detect
whether MSI might be enabled on this device. Factorize this code in
pci_msi_supported(). And improve the documentation about the fact
that only the root chipset must support MSI, but it is hard to
find the root bus so we check all parent busses MSI flags.
Signed-off-by: Brice Goglin <brice@myri.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>
As Mike Miller pointed out, there has been a fair amount of churn in the MSI
code upstream. It appears that during this process, this particular test
(checking the PCI configuration space MSI control register to see if MSI is
already enabled) got dropped, although I haven't been able to find a commit log
that specifically says this was intentional.
I am continuing to dig around.
Chip
I also came to that conclusion but I'm not sure it's absolutely correct. I
notice on my Opteron systems that MSI-X always fails even when booting a fresh
"production" kernel. I'm adding debug to see how the MSI-X table is being
initialized. I also got my hands on a Hardware Diagnostic Tool to try and see
what the hardware tells me. Now I'm getting dangerous. :)
I've tested the 2.6.18-86.el5.bz230717 kernel RPM on rhel5.2s3 (installed using
--oldpackage) and I was able to do multiple kdumps on two different ia64-based
rx6600s (one with 4GiB memory and the other with 96GiB). I used
'crashkernel=768M' on both machines.
I've also tried using 2.6.18-86.el5.bz230717 on rhel5.2s2, but it fails there.
Even after upgrading kexec-tools to the rhel5.2s3 version (1.102pre-16.el5) it
wouldn't work. You really need to start with an rhel5.2s3 install.
Chuck Morrison tested kdump using the 2.6.18-86.el5.bz230717 kernel on rhel5.2s3
on an BL860c and it worked on that machine.
Marilise Cover also tested kdump an rx2660 using the same
snapshot3+2.6.18-86.el5.bz230717 combination with the same positive result.
Chip, for comment #132:
when is reset_devices set (and it should be with kdump), then the
pci_enable_msix shouldn't be even called.
/* If the kernel supports MSI/MSI-X we will try to enable that functionality,
* else we use the IO-APIC interrupt assigned to us by system ROM. If we're
* booting into a crashkernel we use polling mode.
*/
if (!reset_devices)
cciss_interrupt_mode(c, pdev, board_id);
Tom, Chip, Mike - is it possible to get a quick summary of this issue?
Specific questions:
1) Are there specific models where kdump wont work relibably, or is this across
the board for CCISS?
2) Is the scope of the issue that kdump "wont work reliably" or could this cause
other problems (like cause a panic that would not have happened if kdump wasn't
running)?
Thanks,
Sam
My quick summary is kdump is working with the later cciss controllers. The
controller firmware must be updated. We know that early versions of controller
firmware may have issues and recommend users update the firmware using the
Firmware Maintenance CD available on hp.com.
We are still performing regression tests in our labs to determine exactly what
controller/firmware combinations are required.
Created attachment 302760 [details]
use PCI power management to reset the controller
Hi Mike,
We have developed an alternate approach to your polling mode, and we would
appreciate any feedback you can give us. The idea is to use PCI power
management to reset the controller, and possibly reset the MSI/MSI-X
configuration if necessary on kexec. This approach seems to be a much lighter
touch to the driver, and has been successfully tested on x86_64 and ia64.
The patch is attached; note that cciss_reset_controller is defined but never
used and cciss_hard_reset_controller/cciss_reset_msi are the functions that get
used. Kernels built with this patch are available from
(n.b. trailing /cmc/ on the URL).
Chip
Chip,
Overall it looks pretty good, but
1. I pulled down the x86_64 kernel from the link in comment #143. Your patch was
not in there.
2. Why leave cciss_reset_controller if it's not used?.
I like using the PCI power management, that's a good idea. I plan to steal it
for an internal request. :) It's much quicker than doing the soft reset. Not
sure why that is the case.
Did you mean to strip out my patch completely and replace it with yours? I'm
guessing that's why we're still polling.
-- mikem
(In reply to comment #145)
> 2. Why leave cciss_reset_controller if it's not used?
I left it in there for testing purposes only. It the "Reset Controller" message
CDB seems to put the firmware into a strange state; although, even the PCI power
management reset doesn't seem to do the same thing as a warm boot (e.g. the
MSI-X bit remains set in PCI configuration space).
>.
That's strange. On my test machines, it does not do that. The "irq_poll"
kernel command line should cause the kernel to poll IRQs, however.
> Did you mean to strip out my patch completely and replace it with yours? I'm
> guessing that's why we're still polling.
Yes; my patch applies to the original cciss.c source code. Which is why I'm
surprised that you're seeing it grab IRQ 0. We don't see that here..
Chip
Chip,
I reversed my patch and now your patch is working as you expected, except that
MSI-X initialization still fails. As I've said before, I do not believe the
MSI-X issue is related to kexec or the crashkernel. MSI-X init fails even when
booting normally.
I suggest we open a new BZ for the MSI-X failure.
-- mikem
(In reply to comment #147)
>
>.
I got to the bottom of this just now. The issue was that the P600 controller
was taking much longer to recover from the PCI power-management reset than the
other controller in that system. What I did was to use the "No-op" CDB message
to determine when the controller had recovered from reset. This takes a couple
of minutes, but it kexecs fine if one waits long enough. I'm going to respin my
patch and post some updated kernels later today.
Chip
(In reply to comment #147)
> Chip,
> I reversed my patch and now your patch is working as you expected, except that
> MSI-X initialization still fails.
Just to clarify; MSI-X initialization is failing in the original kernel and the
kexec kernel, right? And even if MSI-X initialization fails, you are able to
get a core dump, right?
> As I've said before, I do not believe the
> MSI-X issue is related to kexec or the crashkernel. MSI-X init fails even when
> booting normally.
> I suggest we open a new BZ for the MSI-X failure.
If you are able to get a core dump even when MSI-X initialization fails, then
indeed it is a separate issue and should have a new BZ.
Chip
Correct, I was able to get a core dump even though MSI-X init failed. I'm trying
to figure out to use this hardware diagnostic tool. I'm hoping we can pinpoint
the root cause.
Created attachment 302938 [details]
Use PCI power management to reset the controller
Proposed fix for bz230717
The proposed fix resets the CCISS hardware in three steps
in the kexec kernel:
1. Use PCI power management states to reset the controller
in the kexec kernel.
2. Clear the MSI/MSI-X bits in PCI configuration space so
that MSI initialization in the kexec kernel doesn't fail.
3. Use the CCISS "No-op" message to determine when the
controller firmware has recovered from the PCI PM reset.
Created attachment 303074 [details]
New rev of previous patch for Smart Array 5i
Further testing revealed that the SmartArray 5i controller needs a long pause
between the PCI reset and the first No-op probe. This patch implements a 30s
pause for all device types, just in case there are others out there in the wild
with the same quirk.
This patch has been tested on the following controllers:
HP Smart Array 5i Controller
Board ID: 0x40800e11
Firmware Version: 2.62 (x86_64)
HP Smart Array P400 Controller
Board ID: 0x3234103c
Firmware Version: 2.08 (ia64) & 4.12 (x86_64)
HP Smart Array P600 Controller
Board ID: 0x3225103c
Firmware Version: 1.88 (ia64)
HP Smart Array P800 Controller
Board ID: 0x3223103c
Firmware Version: 4.12 (x86_64)
Pre-build binary kernels with this patch are available from
Any further testing/reports are much appreciated.
Chip
Kdump is successful here on i386
cciss0: HP Smart Array 5i Controller
Board ID: 0x40800e11
Firmware Version: 2.58
Mike, do you have any objections related to the latest pacth ?
Tomas/Chip:
I'm OK with this latest patch. When can we expect to see it in a snapshot?
-- mikem
(In reply to comment #155)
> Tomas/Chip:
> I'm OK with this latest patch. When can we expect to see it in a snapshot?
Possibly as soon as tomorrow. In the meantime, there are test kernels available
from the URL in comment #152.
Chip
We have pulled down those latest kernels and testing is getting underway locally.
in kernel-2.6.18-91.el5
You can download this test kernel from
Greetings Red Hat Partner,
A fix for this issue should be included in the latest packages contained in
RHEL5.2-Snapshot7--available now on partners.redhat.com.
We are nearing GA for 5.2--this is the last opportunity to test and confirm that
your issue is fixed. ASSIGNED.
If you are receiving this message in Issue Tracker, please reply with a message
to Issue Tracker about your results and I will update bugzilla for you. If you
need assistance accessing, please contact your Partner
Manager.
Thank you
HP retested with RHEL 5.2, Snapshot 7. We had to modify grub to reserve space
for the crashkernel for Snapshot7 to work. Is this expected behavior? If so,
does RH document this somewhere?
Sandy,
Please see the following knowledge base article:
<snip>
How to configure kdump
1. Verify the kexec-tools package is installed:
# rpm -q kexec-tools
2. Configure the /etc/kdump.conf file to specify the location where the
vmcore should be dumped. This can be another server via scp, a RAW device, or a
local filesystem.
3. Modify some boot parameters to reserve a chunk of memory for the capture
kernel. For i386 and x86_64 architectures, edit /etc/grub.conf, and append
crashkernel=128M@16M to the end of the kernel line.
<snip>
Responding to Comment #78 from me...success using:
System: HP ProLiant DL365 with Dual-Core AMD Opteron™ Processor 2216 (2.4 GHz)
- Embedded Smart Array SAS Controller P400i
# uname -a
Linux dl365g1 2.6.18-92.el5 #1 SMP Tue Apr 29 13:16:15 EDT 2008 x86_64 x86_64 xx
# cat /proc/cmdline
ro root=LABEL=/ rhgb quiet console=ttyS0 crashkernel=64M@16M
# grep KDUMP_COMMANDLINE_APPEND /etc/sysconfig/kdump
KDUMP_COMMANDLINE_APPEND="irqpoll maxcpus=1 reset_devices"
# ll -h /var/crash/2008-05-01-17\:52/vmcore
-r-------- 1 root root 5.9G May 1 17:53 /var/crash/2008-05-01-17:52/vmcore
# file vmcore
vmcore: ELF 64-bit LSB core file AMD x86-64, version 1 (SYSV), SVR4-style
Passed verification. Chip and Tomas, thanks for your help in resolving this
issue. I plan to steal your PCI power management reset in an internal. | https://partner-bugzilla.redhat.com/show_bug.cgi?id=230717 | CC-MAIN-2019-35 | refinedweb | 9,962 | 65.12 |
Welcome to the next installment in our Twitter clone series! In this tutorial, we'll build Ribbit from scratch, not using PHP, but with Ruby on Rails. Let's get started!
One quick service announcement before we get started: we won't be styling the UI for the application in this tutorial; that was done in Build a Twitter Clone From Scratch: The Design. I'll let you know if we have to tweak anything from that article.
Step 0: Setting up the Environment
First things first: I'm using Ruby 1.9.3 (p194) and Rails version 3.2.8 for this tutorial. Make sure that you're running the same versions. It doesn't matter how you install Ruby; you can use RVM ( tutorial ), rbenv, or just a regular Ruby installation. No matter the approach, each installer gives you the
gem binary, which you can then use to install Rails. Just use this command:
gem install rails
This installs the latest version of Rails, and we can start building our app now that it is installed. I hope you realize that Rails is a command line tool; you'll need to be comfortable in the terminal to be comfortable in this tutorial.
Step 1: Creating the Rails App
We begin by generating the project. In the command line, navigate to whatever directory you want the new project to reside in. Then, run this:
rails new ribbitApp
This single command generates multiple files inside a folder, called
ribbitApp. This is what Rails gives us to start with; it even installed the gems required for the project.
Let's
cd into that directory and initialize a git repo.
cd ribbitApp git init
One of the Rail-generated files is
.gitignore. If you're on a Mac, you'll probably want to add the following line to this file - just to keep things clean:
**.DS_Store
Now, we're ready to make our first commit!
git add . git commit -m 'initial rails app'
Step 2: Prepping the UI
The interface tutorial introduced you to Ribbit's images and stylesheet. Download those assets and copy the
gfx folder and
less.js and
style.less files into your app's
public directory.
Let's add a rule to
style.less: the style for our flash messages. Paste this at the bottom of the file:
.flash { padding: 10px; margin: 20px 0; &.error { background: #ffefef; color: #4c1717; border: 1px solid #4c1717; } &.warning { background: #ffe4c1; color: #79420d; border: 1px solid #79420d; } &.notice { background: #efffd7; color: #8ba015; border: 1px solid #8ba015; } }
That's all! Let's make another commit:
git add . git commit -m 'Add flash styling'
Now, let's create the layout. This is the HTML that wraps the main content of every page - essentially, the header and footer. A Rails app stores this in
app/views/layouts/application.html.erb. Get rid of everything in this file, and add the following code:
<!DOCTYPE html> <html> <head> <link rel="stylesheet/less" href="/style.less"> <script src="/less.js"></script> </head> <body> <header> <div class="wrapper"> <img src="/gfx/logo.png"> <span>Twitter Clone</span> </div> </header> <div id="content"> <div class="wrapper"> <% flash.each do |name, msg| %> <%= content_tag :div, msg, class: "flash #{name}" %> <% end %> <%= yield %> </div> </div> <footer> <div class="wrapper"> Ribbit - A Twitter Clone Tutorial<img src="/gfx/logo-nettuts.png"> </div> </footer> </body> </html>
There are three things you should notice about this. First, every URL to a public asset (images, stylesheet, JavaScript) begins with a forward slash (
/). This is so that we can still load the assets when we're in "deeper" routes. Second, notice the markup for displaying the flash messages. This displays flash messages when they exist. And third, note the
<%= yield %>; this is where we insert other "sub"-templates.
Okay, let's commit this:
git add . git commit -m 'Edit application.html.erb'
Step 3: Creating Users
Of course, we can't have a Twitter clone without users, so let's add that functionality. This can be a complex feature, but Rails makes it a little easier for us.
We naturally don't want to store our users' passwords as plain text; that's a huge security risk. Instead, we'll rely on Rails to automate an encryption process for our passwords. We begin by opening our
Gemfile and searching for these lines:
# To use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.0.0'
Using
has_secure_password is exactly what we want to do, so un-comment that second line. Save the file and head back to the command line. Now we have to run
bundle install to install the bcrypt gem.
We can create our user resource, once the gem has been installed.
A Rails resource is basically a model, its associated controller, and a few other files.
We create a resource by using the
rails generate (or
rails g) command:
rails generate resource user username name email password_digest avatar_url
We pass several parameters to this command, resulting in a
resource, called
user; its model has the following five fields:
username: a unique username, the equivalent of a Twitter handle.
name: the user's actual name.
password_digest: the encrypted version of their password.
avatar_url: the path to their avatar image.
We now need to migrate our database so that it's set up to store users. We accomplish this by running the following command:
rake db:migrate
This creates our
users table, but we don't directly interact with the database with Rails. Instead, we use the ActiveRecord ORM. We need to add some code to
app/models/user.rb. Open that file.
When Rails generated this file, it added a call to the
attr_accessible method. This method determines which properties are readable and writable on this class' instances. By default, all the aforementioned properties are accessible, but we want to change that:
attr_accessible :avatar_url, :email, :name, :password, :password_confirmation, :username
Most of these should make sense, but what's with
password and
password_confirmation? After all, we have only a
password_digest field in our database. This is part of the Rails magic that I mentioned earlier. We can set a
password and
password_confirmation field on a
User instance. If they match, the password will be encrypted and stored in the database. But to enable this functionality, we need to add another line to our
User model class:
has_secure_password
Next, we want to incorporate validation into our model. Calling
has_secure_password takes care of the password fields, so we'll deal with the
username, and
name fields.
The
name field is simple: we just want to ensure that it is present.
validates :name, presence: true
For the
username field, we want to ensure that it exists and is unique; no two users can have the same username:
validates :username, uniqueness: true, presence: true
Finally, the
validates :email, uniqueness: true, presence: true, format: { with: /^[\w.+-]+@([\w]+.)+\w+$/ }
This is a very simplistic email regex, but it should do for our purposes.
Now, what about that
avatar_url field? We want to use the user's email address and pull their associated Gravatar, so we have to generate this URL. We could do this on the fly, but it will be more efficient to store it in the database. First, we need to make sure that we have a clean email address. Let's add a method to our
User class:
private def prep_email self.email = self.email.strip.downcase if self.email end
That
private keyword means that all the methods defined after the keyword are defined as private methods; they cannot be accessed from outside the class (on instances).
This
prep_emailmethod trims the whitespace at the beginning and end of the string, and then converts all characters to lowercase.
This is necessary because we're going to generate a hash for this value.
We want this method to run just before the validation process; add the following line of code near the top of the class.
before_validation :prep_email
Next, let's generate the URL for the avatar by writing another method (put it under the one above):
def create_avatar_url self.avatar_url = "{Digest::MD5.hexdigest(self.email)}?s=50" end
We need to call this method before we save the user to the database. Add this call to the top of the file:
before_save :create_avatar_url
And that's it! Now we have the mechanics of our user functionality in place. Before writing the UI for creating users, let's commit our work so far:
git add . git commit -m 'Create user resource'
Step 5: Writing The User UI
Building a UI in Rails means that we need to be aware of the routes that render our views. If you open
config/routes.rb, you'll find a line like this:
resources :users
This was added to the
routes.rb file when we generated the user resource, and it sets up the default REST routes. Right now, the route we're interested in is the route that displays the form for creating new users:
/users/new. When someone goes to this route, the
new method on the users controller will execute, so that's where we'll start.
The users controller is found in
app/controllers/users_controller.rb. It has no methods by default, so let's add the
new method within the
UsersController class.
def new @user = User.new end
As you know, Ruby instance variables begin with
@ - making
@user available from inside our view. Let's head over to the view by creating a file, named
new.html.erb in the
app/views/users folder. Here's what goes in that view:
<img src="/gfx/frog.jpg"> <div class="panel right"> <h1>New to Ribbit?</h1> <%= form_for @user do |f| %> <% if @user.errors.any? %> <ul> <% @user.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> <% end %> <%= f.text_field :email, placeholder: "email" %> <%= f.text_field :username, placeholder: "username" %> <%= f.text_field :name, placeholder: "name" %> <%= f.password_field :password, placeholder: "password" %> <%= f.password_field :password_confirmation, placeholder: "password" %> <%= f.submit "Create Account" %> <% end %> </div>
This is actually the view that serves as the home page view, when a user is not logged in. We use the
form_for helper method to create a form and pass it the
@user variable as a parameter. Then, inside the form (which is inside the Ruby block), we first print out errors. Of course, there won't be any errors on the page the first time around.
However, any input that fails our validation rules results in an error message that is displayed in a list item.
Then, we have the fields for our user properties. Since this design doesn't have any labels for the text boxes, I've put what would be label text as the fields' placeholder (using the
placeholder attribute). These won't display in older browsers, but that's not relevant to our main goal here.
Now, what happens when the user clicks the "Create Account" button? This form will
POST to the
/users route, resulting in the execution of the
create method in the users controller. Back to that controller, then:
def create @user = User.new(params[:user]) if @user.save redirect_to @user, notice: "Thank you for signing up for Ribbit!" else render 'new' end end
We start by creating a new user, passing the
new method the values from our form. Then, we call the
save method. This method first validates the input; if the data is in the correct format, the method inserts the record into the database and returns
true. Otherwise, it returns
false.
If
@user.savereturns
true, we redirect the viewer to... the
@userobject itself?
This actually redirects to the path for that user, which will be
/users/. If
@user.save returns false, we re-render the
/users/new path and display any validation errors. We also pre-populate the form fields with the the user's previously provided information. Clever, eh?
Well, if we direct the viewer to their new user profile, we need to create that page next. This triggers the
show method in the users controller, so we'll add that first:
def show @user = User.find(params[:id]) end
This method looks at the id number in the route (for example,
/users/4) and finds the associated user in the database. Just as before, we can now use this
@user variable from the view.
Create the
app/views/users/show.html.erb file, and add the following code:
<div id="createRibbit" class="panel right"> <h1>Create a Ribbit</h1> <p> <form> <textarea name="text" class="ribbitText"></textarea> <input type="submit" value="Ribbit!"> </form> </p> </div> <div id="ribbits" class="panel left"> <h1>Your Ribbit Profile</h1> <div class="ribbitWrapper"> <img class="avatar" src="<%= @user.avatar_url %>"> <span class="name"><%= @user.name %></span> @<%= @user.username %> <p> XX Ribbits <span class="spacing">XX Followers</span> <span class="spacing">XX Following</span> </p> </div> </div> <div class="panel left"> <h1>Your Ribbits</h1> <div class="ribbitWrapper"> Ribbits coming . . . </div> </div>
You'll notice that we have a few placeholders in this view. First, there's the form for creating a new ribbit. Then there's the follower, following numbers, and the list of your ribbits. We'll come to all this soon.
There's one more thing to do in this step: we want the root route (
/) to show the new user form for the time being. Open the
config/routes.rb file again, and add this line:
root to: 'users#new'
This simply makes the root route call the
new method in the users controller. Now, we just need to delete the
public/index.html file which overrides this configuration. After you delete that, run the following in the command line:
rails server
You could also run
rails s to achieve the same results. As you would expect, this starts the rails server. You can now point your browser to
localhost:3000/, and you should see the following:
Now, fill in the form and click "Create Account." You should be sent to the user profile, like this:
Great! Now we have our user accounts working. Let's commit this:
git add . git commit -m 'User form and profile pages'
Step 6: Adding Session Support
Even though we implemented the user feature, a user cannot log in just yet. So, let's add session support next.
You may have recognized the way we've created user accounts.
I've taken this general method from Railscast episode 250. That episode also demonstrates how to create session support, and I'll use that approach for Ribbit.
We start by creating a controller to manage our sessions. We won't actually store sessions in the database, but we do need to be able to set and unset session variables. A controller is the correct way to do that.
rails generate controller sessions new create destroy
Here, we create a new controller, called
sessions. We also tell it to generate the
new,
create, and
destroy methods. Of course, it won't fill in these methods, but it will create their "shell" for us.
Now, let's open the
app/controllers/sessions_controller.rb file. The
new method is fine as is, but the
create method needs some attention. This method executes after the user enters their credentials and clicks "Log In." Add the following code:
def create user = User.find_by_username(params[:username]) if user && user.authenticate(params[:password]) session[:userid] = user.id redirect_to rooturl, notice: "Logged in!" else flash[:error] = "Wrong Username or Password." redirect_to root_url end end
We use the
find_by_username method on the
User class to retrieve the user with the provided username. Then, we call the
authenticate method, passing it the password. This method was added as part of the
use_secure_password feature. If the user's credentials pass muster, we can set the
user_id session variable to the user's ID. Finally, we redirect to the root route with the message "Logged in!".
If the user's credentials fail to authenticate, we simply redirect to the root route and set the flash error message to "Username or password was wrong."
Logging out fires the
destroy method. It's a really simple method:
def destroy session[:userid] = nil redirect_to root_url, notice: "Logged out." end
This code is fairly self-explanatory; just get rid of that session variable and redirect to the root.
Rails helped us out once again and added three routes for these methods, found in
config/routes.rb:
get "sessions/new" get "sessions/create" get "sessions/destroy"
We want to change the
sessions/create route to POST, like this:
post "sessions/create"
We're almost ready to add the login form to our views. But first, let's create a helper method that allows us to quickly retrieve the currently logged-in user. We'll put this in the application controller so that we can access it from any view file. The path to the application controller is
app/controllers/application_controller.rb.
private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user
We pass
User.find the
session[:user_id] variable that we set in the sessions controller. The call to
helper_method is what makes this a helper method that we can call from the view.
Now, we can open our
app/views/layouts/application.html.erb file and add the login form. See the
<span>Twitter Clone</span> in the
<header> element? The following code goes right after that:
<% if current_user %> <%= link_to "Log Out", sessions_destroy_path %> <% else %> <%= form_tag sessions_create_path do %> <%= text_field_tag :username, nil, placeholder: "username" %> <%= password_field_tag :password, nil, placeholder: "password" %> <%= submit_tag "Log In" %> <% end %> <% end %>
If the user is logged in (or, if a non-
nil value is returned from
current_user), we'll display a logout link, but we'll add more links here later. You might not have seen the
link_to method before; it takes the provided text and URL and generates a hyperlink.
If no user is logged in, we use the
form_tagmethod to create a form that posts to the
seesions_create_path.
Note that we can't use the
form_for method because we don't have an instance object for this form (like with our user object). The
text_field_tag and
password_field_tag methods accept the same parameters: the name for the field as a symbol, the value for the field (
nil in this case), and then an options object. We're just setting a placeholder value here.
There's a bit of a glitch in our session support: a user is not automatically logged in, after they create a new user account. We can fix this by adding a single line to the
create method in the
UserController class. Right after the
if @user.save line, add:
session[:user_id] = @user.id
Believe it or not, the above line of code finishes the session feature. You should now be able to re-start the Rails server and log in. Try to log out and back in again. The only difference between the two functions is the lack of the login form when you're logged in. But we'll add more later!
Let's commit this:
git add . git commit -m 'users are now logged in upon creation'
Step 7: Creating Ribbits
Now we're finally ready to get to the point of our application: creating Ribbits (our version of tweets). We begin by creating the ribbit resource:
rails g resource ribbit content:text user_id:integer rake db:migrate
This resource only needs two fields: the actual content of the ribbit, and the id of the user who created it. We'll migrate the database to create the new table. Then, we'll make a few modifications to the new Ribbit model. Open
app/models/ribbit.rb and add the following:
class Ribbit < ActiveRecord::Base default_scope order: 'createdat DESC' attr_accessible :content, :userid belongs_to :user validates :content, length: { maximum: 140 } end
The
default_scope call is important; it orders a list of ribbits in from the most recent to least recent. The
belongs_to method creates an association between this Ribbit class and the User class, making our user objects have a
tweets array as a property.
Finally, we have a
validates call, which ensures that our ribbits don't exceed 140 characters.
Oh, yeah: the flip side of the
belongs_to statement. In the User class (
app/models/user.rb), we want to add this line:
has_many :ribbits
This completes the association; now each user can have many ribbits.
We want users to have the ability to create ribbits from their profile page. As you'll recall, we have a form in that template. So let's replace that form in
app/view/users/show.html.erb, as well as make a few other changes. Here's what you should end up with:
<% if current_user %> <div id="createRibbit" class="panel right"> <h1>Create a Ribbit</h1> <p> <%= form_for @ribbit do |f| %> <%= f.textarea :content, class: 'ribbitText' %> <%= f.submit "Ribbit!" %> <% end %> </p> </div> <% end %> <div id="ribbits" class="panel left"> <h1>Your Ribbit Profile</h1> <div class="ribbitWrapper"> <img class="avatar" src="<%= @user.avatar_url %>"> <span class="name"><%= @user.name %></span> @<%= @user.username %> <p> <%= @user.ribbits.size %> Ribbits <span class="spacing">XX Followers</span> <span class="spacing">XX Following</span> </p> </div> </div> <div class="panel left"> <h1>Your Ribbits</h1> <% @user.ribbits.each do |ribbit| %> <div class="ribbitWrapper"> <img class="avatar" src="<%= @user.avatar_url %>"> <span class="name"><%= @user.name %></span> @<%= @user.username %> <span class="time"><%= time_ago_in_words(ribbit.created_at) %></span> <p> <%= ribbit.content %> </p> </div> <% end %> </div>
There are three areas that we change with this code. First, we remove the HTML form at the top and replace it with a call to the
form_for helper function. Of course, it makes sense that we only need a text area for the content (we already know the current user's ID). Note that
form_for accepts a
@ribbit as the parameter, and we need to add that object to the
users_controller#show method (
app/controllers/users_controller.rb):
def show @user = User.find(params[:id]) @ribbit = Ribbit.new end
Notice that we wrap the whole form section (the
<div id="createRibbit">) with an
if statement. If there's no current user (meaning no one is logged in), we won't show the ribbit form.
Next, we want to display the number of the user's ribbits. That number appears just above their follower count. Remember that our user instance has a
ribbits property. So, we can replace our filler text with this:
<%= @user.ribbits.size %> Ribbits
We need to show the user's ribbits. We can loop over that same
ribbits array, and display each ribbit in turn. That's the final part of the code above.
Lastly, (at least as far as ribbit creation is concerned), we need to modify the
create method in the ribbits controller (
app/controllers/ribbits_controller.rb. The method executes when the user clicks the "Ribbit!" button.
def create @ribbit = Ribbit.new(params[:ribbit]) @ribbit.userid = current_user.id</p> if @ribbit.save redirect_to current_user else flash[:error] = "Problem!" redirect_to current_user end end
I know the "Problem!" error message isn't very descriptive, but it will do for our simple application. Really, the only error that could occur is a ribbit longer than 140 characters.
So, give it a try: start the server (
rails server), log in, go to your profile page (, but of course, any user profile page will do), write a ribbit, and click "Ribbit!". The new ribbit should display in the ribbit list on your profile page.
Okay, let's commit these changes:
git add . git commit -m 'ribbit functionality created'
Step 8: Creating the Public Tweets Page
Next up, we want to create a public page that includes all the ribbits made by all users. Logically, that should be the ribbits index view, found at
/ribbits. The controller method for this is
ribbits_controler#index. It's actually a very simple method:
def index @ribbits = Ribbit.all include: :user @ribbit = Ribbit.new end
The first line fetches all the ribbits and their associated users, and the second line creates the new ribbit instance (this page will have a ribbit form).
The other step, of course, is the template (
app/view/ribbits/index.html.erb). It's similar to the user profile>Public>
In this template, the avatar image and the user's name are surrounded by a link that points to the user's profile page. Let's also add a link to the public tweets page. Just before the logout link in
app/view/layouts/application.html.erb, add this:
<%= link_to "Public Ribbits", ribbits_path %>
Finally:
git add . git commit -m 'added the public ribbits page'
Step 9: Following Other Users
It wouldn't be a Twitter clone if we couldn't follow other users, so let's work on that feature next.
This is a little tricky at first. Think about it: our
User records need to to follow other
User records and be followed by other
User records. It's a many-to-many, self-joining association. This means we'll need an association class, and we'll call it "Relationship". Start by creating this resource:
rails g resource relationship follower_id:integer followed_id:integer rake db:migrate
This model only needs two fields: the follower's ID, and the followed's ID (note: the terminology here can get a little confusing. In our case, I'm using the term "followed" to mean the user being, well, followed).
Next up, we want to relate the
User model with this
Relationship model, which we do from both sides. First, in the
Relationship class (
app/models/relationship.rb), we want to add these two lines:
belongs_to :follower, classname: "User" belongs_to :followed, classname: "User"
The first line relates a
User record to the
follower_id field, and the second line relates a
User record to the
followed_id field. It's important to include the class name, because Rails can't infer the class from the property names ('follower' and 'followed'). It can, however, infer the correct database fields (
follower_id and
followed_id) from those names.
Now, in the
User class (
app/model/user.rb), we have to first connect each user model to its associated relationships:
has_many :follower_relationships, classname: "Relationship", foreign_key: "followed_id" has_many :followed_relationships, classname: "Relationship", foreign_key: "follower_id"
We need to create two associations, because we have two sets of relationships per user: all the people following them and all the people they follow. And no, those foreign keys shouldn't be switched. The
follower_relationship association is responsible for all of your followers. Hence, it needs the
followed_id foreign key.
Then, we can use those relationships to get to the followers on the other side of them:
has_many :followers, through: :follower_relationships has_many :followeds, through: :followed_relationships
These give our user records the
followers and
followeds methods. They're both methods that return the arrays of our followers or the people we follow, respectively.
Finally, let's add two methods to our user model that helps us with the UI:
def following? user self.followeds.include? user end def follow user Relationship.create follower_id: self.id, followed_id: user.id end
Let's commit these changes before tweaking the UI.
git add . git commit -m 'created user relationships infrastructure'
Now, the UI is all on the user profile pages, which is
app/views/users/show.html.erb. We'll start with something simple: the follower and following count. See where we have this?
<span class="spacing">XX Followers</span> <span class="spacing">XX Following</span>
We'll replace these placeholder values, like so:
<span class="spacing"><%= @user.followers.count %> Followers</span> <span class="spacing"><%= @user.followeds.count %> Following</span>
We have the follow/unfollow button under these counts, but there are a few states we need to consider. First, we don't want to show any button if the user either is viewing their own profile or if they're not logged in. Second, we want to display an "Unfollow" button if the user already follows this profile's owner.
<% if current_user and @user != current_user %> <% if current_user.following? @user %> <%= form_tag relationship_path, method: :delete do %> <%= submit_tag "Unfollow" %> <% end %> <% else %> <%= form_for @relationship do %> <%= hidden_field_tag :followed_id, @user.id %> <%= submit_tag "Follow" %> <% end %> <% end %> <% end %>
A Rails resource is a basically a model, its associated controller, and a few other files.
Put this code just under the paragraph that holds the above spans.
The forms are the more complex parts here. First, if the current user already follows the viewed user, we'll use
form_tag to create a form that goes to the
relationship_path. Of course, we can't forget to set the
method as
delete because we're deleting a relationship.
If the current user doesn't follow the viewed user, we'll create a
form_for the current relationship. We'll simply use a hidden field to determine which user to follow.
If you're paying attention, you'll know that something's missing: the ability to manipulate a relationship instance from this view. We need a
Relationship instance. If the current user doesn't already follow this user, we need to create a blank relationship. Otherwise, we need to have a relationship on hand to delete! Back to
app/controllers/users_controller.rb, and add the following to the
show method:
@relationship = Relationship.where( follower_id: current_user.id, followed_id: @user.id ).first_or_initialize if current_user
This is a bit different from the usual way of finding or creating a record. This initializes a blank
Relationship instance if no records are found that match the
where parameters. Of course, we only want to do this if there is a
current_user.
The routes for this model are enabled by the
resources :relationship line in the
config/routes.rb, so we don't have to worry about that.
Now, in
app/controllers/relationships_controller.rb, we'll start with the
new method:
def create @relationship = Relationship.new @relationship.followed_id = params[:followed_id] @relationship.follower_id = current_user.id</p> if @relationship.save redirect_to User.find params[:followed_id] else flash[:error] = "Couldn't Follow" redirect_to root_url end end
Pretty standard stuff by now, right? We'll create the relationship, save it, and redirect back to the user's profile.
The
destroy method is also simple:
def destroy @relationship = Relationship.find(params[:id]) @relationship.destroy redirect_to user_path params[:id] end
Now, create another user (or four) and have a few users follow other users. You should see the text of the follow buttons change, as well as the follower / following count.
Great! Now we can commit this feature:
git add . git commit -m 'Following other users is now working'
Step 10: Creating a Few Other Pages
There are a few other simple pages that we want to add. First, let's create a page to list all the registered users. This would be a great place to find new friends, see their pages, and eventually follow them. Logically, this should be the
/users route, so we'll use the
UsersController#index method:
def index @users = User.all end
Now, for
app/views/users/index.html.erb:
<div id="ribbits" class="panel left"> <h1>Public Profile</h1> <% @users.each do |user| %> <div class="ribbitWrapper"> <a href="<%= user_path user %>"> <img class="avatar" src="<%= user.avatar_url %>"> <span class="name"><%= user.name %></span> </a> @<%= user.username %> <p> <%= user.ribbits.size %> Ribbits <span class="spacing"><%= user.followers.count %> Followers</span> <span class="spacing"><%= user.followeds.count %> Following</span> </p> <% if user.ribbits.first %> <p><%= user.ribbits.first.content %></p> <% end %> </div> <% end %> </div>
Finally, let's add a link to this page to the top of our template. Let's also add a link to the logged-in user's profile. Right beside the "Public Ribbits" link, add:
<%= link_to "Public Profiles", users_path %> <%= link_to "My Profile", current_user %>
Next is the buddies page. This is where a user goes to view the ribbits of the people they follow; we'll also redirect users to this page when they're logged in and view the home page.
Strangely, finding the correct place in the code for this page is a bit tricky. After all, each page in our Rails app must be based on a method in one of our controllers. Best practice dictates that each controller has six REST methods that control a resource. In this case, we want to view the ribbits of a subset of users, which, at least to me, seems to be a bit of an edge case. Here's how we'll handle it: let's create a
buddies method in the
UsersController:
def buddies if current_user @ribbit = Ribbit.new buddies_ids = current_user.followeds.map(&:id).push(current_user.id) @ribbits = Ribbit.find_all_by_user_id buddies_ids else redirect_to root_url end end
Obviously, there's nothing to show if a user isn't logged in, so we'll check the
current_user. If we're not logged in, we redirect to the root URL (
/). Otherwise, we create a new ribbit (for our new ribbit form).
We then need to find all ribbits from the current user and the people they follow.
We can use the
followeds array property, and map it to only retrieve the user ids. Then, we push in the current user's ids as well and finally retrieve the ribbits from those users.
Let's store the template in
app/views/users/buddies.html.erb; it's very similar to our public ribbits>Buddies'>
We need to make a route for this method, in order to use it. Open
config/routes.rb and add the following:
get 'buddies', to: 'users#buddies', as: 'buddies'
Now, we can go to
/buddies and see the page!
There's something else we want to do with this, however. If a logged-in user goes to the root URL, we need to redirect them to
/buddies. Remember, this route is currently:
def new @user = User.new end
Let's change it to this:
def new if current_user redirect_to buddies_path else @user = User.new end end
We should also add a link to the buddies page in
app/views/layouts/application.html.erb:
<%= link_to "Buddies' Ribbits", buddies_path %>
And now, we'll commit these changes:
git add . git commit -m 'added buddies page'
Step 11 Deploying to Heroku
The last step is to deploy the application. We'll use Heroku.
The last step is to deploy the application. We'll use Heroku. I'm going to assume that you have a Heroku account, and that you've installed the Heroku toolbelt (the command line tools).
We run into a problem before we even begin! We've been using a SQLite database, because Rails uses SQLite by default. However, Heroku doesn't use SQLite; it uses PostgreSQL for the database. We have to make a change to our Gemfile, a change that actually breaks our local copy of the app (unless you install and configure a PostgreSQL server). Here's my compromise: I'll show you how to do it here, and you can play with my deployed version. But you don't have make the change on your local project.
Thankfully, switching Rails to PostgreSQL is very simple. In our
Gemfile, there's a line that looks like this:
gem "sqlite"
Change that line to this:
gem "pg"
We now must install this gem locally, in order to update
Gemfile.lock. We do this by running:
bundle install
And we commit:
git add . git commit -m 'updated Gemfile with Postgres'
We can now create our Heroku application. In our project directory, run:
heroku create git push heroku master
And finally:
heroku open
That opens your browser with your deployed Heroku application. You can play with my deployed copy.
That's It!
And there you go! We just built a really simple Twitter clone. Sure, there are dozens of features we could add to this, but we nailed the most important pieces: users, ribbits, and followings.
Remember, if Rails isn't your racket, check out the other tutorials in this series! We have a whole line-up of Ribbit tutorials using different languages and frameworks in the pipes. Stay tuned!
| http://code.tutsplus.com/articles/building-ribbit-in-rails--net-29116 | CC-MAIN-2015-11 | refinedweb | 5,979 | 66.54 |
the String literal "Hello" is interpreted as a String reference variable referring to a String object with value "Hello"
"Hello" == s means It checks reference of "Hello" present in pool
Why do you post code snippets as screenshots and not the plain code snippets (and you should of course UseCodeTags )? If I want to compile (and execute) your code snippets, I know have to type them myself. So I'll be losing precious time which I could otherwise be spending on typing a nice reply... And another reason: attached images are not searchable using the search engine, plain text or a code snippet definitely is.
Because Java allows only one public class per fi le, we can create two fi les, Animal.java
and Lion.java, in which the Lion class extends the Animal class. Assuming they are in the
same package, an import statement is not required in Lion.java to access the Animal class.
Here are the contents of Animal.java:
And here are the contents of Lion.java:
Which of these classes compile and use a default constructor? (Choose all that apply)
...
G. public class Bird { void Bird() { }
What is the result of the following?
Answers: | https://www.coderanch.com/u/354057/Aleksandra-Pestova | CC-MAIN-2019-43 | refinedweb | 199 | 65.93 |
Electronic devices you build with Arduino start to become very cool when you connect them to the network.
Let’s see how to connect an Arduino to a WiFi network.
The Arduino must have WiFi connectivity, for example the Arduino MKR WiFi 1010, which is the one I use, or the Arduino Uno WiFi Rev2 and others.
We’re going to use the library WiFiNINA. This library is super handy and lets us connect to a WiFi network, but also create a WiFi network if we want.
Start your Arduino sketch using:
#include <SPI.h> #include <WiFiNINA.h>
The SPI library is used by the WiFiNINA library, so load it as well. SPI stands for Serial Peripheral Interface
The
WiFiNINA library gives us access, among other things, to the
WiFi object that we’re going to use.
Now let’s work on the body of the
setup() function, the only Arduino core function we’re going to implement (we’ll leave
loop() empty).
void setup() { }
First, we’re going to define 2 strings to hold the network name, the SSID, and the network password.
I use Arduino Create, so I just use constants that I’ll fill separately in the
Secret tab:
char ssid[] = SECRET_SSID; char pass[] = SECRET_PASS;
Next we’re going to initialize the Serial interface to communicate information from the Arduino back to Arduino Create:
Serial.begin(9600);
And we wait until it’s ready using
while (!Serial);
Next we put WiFi.begin() inside a loop that checks if its return value is
WL_CONNECTED, and keeps retrying every 2 seconds until it is:
int status = WL_IDLE_STATUS; while (status != WL_CONNECTED) { Serial.print("Connecting to "); Serial.println(ssid); status = WiFi.begin(ssid, pass); delay(2000); }
We first initialize it to
WL_IDLE_STATUS, another constant of WiFiNINA, but we could also initialize it to an empty string.
Once we end this loop we are connected and we can call the
WiFi.localIP() method to get the device IP address and print it to the serial:
Serial.print("IP address: "); Serial.println(WiFi.localIP());
Here’s the full program:
#include <SPI.h> #include <WiFiNINA.h> void setup() { char ssid[] = SECRET_SSID; char pass[] = SECRET_PASS; Serial.begin(9600); while (!Serial); int status = WL_IDLE_STATUS; while (status != WL_CONNECTED) { Serial.print("Connecting to "); Serial.println(ssid); status = WiFi.begin(ssid, pass); delay(5000); } Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void loop() { }
You have access to other information now, like the network SSID with
WiFi.SSID() and the signal strength using
WiFi.RSSI():
Serial.print("Signal strength in dBm: "); Serial.print(WiFi.RSSI());
At this point you are connected and you can move on to other tasks.
Note: you might have a NINA firmware upgrade available. Add this check to your program:
if (WiFi.firmwareVersion() < WIFI_FIRMWARE_LATEST_VERSION) { Serial.println("Firmware upgrade available"); }
to know if that’s the case. If so, using the Arduino IDE (I can’t see how to do this from Arduino Create) connect to the board then load the example sketch
File -> Examples -> WiFiNINA -> Tools -> FirmwareUpdater
Then open the
Tools -> WiFi101 / WiFiNINA Firmware Updater menu:
and press the
Update Firmware button:
| https://flaviocopes.com/arduino-connect-wifi/ | CC-MAIN-2022-27 | refinedweb | 517 | 59.19 |
Related
Tutorial
I18n with React and i18next.
i18next is an i18n framework written in and for JavaScript. It provides the standard i18n features of interpolation, formatting, and handling plurals and context.
A 30,000 foot view of i18next would be that it provides a function that takes a key, some options, and returns the value for the current language.
The following is a simple example of using the aforementioned function with a simple key and no options.
i18n.t('error') // 'An error occurred' in English and // 'Ocurrió un error' in Spanish.
Because the function will likely be called several times in an app, the creators of i18next have chosen a shortname:
t – which is short for translate. It is common to see the
t function in the i18next documentation and you will see it used here in this post.
Although i18next is designed to work with many frameworks, this post will focus on how to internationalize a React app using i18next.
In order to use i18next with React, the
t function needs to be made available to the components that need to be internationalized. This can be done by various means. We’ll demonstrate a couple below.
Manual Integration
Before i18next can be used, it needs to be configured. Here is the configuration used by the examples in this post. It turns off value-escaping since React already takes care of that for us, it sets the current language to English, and it hardcodes translations for two languages (English and Spanish). See the i18next configuration for more options.
import i18next from 'i18next'; i18next .init({ interpolation: { // React already does escaping escapeValue: false, }, lng: 'en', // 'en' | 'es' // Using simple hardcoded resources for simple example resources: { en: { translation: { age: { label: 'Age', }, home: { label: 'Home', }, name: { label: 'Name', }, }, }, es: { translation: { age: { label: 'Años', }, home: { label: 'Casa', }, name: { label: 'Nombre', }, }, }, }, }) export default i18next
Manual integration begins with importing our pre-configured instance of i18next which will provide the
t function.
import React from 'react'; // Import a pre-configured instance of i18next import i18n from './i18n'; function Gator({ gator }) { return ( <div className="Gator"> <label>i18n.t('name.label')</label> <span>{ gator.name } 🐊</span> <label>i18n.t('age.label')</label> <span>{ gator.age }</span> <label>i18n.t('home.label')</label> <span>{ gator.home }</span> </div> ) }
Although the example above will render the labels using the current language (English), the labels won’t be updated after the language changes since React does not yet know how to determine when the language has changed. So, let’s tweak the code to re-render the component when the language changes.
import React from 'react'; // Import a pre-configured instance of i18next import i18n from './i18n'; class Gator extends React.Component { constructor(props) { super(props) this.state = { lng: 'en' } this.onLanguageChanged = this.onLanguageChanged.bind(this) } componentDidMount() { i18n.on('languageChanged', this.onLanguageChanged) } componentWillUnmount() { i18n.off('languageChanged', this.onLanguageChanged) } onLanguageChanged(lng) { this.setState({ lng: lng }) } render() { let gator = this.props.gator, lng = this.state.lng return ( <div> <label>{ i18n.t('name.label', { lng }) }</label> <span>{ gator.name } 🐊</span> <label>{ i18n.t('age.label', { lng }) }</label> <span>{ gator.age }</span> <label>{ i18n.t('home.label', { lng }) }</label> <span>{ gator.home }</span> </div> ) } }
See a working example of the above code.
Although we fixed the problem of the component not re-rendering after the language changes, we introduced a lot of boilerplate code:
Added two lifecycle methods (
componentDidMountand
componentWillUnmount). (Which means we had to switch from a functional component to a class component.)
Added an event listener so we can notify React that the language changed.
Introduced a mechanism to cause the component to re-render. In the example above, state is being used. Another alternative is to call
forceUpdateafter the language changes.
Is there an easier way? Yes, there is!
The react-i18next Binding
Fortunately, there is an easier way with a binding:
react-i18next.
import React from 'react'; import { I18n } from 'react-i18next'; // Import a pre-configured instance of i18next import i18n_unused from './i18n'; function Gator({ gator }) { return ( <I18n> { (t) => { return ( <div> <label>{ t('name.label') }</label> <span>{ gator.name } 🐊</span> <label>{ t('age.label') }</label> <span>{ gator.age }</span> <label>{ t('home.label') }</label> <span>{ gator.home }</span> </div> ) } } </I18n> ) }
The React binding for i18next provides the
I18n component. It expects a single function expression as its children. This function will be passed the
t function. (The use of a function expression as children of a component is known as the function-as-children pattern.)
A lot easier! See a working example of the above code.
So, take a look at i18next and react-i18next for more details on configuration, more advanced translation, and other binding options. | https://www.digitalocean.com/community/tutorials/react-i18n-with-react-and-i18next | CC-MAIN-2020-34 | refinedweb | 775 | 60.82 |
Object.entries error when running Cordova app on Android device
Hi there,
I have a Quasar (v16) Cordova app that runs fine on my Android phone unless I install the Crosswalk plugin to support older Android versions. The Crosswalk plugin is no longer supported so isn’t as up-to-date as the new Chrome version on my phone. When I run it with the Crosswalk plugin, I get the following error in the console and the app just shows a white screen.
Uncaught TypeError: Object.entries is not a function
Since Object.entries is a newer feature of javascript I’m not surprised Crosswalk doesn’t support it. What I’m confused about is that I thought Quasar used Babel to compile newer Javascript down to ES5 syntax so I wouldn’t expect to see this error at all since Object.entries should have been transpiled to ES5 code. Everything seems to be setup properly in my project. Here’s by .babelrc file:
{ "presets": [ [ "env", {"modules": false} ], "stage-2" ], "plugins": ["transform-runtime"], "comments": false }
I also tried adding babel-polyfill using a Quasar plugin which still didn’t work. I’m not sure if this is the correct approach but here’s my plugin code:
import 'babel-polyfill'; export default () => { }
Any thoughts would be appreciated. Here’s my “quasar info” if it’s helpful:
Operating System Darwin(17.5.0) - darwin/x64 NodeJs 8.11.1 Global packages NPM 6.1.0 yarn Not available quasar-cli 0.15.14 vue-cli 2.9.6 cordova 8.0.0 Important local packages quasar-cli 0.15.14 (Quasar Framework CLI) quasar-framework 0.16.0 (Build responsive websites, PWAs, hybrid mobile apps and Electron apps, all simultaneously using same codebase) quasar-extras 1.0.2 (Quasar Framework fonts, icons and i18n.) vue 2.5.16 (Reactive, component-oriented view layer for modern web interfaces.) vue-router 3.0.1 (Official router for Vue.js 2) vuex 3.0.1 (state management for Vue.js) electron Not available babel-core 6.26.0 (Babel compiler core.) webpack 3.11.0 (Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.) webpack-dev-server 2.11.1 (Serves a webpack app. Updates the browser on changes.)
Thanks,
Jason
Hi,
- Quasar DOES use Babel.
- Object.entries has nothing to do with Babel.
- Not all browsers support Object.entries, so you need a polyfill for those that don’t.
Okay, any suggestions on how to add the babel-polyfill? Am I on the right track with the plugin syntax I quoted?
The link I gave you has the polyfill you need. Add an app plugin with it and place it as first in the queue
For babel polyfill, just tamper with the .babelrc – mind that for v0.16+ u’re on Babel 7, not 6 | https://forum.quasar-framework.org/topic/2432/object-entries-error-when-running-cordova-app-on-android-device | CC-MAIN-2018-34 | refinedweb | 499 | 70.09 |
Flutter: Equatable & It’s usage in Bloc
In Dart or any language, We always find it difficult to compare objects and return results. If we do not implement it correctly then in the long term you will face a lot of problems, as this will provide the wrong output as data is not compared as expected, Let's see an example of how dart solve it?
First, we will see the problem which we will be trying to fix
void main() {
User user = User('jitsm555');
print(user == User('jitsm555')); // Output: false
}
class User {
final String name;
User(this.name);
}
As you can see above, both objects having the same values, but while comparing they returns false. This happens because both have different hashcode internally.
Solution!!!
import 'package:equatable/equatable.dart';
void main() {
User user = User('jitsm555');
print(user == User('jitsm555')); // Output: true
}
class User extends Equatable {
final String name;
User(this.name);
@override
List<Object?> get props => [name];
}
Object and data comparison is always hard to do, So here comes the
Equatable as it overrides
== and
hashCode internally, which solves our purpose of data comparison and eventually will save a lot of boilerplate code.
If we are not using the
Equatable then we have to write our own code for object comparison like
class User {
final String name;
User(this.name);
@override
bool operator ==(Object other) => other is User &&
name == other.name;
@override
int get hashCode => name.hashCode;
}
So, coming to the usage of the
Equatable in Bloc, becomes important as it updates the state as per the object changes, so before jumping on it, I recommend you to read the blog on the Bloc Mystery | Part 1 first, as the below topic required some knowledge around it.
Dependency:
To use the
Equatable add the dependency in pubspec.yaml file
dependencies:
equatable: ^2.0.2
In
Bloc, we have to extend
Equatableto
States and Eventsclasses to use this functionality. This helps us when it comes to stream as we need to decide state updation based on it.
Ex:
abstract class LoginState extends Equatable {}
LoginState will not make duplicate calls and will not going to rebuild the widget if the same state occurs. Now, think we haven't used
Equatable it here, then how many times Widget will be rebuild.
Equatable comes with
props property which have its own purpose in object comparison, I have seen developers been neglecting this, and later face a lot of time in debugging.
Let’s see
props usage in Equatable and what makes it special
Define State without props:
class LoginLoadSuccess extends LoginState {
final String name;
final List<User> users;
const LoginLoadSuccess([this.name, this.users = const []]);
}
Define State with props:
props declared when we want
State to be compared against the values declared inside
props List
class LoginLoadSuccess extends LoginState {
final String name;
final List<User> users;
const LoginLoadSuccess([this.name, this.users = const []]); @override
List<Object> get props => [name, users]; }
props property decides which objects we should consider for object comparison, Suppose if we remove the name from the
props then
State will only consider the
users field, avoiding the
name field for object comparison. That is why it's important to use it carefully, as one mistake can cost a lot of time.
Bloc Stream Usage:
As we extending
State with Equatable which makes a comparison of old state data with new state data.
For example, let's look at the below example here
LoginState will build a widget only once, which will avoid the second call as it is duplicated.
@override
Stream<LoginState> mapEventToState(MyEvent event) async* {
final List<User> users = [User(), User()];
yield LoginLoadSuccess(users);
yield LoginLoadSuccess(users);
/// Second call will be avoided, means widget will not rebuild
} | https://medium.com/flutterworld/flutter-equatable-its-use-inside-bloc-7d14f3b5479b?source=user_profile---------1---------------------------- | CC-MAIN-2022-27 | refinedweb | 618 | 57.4 |
need help to translate python script to Qt quick qml code
Hi, I am wondering if somebody could help me to translate py- code to Qt qml code because i have one code script in py and one in qml.
The py code looks like this
from socket import * HOST = '' PORT = 8001 ADDR = (HOST, PORT) serversock = socket(AF_INET, SOCK_STREAM) serversock.bind(ADDR) serversock.listen(2) while 1: print("Wait for connection") clientsock, addr = serversock.accept() print('Connected from' + str(addr)) while 1: data = clientsock.recv(2048) print(data) serversock.close()
and i wont to translate it and use 'data' variable as angle in my ui in qml. please help me.
- p3c0 Moderators
Hi @antemort,
It can't be done purely in QML. You will need to use sockets on C++ side. Qt has C++ API's for sockets. QTcpServer creates a server and QTcpSocket for client. After that you will need to expose them to QML.
Edit: Some one has tried to do that already. See | https://forum.qt.io/topic/55302/need-help-to-translate-python-script-to-qt-quick-qml-code | CC-MAIN-2018-05 | refinedweb | 166 | 76.62 |
Hey there. I have a system set up that creates an array of objects that forms a grid. I'm trying to make the grid start on the position of the gameObject that it's attached to, but I'm having trouble referring to the gameObject. Here's my code.
using UnityEngine;
using System.Collections;
public class GridCreator : MonoBehaviour
{
public int width = 10;
public int height = 10;
public Cell[,] cells;
public GameObject unit;
public class Cell
{
public Vector3 pos;
public int sizeMod = 1;
public Cell(int x, int y)
{
pos = new Vector3((x*sizeMod)+gameObject.transform.position.x,0,(y*sizeMod)+gameObject.transform.position.y);
}
}
void Awake ()
{
cells = new Cell[width, height];
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
cells[x,y] = new Cell(x, y);
GameObject newunit = Instantiate(unit, cells[x,y].pos, Quaternion.identity) as GameObject;
}
}
}
}
The grid works and instantiates Units correctly if I take the additives (+gameObject.transform.position.x/y) out of the equation here
pos = new Vector3((x*sizeMod)+gameObject.transform.position.x,0,(y*sizeMod)+gameObject.transform.position.y);
But when I leave them in I get this error
Cannot access a nonstatic member of outer type `UnityEngine.Component' via nested type `GridCreator.Cell'
Cannot access a nonstatic member of outer type `UnityEngine.Component' via nested type `GridCreator.Cell'
Am I trying to access the variable incorrectly? Not sure what I'm doing wrong. Thanks for any help.
Answer by Owen-Reynolds
·
Oct 12, 2012 at 07:46 PM
The rule causing the problem is that classes can only use things "inside" of them. `Cell` can't use globals `width` or `GameObject` like a function would be able to, since `Cell` isn't really part of `GridCreator` (some other script could make some cells, but have no gridCreator anywhere in the scene.)
Maybe change the constructor: `public Cell(gameObject myBase, float x, float y);` Might also move `sizeMod` up into Grid.
What some people do is have a back pointer, so Cell would have `GridCreator mygrid;`, set at creation, and could use `myGrid.gameObject`. But not worth it for just cells.
Hey, thanks a lot! That really helps. I think a lot of my problems are caused by confusing classes and functions- I'm going to do some reading on that subject.
Anyways, everything made sense besides the 'back pointer' section- not really sure what you meant.
[CODE]Keep Gameobject position exactly at mouse cursor when cast float position to int
1
Answer
How to move a gameObject without affecting its childrens' positions?
2
Answers
Simultaneously moving GameObjects using C# script.
3
Answers
Change transform.position.y in a loop
1
Answer
postion scale and rotation greyed out and not working
1
Answer | https://answers.unity.com/questions/331499/transformposition-error-1.html | CC-MAIN-2020-29 | refinedweb | 457 | 57.06 |
A Top Shelf Web Stack—Rails 5 API + ActiveAdmin + Create React App
Blending a rock-solid API and CMS with the absolute best in front-end tooling, built as a single project and hosted seamlessly on Heroku.
Rails is an incredible framework, but sometimes you don’t need all the bulk of the asset pipeline and a layout system. In Rails 5 you can now create an API-only Rails app, meaning you can build your front-end however you like. It’s no longer 100% omakase.
Like using
create-react-app, for example.
And for projects that don’t need CMS-like capabilities, that works pretty great straight away.
create-react-app even supports proxying API requests in development, so you can be running two servers locally without having to do any
if NODE_ENV === ‘development’ voodoo. Gosh,
create-react-app is great.
Still, I’ve worked with ActiveAdmin on a few projects, and as an interface between you and the database, it’s pretty unmatched for ease of use. There are a host of customisation options, and it’s super easy for clients to use if you need a CMS.
The issue is that removing the non-API bits of Rails breaks it. Not ideal. But never fear, all is not lost! With a couple of steps you can be running a Rails 5, API-only, serving your
create-react-app client on the front end, with full access to ActiveAdmin.
We’re going to build it, then we’re going to deploy it to Heroku, and then we’re going to celebrate with a drink. Because we will have earned it. Given that theme, we’re going to build an app that shows us recipes for delicious drinks. It’s thematically appropriate!
So, what are we going to use?
- Create React App
All the power of a highly-tuned Webpack config without the hassle.
- Rails in API-only mode
Just the best bits, leaving React to handle the UI.
- ActiveAdmin
An instant CMS backend.
- Seamless deployment on Heroku
Same-origin (so no CORS complications) with build steps to manage both Node and Ruby.
And it’ll look something like this:
If you want to skip ahead to the finished repo, you can do so here:
And if you want to see it in action, you do that here:
Let’s get started, shall we?
Step 1: Getting Rails 5 set up
With that delicious low-carb API-only mode
There are a ton of great tutorials on getting Ruby and Rails set up in your local development environment. will work out your operating system, and will walk you through getting Rails 5.0.2 installed.
If you’ve already got Rails 5, awesome. The best way to check that is to run
rails -v in your terminal. If you see
Rails 5.0.1, we’re ready to roll.
Note: At the time of writing the newest version of Rails, 5.1, doesn’t quite work with these steps. Best to stick with 5.0.1 for now.
So, first up, start a new Rails app with the
--api flag:
mkdir list-of-ingredients
cd list-of-ingredients
rails new . --api
Right. We are already part of the way to making a delicious cocktail. Maybe use this time to congratulate yourself, because you’re doing great.
Once the install process has finished, you can fire up Rails:
bin/rails s -p 3001
It’ll do some stuff, eventually telling you that it’s listening on. If you visit it, you should see something like this:
There’s even a kitten! So great.
Step 2: Getting ActiveAdmin working
With a couple of small tweaks to Rails
(Thanks to Roman Rott for this bit.)
So, incredibly (and awesomely, which is not a word), you can still get ActiveAdmin working like a charm with this set up. Before you can install it, you just need to switch a couple of Rails classes and add some middleware that ActiveAdmin relies on.
First, you’ll need to swap your
application_controller.rb from using the
API to using
Base:
As Carlos Ramirez mentions, this requirement is an unfortunate design decision from ActiveAdmin, as now any controllers we make that inherit from
ApplicationController won’t take advantage of the slimmed down API version.
There is a work around, though. Add a new
api_controller.rb to your
app/controllers:
So you can get your controllers to inherit from
ApiController, not
ApplicationController. For example:
From there we’ll need to ensure that the middleware has the stuff it needs for ActiveAdmin to function correctly. API mode strips out cookies and the flash, but we can 100% put them back. In your
config/application.rb add these to the
Application class:
Your
config/application.rb should look something like this:
Do not confuse the flash with The Flash, who is likely heavily trademarked. I don’t have the kind of money I’d need laying around if he turns out to be litigious.
You should also move
gem 'sqlite3' into the
:development, :test group and add
gem 'pg' into the
:production group. Heroku doesn’t support sqlite, and you’ll need to swap those things around once you get to deploying your app. Why not do it now?
Now, keen developers will be sharpening their pitchforks right now, because you should 100% run Postgres locally if you’re developing a Real Application, to ensure your local environment matches your production one. But for the purposes of this exercise, let’s just be roguish and tell no one. They’ll never know.
Bundle and install everything, and then install ActiveAdmin:
bundle install
bin/rails g active_admin:install
You should see something like the following:
Finally, migrate and seed the database:
bin/rake db:migrate
bin/rake db:seed
Once again you can fire up Rails:
bin/rails s -p 3001
But this time hit. You should see something like this:
And you should take a moment to feel pretty great, because that was a lot.
You can log into ActiveAdmin with the username
admin@example.com and the password
password. Security! You can change it really easily in the rad ActiveAdmin environment, though, so fear not.
Step 3: Adding
create-react-app as the client
Yay! Super-speedy Webpack asset handing!
(Shout out to Full Stack React for this bit.)
So. We need a front end. If you don’t have
create-react-app yet, install it globally with:
npm install create-react-app -g
And then, in the root of your app, generate it into the
/client folder:
npm install -g create-react-app
create-react-app client
It’ll take a bit. You probably have time for a cup of tea, if you’re feeling thirsty.
Once it’s installed, jump in and fire it up:
cd client
npm start
Right! You have a simple
create-react-app running. That is good. But we can do more than that.
As I mentioned earlier, one of the best bits about working with
create-react-app and an API is that you can automatically proxy the API calls via the right port, without needing to swap anything between development and production. To do this, jump into your
client/package.json and add a proxy property, like so:
"proxy": ""
Your
client/package.json file will look like this:
(You might wonder why we’re proxying port
3001. Once we hook everything up our scripts will be running the API on port
3001, which is why we’ve been running Rails that way. Nice one picking up on that, though, eagle-eyes. Asking the right questions!)
fetch (along with a bunch of fancy new language features and polyfills you should 100% check out) is included with
create-react-app, so our front end is ready to make calls to the API. But right now that would be pretty pointless—we’ll need some data to actually fetch.
So, let’s get this cocktail party started. We’ll need two relations, the
Drinks, and the
Ingredients that those drinks are made with. You’ll also potentially need a blender, but honestly, a margarita with a couple of ice cubes is still so delicious. Promise.
Now, normally I’d say avoid scaffolding in Rails, because you end up with a ton of boilerplate code that you have to delete, but for the purposes of the exercise, let’s use it. And then delete it. Do what I say, not what I do and all that.
Before that though, I should mention something. One downside to ActiveAdmin using
inherited_resources, which reduces the boilerplate for Rails controllers, is that Rails then uses it when you scaffold anything in your app. That breaks stuff:
"Could not find"is never a good start to the last line of output.
Fortunately, this is a solvable problem. You just need to tell Rails to use the regular scaffolding process. You know, from when we were young and scrappy and people didn’t say JavaScript fatigue like having options is a bad thing. The Good Old Days.
Just remind Rails which
scaffold_controller to use in your
config/application.rb and we can be on our way:
config.app_generators.scaffold_controller = :scaffold_controller
Your
application.rb should look something like this, and everything should be right with the world again:
Crisis averted!
So, scaffolding. First, the
Drink model:
bin/rails g scaffold Drink title:string description:string steps:string source:string
Then, the
Ingredient model:
bin/rails g scaffold Ingredient drink:references description:string
Notice that the
Ingredient references the
Drink. This tells the
Ingredient model to
belong_to the
Drink, which is part of the whole
has_many relative database association thing.
See, my Relational Databases 101 comp-sci class was totally worth it.
Unfortunately this won’t tell your
Drink model to
has_many of the
Ingredient model, so you’ll also need to add that to
app/models/drink.rb all by yourself:
Then we can migrate and tell ActiveAdmin about our new friends:
bin/rake db:migrate
bin/rails generate active_admin:resource Drink
bin/rails generate active_admin:resource Ingredient
Go team.
Now, Rails is a security conscious beast, so you’ll need to add some stuff to the two files ActiveAdmin will have generated,
app/admin/drink.rb and
app/admin/ingredient.rb. Specifically, you’ll need to permit ActiveAdmin to change your model, which when you think about it is pretty important.
First up,
app/admin/drink.rb:
Then
app/admin/ingredient.rb:
Without
permit_params, you can never edit your delicious drink recipes. Not on my watch.
In our routes, we’ll need to hook up the drinks resource. I like to scope my API calls to
/api, so let’s do that:
Start the server:
bin/rails s -p 3001
And you should be able to visit to see… *drumroll*
{
}
Nothing. We should probably add some drinks. To save some time, here’s a
db/seeds.rb that I prepared earlier, featuring a delicious negroni and a delicious margarita:
You’ve already migrated, so it’s just a case of seeding the database:
bin/rake db:seed
Now when you refresh you should see:
So, we’re pretty much good to go on the database front. Let’s just massage our scaffolded controllers a little. First, let’s cut back the
DrinksController. We can make sure
def index only returns the
id and
title of each drink, and we can make sure
def show includes the
id and
description of each ingredient of the drink. Given how little data is being sent back, you could just grab everything from
index, but for the purposes of showing how this could work in the Real World, let’s do it this way.
You’ll want to make sure your controllers are inheriting from
ApiController, too.
And let’s just get rid of 99% of
ingredients_controller.rb, because it’s not going to be doing a lot:
And now we have some fancy data to feed the client. Good for us! This is a big chunk of the setup, and you’re doing great. Let’s celebrate with some Adventure Time, and take this opportunity to think about how great that cocktail is going to be. Talk about earning it:
Next up, let’s create a
Procfile in the root of the app for running the whole Rails /
create-react-app setup locally, because Heroku uses
procfiles to manage your bundle. If you haven’t used them before, you can read about them here.
We’ll call it
Procfile.dev, because while we do need to run a Node server locally we’ll be deploying a pre-built bundle to Heroku, and we won’t need to run a Node server as well. Having a Node server and Rails server locally massively speeds up development time, and it is pretty great, but it’s overkill for production. Your
Procfile.dev should look like this:
Procfiles are managed by
foreman, which if you don’t have installed you can add with:
gem install foreman
And you can fire up the new set up with:
foreman start -f Procfile.dev
Who wants to type that every single time though? Why not make some rake tasks to manage running development and production locally for you? Just add
start.rake to your
/lib/tasks folder:
You’ll also need to add Foreman to your Gemfile (I’d recommend putting it in your
:development group:
Then install it:
bundle install
And from there all you need to do to fire up your development environment is run the super simple:
bin/rake start
Glorious! Ten keystrokes to fire up two servers? What magic is this?!
And to test production (which will take a while to build without a grleat deal of output):
bin/rake start:production
Well, that step was a lot. So what’s happening here?
foreman will start the front end,
/client, on port
3000 and the API on port
3001. It’ll then open the client, in your browser. You can access ActiveAdmin via the API, at, just like you’ve been doing all along.
Now we can sort our the React app. The simplest thing is to just check it works:
In your console, you should see the API call logged:
Which we can 100% use to grab the actual details of each fine beverage from
drinks#show in Rails. Sure, we could’ve just sent everything from the server because it’s only two drinks, but I figure this is closer to how you’d really build something, so let’s go with it.
Now, rather than go through the full front end application, you can either grab the
client folder from the repo:
Or you can install the following dependencies:
npm install semantic-ui-react --save
npm install semantic-ui-css --save
And add them to your
/client app. First, add the css to
client/src/index.js:
And the all the fancy bells and whistles to your
client/src/app.js:
Either way you choose to do it, you’re golden!
You should have a fancy front end that uses Semantic UI and looks something like this:
Step 4: Get everything ready for production
With Rails serving the Webpack bundle
So, how do we get our Rails app serving the Webpack bundle in production?
That’s where the magic of NPM’s
package.json‘s
postinstall comes in. We can get Heroku to build the app on the server, and copy the files into the
/public directory to be served by Rails. We end up running a single Rails server managing our front end and back. It’s win win! There are a couple of steps to make that happen.
First up, let’s make a
package.json file in the root of the app, which tells Heroku to compile the
create-react-app. The
postinstall command will get run after the node build is (you guessed it) installed. First up it’ll build it, then it’ll move the files into
/public. How easy is that?
As always, you are doing great. Also, honestly, my hands are getting sore. On the plus side, this step is super short! Go team!
Step 5: Deploy it to Heroku
And celebrate, because you’ve earned it
We are super close! Soon, everything the light touches will be yours, including a fresh, tasty beverage. So let’s create a new Heroku app and get this thing over the finish line:
heroku apps:create
Now, if you push to Heroku, this looks like a dual Rails / Node app. But your Node code needs to be executed first so it can be served by Rails. This is where Heroku’s buildpacks come in — they transform your deployed code to run on Heroku. We can tell Heroku, via the terminal, to use two buildpacks (or build processes) in a specific order. First
nodejs, to manage the front end build, and then
ruby, to run Rails:
Let’s make a
Procfile, in the root, for production, which will tell Heroku to run the Rails app:
Before we deploy it’s worth noting that
create-react-app defines
react-scripts, which manages the build of the client (along with a bunch of other stuff), as a
devDependency in your
package.json. Heroku sets an
ENV var,
NPM_CONFIG_PRODUCTION, to true, which means your build will disregard any
devDependencies and it will fail. Not ideal.
But not unfixable! To overcome this you have two options. You can either set
NPM_CONFIG_PRODUCTION to false:
heroku config:set NPM_CONFIG_PRODUCTION=false
Or you’ll need to move the
react-scripts in your
/client/package.json out of
devDependencies into
dependencies:
Both options will work, but given that you’ll likely have more than one
devDependency, it’s easier to tell Heroku to recognise them. Normally I’d say you should always tune your production environment for, well, production, but in this case we’re building the assets with Node, not serving them.
With that sorted, we can deploy this beautiful beverage-based beast:
git add .
git commit -vam "Initial commit"
git push heroku master
Heroku will, following the order of the buildpacks, build the
client, and then fire up Rails.
You’ll need to migrate and seed your database on Heroku, or ActiveAdmin will not be thrilled (and you won’t be able to log in). That’s easy enough though:
heroku run rake db:migrate
heroku run rake db:seed
And there you have it:
When you visit your app you’ll see the
create-react-app on the client side, displaying some delicious drink recipes. You’ll also be able hit
/admin (for example,) and access your database using that truly terrible username and password ActiveAdmin chose for you. I’d recommend changing those on production ASAP. I did, so you can’t just change all my demo recipes to be really rude. I’m gutted you’d even try to, honestly, after everything we’ve been through.
It’s worth noting, if you’re planning to use
react-router from here, there’s a few more steps you’ll need to take. Logan asked about it, so thanks Logan!
This isn’t exactly the most thrilling demo (especially given it suggests putting prosecco in a negroni, which is a capital crime in some parts of the world) but hopefully it gets you up and running. All the ingredients to make a delicious Rails API / Activeadmin /
create-react-app beverage are here, and the sky’s the limit.
You can see a ready-to-go repo here, too:
Thanks for taking the time to have a look, and I genuinely hope you celebrated with a drink, alcoholic or otherwise. 🍹
Shout out to Roman Rott and Full Stack React for the inspiration to put this together. And a massive thank you to Glen and Xander for taking the time to make suggestions and proofread this small essay for me. 💖
If you have any questions leave a comment or say hi via Twitter. Alternatively, enjoy a GIF of a dog wearing a hat. | https://medium.com/superhighfives/a-top-shelf-web-stack-rails-5-api-activeadmin-create-react-app-de5481b7ec0b | CC-MAIN-2017-34 | refinedweb | 3,357 | 72.36 |
Type: Posts; User: v.z.afzal@dundee.ac.uk
Good point keang, use that instead.
Come on there's no need for that tone.
String [] sections = "CP GF FGT LEDGER".split(" ");
String finalString ="";
for(int i=0 ; i<sections.length-1 ; i++){
finalString += " " + sections[i];
}
finalString = finalString.trim();
Split each of your strings using split(" ");
Add each element to a map/list
Then just do a comparison of the two lists/maps.
Thanks,
Vackar
Hi,
I wouldn't read to much into what the author is saying. It appears he is using an analogy to describe the process in a way that most unix users might understand.
Piping basically lets you...
Generate a power set for each one, then remove duplicates.
Here's some code to generate power sets:
public class CombinationSet<T> {
List<T> elements = new ArrayList<T>();...
No, what I mean is does it come with some kind client ajax library that automatically integrates with your maplet stuff.
The reason I'm asking is that there are hundreds of web frameworks to...
run
Class c = Class.forName(userDir.replace("\\", ".") + "." + "Page");
if this doesn't work, user dir may have something funny at the start of the string (i.e. c:\\), if it does just strip it...
Hey, I have a question. Does you maplet stuff allow you to use ajax?
There is a framework called Milton that I've used for SSL + webdav, I think it has FTP SSL Support as well. have a look ()
In your method
public void tree3Loop(){
for(int k=0;k<clusterList3.size();k++)
{
buildTree3();
System.out.println(k);
clusterList3.remove(k);
}
Quick question, are you calling your classes/methods a,b,c etc or has this been run through an obfuscator?
From you code it looks like you only need to access the father object in yout nextSibling method. So you need code something like:
class MyNode
{
private MyNode father;
Wow, you're going all out with your advertising. I think this is the third thread I've seen you advertising in.
Wonder if it'll start a trend.
My advice: Model you system to reflect your use case. If it isn't working your model's wrong.
As suggested before, you can maintain a referemce in the child object to the parent that instantiated...
If you just need a 'file' to read from use db4o. (Or some other lightweight non-sql relational db)
Relational modeling, CRUD optomisations etc will not add to anything your attempting to do.
If...
If the aim of your project is to learn java (and not RDBMS administration, SQL etc) and nothing else, then you may want to start with a simpler project.
If you really want to use this as your... | http://forums.codeguru.com/search.php?s=00307e971b5cde438824b6077fb6a7bc&searchid=7002319 | CC-MAIN-2015-22 | refinedweb | 455 | 76.22 |
First time question asker here. I used several different threads on here
to construct a fullcalendar that opens event information in a fancybox.
More specifically, each day has an link (structured as an event) that opens
a list of that days events in a fancybox.
I constructed the
calendar and fancybox links with the following code:
$('#calendar').fullCalendar({
View Replies
When I don't want to execute the default action that is associated with
the event, I use
function listener(e){
if(e.preventDefault) e.preventDefault(); /* Other code */}
But I have just learnt that events have the
boolean cancelable. Then, should I use this code
instead?
cancelable
function listener(e){ if(e.c
i do not know what is going on my firefox!
my aspx and
javascript codes are like this :
<html
xmlns="" ><head
runat="server"> <title></title> <script
type="text/javascript"> function a() {
alert('a'); //alert(event.which); /
Need some help in sorting out design options for simulation framework in
C++ (no C++11).The user creates an "event dispatcher" and registers
interest (using "watchers") in occurrence of "events". The dispatcher
internally holds "event sources" which are used to detect event activation
and manage notifications to watchers. There's a 1:1:1 mapping between
watcher, event and event source cl
I am writing some application with Raphael.js. And it should handle
mouse drag events.
That is, when mouse drag is ended, i try to
catch the point on the Raphael's Paper object
(DIV / SVG element, actually) where the mouse
caused drop event.
Paper
DIV
SVG
drop
FireFox and Chrome are doing
well with event.layerX and ev
event.layerX
ev
Disclaimer: I am anything but a Javascript expert, so I'm not even sure
if I'm approaching this correctly...
I want to be able to
trigger an event in Javascript, but be able to cancel that event if another
event occurs. So, what I'm looking to accomplish is:
I have a button which start/stops a timer. When I click it, I remove the
current event handler, and attach the opposite one. Ie, click "Stop", and
the "Start" function is attached for the next click.
However in
IE (7), not sure about 8. The newly attached event is also triggering after
the original function is finished:
Lifeline in IE7:Button
pushed --> "Stop" functi
I have two classes A and B.In class A, I have an event
EventA
public delegate void
FolderStructureChangedHandler();public event
FolderStructureChangedHandler EventA;
In class B, I
have the same event which named EventB.In the a method of my
application, I want to add all of the handlers registered to EventA to the
event EventB
View Replies
handlers
delegates
event
instance
another
event
This is my application setup :
I have a UserControls folder
in my application inside which there is my .ascx file which happnes to
contain just a simple ASP Button. I have not added any code in the
code-behind of the ascx.
I have a BaseForm.cs (just a C# class
file and NOT an aspx file) which is inheriting from
System.Web.UI.Page
public class BaseForm : Sy
I am developing an API in which I want to be able to know when an event
listener on an object is added or removed. The reason is that some of the
events I am firing will require me to continually poll an object for
updates, and I don't want to have to poll the object if nothing is
listening for the event. I am polling the html5 media player and other
players for buffering updates, so eliminatin | http://bighow.org/tags/event/1 | CC-MAIN-2017-22 | refinedweb | 601 | 63.19 |
This page provides an overview of signed URLs and instructions for using them with Cloud CDN. Signed URLs give time-limited resource access to anyone in possession of the URL, regardless of whether the user has a Google Account.
A signed URL is a URL that provides limited permission and time to make a request. Signed URLs contain authentication information in their query strings, allowing users without credentials to perform specific actions on a resource. When you generate a signed URL, you specify a user or service account that must have sufficient permission to make the request associated with the URL.
After you generate a signed URL, anyone who possesses it can use the signed URL to perform specified actions (such as reading an object) within a specified period of time.
Signed URLs also support an optional
URLPrefix parameter, allowing you to
provide access to multiple URLs based on a common prefix.
If you want to scope access to a specific URL prefix, consider using signed cookies.
Before you begin
Before you use signed URLs, do the following:
Ensure that Cloud CDN is enabled; for instructions, see Using Cloud CDN. You can configure signed URLs on a backend before enabling Cloud CDN, but there is no effect until Cloud CDN is enabled.
If necessary, update to the latest version of the Cloud SDK:
gcloud components update
For an overview, see Signed URLs and signed cookies.
Configuring signed request keys
Creating keys for your signed URLs or signed cookies requires several steps, which are described in the following sections.
Security considerations
Cloud CDN does not validate requests in the following circumstances:
- The request is not signed.
- The backend service or backend bucket for the request doesn't have Cloud CDN enabled.
Signed requests must always be validated at the origin before serving the response. This is because origins can be used for serving a mixture of signed and unsigned content and because a client might access the origin directly.
- Cloud CDN doesn't block requests without a
Signaturequery parameter or
Cloud-CDN-CookieHTTP cookie. It rejects requests with invalid (or otherwise malformed) request parameters.
- When your application detects an invalid signature, make sure that your application responds with an
HTTP 403 (Unauthorized)response code.
HTTP 403response codes aren't cacheable.
- Responses to signed and unsigned requests are cached separately, so a successful response to a valid signed request is never used to serve an unsigned request.
- If your application sends a cacheable response code to an invalid request, valid future requests might be incorrectly rejected.
For Cloud Storage backends, make sure to remove public access, so that Cloud Storage can reject requests that are missing a valid signature.
The following table summarizes the behavior.
Creating signed request keys
You enable support for Cloud CDN signed URLs and signed cookies by creating one or more keys on a Cloud CDN-enabled backend service, backend bucket, or both.
For each backend service or backend bucket, you can create and delete keys as your security needs dictate. Each backend can have up to three keys configured at a time. We suggest periodically rotating your keys by deleting the oldest, adding a new key, and using the new key when signing URLs or cookies.
You can use the same key name in multiple backend services and backend buckets because each set of keys is independent of the others. Key names can be up to 63 characters. To name your keys, use the characters A-Z, a-z, 0-9, _ (underscore), and - (hyphen).
When you create keys, be sure to keep them secure because anyone who has one of your keys can create signed URLs or signed cookies that Cloud CDN accepts until the key is deleted from Cloud CDN. The keys are stored on the computer where you generate the signed URLs or signed cookies. Cloud CDN also stores the keys to verify request signatures.
To keep the keys secret, the key values aren't included in responses to any API requests. If you lose a key, you must create a new one.
To create keys, follow these steps.
Console
- In the Google Cloud Console, go to the Cloud CDN page.
- Click Add origin.
- Select an HTTP(S) load balancer as the origin.
- Select backend services or backend buckets. For each one:
- Click Configure, and then click Add signing key.
- Under Name, give the new signing key a name.
- Under Key creation method, select Automatically generate or Let me enter.
- If you're entering your own key, type the key into the text field.
- Click Done.
- Under Cache entry maximum age, provide a value, and select a Unit of time from the drop-down list. You can choose among second, minute, hour, and day. The maximum amount of time is three (3) days.
- Click Save.
- Click Add.
gcloud
The
gcloud command-line tool reads keys from a local file that
you specify. The key file must be created by generating strongly random 128
bits, encoding them with base64, and:
gcloud compute backend-services \ add-signed-url-key BACKEND_NAME \ --key-name KEY_NAME \ --key-file KEY_FILE_NAME
To add the key to a backend bucket:
gcloud compute backend-buckets \ add-signed-url-key BACKEND_NAME \ --key-name KEY_NAME \ --key-file KEY_FILE_NAME
Configuring Cloud Storage permissions
If you use Cloud Storage and you have restricted who can read the objects, you must give Cloud CDN permission to read the objects by adding the Cloud CDN service account to Cloud Storage ACLs.
You don't need to create the service account. The service account is created automatically the first time that you add a key to a backend bucket in a project.
Before you run the following command, add at least one key to a backend bucket
in your project. Otherwise, the command fails with an error because the
Cloud CDN cache fill service account is not created until you add one
or more keys for the project. Replace
PROJECT_NUM with
your project number and
BUCKET with your storage
bucket.
gsutil iam ch \ serviceAccount:service-PROJECT_NUM@cloud-cdn-fill.iam.gserviceaccount.com:objectViewer \ gs://BUCKET
The Cloud CDN service account
service-PROJECT_NUM@cloud-cdn-fill.iam.gserviceaccount.com
doesn't appear in the list of service accounts in your project. This is because
the Cloud CDN service account is owned by Cloud CDN, not your
project.
For more information about project numbers, see Locate the project ID and project number in the Google Cloud Console Help documentation.
Optionally customizing the maximum cache time
Cloud CDN caches responses for signed requests regardless of the
backend's
Cache-Control header. The maximum time that responses can be cached
without revalidation is set by the
signed-url-cache-max-age flag, which
defaults to one hour and can be modified as shown here.
To set the maximum cache time for a backend service or backend bucket, run one of the following commands:
gcloud compute backend-services update BACKEND_NAME --signed-url-cache-max-age MAX_AGE
gcloud compute backend-buckets update BACKEND_NAME --signed-url-cache-max-age MAX_AGE
Listing signed request key names
To list the keys on a backend service or backend bucket, run one of the following commands:
gcloud compute backend-services describe BACKEND_NAME
gcloud compute backend-buckets describe BACKEND_NAME
Deleting signed request keys
When URLs signed by a particular key should no longer be honored, run one of the following commands to delete that key from the backend service or backend bucket:
gcloud compute backend-services \ delete-signed-url-key BACKEND_NAME --key-name KEY_NAME
gcloud compute backend-buckets \ delete-signed-url-key BACKEND_NAME --key-name KEY_NAME
The last step is to sign URLs and distribute them. You can sign URLs by using
the
gcloud compute sign-url command or by using code that you write yourself.
If you need many signed URLs, custom code provides better performance.
Creating signed URLs
Use these instructions to create signed URLs by using the
gcloud compute sign-url command. This step assumes that you have already
created the keys.
Console
You cannot create signed URLs by using the Cloud Console. You can
use the
gcloud command-line tool or write custom code by using the
following examples.
gcloud
The
gcloud command-line tool includes a command for signing URLs. The
command implements the algorithm described in the section about
writing your own code.
gcloud compute sign-url \ "URL" \ --key-name KEY_NAME \ --key-file KEY_FILE_NAME \ --expires-in TIME_UNTIL_EXPIRATION \ [--validate]
This command reads and decodes the base64url encoded
key value from
KEY_FILE_NAME, and the
--validateflag is not given, the following are not verified:
- The inputs
- The generated URL
- The generated signed URL
Programmatically creating signed URLs
The following code samples demonstrate how to programmatically create signed URLs.
Go
import ( "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" "io" "io/ioutil" "os" "strings" "time" ) // SignURL creates a signed URL for an endpoint on Cloud CDN. // // - url must start with "https://" and should not have the "Expires", "KeyName", or "Signature" // query parameters. // - key should be in raw form (not base64url-encoded) which is 16-bytes long. // - keyName must match a key } // SignURLWithPrefix creates a signed URL prefix for an endpoint on Cloud CDN. // Prefixes allow access to any URL with the same prefix, and can be useful for // granting access broader content without signing multiple URLs. // // - urlPrefix must start with "https://" and should not include query parameters. // - key should be in raw form (not base64url-encoded) which is 16-bytes long. // - keyName must match a key added to the backend service or bucket. func signURLWithPrefix(urlPrefix, keyName string, key []byte, expiration time.Time) (string, error) { if strings.Contains(urlPrefix, "?") { return "", fmt.Errorf("urlPrefix must not include query params: %s", urlPrefix) } encodedURLPrefix := base64.URLEncoding.EncodeToString([]byte(urlPrefix)) input := fmt.Sprintf("URLPrefix=%s&Expires=%d&KeyName=%s", encodedURLPrefix, expiration.Unix(), keyName) mac := hmac.New(sha1.New, key) mac.Write([]byte(input)) sig := base64.URLEncoding.EncodeToString(mac.Sum(nil)) signedValue := fmt.Sprintf("%s&Signature=%s", input, sig) return signedValue, nil } // generateSignedURLs(w io.Writer) error { // The path to a file containing the base64-encoded signing key keyPath := os.Getenv("KEY_PATH") // Note: consider using the GCP Secret Manager for managing access to your // signing key(s). key, err := readKeyFile(keyPath) if err != nil { return err } // Generate a signed URL for a specific URL url := signURL("", "my-key", key, time.Now().Add(time.Hour*24)) fmt.Fprintln(w, url) // Generate a signed URL for urlPrefix, err := signURLWithPrefix("", "my-key", key, time.Unix(1549751401, 0)) if err != nil { return err } fmt.Fprintln(w, urlPrefix) return nil }) def sign_url_prefix(url, url_prefix, key_name, base64_key, expiration_time): """Gets the Signed URL string for the specified URL prefix and configuration. Args: url: URL of request. url_prefix: URL prefix URL prefix and configuration. """ stripped_url = url.strip() parsed_url = urllib.parse.urlsplit(stripped_url) query_params = urllib.parse.parse_qs( parsed_url.query, keep_blank_values=True) encoded_url_prefix = base64.urlsafe_b64encode( url_prefix.strip().encode('utf-8')).decode('utf-8') epoch = datetime.datetime.utcfromtimestamp(0) expiration_timestamp = int((expiration_time - epoch).total_seconds()) decoded_key = base64.urlsafe_b64decode(base64_key) policy_pattern = u'URLPrefix={encoded_url_prefix}&Expires={expires}&KeyName={key_name}' policy = policy_pattern.format( encoded_url_prefix=encoded_url_prefix, expires=expiration_timestamp, key_name=key_name) digest = hmac.new( decoded_key, policy.encode('utf-8'), hashlib.sha1).digest() signature = base64.urlsafe_b64encode(digest).decode('utf-8') signed_url = u'{url}{separator}{policy}&Signature={signature}'.format( url=stripped_url, separator='&' if query_params else '?', policy=policy, signature=signature) print(signed_url)
PHP
/** * Decodes base64url (RFC4648 Section 5) string * * @param string $input base64url encoded string * * @return string */ function base64url_decode($input) { $input .= str_repeat('=', (4 - strlen($input) % 4) % 4); return base64_decode(strtr($input, '-_', '+/'), true); } /** * Encodes a string with base64url (RFC4648 Section 5) * Keeps the '=' padding by default. * * @param string $input String to be encoded * @param bool $padding Keep the '=' padding * * @return string */ function base64url_encode($input, $padding = true) { $output = strtr(base64_encode($input), '+/', '-_'); return ($padding) ? $output : str_replace('=', '', $output); } /** * Creates signed URL for Google Cloud CDN * Details about order of operations: * * Example function invocation (In production store the key safely with other secrets): * * <?php * $base64UrlKey = 'wpLL7f4VB9RNe_WI0BBGmA=='; // head -c 16 /dev/urandom | base64 | tr +/ -_ * $signedUrl = sign_url('', 'my-key', $base64UrlKey, time() + 1800); * echo $signedUrl; * ?> * * @param string $url URL of the endpoint served by Cloud CDN * @param string $keyName Name of the signing key added to the Google Cloud Storage bucket or service * @param string $base64UrlKey Signing key as base64url (RFC4648 Section 5) encoded string * @param int $expirationTime Expiration time as a UNIX timestamp (GMT, e.g. time()) * * @return string */ function sign_url($url, $keyName, $base64UrlKey, $expirationTime) { // Decode the key $decodedKey = base64url_decode($base64UrlKey); // Determine which separator makes sense given a URL $separator = (strpos($url, '?') === false) ? '?' : '&'; // Concatenate url with expected query parameters Expires and KeyName $url = "{$url}{$separator}Expires={$expirationTime}&KeyName={$keyName}"; // Sign the url using the key and encode the signature using base64url $signature = hash_hmac('sha1', $url, $decodedKey, true); $encodedSignature = base64url_encode($signature); // Concatenate the URL and encoded signature return "{$url}&Signature={$encodedSignature}"; }
Generating custom signed URLs
When you write your own code to generate signed URLs, your goal is to create URLs with the following format or algorithm; all URL parameters are case-sensitive and must be in the order shown:
To generate signed URLs, follow these steps:
Ensure that the URL for signing does not have a
Signaturequery parameter.
Determine when the URL expires and append that you give it to shares it with others, accidentally or otherwise.
Set the key name. The URL must be signed with a key of the backend service or backend bucket that serves the URL. It is best to use the most recently added key for key rotation. Add the key to the URL by appending
&KeyName=KEY_NAME. Replace
KEY_NAMEwith the name of the chosen key created in Creating signed request keys.
Sign the URL. Create the signed URL by following these steps. Make sure that the query parameters are in the order shown immediately before step 1, and make sure that nothing in the signed URL changes case.
a. Hash the entire URL (including the beginning and
&KeyName...at the end) with HMAC-SHA1 by using the secret key that corresponds to the key name chosen earlier. Use the raw 16-byte secret key, not the base64url encoded key. Decode it if needed.
b. Use base64url encode to encode the result.
c. Append
&Signature=to the URL, followed by the encoded signature.
Using URL prefixes for signed URLs
Instead of signing the full request URL with the
Expires and
KeyName query
parameters, you can instead sign the
URLPrefix,
Expires, and
KeyName query
parameters only. This allows a given combination of
URLPrefix,
Expires,
KeyName, and
Signature query parameters to be reused verbatim across
multiple URLs that match the
URLPrefix, avoiding the need to create a new
signature for each distinct URL.
In the following example, the highlighted text shows the
parameters that you sign. The
Signature is appended as the final query
parameter, as usual.
URLPrefix denotes a URL-safe base64 encoded URL prefix that encompasses all
paths that the cookie should be valid for.
A
URLPrefix encodes a scheme (either
http:// or
https://), FQDN, and an
optional path. Ending the path with a
/ is optional but recommended. The
prefix shouldn't include query parameters or fragments such as
? or
#.
For example, matches requests to both of the
following:
The prefix's path is used as a text substring, not strictly a directory path.
For example, the prefix grants access to both of the
following:
/data/file1
/database
To avoid this mistake, we recommend ending all prefixes with
/ unless you
intentionally choose to end the prefix with a partial filename such as to grant access to the following:
/videos/123_chunk1
/videos/123_chunk2
/videos/123_chunkN
If the requested URL doesn't match the
URLPrefix, Cloud CDN
rejects the request and returns an
HTTP 403 error to the client.
Validating signed URLs
The process of validating a signed URL is essentially the same as generating a signed URL. For example, suppose that you want to validate the following signed URL:
You can use the secret key named by
KEY_NAME to
independently generate the signature for the following URL:
Then you can verify that it matches
SIGNATURE.
Suppose that you want to validate a signed URL that has a
URLPrefix, as shown
here:
First, verify that the base64-decoded value of
URL_PREFIX
is a prefix of. If so, you can
then calculate the signature for the following:
URLPrefix=URL_PREFIXExpires=EXPIRATION&KeyName=KEY_NAME
You can then verify that it matches
SIGNATURE.
Removing public access to the Cloud Storage bucket
For signed URLs to properly protect content, it is important that the
origin server not grant public access to that content. When using a
Cloud Storage bucket, a common approach is to make objects public
temporarily for testing purposes. After enabling signed URLs, it's important to
remove the
allUsers (and
allAuthenticatedUsers, if applicable) READ
permissions (in other words, the Storage Object
Viewer IAM role) on the bucket.
After you disable public access on the bucket, individual users can still access Cloud Storage without signed URLs if they have access permission, such as OWNER permission.
To remove public
allUsers READ access on a Cloud Storage bucket,
reverse the action described in
Making all objects in a bucket publicly readable.
Distributing and using signed URLs
The URL returned from the
gcloud command-line tool or produced by your custom
code can be distributed according to your needs. We recommend signing only HTTPS
URLs, because HTTPS provides a secure transport that prevents the
Signature
component of the signed URL from being intercepted. Similarly, make sure that
you distribute the signed URLs over secure transport protocols such as
TLS/HTTPS. | https://cloud.google.com/cdn/docs/using-signed-urls?hl=RU | CC-MAIN-2021-17 | refinedweb | 2,907 | 54.22 |
In this section you will learn how to use the do-while statement in java.
AdsTutorials
In this section you will learn about do-while loop in Java. do-while loop is similar to while loop but the difference is do-while loop execute the condition at least once. Some time we need to execute certain condition repeatedly and run at least once. For that we need a do-while loop so that at least once a block of statement will executed. do-while loop execute once without testing the condition but in while loop what happen if the condition is true then only the statement inside the while loop will be executed, otherwise the control will jump outside the while loop.
Syntax:
do{ statement; } while(boolean-expression);
The boolean expression will execute once before testing the boolean expression, and after that if the boolean expression is true then control will jump up and execute the statement inside the do, until the boolean expression will become false.
do-while loop consist of condition and statement. First the code inside the loop is executed then the condition is evaluated and if the boolean expression or condition is true then again the code will executed. It will execute until the boolean expression become false. Because do-while loop check the condition after the statement is executed. So while is called pre-test loop and do-while loop is also known as post-test loop. The while loop is a entry-control loop which test the condition first then block inside the loop is executed and do-while loop is a exit-control loop. It means the code always executed first and then the boolean-expression is evaluated. Here is the flow diagram of do while loop as follows:
Example : Using this example you will understand the do-while loop easily.
public class DowhileExample { public static void main(String args[]) { int i=0; do { System.out.println("Value of i ="+i); i++; }while(i<=10); } }
Output from the program:
Advertisements
Posted on: July 5, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: Do-while loop in Java
Post your Comment | http://roseindia.net/java/beginners/java-DoWhile.shtml | CC-MAIN-2017-43 | refinedweb | 371 | 60.45 |
Google CTF 2020 Write Up
I found a link to the Google CTF as it was ongoing. Me and Ben (Team Skydog! Arf! Arf!) have been meaning to do a CTF for years and a combination of covid and procrastinating packing for a move finally made it happen!
The “easy” problems were ass kickers. I guess they were easy in the sense that total n00bs like us could eventually get them. But good lord. It seems inhuman to me that there are people rocking these things, but there are.
We were able to finish 3 problems and got close to a 4th.
There are similar write ups here . Doesn’t seem like I did anything that unusual.
Beginner Reversing
This one was a binary that needed a password inputted . I booted up Ghidra to take a look at the binary which helped a lot in seeing a decompiled version. I’ve never really used Ghidra before. This is what Ghidra showed
ulong main(void) { int iVar1; uint uVar2; undefined auVar3 [16]; undefined input [16]; undefined4 local_28; undefined4 uStack36; undefined4 uStack32; undefined4 uStack28; printf("Flag: "); __isoc99_scanf(&DAT_0010200b,input); auVar3 = pshufb(input,SHUFFLE); auVar3 = CONCAT412(SUB164(auVar3 >> 0x60,0) + ADD32._12_4_, CONCAT48(SUB164(auVar3 >> 0x40,0) + ADD32._8_4_, CONCAT44(SUB164(auVar3 >> 0x20,0) + ADD32._4_4_, SUB164(auVar3,0) + ADD32._0_4_))) ^ XOR; local_28 = SUB164(auVar3,0); uStack36 = SUB164(auVar3 >> 0x20,0); uStack32 = SUB164(XOR >> 0x40,0); uStack28 = SUB164(XOR >> 0x60,0); iVar1 = strncmp(input,(char *)&local_28,0x10); if (iVar1 == 0) { uVar2 = strncmp((char *)&local_28,EXPECTED_PREFIX,4); if (uVar2 == 0) { puts("SUCCESS"); goto LAB_00101112; } } uVar2 = 1; puts("FAILURE"); LAB_00101112: return (ulong)uVar2; }
001010a9 e8 b2 ff CALL __isoc99_scanf undefined __isoc99_scanf() ff ff 001010ae 66 0f 6f MOVDQA XMM0,xmmword ptr [RSP]=>input 04 24 001010b3 48 89 ee MOV RSI,RBP 001010b6 4c 89 e7 MOV RDI,R12 001010b9 ba 10 00 MOV EDX,0x10 00 00 001010be 66 0f 38 PSHUFB XMM0,xmmword ptr [SHUFFLE] = 00 05 a9 2f 00 00 001010c7 66 0f fe PADDD XMM0,xmmword ptr [ADD32] = 05 91 2f = null 00 00 001010cf 66 0f ef PXOR XMM0,xmmword ptr [XOR] = 05 79 2f 00 00 001010d7 0f 29 44 MOVAPS xmmword ptr [RSP + local_28],XMM0 24 10 001010dc e8 4f ff CALL strncmp int strncmp(char * __s1, char * ff ff 001010e1 85 c0 TEST EAX,EAX 001010e3 75 1b JNZ LAB_00101100 001010e5 48 8b 35 MOV RSI=>DAT_00102020,qword ptr [EXPECTED_PREFIX] = 00102020 94 2f 00 00 = 43h C 001010ec ba 04 00 MOV EDX,0x4 00 00 001010f1 48 89 ef MOV RDI,RBP 001010f4 e8 37 ff CALL strncmp int strncmp(char * __s1, char * ff ff
Actually having this in ghidra makes this easier to see than it is here because Ghidra tells you which line of C is which line of assembly. Basically, it appears (after looking up some assembly instructions) that we need to find a string that after shuffling by a fixed pattern (SHUFFLE), packed adding a constant (ADD32), and xoring with a constant (XOR) equals itself.
I suppose this must be solvable by hand? They are suspiciously reversible operations. But I ended up using Z3 because I already know it pretty well. Something that made me totally nuts was translating byte ordering between x86 and z3. The only way I was able to do it was to go into gdb and go through the program instruction and make sure xmm0 had the same values as z3.
gdb a.out break main run tui enable layout asm ni a bunch of times print $xmm0
Then I put in the appropriate list reversals or reversed the bytes of the binary constants. It wasn’t so bad once I realized I had to do that.
from z3 import * x = BitVec('x', 128) #print(Extract(,0,x)) chunks8 = [ Extract(i*8+7, 8*i,x ) for i in range(16)] #print([print for chunk in chunks8]) print(chunks8) shuffle = [0x02 ,0x06 ,0x07 , 0x01, 0x05, 0x0b, 0x09, 0x0e, 0x03 , 0x0f ,0x04 ,0x08, 0x0a, 0x0c, 0x0d, 0x00] #shuffle = [ 16 - i for i in shuffle ] #?? Endian? # for z3 ,extract 0 is the least significant shufflex = [chunks8[shuf] for shuf in shuffle] shufflex = Concat(list(reversed(shufflex))) print(shufflex) chunks32 = [ Extract(i*32+31, 32*i,shufflex ) for i in range(4)] #[Concat( shufflex[4*i: 4*i+4]) ) for i in range(4)] print(chunks32) #add32 = [0xefbeadde, 0xaddee1fe, 0x37133713, 0x66746367] add32 = [0xedeadbeef, 0xfee1dead, 0x13371337, 0x67637466] added = [ chunk + addo for chunk,addo in zip(chunks32,add32) ] print(added) xnew = Concat(list(reversed(added))) ^ 0xAAF986EB34F823D4385F1A8D49B45876 # 0x7658b4498d1a5f38d423f834eb86f9aa print(xnew) s = Solver() s.add(xnew == x) #s.add(x != 649710491438454045931875052661658691 ) #s.add(Extract( 4*8-1 , 0, xnew) == 0x102020 ) # 0x202010 print(s.check()) m = s.model() print(m) print(m.eval(xnew)) #bit32chunks = [ Extract(high, low, x) for i in range(4)] #lower = Extract(31, 0, x) #lower = Extract(31, 0, x) #x = BitVec('addx', 128) #[ Extract(high, low, x) for i in range(0,16)]
I still don’t understand what is going on with the EXPECTED_PREFIX part. Somehow that memory gets filled with “CTF”, even though it doesn’t have that in the binary file. So maybe that is a red herring?
I wonder if KLEE would’ve just found it or if there was some other automated tool that would’ve worked? I see that one write up used angr
Beginner Hardware
This one had a verilog file and a verilator C++ file. Basically, a string is clocked into a circuit which does some minimal scrambling and then sets a flag once a good key has been sent in. An unexpectedly hard part was figuring out how to get verilator to work, which wasn’t strictly necessary. Another hard part was realizing that I was supposed to netcat the key into a server. Somehow I just totally ignored the url that was in the question prompt
Again, I used my formal method super powers just because. I downloaded EBMC, although yosys smtbmc would probably also work
~/Downloads/ebmc check.sv --trace --bound 100
I edited the file slightly. I turned
always_ff into
always since ebmc didn’t seem to support it. I also initialized the memory to zero so that I could get an actual trace and asserted that
open_safe == 0 so that it would give me a countermodel that opens the safe. ebmc returned a trace, which I sent over netcat to the server and got the real key. One could back out the key by hand here, since it is fairly simple scrambling.
module check( input clk, input [6:0] data, output wire open_safe ); reg [6:0] memory [7:0]; reg [2:0] idx = 0; //initial begin // memory[0] = 7'b1000011; // memory[5] = 7'b1010100; // memory[2] = 7'b1010100; // memory[7] = 7'b1111011 ; // 7'x7b; //end integer i; initial begin for (i=0;i<8;i=i+1) memory[i] = 0; end wire [55:0] magic = { {memory[0], memory[5]}, {memory[6], memory[2]}, {memory[4], memory[3]}, {memory[7], memory[1]} }; wire [55:0] kittens = { magic[9:0], magic[41:22], magic[21:10], magic[55:42] }; assign open_safe = kittens == 56'd3008192072309708; always @(posedge clk) begin memory[idx] <= data; idx <= idx + 5; end assert property (open_safe==0); // || memory[0] == 7'b110111); //|| memory[0] != b00110111 endmodule
Chunk Norris - Crypto
This one kicked my ass. I know basically nothing about crypto. The prompt was that there is a file that generates primes for an RSA encrytion. They are using a fishy looking generator for the primes.
#!/usr/bin/python3 -u import random from Crypto.Util.number import * import gmpy2 a = 0xe64a5f84e2762be5 chunk_size = 64 def gen_prime(bits): s = random.getrandbits(chunk_size) while True: s |= 0xc000000000000001 p = 0 for _ in range(bits // chunk_size): p = (p << chunk_size) + s s = a * s % 2**chunk_size if gmpy2.is_prime(p): return p n = gen_prime(1024) * gen_prime(1024) e = 65537 flag = open("flag.txt", "rb").read() print('n =', hex(n)) print('e =', hex(e)) print('c =', hex(pow(bytes_to_long(flag), e, n)))
I went up a couple blind alleys. The first thing we tried was brute forcing. Maybe if the generator is incredibly weak, we can just generate 1,000,000 primes and we’ll get a match. No such luck.
Second I tried interpreting the whole problem into Z3 and Boolector. This did not work either. In hindsight, maybe it could have? Maybe I messed up somewhere in this code?
import random from Crypto.Util.number import * import gmpy2 from z3 import * #x = BitVec('n', 1024) prime_size = 1024 chunk_size = 64 s1 = ZeroExt(2*prime_size - chunk_size, BitVec('s1', chunk_size)) #prime_size) s2 = ZeroExt(2*prime_size - chunk_size, BitVec('s2', chunk_size)) a = 0xe64a5f84e2762be5 def gen_prime(s, bits): s |= 0xc000000000000001 p = 0 for _ in range(bits // chunk_size): p = (p << chunk_size) + s s = a * s % 2**chunk_size return p def gen_prime(s, bits): s |= 0xc000000000000001 p = 0 for _ in range(bits // chunk_size): p = (p << chunk_size) + s s = a * s % 2**chunk_size return p p = gen_prime(s1,prime_size) q = gen_prime(s2,prime_size) #n = #n = 0x90000000000055e4350fbb6baa0349fbde32f2f237fa10573dd3d46b #n = BitVecVal("0x90000000000055e4350fbb6baa0349fbde32f2f237fa10573dd3d46b", 64) n = BitVec("n",2048) #(declare-const n (_ BitVec 224) ) #s = parse_smt2_string( " (assert (= n #x900000000001165742e188538bc53a3e129279c049360928a59b2de9))" , decls={"n": n}) #n = BitVecVal(0x90000000000055e4350fbb6baa0349fbde32f2f237fa10573dd3d46b, 64) #print(hex(int(str(n)))) 0xd #s = Solver() bv_solver = Solver() '''Then(With('simplify', mul2concat=True), 'solve-eqs', 'bit-blast', 'sat').solver() ''' s = bv_solver #nstr = "#xd" nstr = "#x" s.add(parse_smt2_string( f" (assert (= n {nstr}))" , decls={"n": n})) #s.add( s1 < 2**chunk_size) #s.add( s2 < 2**chunk_size) s.add(s1 <= s2) s.add( p * q == n) set_option(verbose=10) print(s.to_smt2()) print(s.check()) m = s.model() print(m) print(m.eval(p)) print(m.eval(q))
We also tried using this tool and see if we got any hits. Didn’t work. An interesting resource in any case, and I ended up using to to actually do the decryption once I had the primes.
Reading the problem prompt I realized they were emphasizing the way the random number generator was constructed. It turns out that this generator has a name . This did not lead to any revelations, so is actually a counter productive observation.
Anyway, looking at it, each 64 bit chunk is kind of independent of each other in the primes. And when you multiply the built primes, the chunks still don’t interweave all the much, especially the most and least significant chunk of n. Eventually I realized that the first and last chunk of the key n are simply related to the product of the 2 random numbers
s used to generate the primes. The least significant chunk of
n = s1 * s2 * a^30 mod 2^64. And the most significant chunk of n is the most significant 64 bits of s1 * s2 ( minus an unknown but small number of carries). We can reverse the a^30 by using the modular inverse of a which I used a web form to calculate. Then we basically have the product of s1 and s2. s1 and s2 are not primes, and this is a much smaller problem, so factoring these numbers is not a challenge.
import random from Crypto.Util.number import * import gmpy2 for q in range(16): # search over possible carries #e = q * 2 ** 64 #print(hex(e)) backn = 0x0273d3d4255f6b19 # least sig bits of n frontn = 0xab802dca026b1825 - q # most sig bits of n minus some carry chunk_size = 64 bits = 1024 a = 0xe64a5f84e2762be5 #16594180801339730917 ainv = 13928521563655641581 # modular inverse wrt 2^64 n0 = gmpy2.mpz(") abackn = backn # mutiply a^inv ** (30? or 32?) * backn = s1 * s2 mod 2**64 for _ in range(bits // chunk_size - 1): abackn = ainv * abackn % 2**chunk_size abackn = ainv * abackn % 2**chunk_size print("abackn ", hex(abackn)) def prime_factors(n): # all prime factors, from a stack exchange post i = 2 factors = [] while i * i <= n: #print(i) if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors def gen_prime_s(s,bits): s |= 0xc000000000000001 p = 0 for _ in range(bits // chunk_size): p = (p << chunk_size) + s s = a * s % 2**chunk_size return p print(len(hex(abackn))) tot_ss = (frontn * (2 ** (chunk_size))) + abackn # combine the front and back. Should = s1 * s2 print("frontbk", hex(tot_ss)) print(len(hex(tot_ss))) g = prime_factors( tot_ss) print(g) ng = len(g) for i in range(2**ng): # try all ways of splitting prime list. Could do something less stupid, but whatev s1 = 1 s2 = 1 for x in range(ng): if (i >> x) & 1: s1 *= g[x] else: s2 *= g[x] p = gen_prime_s(s1,1024) q = gen_prime_s(s2,1024) n = p*q if n == n0: print("holy shit") print(f"p = {p}", ) print(f"q = {q}", )
Pasteurize Web
Strangely enough the web was also pretty hard. This is partially because this is getting further from stuff I know about. We ended up not finishing this one but I think we got close. We’re given access to a notes web app. Looking at the source, it turns out the server source was also being served. Eventually we figured out that we could curl in notes in an unexpected format using url-encoding which was conspicuously enabled in body-parser. The sanitizer makes the assumption that it is receiving a string, not an object. When the sanitizer removes the quotes from the JSON.stringify, it actually can remove an opening brace {, and then the first label of the object closes the string. When the note text is spliced into the webpage it isn’t properly escaped. We were able to get code to run via sending in an object with labels that were javascript code
curl -d 'content[;a=4;alert();]=;7;&content[;a=5;]=;4;' -H "Content-Type: application/x-www-form-urlencoded" -X POST
By running an ajax request we could recevie data from TJMike’s browser
curl -d 'content[;var xhttp = new XMLHttpRequest();xhttp.open(`POST`, ``, true);xhttp.send(document.documentElement.innerHTML);]=;7;&content[;a=5;]=;4;' -H "Content-Type: application/x-www-form-urlencoded" -X POST
We were at the time limit then. I’ve heard we needed to grab the document.cookies and that had the key in it?
All told pretty cool. A very well organized CTF with fun challenges. I dunno if CTFs are for me. I felt my blood pressure raising a lot. | https://www.philipzucker.com/google-ctf-2020-write-up/ | CC-MAIN-2021-39 | refinedweb | 2,370 | 70.13 |
Your message dated Sun, 11 Apr 2010 14:30:35 +0000 with message-id <E1O0yBH-00006w-SG@ravel.debian.org> and subject line C++ and mudflap packages not built anymore from the gcc-4.1 source has caused the Debian Bug report #395837, regarding g++-4.1: dynamic_cast returns different results based on the order of5837: Debian Bug Tracking System Contact owner@bugs.debian.org with problems
--- Begin Message ---
- To: submit@bugs.debian.org
- Subject: g++-4.1: dynamic_cast returns different results based on the order of bases
- From: "Vladimir Grebinskiy" <vgrebinski@gmail.com>
- Date: Fri, 27 Oct 2006 22:09:12 -0400
- Message-id: <49639cbf0610271909m34a01c35gb54ebb9495d103@mail.gmail.com>Package:g++-4.1 Version:4.1.1-18 What should dynamic_cast return if we have virtual base class that is first derived publicly, then privately? The following example shows that in gcc-4.1 dynamic_cast result depends on the order of declarations: /////// cl1.cc ////////////// #include <iostream> using namespace std; class A { public: virtual ~A() {} }; class B : public virtual A {}; class C : private virtual A {}; //! derived privately class T { public: virtual ~T() {}}; class D : public C, public B, public T {}; A* f(T* p) {return dynamic_cast<A*>(p);} int main() { D* p = new D; A* q = p; cout << f(p) << " " << q << endl; } ////////// end of cl1.cc /////////g++ cl1.cc && ./a.out0x804b008 0x804b008 ^^^^^^^^^ dynamic_cast from T* to A* is successfull Now, derive D first from B then C: ////////////////////// cl2.cc ///////////////// #include <iostream> using namespace std; class A { public: virtual ~A() {} }; class B : public virtual A {}; class C : private virtual A {}; class T { public: virtual ~T() {} }; class D : public B, public C, public T {}; //! change order of B and C A* f(T* p) {return dynamic_cast<A*>(p);} int main() { D* p = new D; A* q = p; cout << f(p) << " " << q << endl; } ///////////////// end of cl2.cc /////////////g++ cl2.cc && ./a.out0 0x804b008 ^^ dynamic_cast from T* to A* failed. On the other hand paragraph 5.2.7.8 of the C++ standard seems to indicate that dynamic_cast should succeed (T* is public base; is A unambiguous? -- yes, is A public base - yes (and no?)) Same results with gcc-snapshot. Vladimir1026 (prerelease) (Debian 4.1.1-18)
--- End Message ---
--- Begin Message ---
- To: 395837-done@bugs.debian.org
- Subject: C++ and mudflap packages not built anymore from the gcc-4.1 source
- From: Matthias Klose <doko@debian.org>
- Date: Sun, 11 Apr 2010 14:30:35 +0000
- Message-id: <E1O0yBH-00006w-SG@ravel.debian.org>The C++ and mudflap binary packages are not built anymore from the gcc-4.1 source package. Tagging this report as won't fix, and closing the report. Please check if the problem is fixed in gcc-4.4 (or gcc-4.5/gcc-snapshot). If the problem is not fixed, and not yet reported for the new compiler version(s), open a new report.
--- End Message --- | https://lists.debian.org/debian-gcc/2010/04/msg00129.html | CC-MAIN-2014-15 | refinedweb | 476 | 68.36 |
I have the following configuration at home:
* Linux box (Debian 4.0): Samba Server
* Windows box (Windows XP SP3): Samba Client
On the linux box I have a file that is read-only:
-r--r--r-- 1 apache servergroup 37 2008-09-26 16:48 dir-props
The directory that contains this file has the following rights:
drwxr-xr-x 2 apache servergroup 4096 2008-09-26 17:09 .svn
This directory is accessable through a Samba share. The Samba configuration is:
[global]
netbios name = deepthought
server string = Samba Server
workgroup = Maya Group
security = user
encrypt passwords = yes
smb passwd file = /srv/config/samba/smbpasswd
guest ok = yes
null passwords = no
browsable = yes
browse list = yes
[server]
path = /srv
create mask = 0644
directory mask = 0755
valid users = manski
force user = apache
read only = no
store dos attributes = no
map read only = yes
The problem now is that I can't move/rename this file (dir-props) with the Windows API function "MoveFileEx()" through the Samba client as the file is read-only. I get an "ERROR_ACCESS_DENIED" (Code 5).
When I, however, try to do the same thing on a "native" share (i.e. from another Windows XP box) everything is fine (i.e. no error and the file is renamed afterwards).
So, I think you should change this behaviour to fit the one of "native" Windows shares. An example where this method is used is a Subversion client that tries to do a commit on a Samba share (which doesn't work).
To test this behaviour you may use the following C (maybe C++) code:
#include <Stdio.h>
#include <Tchar.h>
#include <Windows.h>
TCHAR* from_file = "Z:\\test.txt";
TCHAR* to_file = "Z:\\test2.txt";
int _tmain(int argc, _TCHAR* argv[])
{
printf("%s\n", from_file);
if (MoveFileEx(from_file, to_file, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
{
printf("Good");
}
else
{
printf("Error: %d", GetLastError());
}
return 0;
}
I hope this helps.
Can you attach the binary of this program as an attachment to this bug. I don't have quick access to a Windows C compiler at the moment. Also a debug level 10 log from smbd when this program fails would help.
Thanks,
Jeremy.
Created attachment 3639 [details]
Patch for 3.2.x.
Here's the patch for 3.2.x. Will be in the next release. Thanks !
Jeremy.
Marking bug as fixed.
Please re-open if it is still an issue.
Thanks for reporting! | https://bugzilla.samba.org/show_bug.cgi?id=5797 | CC-MAIN-2021-17 | refinedweb | 398 | 65.52 |
Can't catch Enter (Return)
Hello,
I have tried the following code to qDebug something when I click the Enter Button, but nothing happens:
#include <QKeyEvent> bool MainWindow::eventFilter(QObject* obj, QEvent* event) { if (event->type()==QEvent::KeyPress) { QKeyEvent* key = static_cast<QKeyEvent*>(event); if ( (key->key()==Qt::Key_Enter) || (key->key()==Qt::Key_Return) ) { qDebug()<< "pressed"; } else { return QObject::eventFilter(obj, event); } return true; } else { return QObject::eventFilter(obj, event); } return false; } private slots: bool eventFilter(QObject* obj, QEvent* event);
@Chaki
Where is the focus when you click the Enter key? Is it on a widget, or do you have a blank main window?
- jsulm Lifetime Qt Champion last edited by
@Chaki said in Can't catch Enter (Return):
when I click the Enter Button
Do you mean: when I press the enter key?
Or are you using virtual keyboard?
I have solved it:
connect(ui->line_Edit, SIGNAL(returnPressed()),ui->btn_Button,SIGNAL(clicked()));
@Chaki
Which is what I suggested: you are pressing the Enter key on a
QLineEdit, but you did not tell us that, it helps if you do! :) That line edit has the focus, so the key press will not get sent to the main window.... | https://forum.qt.io/topic/113255/can-t-catch-enter-return | CC-MAIN-2022-27 | refinedweb | 196 | 51.31 |
Hello all,
I have been trying to call a function written in managed code, but it needs to be called from unmanaged code. Basically, I have a master thread within C++ code, that needs to update a .NET interface. The only way to do this is by calling a .NET function from within the master thread.
I have wrote a very basic program to try and get this working, but with no success. I have a std c++ class and a .net manged class. I create a .net delegate to that manged function, and pass the delegate to my standard class. It is then called from the main program. However, I keep getting an error which I have not been able to resolve.
If anyone could give me some suggestions as to where I am going wrong, that would be great. I have attached a zip file which demonstrates this, but with C# and a c++ dll. However, my interface needs to be in .net c++. You will have to rename the extension to .zip.
Code:#include <iostream> #include <tchar.h> using namespace System; class StdClass { public: typedef int (__stdcall *Callback)(int x, int y); StdClass(Callback ptr) { m_CallBack = ptr; } int Call(int x, int y) { return (*m_CallBack)(x, y); } private: Callback m_CallBack; }; __gc class GcClass { public: int Call(int x, int y) { return x * y; } }; __delegate int CallbackDelegate(int x, int y); int _tmain() { GcClass *gcClass = new GcClass(); CallbackDelegate *callBack = new CallbackDelegate(gcClass, &GcClass::Call); StdClass *stdClass = new StdClass((StdClass::Callback)callBack); int iResult = stdClass->Call(3, 3); delete stdClass; return 0; } | http://cboard.cprogramming.com/cplusplus-programming/61688-calling-manged-code-unmanged-code.html | CC-MAIN-2013-48 | refinedweb | 263 | 65.12 |
Red Hat Bugzilla – Bug 2556
glibc segfaults when using gdb on qt apps (vfprintf problem?)
Last modified: 2008-05-01 11:37:50 EDT
When running gdb on a Qt application, the program will
segfault in vfprintf when printing an initial debug message.
Here's the last two entries in the stack
#0 0x404dd5a8 in main_arena () from /lib/libc.so.6
#1 0x4043df06 in buffered_vfprintf (s=0x404dd500,
format=0x40171ca0 "Qt: gdb: -nograb added to command-line
options.\n\t Use the -dograb option to enforce grabbing.",
args=0xbffff2ac) at vfprintf.c:1752
I set the priority to low because you can get around this by
starting the program with "run -nograb". It seems like it
might be indicative of larger problems, though.
The program below will demonstrate the problem. It will run
normally (do nothing) from a command line, but dies when run
from gdb.
#include <qapp.h>
int main( int argc, char** argv )
{
QApplication a(argc,argv);
return a.exec();
}
Verified. GDB 4.18 can debug this program without problems. I really
suggest we get an update for gdb out the door for 6.0 asap. It isn't
just Qt -- anyone debugging moderately complex C++ applications cannot
debug with Red Hat Linux 6.0.
*** Bug 1772 has been marked as a duplicate of this bug. ***.
------- Additional Comments From kingdon@redhat.com 07/12/99 11:12 -------
There is no DNS entry for
Does this test case have a new location?
Please try gdb-4.18-3 which is now in Rawhide. | https://bugzilla.redhat.com/show_bug.cgi?id=2556 | CC-MAIN-2017-26 | refinedweb | 253 | 68.16 |
import "golang.org/x/crypto/openpgp/clearsign"
Package clearsign generates and processes OpenPGP, clear-signed data. See RFC 4880, section 7.
Clearsigned messages are cryptographically signed, but the contents of the message are kept in plaintext so that it can be read without special tools.
func Encode(w io.Writer, privateKey *packet.PrivateKey, config *packet.Config) (plaintext io.WriteCloser, err error)
Encode returns a WriteCloser which will clear-sign a message with privateKey and write it to w. If config is nil, sensible defaults are used.
type Block struct { Headers textproto.MIMEHeader // Optional message headers Plaintext []byte // The original message text Bytes []byte // The signed message ArmoredSignature *armor.Block // The signature block }
A Block represents a clearsigned message. A signature on a Block can be checked by passing Bytes into openpgp.CheckDetachedSignature.
Decode finds the first clearsigned message in data and returns it, as well as the suffix of data which remains after the message.
Package clearsign imports 10 packages (graph) and is imported by 74 packages. Updated 2017-11-30. Refresh now. Tools for package owners. | https://godoc.org/golang.org/x/crypto/openpgp/clearsign | CC-MAIN-2017-51 | refinedweb | 177 | 52.87 |
Model Web Pages with the Page Object PatternBy Darko Gjorgjievski
We interact with web pages every day. On the low level, clicking on various HTML elements or entering text in text forms using input devices. What’s the higher-level purpose of doing those things? It’s trying to get something done. Completing a Google search, submitting a contact form, or rating something. The Page Object pattern is a great, object-oriented way to keep your code clean while accomplishing those higher-level things as your application grows.
Fundamentals of the Page Object Pattern
Why use the Page Object pattern? Two words: code reuse. Let me explain.
Suppose you’re making an application that will go to a search engine and perform a search using a particular phrase. To do this, you will need to:
- Go to the web page
- Locate the HTML element where you can input text and enter your keyword (the text box)
- Find the Search button and click it
If you’re familiar with the Watir-Webdriver/Selenium, you know you can accomplish this easily with three lines. If you are not familiar with Watir/Selenium, please read my Watir article and then come back to this article. I’m waiting.
Suppose you needed to do each of these three actions several times in your code. What can you do? Sure, you can wrap your code in a method, and you’re done, right? But what if your application is getting more complex? Suppose that, instead of clicking the Search button, you want to click “I’m feeling Lucky” after entering your text. Or maybe, for some reason, first click the Search button twice and then enter the text and click Search again, doing that several times in your code.
You can end up with several methods containing several references to some HTML element. When the HTML element changes (due to a page redesign, it is no longer in class X but Y), you’ll need to make changes in several places in the code. Now, imagine something ten times more complicated than a search page, containing 20 different elements, which you can combine in 7 different ways. Things get really messy, really fast.
The Page Object pattern solves this problem by helping you model a single web page as a class, exposing its “services” (search for a keyword, search using “I’m Feeling Lucky”) as public methods. A web-based email page might have methods to compose an email, read the inbox, or save the message as a draft. You don’t want to bother how it’s doing that under the hood.
You can get away with Watir/Selenium if you’re dealing with a simple application and using the Page Object pattern may be overkill (I’m using a simple case through this article to illustrate how the whole gem works.) Patterns like Page Object weren’t invented for that purpose. They were created to keep your code manageable as it gets larger.
page-object: A Ruby Gem
The page-object gem is a very straightforward implementation of this pattern. To install it, just type
gem install page-object and you’re done. Make sure you also have the Watir-Webdriver installed because we’ll be using it for this article.
Previously, we mentioned that the Page Object pattern allows you to model a web page, exposing its “services” as public methods. When you want to model a specific web page using the Page Object gem, you’ll go through these 3 steps:
- Create the page by defining a class and including PageObject as a module.
- Describe the page by specifying the HTML elements you’ll use to interact with it.
- Use the page. by initializing the class as an object and calling its methods.
Create a Search Page
Let’s implement these 3 steps using a simple Search Page. To get started, we’ll create a class and include the Page Object module in it. Try running this code to see if everything is working.
require 'page-object' class SearchPage include PageObject # some code to declare the HTML elements end
What’s the whole point of including the
PageObject module? Every module provides methods, and this is no exception. It will also include some metaprogramming magic that we’ll explore later.
Describe the Single Search Page
The web was simple back in 2006. This Yahoo Search page was no exception. Let’s try and describe it by giving it a name and pointing the location to it.
Before getting started with using the Page Object on a web page, ask yourself: “What am I trying to do on this page?“, and then: What HTML elements will I need to get those things done?
We’re starting simple with our search page, just using it to search for a specific keyword. To accomplish that, we need to define a text box and the search button.
This is a useful reference where you can see helpful instructions for defining most elements. Try doing it yourself first. My result looks like this:
class SearchPage include PageObject text_field(:search_box, id: 'yschsp') button(:search_button, class: 'ygbt') end
text_field and
button are simply method calls. When defining an HTML element in a Page Object (via methods like those two), there are two main things you need to do:
Name the element (we named our two elements
search_boxand
search_button, respectively.) You do that by passing the name as a symbol for the first argument.
Provide instructions on how to locate it. What is it that uniquely identifies that element on the page? Often, it’s just one thing like the
id(
:yschsp) or the CSS
class(
ygbt). But what if this wasn’t the case?. Suppose there was another element on the page that had the same class as the button and no identifier. In that case, specify another attribute to make it clear what to locate.
Here’s the code I would use:
button(:search_button, class: 'ygbt', value: 'Search the Web')
Yes, you can specify more than one attribute to help locate an HTML element. Our button doesn’t need this modification though because the
ygbt class isn’t being used to identify anything else on the page.
Elements Defined, Now What?
This is where the magic happens! After modeling/defining our text field and button, we created five different methods. Yes, five of them! For example, after typing this:
text_field(:search_box, id: 'yschsp')
Page Object will create three separate methods:
search_box # returns the value in the text field search_box= # sets the value of the text field search_box_element # returns a reference to the actual HTML element
The whole point of defining and modeling HTML elements with calls to
text_field and
button is to create the above methods. Those newly created methods allow us to work with and manipulate the actual element.
For more information on what methods get created when you define an element, consult this Wiki page. In the next section, we’ll play around with them a bit.
Use Your Page Object
Page Object needs a Watir/Selenium browser instance to function. The page-object gem doesn’t give instructions to the browser directly, for more information see this article). I’ll be using Watir through this article. Let’s define a new browser instance first:
require 'watir-webdriver' browser = Watir::Browser.new :chrome
We forgot to add one essential thing to the definition of our
SearchPage. Can you guess which one? Sure, we have all the elements defined to manipulate the page. But what page exactly? Where is that page located? To tell Page Object the URL where the page can be found, add the
page_url method directly inside the
SearchPage class with an argument specifying the actual URL:
page_url('')
If you’re not sure how all of this comes together, the complete code is below.
We now have all of the necessary elements to get started! To start using the Page Object class, just create an instance of it and specify the browser instance you want to use as a parameter:
search_page = SearchPage.new(browser)
You cannot use your Page Object class without connecting it to a browser. It must have something to act upon.
Here’s the complete code. I added a few
sleep methods so you can clearly see what’s happening. See if you understand it fully and try running it on your computer before continuing with this article:
require 'page-object' require 'watir-webdriver' class SearchPage include PageObject page_url('') text_field(:search_box, id: 'yschsp') button(:search_button, class: 'ygbt') end browser = Watir::Browser.new :chrome search_page = SearchPage.new(browser) ; sleep 5 search_page.goto; sleep 5 search_page.search_box = 'I love SitePoint!'; sleep 5 search_page.search_button
Since we’re dealing with an Archive.org page here, you won’t get the actual search results once your script presses the “Search the web” button. I encourage you to modify it for the original [] and get it working after finishing this article.
You already know where the
search_box= and
search_button methods came from, but what about
goto?
goto is also a generated method. It was created when we called
page_url to specify the URL.
text_box,
page_url and
button are called accessors. Once you invoke them directly inside your class, page-object automatically creates relevant methods you can use when you create an object, as we saw above.
Using
page_url creates the
goto method that takes you to the page. Using
text_area creates four different methods. A button definition creates three.
Most of the time, you’ll want to
goto the page immediately when you create the Page Object instance (
search_page), though. This is easily accomplished by adding another argument to the constructor:
search_page = SearchPage.new(browser, true)
If the first argument was the browser instance, the second is whether to visit the page specified in
page_url immediately (by calling
goto for you in the background).
Grouping Towards a Common Purpose
So far, I am trying to demonstrate how Page Object works. The code above could be, in fact, be written easily in Watir and it would be approximately the same length. The magic of this pattern comes to life when we group everything together in a method towards a common purpose (looking up a keyword). Let’s add this method to the
SearchPage class definition:
def look_for(keyword) self.search_box = keyword; sleep 5 self.search_button end
And then do:
search_page = SearchPage.new(browser, true) search_page.look_for('I love SitePoint')
This is way cleaner than what Watir offers. A note on why it’s a good idea to include
self inside
look_for: Many of the methods generated by page-object are assignment-type methods, like
searchbox =. When calling these types of methods inside an instance method like
look_for, if you don’t add
self before them, Ruby will interpret them as local variables and not as method calls. For example, try predicting what this code will print to the console:
def hello=(arg) # assignment method puts arg end def hi(arg) # ordinary method puts arg end def integrate hello = 'article' # it's supposed to call the assignment method hi('blog') self.hello = 'ruby' end integrate
The output will be ‘blog’ and ‘ruby’, ‘article’ will not print at all.
Uh, Oh…Our Search Page Changed
Let’s fast forward our search page to 2013, when Yahoo Search had a major redesign. Here’s the URL. Put this link as a new argument to
page_url and try running your code. You should get this:
unable to locate element, using {:class=>"ygbt", :tag_name=>"button"} (Watir::Exception::UnknownObjectException)
With the new design, Yahoo changed its search button, no longer identifying it with
ygbt as the class name. The class is now called
sbb-sd. To make our code work again, just change the line where you define the button in your class:
button(:search_button, class: 'sbb-sd')
I want you to imagine what would the process be if you were not using the Page Object pattern. What if you had 5 ordinary methods, each utilizing this button, and each of them used this button towards a specific purpose. You’d have to change your code 5 times! Sure, you could implement your own pattern, but see how much more complex it is to do manually. Also, this is using Watir, the simplest possible automation tool using Ruby, one of the languages with the cleanest syntax. Imagine using Selenium and Java to implement your own Page Object pattern.
Here’s the complete code that includes the new argument for
page_url and the
look_for method:
require 'page-object' require 'watir-webdriver' class SearchPage include PageObject page_url('') def look_for(keyword) self.search_box = keyword; sleep 5 self.search_button end text_field(:search_box, id: 'yschsp') button(:search_button, class: 'sbb-sd') end browser = Watir::Browser.new :chrome search_page = SearchPage.new(browser, true) search_page.look_for('I love SitePoint')
Tips on Using Page Object
Here are some useful tips that might come in handy as you use this gem:
Accessing the Browser Instance
You can access the browser instance from your
PageObject class either via
@browser or using its getter attribute
browser, for example:
def look_for(keyword) self.search_box = keyword; sleep 5 self.search_button puts browser.text end
Navigating the Browser Without the Browser Instance
You have plenty of methods to go forward, back, refresh, clean cookies, etc. using the browser instance. I’ve added a 2 second pause between each action so you can see what’s going on more clearly:
def look_for(keyword) self.search_box = keyword self.search_button back; sleep 2 forward; sleep 2 clear_cookies; sleep 2; puts 'Cookies cleared!' puts current_url; sleep 2 puts element_with_focus; sleep 2 refresh; sleep 2 save_screenshot('screenshot.jpeg'); sleep 2 end
Handling Alerts
Page Object allows you to skip an alert box, getting only its value. Take this page, for example, and try to click the “Try it now” button. You should get “Hello from JavaScript!”. Now, try this code:
class AlertPage include PageObject page_url('') def get_alert_text message = alert do self.try_it_now end p message end button(:try_it_now, value: 'Try it now') end browser = Watir::Browser.new :chrome alert_page = AlertPage.new(browser, true) alert_page.get_alert_text
Notice how the alert box doesn’t appear at all! For doing the same with confirm/prompts, see this article.
Watir has pretty nice methods for dealing with alert boxes & Ajax which I find to be more convenient.
After Initialization
Do not use
initialize if you want some code to execute when you create your object.
PageObject makes use of this method and things will break if you try to overwrite it. Instead, use
initialize_page. Try adding this method to your
SearchPage class to see what I mean:
def initialize_page puts 'I am being initialized!' end
How to Learn More
Here are more useful resources where you can learn about Page Object:
- The gem’s Wiki
- The author’s blog (the comments also contain lot of useful material)
- This article :) Hope you found it useful!
Give the Page Object pattern a try the next time you need to use a web page in your Ruby. I think it will save you much time and aggravation. | https://www.sitepoint.com/model-web-pages-with-the-page-object-pattern/ | CC-MAIN-2017-13 | refinedweb | 2,518 | 64.91 |
#include <bookmarkstorage.h>
This is an implementation of XEP-0048 (Bookmark Storage).
You can use this class to store bookmarks to multi-user chat rooms or ordinary URLs on the server (and to retrieve them later on). To retrieve all stored bookmarks for the current user you have to create a class which inherits from BookmarkHandler. This handler receives retrieved bookmarks.
To store additional bookmarks you have to fetch the currently stored ones first, add your new bookmark to the list, and transfer them all together back to the server. This protocol does not support storage of 'deltas', that is, when saving bookmarks all previously saved bookmarks are overwritten.
Definition at line 97 of file bookmarkstorage.h.
Constructs a new BookmarkStorage object.
Definition at line 22 of file bookmarkstorage.cpp.
Virtual destructor.
Definition at line 28 of file bookmarkstorage.cpp.
Reimplement this function to receive the private XML that was requested earlier using
PrivateXML::requestXML().
Implements PrivateXMLHandler.
Definition at line 74 of file bookmarkstorage.cpp.
This function is called to notify about the result of a 'store' or 'request' operation (successful requests are announced by means of handlePrivateXML()).
Implements PrivateXMLHandler.
Definition at line 129 of file bookmarkstorage.cpp.
Use this function to register a BookmarkHandler.
Definition at line 133 of file bookmarkstorage.cpp.
Use this function to un-register the BookmarkHandler.
Definition at line 138 of file bookmarkstorage.cpp.
Use this function to initiate retrieval of bookmarks. Use registerBookmarkHandler() to register an object which will receive the lists of bookmarks.
Definition at line 69 of file bookmarkstorage.cpp.
Use this function to store a number of URL and conference bookmarks on the server. Make sure you store the whole set of bookmarks, not a 'delta'.
Definition at line 32 of file bookmarkstorage.cpp. | https://camaya.net/api/gloox-0.9.9.12/classgloox_1_1BookmarkStorage.html | CC-MAIN-2019-18 | refinedweb | 293 | 51.24 |
So, in Go (and C and C++ for that matter), the asterisk is overloaded to mean multiplication (when used between a pair of numbers or variables, as in
x*y), pointer declaration (when preceding a type name, as in
z *MyType), and pointer dereference (when preceding a pointer variable's name, as in
*z). Note that Go's channels, maps, and slices are all created using the
make() function, and
make() always returns a reference to the value it created. References behave very much like pointers in that when they are passed to functions, any changes made to them inside the function also affect the original channel, map, or slice. However, references don't need to be dereferenced, so in most cases, there's no need to use asterisks with them. But if we want to modify a slice inside a function or method using
append() (as opposed to simply changing one of its existing items), then we must either pass the slice by pointer, or return the slice (and set the original slice to the function or method's return value) because
append() sometimes returns a different slice reference than the one it was passed.
The
Stack type uses a slice for its representation, therefore
Stack values can be used with functions that operate on a slice, such as
append() and
len(). Nonetheless,
Stack values are values in their own right, distinct from their representation, so they must be passed by pointer if we want to modify them.
func (stack Stack) Top() (interface{}, error) { if len(stack) == 0 { return nil, errors.New("can't Top() an empty stack") } return stack[len(stack)-1], nil }
The
Stack.Top() method returns the item at the top of the stack (the item that was added last) and a
nil error value; or a
nil item and a non-
nil error value, if the stack is empty. The
stack receiver is passed by value because the stack wasn't modified.
The
error type is an interface type that specifies a single method, the
Error() string. In general, Go's library functions return an
error as their last (or only) return value to indicate success (where
error is
nil) or failure. Here, we have made our
Stack type work like a standard library type by creating a new
error value using the
errors package's
errors.New() function.
Go uses
nil for zero pointers (and for zero references); that is, for pointers that point to nothing and for references that refer to nothing. (Go's
nil is effectively the same as
NULL or
0 in C and C++,
null in Java, and
nil in Objective-C.) Such pointers should be used only in conditions or assignments; methods should not normally be called on them. Constructors are never called implicitly in Go. Instead, Go guarantees that when a value is created, it is always initialized to its zero value. For example, numbers are initialized to
0, strings to the empty string, pointers to
nil, and the fields inside
structs are similarly initialized. So there is no uninitialized data in Go, thus eliminating a major source of errors afflicting many other programming languages. If the zero value isn't suitable, we can write a construction function and call it explicitly as we do here to create a new
error. It is also possible to prevent values of a type being created without using a constructor function.
If the
stack is nonempty, we return its topmost value and a
nil
error value. Since Go uses zero-based indexing, the first element in a slice or array is at position
0 and the last element is at position
len(sliceOrArray)-1.
There is no formality when returning more than one value from a function or method; we simply list the types we are returning after the function or method's name and ensure that we have at least one
return statement that has a corresponding list of values.
func (stack *Stack) Pop() (interface{}, error) { theStack := *stack if len(theStack) == 0 { return nil, errors.New("can't Pop() an empty stack") } x := theStack[len(theStack)-1] *stack = theStack[:len(theStack)-1] return x, nil }
The
Stack.Pop() method is used to remove and return the top (last added) item from the stack. Like the
Stack.Top() method, it returns the item and a
nil error, or if the stack is empty, a
nil item and a non-
nil error.
The method must have a receiver that is a pointer because it modifies the stack by removing the returned item. For syntactic convenience, rather than referring to
*stack (the actual stack that the
stack variable points to) throughout the method, we assign the actual stack to a local variable (
theStack), and work with that variable instead. This is quite cheap, because
*stack is pointing to a
Stack, which uses a slice for its representation so we are really assigning little more than a reference to a slice.
If the stack is empty, we return a suitable error. Otherwise, we retrieve the stack's top (last) item and store it in a local variable (
x). Then we take a slice of the stack (which itself is a slice). The new slice has one less element than the original and is immediately set to be the value that the stack pointer points to. And at the end, we return the retrieved value and a
nil error. We can reasonably expect any decent Go compiler to reuse the slice, simply reducing the slice's length by one, while leaving its capacity unchanged, rather than copying all the data to a new slice.
The item to return is retrieved using the
[] index operator with a single index (➊); in this case, the index of the slice's last element. The new slice is obtained by using the
[] slice operator with an index range (➋). An index range has the form
first:end. If
first is omitted as here
0 is assumed, and if
end is omitted, the
len() of the slice is assumed. The slice thus obtained has elements with indexes from and including the
first up to and excluding the
end. So in this case, by specifying the last index as one less than the
length, we slice up to the last-but-one element, effectively removing the last element from the slice.
In this example, we used
Stack receivers rather than pointers of type
*Stack for those methods that don't modify the
Stack. For custom types with lightweight representations (say, a few
ints or
strings), this is perfectly reasonable. But for heavyweight custom types, it is usually best to always use pointer receivers because a pointer is much cheaper to pass (typically a simple 32- or 64-bit value) than a large value, even for methods where the value isn't modified.
A subtle point to note regarding pointers and methods is that if we call a method on a value, and the method requires a pointer to the value it is called on, Go is smart enough to pass the value's address rather than a copy of the value (providing the value is addressable). Correspondingly, if we call a method on a pointer to a value, and the method requires a value, Go is smart enough to dereference the pointer and give the method the pointed-to value. (This is why Go does not have or need the
-> indirection operator used by C and C++.)\As this example illustrates, creating custom types in Go is generally straightforward, and doesn't involve the cumbersome formalities that many other languages demand.
Files, Maps, and Closures
To have any practical use, a programming language must provide some means of reading and writing external data. Now that we've had a glimpse of Go's versatile and powerful print functions from its
fmt package, we will look at Go's basic file-handling facilities. We will also look at some more advanced features such as Go's treatment of functions and methods as first-class values, which makes it possible to pass them as parameters. And in addition, we will make use of Go's map type (also known as a data dictionary or hash).
By the mid-twentieth century, American English surpassed British English as the most widely used form of English. In this section's example, we will review a program that reads a text file and writes out a copy of the file into a new file with any words using British spellings replaced with their U.S. counterparts. (This doesn't help with differences in semantics or idioms, of course.) The program is in the file
americanise/americanise.go, and we will review it top-down, starting with its imports, then its
main() function, then the functions that
main() calls, and so on.
import ( "bufio" "fmt" "io" "io/ioutil" "log" "os" "path/filepath" "regexp" "strings" )
All the
americanise program's imports are from Go's standard library. Packages can be nested inside one another without formality, as the
io package's
ioutil package and the
path package's
filepath package illustrate. | http://www.drdobbs.com/open-source/go-tutorial-object-orientation-and-gos-s/240005402?pgno=2 | CC-MAIN-2014-35 | refinedweb | 1,522 | 56.89 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.