Search Results

Search found 592 results on 24 pages for 'rolling stones'.

Page 3/24 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Original object is also changed when values of cloned object are changed.

    - by fari
    I am trying to use clone but the original object is also changed when values of cloned object are changed. As you can see KalaGameState does not use any objects so a shallow copy should work. /** * This class represents the current state of a Kala game, including * which player's turn it is along with the state of the board; i.e. the * numbers of stones in each side pit, and each player's 'kala'). */ public class KalaGameState implements Cloneable { // your code goes here private int turn; private int[] sidePit; private boolean game; public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // This should never happen throw new InternalError(e.toString()); } } /** * Constructs a new GameState with a specified number of stones in each * player's side pits. * @param startingStones the number of starting stones in each side pit. * @throws InvalidStartingStonesException if startingStones not in the range 1-10. */ public KalaGameState(int startingStones) throws InvalidStartingStonesException { game=true; turn=0; sidePit=new int[14]; for (int i=0; i <= 13 ; i++) { sidePit[i] = startingStones; } sidePit[6] =0; sidePit[13] =0; // your code goes here } /** * Returns the ID of the player whose turn it is. * @return A value of 0 = Player A, 1 = Player B. */ public int getTurn() { return turn; // your code goes here } /** * Returns the current kala for a specified player. * @param playerNum A value of 0 for Player A, 1 for Player B. * @throws IllegalPlayerNumException if the playerNum parameter * is not 0 or 1. */ public int getKala(int playerNum) throws IllegalPlayerNumException { if(playerNum!=0 || playerNum!=1) throw new IllegalPlayerNumException(playerNum); if(playerNum==0) return sidePit[6]; else return sidePit[13]; // your code goes here } /** * Returns the current number of stones in the specified pit for * the player whose turn it is. * @param sidePitNum the side pit being queried in the range 1-6. * @throws IllegalSidePitNumException if the sidePitNum parameter. * is not in the range 1-6. */ public int getNumStones(int sidePitNum) throws IllegalSidePitNumException { if(turn==0) { if(sidePitNum>6 ) throw new IllegalSidePitNumException(sidePitNum); } else if(sidePitNum>12) throw new IllegalSidePitNumException(sidePitNum); if(turn==0) return sidePit[sidePitNum]; else return sidePit[sidePitNum+6]; // your code goes here } /** * Returns the current number of stones in the specified pit for a specified player. * @param playerNum the player whose kala is sought. (0 = Player A, 1 = Player B). * @param sidePitNum the side pit being queried (in the range 1-6). * @throws IllegalPlayerNumException if the playerNum parameter is not 0 or 1. * @throws IllegalSidePitNumException if the sidePitNum parameter is not in the * range 1-6. */ public int getNumStones(int playerNum, int sidePitNum) throws IllegalPlayerNumException, IllegalSidePitNumException { /*if(playerNum>2) throw new IllegalPlayerNumException(playerNum); if(turn==0) { if(sidePitNum>6 ) throw new IllegalSidePitNumException(sidePitNum); } else if(sidePitNum>12) throw new IllegalSidePitNumException(sidePitNum); */ if(playerNum==0) return sidePit[sidePitNum]; else if(playerNum==1) return sidePit[sidePitNum+7]; else return sidePit[sidePitNum]; } /** * Returns the current score for a specified player - the player's * kala plus the number of stones in each of their side pits. * @param playerNum the player whose kala is sought. (0 = Player A, 1 = Player B). * @throws IllegalPlayerNumException if the playerNum parameter is not 0 or 1. */ public int getScore(int playerNum) throws IllegalPlayerNumException { if(playerNum>1) throw new IllegalPlayerNumException(playerNum); int score=0; if(playerNum==0) { for(int i=0;i<=5;i++) score=score+sidePit[i]; score=score+sidePit[6]; } else { for(int i=7;i<=12;i++) score=score+sidePit[i]; score=score+sidePit[13]; } // your code goes here return score; } private int getSidePitArrayIndex(int sidePitNum) throws IllegalSidePitNumException { if(turn==0) { if(sidePitNum>6 ) throw new IllegalSidePitNumException(sidePitNum); } else if(sidePitNum>12) throw new IllegalSidePitNumException(sidePitNum); if(turn==0) { return sidePitNum--; } else { return sidePitNum+6; } } public boolean gameOver() { int stone=0; if(turn==0) for(int i=0;i<=5;i++) stone=stone+getNumStones(i); else for(int i=7;i<=12;i++) stone=stone+getNumStones(i-7); if (stone==0) game=false; return game; } /** * Makes a move for the player whose turn it is. * @param sidePitNum the side pit being queried (should be in the range 1-6) * @throws IllegalSidePitNumException if the sidePitNum parameter is not in the range 1-6. * @throws IllegalMoveException if the side pit is empty and has no stones in it. */ public void makeMove(int sidePitNum) throws IllegalSidePitNumException, IllegalMoveException { if(turn==0) { if(sidePitNum>6 ) throw new IllegalSidePitNumException(sidePitNum); } else if(sidePitNum>12) throw new IllegalSidePitNumException(sidePitNum); /* if(turn==0) { if(sidePit[sidePitNum-1]==0) throw new IllegalMoveException(sidePitNum); } else { if(sidePit[sidePitNum-1+7]==0) throw new IllegalMoveException(sidePitNum); } */ sidePitNum--; int temp=sidePitNum; int pitNum=sidePitNum+1; int stones=getNumStones(turn,sidePitNum); if(turn==0) sidePit[sidePitNum]=0; else { sidePitNum=sidePitNum+7; sidePit[sidePitNum]=0; pitNum=pitNum+7; } while(stones!=0) { if(turn==0) { sidePit[pitNum]=sidePit[pitNum]+1; stones--; pitNum++; if(pitNum==13) pitNum=0; } else { sidePit[pitNum]=sidePit[pitNum]+1; stones--; pitNum++; if(pitNum==6) pitNum=7; else if(pitNum==14) pitNum=0; } } boolean res=anotherTurn(pitNum); if(!res){ capture(pitNum,temp); if(turn==0) turn=1; else turn=0;} } private boolean anotherTurn(int pitNum) {pitNum--; boolean temp=false; if(turn==0) {if(pitNum==6) {turn=0; temp=true; } } else if(pitNum==-1) {turn=1; temp=true; } return temp; } private void capture(int pitNum, int pit) { pitNum--; if(turn==0){ if(sidePit[pitNum]==1 && pitNum<6) { if(pitNum==0) { sidePit[6]=sidePit[6]+sidePit[12]+1; sidePit[12]=0; } else if(pitNum==1) { sidePit[6]=sidePit[6]+sidePit[11]+1; sidePit[11]=0; } else if(pitNum==2) { sidePit[6]=sidePit[6]+sidePit[10]+1; sidePit[10]=0; } else if(pitNum==3) { sidePit[6]=sidePit[6]+sidePit[9]+1; sidePit[9]=0; } else if(pitNum==4) { sidePit[6]=sidePit[6]+sidePit[8]+1; sidePit[8]=0; } else if(pitNum==5) { sidePit[6]=sidePit[6]+sidePit[7]+1; sidePit[7]=0; } sidePit[pitNum]=0; } } if(turn==1) { //pitNum=pitNum; if(sidePit[pitNum]==1 && pit+7>6) { if(pitNum==7) { sidePit[13]=sidePit[13]+sidePit[5]+1; sidePit[7]=0; } else if(pitNum==8) { sidePit[13]=sidePit[13]+sidePit[4]+1; sidePit[4]=0; } else if(pitNum==9) { sidePit[13]=sidePit[13]+sidePit[3]+1; sidePit[3]=0; } else if(pitNum==10) { sidePit[13]=sidePit[13]+sidePit[2]+1; sidePit[2]=0; } else if(pitNum==11) { sidePit[13]=sidePit[13]+sidePit[1]+1; sidePit[1]=0; } else if(pitNum==12) { sidePit[13]=sidePit[13]+sidePit[0]+1; sidePit[0]=0; } sidePit[pitNum]=0; } } } } import java.io.BufferedReader; import java.io.InputStreamReader; public class RandomPlayer extends KalaPlayer{ //KalaGameState state; public int chooseMove(KalaGameState gs) throws NoMoveAvailableException {int[] moves; moves=getMoves(gs); try{ for(int i=0;i<=5;i++) System.out.println(moves[i]); for(int i=0;i<=5;i++) { if(moves[i]==1) { KalaGameState state=(KalaGameState) gs.clone(); state.makeMove(moves[i]); gs.getTurn(); moves[i]=evalValue(state.getScore(0),state.getScore(1)); } } } catch(IllegalMoveException e) { System.out.println(e); //chooseMove(state); } return 10; } private int evalValue(int score0,int score1) { int score=0; //int score0=0; // int score1=0; //getScore(0); //score1=state.getScore(1); //if((state.getTurn())==0) score=score1-score0; //else //score=score1-score0; System.out.println("score: "+score); return score; } public int[] getMoves(KalaGameState gs) { int[] moves=new int[6]; for(int i=1;i<=6;i++) { if(gs.getNumStones(i)!=0) moves[i-1]=1; else moves[i-1]=0; } return moves; } } Can you explain what is going wrong, please?

    Read the article

  • SQL Server rolling forward lots of transactions, what should I look at?

    - by Anthony D
    I am running SQL Server Express on a Windows XP Embedded box. It runs for a day or two, doing some transactional processing for a POS type system, and with another system pulling data out to an OLAP DB for processing. After a while, I see in the event viewer the sequence SQL Server puts out when it restarts, copy rights, command line parameters, and so on. It seems like that coincides with our OLAP process crashing. I then see that when it restarts our transaction DB, it does a recovery, pulling in 10K or so in transactions that need to be rolled forward. Does this mean SQL has crashed? I don't really see much to indicate what happened. Update 1 I noticed I have my memory limit set to 1MB per query and 2TB for the server. These are the defaults. I only have one GB in the box. We have seen SQL crash a whole box by just using all the system memory. In this case though the whole box is up when we get to it.

    Read the article

  • Simple way to implement computer-go board in Java

    - by codingbear
    I want to make a simple Go board to design an Computer Go game. In a go game, you lie a "stone" (white or black) on a position where horizontal and vertical lines intersect. What are some simple ways to restrict users from placing their stones in other locations? Maybe I'm just not seeing a simple solution. EDIT I guess I should rephrase my question better: I want to know how to do the background image of Go board, so that I can lie my stones on the intersection of the horizontal and the vertical lines. I was thinking about getting a just regular Go board image, and when I'm actually rendering stones, I find right position of pixels to lie stones. However, that solution did not seem to be the best solution, since I need to worry about size of stone images and think about proportionality when I either expand or shrink the board window.

    Read the article

  • An algorithm for pavement usage calculation

    - by student
    Given an area of specific size I need to find out how many pavement stones to use to completely pave the area. Suppose that I have an empty floor of 100 metre squares and stones with 20x10 cm and 30x10 cm sizes. I must pave the area with minimum usage of stones of both sizes. Anyone knows of an algorithm that calculates this? (Sorry if my English is bad) C# is preferred.

    Read the article

  • Compute weighted averages for large numbers

    - by Travis
    I'm trying to get the weighted average of a few numbers. Basically I have: Price - 134.42 Quantity - 15236545 There can be as few as one or two or as many as fifty or sixty pairs of prices and quantities. I need to figure out the weighted average of the price. Basically, the weighted average should give very little weight to pairs like Price - 100000000.00 Quantity - 3 and more to the pair above. The formula I currently have is: ((price)(quantity) + (price)(quantity) + ...)/totalQuantity So far I have this done: double optimalPrice = 0; int totalQuantity = 0; double rolling = 0; System.out.println(rolling); Iterator it = orders.entrySet().iterator(); while(it.hasNext()) { System.out.println("inside"); Map.Entry order = (Map.Entry)it.next(); double price = (Double)order.getKey(); int quantity = (Integer)order.getValue(); System.out.println(price + " " + quantity); rolling += price * quantity; totalQuantity += quantity; System.out.println(rolling); } System.out.println(rolling); return totalQuantity / rolling; The problem is I very quickly max out the "rolling" variable. How can I actually get my weighted average? Thanks!

    Read the article

  • log4j.xml configuration with <rollingPolicy> and <triggeringPolicy>

    - by Mike Smith
    I try to configure log4j.xml in such a way that file will be rolled upon file size, and the rolled file's name will be i.e: "C:/temp/test/test_log4j-%d{yyyy-MM-dd-HH_mm_ss}.log" I followed this discussion: http://web.archiveorange.com/archive/v/NUYyjJipzkDOS3reRiMz Finally it worked for me only when I add: try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } to the method: public boolean isTriggeringEvent(Appender appender, LoggingEvent event, String filename, long fileLength) which make it works. The question is if there is a better way to make it work? since this method call many times and slow my program. Here is the code: package com.mypack.rolling; import org.apache.log4j.rolling.RollingPolicy; import org.apache.log4j.rolling.RolloverDescription; import org.apache.log4j.rolling.TimeBasedRollingPolicy; /** * Same as org.apache.log4j.rolling.TimeBasedRollingPolicy but acts only as * RollingPolicy and NOT as TriggeringPolicy. * * This allows us to combine this class with a size-based triggering policy * (decision to roll based on size, name of rolled files based on time) * */ public class CustomTimeBasedRollingPolicy implements RollingPolicy { TimeBasedRollingPolicy timeBasedRollingPolicy = new TimeBasedRollingPolicy(); /** * Set file name pattern. * @param fnp file name pattern. */ public void setFileNamePattern(String fnp) { timeBasedRollingPolicy.setFileNamePattern(fnp); } /* public void setActiveFileName(String fnp) { timeBasedRollingPolicy.setActiveFileName(fnp); }*/ /** * Get file name pattern. * @return file name pattern. */ public String getFileNamePattern() { return timeBasedRollingPolicy.getFileNamePattern(); } public RolloverDescription initialize(String file, boolean append) throws SecurityException { return timeBasedRollingPolicy.initialize(file, append); } public RolloverDescription rollover(String activeFile) throws SecurityException { return timeBasedRollingPolicy.rollover(activeFile); } public void activateOptions() { timeBasedRollingPolicy.activateOptions(); } } package com.mypack.rolling; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.Appender; import org.apache.log4j.rolling.TriggeringPolicy; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; /** * Copy of org.apache.log4j.rolling.SizeBasedTriggeringPolicy but able to accept * a human-friendly value for maximumFileSize, eg. "10MB" * * Note that sub-classing SizeBasedTriggeringPolicy is not possible because that * class is final */ public class CustomSizeBasedTriggeringPolicy implements TriggeringPolicy, OptionHandler { /** * Rollover threshold size in bytes. */ private long maximumFileSize = 10 * 1024 * 1024; // let 10 MB the default max size /** * Set the maximum size that the output file is allowed to reach before * being rolled over to backup files. * * <p> * In configuration files, the <b>MaxFileSize</b> option takes an long * integer in the range 0 - 2^63. You can specify the value with the * suffixes "KB", "MB" or "GB" so that the integer is interpreted being * expressed respectively in kilobytes, megabytes or gigabytes. For example, * the value "10KB" will be interpreted as 10240. * * @param value * the maximum size that the output file is allowed to reach */ public void setMaxFileSize(String value) { maximumFileSize = OptionConverter.toFileSize(value, maximumFileSize + 1); } public long getMaximumFileSize() { return maximumFileSize; } public void setMaximumFileSize(long maximumFileSize) { this.maximumFileSize = maximumFileSize; } public void activateOptions() { } public boolean isTriggeringEvent(Appender appender, LoggingEvent event, String filename, long fileLength) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } boolean result = (fileLength >= maximumFileSize); return result; } } and the log4j.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true"> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c -> %m%n" /> </layout> </appender> <appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender"> <param name="file" value="C:/temp/test/test_log4j.log" /> <rollingPolicy class="com.mypack.rolling.CustomTimeBasedRollingPolicy"> <param name="fileNamePattern" value="C:/temp/test/test_log4j-%d{yyyy-MM-dd-HH_mm_ss}.log" /> </rollingPolicy> <triggeringPolicy class="com.mypack.rolling.CustomSizeBasedTriggeringPolicy"> <param name="MaxFileSize" value="200KB" /> </triggeringPolicy> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c -> %m%n" /> </layout> </appender> <logger name="com.mypack.myrun" additivity="false"> <level value="debug" /> <appender-ref ref="FILE" /> </logger> <root> <priority value="debug" /> <appender-ref ref="console" /> </root> </log4j:configuration>

    Read the article

  • PostgreSQL: Rolling back a transaction within a plpgsql function?

    - by jamieb
    Coming from the MS SQL world, I tend to make heavy use of stored procedures. I'm currently writing an application uses a lot of PostgreSQL plpgsql functions. What I'd like to do is rollback all INSERTS/UPDATES contained within a particular function if I get an exception at any point within it. I was originally under the impression that each function is wrapped in it's own transaction and that an exception would automatically rollback everything. However, that doesn't seem to be the case. I'm wondering if I ought to be using savepoints in combination with exception handling instead? But I don't really understand the difference between a transaction and a savepoint to know if this is the best approach. Any advice please? CREATE OR REPLACE FUNCTION do_something( _an_input_var int ) RETURNS bool AS $$ DECLARE _a_variable int; BEGIN INSERT INTO tableA (col1, col2, col3) VALUES (0, 1, 2); INSERT INTO tableB (col1, col2, col3); VALUES (0, 1, 'whoops! not an integer'); -- The exception will cause the function to bomb, but the values -- inserted into "tableA" are not rolled back. RETURN True; END; $$ LANGUAGE plpgsql;

    Read the article

  • What issues to consider when rolling your own data-backend for Silverlight / AJAX on non-ASP.NET ser

    - by Edward Tanguay
    I have read-only Silverlight and AJAX apps which read static text and XML files from a PHP/Apache server, which works very nicely with features such as asynchronous loading, lazy-loading only what I need for each page, loading in the background, developed a little query language to get a PHP script to create custom XML files etc. it's pragmatic read-only REST, and all works fast and fine for read-only sites. Now I want to also add the ability to write data from these apps to a database on the same PHP/Apache server. For those of you who have built similar data-access layers, what do I need to consider while building this, especially regarding security so that not just any client can write and alter my database, e.g.: check HTTP_USER_AGENT for security check REMOTE_ADDR for security require a special code for security, perhaps a list of TAN codes (such as banks use for online transactions) each which can only be used once, both the client and server have these I wonder if there is some kind of standard REST query I should lean on for e.g. building SQL-like statements in the URL parameters, e.g. http://www.thedatalayersite.com/query?insertinto=customers&... Any thoughts, notes from experience, ideas, gotchas, especially ideas on tightening down security in this endeavor would be helpful.

    Read the article

  • Rolling back a git tree, fully or partially (single file) how to?

    - by Tzury Bar Yochay
    On a given server, I have a set of daemons each of which has its own configuration file. I would like to use git to manage the configuration files editing during time and always have the option to rollback to the "factory defaults" in regards to all files or a specific one. For instance, given the following structure: $ ls -l total 0 -rw-r--r-- 1 tzury tzury 0 2011-01-05 06:36 bar.conf -rw-r--r-- 1 tzury tzury 0 2011-01-05 06:36 baz.conf -rw-r--r-- 1 tzury tzury 0 2011-01-05 06:36 foo.conf Assuming all those .conf files are stored in a git repository, I want to be able to restore all files into their original shape (that would be the first git commit). Yet, I would also like to be able to rollback a specific file to the factory defaults, while others remain up to date.

    Read the article

  • Writing a custom wpf 'rolling' plot control (are there any components with such functionality?)

    - by adrin
    I need a wpf plot control that would 'roll' (scroll) as data is fed to it (instead of stretching, etc). Unfortunately i didnt find a working component so now I am considering writing my own control (its plotting features need to be simple). Did anyone write a custom plot/chart control? Is it difficult? What container should I use (Canvas & ViewBox?) so that it is reasonably fast, easy to write and scales as window is resized?

    Read the article

  • Code to generate random numbers in C++

    - by user1678927
    Basically I have to write a program to generate random numbers to simulate the rolling of a pair of dice. This program should be constructed in multiple files. The main function should be in one file, the other functions should be in a second source file, and their prototypes should be in a header file. First I write a short function that returns a random value between 1 and 6 to simulate the rolling of a single 6-sided die.Second, i write a function that pretends to roll a pair of dice by calling this function twice. My program starts by asking the user how many rolls should be made. Then I write a function to simulate rolling the dice this many times, keeping a count of exactly how many times the values 2,3,4,5,6,7,8,9,10,11,12(each number is the sum of a pair of dice) occur in an array. Later I write a function to display a small bar chart using these counts that ideally would look something like below for a sample of 144 rolls, where the number of asterisks printed corresponds to the count: 2 3 4 5 6 7 8 9 10 11 12 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Next, to see how well the random number generator is doing, I write a function to compute the average value rolled. Compare this to the ideal average of 7. Also, print out a small table showing the counts of each roll made by the program, the ideal count based on the frequencies above given the total number of rolls, and the difference between these values in separate columns. This is my incomplete code so far: "Compiler visual studio 2010" int rolling(){ //Function that returns a random value between 1 and 6 rand(unsigned(time(NULL))); int dice = 1 + (rand() %6); return dice; } int roll_dice(int num1,int num2){ //it calls 'rolling function' twice int result1,result2; num1 = rolling(); num2 = rolling(); result1 = num1; result2 = num2; return result1,result2; } int main(void){ int times,i,sum,n1,n2; int c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11;//counters for each sum printf("Please enter how many times you want to roll the dice.\n") scanf_s("%i",&times); I pretend to use counters to count each sum and store the number(the count) in an array. I know i need a loop (for) and some conditional statements (if) but m main problem is to get the values from roll_dice and store them in n1 and n2 so then i can sum them up and store the sum in 'sum'.

    Read the article

  • I am getting exception in main thread...even when i am handling the exception

    - by fari
    public KalaGame(KeyBoardPlayer player1,KeyBoardPlayer player2) { //super(0); int key=0; try { do{ System.out.println("Enter the number of stones to play with: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); key = Integer.parseInt(br.readLine()); if(key<0 || key>10) throw new InvalidStartingStonesException(key); } while(key<0 || key>10); player1=new KeyBoardPlayer(); player2 = new KeyBoardPlayer(); this.player1=player1; this.player2=player2; state=new KalaGameState(key); } catch(IOException e) { System.out.println(e); } } when i enter an invalid number of stones i get this error Exception in thread "main" InvalidStartingStonesException: The number of starting stones must be greater than 0 and less than or equal to 10 (attempted 22) why isn't the exception handled by the throw i defined at KalaGame.<init>(KalaGame.java:27) at PlayKala.main(PlayKala.java:10)

    Read the article

  • Programming Contest Question: Counting Polyominos

    - by Martijn Courteaux
    Hi, An example question for a programming contest was to write a program that finds out how much polyominos are possible with a given number of stones. So for two stones (n = 2) there is only one polyominos: XX You might think this is a second solution: X X But it isn't. The polyominos are not unique if you can rotate them. So, for 4 stones (n = 4), there are 7 solutions: X X XX X X X X X X XX X XX XX XX X X X XX X X XX The application has to be able to find the solution for 1 <= n <=10 PS: Using the list of polyominos on Wikipedia isn't allowed ;) EDIT: Of course the question is: How to do this in Java, C/C++, C#

    Read the article

  • What exactly is an invalid HTTP_HOST header

    - by rolling stone
    I've implemented Django's relatively new allowed hosts setting, which is meant to prevent attackers from submitting requests with a fake HTTP Host header. Since adding that setting, I now get anywhere from 20-100 emails a day notifying me of invalid HTTP_HOST headers. I've copied in an example of a typical error message below. I'm hosting my site on EC2, and am relatively new to setting up/maintaining a server, so my question is what exactly is happening here, and what is the best way to manage these invalid and I assume malicious requests? [Django] ERROR: Invalid HTTP_HOST header: 'www.launchastartup.com'.You may need to add u'www.launchastartup.com' to ALLOWED_HOSTS.

    Read the article

  • Logging Application Block

    - by Gordon Carpenter-Thompson
    I'm using the Logging Application Block in my ASP.NET application and want to convert the application to a Sharepoint WebPart. It all works fine as long as I change: <trust level="WSS_Minimal" originUrl="" /> to <trust level="Full" originUrl="" /> If not I get an exception in the logs: Failed to add webpart *************255Fcatalogs%252Fwp%252FSearchWebPart%252Ewebpart;SearchWebPart. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Logging.Logger' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Logging.Logger' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource' threw an exception. ---> System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neut... ...ral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.AppDomainSetup.VerifyDir(String dir, Boolean normalize) at System.AppDomainSetup.get_ConfigurationFile() at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSourceImplementation..ctor(Boolean refresh) at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource..cctor() The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.FileIOPermission The first permission that failed was: <IPermission class="System.Security.Permissions.FileIOPermi... ...ssion, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" PathDiscovery="D:\Inetpub\wwwroot\wss\VirtualDirectories\8686\web.config"/> The demand was for: <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" PathDiscovery="D:\Inetpub\wwwroot\wss\VirtualDirectories\8686\web.config"/> The granted set of the failing assembly was: <PermissionSet class="System.Security.PermissionSet" version="1"> <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Execution"/> <IPermission class="System.Security.Permissions.StrongNameIdentityPermis... ...sion, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100257FAE170ABB2AB4A8EF914DFEA757F7DB8C221F01850FC8753A4C6585C0B07749DA33DF4D64A721A070E7CDCDEFC8C786E3626418389BCF461E4300E6F4C477BE5CE64AD12C29D517208D6BA627D9F73A9066B7638BE1FEE3EABE6C3E537B546CB3B5DE5E436F95278BB1E9DBDE85C2A6B624010A8073841D467CC7A0A0C6C8" Name="Microsoft.Practices.EnterpriseLibrary.Common" AssemblyVersion="3.1.0.0"/> <IPermission class="System.Security.Permissions.UrlIdentityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Url="file:///D:/Inetpub/wwwroot/wss/VirtualDirectories/8686/bin/Microsoft.Practices.EnterpriseLibrary.Common.DLL"/> <IPe... ...rmission class="System.Security.Permissions.ZoneIdentityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Zone="MyComputer"/> <IPermission class="System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Level="Minimal"/> <IPermission class="Microsoft.SharePoint.Security.WebPartPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" version="1" Connections="True"/> </PermissionSet> The assembly or AppDomain that failed was: Microsoft.Practices.EnterpriseLibrary.Common, Version=3.1.0.0, Culture=neutral, PublicKeyToken=a646907c4a695009 The Zone of the assembly that failed was: MyComputer The Url of the assem... ...bly that failed was: file:///D:/Inetpub/wwwroot/wss/VirtualDirectories/8686/bin/Microsoft.Practices.EnterpriseLibrary.Common.DLL --- End of inner exception stack trace --- at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource..ctor() at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceFactory.Create() at Microsoft.Practices.EnterpriseLibrary.Logging.Logger..cctor() --- End of inner exception stack trace --- at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(LogEntry log) at com.okana.sharepoint.SearchWebPart.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Control.AddedControl(Control control, Int32 index) at System.Web.UI.ControlCollection.Add(Con... ...trol child) at System.Web.UI.WebControls.WebParts.WebPartManager.WebPartManagerControlCollection.AddWebPartHelper(WebPart webPart) at System.Web.UI.WebControls.WebParts.WebPartManager.WebPartManagerControlCollection.AddWebPart(WebPart webPart) at System.Web.UI.WebControls.WebParts.WebPartManager.AddWebPart(WebPart webPart) at System.Web.UI.WebControls.WebParts.WebPartManagerInternals.AddWebPart(WebPart webPart) at Microsoft.SharePoint.WebPartPages.SPWebPartManager.AddWebPartWithRetry(WebPart webPart) at Microsoft.SharePoint.WebPartPages.SPWebPartManager.AddDynamicWebPart(WebPart webPart) at Microsoft.SharePoint.WebPartPages.SPWebPartManager.LoadWebPart(WebPart aspWebPart, String zoneId, Int32 zoneIndex, Boolean isClosed) at Microsoft.SharePoint.WebPartPages.... ...SPWebPartManager.AddWebPartInternalShared(WebPart webPart) at Microsoft.SharePoint.WebPartPages.SPWebPartManager.AddWebPartInternal(SPSupersetWebPart superset, Boolean throwIfLocked) --- End of inner exception stack trace --- at Microsoft.SharePoint.WebPartPages.SPWebPartManager.AddWebPartInternal(SPSupersetWebPart superset, Boolean throwIfLocked) at Microsoft.SharePoint.WebPartPages.SPWebPartManager.AddWebPartInternal(SPSupersetWebPart superset) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) My log configuration is this: <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true"> <listeners> <add fileName="XAE.log" rollSizeKB="0" timeStampPattern="yyyy-MM-dd" rollFileExistsBehavior="Overwrite" rollInterval="Day" formatter="Text Formatter" header="" footer="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral" traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral" name="Rolling Flat File Trace Listener" /> <add fileName="IDOL.log" rollSizeKB="0" timeStampPattern="yyyy-MM-dd" rollFileExistsBehavior="Overwrite" rollInterval="Day" formatter="Text Formatter" header="" footer="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral" traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral" name="IDOL Rolling Flat File Trace Listener" /> </listeners> <formatters> <add template="{timestamp(local)} : {category} : {message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral" name="Text Formatter" /> </formatters> <categorySources> <!-- For any log entries that you wish to suppress set "All" to "Off" --> <add switchValue="All" name="Communication"> <listeners> <add name="Rolling Flat File Trace Listener" /> </listeners> </add> <add switchValue="All" name="Debug"> <listeners> <add name="Rolling Flat File Trace Listener" /> </listeners> </add> <add switchValue="All" name="Exception"> <listeners> <add name="Rolling Flat File Trace Listener" /> </listeners> </add> <add switchValue="All" name="General"> <listeners> <add name="Rolling Flat File Trace Listener" /> </listeners> </add> <add switchValue="All" name="Warning"> <listeners> <add name="Rolling Flat File Trace Listener" /> </listeners> </add> <add switchValue="All" name="IDOL"> <listeners> <add name="IDOL Rolling Flat File Trace Listener" /> </listeners> </add> </categorySources> <specialSources> <allEvents switchValue="All" name="All Events" /> <notProcessed switchValue="All" name="Unprocessed Category" /> <errors switchValue="All" name="Logging Errors &amp; Warnings"> <listeners> <add name="Rolling Flat File Trace Listener" /> </listeners> </errors> </specialSources> </loggingConfiguration> Clearly this is because it's trying to create the log files and WSS_Minimal doesn't allow this. Is there a simple way to disable all logging for now? Removing the logging is problematic as it's used in the underlying libraries. I have tried setting all switchValue="All" to "Off" but it still throws the exception even though nothing should be logged

    Read the article

  • Get application names with specific permission

    - by rolling.stones
    I want list of all applications installed on the device which use a specific permission like INTERNET. i am using this code , but not able to retrieve results , please help . private ArrayList<String> getInstalledApps(Context context) { ArrayList<String> results = new ArrayList<String>(); PackageManager packageManager = context.getPackageManager(); List<PackageInfo> applist = packageManager.getInstalledPackages(0); Iterator<PackageInfo> it = applist.iterator(); while (it.hasNext()) { PackageInfo pk = (PackageInfo) it.next(); if (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(Manifest.permission.INTERNET, pk.packageName)) results.add("" + pk.applicationInfo.loadLabel(packageManager)); } for (int i = 0; i <= results.size(); i++) { Log.v("app using internet = ", results.toString()); } return results; } Thanks in advance. Any help accepted :)

    Read the article

  • SQL SERVER – How to Roll Back SQL Server Database Changes

    - by Pinal Dave
    In a perfect scenario, no unexpected and unplanned changes occur. There are no unpleasant surprises, no inadvertent changes. However, even with all precautions and testing, there is sometimes a need to revert a structure or data change. One of the methods that can be used in this situation is to use an older database backup that has the records or database object structure you want to revert to. For this method, you have to have the adequate full database backup and a tool that will help you with comparison and synchronization is preferred. In this article, we will focus on another method: rolling back the changes. This can be done by using: An option in SQL Server Management Studio T-SQL, or ApexSQL Log The first two solutions have been described in this article The disadvantages of these methods are that you have to know when exactly the change you want to revert happened and that all transactions on the database executed in a specific time range are rolled back – the ones you want to undo and the ones you don’t. How to easily roll back SQL Server database changes using ApexSQL Log? The biggest challenge is to roll back just specific changes, not all changes that happened in a specific time range. While SQL Server Management Studio option and T-SQL read and roll forward all transactions in the transaction log files, I will show you a solution that finds and scripts only the specific changes that match your criteria. Therefore, you don’t need to worry about all other database changes that you don’t want to roll back. ApexSQL Log is a SQL Server disaster recovery tool that reads transaction logs and provides a wide range of filters that enable you to easily rollback only specific data changes. First, connect to the online database where you want to roll back the changes. Once you select the database, ApexSQL Log will show its recovery model. Note that changes can be rolled back even for a database in the Simple recovery model, when no database and transaction log backups are available. However, ApexSQL Log achieves best results when the database is in the Full recovery model and you have a chain of subsequent transaction log backups, back to the moment when the change occurred. In this example, we will use only the online transaction log. In the next step, use filters to read only the transactions that happened in a specific time range. To remove noise, it’s recommended to use as many filters as possible. Besides filtering by the time of the transaction, ApexSQL Log can filter by the operation type: Table name: As well as transaction state (committed, aborted, running, and unknown), name of the user who committed the change, specific field values, server process IDs, and transaction description. You can select only the tables affected by the changes you want to roll back. However, if you’re not certain which tables were affected, you can leave them all selected and once the results are shown in the main grid, analyze them to find the ones you to roll back. When you set the filters, you can select how to present the results. ApexSQL Log can automatically create undo or redo scripts, export the transactions into an XML, HTML, CSV, SQL, or SQL Bulk file, and create a batch file that you can use for unattended transaction log reading. In this example, I will open the results in the grid, as I want to analyze them before rolling back the transactions. The results contain information about the transaction, as well as who and when made it. For UPDATEs, ApexSQL Log shows both old and new values, so you can easily see what has happened. To create an UNDO script that rolls back the changes, select the transactions you want to roll back and click Create undo script in the menu. For the DELETE statement selected in the screenshot above, the undo script is: INSERT INTO [Sales].[PersonCreditCard] ([BusinessEntityID], [CreditCardID], [ModifiedDate]) VALUES (297, 8010, '20050901 00:00:00.000') When it comes to rolling back database changes, ApexSQL Log has a big advantage, as it rolls back only specific transactions, while leaving all other transactions that occurred at the same time range intact. That makes ApexSQL Log a good solution for rolling back inadvertent data and schema changes on your SQL Server databases. Reference: Pinal Dave (http://blog.sqlauthority.com)Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL Tagged: ApexSQL

    Read the article

  • Where are my date ranges in Analytics coming from?

    - by Jeffrey McDaniel
    In the P6 Reporting Database there are two main tables to consider when viewing time - W_DAY_D and W_Calendar_FS.  W_DAY_D is populated internally during the ETL process and will provide a row for every day in the given time range. Each row will contain aspects of that day such as calendar year, month, week, quarter, etc. to allow it to be used in the time element when creating requests in Analytics to group data into these time granularities. W_Calendar_FS is used for calculations such as spreads, but is also based on the same set date range. The min and max day_dt (W_DAY_D) and daydate (W_Calendar_FS) will be related to the date range defined, which is a start date and a rolling interval plus a certain range. Generally start date plus 3 years.  In P6 Reporting Database 2.0 this date range was defined in the Configuration utility.  As of P6 Reporting Database 3.0, with the introduction of the Extended Schema this date range is set in the P6 web application. The Extended Schema uses this date range to calculate the data for near real time reporting in P6.  This same date range is validated and used for the P6 Reporting Database.  The rolling date range means if today is April 1, 2010 and the rolling interval is set to three years, the min date will be 1/1/2010 and the max date will be 4/1/2013.  1/1/2010 will be the min date because we always back fill to the beginning of the year. On April 2nd, the Extended schema services are run and the date range is adjusted there to move the max date forward to 4/2/2013.  When the ETL process is run the Reporting Database will pick up this change and also adjust the max date on the W_DAY_D and W_Calendar_FS. There are scenarios where date ranges affecting areas like resource limit may not be adjusted until a change occurs to cause a recalculation, but based on general system usage these dates in these tables will progress forward with the rolling intervals. Choosing a large date range can have an effect on the ETL process for the P6 Reporting Database. The extract portion of the process will pull spread data over into the STAR. The date range defines how long activity and resource assignment spread data is spread out in these tables. If an activity lasts 5 days it will have 5 days of spread data. If a project lasts 5 years, and the date range is 3 years the spread data after that 3 year date range will be bucketed into the last day in the date range. For the overall project and even the activity level you will still see the correct total values.  You just would not be able to see the daily spread 5 years from now. This is an important question when choosing your date range, do you really need to see spread data down to the day 5 years in the future?  Generally this amount of granularity years in the future is not needed. Remember all those values 5, 10, 15, 20 years in the future are still available to report on they would be in more of a summary format on the activity or project.  The data is always there, the level of granularity is the decision.

    Read the article

  • Bitbucket and a small development house

    - by Marlon
    I am in the process of finally rolling Mercurial as our version control system at work. This is a huge deal for everyone as, shockingly, they have never used a VCS. After months of putting the bug in management's ears, they finally saw the light and now realise how much better it is than working with a network of shared folders! In the process of rolling this out, I am thinking of different strategies to manage our stuff and I am leaning towards using Bitbucket as our "central" repository. The projects in Bitbucket will solely be private projects and everyone will push and pull from there. I am open to different suggestions, but has anyone got a similar setup? If so, what caveats have you encountered?

    Read the article

  • Bitbucket and a small development house

    - by Marlon
    I am in the process of finally rolling Mercurial as our version control system at work. This is a huge deal for everyone as, shockingly, they have never used a VCS. After months of putting the bug in management's ears, they finally saw the light and now realise how much better it is than working with a network of shared folders! In the process of rolling this out, I am thinking of different strategies to manage our stuff and I am leaning towards using Bitbucket as our "central" repository. The projects in Bitbucket will solely be private projects and everyone will push and pull from there. I am open to different suggestions, but has anyone got a similar setup? If so, what caveats have you encountered?

    Read the article

  • Crash/Instance Recovery?Media Recovery?????

    - by Liu Maclean(???)
    Crash/Instance Recovery?Media Recovery???????: Crash/Instance Recovery???????????????(incremental checkpoint)??apply redo??????????????????????????logfile switch checkpoint,?????????????????????,????crash/instance recovery???????????????????????(online redo logfile)? ????Media Recovery????????????apply redo??????,???????????????? ?????????????????,??RMAN?DBA(???????)?????????????????? Crash/Instance Recovery??????????????????????????? ?Oracle??????????????????????,??????????????? ??,??????????(incomplete recovery)?????(partial recovery)???,????????(db)??????????? Crash/Instance Recovery?Media Recovery??????: Crash/Instance Recovery?Media Recovery???????????(rolling forward),????????redo log?????? ???Crash/Instance Recovery??Media Recovery???,????????????????????,???????????????????????,????????????????????????? ????: ????????SMON??(?):Recover Dead transaction????Oracle????rolling forward(?)????????SMON??(?):Instance Recovery

    Read the article

  • Text indent after the first line in a paragraph

    - by bobo
    - A Reuters reporter in Surkhrod district in Nangarhar province, where villagers said the raids took place, said Afghan police fired at the crowd after some of them started throwing stones at local government buildings. <p> - A Reuters reporter in Surkhrod district in Nangarhar province, where villagers said the raids took place, said Afghan police fired at the crowd after some of them started throwing stones at local government buildings.</p> In the above paragraph, I would like to use CSS to make all lines after the first line to automatically indent some space so that each line stays right after the - in the first line. It's similar to a list item with list position set to outside, but I don't want to use a list. What is the simplest way you can think of to achieve this effect? Less extra html markups will be better. Many thanks to you all.

    Read the article

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