Search Results

Search found 2448 results on 98 pages for 'val'.

Page 7/98 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • VBA Add to Array and Use Previous Value

    - by MattHead93
    I'm trying to write some code that will take a value WeekNum, and add it to an array Week(1 To 51), and then associate a value from a Textbox TargDef. Once this has been added to the array, I want to look up the value of the array for the previous WeekNum and add it to a value ProdTarg. I've created this much so far: Dim Week(1 To 51) Dim Count As Integer If TargDef < 0 Then Count = WeekNum Week(Count) = Abs(Val(TargDef)) If Val(Week((Count) - 1)) = 0 Then ProdTarg = Val(ProdTarg) Else ProdTard = Val(ProdTarg) + Val(Week((Count) - 1)) End If End If I am currently receiving the error "Subscript out of Range" for the line If Val(Week((Count) - 1)) = 0 Then Any help will be greatly appreciated!

    Read the article

  • How do I UPDATE a Linked Server table where "alias" is required, in SQL Server 2000?

    - by Mark Hurd
    In SQL Server 2005 tablename can be used to distinguish which table you're referring to: UPDATE LinkedServer.database.user.tablename SET val=u.val FROM localtable u WHERE tablename.ID=u.ID In SQL Server 2000 this results in Server: Msg 107, Level 16, State 2 The column prefix 'tablename' does not match with a table name or alias name used in the query. Trying UPDATE LinkedServer.database.user.tablename SET val=u.val FROM localtable u WHERE LinkedServer.database.user.tablename.ID=u.ID results in Server: Msg 117, Level 15, State 2 The number name 'LinkedServer.database.user.tablename' contains more than the maximum number of prefixes. The maximum is 3. And, of course, UPDATE LinkedServer.database.user.tablename SET val=u.val FROM localtable u WHERE ID=u.ID results in Server: Msg 209, Level 16, State 1 Ambiguous column name 'ID'. (In fact searching on "The number name contains more than the maximum number of prefixes. The maximum is 3." I found the answer, but I've typed up this question and I'm going to post it! :-) )

    Read the article

  • GAE JCache NumberFormatException, will I need to write Java to avoid?

    - by Jasper
    This code below produces a NumberFormatException in this line: val cache = cf.createCache(Collections.emptyMap()) Do you see any errors? Will I need to write a Java version to avoid this, or is there a Scala way? ... import java.util.Collections import net.sf.jsr107cache._ object QueryGenerator extends ServerResource { private val log = Logger.getLogger(classOf[QueryGenerator].getName) } class QueryGenerator extends ServerResource { def getCounter(cache:Cache):long = { if (cache.containsKey("counter")) { cache.get("counter").asInstanceOf[long] } else { 0l } } @Get("html") def getHtml(): Representation = { val cf = CacheManager.getInstance().getCacheFactory() val cache = cf.createCache(Collections.emptyMap()) val counter = getCounter(cache) cache.put("counter", counter + 1) val q = QueueFactory.getQueue("query-generator") q.add(TaskOptions.Builder.url("/tasks/query-generator").method(Method.GET).countdownMillis(1000L)) QueryGenerator.log.warning(counter.toString) new StringRepresentation("QueryGenerator started!", MediaType.TEXT_HTML) } } Thanks!

    Read the article

  • Is there a way to keep track of javascript hits?

    - by user54197
    I am populating a table based on a javascript function. I want to limit the data entered to 2, afterwhich I hide the table. Is there a way to track how many hits the javascript code gets hit? function addNewRow() { $('#displayInjuryTable tr:last').after('<tr><td style="font-size:smaller;" class="name"></td><td style="font-size:smaller;" class="address"></td></tr>'); var $tr = $('#displayInjuryTable tr:last'); var propertyCondition = $('#txtInjuryAddress').val(); $tr.find('.name').text($('#txtInjuryName').val()); if (propertyCondition != "") { $tr.find('.address').text($('#txtInjuryAddress').val() + ', ' + $('#txtInjuryCity').val() + ' ' + $('#txtInjuryState').val() + ' ' + $('#txtInjuryZip').val()); }

    Read the article

  • Android Bitmap : collision Detecting [on hold]

    - by user2505374
    I am writing an Android game right now and I would need some help in the collision of the wall on screen. When I drag the ball in the top and right it able to collide in wall but when I drag it faster it was able to overlap in the wall. public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { // if the player moves case MotionEvent.ACTION_MOVE: { if (playerTouchRect.contains(x, y)) { boolean left = false; boolean right = false; boolean up = false; boolean down = false; boolean canMove = false; boolean foundFinish = false; if (x != pLastXPos) { if (x < pLastXPos) { left = true; } else { right = true; } pLastXPos = x; } if (y != pLastYPos) { if (y < pLastYPos) { up = true; } else { down = true; } pLastYPos = y; } plCellRect = getRectFromPos(x, y); newplRect.set(playerRect); newplRect.left = x - (int) (playerRect.width() / 2); newplRect.right = x + (int) (playerRect.width() / 2); newplRect.top = y - (int) (playerRect.height() / 2); newplRect.bottom = y + (int) (playerRect.height() / 2); int currentRow = 0; int currentCol = 0; currentRow = getRowFromYPos(newplRect.top); currentCol = getColFromXPos(newplRect.right); if(!canMove){ canMove = mapManager.getCurrentTile().pMaze[currentRow][currentCol] == Cell.wall; canMove =true; } finishTest = mapManager.getCurrentTile().pMaze[currentRow][currentCol]; foundA = finishTest == Cell.valueOf(letterNotGet + ""); canMove = mapManager.getCurrentTile().pMaze[currentRow][currentCol] != Cell.wall; canMove = (finishTest == Cell.floor || finishTest == Cell.pl) && canMove; if (canMove) { invalidate(); setTitle(); } if (foundA) { mapManager.getCurrentTile().pMaze[currentRow][currentCol] = Cell.floor; // finishTest letterGotten.add(letterNotGet); playCurrentLetter(); /*sounds.play(sExplosion, 1.0f, 1.0f, 0, 0, 1.5f);*/ foundS = letterNotGet == 's'; letterNotGet++; }if(foundS){ AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity); builder.setTitle(mainActivity.getText(R.string.finished_title)); LayoutInflater inflater = mainActivity.getLayoutInflater(); View view = inflater.inflate(R.layout.finish, null); builder.setView(view); View closeButton =view.findViewById(R.id.closeGame); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View clicked) { if(clicked.getId() == R.id.closeGame) { mainActivity.finish(); } } }); AlertDialog finishDialog = builder.create(); finishDialog.show(); } else { Log.d(TAG, "INFO: updated player position"); playerRect.set(newplRect); setTouchZone(); updatePlayerCell(); } } // end of (CASE) if playerTouch break; } // end of (SWITCH) Case motion }//end of Switch return true; }//end of TouchEvent private void finish() { // TODO Auto-generated method stub } public int getColFromXPos(int xPos) { val = xPos / (pvWidth / mapManager.getCurrentTile().pCols); if (val == mapManager.getCurrentTile().pCols) { val = mapManager.getCurrentTile().pCols - 1; } return val; } /** * Given a y pixel position, return the row of the cell it is in This is * used when determining the type of adjacent Cells. * * @param yPos * y position in pixels * @return The cell this position is in */ public int getRowFromYPos(int yPos) { val = yPos / (pvHeight / mapManager.getCurrentTile().pRows); if (val == mapManager.getCurrentTile().pRows) { val = mapManager.getCurrentTile().pRows - 1; } return val; } /** * When preserving the position we need to know which cell the player is in, * so calculate it from the centre on its Rect */ public void updatePlayerCell() { plCell.x = (playerRect.left + (playerRect.width() / 2)) / (pvWidth / mapManager.getCurrentTile().pCols); plCell.y = (playerRect.top + (playerRect.height() / 2)) / (pvHeight / mapManager.getCurrentTile().pRows); if (mapManager.getCurrentTile().pMaze[plCell.y][plCell.x] == Cell.floor) { for (int row = 0; row < mapManager.getCurrentTile().pRows; row++) { for (int col = 0; col < mapManager.getCurrentTile().pCols; col++) { if (mapManager.getCurrentTile().pMaze[row][col] == Cell.pl) { mapManager.getCurrentTile().pMaze[row][col] = Cell.floor; break; } } } mapManager.getCurrentTile().pMaze[plCell.y][plCell.x] = Cell.pl; } } public Rect getRectFromPos(int x, int y) { calcCell.left = ((x / cellWidth) + 0) * cellWidth; calcCell.right = calcCell.left + cellWidth; calcCell.top = ((y / cellHeight) + 0) * cellHeight; calcCell.bottom = calcCell.top + cellHeight; Log.d(TAG, "Rect: " + calcCell + " Player: " + playerRect); return calcCell; } public void setPlayerRect(Rect newplRect) { playerRect.set(newplRect); } private void setTouchZone() { playerTouchRect.set( playerRect.left - playerRect.width() / TOUCH_ZONE, playerRect.top - playerRect.height() / TOUCH_ZONE, playerRect.right + playerRect.width() / TOUCH_ZONE, playerRect.bottom + playerRect.height() / TOUCH_ZONE); } public Rect getPlayerRect() { return playerRect; } public Point getPlayerCell() { return plCell; } public void setPlayerCell(Point cell) { plCell = cell; }

    Read the article

  • Generating tileable terrain using Perlin Noise [duplicate]

    - by terrorcell
    This question already has an answer here: How do you generate tileable Perlin noise? 9 answers I'm having trouble figuring out the solution to this particular algorithm. I'm using the Perlin Noise implementation from: https://code.google.com/p/mikeralib/source/browse/trunk/Mikera/src/main/java/mikera/math/PerlinNoise.java Here's what I have so far: for (Chunk chunk : chunks) { PerlinNoise noise = new PerlinNoise(); for (int y = 0; y < CHUNK_SIZE_HEIGHT; ++y) { for (int x = 0; x < CHUNK_SIZE_WIDTH; ++x) { int index = get1DIndex(y, CHUNK_SIZE_WIDTH, x); float val = 0; for (int i = 2; i <= 32; i *= i) { double n = noise.tileableNoise2(i * x / (float)CHUNK_SIZE_WIDTH, i * y / (float)CHUNK_SIZE_HEIGHT, CHUNK_SIZE_WIDTH, CHUNK_SIZE_HEIGHT); val += n / i; } // chunk tile at [index] gets set to the colour 'val' } } } Which produces something like this: Each chunk is made up of CHUNK_SIZE number of tiles, and each tile has a TILE_SIZE_WIDTH/HEIGHT. I think it has something to do with the inner-most for loop and the x/y co-ords given to the noise function, but I could be wrong. Solved: PerlinNoise noise = new PerlinNoise(); for (Chunk chunk : chunks) { for (int y = 0; y < CHUNK_SIZE_HEIGHT; ++y) { for (int x = 0; x < CHUNK_SIZE_WIDTH; ++x) { int index = get1DIndex(y, CHUNK_SIZE_WIDTH, x); float val = 0; float xx = x * TILE_SIZE_WIDTH + chunk.x; float yy = y * TILE_SIZE_HEIGHT + chunk.h; int w = CHUNK_SIZE_WIDTH * TILE_SIZE_WIDTH; int h = CHUNK_SIZE_HEIGHT * TILE_SIZE_HEIGHT; for (int i = 2; i <= 32; i *= i) { double n = noise.tileableNoise2(i * xx / (float)w, i * yy / (float)h, w, h); val += n / i; } // chunk tile at [index] gets set to the colour 'val' } } }

    Read the article

  • Better way for calculating project euler's 2nd problem Fibonacci sequence)

    - by firephil
    object Problem_2 extends App { def fibLoop():Long = { var x = 1L var y = 2L var sum = 0L var swap = 0L while(x < 4000000) { if(x % 2 ==0) sum +=x swap = x x = y y = swap + x } sum } def fib:Int = { lazy val fs: Stream[Int] = 0 #:: 1 #:: fs.zip(fs.tail).map(p => p._1 + p._2) fs.view.takeWhile(_ <= 4000000).filter(_ % 2 == 0).sum } val t1 = System.nanoTime() val res = fibLoop val t2 = (System.nanoTime() - t1 )/1000 println(s"The result is: $res time taken $t2 ms ") } Is there a better functional way for calculating the fibonaci sequence and taking the sum of the the even values below 4million ? (projecteuler.net - problem 2) The imperative method is 1000x faster ?

    Read the article

  • JQuery Validation [migrated]

    - by user41354
    Im trying to get my form to validate...so basically its working, but a little bit too well, I have two text boxes, one is a start date, the other an end date in the format of mm/dd/yyyy if the start date is greater than the end date...there is an error if the end date is less than the start date...there is an error if the start date is less than today's date...there is an error The only thing is when I correct the error, the error warning is still there...here is my code: dates.change(function () { var testDate = $(this).val(); var otherDate = dates.not(this).val(); var now = new Date(); now.setHours(0, 0, 0, 0); // Pass Dates if (testDate != '' && new Date(testDate) < now) { addError($(this)); $('.flightDateError').text('* Dates cannot be earlier than today.'); isValid = false; return; } // Required Text if ($(this).hasClass("FromCal") && testDate == '') { addError($(this)); $('.flightDateError').text('* Required'); isValid = false; return; } // Validate Date if (!isValidDate(testDate)) { // $(this).addClass('validation_error_input'); addError($(this)); $('.flightDateError').text('* Invalid Date'); isValid = false; return; } else { // $(this).removeClass('validation_error_input'); removeError($(this)); if (!dates.not(this).hasClass('validation_error_input')) $('.flightDateError').text(' '); } // Validate Date Ranges if ($(this).val() != '' && dates.not(this).val != '') { if ($(this).hasClass("FromCal")) { if (new Date(testDate) > new Date(otherDate)) { addError($(this)); $('.flightDateError').text('* Start date must be earlier than end date.'); isValid = false; return; } } else{ if (new Date(testDate) < new Date(otherDate)) { addError($(this)); $('.flightDateError').text('* End date must be later than start date.'); return; } } } }); The main Issue is this part, I believe // Validate Date Ranges if ($(this).val() != '' && dates.not(this).val != '') { if ($(this).hasClass("FromCal")) { if (new Date(testDate) > new Date(otherDate)) { addError($(this)); $('.flightDateError').text('* Start date must be earlier than end date.'); isValid = false; return; } } else{ if (new Date(testDate) < new Date(otherDate)) { addError($(this)); $('.flightDateError').text('* End date must be later than start date.'); return; } } } testDate is the start date otherDate is the end date Thanks in advanced, J

    Read the article

  • Error Loading Simple XML

    - by Rooneyl
    I have an xml document (generated from msword 2010), which I am trying to process using simple xml. Sample of xml: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 wp14"> <w:body> <w:p w:rsidR="005B1098" w:rsidRDefault="005B1098"/> <w:p w:rsidR="00F254A4" w:rsidRDefault="00F254A4"/> <w:p w:rsidR="00F254A4" w:rsidRPr="008475A1" w:rsidRDefault="00C15492" w:rsidP="008475A1"> <w:pPr> <w:jc w:val="center"/> <w:rPr> <w:b/> <w:sz w:val="44"/> <w:szCs w:val="44"/> </w:rPr> </w:pPr> <w:r w:rsidRPr="008475A1"> <w:rPr> <w:b/> <w:sz w:val="44"/> <w:szCs w:val="44"/> </w:rPr> <w:t>Test file</w:t> </w:r> </w:p> <w:p w:rsidR="00C15492" w:rsidRPr="008475A1" w:rsidRDefault="00C15492" w:rsidP="008475A1"> <w:pPr> <w:jc w:val="center"/> <w:rPr> <w:sz w:val="20"/> <w:szCs w:val="20"/> </w:rPr> </w:pPr> <w:r w:rsidRPr="008475A1"> <w:rPr> <w:sz w:val="20"/> <w:szCs w:val="20"/> </w:rPr> <w:t>another paragraph</w:t> </w:r> </w:p> </w:body> </w:document> I am trying to open it using: if(!$simple_xml = simplexml_load_file($content)){ trigger_error('Error reading XML file',E_USER_ERROR); } else { echo 'loaded'; } And get the error: Message: simplexml_load_file(): I/O warning : failed to load external entity " Test file another paragraph " Any ideas?

    Read the article

  • Highlighting dates between two selected dates jQuery UI Datepicker

    - by Ralph
    I have one datepicker with numberOfMonths set to 2. Arrival Date and Departure Date are determined using this logic (within onSelect): if ((count % 2)==0) { depart = $("#datepicker-1").datepicker('getDate'); if (arriv depart) { temp=arriv; arriv=depart; depart=temp; } $("#check-in").val($.datepicker.formatDate("DD, MM d, yy",arriv)); $("#check-out").val($.datepicker.formatDate("DD, MM d, yy",depart)); } else { arriv = $("#datepicker-1").datepicker('getDate'); depart = null; if ((arriv depart)&&(depart!=null)) { temp=arriv; arriv=depart; depart=temp; } $("#day-count").val(''); $("#check-in").val($.datepicker.formatDate("DD, MM d, yy",arriv)); $("#check-out").val($.datepicker.formatDate("DD, MM d, yy",depart)); } if(depart!=null) { diffDays = Math.abs((arriv.getTime() - depart.getTime())/(oneDay)); if (diffDays == 0) { $("#day-count").val((diffDays+1)+' Night/s'); } else { $("#day-count").val(diffDays+' Night/s'); } } Getting the number of days within these 2 dates has no problem What I want now is highlight those dates starting from the Arrival to Departure I tried working around the onSelect but had no luck. I am now using beforeShowDay to highlight these dates but I can't seem to figure it out Got a sample from here Basically, it is customized to highlight 11 or 12 days after the selected date (Here's the code from that link). $('#datePicker').datepicker({beforeShowDay: function(date) { if (selected != null && date.getTime() selected.getTime() && (date.getTime() - selected.getTime()) Since I am new to using the UI, and the logic is not clear to me yet, I can't seem to figure this out. Any ideas on how I can make this highlight dates between the Arrival and Departure using my aforementioned logic used in determining the two?

    Read the article

  • Multiple Instances of Static Singleton

    - by Nexus
    I've recently been working with code that looks like this: using namespace std; class Singleton { public: static Singleton& getInstance(); int val; }; Singleton &Singleton::getInstance() { static Singleton s; return s; } class Test { public: Test(Singleton &singleton1); }; Test::Test(Singleton &singleton1) { Singleton singleton2 = Singleton::getInstance(); singleton2.val = 1; if(singleton1.val == singleton2.val) { cout << "Match\n"; } else { cout << "No Match " << singleton1.val << " - " << singleton2.val << "\n"; } } int main() { Singleton singleton = Singleton::getInstance(); singleton.val = 2; Test t(singleton); } Every time I run it I get "No Match". From what I can tell when stepping through with GDB is that there are two instances of the Singleton. Why is this?

    Read the article

  • initialising a 2-dim Array in Scala

    - by Stefan W.
    (Scala 2.7.7:) I don't get used to 2d-Arrays. Arrays are mutable, but how do I specify a 2d-Array which is - let's say of size 3x4. The dimension (2D) is fixed, but the size per dimension shall be initializable. I tried this: class Field (val rows: Int, val cols: Int, sc: java.util.Scanner) { var field = new Array [Char](rows)(cols) for (r <- (1 to rows)) { val line = sc.nextLine () val spl = line.split (" ") field (r) = spl.map (_.charAt (0)) } def put (val rows: Int, val cols: Int, c: Char) = todo () } I get this error: :11: error: value update is not a member of Char field (r) = spl.map (_.charAt (0)) If it would be Java, it would be much more code, but I would know how to do it, so I show what I mean: public class Field { private char[][] field; public Field (int rows, int cols, java.util.Scanner sc) { field = new char [rows][cols]; for (int r = 0; r < rows; ++r) { String line = sc.nextLine (); String[] spl = line.split (" "); for (int c = 0; c < cols; ++c) field [r][c] = spl[c].charAt (0); } } public static void main (String args[]) { new Field (3, 4, new java.util.Scanner ("fraese.fld")); } } and fraese.fld would look, for example, like that: M M M M . M I get some steps wide with val field = new Array Array [Char] but how would I then implement 'put'? Or is there a better way to implement the 2D-Array. Yes, I could use a one-dim-Array, and work with put (y, x, c) = field (y * width + x) = c but I would prefer a notation which looks more 2d-ish.

    Read the article

  • Unrecognized function - but why?

    - by fmz
    I have an Ajax contact form that links to a jquery file but for some reason I get the following error in Firebug: $("#contactform").submit is not a function Here is the link to the jquery file: <script type="text/javascript" src="scripts/jquery.jigowatt.js"></script> Here is the jquery code: jQuery(document).ready(function(){ $('#contactform').submit(function(){ var action = $(this).attr('action'); $("#message").slideUp(750,function() { $('#message').hide(); $('#submit') .after('<img src="assets/ajax-loader.gif" class="loader" />') .attr('disabled','disabled'); $.post(action, { name: $('#name').val(), company: $('#company').val(), email: $('#email').val(), phone: $('#phone').val(), subject: $('#purpose').val(), comments: $('#comments').val(), verify: $('#verify').val() }, function(data){ document.getElementById('message').innerHTML = data; $('#message').slideDown('slow'); $('#contactform img.loader').fadeOut('slow',function() {$(this).remove()}); $('#contactform #submit').attr('disabled',''); if(data.match('success') != null) $('#contactform').slideUp('slow'); } ); }); return false; }); }); And last but not least, here is the page where it is all supposed to come together: http://theideapeople.com.previewdns.com/contact_us.html I would appreciate some help getting the function to function properly. Thanks.

    Read the article

  • How to link jQuery UI datepicker functionality with a select list

    - by take2
    I'm trying to connect jQuery UI's datepicker with a select list. I have found one explanation on jQuery's Forum ( forum.jquery.com/topic/jquery-ui-datepicker-with-select-lists), but I can't get it working. There are input and select list both declared: <select id="selectMonth"><option value="01">Jan</option><option value="02">Feb</option> <option value="03">Mar</option><option value="04">Apr</option>...</select> <select id="selectDay"><option value="01">1</option><option value="02">2</option> <option value="03">3</option><option value="04">4</option>...</select> <select id="selectYear"><option value="2012">2012</option><option value="2013">2013</option> <option value="2014">2014</option>...</select> <p>Date: <input type="text" id="selectedDatepicker" /></p> This is the script: $(function() { $('#selectedDatepicker').datepicker({ beforeShow: readSelected, onSelect: updateSelected, minDate: new Date(2012, 1 - 1, 1), maxDate: new Date(2014, 12 - 1, 31), showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calendar.gif'}); // Prepare to show a date picker linked to three select controls function readSelected() { $('#selectedDatepicker').val($('#selectMonth').val() + '/' + $('#selectDay').val() + '/' + $('#selectYear').val()); return {}; } // Update three select controls to match a date picker selection function updateSelected(date) { $('#selectMonth').val(date.substring(0, 2)); $('#selectDay').val(date.substring(3, 5)); $('#selectYear').val(date.substring(6, 10)); } }); And here is the fiddle: http://jsfiddle.net/xKXZm/ They are not connected properly, the only "connected behaviour" is that when you click on the input button, it picks up the value of the select list. On the other hand, the select list never picks up the value of the input nor will the input pick up the value of the select list until you click on it.

    Read the article

  • assigning selected="selected" to dynamic option list

    - by leemjac
    In an "edit article" page i have a select list which displays author first and last name, as well as authorId as the value. As well as the article context and headline and so on (fetched with a different method) - though this method also holds the authorId of the specific article. I need to have the Author of the Article selected in the option list, instead of it defaulting to the first option in the select list. what i have: echo''; //loop through author names in option list $authors_name foreach($authors_name as $nameRow){ echo'<option class="authorId" value = "' . $nameRow['AuthorID'] . '">'. $nameRow['FirstName'].' '.$nameRow['LastName'] .''; } echo'</select>'; and the jquery: var currID = ('#selectAuthor').val(); if(('.authorId').val() == currID){ $('.authorId').addClass('new_class') $('.new_class').prop('selected',true); } OR var currID = ('#selectAuthor').val(); if($("select option[value=currID]").attr('selected','selected')); Any help would be greatly appreciated, I hope what I am trying to do is clear. Thanks in advance I have simplified it with just regular input and checked it in jsfiddle.net here is the HTML '; <option value = "2">Name val 2</option> <option value = "5">Name val 5</option> <option value = "1">Name val 1</option> and here is the jquery var currID = $('#selectAuthor').val(); if($("select option[value='+currID+']").prop('selected',true));? and even then it doesn't apply selected="selected" to option with value="1"

    Read the article

  • power and modulo on the fly for big numbers

    - by user unknown
    I raise some basis b to the power p and take the modulo m of that. Let's assume b=55170 or 55172 and m=3043839241 (which happens to be the square of 55171). The linux-calculator bc gives the results (we need this for control): echo "p=5606;b=55171;m=b*b;((b-1)^p)%m;((b+1)^p)%m" | bc 2734550616 309288627 Now calculating 55170^5606 gives a somewhat large number, but since I have to do a modulooperation, I can circumvent the usage of BigInt, I thought, because of: (a*b) % c == ((a%c) * (b%c))%c i.e. (9*7) % 5 == ((9%5) * (7%5))%5 => 63 % 5 == (4 * 2) %5 => 3 == 8 % 5 ... and a^d = a^(b+c) = a^b * a^c, therefore I can divide b+c by 2, which gives, for even or odd ds d/2 and d-(d/2), so for 8^5 I can calculate 8^2 * 8^3. So my (defective) method, which always cut's off the divisor on the fly looks like that: def powMod (b: Long, pot: Int, mod: Long) : Long = { if (pot == 1) b % mod else { val pot2 = pot/2 val pm1 = powMod (b, pot, mod) val pm2 = powMod (b, pot-pot2, mod) (pm1 * pm2) % mod } } and feeded with some values, powMod (55170, 5606, 3043839241L) res2: Long = 1885539617 powMod (55172, 5606, 3043839241L) res4: Long = 309288627 As we can see, the second result is exactly the same as the one above, but the first one looks quiet different. I'm doing a lot of such calculations, and they seem to be accurate as long as they stay in the range of Int, but I can't see any error. Using a BigInt works as well, but is way too slow: def calc2 (n: Int, pri: Long) = { val p: BigInt = pri val p3 = p * p val p1 = (p-1).pow (n) % (p3) val p2 = (p+1).pow (n) % (p3) print ("p1: " + p1 + " p2: " + p2) } calc2 (5606, 55171) p1: 2734550616 p2: 309288627 (same result as with bc) Can somebody see the error in powMod?

    Read the article

  • Operator+ for a subtype of a template class.

    - by baol
    I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+. #include <iostream> template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs; }; template<typename other_type> typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left, const typename c<other_type>::subtype& right) { return typename c<other_type>::subtype(left.val + right.val); } // This one works // c<int>::subtype operator+(const c<int>::subtype& left, // const c<int>::subtype& right) // { return c<int>::subtype(left.val + right.val); } int main() { c<int> c1 = 1; c<int> c2 = 2; c<int>::subtype cs3 = c1.cs + c2.cs; std::cerr << cs3.val << std::endl; } I think the reason is because the compiler (g++4.3) cannot guess the template type so it's searching for operator+<int> instead of operator+. What's the reason for that? What elegant solution can you suggest?

    Read the article

  • Determine if a Range contains a value

    - by Brad Dwyer
    I'm trying to figure out a way to determine if a value falls within a Range in Swift. Basically what I'm trying to do is adapt one of the examples switch statement examples to do something like this: let point = (1, -1) switch point { case let (x, y) where (0..5).contains(x): println("(\(x), \(y)) has an x val between 0 and 5.") default: println("This point has an x val outside 0 and 5.") } As far as I can tell, there isn't any built in way to do what my imaginary .contains method above does. So I tried to extend the Range class. I ended up running into issues with generics though. I can't extend Range<Int> so I had to try to extend Range itself. The closest I got was this but it doesn't work since >= and <= aren't defined for ForwardIndex extension Range { func contains(val:ForwardIndex) -> Bool { return val >= self.startIndex && val <= self.endIndex } } How would I go about adding a .contains method to Range? Or is there a better way to determine whether a value falls within a range? Edit2: This seems to work to extend Range extension Range { func contains(val:T) -> Bool { for x in self { if(x == val) { return true } } return false } } var a = 0..5 a.contains(3) // true a.contains(6) // false a.contains(-5) // false I am very interested in the ~= operator mentioned below though; looking into that now.

    Read the article

  • Operator+ for a subtype of a template classe.

    - by baol
    I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+. #include <iostream> template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs; }; template<typename other_type> typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left, const typename c<other_type>::subtype& right) { return typename c<other_type>::subtype(left.val + right.val); } // This one works // c<a>::subtype operator+(const c<a>::subtype& left, // const c<a>::subtype& right) // { return c<a>::subtype(left.val + right.val); } int main() { c<int> c1 = 1; c<int> c2 = 2; c<int>::subtype cs3 = c1.cs + c2.cs; std::cerr << cs3.val << std::endl; } I think the reason is because the compiler (g++4.3) cannot guess the template type so it's searching for operator+<int> instead of operator+. What's the reason for that? What elegant solution can you suggest?

    Read the article

  • Array length is zero in jQuery.

    - by James123
    I wrote like this. After submit click loop is not excuting. But I saw value are there, But array lenght is showing '0'. (Please see picture). Why it is not going into loop? and $('#myVisibleRows').val(idsString); becoming 'empty'. $(document).ready(function() { $('tr[@class^=RegText]').hide().children('td'); var list_Visible_Ids = []; var idsString, idsArray; alert($('#myVisibleRows').val()); idsString = $('#myVisibleRows').val(); idsArray = idsString.split(','); $.each(idsArray, function() { if (this != "") { $('#' + this).siblings(('.RegText').toggle(true)); window['list_Visible_Ids'][this] = 1; } }); $('tr.subCategory1') .css("cursor", "pointer") .attr("title", "Click to expand/collapse") .click(function() { //this = $(this); $(this).siblings('.RegText').toggle(); list_Visible_Ids[$(this).attr('id')] = $(this).css('display') != 'none' ? 1 : null; alert(list_Visible_Ids[$(this).attr('id')]) }); $('#form1').submit(function() { idsString = ''; $.each(list_Visible_Ids, function(key, val) { alert(val); if (val) { idsString += (idsString != '' ? ',' : '') + key; } }); $('#myVisibleRows').val(idsString); form.submit(); }); });

    Read the article

  • Type contraint problem of C#

    - by user351565
    I meet a problem about type contraint of c# now. I wrote a pair of methods that can convert object to string and convert string to object. ex. static string ConvertToString(Type type, object val) { if (type == typeof(string)) return (string)val; if (type == typeof(int)) return val.ToString(); if (type.InSubclassOf(typeof(CodeObject))) return ((CodeObject)val).Code; } static T ConvertToObject<T>(string str) { Type type = typeof(T); if (type == typeof(string)) return (T)(object)val; if (type == typeof(int)) return (T)(object)int.Parse(val); if (type.InSubclassOf(typeof(CodeObject))) return Codes.Get<T>(val); } where CodeObject is a base class of Employees, Offices ..., which can fetch by static method Godes.Get where T: CodeObject but the code above cannot be compiled because error #CS0314 the generic type T of method ConvertToObject have no any constraint but Codes.Get request T must be subclass of CodeObject i tried use overloading to solve the problem but not ok. is there any way to clear up the problem? like reflection?

    Read the article

  • Using data.table to aggregate

    - by dayne
    After multiple suggestions from SO users, I am finally trying to convert my code over to using data.tables. library(data.table) DT <- data.table(plate = paste0("plate",rep(1:2,each=5)), id = rep(c("CTRL","CTRL","ID1","ID2","ID3"),2), val = 1:10) > DT plate id val 1: plate1 CTRL 1 2: plate1 CTRL 2 3: plate1 ID1 3 4: plate1 ID2 4 5: plate1 ID3 5 6: plate2 CTRL 6 7: plate2 CTRL 7 8: plate2 ID1 8 9: plate2 ID2 9 10: plate2 ID3 10 What I would like to do is take the average of DT[,val] by plate when the id is "CTRL". I would normally aggregate the data frame, then use match to map the values back to a new column, 'ctrl'. Using the data.table package I can get: DT[id=="CTRL",ctrl:=mean(val),by=plate] > DT plate id val ctrl 1: plate1 CTRL 1 1.5 2: plate1 CTRL 2 1.5 3: plate1 ID1 3 NA 4: plate1 ID2 4 NA 5: plate1 ID3 5 NA 6: plate2 CTRL 6 6.5 7: plate2 CTRL 7 6.5 8: plate2 ID1 8 NA 9: plate2 ID2 9 NA 10: plate2 ID3 10 NA What I need is really: DT <- data.table(plate = paste0("plate",rep(1:2,each=5)), id = rep(c("CTRL","CTRL","ID1","ID2","ID3"),2), val = 1:10, ctrl = rep(c(1.5,6.5),each=5)) > DT plate id val ctrl 1: plate1 CTRL 1 1.5 2: plate1 CTRL 2 1.5 3: plate1 ID1 3 1.5 4: plate1 ID2 4 1.5 5: plate1 ID3 5 1.5 6: plate2 CTRL 6 6.5 7: plate2 CTRL 7 6.5 8: plate2 ID1 8 6.5 9: plate2 ID2 9 6.5 10: plate2 ID3 10 6.5 Eventually I would like to use much more complicated selections of the values, but I do not know how to select specific values, run some function, then map those values back to the appropriate row using data frames.

    Read the article

  • JQUERY, AJAX Request and then loop through the data.

    - by nobosh
    Does anyone see anything wrong with the following: $.ajax({ url: '/tags/ajax/post-tag/', data: { newtaginput : $('#tag-input').val(), customerid : $('#customerid').val()}, success: function(data) { // After posting alert(data); arr = data.tagsinserted.split(','); alert(arr); //Loop through $.each(arr, function(n, val){ alert(n + ' ' + val) }); } }, "json"); tagsinserted is what's being returned, here is the full response: {"returnmessage":"The Ajax operation was successful.","tagsinserted":"b7,b4,dog,cat","returncode":"0"} Thanks

    Read the article

  • Creating a tiled map with blender

    - by JamesB
    I'm looking at creating map tiles based on a 3D model made in blender, The map is 16 x 16 in blender. I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400. The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600 What I need is a script for blender that can create the tiles from the model. I've never written in python before so I've been trying to adapt a couple of the scripts which are already there. So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles. Here is what I've got so far... #!BPY """ Name: 'Export Map Tiles' Blender: '242' Group: 'Export' Tip: 'Export to Map' """ import Blender from Blender import Scene,sys from Blender.Scene import Render def init(): thumbsize = 200 CameraHeight = 4.4 YStart = -8 YMove = 4 XStart = -8 XMove = 4 ZoomLevel = 1 Path = "/Images/Map/" Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path] def show_prefs(): buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]); buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1]) buttonYStart = Blender.Draw.Create(Blender.drawmap[2]) buttonYMove = Blender.Draw.Create(Blender.drawmap[3]) buttonXStart = Blender.Draw.Create(Blender.drawmap[4]) buttonXMove = Blender.Draw.Create(Blender.drawmap[5]) buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6]) buttonPath = Blender.Draw.Create(Blender.drawmap[7]) block = [] block.append(("Image Size", buttonthumbsize, 0, 500)) block.append(("Camera Height", buttonCameraHeight, -0, 10)) block.append(("Y Start", buttonYStart, -10, 10)) block.append(("Y Move", buttonYMove, 0, 5)) block.append(("X Start", buttonXStart,-10, 10)) block.append(("X Move", buttonXMove, 0, 5)) block.append(("Zoom Level", buttonZoomLevel, 1, 10)) block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles")) retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block) if retval: Blender.drawmap[0] = buttonthumbsize.val Blender.drawmap[1] = buttonCameraHeight.val Blender.drawmap[2] = buttonYStart.val Blender.drawmap[3] = buttonYMove.val Blender.drawmap[4] = buttonXStart.val Blender.drawmap[5] = buttonXMove.val Blender.drawmap[6] = buttonZoomLevel.val Blender.drawmap[7] = buttonPath.val Export() def Export(): scn = Scene.GetCurrent() context = scn.getRenderingContext() def cutStr(str): #cut off path leaving name c = str.find("\\") while c != -1: c = c + 1 str = str[c:] c = str.find("\\") str = str[:-6] return str #variables from gui: thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap XMove = XMove / ZoomLevel YMove = YMove / ZoomLevel Camera = Scene.GetCurrent().getCurrentCamera() Camera.LocZ = CameraHeight / ZoomLevel YStart = YStart + (YMove / 2) XStart = XStart + (XMove / 2) #Point it straight down Camera.RotX = 0 Camera.RotY = 0 Camera.RotZ = 0 TileCount = 4**ZoomLevel #Because the first thing we do is move the camera, start it off the map Camera.LocY = YStart - YMove for i in range(0,TileCount): Camera.LocY = Camera.LocY + YMove Camera.LocX = XStart - XMove for j in range(0,TileCount): Camera.LocX = Camera.LocX + XMove Render.EnableDispWin() context.extensions = True context.renderPath = Path #setting thumbsize context.imageSizeX(thumbsize) context.imageSizeY(thumbsize) #could be put into a gui. context.imageType = Render.PNG context.enableOversampling(0) #render context.render() #save image ZasString = '%s' %(int(ZoomLevel)) XasString = '%s' %(int(j+1)) YasString = '%s' %(int((3-i)+1)) context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString) #close the windows Render.CloseRenderWindow() try: type(Blender.drawmap) except: #print 'initialize extern variables' init() show_prefs()

    Read the article

  • setting a value through jquery

    - by Hulk
    <script> function edit(elem) { var ele=$(elem).siblings('label#test').html(); var a=document.getElementById('test'); var htm = '<input type="text" name="modal" id="modal" style="width:70%;" value="'+$(elem).siblings('label#test').html();+'"/>'; $dialog.html(htm) .dialog({ autoOpen: true, position: 'center' , title: 'EDIT', draggable: false, width : 300, height : 40, resizable : false, modal : true, buttons: { "Save" : function() { if($('#modal').val() != ''){a.value=$('#modal').val();$dialog.dialog('close');} else {alert('i++'+$('#modal').val()+'++');} } } }); $dialog.dialog('open'); } $(document).ready(function() { var flag=0; $("input:radio[@name=template]").click(function() { var checkedoption = $(this).val(); if (checkedoption == "template3") { if (flag == 0) { var html = '<input type="text" name="val" id="val" />&nbsp;&nbsp;&nbsp;<input type="button" value="Add" id="add"><br>'; $('#useroptions').append(html); flag=1; $('#add').click(function(){ var a = $('#val').val(); if (a == '') { alert('Enter options'); } else { var section= '<tr class="clickable"><td id="userval" BGCOLOR="#FF6699"><label id="test">' + a + '</label>&nbsp;&nbsp;&nbsp; <IMG SRC="/media/img/chunkedit.gif" onclick="javascript:edit(this);" >&nbsp;&nbsp;&nbsp;<IMG SRC="/media/img/close.gif" onclick="javascript:remove(this);" ></td></tr>'; $('#useroptions').append(section); } }); } } }); }); </script> <form> <table> <tr><td> <div id="useroptions"></div> </tr></td> </table> </form> How to set a new value for test in the above code.. Thanks

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >