Search Results

Search found 255 results on 11 pages for 'pow'.

Page 8/11 | < Previous Page | 4 5 6 7 8 9 10 11  | Next Page >

  • Monogame/SharpDX - Shader parameters missing

    - by Layoric
    I am currently working on a simple game that I am building in Windows 8 using MonoGame (develop3d). I am using some shader code from a tutorial (made by Charles Humphrey) and having an issue populating a 'texture' parameter as it appears to be missing. Edit I have also tried 'Texture2D' and using it with a register(t0), still no luck I'm not well versed writing shaders, so this might be caused by a more obvious problem. I have debugged through MonoGame's Content processor to see how this shader is being parsed, all the non 'texture' parameters are there and look to be loading correctly. Edit This seems to go back to D3D compiler. Shader code below: #include "PPVertexShader.fxh" float2 lightScreenPosition; float4x4 matVP; float2 halfPixel; float SunSize; texture flare; sampler2D Scene: register(s0){ AddressU = Clamp; AddressV = Clamp; }; sampler Flare = sampler_state { Texture = (flare); AddressU = CLAMP; AddressV = CLAMP; }; float4 LightSourceMaskPS(float2 texCoord : TEXCOORD0 ) : COLOR0 { texCoord -= halfPixel; // Get the scene float4 col = 0; // Find the suns position in the world and map it to the screen space. float2 coord; float size = SunSize / 1; float2 center = lightScreenPosition; coord = .5 - (texCoord - center) / size * .5; col += (pow(tex2D(Flare,coord),2) * 1) * 2; return col * tex2D(Scene,texCoord); } technique LightSourceMask { pass p0 { VertexShader = compile vs_4_0 VertexShaderFunction(); PixelShader = compile ps_4_0 LightSourceMaskPS(); } } I've removed default values as they are currently not support in MonoGame and also changed ps and vs to v4 instead of 2. Could this be causing the issue? As I debug through 'DXConstantBufferData' constructor (from within the MonoGameContentProcessing project) I find that the 'flare' parameter does not exist. All others seem to be getting created fine. Any help would be appreciated. Update 1 I have discovered that SharpDX D3D compiler is what seems to be ignoring this parameter (perhaps by design?). The ConstantBufferDescription.VariableCount seems to be not counting the texture variable. Update 2 SharpDX function 'GetConstantBuffer(int index)' returns the parameters (minus textures) which is making is impossible to set values to these variables within the shader. Any one know if this is normal for DX11 / Shader Model 4.0? Or am I missing something else?

    Read the article

  • Objective-C Moving UIView along a curved path

    - by PruitIgoe
    I'm not sure if I am approaching this the correct way. In my app, when a user touches the screen I capture the point and create an arc from a fixed point to that touch point. I then want to move a UIView along that arc. Here's my code: ViewController.m //method to "shoot" object - KIP_Projectile creates the arc, KIP_Character creates the object I want to move along the arc ... //get arc for trajectory KIP_Projectile* vThisProjectile = [[KIP_Projectile alloc] initWithFrame:CGRectMake(51.0, fatElvisCenterPoint-30.0, touchPoint.x, 60.0)]; vThisProjectile.backgroundColor = [UIColor clearColor]; [self.view addSubview:vThisProjectile]; ... KIP_Character* thisChar = [[KIP_Character alloc] initWithFrame:CGRectMake(51, objCenterPoint-5, imgThisChar.size.width, imgThisChar.size.height)]; thisChar.backgroundColor = [UIColor clearColor]; thisChar.charID = charID; thisChar.charType = 2; thisChar.strCharType = @"Projectile"; thisChar.imgMyImage = imgThisChar; thisChar.myArc = vThisProjectile; [thisChar buildImage]; [thisChar traceArc]; in KIP_Projectile I build the arc using this code: - (CGMutablePathRef) createArcPathFromBottomOfRect : (CGRect) rect : (CGFloat) arcHeight { CGRect arcRect = CGRectMake(rect.origin.x, rect.origin.y + rect.size.height - arcHeight, rect.size.width, arcHeight); CGFloat arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height)); CGPoint arcCenter = CGPointMake(arcRect.origin.x + arcRect.size.width/2, arcRect.origin.y + arcRadius); CGFloat angle = acos(arcRect.size.width / (2*arcRadius)); CGFloat startAngle = radians(180) + angle; CGFloat endAngle = radians(360) - angle; CGMutablePathRef path = CGPathCreateMutable(); CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius, startAngle, endAngle, 0); return path; } - (void)drawRect:(CGRect)rect { CGContextRef currentContext = UIGraphicsGetCurrentContext(); _myArcPath = [self createArcPathFromBottomOfRect:self.bounds:30.0]; CGContextSetLineWidth(currentContext, 1); CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f}; CGContextSetStrokeColor(currentContext, red); CGContextAddPath(currentContext, _myArcPath); CGContextStrokePath(currentContext); } Works fine. The arc is displayed with a red stroke on the screen. In KIP_Character, which has been passed it's relevant arc, I am using this code but getting no results. - (void) traceArc { CGMutablePathRef myArc = _myArc.myArcPath; // Set up path movement CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; pathAnimation.calculationMode = kCAAnimationPaced; pathAnimation.fillMode = kCAFillModeForwards; pathAnimation.removedOnCompletion = NO; pathAnimation.path = myArc; CGPathRelease(myArc); [self.layer addAnimation:pathAnimation forKey:@"savingAnimation"]; } Any help here would be appreciated.

    Read the article

  • design a model for a system of dependent variables

    - by dbaseman
    I'm dealing with a modeling system (financial) that has dozens of variables. Some of the variables are independent, and function as inputs to the system; most of them are calculated from other variables (independent and calculated) in the system. What I'm looking for is a clean, elegant way to: define the function of each dependent variable in the system trigger a re-calculation, whenever a variable changes, of the variables that depend on it A naive way to do this would be to write a single class that implements INotifyPropertyChanged, and uses a massive case statement that lists out all the variable names x1, x2, ... xn on which others depend, and, whenever a variable xi changes, triggers a recalculation of each of that variable's dependencies. I feel that this naive approach is flawed, and that there must be a cleaner way. I started down the path of defining a CalculationManager<TModel> class, which would be used (in a simple example) something like as follows: public class Model : INotifyPropertyChanged { private CalculationManager<Model> _calculationManager = new CalculationManager<Model>(); // each setter triggers a "PropertyChanged" event public double? Height { get; set; } public double? Weight { get; set; } public double? BMI { get; set; } public Model() { _calculationManager.DefineDependency<double?>( forProperty: model => model.BMI, usingCalculation: (height, weight) => weight / Math.Pow(height, 2), withInputs: model => model.Height, model.Weight); } // INotifyPropertyChanged implementation here } I won't reproduce CalculationManager<TModel> here, but the basic idea is that it sets up a dependency map, listens for PropertyChanged events, and updates dependent properties as needed. I still feel that I'm missing something major here, and that this isn't the right approach: the (mis)use of INotifyPropertyChanged seems to me like a code smell the withInputs parameter is defined as params Expression<Func<TModel, T>>[] args, which means that the argument list of usingCalculation is not checked at compile time the argument list (weight, height) is redundantly defined in both usingCalculation and withInputs I am sure that this kind of system of dependent variables must be common in computational mathematics, physics, finance, and other fields. Does someone know of an established set of ideas that deal with what I'm grasping at here? Would this be a suitable application for a functional language like F#? Edit More context: The model currently exists in an Excel spreadsheet, and is being migrated to a C# application. It is run on-demand, and the variables can be modified by the user from the application's UI. Its purpose is to retrieve variables that the business is interested in, given current inputs from the markets, and model parameters set by the business.

    Read the article

  • Router startup problem

    - by gfmoz
    I have problems with my Tilgin Vood Router. As I try to start my router by turning the power on (captain obvious), it generally doesn't work the first 3-4 times. This is getting very annoying. Five minutes after turning the power on the router's signal LEDs don't blink in the way they should do in a connected state. I can connect to my routers web configuration interface through my PC connected to it via LAN though I can't access the internet. It usually takes the router five minutes to get to the point where it should be connected to the internet but as it doesn't work the first times. So I turn on my router 3-5 times, let him work 5 minutes and then suddenly, after turning the pow*emphasized text*er off and on again it all works. The problem is regarding startup only, when I get it to work everything runs as smooth as a 1980-s text-based C++ game on a 3ghz machine. I also have to restart my PC too in order for everything to work. - How can I solve this problem? - Just leave the router turned on all time? I prefer a daily IP switch, though. - May the problem have something to do with my PC? There is another one connected to the router too and it doesn't work there either.

    Read the article

  • How to synchronize cuda threads when they are in the same loop and we need to synchronize them to ex

    - by Vickey
    Hi all, I have written a code and Now I want to implement this on cuda GPU but I'm new to synchronization so please help me with this, It's little urgent to me. Below I'm presenting the code and I want to that LOOP1 to be executed by all threads (heance I want to this portion to take advantage of cuda and the remaining portion (the portion other from the LOOP1) is to be executed by only a single thread. do{ point_set = master_Q[(*num_mas) - 1].q; List* temp = point_set; List* pa = point_set; if(master_Q[num_mas[0] - 1].max) max_level = (int) (ceilf(il2 * log(master_Q[num_mas[0] - 1].max))); *num_mas = (*num_mas) - 1; while(point_set){ List* insert_ele = temp; while(temp){ insert_ele = temp; if((insert_ele->dist[insert_ele->dist_index-1] <= pow(2, max_level-1)) || (top_level == max_level)){ if(point_set == temp){ point_set = temp->next; pa = temp->next; } else{ pa->next = temp->next; } temp = NULL; List* new_point_set = point_set; float maximum_dist = 0; if(parent->p_index != insert_ele->point_index){ List* tmp = new_point_set; float *b = &(data[(insert_ele->point_index)*point_len]); **LOOP 1:** while(tmp){ float *c = &(data[(tmp->point_index)*point_len]); float sum = 0.; for(int j = 0; j < point_len; j+=2){ float d1 = b[j] - c[j]; float d2 = b[j+1] - c[j+1]; d1 *= d1; d2 *= d2; sum = sum + d1 + d2; } tmp->dist[tmp->dist_index] = sqrt(sum); if(maximum_dist < tmp->dist[tmp->dist_index]) maximum_dist = tmp->dist[tmp->dist_index]; tmp->dist_index = tmp->dist_index+1; tmp = tmp->next; } max_distance = maximum_dist; } while(new_point_set || insert_ele){ List* far, *par, *tmp, *tmp_new; far = NULL; tmp = new_point_set; tmp_new = NULL; float level_dist = pow(2, max_level-1); float maxdist = 0, maxp = 0; while(tmp){ if(tmp->dist[(tmp->dist_index)-1] > level_dist){ if(maxdist < tmp->dist[tmp->dist_index-1]) maxdist = tmp->dist[tmp->dist_index-1]; if(tmp == new_point_set){ new_point_set = tmp->next; par = tmp->next; } else{ par->next = tmp->next; } if(far == NULL){ far = tmp; tmp_new = far; } else{ tmp_new->next = tmp; tmp_new = tmp; } if(parent->p_index != insert_ele->point_index) tmp->dist_index = tmp->dist_index - 1; tmp = tmp->next; tmp_new->next = NULL; } else{ par = tmp; if(maxp < tmp->dist[(tmp->dist_index)-1]) maxp = tmp->dist[(tmp->dist_index)-1]; tmp = tmp->next; } } if(0 == maxp){ tmp = new_point_set; aloc_mem[*tree_index].p_index = insert_ele->point_index; aloc_mem[*tree_index].no_child = 0; aloc_mem[*tree_index].level = max_level--; parent->children_index[parent->no_child++] = *tree_index; parent = &(aloc_mem[*tree_index]); tree_index[0] = tree_index[0]+1; while(tmp){ aloc_mem[*tree_index].p_index = tmp->point_index; aloc_mem[(*tree_index)].no_child = 0; aloc_mem[(*tree_index)].level = master_Q[(*cur_count_Q)-1].level; parent->children_index[parent->no_child] = *tree_index; parent->no_child = parent->no_child + 1; (*tree_index)++; tmp = tmp->next; } cur_count_Q[0] = cur_count_Q[0]-1; new_point_set = NULL; } master_Q[*num_mas].q = far; master_Q[*num_mas].parent = parent; master_Q[*num_mas].valid = true; master_Q[*num_mas].max = maxdist; master_Q[*num_mas].level = max_level; num_mas[0] = num_mas[0]+1; if(0 != maxp){ aloc_mem[*tree_index].p_index = insert_ele->point_index; aloc_mem[*tree_index].no_child = 0; aloc_mem[*tree_index].level = max_level; parent->children_index[parent->no_child++] = *tree_index; parent = &(aloc_mem[*tree_index]); tree_index[0] = tree_index[0]+1; if(maxp){ int new_level = ((int) (ceilf(il2 * log(maxp)))) +1; if (new_level < (max_level-1)) max_level = new_level; else max_level--; } else max_level--; } if( 0 == maxp ) insert_ele = NULL; } } else{ if(NULL == temp->next){ master_Q[*num_mas].q = point_set; master_Q[*num_mas].parent = parent; master_Q[*num_mas].valid = true; master_Q[*num_mas].level = max_level; num_mas[0] = num_mas[0]+1; } pa = temp; temp = temp->next; } } if((*num_mas) > 1){ List *temp2 = master_Q[(*num_mas)-1].q; while(temp2){ List* temp3 = master_Q[(*num_mas)-2].q; master_Q[(*num_mas)-2].q = temp2; if((master_Q[(*num_mas)-1].parent)->p_index != (master_Q[(*num_mas)-2].parent)->p_index){ temp2->dist_index = temp2->dist_index - 1; } temp2 = temp2->next; master_Q[(*num_mas)-2].q->next = temp3; } num_mas[0] = num_mas[0]-1; } point_set = master_Q[(*num_mas)-1].q; temp = point_set; pa = point_set; parent = master_Q[(*num_mas)-1].parent; max_level = master_Q[(*num_mas)-1].level; if(master_Q[(*num_mas)-1].max) if( max_level > ((int) (ceilf(il2 * log(master_Q[(*num_mas)-1].max)))) +1) max_level = ((int) (ceilf(il2 * log(master_Q[(*num_mas)-1].max)))) +1; num_mas[0] = num_mas[0]-1; } }while(*num_mas > 0);

    Read the article

  • InSync12 and Australia Visits: UX is Global, Regional, Everywhere!

    - by ultan o'broin
    I attended the Australian Oracle User Group (AUSOUG) and Quest International User Group's InSync12 event in Melbourne, Australia: the user group conference for Oracle products in the ANZ region. I demoed Oracle Fusion Applications and then presented how Oracle crafted the world class Fusion Apps user experience (UX). I explained about the Oracle user experience design pattern strategy of uptake for all apps, not just Fusion, and what our UX pattern externalization strategy means for customers, partners, and ADF developers. A great conference, lots of energy, the InSync12 highlights for me were Oracle's Senior Vice President Cliff Godwin’s fast-moving Oracle E-Business Suite (EBS) roadshow with the killer Oracle Endeca user experience uptake, and Oracle ADF product outreachmeister Chris Muir’s (@chriscmuir) session on Oracle ADF Mobile solution and his hands-on mobile app development showing how existing ADF/JDev skills can build a secure, code once-deploy-to-many-device hybrid app solution in minutes. Cliff Godwin shows off the Oracle Endeca integration with Oracle E-Business Suite. Chris Muir talked the talk and then walked the walked with Oracle ADF Mobile. Applications UX was mixing it up with the crowd at InSync12 too, showing off cool mobile UX solutions, gathering data for future innovations, and engaging with EBS, JD Edwards, and PeopleSoft apps customers and partners. User conferences such as InSync12 are an important part of our Oracle Applications UX user-centered design process, giving real apps users the opportunity to make real inputs and a way for us to watch and to listen to their needs and wants and get views on current and emerging UX too. Eric Stilan (@icondaddy) of Applications UX uses an iPad to gather feedback on the latest UX designs from conference attendees. While in Melbourne, I also visited impressive Oracle partner, Callista for a major ADF and UX pow-wow, and was the er, star of a very proactive event hosted by another partner Park Lane Information Technology (coordinated by Bambi Price (@bambiprice) of ODTUG) where I explained what UX is about, and how partner and customers can engage, participate and deploy that Applications UX scientific insight to advantage for their entire business. I also paired up with Oracle Australia in Sydney to visit key customers while there, and back at Oracle in Melbourne I spoke with sales consultants and account managers about regional opportunities and UX strategy, and came away with an understanding of what makes the Oracle market tick in Australia. Mobile worker solution development and user experience is hot news in Australia, and this was a great opportunity to team up with Chris Muir and show how the alignment of the twin stars of UX design patterns and ADF technology enables developers to make great-looking, usable apps that really sparkle. Our UX design patterns--or functional (UI) patterns, to use the developer world language--means that developers now have not only a great tool set to build apps on Oracle ADF/FMW but proven, tested usability solutions to solve common problems they can apply in the IDE too. In all, a whirlwind UX visit, packed with events and delivery opportunities, and all too short a time in the wonderful city of Melbourne. I need to get back there soon! For those who need a reminder, there's a website explaining how to get involved with, and participate in, Applications User Experience (including the Oracle Usability Advisory Board) events and programs. Thank you to AUSOUG, Quest, InSync, Callista, Park Lane IT, everyone at Oracle Australia, Chris Muir, and all the other people who came together to make this a productive visit. Stay tuned for more UX developments and engagements in the region on the Oracle VoX blog and Usable Apps website too!

    Read the article

  • XNA 4.0 - Normal mapping shader - strange texture artifacts

    - by Taylor
    I recently started using custom shader. Shader can do diffuse and specular lighting and normal mapping. But normal mapping is causing really ugly artifacts (some sort of pixeling noise) for textures in greater distance. It looks like this: Image link This is HLSL code: // Matrix float4x4 World : World; float4x4 View : View; float4x4 Projection : Projection; //Textury texture2D ColorMap; sampler2D ColorMapSampler = sampler_state { Texture = <ColorMap>; MinFilter = Anisotropic; MagFilter = Linear; MipFilter = Linear; MaxAnisotropy = 16; }; texture2D NormalMap; sampler2D NormalMapSampler = sampler_state { Texture = <NormalMap>; MinFilter = Anisotropic; MagFilter = Linear; MipFilter = Linear; MaxAnisotropy = 16; }; // Light float4 AmbientColor : Color; float AmbientIntensity; float3 DiffuseDirection : LightPosition; float4 DiffuseColor : Color; float DiffuseIntensity; float4 SpecularColor : Color; float3 CameraPosition : CameraPosition; float Shininess; // The input for the VertexShader struct VertexShaderInput { float4 Position : POSITION0; float2 TexCoord : TEXCOORD0; float3 Normal : NORMAL0; float3 Binormal : BINORMAL0; float3 Tangent : TANGENT0; }; // The output from the vertex shader, used for later processing struct VertexShaderOutput { float4 Position : POSITION0; float2 TexCoord : TEXCOORD0; float3 View : TEXCOORD1; float3x3 WorldToTangentSpace : TEXCOORD2; }; // The VertexShader. VertexShaderOutput VertexShaderFunction(VertexShaderInput input, float3 Normal : NORMAL) { VertexShaderOutput output; float4 worldPosition = mul(input.Position, World); float4 viewPosition = mul(worldPosition, View); output.Position = mul(viewPosition, Projection); output.TexCoord = input.TexCoord; output.WorldToTangentSpace[0] = mul(normalize(input.Tangent), World); output.WorldToTangentSpace[1] = mul(normalize(input.Binormal), World); output.WorldToTangentSpace[2] = mul(normalize(input.Normal), World); output.View = normalize(float4(CameraPosition,1.0) - worldPosition); return output; } // The Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 { float4 color = tex2D(ColorMapSampler, input.TexCoord); float3 normalMap = 2.0 *(tex2D(NormalMapSampler, input.TexCoord)) - 1.0; normalMap = normalize(mul(normalMap, input.WorldToTangentSpace)); float4 normal = float4(normalMap,1.0); float4 diffuse = saturate(dot(-DiffuseDirection,normal)); float4 reflect = normalize(2*diffuse*normal-float4(DiffuseDirection,1.0)); float4 specular = pow(saturate(dot(reflect,input.View)), Shininess); return color * AmbientColor * AmbientIntensity + color * DiffuseIntensity * DiffuseColor * diffuse + color * SpecularColor * specular; } // Techniques technique Lighting { pass Pass1 { VertexShader = compile vs_2_0 VertexShaderFunction(); PixelShader = compile ps_2_0 PixelShaderFunction(); } } Any advice? Thanks!

    Read the article

  • 2D Tile Based Collision Detection

    - by MrPlosion1243
    There are a lot of topics about this and it seems each one addresses a different problem, this topic does the same. I was looking into tile collision detection and found this where David Gouveia explains a great way to get around the person's problem by separating the two axis. So I implemented the solution and it all worked perfectly from all the testes I through at it. Then I implemented more advanced platforming physics and the collision detection broke down. Unfortunately I have not been able to get it to work again which is where you guys come in :)! I will present the code first: public void Update(GameTime gameTime) { if(Input.GetKeyDown(Keys.A)) { velocity.X -= moveAcceleration; } else if(Input.GetKeyDown(Keys.D)) { velocity.X += moveAcceleration; } if(Input.GetKeyDown(Keys.Space)) { if((onGround && isPressable) || (!onGround && airTime <= maxAirTime && isPressable)) { onGround = false; airTime += (float)gameTime.ElapsedGameTime.TotalSeconds; velocity.Y = initialJumpVelocity * (1.0f - (float)Math.Pow(airTime / maxAirTime, Math.PI)); } } else if(Input.GetKeyReleased(Keys.Space)) { isPressable = false; } if(onGround) { velocity.X *= groundDrag; velocity.Y = 0.0f; } else { velocity.X *= airDrag; velocity.Y += gravityAcceleration; } velocity.Y = MathHelper.Clamp(velocity.Y, -maxFallSpeed, maxFallSpeed); velocity.X = MathHelper.Clamp(velocity.X, -maxMoveSpeed, maxMoveSpeed); position += velocity * (float)gameTime.ElapsedGameTime.TotalSeconds; position = new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y)); if(Math.Round(velocity.X) != 0.0f) { HandleCollisions2(Direction.Horizontal); } if(Math.Round(velocity.Y) != 0.0f) { HandleCollisions2(Direction.Vertical); } } private void HandleCollisions2(Direction direction) { int topTile = (int)Math.Floor((float)Bounds.Top / Tile.PixelTileSize); int bottomTile = (int)Math.Ceiling((float)Bounds.Bottom / Tile.PixelTileSize) - 1; int leftTile = (int)Math.Floor((float)Bounds.Left / Tile.PixelTileSize); int rightTile = (int)Math.Ceiling((float)Bounds.Right / Tile.PixelTileSize) - 1; for(int x = leftTile; x <= rightTile; x++) { for(int y = topTile; y <= bottomTile; y++) { Rectangle tileBounds = new Rectangle(x * Tile.PixelTileSize, y * Tile.PixelTileSize, Tile.PixelTileSize, Tile.PixelTileSize); Vector2 depth; if(Tile.IsSolid(x, y) && Intersects(tileBounds, direction, out depth)) { if(direction == Direction.Horizontal) { position.X += depth.X; } else { onGround = true; isPressable = true; airTime = 0.0f; position.Y += depth.Y; } } } } } From the code you can see when velocity.X is not equal to zero the HandleCollisions() Method is called along the horizontal axis and likewise for the vertical axis. When velocity.X is not equal to zero and velocity.Y is equal to zero it works fine. When velocity.Y is not equal to zero and velocity.X is equal to zero everything also works fine. However when both axis are not equal to zero that's when it doesn't work and I don't know why. I basically teleport to the left side of a tile when both axis are not equal to zero and there is a air block next to me. Hopefully someone can see the problem with this because I sure don't as far as I'm aware nothing has even changed from what I'm doing to what the linked post's solution is doing. Thanks.

    Read the article

  • Are Chief Digital Officers the Result of CMO/CIO Refusal to Change?

    - by Mike Stiles
    Apparently CDO no longer just stands for “Collateralized Debt Obligations.”  It stands for Chief Digital Officer. And they’re the ones who are supposed to answer the bat signal CEO’s are throwing into the sky, swoop in and POW! drive the transition of the enterprise to integrated digital systems. So imagine being a CMO or a CIO at such an enterprise and realizing it’s been determined that you are not the answer that’s needed. In fact, IntelligentHQ author Ashley Friedlein points out the very rise of the CDO is an admission of C-Suite failure to become savvy enough, quickly enough in modern technology. Is that fair? Despite the repeated drumbeat that CMO’s and CIO’s must enter a new era of cooperation and collaboration to enact the social-enabled enterprise, the verdict seems to be that if it’s happening at all, it’s not happening fast enough. Therefore, someone else is needed with the authority to make things happen. So who is this relatively new beast? Gartner VP David Willis says, “The Chief Digital Officer plays in the place where the enterprise meets the customer, where the revenue is generated, and the mission accomplished.” In other words, where the rubber meets the road. They aren’t just another “C” heading up a unit. They’re the CEO’s personal SWAT team, able to call the shots necessary across all units to affect what has become job one…customer experience. And what are the CMO’s and CIO’s doing while this is going on? Playing corporate games. Accenture reports 38% of CMOs say IT deliberately keeps them out of the loop, with 35% saying marketing’s needs aren’t a very high priority. 31% of CIOs say marketers don’t understand tech and regularly go around them for solutions. Fun! Meanwhile the CEO feels the need to bring in a parental figure to pull it all together. Gartner thinks 25% of all orgs will have a CDO by 2015 as CMO’s and particularly CIO’s (Peter Hinssen points out many CDO’s are coming “from anywhere but IT”) let the opportunity to be the agent of change their company needs slip away. Perhaps most interestingly, these CDO’s seem to be entering the picture already on the fast track. One consultancy counted 7 instances of a CDO moving into the CEO role, which, as this Wired article points out, is pretty astounding since nobody ever heard of the job a few years ago. And vendors are quickly figuring out that this is the person they need to be talking to inside the brand. The position isn’t without its critics. Forrester’s Martin Gill says the reaction from executives at some traditional companies to someone being brought in to be in charge of digital might be to wash their own hands of responsibility for all things digital – a risky maneuver given the pervasiveness of digital in business. They might not even be called Chief Digital Officers. They might be the Chief Customer Officer, Chief Experience Officer, etc. You can call them Twinkletoes if you want to, but essentially anyone who has the mandate direct from the CEO to enact modern technology changes not currently being championed by the CMO or CIO can be regarded as “boss.” @mikestiles @oraclesocialPhoto: freedigitalphotos.net

    Read the article

  • Is there an easy way to type in common math symbols?

    - by srcspider
    Disclaimer: I'm sure someone is going to moan about easy-of-use, for the purpose of this question consider readability to be the only factor that matters So I found this site that converts to easting northing, it's not really important what that even means but here's how the piece of javascript looks. /** * Convert Ordnance Survey grid reference easting/northing coordinate to (OSGB36) latitude/longitude * * @param {OsGridRef} gridref - easting/northing to be converted to latitude/longitude * @returns {LatLonE} latitude/longitude (in OSGB36) of supplied grid reference */ OsGridRef.osGridToLatLong = function(gridref) { var E = gridref.easting; var N = gridref.northing; var a = 6377563.396, b = 6356256.909; // Airy 1830 major & minor semi-axes var F0 = 0.9996012717; // NatGrid scale factor on central meridian var f0 = 49*Math.PI/180, ?0 = -2*Math.PI/180; // NatGrid true origin var N0 = -100000, E0 = 400000; // northing & easting of true origin, metres var e2 = 1 - (b*b)/(a*a); // eccentricity squared var n = (a-b)/(a+b), n2 = n*n, n3 = n*n*n; // n, n², n³ var f=f0, M=0; do { f = (N-N0-M)/(a*F0) + f; var Ma = (1 + n + (5/4)*n2 + (5/4)*n3) * (f-f0); var Mb = (3*n + 3*n*n + (21/8)*n3) * Math.sin(f-f0) * Math.cos(f+f0); var Mc = ((15/8)*n2 + (15/8)*n3) * Math.sin(2*(f-f0)) * Math.cos(2*(f+f0)); var Md = (35/24)*n3 * Math.sin(3*(f-f0)) * Math.cos(3*(f+f0)); M = b * F0 * (Ma - Mb + Mc - Md); // meridional arc } while (N-N0-M >= 0.00001); // ie until < 0.01mm var cosf = Math.cos(f), sinf = Math.sin(f); var ? = a*F0/Math.sqrt(1-e2*sinf*sinf); // nu = transverse radius of curvature var ? = a*F0*(1-e2)/Math.pow(1-e2*sinf*sinf, 1.5); // rho = meridional radius of curvature var ?2 = ?/?-1; // eta = ? var tanf = Math.tan(f); var tan2f = tanf*tanf, tan4f = tan2f*tan2f, tan6f = tan4f*tan2f; var secf = 1/cosf; var ?3 = ?*?*?, ?5 = ?3*?*?, ?7 = ?5*?*?; var VII = tanf/(2*?*?); var VIII = tanf/(24*?*?3)*(5+3*tan2f+?2-9*tan2f*?2); var IX = tanf/(720*?*?5)*(61+90*tan2f+45*tan4f); var X = secf/?; var XI = secf/(6*?3)*(?/?+2*tan2f); var XII = secf/(120*?5)*(5+28*tan2f+24*tan4f); var XIIA = secf/(5040*?7)*(61+662*tan2f+1320*tan4f+720*tan6f); var dE = (E-E0), dE2 = dE*dE, dE3 = dE2*dE, dE4 = dE2*dE2, dE5 = dE3*dE2, dE6 = dE4*dE2, dE7 = dE5*dE2; f = f - VII*dE2 + VIII*dE4 - IX*dE6; var ? = ?0 + X*dE - XI*dE3 + XII*dE5 - XIIA*dE7; return new LatLonE(f.toDegrees(), ?.toDegrees(), GeoParams.datum.OSGB36); } I found that to be a really nice way of writing an algorythm, at least as far as redability is concerned. Is there any way to easily write the special symbols. And by easily write I mean NOT copy/paste them.

    Read the article

  • Simple OpenGL program major slow down at high resolution

    - by Grieverheart
    I have created a small OpenGL 3.3 (Core) program using freeglut. The whole geometry is two boxes and one plane with some textures. I can move around like in an FPS and that's it. The problem is I face a big slow down of fps when I make my window large (i.e. above 1920x1080). I have monitors GPU usage when in full-screen and it shows GPU load of nearly 100% and Memory Controller load of ~85%. When at 600x600, these numbers are at about 45%, my CPU is also at full load. I use deferred rendering at the moment but even when forward rendering, the slow down was nearly as severe. I can't imagine my GPU is not powerful enough for something this simple when I play many games at 1080p (I have a GeForce GT 120M btw). Below are my shaders, First Pass #VS #version 330 core uniform mat4 ModelViewMatrix; uniform mat3 NormalMatrix; uniform mat4 MVPMatrix; uniform float scale; layout(location = 0) in vec3 in_Position; layout(location = 1) in vec3 in_Normal; layout(location = 2) in vec2 in_TexCoord; smooth out vec3 pass_Normal; smooth out vec3 pass_Position; smooth out vec2 TexCoord; void main(void){ pass_Position = (ModelViewMatrix * vec4(scale * in_Position, 1.0)).xyz; pass_Normal = NormalMatrix * in_Normal; TexCoord = in_TexCoord; gl_Position = MVPMatrix * vec4(scale * in_Position, 1.0); } #FS #version 330 core uniform sampler2D inSampler; smooth in vec3 pass_Normal; smooth in vec3 pass_Position; smooth in vec2 TexCoord; layout(location = 0) out vec3 outPosition; layout(location = 1) out vec3 outDiffuse; layout(location = 2) out vec3 outNormal; void main(void){ outPosition = pass_Position; outDiffuse = texture(inSampler, TexCoord).xyz; outNormal = pass_Normal; } Second Pass #VS #version 330 core uniform float scale; layout(location = 0) in vec3 in_Position; void main(void){ gl_Position = mat4(1.0) * vec4(scale * in_Position, 1.0); } #FS #version 330 core struct Light{ vec3 direction; }; uniform ivec2 ScreenSize; uniform Light light; uniform sampler2D PositionMap; uniform sampler2D ColorMap; uniform sampler2D NormalMap; out vec4 out_Color; vec2 CalcTexCoord(void){ return gl_FragCoord.xy / ScreenSize; } vec4 CalcLight(vec3 position, vec3 normal){ vec4 DiffuseColor = vec4(0.0); vec4 SpecularColor = vec4(0.0); vec3 light_Direction = -normalize(light.direction); float diffuse = max(0.0, dot(normal, light_Direction)); if(diffuse 0.0){ DiffuseColor = diffuse * vec4(1.0); vec3 camera_Direction = normalize(-position); vec3 half_vector = normalize(camera_Direction + light_Direction); float specular = max(0.0, dot(normal, half_vector)); float fspecular = pow(specular, 128.0); SpecularColor = fspecular * vec4(1.0); } return DiffuseColor + SpecularColor + vec4(0.1); } void main(void){ vec2 TexCoord = CalcTexCoord(); vec3 Position = texture(PositionMap, TexCoord).xyz; vec3 Color = texture(ColorMap, TexCoord).xyz; vec3 Normal = normalize(texture(NormalMap, TexCoord).xyz); out_Color = vec4(Color, 1.0) * CalcLight(Position, Normal); } Is it normal for the GPU to be used that much under the described circumstances? Is it due to poor performance of freeglut? I understand that the problem could be specific to my code, but I can't paste the whole code here, if you need more info, please tell me.

    Read the article

  • Intern Screening - Software 'Quiz'

    - by Jeremy1026
    I am in charge of selecting a new software development intern for a company that I work with. I wanted to throw a little 'quiz' at the applicants before moving forth with interviews so as to weed out the group a little bit to find some people that can demonstrate some skill. I put together the following quiz to send to applicants, it focuses only on PHP, but that is because that is what about 95% of the work will be done in. I'm hoping to get some feedback on A. if its a good idea to send this to applicants and B. if it can be improved upon. # 1. FizzBuzz # Write a small application that does the following: # Counts from 1 to 100 # For multiples of 3 output "Fizz" # For multiples of 5 output "Buzz" # For multiples of 3 and 5 output "FizzBuzz" # For numbers that are not multiples of 3 nor 5 output the number. <?php ?> # 2. Arrays # Create a multi-dimensional array that contains # keys for 'id', 'lot', 'car_model', 'color', 'price'. # Insert three sets of data into the array. <?php ?> # 3. Comparisons # Without executing the code, tell if the expressions # below will return true or false. <?php if ((strpos("a","abcdefg")) == TRUE) echo "True"; else echo "False"; //True or False? if ((012 / 4) == 3) echo "True"; else echo "False"; //True or False? if (strcasecmp("abc","ABC") == 0) echo "True"; else echo "False"; //True or False? ?> # 4. Bug Checking # The code below is flawed. Fix it so that the code # runs properly without producing any Errors, Warnings # or Notices, and returns the proper value. <?php //Determine how many parts are needed to create a 3D pyramid. function find_3d_pyramid($rows) { //Loop through each row. for ($i = 0; $i < $rows; $i++) { $lastRow++; //Append the latest row to the running total. $total = $total + (pow($lastRow,3)); } //Return the total. return $total; } $i = 3; echo "A pyramid consisting of $i rows will have a total of ".find_3d_pyramid($i)." pieces."; ?> # 5. Quick Examples # Create a small example to complete the task # for each of the following problems. # Create an md5 hash of "Hello World"; # Replace all occurances of "_" with "-" in the string "Welcome_to_the_universe." # Get the current date and time, in the following format, YYYY/MM/DD HH:MM:SS AM/PM # Find the sum, average, and median of the following set of numbers. 1, 3, 5, 6, 7, 9, 10. # Randomly roll a six-sided die 5 times. Store the 5 rolls into an array. <?php ?>

    Read the article

  • {PHP} Fatal error: Using $this when not in object context (Joomla)

    - by Asher
    Hi all, i don't really know php and have hit a brick wall. The problem is that my site is showing the following error... Fatal error: Using $this when not in object context in /hermes/web07/b2350/pow.thefoodie/htdocs/index.php on line 11 This is the begining of my index.php file... // no direct access define( 'YOURBASEPATH', dirname(FILE) ); ? language; ?" lang="language; ?" main_body ul li { behavior: url(baseurl; ?/templates/template ?/css/iepngfix.htc) } baseurl; ?/templates/template ?/js/pngfix.js" baseurl; ?/templates/template ?/css/template_css.css" rel="stylesheet" type="text/css" media="all" / baseurl; ?/templates/template ?/js/fx_styles.js" baseurl; ?/templates/template ?/js/accordion.js" // *************************** // // Template Parameters // // *************************** $h1 = $this-params-get("logo"); $linked_h1 = ($this-params-get("logoLinked", 1) == 0)?"false":"true"; $h1_title = $this-params-get("logoTitle"); $h2_motto = $this-params-get("logoMotto"); // Please do NOT change this unless you know what you doing. $template_path = $this-baseurl.'/templates/'.$this-template; // template path $default_font = "default"; // **************************** ? Any help would be great as i am completely lost.

    Read the article

  • [SOLVED] BitmapFactory.decodeStream returning null when options are set.

    - by Robert Foss
    Hi! I'm having issues with BitmapFactory.decodeStream(inputStream). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps. What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream. Here httpIM:NOT//nornalbion.SPAMcom/blog/?p=143 httpIM:NOT//kfb-android.blogspot.SPAMcom/2009/04/image-processing-in-android.html WORKS JUST FINE URL url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); DOESNT WORK InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); InputStream is = connection.getInputStream(); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH); if(options.outHeight * options.outWidth * 2 >= 200*100*2){ // Load, scaling to smallest power of 2 that'll get it <= desired dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int)Math.pow(2d, Math.floor( Math.log(sampleSize)/Math.log(2d))); } // Do the actual decoding options.inJustDecodeBounds = false; Bitmap img = BitmapFactory.decodeStream(is, null, options);

    Read the article

  • Detect blow in Mic and do something {iPhone SDK}

    - by Momeks
    Hi , i found this tutorial , and it's good , but doesn't work for me ! here is the code : - (void)listenForBlow:(NSTimer *)timer { [recorder updateMeters]; const double ALPHA = 0.05; double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0])); lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults; if (lowPassResults > 0.95) NSLog(@"Mic blow detected"); //change the background color e.g ! } in the console show me the nslog reseult like this (without any bowling !): 2010-04-11 23:32:27.935 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:27.965 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:27.995 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.026 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.055 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.086 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.115 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.145 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.175 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.205 MicBlow[2358:207] Mic blow detected 2010-04-11 23:32:28.236 MicBlow[2358:207] Mic blow detected i change this value : if (lowPassResults < 0.95) to if (lowPassResults > 0.95) so it seems work ! but doesn't chage anything , again if i put the background changing code the , my code change background but without any bowling !! what's the problem ?

    Read the article

  • FLEX/BISON : Why my rule is not regonized ?

    - by Natim
    Hi, I am trying to do a little exercice in FLEX and BISON. Here is the code I wrote : calc_pol.y %{ #define YYSTYPE double #include "calc_pol.tab.h" #include <math.h> #include <stdlib.h> %} %start line %token NOMBRE %token FIN %% line: exp '\n' { printf("\t%.2lf\n", $1); }; exp: exp exp '+' { $$ = $1 + $2 ;} | exp exp '-' { $$ = $1 - $2 ;} | exp exp '*' { $$ = $1 * $2 ;} | exp exp '/' { $$ = $1 / $2 ;} | exp exp '^' { $$ = pow($1, $2) ;} | NOMBRE; %% calc_pol.l %{ #include "calc_pol.tab.h" #include <stdlib.h> #include <stdio.h> extern YYSTYPE yylval; %} blancs [ \t]+ chiffre [0-9] entier [+-]?[1-9][0-9]* | 0 reel {entier}('.'{entier})? %% {blancs} {reel} { yylval = atof(yytext); return NOMBRE; } \n { return FIN; } . { return yytext[0]; } %% Makefile all: calc_pol.tab.c lex.yy.c gcc -o calc_pol $< -ly -lfl -lm calc_pol.tab.c: calc_pol.y bison -d calc_pol.y lex.yy.c: calc_pol.l flex calc_pol.l Do you have any idea of what's wrong ? Thanks Edited: The error message is flex calc_pol.l: calc_pol.l:18: règle non reconnue Line 18 is the line beginning with {reel}, and the error message translates to English as "unrecognized rule".

    Read the article

  • BitmapFactory.decodeStream returning null when options are set.

    - by Robert Foss
    Hi! I'm having issues with BitmapFactory.decodeStream(). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps. What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream. Here httpIM:NOT//nornalbion.SPAMcom/blog/?p=143 httpIM:NOT//kfb-android.blogspot.SPAMcom/2009/04/image-processing-in-android.html WORKS JUST FINE InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); DOESNT WORK InputStream is = connection.getInputStream(); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH); if(options.outHeight * options.outWidth * 2 >= 200*100*2){ // Load, scaling to smallest power of 2 that'll get it <= desired dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int)Math.pow(2d, Math.floor( Math.log(sampleSize)/Math.log(2d))); System.out.println("Samplesize: " + options.inSampleSize); } // Do the actual decoding options.inJustDecodeBounds = false; //options.inTempStorage = new byte[IMG_BUFFER_LEN]; Bitmap img = BitmapFactory.decodeStream(is, null, options);

    Read the article

  • How to make Python Extensions for Windows for absolute beginners

    - by JR
    Hello: I've been looking around the internet trying to find a good step by step guide to extend Python in Windows, and I haven't been able to find something for my skill level. let's say you have some c code that looks like this: #include <stdio.h> #include <math.h> double valuex(float value, double rate, double timex) { float value; double rate, timex; return value / double pow ((1 + rate), (timex)); } and you want to turn that into a Python 3 module for use on a windows (64bit if that makes a difference) system. How would you go about doing that? I've looked up SWIG and Pyrex and in both circumstances they seem geared towards the unix user. With Pyrex I am not sure if it works with Python 3. I'm just trying to learn the basics of programing, using some practical examples. Lastly, if there is a good book that someone can recommend for learning to extend, I would greatly appreciate it. Thank you.

    Read the article

  • Static Data Structures on Embedded Devices (Android in particular)

    - by Mark
    I've started working on some Android applications and have a question regarding how people normally deal with situations where you have a static data set and have an application where that data is needed in memory as one of the standard java collections or as an array. In my current specific issue i have a spreadsheet with some pre-calculated data. It consists of ~100 rows and 3 columns. 1 Column is a string, 1 column is a float, 1 column is an integer. I need access to this data as an array in java. It seems like i could: 1) Encode in XML - This would be cpu intensive to decode in my experience. 2) build into SQLite database - seems like a lot of overhead for static access to data i only need array style access to in ram. 3) Build into binary blob and read in. (never done this in java, i miss void *) 4) Build a python script to take the CSV version of my data and spit out a java function that adds the values to my desired structure with hard coded values. 5) Store a string array via androids resource mechanism and compute the other 2 columns on application load. In my case the computation would require a lot of calls to Math.log, Math.pow and Math.floor which i'd rather not have to do for load time and battery usage reasons. I mostly work in low power embedded applications in C and as such #4 is what i'm used to doing in these situations. It just seems like it should be far easier to gain access to static data structures in java/android. Perhaps I'm just being too battery usage conscious and in my single case i imagine the answer is that it doesn't matter much, but if every application took that stance it could begin to matter. What approaches do people usually take in this situation? Anything I missed?

    Read the article

  • EF 4.0 : Save Changes Retry Logic

    - by BGR
    Hi, I would like to implement an application wide retry system for all entity SaveChanges method calls. Technologies: Entity framework 4.0 .Net 4.0 namespace Sample.Data.Store.Entities { public partial class StoreDB { public override int SaveChanges(System.Data.Objects.SaveOptions options) { for (Int32 attempt = 1; ; ) { try { return base.SaveChanges(options); } catch (SqlException sqlException) { // Increment Trys attempt++; // Find Maximum Trys Int32 maxRetryCount = 5; // Throw Error if we have reach the maximum number of retries if (attempt == maxRetryCount) throw; // Determine if we should retry or abort. if (!RetryLitmus(sqlException)) throw; else Thread.Sleep(ConnectionRetryWaitSeconds(attempt)); } } } static Int32 ConnectionRetryWaitSeconds(Int32 attempt) { Int32 connectionRetryWaitSeconds = 2000; // Backoff Throttling connectionRetryWaitSeconds = connectionRetryWaitSeconds * (Int32)Math.Pow(2, attempt); return (connectionRetryWaitSeconds); } /// <summary> /// Determine from the exception if the execution /// of the connection should Be attempted again /// </summary> /// <param name="exception">Generic Exception</param> /// <returns>True if a a retry is needed, false if not</returns> static Boolean RetryLitmus(SqlException sqlException) { switch (sqlException.Number) { // The service has encountered an error // processing your request. Please try again. // Error code %d. case 40197: // The service is currently busy. Retry // the request after 10 seconds. Code: %d. case 40501: //A transport-level error has occurred when // receiving results from the server. (provider: // TCP Provider, error: 0 - An established connection // was aborted by the software in your host machine.) case 10053: return (true); } return (false); } } } The problem: How can I run the StoreDB.SaveChanges to retry on a new DB context after an error occured? Something simular to Detach/Attach might come in handy. Thanks in advance! Bart

    Read the article

  • sqrt(int_value + 0.0) -- Does it have a purpose?

    - by Earlz
    Hello, while doing some homework in my very strange C++ book, which I've been told before to throw away, had a very peculiar code segment. I know homework stuff always throws in extra "mystery" to try to confuse you like indenting 2 lines after a single-statement for-loop. But this one I'm confused on because it seems to serve some real-purpose. basically it is like this: int counter=10; ... if(pow(floor(sqrt(counter+0.0)),2) == counter) ... I'm interested in this part especially: sqrt(counter+0.0) Is there some purpose to the +0.0? Is this the poormans way of doing a static cast to a double? Does this avoid some compiler warning on some compiler I do not use? The entire program printed the exact same thing and compiled without warnings on g++ whenever I left out the +0.0 part. Maybe I'm not using a weird enough compiler? Edit: Also, does gcc just break standard and not make an error for Ambiguous reference since sqrt can take 3 different types of parameters? [earlz@EarlzBeta-~/projects/homework1] $ cat calc.cpp #include <cmath> int main(){ int counter=0; sqrt(counter); } [earlz@EarlzBeta-~/projects/homework1] $ g++ calc.cpp /usr/lib/libstdc++.so.47.0: warning: strcpy() is almost always misused, please use strlcpy() /usr/lib/libstdc++.so.47.0: warning: strcat() is almost always misused, please use strlcat() [earlz@EarlzBeta-~/projects/homework1] $

    Read the article

  • Pass data from one form to another on a seperate page

    - by Micanio
    I am building a price/distance calculator with Google Maps API and am trying to pass the info from the calculator to a booking form on a separate page. My first form has 2 submit buttons - one to make the calculation, and one to submit the relevant data to the booking form. I'm stuck trying to make the 2nd button work. Once the API calculation has been made, I get 4 values - From, To, Cost, Distance. I am trying to pass the From, To and Cost values into my booking form by clicking the second button. But I can;t seem to get it to work. I've tried POST and GET but I think I may have been doing something wrong with both. Any help is appreciated. Code for API form: <script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAwCUxKrPl8_9WadET5dc4KxTqOwVK5HCwTKtW27PjzpqojXnJORQ2kUsdCksByD4hzcGXiOxvn6C4cw&sensor=true"></script> <script type="text/javascript"> var geocoder = null; var location1 = null; var location2 = null; var gDir = null; var directions = null; var total = 0; function roundNumber(num, dec) { var result = Math.floor(num*Math.pow(10 ,dec))/Math.pow(10,dec); return result; } function from(form) { address1=form.start.options[form.start.selectedIndex].value form.address1.value=address1 form.address1.focus() } function to(form) { address2=form.end.options[form.end.selectedIndex].value form.address2.value=address2 form.address2.focus() } function initialize() { var map = new GMap2(document.getElementById("map_canvas")); map.setCenter(new GLatLng(54.019066,-1.381531),9); map.setMapType(G_NORMAL_MAP); geocoder = new GClientGeocoder(); gDir = new GDirections(map); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; var miles = drivingDistanceMiles.toFixed(0); //var cost = (((miles - 1) * 1.9) + 3.6).toFixed(2); var meters = gDir.getDistance().meters.toFixed(1); if(miles < 70){ var cost = miles *1.75; } if(miles >70){ var cost = miles *1.2; } document.getElementById('from').innerHTML = '<strong>From: </strong>' + location1.address; document.getElementById('to').innerHTML = '<strong>To: </strong>' + location2.address; document.getElementById('cost').innerHTML = '<span class="fare"><strong>Estimated Taxi FARE:</strong>' + ' £' + cost.toFixed(2) + '</span>'; document.getElementById('miles').innerHTML = '<strong>Distance: </strong>' + miles + ' Miles'; }); } function showLocation() // start of possible values for address not recognized on google search // values for address1 { if (document.forms[0].address1.value == "heathrow" || document.forms[0].address1.value == "Heathrow" || document.forms[0].address1.value == "heathrow airport" || document.forms[0].address1.value == "Heathrow Airport" || document.forms[0].address1.value == "London Heathrow" || document.forms[0].address1.value =="london heathrow" ) { (document.forms[0].address1.value = "Heathrow Airport"); } if (document.forms[0].address2.value == "heathrow" || document.forms[0].address2.value == "Heathrow" || document.forms[0].address2.value == "heathrow airport" || document.forms[0].address2.value == "Heathrow Airport" || document.forms[0].address2.value == "London Heathrow" || document.forms[0].address2.value =="london heathrow" ) { (document.forms[0].address2.value = "Heathrow Airport"); } geocoder.getLocations(document.forms[0].address1.value + document.forms[0].uk.value || document.forms[0].start.value + document.forms[0].uk.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to find the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(document.forms[0].address2.value + document.forms[0].uk.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to find the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); } </script> <style> #quote { font-family: Georgia, "Times New Roman", Times, serif; } </style> </head> <body style="background-color: rgb(255, 255, 255);" onUnload="GUnload()" onLoad="initialize()"> <div id="sidebar"> <!--MAPS--> <div id="calc_top"></div> <div id="calc_body"> <div id="calc_inside"> <span style="font-size: 16px; font-weight: bold;">Get A Quote Now</span> <p class="disclaimer">Fares can be calculated using either Area, Exact Address or Postcode, when entering address please include both road name and area i.e. <em>Harrogate Road, Ripon</em>. You can also select a pickup point and destination from the dropdown boxes. </p> <form onSubmit="showLocation(); return false;" action="#" id="booking_form"> <p> <select onChange="from(this.form)" name="start"> <option selected="selected">Select a Pickup Point</option> <option value="Leeds Bradford Airport">Leeds Bradford Airport</option> <option value="Manchester Airport">Manchester Airport</option> <option value="Teesside International Airport">Teeside Airport</option> <option value="Liverpool John Lennon Airport">Liverpool Airport</option> <option value="East Midlands Airport">East Midlands Airport</option> <option value="Heathrow International Airport">Heathrow Airport</option> <option value="Gatwick Airport">Gatwick Airport</option> <option value="Stanstead Airport">Stanstead Airport</option> <option value="Luton International Airport">Luton Airport</option> </select> </p> <p> <input type="text" value="From" name="address1"><br> <p> <select onChange="to(this.form)" name="end"> <option selected="selected">Select a Destination</option> <option value="Leeds Bradford Airport">Leeds Bradford Airport</option> <option value="Manchester Airport">Manchester Airport</option> <option value="Teesside International Airport">Teeside Airport</option> <option value="Liverpool John Lennon Airport">Liverpool Airport</option> <option value="East Midlands Airport">East Midlands Airport</option> <option value="Heathrow International Airport">Heathrow Airport</option> <option value="Gatwick Airport">Gatwick Airport</option> <option value="Stanstead Airport">Stanstead Airport</option> <option value="Luton International Airport">Luton Airport</option> </select> </p> <input type="text" value="To" name="address2"><br> <input type="hidden" value=" uk" name="uk"> <br> <input type="submit" value="Get Quote"> <input type="button" value="Reset" onClick="resetpage()"><br /><br /> <input type="submit" id="CBSubmit" value="Confirm and Book" action=""/> </p> </form> <p id="from"><strong>From:</strong></p> <p id="to"><strong>To:</strong></p> <p id="miles"><strong>Distance: </strong></p> <p id="cost"><span class="fare"><strong>Estimated Taxi FARE:</strong></span></p> <p id="results"></p> <div class="style4" style="width: 500px; height: 500px; position: relative; background-color: rgb(229, 227, 223);" id="map_canvas"></div> </div> </div> Code for Booking Form: <form method="post" action="contactengine.php" id="contact_form"> <p> <label for="Name" id="Name">Name:</label> <input type="text" name="Name" /> <label for="Email" id="Email">Email:</label> <input type="text" name="Email" /> <label for="tel" id="tel">Tel No:</label> <input type="text" name="tel" /><br /><br /> <label for="from" id="from">Pickup Point:</label> <input type="text" name="from" value="" /><br /><br /> <label for="to" id="to">Destination:</label> <input type="text" name="to" value=""/><br /> <label for="passengers" id="passengers">No. of passengers</label> <input type="text" name="passengers" /><br /><br /> <label for="quote" id="quote">Price of journey:</label> <input type="text" name="quote" value="" /><br /><br /> <label for="Message" id="Message">Any other info:</label> <textarea name="Message" rows="20" cols="40"></textarea> <br /> Are you an account holder?<br /> <label for="account" id="yes" /> Yes:</label> <input type="radio" class="radio" value="yes" name="account"> <label for="account" id="yes" /> No:</label> <input type="radio" class="radio" value="no" name="account"> </p> <small>Non-account holders will have to pay a £5 booking fee when confirming thier booking</small> <input type="submit" name="submit" value="Submit" class="submit-button" /> </p> </form> Thanks in advance

    Read the article

  • Why does Clojure hang after hacing performed my calculations?

    - by Thomas
    Hi all, I'm experimenting with filtering through elements in parallel. For each element, I need to perform a distance calculation to see if it is close enough to a target point. Never mind that data structures already exist for doing this, I'm just doing initial experiments for now. Anyway, I wanted to run some very basic experiments where I generate random vectors and filter them. Here's my implementation that does all of this (defn pfilter [pred coll] (map second (filter first (pmap (fn [item] [(pred item) item]) coll)))) (defn random-n-vector [n] (take n (repeatedly rand))) (defn distance [u v] (Math/sqrt (reduce + (map #(Math/pow (- %1 %2) 2) u v)))) (defn -main [& args] (let [[n-str vectors-str threshold-str] args n (Integer/parseInt n-str) vectors (Integer/parseInt vectors-str) threshold (Double/parseDouble threshold-str) random-vector (partial random-n-vector n) u (random-vector)] (time (println n vectors (count (pfilter (fn [v] (< (distance u v) threshold)) (take vectors (repeatedly random-vector)))))))) The code executes and returns what I expect, that is the parameter n (length of vectors), vectors (the number of vectors) and the number of vectors that are closer than a threshold to the target vector. What I don't understand is why the programs hangs for an additional minute before terminating. Here is the output of a run which demonstrates the error $ time lein run 10 100000 1.0 [null] 10 100000 12283 [null] "Elapsed time: 3300.856 msecs" real 1m6.336s user 0m7.204s sys 0m1.495s Any comments on how to filter in parallel in general are also more than welcome, as I haven't yet confirmed that pfilter actually works.

    Read the article

  • C# Why can't I find Sum() of this HashSet. says "Arithmetic operation resulted in an overflow."

    - by user2332665
    I was trying to solve this problem projecteuler,problem125 this is my solution in python(just for understanding the logic) import math lim=10**8 found=set() for start in xrange(1,int(math.sqrt(lim))): sos = start*start for i in xrange(start+1,int(math.sqrt(lim))): sos += (i*i) if sos >= lim: break s=str(int(sos)) if s==s[::-1]: found.add(sos) print sum(found) the same code I wrote in C# is as follows using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { public static bool isPalindrome(string s) { string temp = ""; for (int i=s.Length-1;i>=0;i-=1){temp+=s[i];} return (temp == s); } static void Main(string[] args) { int lim = Convert.ToInt32(Math.Pow(10,8)); var found = new HashSet<int>(); for (int start = 1; start < Math.Sqrt(lim); start += 1) { int s = start *start; for (int i = start + 1; start < Math.Sqrt(lim); i += 1) { s += i * i; if (s > lim) { break; } if (isPalindrome(s.ToString())) { found.Add(s); } } } Console.WriteLine(found.Sum()); } } } the code debugs fine until it gives an exception at Console.WriteLine(found.Sum()); (line31). Why can't I find Sum() of the set found

    Read the article

  • Jquery: Create hidden attributes? I need to reduce tag bulkyness.

    - by Dan
    I'm sure we've all done this before: <a id="232" rel="link_to_user" name="user_details" class="list hoverable clickable selectable"> USER #232 </a> But then we say, oh my, I need more ways to store tracking info about this div! <a id="232-343-22" rel="link_to_user:fotomeshed" name="user_details" class="groupcolor-45 elements-698 list hoverable clickable selectable"> User: John Doe </a> And the sickness keeps growing. We just keep on packing it inside that poor little element and it's attributes. All so we can keep track of who it is. So with my limited knowledge of JS, someone please tell me how to do something like this: <a id="33">USER #33</a> $(#33).attr({title:'User Record','username':'john', 'group_color':'green', 'element_num':78}); So here we just added what I would call invisible attributes, because we just played God and made those attributes up on the fly like it was no problem. The cool part is that these would be kept in their own little object somewhere in variable land. NOT in the tag itself. Then later on, in a code nested far far away, be able to say, oh, i wonder what group_color John is... user_group_color = $(table).find(a['username':'john']).attr('group_color'); THEN BAM!!!! POW!!!! alert(user_group_color + " is a bitchin color!"); You get to know his group color... all without adding a bunch of bloated element tracking nonsense into our tags. So does this sort of thing exist? If not, how do I make it?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11  | Next Page >