Daily Archives

Articles indexed Monday October 15 2012

Page 12/19 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • SOAP web services in haskell?

    - by Dave
    I have to write a bunch of small web services. They must be defined by a WSDL and work via SOAP-RPC, in order to work with an existing workflow engine and service registry framework. I can, however, serve them on a service stack/platform of my choice. I'm presently writing them in Java, and it's not too bad. But I'm thinking my life might be easier if I was able to write these services in Haskell. Searching on Google, it looks like, once upon a time, someone else had the same idea and started a project called "HAIFA". However, it looks like HAIFA hasn't been maintained for some years, and I couldn't find any other frameworks supporting serving up services written in Haskell as SOAP web services. Does anyone know of any other frameworks that will allow me to easily write SOAP-based web services using Haskell? If not, has anyone done this manually (i.e., use XML libraries from hackage to process the incoming soap-rpc requests, and create soap-rpc compliant replies)? Was it difficult to do? Any gotchas? Was it worth the effort? Thanks in advance!

    Read the article

  • Execution Plan Optimization when where clause is removed then added back

    - by nmushov
    I have a stored procedure that uses a table valued function which executes in 9 seconds. If I alter the table valued function and remove the where clause, the stored procedure executes in 3 seconds. If I add the where clause back, the query still executes in 3 seconds. I took a look at the execution plans and it appears that after I remove the where clause, the execution plan includes parallelism and the scan count for 2 of my tables drops for 50000 and 65000 down to 5 and 3. After I add the where clause back, the optimized execution plan still runs unless I run DBCC FREEPROCCACHE. Questions 1. Why would SQL Server start using the optimized execution plan for both queries only when I first remove the where clause? Is there a way to force SQL Server to use this execution plan? Also, this is a paramaterized all-in-one query that uses the (Parameter is null or Parameter) in the where clause, which I believe is bad for performance. RETURNS TABLE AS RETURN ( SELECT TOP (@PageNumber * @PageSize) CASE WHEN @SortOrder = 'Expensive' THEN ROW_NUMBER() OVER (ORDER BY SellingPrice DESC) WHEN @SortOrder = 'Inexpensive' THEN ROW_NUMBER() OVER (ORDER BY SellingPrice ASC) WHEN @SortOrder = 'LowMiles' THEN ROW_NUMBER() OVER (ORDER BY Mileage ASC) WHEN @SortOrder = 'HighMiles' THEN ROW_NUMBER() OVER (ORDER BY Mileage DESC) WHEN @SortOrder = 'Closest' THEN ROW_NUMBER() OVER (ORDER BY P1.Distance ASC) WHEN @SortOrder = 'Newest' THEN ROW_NUMBER() OVER (ORDER BY [Year] DESC) WHEN @SortOrder = 'Oldest' THEN ROW_NUMBER() OVER (ORDER BY [Year] ASC) ELSE ROW_NUMBER() OVER (ORDER BY InventoryID ASC) END as rn, P1.InventoryID, P1.SellingPrice, P1.Distance, P1.Mileage, Count(*) OVER () RESULT_COUNT, dimCarStatus.[year] FROM (SELECT InventoryID, SellingPrice, Zip.Distance, Mileage, ColorKey, CarStatusKey, CarKey FROM facInventory JOIN @ZipCodes Zip ON Zip.DealerKey = facInventory.DealerKey) as P1 JOIN dimColor ON dimColor.ColorKey = P1.ColorKey JOIN dimCarStatus ON dimCarStatus.CarStatusKey = P1.CarStatusKey JOIN dimCar ON dimCar.CarKey = P1.CarKey WHERE (@ExteriorColor is NULL OR dimColor.ExteriorColor like @ExteriorColor) AND (@InteriorColor is NULL OR dimColor.InteriorColor like @InteriorColor) AND (@Condition is NULL OR dimCarStatus.Condition like @Condition) AND (@Year is NULL OR dimCarStatus.[Year] like @Year) AND (@Certified is NULL OR dimCarStatus.Certified like @Certified) AND (@Make is NULL OR dimCar.Make like @Make) AND (@ModelCategory is NULL OR dimCar.ModelCategory like @ModelCategory) AND (@Model is NULL OR dimCar.Model like @Model) AND (@Trim is NULL OR dimCar.Trim like @Trim) AND (@BodyType is NULL OR dimCar.BodyType like @BodyType) AND (@VehicleTypeCode is NULL OR dimCar.VehicleTypeCode like @VehicleTypeCode) AND (@MinPrice is NULL OR P1.SellingPrice >= @MinPrice) AND (@MaxPrice is NULL OR P1.SellingPrice < @MaxPrice) AND (@Mileage is NULL OR P1.Mileage < @Mileage) ORDER BY CASE WHEN @SortOrder = 'Expensive' THEN -SellingPrice WHEN @SortOrder = 'Inexpensive' THEN SellingPrice WHEN @SortOrder = 'LowMiles' THEN Mileage WHEN @SortOrder = 'HighMiles' THEN -Mileage WHEN @SortOrder = 'Closest' THEN P1.Distance WHEN @SortOrder = 'Newest' THEN -[YEAR] WHEN @SortOrder = 'Oldest' THEN [YEAR] ELSE InventoryID END )

    Read the article

  • Increase efficiency for an R simulator of the Monty Hall Puzzle

    - by jahan_m
    The Monty Hall Problem is a simple puzzle involving probability that even stumps professionals in careers dealing with some heavy-duty math. Here's the basic problem: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice? You can find numerous explanations of the solution here: http://en.wikipedia.org/wiki/Monty_Hall_problem Goal of my simulation: Prove that a switching strategy will win you the car 2/3 of the time. I got curious and wanted to write a little function that simulates the problem many times and returns the proportion of wins if you switched and the proportion of wins if you stayed with your first choice. The function then plots the cumulative wins. First and foremost, I'm interested in hearing if my simulation is indeed replicating the Monty Problem, or if some aspect of the code got it wrong. Secondly, this function takes a long time to run once I get to about 10,000 simulations. I know I don't need this many simulations to prove this but I'd love to hear some ideas on how to make it more efficient. Thanks for your feedback! Monty_Hall=function(repetitions){ doors=c('A','B','C') stay_wins=0 switch_wins=0 series=data.frame(sim_num=seq(repetitions),cum_sum_stay=replicate(repetitions,0),cum_sum_switch=replicate(repetitions,0)) for(i in seq(repetitions)){ winning_door=sample(doors,1) contestant_chooses=sample(doors,1) if(contestant_chooses==winning_door) stay_wins=stay_wins+1 else switch_wins=switch_wins+1 series[i,'cum_sum_stay']=stay_wins series[i,'cum_sum_switch']=switch_wins } plot(series$sim_num,series$cum_sum_switch,col=2,ylab='Cumulative # of wins', xlab='Simulation #',main=sprintf('%d Simulations of the Monty Hall Paradox',repetitions),type='l') lines(series$sim_num,series$cum_sum_stay,col=4) legend('topleft',legend=c('Cumulative wins from switching', 'Cumulative wins from staying'),col=c(2,4),lty=1) result=list(series=series,stay_wins=stay_wins,switch_wins=switch_wins, proportion_stay_wins=stay_wins/repetitions, proportion_switch_wins=switch_wins/repetitions) return(result) } #Theory predicts that it is to the contestant's advantage if he #switches his choice to the other door. This function simulates the game #many times, and shows you the proportion of games in which staying or #switching would win the car. It also plots the cumulative wins for each strategy. Monty_Hall(100)

    Read the article

  • Event sourcing: Write event before or after updating the model

    - by Magnus
    I'm reasoning about event sourcing and often I arrive at a chicken and egg problem. Would be grateful for some hints on how to reason around this. If I execute all I/O-bound processing async (ie writing to the event log) then how do I handle, or sometimes even detect, failures? I'm using Akka Actors so processing is sequential for each event/message. I do not have any database at this time, instead I would persist all the events in an event log and then keep an aggregated state of all the events in a model stored in memory. Queries are all against this model, you can consider it to be a cache. Example Creating a new user: Validate that the user does not exist in model Persist event to journal Update model (in memory) If step 3 breaks I still have persisted my event so I can replay it at a later date. If step 2 breaks I can handle that as well gracefully. This is fine, but since step 2 is I/O-bound I figured that I should do I/O in a separate actor to free up the first actor for queries: Updating a user while allowing queries (A0 = Front end/GUI actor, A1 = Processor Actor, A2 = IO-actor, E = event bus). (A0-E-A1) Event is published to update user 'U1'. Validate that the user 'U1' exists in model (A1-A2) Persist event to journal (separate actor) (A0-E-A1-A0) Query for user 'U1' profile (A2-A1) Event is now persisted continue to update model (A0-E-A1-A0) Query for user 'U1' profile (now returns fresh data) This is appealing since queries can be processed while I/O-is churning along at it's own pace. But now I can cause myself all kinds of problems where I could have two incompatible commands (delete and then update) be persisted to the event log and crash on me when replayed up at a later date, since I do the validation before persisting the event and then update the model. My aim is to have a simple reasoning around my model (since Actor processes messages sequentially single threaded) but not be waiting for I/O-bound updates when Querying. I get the feeling I'm modeling a database which in itself is might be a problem. If things are unclear please write a comment.

    Read the article

  • using replace to produce javascript code, django

    - by durdenk
    I want to use highcharts with my django site but it requires a comlex javascript code such as below. So I wanted to get this script in my python code and replace apropriate portions then write it in my template, first question is, is this a dump way to do that for a person not knowing javascript. I can read it tough. Second question is, Why I cant replace this string. Lets say this string is a variable like this. lineChartsTemplate = """ ... ... """ if I try and do lineChartsTemplate .replace('dataCategory', dataCategory) it basically suppossed to change dataCategory text with my dataCategory variable, but no such luck. I need guidance here. thx. $(function () { var chart = new Highcharts.Chart({ chart: { renderTo: 'container', type: 'bar' }, xAxis: { categories: dataCategory }, yAxis: { }, legend: { layout: 'vertical', floating: true, backgroundColor: '#FFFFFF', align: 'right', verticalAlign: 'top', y: 60, x: -60 }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ this.x +': '+ this.y; } }, plotOptions: { }, series: [{ data: dataList , name : 'Satislar'}] }); });

    Read the article

  • Displaying individual elements of an object in an Arraylist through a for loop?

    - by user1180888
    I'm trying to Display individual elements of an Object I have created. It is a simple Java program that allows users to add and keep track of Player Details. I'm just stumped when it comes to displaying the details after they have been added already. here is what my code looks like I can create the object and input it into the arraylist no problem using the case 2, but when I try to print it out I want to do something like System.out.println("Player Name" + myPlayersArrayList.PlayerName + "Player Position" + myPlayerArrayList.PlayerPosition + "Player Age" + "Player Age"); I know that is not correct, but I dont really know what to do, if anyone can be of any help it would be greatly appreciated. Thanks System.out.println("Welcome to the Football Player database"); System.out.print(System.getProperty("line.separator")); UserInput myFirstUserInput = new UserInput(); int selection; ArrayList<Player> myPlayersArrayList = new ArrayList<Player>(); while (true) { System.out.println("1. View The Players"); System.out.println("2. Add A Player"); System.out.println("3. Edit A Player"); System.out.println("4. Delete A Player"); System.out.println("5. Exit ") ; System.out.print(System.getProperty("line.separator")); selection = myFirstUserInput.getInt("Please select an option"); System.out.print(System.getProperty("line.separator")); switch(selection){ case 1: if (myPlayersArrayList.isEmpty()) { System.out.println("No Players Have Been Entered Yet"); System.out.print(System.getProperty("line.separator")); break;} else {for(int i = 0; i < myPlayersArrayList.size(); i++){ System.out.println(myPlayersArrayList); } break; case 2: { String playerName,playerPos; int playerAge; playerName = (myFirstUserInput.getString("Enter Player name")); playerPos = (myFirstUserInput.getString("Enter Player Position")); playerAge = (myFirstUserInput.getInt("Enter Player Age")); myPlayersArrayList.add(new Player(playerName, playerPos, playerAge)); ; break; }

    Read the article

  • What is wrong with this simple type definition? (Expecting one more argument to...)

    - by fluteflute
    basic.hs: areaCircle :: Floating -> Floating areaCircle r = pi * r * r Command: *Main> :l basic.hs [1 of 1] Compiling Main ( Sheet1.hs, interpreted ) Sheet1.hs:2:15: Expecting one more argument to `Floating' In the type signature for `areaCircle': areaCircle :: Floating -> Floating Failed, modules loaded: none. I see that areaCircle :: Floating a => a -> a loads as expected. Why is the above version not acceptable?

    Read the article

  • how to use store define in store folder

    - by Kevin Morfin
    I'm new to sencha-touch. I was wondering how to properly use the file structure in sencha-touch. For example, under the app folder there's your controller, model, profile, store, view folders. If I define a store, for example under the the store folder I create a file named search.js Ext.define('Volunteer.store.search'{ extend: 'Ext.data.Store', requires: ['Volunteer.model.person'], config:{ model: 'Volunteer.model.person' } }); How do I use this store in a different file?

    Read the article

  • T4MVC Optional Parameter Inferred From Current Context

    - by Itakou
    I have read the other post about this at T4MVC OptionalParameter values implied from current context and I am using the latest T4MVC (2.11.1) which is suppose to have the fix in. I even checked checked to make sure that it's there -- and it is. I am still getting the optional parameters filled in based on the current context. For example: Let's say I have a list that is by default ordered by a person's last name. I have the option to order by first name instead with the URL http://localhost/list/stuff?orderby=firstname When I am in that page, I want to go back to order by first name with the code: @Html.ActionLink("order by last name", MVC.List.Stuff(null)) the link I wanted was simply http://localhost/list/stuff without any parameters to keep the URL simple and short - invoking default behaviors within the action. But instead the orderby is kept and the url is still http://localhost/list/stuff?orderby=firstname Any help would be great. I know that in the most general cases, this does remove the query parameter - maybe I do have a specific case where it was not removed. I find that it only happens when I have the URL inside a page that I included with RenderPartial. My actual code is <li>@Html.ActionLink("Recently Updated", MVC.Network.Ticket.List(Model.UI.AccountId, "LastModifiedDate", null, null, null, null, null))</li> <li>@Html.ActionLink("Recently Created", MVC.Network.Ticket.List(Model.UI.AccountId, "CreatedDate", null, null, null, null, null))</li> <li>@Html.ActionLink("Most Severe", MVC.Network.Ticket.List(Model.UI.AccountId, "MostSevere", null, null, null, null, null))</li> <li>@Html.ActionLink("Previously Closed", MVC.Network.Ticket.List(Model.UI.AccountId, "LastModifiedDate", null, "Closed", null, null, null))</li> the problem happens when someone clicks Previously Closed and and go to ?status=closed. When they click Recently Updated, which I want to the ?status so that it shows the active ones, the ?status=closed stays. Any insight would be greatly appreciated.

    Read the article

  • Assigning unsigned char* buffer to a string

    - by CPPChase
    This question might be asked before but I couldn't find exactly what I need. My problem is, I have a buffer loaded by data downloaded from a webservice. The buffer is in unsigned char* form in which there is no '\0' at the end. Then I have a poco xml parser needs a string. I tried assigning it to string but now I realized it would cause problem such as leaking. here is the code: DOMParser::DOMParser(unsigned char* consatData, int consatDataSize, unsigned char* lagData, int lagDataSize) { Poco::XML::DOMParser parser; std::string consat; consat.assign((const char*) consatData, consatDataSize); pDoc = parser.parseString(consat); ParseConsat(); } Poco xml parser does have a ParseMemory which need a const char* and size of data but for some reason it just gives me segmentation fault. So I think it's safer to turn it to string. Thanks in advance.

    Read the article

  • How to Tweet from multiple acounts with twitter Gem in Rails?

    - by Jmlevick
    I have an application wich has Oauth access using Twitter as provider. I also have the ability to ask the logged user permisson to Read and Write in his/her account and once a user authorized the app, I can send tweets as the user with something like: u = User.find(id) u.twitter.update("Some-Status-Here") in the rails console... What I want to do is to Tweet as all the users in one command, but if I try something like: u = User.all u.twitter.update("Some-Status-Here") I get this error: undefined method `twitter' for #<Array:0x00000002e2f188> How can I tweet as all the users in one command? What am I doing wrong? I feel it is a very basic thing I'm missing... Can someone help me? Thank You.

    Read the article

  • SQL Query to return maximums over decades

    - by Abraham Lincoln
    My question is the following. I have a baseball database, and in that baseball database there is a master table which lists every player that has ever played. There is also a batting table, which tracks every players' batting statistics. I created a view to join those two together; hence the masterplusbatting table. CREATE TABLE `Master` ( `lahmanID` int(9) NOT NULL auto_increment, `playerID` varchar(10) NOT NULL default '', `nameFirst` varchar(50) default NULL, `nameLast` varchar(50) NOT NULL default '', PRIMARY KEY (`lahmanID`), KEY `playerID` (`playerID`), ) ENGINE=MyISAM AUTO_INCREMENT=18968 DEFAULT CHARSET=latin1; CREATE TABLE `Batting` ( `playerID` varchar(9) NOT NULL default '', `yearID` smallint(4) unsigned NOT NULL default '0', `teamID` char(3) NOT NULL default '', `lgID` char(2) NOT NULL default '', `HR` smallint(3) unsigned default NULL, PRIMARY KEY (`playerID`,`yearID`,`stint`), KEY `playerID` (`playerID`), KEY `team` (`teamID`,`yearID`,`lgID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; Anyway, my first query involved finding the most home runs hit every year since baseball began, including ties. The query to do that is the following.... select f.yearID, f.nameFirst, f.nameLast, f.HR from ( select yearID, max(HR) as HOMERS from masterplusbatting group by yearID )as x inner join masterplusbatting as f on f.yearID = x.yearId and f.HR = x.HOMERS This worked great. However, I now want to find the highest HR hitter in each decade since baseball began. Here is what I tried. select f.yearID, truncate(f.yearid/10,0) as decade,f.nameFirst, f.nameLast, f.HR from ( select yearID, max(HR) as HOMERS from masterplusbatting group by yearID )as x inner join masterplusbatting as f on f.yearID = x.yearId and f.HR = x.HOMERS group by decade You can see that I truncated the yearID in order to get 187, 188, 189 etc instead of 1897, 1885,. I then grouped by the decade, thinking that it would give me the highest per decade, but it is not returning the correct values. For example, it's giving me Adrian Beltre with 48 HR's in 2004 but everyone knows that Barry Bonds hit 73 HR in 2001. Can anyone give me some pointers?

    Read the article

  • getjson alternative method for variable

    - by Florian Stanek
    I made a script which gets the data from a json file and parse it. It worked on a webserver. But now I have to find a solution to get it work on a local file (file:///C:/xampp/htdocs/script/index.html) instead on a server. It only works in FF: $.getJSON('data2.json', function(data) { $.each(data.selection_form.entities, function(i,name){ ...do something }); }); Any ideas? A local webserver is not a solution.

    Read the article

  • Null reading in stream images? Unable to start activity ComponentInfo

    - by lasmith
    I have reviewed a lot of similar questions regarding not being able to launch an activity but they don't seem to quite match my problem. I am working on a simple black jack game but its force quitting. I suspect there is a problem with loading up the card png images I have. Stepping through the debugger it crashes right while in the resetGame() function. I'm sure I am doing something dumb. My Logcat: 10-15 20:21:43.309: E/AndroidRuntime(2863): FATAL EXCEPTION: main 10-15 20:21:43.309: E/AndroidRuntime(2863): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.smith.blackjack/com.smith.blackjack.Main}: java.lang.NullPointerException 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.ActivityThread.access$600(ActivityThread.java:130) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.os.Handler.dispatchMessage(Handler.java:99) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.os.Looper.loop(Looper.java:137) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.ActivityThread.main(ActivityThread.java:4745) 10-15 20:21:43.309: E/AndroidRuntime(2863): at java.lang.reflect.Method.invokeNative(Native Method) 10-15 20:21:43.309: E/AndroidRuntime(2863): at java.lang.reflect.Method.invoke(Method.java:511) 10-15 20:21:43.309: E/AndroidRuntime(2863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 10-15 20:21:43.309: E/AndroidRuntime(2863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-15 20:21:43.309: E/AndroidRuntime(2863): at dalvik.system.NativeStart.main(Native Method) 10-15 20:21:43.309: E/AndroidRuntime(2863): Caused by: java.lang.NullPointerException 10-15 20:21:43.309: E/AndroidRuntime(2863): at com.smith.blackjack.DeckOfCards.<init>(DeckOfCards.java:17) 10-15 20:21:43.309: E/AndroidRuntime(2863): at com.smith.blackjack.Main.resetGame(Main.java:98) 10-15 20:21:43.309: E/AndroidRuntime(2863): at com.smith.blackjack.Main.onCreate(Main.java:67) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.Activity.performCreate(Activity.java:5008) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 10-15 20:21:43.309: E/AndroidRuntime(2863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 10-15 20:21:43.309: E/AndroidRuntime(2863): ... 11 more My androidmanifest: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.smith.blackjack" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".Main" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> Here is my Main.java package com.smith.blackjack; import android.os.Bundle; import android.app.Activity; import android.content.res.AssetManager; import android.graphics.drawable.Drawable; import java.io.IOException; import java.io.InputStream; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class Main extends Activity { private ImageView dealerCard0; private ImageView dealerCard1; private ImageView dealerCard2; private ImageView dealerCard3; private ImageView playerCard0; private ImageView playerCard1; private ImageView playerCard2; private ImageView playerCard3; private ImageView imgResult; private Button btnDeal; private Button btnDraw; private Button btnHold; private DeckOfCards deckOfCards; private int[] dealerValues; private int dealerSum; private int dealerCardNumber; private int[] playerValues; private int playerSum; private int playerCardNumber; private InputStream dealerHiddenCard; private Card dealerCard; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); dealerCard0 = (ImageView) findViewById(R.id.dealerCard0); dealerCard1 = (ImageView) findViewById(R.id.dealerCard1); dealerCard2 = (ImageView) findViewById(R.id.dealerCard2); dealerCard3 = (ImageView) findViewById(R.id.dealerCard3); playerCard0 = (ImageView) findViewById(R.id.playerCard0); playerCard1 = (ImageView) findViewById(R.id.playerCard1); playerCard2 = (ImageView) findViewById(R.id.playerCard2); playerCard3 = (ImageView) findViewById(R.id.playerCard3); imgResult = (ImageView) findViewById(R.id.imgResult); btnDeal = (Button) findViewById(R.id.deal); btnDraw = (Button) findViewById(R.id.draw); btnHold = (Button) findViewById(R.id.hold); btnDeal.setOnClickListener(btnDealListener); btnDraw.setOnClickListener(btnDrawListener); btnHold.setOnClickListener(btnHoldListener); resetGame(); } private void resetGame(){ AssetManager assets = getAssets(); dealerValues = new int[4]; playerValues = new int[4]; dealerSum = 0; playerSum = 0; dealerCardNumber = 0; playerCardNumber = 0; for (int i = 0; i < 4; i++) { dealerValues[i] = 0; playerValues[i] = 0; } try { InputStream stream = assets.open("cardback.png"); // stream = assets.open("cardback.png"); Drawable cardImage = Drawable.createFromStream(stream, null); dealerCard0.setImageDrawable(cardImage); dealerCard1.setImageDrawable(cardImage); dealerCard2.setImageDrawable(cardImage); dealerCard3.setImageDrawable(cardImage); playerCard0.setImageDrawable(cardImage); playerCard1.setImageDrawable(cardImage); playerCard2.setImageDrawable(cardImage); playerCard3.setImageDrawable(cardImage); imgResult.setImageDrawable(cardImage); deckOfCards = new DeckOfCards(); deckOfCards.shuffle(); assets.close(); } catch (IOException e){ Log.e("Reset Game", "Error Loading", e); } } public OnClickListener btnDealListener = new OnClickListener() { // @Override public void onClick(View v) { try { AssetManager assets = getAssets(); InputStream stream; // first player card Card newCard; newCard = deckOfCards.dealCard(); playerValues[playerCardNumber] = newCard.faceValue; playerCardNumber++; stream = assets.open(newCard.File); Drawable cardImage = Drawable.createFromStream(stream, newCard.File); playerCard0.setImageDrawable(cardImage); assets.close(); // second player card newCard = deckOfCards.dealCard(); playerValues[playerCardNumber] = newCard.faceValue; playerCardNumber++; stream = assets.open(newCard.File); cardImage = Drawable.createFromStream(stream, newCard.File); playerCard1.setImageDrawable(cardImage); assets.close(); // first dealer card hidden newCard = deckOfCards.dealCard(); dealerCard = newCard; dealerValues[dealerCardNumber] = newCard.faceValue; dealerCardNumber++; dealerHiddenCard = assets.open(newCard.File); stream = assets.open("cardback.png"); cardImage = Drawable.createFromStream(stream, "cardback"); dealerCard0.setImageDrawable(cardImage); assets.close(); // second dealer card open newCard = deckOfCards.dealCard(); dealerValues[dealerCardNumber] = newCard.faceValue; dealerCardNumber++; stream = assets.open(newCard.File); cardImage = Drawable.createFromStream(stream, newCard.File); dealerCard1.setImageDrawable(cardImage); assets.close(); } catch (IOException e){ Log.e("Deal", "Error Loading", e); } }; }; public OnClickListener btnDrawListener = new OnClickListener() { // @Override public void onClick(View v) { try { AssetManager assets = getAssets(); InputStream stream; // get next player card Card newCard; newCard = deckOfCards.dealCard(); playerValues[playerCardNumber] = newCard.faceValue; playerCardNumber++; stream = assets.open(newCard.File); Drawable cardImage = Drawable.createFromStream(stream, newCard.File); switch (playerCardNumber){ case 3: playerCard2.setImageDrawable(cardImage); case 4: playerCard3.setImageDrawable(cardImage); } assets.close(); } catch (IOException e){ Log.e("Draw", "Error Loading", e); } }; }; public OnClickListener btnHoldListener = new OnClickListener() { // @Override public void onClick(View v) { Drawable cardImage; // evaluate player hand playerSum = evaluate(playerValues); if (playerSum > 21){ // player losses } // flip over the dealer hidden card cardImage = Drawable.createFromStream(dealerHiddenCard, dealerCard.File); Card newCard; InputStream stream; AssetManager assets = getAssets(); for (int i=2; i<4; i++){ dealerSum = evaluate(dealerValues); if (dealerSum < 16 ) { newCard = deckOfCards.dealCard(); dealerValues[dealerCardNumber] = newCard.faceValue; dealerCardNumber++; try { stream = assets.open(newCard.File); cardImage = Drawable.createFromStream(stream, newCard.File); switch (dealerCardNumber){ case 3: dealerCard2.setImageDrawable(cardImage); case 4: dealerCard3.setImageDrawable(cardImage); } assets.close(); } catch (IOException e){ Log.e("Draw", "Error Loading", e); } if (dealerSum < playerSum) { // player wins } if (dealerSum > playerSum){ // dealer wins } if (dealerSum == playerSum){ // it is a draw } } } }; }; public int evaluate (int[]values) { int sumCards = 0; for (int i = 0; i < 4; i++){ sumCards += values[i]; } if (sumCards > 21) { for (int i = 0; i < 4; i++){ if (values[i] == 11) { values[i] = 1; sumCards -= 10; continue; } } } return sumCards; } } My DeckOfCards class: package com.smith.blackjack; import java.util.Random; public class DeckOfCards { private Card [] deck; private int currentCard; private static final int NUMBER_OF_CARDS = 52; private static final Random randomNumbers = new Random(); public DeckOfCards () { deck = new Card[NUMBER_OF_CARDS]; currentCard = 0 ; for(int count = 0; count < deck.length; count++) { deck[count].faceValue = count + 1; } } public void shuffle () { currentCard = 0; for (int first = 0; first < deck.length; first ++){ int second = randomNumbers.nextInt(NUMBER_OF_CARDS); int temp = deck[first].faceValue; deck[first].faceValue=deck[second].faceValue; deck[second].faceValue = temp; } } public Card dealCard(){ Card temp = new Card(); temp.faceValue = 0; temp.File = ""; if(currentCard < deck.length) { temp.faceValue = deck[currentCard].faceValue / 4; int suit = deck[currentCard].faceValue % 4; String suitString = ""; switch (suit){ case 0: suitString = "c"; case 1: suitString = "d"; case 2: suitString = "h"; case 3: suitString = "s"; } Integer face = temp.faceValue / 4 ; String faceString = face.toString(); temp.File = faceString + suitString + ".png"; switch (temp.faceValue){ case 11: temp.faceValue = 10; case 12: temp.faceValue = 10; case 13: temp.faceValue = 10; } return temp; } else return temp; } }

    Read the article

  • How Do I Setup the Notepad++ Run Command for Ruby?

    - by EstanislaoStan
    I'm trying to setup the Notepad++ IDE so that when I press F6 the Ruby script I'm editing will run. After searching the internet I've found that putting [cmd /K ruby "$(FULL_CURRENT_PATH)"] without the brackets into the run dialogue box that pops up when I press F5 will run basic scripts in the Command Prompt (I'm using Windows 7). However, if my code loads any external data such as .txt files, or as I've found with Gosu, loads any image files, Ruby complains that things do not exist which do in fact exist. I know my code and Ruby installation (Ruby 1.9.3) are fine because prior to now I've been using FreeRIDE, an older, somewhat buggy IDE that I've grown tired of, and my code runs fine when I press F5 using that IDE. Some examples of the complaints follow. My Text Adventure: C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Fold er/Ruby Scripts/Text Adventure/0.1.0/File Parser/DungeonContentFileParser.rb:8:i n `initialize': No such file or directory - Example Dungeon Creator File.txt (Er rno::ENOENT) from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Text Adventure/0.1.0/File Parser/DungeonContentFile Parser.rb:8:in `open' from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Text Adventure/0.1.0/File Parser/DungeonContentFile Parser.rb:8:in `encapsulate_method' from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Text Adventure/0.1.0/File Parser/DungeonContentFile Parser.rb:117:in `sort_room_data_external_method' from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Text Adventure/0.1.0/File Parser/DungeonContentFile Parser.rb:125:in `<main>' D:\Programming Stuff\Notepad++> My Gosu Program: C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Fold er/Ruby Scripts/Game Development/Circular Motion.rb:10:in `initialize': Could no t load image media/Space2.png using either GDI+ or FreeImage: Unknown error (Run timeError) from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Game Development/Circular Motion.rb:10:in `new' from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Game Development/Circular Motion.rb:10:in `initiali ze' from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Game Development/Circular Motion.rb:181:in `new' from C:/Users/Estanislao/Dropbox/Allway Sync/My Important Documents/Text Focused Folder/Ruby Scripts/Game Development/Circular Motion.rb:181:in `<main>' D:\Programming Stuff\Notepad++> If anyone could lend any help at all I'd really appreciate it.

    Read the article

  • Using AVG() in Oracle SQL

    - by Viet Anh
    I have a table named Student as followed: CREATE TABLE "STUDENT" ( "ID" NUMBER(*,0), "NAME" VARCHAR2(20), "AGE" NUMBER(*,0), "CITY" VARCHAR2(20), PRIMARY KEY ("ID") ENABLE ) I am trying to get all the records of the students having a larger age than the average age. This is what I tried: SELECT * FROM student WHERE age > AVG(age) and SELECT * FROM student HAVING age > AVG(age) Both ways did not work!

    Read the article

  • Updating iOS application content which include images

    - by azamsharp
    I am working on a Vegetable gardening application. Apart from the vegetable name and description I also have vegetable image. Currently, I have all the images in the Supported Files folder in the Xcode project. But later on I want to update the application dynamically without having the user download a new version. When the user updates the application or downloads new data from the server that data will include the images. Can I store those images in the supporting file folder or somewhere where they can be references by just the name. RELATED QUESTION: I will also allow the user to take pictures of their vegetables and then write notes about the vegetables like "just planted", "about to harvest" etc. What is the recommended approach for storing pictures/photos. I can always store them in the user's photo library and then store the reference in the local database and then fetch and display the picture using the reference. The problem with that approach might be that if the user accidentally deletes the picture from the library then it will no longer be displayed in my application. The only way I see if to store the picture in the app local database as a BLOB.

    Read the article

  • Can an XML prolog contain custom information?

    - by DaveJohnston
    Is it legal to add additional custom information somewhere in an XML prolog? For example, in my case, I would like to add an indicator of which serialiser version was used to create the XML, so that clients receiving the XML could automatically select the correct corresponding de-serialiser. I could add the information as an attribute of the root tag, but I thought it would be cleaner to add the information in the prolog, like the standard XML version: <?xml version="1.0"?> something like: <?serialiser version="1.0"?> or is the prolog reserved purely for those things specified by W3C?

    Read the article

  • cakephp hasMany through and multiselect form

    - by Zoran Kalinic
    I'm using cakephp 2.2.2 and I have a problem with the editing view Models and relationships are: Person hasMany OrganizationPerson Organization hasMany OrganizationPerson OrganizationPerson belongs to Person,Organization A basic hasMany through relationship as found within cake documentation. Tables are: people (id,...) organizations (id,...) organization_people (id, person_id,organization_id,...) In the person add and edit forms there is a select box allowing a user to select multiple organization. The problem I have is, when a user edits an existing person, the associated organizations aren't pre-selected. Here is the code in the PeopleController: $organizations = $this->Person->OrganizationPerson->Organization->find('list'); $this->set(compact('organizations')); Related part of the code in the People/edit code looks like: $this->Form->input('OrganizationPerson.organization_id', array('multiple' => true, 'empty' => false)); This will populate the select field, but it does not pre-select it with the Person's associated organizations. Format and content of the $this-data: Array ( [Person] => Array ( [id] => 1 ... ) [OrganizationPerson] => Array ( [0] => Array ( [id] => 1 [person_id] => 1 [organization_id] => 1 ... ) [1] => Array ( [id] => 2 [person_id] => 1 [organization_id] => 2 ... ) ) ) What I have to add/change in the code to get pre-selected organizations? Thanks in advance!

    Read the article

  • Enabling depth testing when using CAOpenGLLayer

    - by Andrew
    If one is using a subclass of NSOpenGLView then one enables depth testing by selecting a 16/24/32 bit buffer from the attributes menu in Xcode, and then adding glEnable(GL_DEPTH_TEST); glClear(GL_DEPTH_BUFFER_BIT); to the drawRect method. However, in the application I'm creating I'm rendering OpenGL content via the drawInCGLContext method of a CAOpenGLLayer which is contained within a subclass of NSView. This means that it is no longer possible to create a depth buffer via the inspector. Does anyone know how I can achieve this in such a situation?

    Read the article

  • MvvmCross experiences, hindsight, limitations?

    - by Jason Steele
    I am considering using the MvvmCross framework for a cross platform mobile application that will target Android, iPhone and WP7. Does anyone have any experience with this framework they would like to share, and are they aware of any constraints or limitations that it would be useful to be aware of? For example, am I still able to use native page transitions of my choosing? Are there any performance or storage (app size) implications?

    Read the article

  • GTK#-related error on MonoDevelop 2.8.5 on Ubuntu 11.04

    - by Mehrdad
    When I try to create a new solution in MonoDevelop 2.8.5 in Ubuntu 11.04 x64, it shows me: System.ArgumentNullException: Argument cannot be null. Parameter name: path1 at System.IO.Path.Combine (System.String path1, System.String path2) [0x00000] in <filename unknown>:0 at MonoDevelop.Core.FilePath.Combine (System.String[] paths) [0x00000] in <filename unknown>:0 at MonoDevelop.Projects.ProjectCreateInformation.get_BinPath () [0x00000] in <filename unknown>:0 at MonoDevelop.Projects.DotNetProject..ctor (System.String languageName, MonoDevelop.Projects.ProjectCreateInformation projectCreateInfo, System.Xml.XmlElement projectOptions) [0x00000] in <filename unknown>:0 at MonoDevelop.Projects.DotNetAssemblyProject..ctor (System.String languageName, MonoDevelop.Projects.ProjectCreateInformation projectCreateInfo, System.Xml.XmlElement projectOptions) [0x00000] in <filename unknown>:0 at MonoDevelop.Projects.DotNetProjectBinding.CreateProject (System.String languageName, MonoDevelop.Projects.ProjectCreateInformation info, System.Xml.XmlElement projectOptions) [0x00000] in <filename unknown>:0 at MonoDevelop.Projects.DotNetProjectBinding.CreateProject (MonoDevelop.Projects.ProjectCreateInformation info, System.Xml.XmlElement projectOptions) [0x00000] in <filename unknown>:0 at MonoDevelop.Projects.ProjectService.CreateProject (System.String type, MonoDevelop.Projects.ProjectCreateInformation info, System.Xml.XmlElement projectOptions) [0x00000] in <filename unknown>:0 at MonoDevelop.Ide.Templates.ProjectDescriptor.CreateItem (MonoDevelop.Projects.ProjectCreateInformation projectCreateInformation, System.String defaultLanguage) [0x00000] in <filename unknown>:0 at MonoDevelop.Ide.Templates.ProjectTemplate.HasItemFeatures (MonoDevelop.Projects.SolutionFolder parentFolder, MonoDevelop.Projects.ProjectCreateInformation cinfo) [0x00000] in <filename unknown>:0 at MonoDevelop.Ide.Projects.NewProjectDialog.SelectedIndexChange (System.Object sender, System.EventArgs e) [0x00000] in <filename unknown>:0 I strace'd it and saw repeated failed accesses to files like: /usr/lib/mono/gac/gtk-sharp/2.12.0.0__35e10195dab3c99f/libgtk-x11-2.0.so.0.la so I'm assuming that's the cause of the problem. However, I've installed (and re-installed) anything GTK#-related that I could think of... and the error still occurs. Does anyone know how to fix it?

    Read the article

  • Using capistrano to deploy from different git branches

    - by Toms Mikoss
    I am using capistrano to deploy a RoR application. The codebase is in a git repository, and branching is widely used in development. Capistrano uses deploy.rb file for it's settings, one of them being the branch to deploy from. My problem is this: let's say I create a new branch A from master. The deploy file will reference master branch. I edit that, so A can be deployed to test environment. I finish working on the feature, and merge branch A into master. Since the deploy.rb file from A is fresher, it gets merged in and now the deploy.rb in master branch references A. Time to edit again. That's a lot of seemingly unnecessary manual editing - the parameter should always match current branch name. On top of that, it is easy to forget to edit the settings each and every time. What would be the best way to automate this process? Edit: Turns out someone already had done exactly what I needed.

    Read the article

  • Sample Browser for Visual Studio 2012!

    - by pluginbaby
    Remember the "All-In-One Code Framework", a set of cool code samples available on CodePlex ? Well, the same team along with MSDN just released a Sample Browser Visual Studio Extension for Visual Studio 2012 and Visual Studio 2010. The Sample Browser Visual Studio Extension allows developers to search and download 3500+ code samples from within Visual Studio 2012 and Visual Studio 2010. If you are into Windows 8 dev like me, you’ll be happy to know that it already offers samples for WinRT with XAML and C#. Installation: http://visualstudiogallery.msdn.microsoft.com/4934b087-e6cc-44dd-b992-a71f00a2a6df

    Read the article

  • XSF-FO intellisense and national languages with Apache FOP

    - by Lukasz Kurylo
    Some time ago I showed how to get an intellisense and how to configure the FO.NET to acquire national characters inside the generated pdf files. Due to the limitations that I mensioned in my previous post, I started playing with the Apache FOP. In this post I want to show, how to acquire the same result as I showed in the two posts related to FO.NET.   Intellisense   To get the intellisense from the XSL-FO templates set the xsi:schemaLocation the same way I showed it in this post. The only diffrence to FO.NET is that, during generating the document by the code I showed last time we will get an exception:   org.apache.fop.fo.ValidationException: Invalid property encountered on "fo:root": xsi:schemaLocation (See position 6:11)   Fortunatelly there is a very easy way to resolve this without removing the entire attribute along with the intellisense. Add to the FopFactory the ignoreNamespace by:   FopFactory fopFactory = FopFactory.newInstance(); fopFactory.ignoreNamespace(http://www.w3.org/2001/XMLSchema-instance);   Notice that, the url specified in this method this is a namespace for the xmlns:xsi namespace, not xsi.schemaLocation.   Fonts / national characters   This point is a little dfferent to acquire, but not more complicated that it was with FO.NET. To set the fonts in Apache FOP 1.0, we need a configuration file. A sample one can be get from the directory where we unpacked the fop binaries, from conf subdirectory. There is a file called fop.xconf. We must copy this file to our solution. In the simplest way, in the <fonts> tag we can add  <auto-detect/>. Thanks to this, FOP will index all fonts available on the installed operating system. There probably should be no problem, if we have a http handler or a WCF Service on the server that serves the generated pdf documents. In this situation we can use all available fonts on this server.   To use this config file, we must set a path to it:   FopFactory fopFactory = FopFactory.newInstance(); fopFactory.setUserConfig(new File("fop.xconf"));

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >