Search Results

Search found 1803 results on 73 pages for 'pi calculation'.

Page 62/73 | < Previous Page | 58 59 60 61 62 63 64 65 66 67 68 69  | Next Page >

  • Remove redundant SQL code

    - by Dave Jarvis
    Code The following code calculates the slope and intercept for a linear regression against a slathering of data. It then applies the equation y = mx + b against the same result set to calculate the value of the regression line for each row. Can the two separate sub-selects be joined so that the data and its slope/intercept are calculated without executing the data gathering part of the query twice? SELECT AVG(D.AMOUNT) as AMOUNT, Y.YEAR * ymxb.SLOPE + ymxb.INTERCEPT as REGRESSION_LINE, Y.YEAR as YEAR, MAKEDATE(Y.YEAR,1) as AMOUNT_DATE FROM CITY C, STATION S, YEAR_REF Y, MONTH_REF M, DAILY D, (SELECT ((avg(t.AMOUNT * t.YEAR)) - avg(t.AMOUNT) * avg(t.YEAR)) / (stddev( t.AMOUNT ) * stddev( t.YEAR )) as CORRELATION, ((sum(t.YEAR) * sum(t.AMOUNT)) - (count(1) * sum(t.YEAR * t.AMOUNT))) / (power(sum(t.YEAR), 2) - count(1) * sum(power(t.YEAR, 2))) as SLOPE, ((sum( t.YEAR ) * sum( t.YEAR * t.AMOUNT )) - (sum( t.AMOUNT ) * sum(power(t.YEAR, 2)))) / (power(sum(t.YEAR), 2) - count(1) * sum(power(t.YEAR, 2))) as INTERCEPT FROM ( SELECT AVG(D.AMOUNT) as AMOUNT, Y.YEAR as YEAR, MAKEDATE(Y.YEAR,1) as AMOUNT_DATE FROM CITY C, STATION S, YEAR_REF Y, MONTH_REF M, DAILY D WHERE $X{ IN, C.ID, CityCode } AND SQRT( POW( C.LATITUDE - S.LATITUDE, 2 ) + POW( C.LONGITUDE - S.LONGITUDE, 2 ) ) < $P{Radius} AND S.STATION_DISTRICT_ID = Y.STATION_DISTRICT_ID AND Y.YEAR BETWEEN 1900 AND 2009 AND M.YEAR_REF_ID = Y.ID AND M.CATEGORY_ID = $P{CategoryCode} AND M.ID = D.MONTH_REF_ID AND D.DAILY_FLAG_ID <> 'M' GROUP BY Y.YEAR ) t ) ymxb WHERE $X{ IN, C.ID, CityCode } AND SQRT( POW( C.LATITUDE - S.LATITUDE, 2 ) + POW( C.LONGITUDE - S.LONGITUDE, 2 ) ) < $P{Radius} AND S.STATION_DISTRICT_ID = Y.STATION_DISTRICT_ID AND Y.YEAR BETWEEN 1900 AND 2009 AND M.YEAR_REF_ID = Y.ID AND M.CATEGORY_ID = $P{CategoryCode} AND M.ID = D.MONTH_REF_ID AND D.DAILY_FLAG_ID <> 'M' GROUP BY Y.YEAR Question How do I execute the duplicate bits only once per query, instead of twice? The duplicate bit is the WHERE clause: $X{ IN, C.ID, CityCode } AND SQRT( POW( C.LATITUDE - S.LATITUDE, 2 ) + POW( C.LONGITUDE - S.LONGITUDE, 2 ) ) < $P{Radius} AND S.STATION_DISTRICT_ID = Y.STATION_DISTRICT_ID AND Y.YEAR BETWEEN 1900 AND 2009 AND M.YEAR_REF_ID = Y.ID AND M.CATEGORY_ID = $P{CategoryCode} AND M.ID = D.MONTH_REF_ID AND D.DAILY_FLAG_ID <> 'M' Related http://stackoverflow.com/questions/1595659/how-to-eliminate-duplicate-calculation-in-sql Thank you!

    Read the article

  • What function does .NET NPV() use? Doesn't match manual calculations

    - by Matthew PK
    I am using the NPV() function in VB.NET to get NPV for a set of cash flows. However, the result of NPV() is not consistent with my results performing the calculation manually (nor the Investopedia NPV calc... which matches my manual results) My correct manual results and the NPV() results are close, within 5%.. but not the same... Manually, using the NPV formula: NPV = C0 + C1/(1+r)^1 + C2/(1+r)^2 + C3/(1+r)^3 + .... + Cn/(1+r)^n The manual result is stored in RunningTotal With rate r = 0.04 and period n = 10 Here is my relevant code: EDIT: Do I have OBOB somewhere? YearCashOutFlow = CDbl(TxtAnnualCashOut.Text) YearCashInFlow = CDbl(TxtTotalCostSave.Text) YearCount = 1 PAmount = -1 * (CDbl(TxtPartsCost.Text) + CDbl(TxtInstallCost.Text)) RunningTotal = PAmount YearNPValue = PAmount AnnualRateIncrease = CDbl(TxtUtilRateInc.Text) While AnnualRateIncrease > 1 AnnualRateIncrease = AnnualRateIncrease / 100 End While AnnualRateIncrease = 1 + AnnualRateIncrease ' ZERO YEAR ENTRIES ListBoxNPV.Items.Add(Format(PAmount, "currency")) ListBoxCostSave.Items.Add("$0.00") ListBoxIRR.Items.Add("-100") ListBoxNPVCum.Items.Add(Format(PAmount, "currency")) CashFlows(0) = PAmount '''' Do While YearCount <= CInt(TxtLifeOfProject.Text) ReDim Preserve CashFlows(YearCount) CashFlows(YearCount) = Math.Round(YearCashInFlow - YearCashOutFlow, 2) If CashFlows(YearCount) > 0 Then OnePos = True YearNPValue = CashFlows(YearCount) / (1 + DiscountRate) ^ YearCount RunningTotal = RunningTotal + YearNPValue ListBoxNPVCum.Items.Add(Format(Math.Round(RunningTotal, 2), "currency")) ListBoxCostSave.Items.Add(Format(YearCashInFlow, "currency")) If OnePos Then ListBoxIRR.Items.Add((IRR(CashFlows, 0.1)).ToString) ListBoxNPV.Items.Add(Format(NPV(DiscountRate, CashFlows), "currency")) Else ListBoxIRR.Items.Add("-100") ListBoxNPV.Items.Add(Format(RunningTotal, "currency")) End If YearCount = YearCount + 1 YearCashInFlow = AnnualRateIncrease * YearCashInFlow Loop

    Read the article

  • Populate a column as a result of performing math on two columns in a jqGrid.

    - by HacksawOnRye
    Background: Our company selected a workflow tool that has some "interersting" UI restrictions. jqGrid has been identified as one of best ways to overcome these restrictions. Consequently, the answers to this question need to be restricted to functionlity available within the jqGrid space. It pains me to pose this question and I know you will tempted to go down a million other paths - most that we have already traveled before. :( Question: Can jqGrid populate a column as a result of performing math on two other columns. The source of those two columns is in our control so we can "guarantee" that numeric data will be returned. Also, the result is something that we simplay want to display on demand but not store yet. On the example below, is there a function that allow the 'total' column to be populated from the following calculation: 'amount' * 'tax' Example jqGrid javascript: jQuery("#list3").jqGrid({ url:'server.php?q=2', datatype: "json", colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'], colModel:[ {name:'id',index:'id', width:60, sorttype:"int"}, {name:'invdate',index:'invdate', width:90, sorttype:"date"}, {name:'name',index:'name', width:100}, {name:'amount',index:'amount', width:80, align:"right",sorttype:"float"}, {name:'tax',index:'tax', width:80, align:"right",sorttype:"float"}, {name:'total',index:'total', width:80,align:"right",sorttype:"float"}, {name:'note',index:'note', width:150, sortable:false} ], rowNum:20, rowList:[10,20,30], pager: '#pager3', sortname: 'id', viewrecords: true, sortorder: "desc", loadonce: true, caption: "Load Once Example" });

    Read the article

  • Extjs 4.1 How to call controller action method from form

    - by Omar Faruq
    Extjs 4.1 How to call controller action method from form which is already use in a button action but i want this method reuse from a form field but do not how i can do? // here is my controller code init: function() { this.control({ 'itemsgrid': { removeitem: this.removeUser }, 'salewindow button[action=resetAll]': { click: this.resertform }, 'salewindow button[action=saveOrder]' : { click : this.onsaveOrder }, 'salewindow button[action=PDF]' : { click : this. pdfreport } }); }, resertform : function(button){ var store = Ext.data.StoreManager.get('Items'); store.destroy(); var vatstore = Ext.data.StoreManager.get('Vats'); vatstore.reload(); var rebatestore = Ext.data.StoreManager.get('Rebates'); rebatestore.reload(); Ext.getCmp('calculation-form').getForm().reset(); Ext.getCmp('itemform2').getForm().reset(); Ext.getCmp('itemsgrid').subtotalquantity(p=0); store.reload(); var co=store.getCount(); console.log(co); Ext.getCmp('customerID').setValue('0'); var a = Ext.getCmp('customerID').getValue(); Ext.getCmp('itemform2').customerinfo(a); } //and here is my from field listener { xtype : 'textfield', name : 'BranchId', fieldLabel : 'Branch Id', allowNegative : false, id : 'branchid', value : '1', onBlur: function(){ restoreItem();// i want call this method from here whis is stay in controller } }

    Read the article

  • prolog - infinite rule

    - by Tom
    I have the next rules % Signature: natural_number(N)/1 % Purpose: N is a natural number. natural_number(0). natural_number(s(X)) :- natural_number(X) ackermann(0, N, s(N)). //rule 1 ackermann(s(M),0,Result):- ackermann(M,s(0),Result). //rule 2 ackermann(s(M),s(N),Result):-ackermann(M,Result1,Result),ackermann(s(M),N,Result1). //rule 3 The query is: ackermann (M,N,s(s(0))). Now, as I understood, In the third calculation, we got an infinite search (failture branch). I check it, and I got a finite search (failture branch). I'll explain: In the first, we got a substitue of M=0, N=s(0) (rule 1 - succsess!). In the second, we got a substitue of M=s(0),N=0 (rule 2 - sucsses!). But what now? I try to match M=s(s(0)) N=0, But it got a finite search - failture branch. Why the comipler doesn't write me "fail". Thank you.

    Read the article

  • Thread management advice - Is TPL a good idea?

    - by Ian
    I'm hoping to get some advice on the use of thread managment and hopefully the task parallel library, because I'm not sure I've been going down the correct route. Probably best is that I give an outline of what I'm trying to do. Given a Problem I need to generate a Solution using a heuristic based algorithm. I start of by calculating a base solution, this operation I don't think can be parallelised so we don't need to worry about. Once the inital solution has been generated, I want to trigger n threads, which attempt to find a better solution. These threads need to do a couple of things: They need to be initalized with a different 'optimization metric'. In other words they are attempting to optimize different things, with a precedence level set within code. This means they all run slightly different calculation engines. I'm not sure if I can do this with the TPL.. If one of the threads finds a better solution that the currently best known solution (which needs to be shared across all threads) then it needs to update the best solution, and force a number of other threads to restart (again this depends on precedence levels of the optimization metrics). I may also wish to combine certain calculations across threads (e.g. keep a union of probabilities for a certain approach to the problem). This is probably more optional though. The whole system needs to be thread safe obviously and I want it to be running as fast as possible. I tried quite an implementation that involved managing my own threads and shutting them down etc, but it started getting quite complicated, and I'm now wondering if the TPL might be better. I'm wondering if anyone can offer any general guidance? Thanks...

    Read the article

  • how to use shared variable using stored procedure in crystal reports

    - by sonia
    i have a parent report and it contains a two sub report. * subreport: item which get all fields from store procedure named spGetReportItem. like ItemName ItemQuantity TotalItemCost ab 4 45 dd 6 98 *subreport: Labour which get all fields from store procedure named spGetReportLabour. like labourName labourQuantity TotalLabourCost ab 44 455 dd 63 986 i want to find the total of totalitemcost and total of totallabourcost and then want grandtotal of totalitemcost and totallabourcost. i have seen many examples on internet in which shared variable is used in the formula bt the problem is that they have used the table but i m fetching data from stored procedure. so how can i access the stored procedure fields for calculation. like i have seen that many have used: shared numbervar total:=sum({tablename.ColumnName}); but i have used stored procedure instead of table so how could i find total of field that resultset returns from stored procedure.. plz give me answer as soon as possible.. i need it urgently. thanks..

    Read the article

  • OnClickListener error: Source not found

    - by fordays
    Hi, I'm brand new to Android development and right now I am building a simple calculator for healthcare workers. My program implements the OnClickListener class, but every time I click on the button to initiate the calculation, I get an error saying the "Source is not Found". Here is the code: public class KidneyeGFR extends Activity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Calculate = (Button)this.findViewById(R.id.Calculate); Calculate.setOnClickListener(this); } public void onClick(View v) { if (Female.isChecked()) { gender = 0.742; } else { gender = 1.0; } if (African.isChecked()) { race = 1.212; } else { race = 1.0; } calculateBone(); } protected void calculateBone() { int age = Integer.parseInt(EditAge.getText().toString()); double serum = Double.parseDouble(EditSerum.getText().toString()); finalgfr = BONECONST * Math.pow(serum, -1.154) * Math.pow(age, -0.203) * gender * race; BONEtext.setText(Double.toString(finalbone)); }

    Read the article

  • Calculate the year for ending month/day?

    - by Dave Jarvis
    Given: Start Year Start Month & Start Day End Month & End Day What SQL statement results in TRUE if a date lands between the Start and End days? 1st example: Start Date = 11-22 End Date = 01-17 Start Year = 2009 Specific Date = 2010-01-14 TRUE 2nd example: Start Date = 11-22 End Date = 11-16 Start Year = 2009 Specific Date = 2010-11-20 FALSE 3rd example: Start Date = 02-25 End Date = 03-19 Start Year = 2004 Specific Date = 2004-02-29 TRUE I was thinking of using the MySQL functions datediff and sign plus a CASE condition to determine whether the year wraps, but it seems rather expensive. Am looking for a simple, efficient calculation. Update 1 The problem is the end date cannot simply use the year. The year must be increased if the end month/day combination happens before the start date. The start date is easy: Start Date = date( concat_ws( '-', year, Start Month, Start Day ) ) The end date is not so simple. Update 2 Here is what I was thinking about for obtaining the end year: end_year = case sign( diff( date( concat_ws( year, start_month, start_day ) ), date( concat_ws( year, end_month, end_day ) ) ) ) when -1 then Start_Year + 1 else Start_Year end case Then wrap that expression (once syntactically correct) inside of another date, followed by BETWEEN statement. Update 3 To clear up some confusion: there is no end year. The end year must be calculated. Thank you!

    Read the article

  • Learning Java, how to type text on canvas?

    - by Voley
    I'm reading a book by Eric Roberts - Art and science of java and it got an excersise that I can't figure out - You have to make calendar, with GRect's, 7 by 6, that goes ok, the code part is easy, but also you have to type the numbers of the date on those rectangles, and it's kinda hard for me, there is nothing about it in the book. I tried using GLabel thing, but here arises the problem that I need to work on those numbers, and it says "can't convert from int to string and vice versa". GLabel (string, posX, posY) - it is not accepting int as a parameter, only string, I even tried typecasting, still not working. For example I want to make a loop int currentDate = 1; while (currentDate < 31) { add(new Glabel(currentDate, 100, 100); currentDate++; This code is saying that no man, can't convert int to string. If i try changing currentDate to string, it works, but I got a problem with calculation, as I can't manipulate with number in string, it doesn't even allow to typecast it into int. How can I fix it? Maybe there is another class or method to type the text over those rectangles? I know about println but it doen't have any x or y coordinates, so I can't work with it. And I think it's only for console programs.

    Read the article

  • Zend Framework - counting rows in select clause ?

    - by moogeek
    Hello! I'm investigating Zend Framework and currently stucked in counting resulting rows of sql query... Every method I try (from documentation and some blogposts and tutorials) returns an error (like Call to undefined function) or simply gives the incorrect value. I've tried this: $checkquery = $db->select() ->from('users', 'COUNT(*)') ->where('login = ?', $login) ->where('password = ?', $password) ->query(); $checkrequest=fetchRow($checkquery)->num; ...then this one: $checkquery = $db->select() ->from('users', '*') ->where('login = ?', $login) ->where('password = ?', $password) ->query(); $checkrequest=count($checkquery->fetchAll()); and even: $checkquery = $db->select() ->from('users', '*') ->where('login = ?', $login) ->where('password = ?', $password) ->query(); $checkrequest=$checkquery->fetchAll()->num; Also rowCount() and count(fetchRow()) and count(fetchAll()->toArray()). But always I got an error message or duplicate inserts in db in further insert function. So what is the correct way to do the resulting row calculation in select clause in Zend Framework 1.9 (I use this one) ?

    Read the article

  • shell script filter du and find by a string inside a file in a subfolder

    - by Jason
    I have the following command that I run on cygwin: find /cygdrive/d/tmp/* -maxdepth 0 -mtime -150 -type d | xargs du --max-depth=0 > foldersizesreport.csv I intended to do the following with this command: for each folder under /d/tmp/ that was modified in last 150 days, check its total size including files within it and report it to file foldersizesreport.csv however that is now not good enough for me, as it turns out inside each /d/tmp/subfolder1/somefile.properties /d/tmp/subfolder2/somefile.properties /d/tmp/subfolder3/somefile.properties /d/tmp/subfolder4/somefile.properties so as you see inside each subfolderX there is a file named somefile.properties inside it there is a property SOMEPROPKEY=3808612800100 (among other properties) this is the time in millisecond, i need to change the command so that instead of -mtime -150 it will include in the whole calculation only subfolderX that has a file inside them somefile.properties where the SOMEPROPKEY=3808612800100 is the time in millisecond in future, if the value SOMEPROPKEY=23948948 is in past then dont at all include the folder in the foldersizesreport.csv because its not relevant to me. so the result report should be looking like: /d/tmp/,subfolder1,<itssizein KB> /d/tmp/,subfolder2,<itssizein KB> and if subfolder3 had a SOMEPROPKEY=34243234 (time in ms in past) then it would not be in that csv file. so basically I'm looking for: find /cygdrive/d/tmp/* -maxdepth 0 -mtime -150 -type d | <only subfolders that have in them property in file SOMEPROPKEY=28374874827 - time in ms in future and not in past | xargs du --max-depth=0 > foldersizesreport.csv

    Read the article

  • Database design: Calculating the Account Balance

    - by 001
    How do I design the database to calculate the account balance? 1) Currently I calculate the account balance from the transaction table In my transaction table I have "description" and "amount" etc.. I would then add up all "amount" values and that would work out the user's account balance. I showed this to my friend and he said that is not a good solution, when my database grows its going to slow down???? He said I should create separate table to store the calculated account balance. If did this, I will have to maintain two tables, and its risky, the account balance table could go out of sync. Any suggestion? EDIT: OPTION 2: should I add an extra column to my transaction tables "Balance". now I do not need to go through many rows of data to perform my calculation. Example John buys $100 credit, he debt $60, he then adds $200 credit. Amount $100, Balance $100. Amount -$60, Balance $40. Amount $200, Balance $240.

    Read the article

  • Is it good choice to move a Sublayer around a view using UIPanGestureRecognizer?

    - by Pranjal Bikash Das
    I have a CALayer and as sublayer to this CALayer i have added an imageLayer which contains an image of resolution 276x183. I added a UIPanGestureRecognizer to the main view and calculation the coordinates of the CALayer as follows: - (void)panned:(UIPanGestureRecognizer *)sender{ subLayer.frame=CGRectMake([sender locationInView:self.view].x-138, [sender locationInView:self.view].y-92, 276, 183); } in viedDidLoad i have: subLayer.backgroundColor=[UIColor whiteColor].CGColor; subLayer.frame=CGRectMake(22, 33, 276, 183); imageLayer.contents=(id)[UIImage imageNamed:@"A.jpg"].CGImage; imageLayer.frame=subLayer.bounds; imageLayer.masksToBounds=YES; imageLayer.cornerRadius=15.0; subLayer.shadowColor=[UIColor blackColor].CGColor; subLayer.cornerRadius=15.0; subLayer.shadowOpacity=0.8; subLayer.shadowOffset=CGSizeMake(0, 3); [subLayer addSublayer:imageLayer]; [self.view.layer addSublayer:subLayer]; It is giving desired output but a bit slow in the simulator. I have not yet tested it in Device. so my question is - Is it OK to move a CALayer containing an image??

    Read the article

  • How to write an intersects for Shapes in android

    - by Rafael T
    I have an written an Object called Shape which has a Point representing the topLeftCorner and a Dimension with represents its width and height. To get the topRightCorner I can simply add the width to the topLeftPoint.x. I use to rotate them on a certain degree around their center. The problem after the rotation is, that my intersects(Shape) method fails, because it does not honor the rotation of the Shapes. The rotation will be the same for each Shape. My current implementation looks like this inside my Shape Object: public boolean intersects(Shape s){ // functions returning a Point of shape s return intersects(s.topLeft()) || intersects(s.topRight()) || intersects(s.bottomLeft()) || intersects(s.bottomRight()) || intersects(s.leftCenter()) || intersects(s.rightCenter()) || intersects(s.center()); } public boolean intersects(Point p){ return p.x >= leftX() && p.x <= rightX() && p.y >= topY() && p.y <= bottomY(); } Basically I need functions like rotatedLeftX() or rotatedTopRight() to work properly. Also for that calculation I think it doesn't matter when the topLeft point before a rotation of ie 90 will turn into topRight... I already read this and this Question here, but do not understand it fully.

    Read the article

  • Magento - use an alternate "price.phtml" (in addition to the existing one)

    - by sdek
    I am looking for a way to have an alternate template/catalog/product/price.phml used in one specific location, and to continue using the existing price.phtml file in all other locations. To explain further, I need to display the regular price, and then another special price right below it - but only on the product page (for the main product being displayed). This special price is not a price that can be calculated by the catalog price rules, so I wrote my own module to do the calculation. So, everywhere that I am displaying prices I want to display with the regular ol' template/catalog/product/price.phtml file... but for the product page (the main product - not the related, upsells, etc) I want to use my own custom template/catalog/product/price-custom.phtml template file. Can anybody help? Normally I just look in the layout xml files (for example catalog.xml) to find these types of things, but price.phtml is kinda special - it isn't that simple. And for the life of me I can't figure out if there is an easy way to swap it out conditionally on the page being viewed. I am aware that I can just update price.phtml to always print out this extra price, and then use css to hide the price everywhere, but I would rather not do that if possible. (Also you may want to know that I only have simple products.)

    Read the article

  • How to check if a number is a power of 2

    - by configurator
    Today I needed a simple algorithm for checking if a number is a power of 2. The algorithm needs to be: Simple Correct for any ulong value. I came up with this simple algorithm: private bool IsPowerOfTwo(ulong number) { if (number == 0) return false; for (ulong power = 1; power > 0; power = power << 1) { // this for loop used shifting for powers of 2, meaning // that the value will become 0 after the last shift // (from binary 1000...0000 to 0000...0000) then, the for // loop will break out if (power == number) return true; if (power > number) return false; } return false; } But then I thought, how about checking if log2x is an exactly round number? But when I checked for 2^63+1, Math.Log returned exactly 63 because of rounding. So I checked if 2 to the power 63 is equal to the original number - and it is, because the calculation is done in doubles and not in exact numbers: private bool IsPowerOfTwo_2(ulong number) { double log = Math.Log(number, 2); double pow = Math.Pow(2, Math.Round(log)); return pow == number; } This returned true for the given wrong value: 9223372036854775809. Does anyone have any suggestion for a better algorithm?

    Read the article

  • Designing model/database for distance between any two locations (that may change)

    - by Yo Ludke
    We should create a web app which has a number of events each with a location (created as user-generated content, so the number of events will be increasingly large). The distance between any events should be available, for example to determine the top 5 closest events and such things. Users may change the locations of events. How should one design the database/model for this (in a scalable way)? I was thinking of doing it with a "distance table" (like so http://www.deutschland-tourist.info/images/entfernungstabelle.gif). Then every time, if a location changes, one row and one column have to be recalculated (this should be done with a delayed job, because it is not important to have the changes instantly). Possible problems in Scaling: Database to large (n² items for n events), too much calculation to be done. For example we should see if this is okay for 10.000 users. If each has created just one event, then this would be 100 million integers... Do you think this would be a good way to do it efficiently? How could one realize such a distance table with an rails model? Is it possible with a SQL databse? Would you start other approaches?

    Read the article

  • Client-Side Dynamic Removal of <script> Tags in <head>

    - by merv
    Is it possible to remove script tags in the <head> of an HTML document client-side and prior to execution of those tags? On the server-side I am able to insert a <script> above all other <script> tags in the <head>, except one, and I would like to be able to remove all subsequent scripts. I do not have the ability to remove <script> tags from the server side. What I've tried: (function (c,h) { var i, s = h.getElementsByTagName('script'); c.log("Num scripts: " + s.length); i = s.length - 1; while(i > 1) { h.removeChild(s[i]); i -= 1; } })(console, document.head); However, the logged number of scripts comes out to only 1, since (as @ryan pointed out) the code is being executed prior to the DOM being ready. Although wrapping the code above in a document.ready event callback does enable proper calculation of the number of <script> tags in the <head>, waiting until the DOM is ready fails to prevent the scripts from loading. Is there a reliable means of manipulating the HTML prior to the DOM being ready? Background If you want more context, this is part of an attempt to consolidate scripts where no option for server-side aggregation is available. Many of the JS libraries being loaded are from a CMS with limited configuration options. The content is mostly static, so there is very little concern about manually aggregating the JavaScript and serving it from a different location. Any suggestions for alternative applicable aggregation techniques would also be welcome.

    Read the article

  • How can I make Access think there is a primary key

    - by user3692757
    I have a table and I'm trying to join it with another table, but it doesn't have a distinctive primary key. The two tables do share similarities, “Acct” and “Location”. If I could concatenate “Acct&Location” it would become a primary key, but Access won’t let me make a primary key from a calculation. I provided a small sample below. Each hospital has an “Acct”, but the “Acct” will show up once for each “Location”. How can I make join these in a relationship? I connected the two in a relationships and tried to “Enforce Referential Integrity”, but it indicated “No unique index found for the referenced field of the primary key”. Also, if I run a “Find UnMatched Query” it doesn’t find anything. I think its because I can’t make it realize that in combination “Acct” and “Location” can be perceived as primary keys when used in conjunction of each other. Acct 1 2 3 1 2 3 1 2 3| Location ABI ABI ABI NHO NHO NHO NTX NTX NTX I tried to load an image to illustrate it better, but I haven't made enough post.

    Read the article

  • How do you perform arithmetic calculations on symbols in Scheme/Lisp?

    - by kunjaan
    I need to perform calculations with a symbol. I need to convert the time which is of hh:mm form to the minutes passed. ;; (get-minutes symbol)->number ;; convert the time in hh:mm to minutes ;; (get-minutes 6:19)-> 6* 60 + 19 (define (get-minutes time) (let* ((a-time (string->list (symbol->string time))) (hour (first a-time)) (minutes (third a-time))) (+ (* hour 60) minutes))) This is an incorrect code, I get a character after all that conversion and cannot perform a correct calculation. Do you guys have any suggestions? I cant change the input type. Context: The input is a flight schedule so I cannot alter the data structure. ;; ---------------------------------------------------------------------- Edit: Figured out an ugly solution. Please suggest something better. (define (get-minutes time) (let* ((a-time (symbol->string time)) (hour (string->number (substring a-time 0 1))) (minutes (string->number (substring a-time 2 4)))) (+ (* hour 60) minutes)))

    Read the article

  • Need help with height 100% layout

    - by serg
    I am trying to build the following layout (file browser type of thing, left block would contain a list of files, right panel would contain selected file content): <------------- MENU -------------------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> <--- LEFT ----><------- RIGHT ---------> The page itself shouldn't have any scrollbars. Menu has 100% width and fixed height Left block has fixed width and 100% height. If content is taller - scroll bar appears inside the left block only. Right block contains <pre> element and takes the remaining width and 100% height. If content is wider or taller - scrollbar appears inside the right block only. This is what I have so far: http://jsbin.com/uqegi4/3/edit The problem is fixed menu height messes up 100% height calculation and all scrollbars inside left and right blocks appear at wrong time. I don't care about cross browser compatibility, only Chrome matters. Thanks.

    Read the article

  • queued view updates not happening when performSelector afterDelay:0 used

    - by JosephH
    Hi all, I have an app that performs some calculations based on data arriving on a socket or local user interaction. I want to show an 'activity spinner' whilst the calculation happens. spinner = [[UIActivityIndiactorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; [spinner setCenter:self.view.center]; [self.view addSubview:spinner]; [spinner startAnimating]; [self performSelector:@selector(doCalcs) withObject:nil afterDelay:0]; This works well, except in the case where the code is run as a result of a message arriving over the network. I'm using http://code.google.com/p/cocoaasyncsocket/ to handle sockets and the code is running in the onSocket:didReadData:withTag: method. 'doCalcs' takes a few seconds. The spinner doesn't appear whilst it's running. If I change afterDelay:0 to afterDelay:1 then the spinner does appear the whole time doCalcs is running, but with the downside that it takes an extra second. So it seems the code is all correct, but for whatever reason the spinner isn't getting a chance to get on screen before doCalcs runs. Any suggestions would be most welcome.

    Read the article

  • Multithreading using pthread in C++ with shared variables

    - by Saviour Self
    I'm new to threading (and C/C++ for that matter), and I'm attempting to use multiple threads to access shared variables. In the main, I've created a variable char inputarray[100]; Thread 1: This thread will be reading data from stdin in 2 byte bursts, and appending them to the inputarray. (input by feeding a file in) Thread 2: This thread will be reading data 1 byte at a time, performing a calculation, and putting its data into an output array. Thread 3: This thread will be outputting data from the output array in 2 byte bursts. (stdout) I've attempted the input part and got it working by passing a struct, but would like to do it without using a struct, but it has been giving me problems. If I can get input down, I'm sure I'll be able to use a similar strategy to complete output. Any help would be greatly appreciated. Below is a rough template for the input thread. #include <stdio.h> #include <pthread.h> using namespace std; void* input(void* arg) { char reading[3]; fread(reading,1,2,stdin); //append to char inputarray[]..??? } int main() { char inputarray[100]; pthread_t t1; pthread_create(&t1, NULL, &input, &inputarray); void *result; pthread_join(t1,&result); return 0; }

    Read the article

  • Looping through NSArray while subtracting values from each object? [on hold]

    - by Julian
    I have NSNumber objects stored in an NSMutableArray. I am attempting to perform a calculation on each object in the array. What I want to do is: 1) Take a random higher number variable and keep subtracting a smaller number variable in increments until the value of the variable is equal to the value in the array. For example: NSMutableArray object is equal to 2.50. I have an outside variable of 25 that is not in the array. I want to subtract 0.25 multiple times from the variable until I reach less than or equal to 2.50. I also need a parameter so if the number does not divide evenly and goes below the array value, it resorts to the original array value of 2.50. Lastly, for each iteration, I want to print the values as they are counting down as a string. I was going to provide code, but I don't want to make this more confusing than it has to be. So my output would be: VALUE IS: 24.75 VALUE IS: 24.50 VALUE IS: 24.25 … VALUE IS: 2.50 END

    Read the article

< Previous Page | 58 59 60 61 62 63 64 65 66 67 68 69  | Next Page >