Search Results

Search found 499 results on 20 pages for 'bird jaguar iv'.

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

  • Java enums: Gathering info from another enums

    - by Samuel Carrijo
    I made a similar question a few days ago, but now I have new requirements, and new challenges =). As usual, I'm using the animal enums for didactic purposes, once I don't want to explain domain-specific stuff I have a basic enum of animals, which is used by the whole zoo (I can add stuff to it, but must keep compatibility): public enum Animal { DOG, ELEPHANT, WHALE, SHRIMP, BIRD, GIRAFFE; } I need to categorize them in a few, non-related categories, like gray animals (whale (my whale is gray) and elephant), small animals (bird, shrimp and dog), sea animals (whale and shrimp). I could, as suggested in my previous questions, add a lot of booleans, like isGray, isSmall and isFromSea, but I'd like an approach where I could keep this somewhere else (so my enum doesn't need to know much). Something like: public enum Animal { DOG, ELEPHANT, WHALE, SHRIMP, BIRD, GIRAFFE; public boolean isGray() { // What comes here? } } Somewhere else public enum GrayAnimal { WHALE, ELEPHANT; } How is this possible? Am I requesting too much from Java?

    Read the article

  • General String Encryption in .NET

    - by cryptospin
    I am looking for a general string encryption class in .NET. (Not to be confused with the 'SecureString' class.) I have started to come up with my own class, but thought there must be a .NET class that already allows you to encrypt/decrypt strings of any encoding with any Cryptographic Service Provider. Public Class SecureString Private key() As Byte Private iv() As Byte Private m_SecureString As String Public ReadOnly Property Encrypted() As String Get Return m_SecureString End Get End Property Public ReadOnly Property Decrypted() As String Get Return Decrypt(m_SecureString) End Get End Property Public Sub New(ByVal StringToSecure As String) If StringToSecure Is Nothing Then StringToSecure = "" m_SecureString = Encrypt(StringToSecure) End Sub Private Function Encrypt(ByVal StringToEncrypt As String) As String Dim result As String = "" Dim bytes() As Byte = Text.Encoding.UTF8.GetBytes(StringToEncrypt) Using provider As New AesCryptoServiceProvider() With provider .Mode = CipherMode.CBC .GenerateKey() .GenerateIV() key = .Key iv = .IV End With Using ms As New IO.MemoryStream Using cs As New CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(bytes, 0, bytes.Length) cs.FlushFinalBlock() End Using result = Convert.ToBase64String(ms.ToArray()) End Using End Using Return result End Function Private Function Decrypt(ByVal StringToDecrypt As String) As String Dim result As String = "" Dim bytes() As Byte = Convert.FromBase64String(StringToDecrypt) Using provider As New AesCryptoServiceProvider() Using ms As New IO.MemoryStream Using cs As New CryptoStream(ms, provider.CreateDecryptor(key, iv), CryptoStreamMode.Write) cs.Write(bytes, 0, bytes.Length) cs.FlushFinalBlock() End Using result = Text.Encoding.UTF8.GetString(ms.ToArray()) End Using End Using Return result End Function End Class

    Read the article

  • RiverTrail - JavaScript GPPGU Data Parallelism

    - by JoshReuben
    Where is WebCL ? The Khronos WebCL working group is working on a JavaScript binding to the OpenCL standard so that HTML 5 compliant browsers can host GPGPU web apps – e.g. for image processing or physics for WebGL games - http://www.khronos.org/webcl/ . While Nokia & Samsung have some protype WebCL APIs, Intel has one-upped them with a higher level of abstraction: RiverTrail. Intro to RiverTrail Intel Labs JavaScript RiverTrail provides GPU accelerated SIMD data-parallelism in web applications via a familiar JavaScript programming paradigm. It extends JavaScript with simple deterministic data-parallel constructs that are translated at runtime into a low-level hardware abstraction layer. With its high-level JS API, programmers do not have to learn a new language or explicitly manage threads, orchestrate shared data synchronization or scheduling. It has been proposed as a draft specification to ECMA a (known as ECMA strawman). RiverTrail runs in all popular browsers (except I.E. of course). To get started, download a prebuilt version https://github.com/downloads/RiverTrail/RiverTrail/rivertrail-0.17.xpi , install Intel's OpenCL SDK http://www.intel.com/go/opencl and try out the interactive River Trail shell http://rivertrail.github.com/interactive For a video overview, see  http://www.youtube.com/watch?v=jueg6zB5XaM . ParallelArray the ParallelArray type is the central component of this API & is a JS object that contains ordered collections of scalars – i.e. multidimensional uniform arrays. A shape property describes the dimensionality and size– e.g. a 2D RGBA image will have shape [height, width, 4]. ParallelArrays are immutable & fluent – they are manipulated by invoking methods on them which produce new ParallelArray objects. ParallelArray supports several constructors over arrays, functions & even the canvas. // Create an empty Parallel Array var pa = new ParallelArray(); // pa0 = <>   // Create a ParallelArray out of a nested JS array. // Note that the inner arrays are also ParallelArrays var pa = new ParallelArray([ [0,1], [2,3], [4,5] ]); // pa1 = <<0,1>, <2,3>, <4.5>>   // Create a two-dimensional ParallelArray with shape [3, 2] using the comprehension constructor var pa = new ParallelArray([3, 2], function(iv){return iv[0] * iv[1];}); // pa7 = <<0,0>, <0,1>, <0,2>>   // Create a ParallelArray from canvas.  This creates a PA with shape [w, h, 4], var pa = new ParallelArray(canvas); // pa8 = CanvasPixelArray   ParallelArray exposes fluent API functions that take an elemental JS function for data manipulation: map, combine, scan, filter, and scatter that return a new ParallelArray. Other functions are scalar - reduce  returns a scalar value & get returns the value located at a given index. The onus is on the developer to ensure that the elemental function does not defeat data parallelization optimization (avoid global var manipulation, recursion). For reduce & scan, order is not guaranteed - the onus is on the dev to provide an elemental function that is commutative and associative so that scan will be deterministic – E.g. Sum is associative, but Avg is not. map Applies a provided elemental function to each element of the source array and stores the result in the corresponding position in the result array. The map method is shape preserving & index free - can not inspect neighboring values. // Adding one to each element. var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.map(function inc(v) {     return v+1; }); //<2,3,4,5,6> combine Combine is similar to map, except an index is provided. This allows elemental functions to access elements from the source array relative to the one at the current index position. While the map method operates on the outermost dimension only, combine, can choose how deep to traverse - it provides a depth argument to specify the number of dimensions it iterates over. The elemental function of combine accesses the source array & the current index within it - element is computed by calling the get method of the source ParallelArray object with index i as argument. It requires more code but is more expressive. var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.combine(function inc(i) { return this.get(i)+1; }); reduce reduces the elements from an array to a single scalar result – e.g. Sum. // Calculate the sum of the elements var source = new ParallelArray([1,2,3,4,5]); var sum = source.reduce(function plus(a,b) { return a+b; }); scan Like reduce, but stores the intermediate results – return a ParallelArray whose ith elements is the results of using the elemental function to reduce the elements between 0 and I in the original ParallelArray. // do a partial sum var source = new ParallelArray([1,2,3,4,5]); var psum = source.scan(function plus(a,b) { return a+b; }); //<1, 3, 6, 10, 15> scatter a reordering function - specify for a certain source index where it should be stored in the result array. An optional conflict function can prevent an exception if two source values are assigned the same position of the result: var source = new ParallelArray([1,2,3,4,5]); var reorder = source.scatter([4,0,3,1,2]); // <2, 4, 5, 3, 1> // if there is a conflict use the max. use 33 as a default value. var reorder = source.scatter([4,0,3,4,2], 33, function max(a, b) {return a>b?a:b; }); //<2, 33, 5, 3, 4> filter // filter out values that are not even var source = new ParallelArray([1,2,3,4,5]); var even = source.filter(function even(iv) { return (this.get(iv) % 2) == 0; }); // <2,4> Flatten used to collapse the outer dimensions of an array into a single dimension. pa = new ParallelArray([ [1,2], [3,4] ]); // <<1,2>,<3,4>> pa.flatten(); // <1,2,3,4> Partition used to restore the original shape of the array. var pa = new ParallelArray([1,2,3,4]); // <1,2,3,4> pa.partition(2); // <<1,2>,<3,4>> Get return value found at the indices or undefined if no such value exists. var pa = new ParallelArray([0,1,2,3,4], [10,11,12,13,14], [20,21,22,23,24]) pa.get([1,1]); // 11 pa.get([1]); // <10,11,12,13,14>

    Read the article

  • Android gallery widget should never end

    - by Faisal khan
    Following code display the Gallery items. Gallery g = (Gallery) findViewById(R.id.icon_gallery); ImageAdapter iv = new ImageAdapter(this); g.setAdapter(iv); // line dispalys default selection center of the image. g.setSelection(iv.getCount()/2, true); There are 5 images i added in imageAdapter. displaying 3rd image in the center. When user drag gallery from left to right or right to left it stops after 2 item scroll i want this scroll to never finish it should start start cycle again once cycle finish. how can i do it ?

    Read the article

  • Android camera to take multiple photos

    - by user2975407
    problem.java public class problem extends Activity { ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.problem); iv=(ImageView) findViewById(R.id.imageView1); Button b=(Button) findViewById(R.id.button1); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 0); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); Bitmap bm=(Bitmap) data.getExtras().get("data"); iv.setImageBitmap(bm); } } From this code I can only take one photo and it displayed in the screen. **But I want to take more photos nearly 5 photos and display in the screen** Further I want to add these photos to MySQL database.please help me to do that.I am new to android

    Read the article

  • Create image from scratch with JMagick

    - by Michael IV
    I am using Java port of ImageMagick called JMagick .I need to be able to create a new image and write an arbitrary text chunk into it.The docs are very poor and what I managed to get so far is to write text into the image which comes from IO.Also , in all the examples I have found it seems like the very first operation ,before writing new image data , is always loading of an existing image into ImageInfo instance.How do I create an image from scratch with JMagick and then write a text into it? Here is what I do now : try { ImageInfo info = new ImageInfo(); info.setSize("512x512"); info.setUnits(ResolutionType.PixelsPerInchResolution); info.setColorspace(ColorspaceType.RGBColorspace); info.setBorderColor(PixelPacket.queryColorDatabase("red")); info.setDepth(8); BufferedImage img = new BufferedImage(512,512,BufferedImage.TYPE_4BYTE_ABGR); byte[] imageBytes = ((DataBufferByte) img.getData().getDataBuffer()).getData(); MagickImage mimage = new MagickImage(info,imageBytes); DrawInfo aInfo = new DrawInfo(info); aInfo.setFill(PixelPacket.queryColorDatabase("green")); aInfo.setUnderColor(PixelPacket.queryColorDatabase("yellow")); aInfo.setOpacity(0); aInfo.setPointsize(36); aInfo.setFont("Arial"); aInfo.setTextAntialias(true); aInfo.setText("JMagick Tutorial"); aInfo.setGeometry("+40+40"); mimage.annotateImage(aInfo); mimage.setFileName("text.jpg"); mimage.writeImage(info); } catch (MagickException ex) { Logger.getLogger(LWJGL_IDOMOO_SIMPLE_TEST.class.getName()).log(Level.SEVERE, null, ex); } It doesn't work , the JVM crashes with access violation as it probably expects for the input image from IO.

    Read the article

  • How to center align background image in JPanel

    - by Jaguar
    I wanted to add background image to my JFrame. Background image means I can later add Components on the JFrame or JPanel Although I coudn't find how to add background image to a JFrame, I found out how to add background image to a JPanel from here: How to set background image in Java? This solved my problem, but now since my JFrame is resizable I want to keep the image in center. The code I found uses this method public void paintComponent(Graphics g) { //Draw the previously loaded image to Component. g.drawImage(img, 0, 0, null); //Draw image } Can anyone say how to align the image to center of the JPanel. As g.drawImage(img, 0, 0, null); provides x=0 and y=0 Also if there is a method to add background image to a JFrame then I would like to know. Thanks.

    Read the article

  • "Security Warning" comes up when I run via another program

    - by Alexander Bird
    If I execute vmmap from the command line it works fine. However, if I call some other program and pass vmmap as a paramater for this other program to start the execution, then I get this "security error" popup -- which makes it hard to automate scripts. In other words, I want to wrap vmmap via another program. In my case, I want to wrap vmmap via another program because whenever vmmap runs, it will bring a window up momentarily and then disappear. So I try passing vmmap as an argument to another program which will start the program "headlessly". I tried this program and this program, and in both cases I get the same popup which defeats the purpose of automation. Why does this happen when the program isn't run directly? Does anyone know the internals of what this warning is? And, utlimately, is there a way to stop this from happening, but only for this instance? I don't want to disable this warning-system on my whole computer. EDIT: I am using Windows Server 2003, and I don't necessarily need solutions for other platforms, but I would like to know what they are if they are platform-dependent solutions.

    Read the article

  • How to put 1000 lightweight server applications in the cloud

    - by Dan Bird
    The company I work for sells a commercial desktop/server app that runs on any non dedicated Windows PC or server and uses Tomcat for all interactions with the application. Customers are asking that we host their instance of the application so they don't have to run it locally on their own servers. The app is lightweight and an average server, in theory, could handle 25-50 instances before users would notice a slowdown. However only 1 instance can run per Windows instance (because the application writes to a common registry branch) so we'd need something like VMWare to create 25-50 Windows instances. We know we eventually need to reprogram to make it truly cloud-worthy but what would you recommend for a server farm or whatever for this? We don't have the setup to purchase our own servers so we must use a 3rd party. We have budgeted $500 - $1000 per year per customer for this service. Thanks in advance for your suggestions, experiences and guidance.

    Read the article

  • Python script shows different pythonpath

    - by Bird Jaguar IV
    Attempting to run runsnake gives ImportError: No module named wx Opening an ipython or python session seems to work fine: >>> import wx >>> import sys >>> print [p for p in sys.path if 'wx' in p] ['/usr/local/lib/wxPython-2.9.4.0/lib/python2.7/site-packages', '/usr/local/lib/wxPython-2.9.4.0/lib/python2.7/site-packages/wx-2.9.4-osx_cocoa', '/usr/local/lib/wxPython-2.9.4.0/lib/python2.7/site-packages/wx-2.9.1-osx_cocoa/tools'] as does putting that code in a script and calling python script.py. But putting that code at the beginning of runsnake.py prints an empty list (printing the whole sys.path prints a path quite different from my $PYTHONPATH). Why would it be different, and how to I get it to recognize wxPython?

    Read the article

  • How to setPage() a JEditorPane with a localfile which is outside of the .jar file?

    - by Jaguar
    My program has the following path in the .jar file src/test/Program.class and my program is as follow... Program.java package test; import java.io.File; import java.io.IOException; import javax.swing.JEditorPane; import javax.swing.JFrame; public class Program { JEditorPane editorPane; public Program() { File file = new File("temp.htm"); try { file.createNewFile(); editorPane = new JEditorPane(); editorPane.setPage(Program.class.getResource("temp.htm")); } catch (IOException e) { e.printStackTrace(); } } public JEditorPane getEditorPane(){ return editorPane; } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); frame.setVisible(true); Program p = new Program(); frame.getContentPane().add(p.getEditorPane()); } } The problem is that I have compiled the program in a .jar file. The file.createNewFile(); creates the temp.htm file outside the .jar file So when editorPane.setPage(Program.class.getResource("temp.htm")); is called the file is not found as it searches for file inside the test package. How to setPage() the temp.htm file whiich is outside the .jar file but in the same folder as the .jar file? As the temp.htm is a localfile and I want a relative path instead of an absolute path. Thanks.

    Read the article

  • Possible to change function name in definition?

    - by Bird Jaguar IV
    I tried several ways to change the function name in the definition, but they failed. >>> def f(): pass >>> f.__name__ 'f' >>> def f(): f.__name__ = 'new name' >>> f.__name__ 'f' >>> def f(): self.__name__ = 'new name' >>> f.__name__ 'f' But I can change the name attribute after defining it. >>> def f(): pass >>> f.__name__ = 'new name' >>> f.__name__ 'new name' Any way to change/set it in the definition (other than using a decorator)?

    Read the article

  • How to find the largest square in the number (Java)

    - by Ypsilon IV
    Hello everyone, I want to find the largest square in the number, but I am stuck at some point. I would really appreciate some suggestions. This is what I've done so far: I take the number on the input, factorize into prime numbers, and put the sequence of prime numbers to ArrayList. Numbers are sorted, in a sense, thus the numbers in the sequence are increasing. For example, 996 is 2 2 3 83 1000 is 2 2 2 5 5 5 100000 is 2 2 2 2 2 5 5 5 5 5 My idea now is to count number of occurrences of each elements in the sequence, so if the number of occurrences is divisible by two, then this is the square. In this way, I can get another sequence, where the right most element divisible by two is the largest square. What is the most efficient way to count occurrences in the ArrayList? Or is there any better way to find the largest square? Many thanks in advance!

    Read the article

  • Adding an inheritance to an Qt designed object

    - by Jaguar
    Hello, I have a problem and I want to implement the MVC pattern to my QT application, that's why I need for example to inherite in my QTableWidget about another class like myClass { myMethod(); } but our QTableWidget is contained by our Mainwidows that is designed by the QT designer and generate an ui_MainWindow class ! Do you know how to do that ? Is that a method inside the Qt Designer to do that ? or another method ? Thank you for your answer !

    Read the article

  • Remove successive 0th entries in args[] for a Java command line interface?

    - by Bill IV
    I recall seeing, somewhere, an example that stepped through String args[] by deleting the lowest numbered value(s) public static void main( String args[]) { while (args.length > 0 ) { // do something and obliterate elements from args[] } } Obviously, a variable tracking current position in args and compared to args.length will do it; or an ArrayList made from args[]'s contents, with argsAL.size(). Am I mis-remembering an ArrayList example? I know this is a borderline question, the likely answer is, "No, there isn't and there shouldn't be either!". Maybe I'm over-focused... Bill

    Read the article

  • Creating Wildcard Certificates with makecert.exe

    - by Shawn Cicoria
    Be nice to be able to make wildcard certificates for use in development with makecert – turns out, it’s real easy.  Just ensure that your CN=  is the wildcard string to use. The following sequence generates a CA cert, then the public/private key pair for a wildcard certificate REM make the CA makecert -pe -n "CN=*.contosotest.com" -a sha1 -len 2048 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -ic CA.cer -iv CA.pvk -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 -sv wildcard.pvk wildcard.cer pvk2pfx -pvk wildcard.pvk -spc wildcard.cer -pfx wildcard.pfx REM now make the server wildcard cert makecert -pe -n "CN=*.contosotest.com" -a sha1 -len 2048 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -ic CA.cer -iv CA.pvk -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 -sv wildcard.pvk wildcard.cer pvk2pfx -pvk wildcard.pvk -spc wildcard.cer -pfx wildcard.pfx

    Read the article

  • Informed TDD &ndash; Kata &ldquo;To Roman Numerals&rdquo;

    - by Ralf Westphal
    Originally posted on: http://geekswithblogs.net/theArchitectsNapkin/archive/2014/05/28/informed-tdd-ndash-kata-ldquoto-roman-numeralsrdquo.aspxIn a comment on my article on what I call Informed TDD (ITDD) reader gustav asked how this approach would apply to the kata “To Roman Numerals”. And whether ITDD wasn´t a violation of TDD´s principle of leaving out “advanced topics like mocks”. I like to respond with this article to his questions. There´s more to say than fits into a commentary. Mocks and TDD I don´t see in how far TDD is avoiding or opposed to mocks. TDD and mocks are orthogonal. TDD is about pocess, mocks are about structure and costs. Maybe by moving forward in tiny red+green+refactor steps less need arises for mocks. But then… if the functionality you need to implement requires “expensive” resource access you can´t avoid using mocks. Because you don´t want to constantly run all your tests against the real resource. True, in ITDD mocks seem to be in almost inflationary use. That´s not what you usually see in TDD demonstrations. However, there´s a reason for that as I tried to explain. I don´t use mocks as proxies for “expensive” resource. Rather they are stand-ins for functionality not yet implemented. They allow me to get a test green on a high level of abstraction. That way I can move forward in a top-down fashion. But if you think of mocks as “advanced” or if you don´t want to use a tool like JustMock, then you don´t need to use mocks. You just need to stand the sight of red tests for a little longer ;-) Let me show you what I mean by that by doing a kata. ITDD for “To Roman Numerals” gustav asked for the kata “To Roman Numerals”. I won´t explain the requirements again. You can find descriptions and TDD demonstrations all over the internet, like this one from Corey Haines. Now here is, how I would do this kata differently. 1. Analyse A demonstration of TDD should never skip the analysis phase. It should be made explicit. The requirements should be formalized and acceptance test cases should be compiled. “Formalization” in this case to me means describing the API of the required functionality. “[D]esign a program to work with Roman numerals” like written in this “requirement document” is not enough to start software development. Coding should only begin, if the interface between the “system under development” and its context is clear. If this interface is not readily recognizable from the requirements, it has to be developed first. Exploration of interface alternatives might be in order. It might be necessary to show several interface mock-ups to the customer – even if that´s you fellow developer. Designing the interface is a task of it´s own. It should not be mixed with implementing the required functionality behind the interface. Unfortunately, though, this happens quite often in TDD demonstrations. TDD is used to explore the API and implement it at the same time. To me that´s a violation of the Single Responsibility Principle (SRP) which not only should hold for software functional units but also for tasks or activities. In the case of this kata the API fortunately is obvious. Just one function is needed: string ToRoman(int arabic). And it lives in a class ArabicRomanConversions. Now what about acceptance test cases? There are hardly any stated in the kata descriptions. Roman numerals are explained, but no specific test cases from the point of view of a customer. So I just “invent” some acceptance test cases by picking roman numerals from a wikipedia article. They are supposed to be just “typical examples” without special meaning. Given the acceptance test cases I then try to develop an understanding of the problem domain. I´ll spare you that. The domain is trivial and is explain in almost all kata descriptions. How roman numerals are built is not difficult to understand. What´s more difficult, though, might be to find an efficient solution to convert into them automatically. 2. Solve The usual TDD demonstration skips a solution finding phase. Like the interface exploration it´s mixed in with the implementation. But I don´t think this is how it should be done. I even think this is not how it really works for the people demonstrating TDD. They´re simplifying their true software development process because they want to show a streamlined TDD process. I doubt this is helping anybody. Before you code you better have a plan what to code. This does not mean you have to do “Big Design Up-Front”. It just means: Have a clear picture of the logical solution in your head before you start to build a physical solution (code). Evidently such a solution can only be as good as your understanding of the problem. If that´s limited your solution will be limited, too. Fortunately, in the case of this kata your understanding does not need to be limited. Thus the logical solution does not need to be limited or preliminary or tentative. That does not mean you need to know every line of code in advance. It just means you know the rough structure of your implementation beforehand. Because it should mirror the process described by the logical or conceptual solution. Here´s my solution approach: The arabic “encoding” of numbers represents them as an ordered set of powers of 10. Each digit is a factor to multiply a power of ten with. The “encoding” 123 is the short form for a set like this: {1*10^2, 2*10^1, 3*10^0}. And the number is the sum of the set members. The roman “encoding” is different. There is no base (like 10 for arabic numbers), there are just digits of different value, and they have to be written in descending order. The “encoding” XVI is short for [10, 5, 1]. And the number is still the sum of the members of this list. The roman “encoding” thus is simpler than the arabic. Each “digit” can be taken at face value. No multiplication with a base required. But what about IV which looks like a contradiction to the above rule? It is not – if you accept roman “digits” not to be limited to be single characters only. Usually I, V, X, L, C, D, M are viewed as “digits”, and IV, IX etc. are viewed as nuisances preventing a simple solution. All looks different, though, once IV, IX etc. are taken as “digits”. Then MCMLIV is just a sum: M+CM+L+IV which is 1000+900+50+4. Whereas before it would have been understood as M-C+M+L-I+V – which is more difficult because here some “digits” get subtracted. Here´s the list of roman “digits” with their values: {1, I}, {4, IV}, {5, V}, {9, IX}, {10, X}, {40, XL}, {50, L}, {90, XC}, {100, C}, {400, CD}, {500, D}, {900, CM}, {1000, M} Since I take IV, IX etc. as “digits” translating an arabic number becomes trivial. I just need to find the values of the roman “digits” making up the number, e.g. 1954 is made up of 1000, 900, 50, and 4. I call those “digits” factors. If I move from the highest factor (M=1000) to the lowest (I=1) then translation is a two phase process: Find all the factors Translate the factors found Compile the roman representation Translation is just a look-up. Finding, though, needs some calculation: Find the highest remaining factor fitting in the value Remember and subtract it from the value Repeat with remaining value and remaining factors Please note: This is just an algorithm. It´s not code, even though it might be close. Being so close to code in my solution approach is due to the triviality of the problem. In more realistic examples the conceptual solution would be on a higher level of abstraction. With this solution in hand I finally can do what TDD advocates: find and prioritize test cases. As I can see from the small process description above, there are two aspects to test: Test the translation Test the compilation Test finding the factors Testing the translation primarily means to check if the map of factors and digits is comprehensive. That´s simple, even though it might be tedious. Testing the compilation is trivial. Testing factor finding, though, is a tad more complicated. I can think of several steps: First check, if an arabic number equal to a factor is processed correctly (e.g. 1000=M). Then check if an arabic number consisting of two consecutive factors (e.g. 1900=[M,CM]) is processed correctly. Then check, if a number consisting of the same factor twice is processed correctly (e.g. 2000=[M,M]). Finally check, if an arabic number consisting of non-consecutive factors (e.g. 1400=[M,CD]) is processed correctly. I feel I can start an implementation now. If something becomes more complicated than expected I can slow down and repeat this process. 3. Implement First I write a test for the acceptance test cases. It´s red because there´s no implementation even of the API. That´s in conformance with “TDD lore”, I´d say: Next I implement the API: The acceptance test now is formally correct, but still red of course. This will not change even now that I zoom in. Because my goal is not to most quickly satisfy these tests, but to implement my solution in a stepwise manner. That I do by “faking” it: I just “assume” three functions to represent the transformation process of my solution: My hypothesis is that those three functions in conjunction produce correct results on the API-level. I just have to implement them correctly. That´s what I´m trying now – one by one. I start with a simple “detail function”: Translate(). And I start with all the test cases in the obvious equivalence partition: As you can see I dare to test a private method. Yes. That´s a white box test. But as you´ll see it won´t make my tests brittle. It serves a purpose right here and now: it lets me focus on getting one aspect of my solution right. Here´s the implementation to satisfy the test: It´s as simple as possible. Right how TDD wants me to do it: KISS. Now for the second equivalence partition: translating multiple factors. (It´a pattern: if you need to do something repeatedly separate the tests for doing it once and doing it multiple times.) In this partition I just need a single test case, I guess. Stepping up from a single translation to multiple translations is no rocket science: Usually I would have implemented the final code right away. Splitting it in two steps is just for “educational purposes” here. How small your implementation steps are is a matter of your programming competency. Some “see” the final code right away before their mental eye – others need to work their way towards it. Having two tests I find more important. Now for the next low hanging fruit: compilation. It´s even simpler than translation. A single test is enough, I guess. And normally I would not even have bothered to write that one, because the implementation is so simple. I don´t need to test .NET framework functionality. But again: if it serves the educational purpose… Finally the most complicated part of the solution: finding the factors. There are several equivalence partitions. But still I decide to write just a single test, since the structure of the test data is the same for all partitions: Again, I´m faking the implementation first: I focus on just the first test case. No looping yet. Faking lets me stay on a high level of abstraction. I can write down the implementation of the solution without bothering myself with details of how to actually accomplish the feat. That´s left for a drill down with a test of the fake function: There are two main equivalence partitions, I guess: either the first factor is appropriate or some next. The implementation seems easy. Both test cases are green. (Of course this only works on the premise that there´s always a matching factor. Which is the case since the smallest factor is 1.) And the first of the equivalence partitions on the higher level also is satisfied: Great, I can move on. Now for more than a single factor: Interestingly not just one test becomes green now, but all of them. Great! You might say, then I must have done not the simplest thing possible. And I would reply: I don´t care. I did the most obvious thing. But I also find this loop very simple. Even simpler than a recursion of which I had thought briefly during the problem solving phase. And by the way: Also the acceptance tests went green: Mission accomplished. At least functionality wise. Now I´ve to tidy up things a bit. TDD calls for refactoring. Not uch refactoring is needed, because I wrote the code in top-down fashion. I faked it until I made it. I endured red tests on higher levels while lower levels weren´t perfected yet. But this way I saved myself from refactoring tediousness. At the end, though, some refactoring is required. But maybe in a different way than you would expect. That´s why I rather call it “cleanup”. First I remove duplication. There are two places where factors are defined: in Translate() and in Find_factors(). So I factor the map out into a class constant. Which leads to a small conversion in Find_factors(): And now for the big cleanup: I remove all tests of private methods. They are scaffolding tests to me. They only have temporary value. They are brittle. Only acceptance tests need to remain. However, I carry over the single “digit” tests from Translate() to the acceptance test. I find them valuable to keep, since the other acceptance tests only exercise a subset of all roman “digits”. This then is my final test class: And this is the final production code: Test coverage as reported by NCrunch is 100%: Reflexion Is this the smallest possible code base for this kata? Sure not. You´ll find more concise solutions on the internet. But LOC are of relatively little concern – as long as I can understand the code quickly. So called “elegant” code, however, often is not easy to understand. The same goes for KISS code – especially if left unrefactored, as it is often the case. That´s why I progressed from requirements to final code the way I did. I first understood and solved the problem on a conceptual level. Then I implemented it top down according to my design. I also could have implemented it bottom-up, since I knew some bottom of the solution. That´s the leaves of the functional decomposition tree. Where things became fuzzy, since the design did not cover any more details as with Find_factors(), I repeated the process in the small, so to speak: fake some top level, endure red high level tests, while first solving a simpler problem. Using scaffolding tests (to be thrown away at the end) brought two advantages: Encapsulation of the implementation details was not compromised. Naturally private methods could stay private. I did not need to make them internal or public just to be able to test them. I was able to write focused tests for small aspects of the solution. No need to test everything through the solution root, the API. The bottom line thus for me is: Informed TDD produces cleaner code in a systematic way. It conforms to core principles of programming: Single Responsibility Principle and/or Separation of Concerns. Distinct roles in development – being a researcher, being an engineer, being a craftsman – are represented as different phases. First find what, what there is. Then devise a solution. Then code the solution, manifest the solution in code. Writing tests first is a good practice. But it should not be taken dogmatic. And above all it should not be overloaded with purposes. And finally: moving from top to bottom through a design produces refactored code right away. Clean code thus almost is inevitable – and not left to a refactoring step at the end which is skipped often for different reasons.   PS: Yes, I have done this kata several times. But that has only an impact on the time needed for phases 1 and 2. I won´t skip them because of that. And there are no shortcuts during implementation because of that.

    Read the article

  • How do I combine the two methods of cryptography, CBC cipher block and Vingenere Chiper [on hold]

    - by Bangpe
    Code Vingenere static String encrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A'); j = ++j % key.length(); } return res; } Code CBC Chiper public CbcBlockCipher( BlockCipher blockCipher ) { super( blockCipher.keySize(), blockCipher.blockSize() ); this.blockCipher = blockCipher; iv = new byte[blockSize()]; zeroBlock( iv ); temp = new byte[blockSize()]; }

    Read the article

  • Error "Input length must be multiple of 8 when decrypting with padded cipher"

    - by Ross Peoples
    I am trying to move a project from C# to Java for a learning exercise. I am still very new to Java, but I have a TripleDES class in C# that encrypts strings and returns a string value of the encrypted byte array. Here is my C# code: using System; using System.IO; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace tDocc.Classes { /// <summary> /// Triple DES encryption class /// </summary> public static class TripleDES { private static byte[] key = { 110, 32, 73, 24, 125, 66, 75, 18, 79, 150, 211, 122, 213, 14, 156, 136, 171, 218, 119, 240, 81, 142, 23, 4 }; private static byte[] iv = { 25, 117, 68, 23, 99, 78, 231, 219 }; /// <summary> /// Encrypt a string to an encrypted byte array /// </summary> /// <param name="plainText">Text to encrypt</param> /// <returns>Encrypted byte array</returns> public static byte[] Encrypt(string plainText) { UTF8Encoding utf8encoder = new UTF8Encoding(); byte[] inputInBytes = utf8encoder.GetBytes(plainText); TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); ICryptoTransform cryptoTransform = tdesProvider.CreateEncryptor(key, iv); MemoryStream encryptedStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write); cryptStream.Write(inputInBytes, 0, inputInBytes.Length); cryptStream.FlushFinalBlock(); encryptedStream.Position = 0; byte[] result = new byte[encryptedStream.Length]; encryptedStream.Read(result, 0, (int)encryptedStream.Length); cryptStream.Close(); return result; } /// <summary> /// Decrypt a byte array to a string /// </summary> /// <param name="inputInBytes">Encrypted byte array</param> /// <returns>Decrypted string</returns> public static string Decrypt(byte[] inputInBytes) { UTF8Encoding utf8encoder = new UTF8Encoding(); TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); ICryptoTransform cryptoTransform = tdesProvider.CreateDecryptor(key, iv); MemoryStream decryptedStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write); cryptStream.Write(inputInBytes, 0, inputInBytes.Length); cryptStream.FlushFinalBlock(); decryptedStream.Position = 0; byte[] result = new byte[decryptedStream.Length]; decryptedStream.Read(result, 0, (int)decryptedStream.Length); cryptStream.Close(); UTF8Encoding myutf = new UTF8Encoding(); return myutf.GetString(result); } /// <summary> /// Decrypt an encrypted string /// </summary> /// <param name="text">Encrypted text</param> /// <returns>Decrypted string</returns> public static string DecryptText(string text) { if (text == "") { return text; } return Decrypt(Convert.FromBase64String(text)); } /// <summary> /// Encrypt a string /// </summary> /// <param name="text">Unencrypted text</param> /// <returns>Encrypted string</returns> public static string EncryptText(string text) { if (text == "") { return text; } return Convert.ToBase64String(Encrypt(text)); } } /// <summary> /// Random number generator /// </summary> public static class RandomGenerator { /// <summary> /// Generate random number /// </summary> /// <param name="length">Number of randomizations</param> /// <returns>Random number</returns> public static int GenerateNumber(int length) { byte[] randomSeq = new byte[length]; new RNGCryptoServiceProvider().GetBytes(randomSeq); int code = Environment.TickCount; foreach (byte b in randomSeq) { code += (int)b; } return code; } } /// <summary> /// Hash generator class /// </summary> public static class Hasher { /// <summary> /// Hash type /// </summary> public enum eHashType { /// <summary> /// MD5 hash. Quick but collisions are more likely. This should not be used for anything important /// </summary> MD5 = 0, /// <summary> /// SHA1 hash. Quick and secure. This is a popular method for hashing passwords /// </summary> SHA1 = 1, /// <summary> /// SHA256 hash. Slower than SHA1, but more secure. Used for encryption keys /// </summary> SHA256 = 2, /// <summary> /// SHA348 hash. Even slower than SHA256, but offers more security /// </summary> SHA348 = 3, /// <summary> /// SHA512 hash. Slowest but most secure. Probably overkill for most applications /// </summary> SHA512 = 4, /// <summary> /// Derrived from MD5, but only returns 12 digits /// </summary> Digit12 = 5 } /// <summary> /// Hashes text using a specific hashing method /// </summary> /// <param name="text">Input text</param> /// <param name="hash">Hash method</param> /// <returns>Hashed text</returns> public static string GetHash(string text, eHashType hash) { if (text == "") { return text; } if (hash == eHashType.MD5) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA1) { SHA1Managed hasher = new SHA1Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA256) { SHA256Managed hasher = new SHA256Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA348) { SHA384Managed hasher = new SHA384Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA512) { SHA512Managed hasher = new SHA512Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.Digit12) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); string newHash = ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); return newHash.Substring(0, 12); } return ""; } /// <summary> /// Generates a hash based on a file's contents. Used for detecting changes to a file and testing for duplicate files /// </summary> /// <param name="info">FileInfo object for the file to be hashed</param> /// <param name="hash">Hash method</param> /// <returns>Hash string representing the contents of the file</returns> public static string GetHash(FileInfo info, eHashType hash) { FileStream hashStream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read); string hashString = ""; if (hash == eHashType.MD5) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA1) { SHA1Managed hasher = new SHA1Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA256) { SHA256Managed hasher = new SHA256Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA348) { SHA384Managed hasher = new SHA384Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA512) { SHA512Managed hasher = new SHA512Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } hashStream.Close(); hashStream.Dispose(); hashStream = null; return hashString; } /// <summary> /// Converts a byte array to a hex string /// </summary> /// <param name="data">Byte array</param> /// <returns>Hex string</returns> public static string ByteToHex(byte[] data) { StringBuilder builder = new StringBuilder(); foreach (byte hashByte in data) { builder.Append(string.Format("{0:X1}", hashByte)); } return builder.ToString(); } /// <summary> /// Converts a hex string to a byte array /// </summary> /// <param name="hexString">Hex string</param> /// <returns>Byte array</returns> public static byte[] HexToByte(string hexString) { byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i <= returnBytes.Length - 1; i++) { returnBytes[i] = byte.Parse(hexString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } return returnBytes; } } } And her is what I've got for Java code so far, but I'm getting the error "Input length must be multiple of 8 when decrypting with padded cipher" when I run the test on this: import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.tdocc.utils.Base64; public class TripleDES { private static byte[] keyBytes = { 110, 32, 73, 24, 125, 66, 75, 18, 79, (byte)150, (byte)211, 122, (byte)213, 14, (byte)156, (byte)136, (byte)171, (byte)218, 119, (byte)240, 81, (byte)142, 23, 4 }; private static byte[] ivBytes = { 25, 117, 68, 23, 99, 78, (byte)231, (byte)219 }; public static String encryptText(String plainText) { try { if (plainText.isEmpty()) return plainText; return Base64.decode(TripleDES.encrypt(plainText)).toString(); } catch (Exception e) { e.printStackTrace(); } return null; } public static byte[] encrypt(String plainText) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException { try { final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(ivBytes); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = plainText.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); return cipherText; } catch (Exception e) { e.printStackTrace(); } return null; } public static String decryptText(String message) { try { if (message.isEmpty()) return message; else return TripleDES.decrypt(message.getBytes()); } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(byte[] message) { try { final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(ivBytes); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, iv); final byte[] plainText = cipher.doFinal(message); return plainText.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }

    Read the article

  • How to encrypt in VBScript using AES?

    - by Jon
    I am looking to encrypt some data using Rijndael/AES in VBScript using a specific key and IV value. Are there any good function libraries or COM components that would be good to use? I looked at CAPICOM; it allows a passphrase only, and won't allow setting specific key and IV values.

    Read the article

  • .NET file Decryption - Bad Data

    - by Jon
    I am in the process of rewriting an old application. The old app stored data in a scoreboard file that was encrypted with the following code: private const String SSecretKey = @"?B?n?Mj?"; public DataTable GetScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardLocation); if (!f.Exists) { return setupNewScoreBoard(); } DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } This works fine. I have copied the code into my new app so that I can create a legacy loader and convert the data into the new format. The problem is I get a "Bad Data" error: System.Security.Cryptography.CryptographicException was unhandled Message="Bad Data.\r\n" Source="mscorlib" The error fires at this line: dTable.ReadXml(new StreamReader(cryptostreamDecr)); The encrypted file was created today on the same machine with the old code. I guess that maybe the encryption / decryption process uses the application name / file or something and therefore means I can not open it. Does anyone have an idea as to: A) Be able explain why this isn't working? B) Offer a solution that would allow me to be able to open files that were created with the legacy application and be able to convert them please? Here is the whole class that deals with loading and saving the scoreboard: using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.IO; using System.Data; using System.Xml; using System.Threading; namespace JawBreaker { [Serializable] class ScoreBoardLoader { private Jawbreaker jawbreaker; private String sSecretKey = @"?B?n?Mj?"; private String scoreBoardFileLocation = ""; private bool keepScoreBoardUpdated = true; private int intTimer = 180000; public ScoreBoardLoader(Jawbreaker jawbreaker, String scoreBoardFileLocation) { this.jawbreaker = jawbreaker; this.scoreBoardFileLocation = scoreBoardFileLocation; } // Call this function to remove the key from memory after use for security [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")] public static extern bool ZeroMemory(IntPtr Destination, int Length); // Function to Generate a 64 bits Key. private string GenerateKey() { // Create an instance of Symetric Algorithm. Key and IV is generated automatically. DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create(); // Use the Automatically generated key for Encryption. return ASCIIEncoding.ASCII.GetString(desCrypto.Key); } public void writeScoreboardToFile() { DataTable tempScoreBoard = getScoreboardFromFile(); //add in the new scores to the end of the file. for (int i = 0; i < jawbreaker.Scoreboard.Rows.Count; i++) { DataRow row = tempScoreBoard.NewRow(); row.ItemArray = jawbreaker.Scoreboard.Rows[i].ItemArray; tempScoreBoard.Rows.Add(row); } //before it is written back to the file make sure we update the sync info if (jawbreaker.SyncScoreboard) { //connect to webservice, login and update all the scores that have not been synced. for (int i = 0; i < tempScoreBoard.Rows.Count; i++) { try { //check to see if that row has been synced to the server if (!Boolean.Parse(tempScoreBoard.Rows[i].ItemArray[7].ToString())) { //sync info to server //update the row to say that it has been updated object[] tempArray = tempScoreBoard.Rows[i].ItemArray; tempArray[7] = true; tempScoreBoard.Rows[i].ItemArray = tempArray; tempScoreBoard.AcceptChanges(); } } catch (Exception ex) { jawbreaker.writeErrorToLog("ERROR OCCURED DURING SYNC TO SERVER UPDATE: " + ex.Message); } } } FileStream fsEncrypted = new FileStream(scoreBoardFileLocation, FileMode.Create, FileAccess.Write); DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey); ICryptoTransform desencrypt = DES.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write); MemoryStream ms = new MemoryStream(); tempScoreBoard.WriteXml(ms, XmlWriteMode.WriteSchema); ms.Position = 0; byte[] bitarray = new byte[ms.Length]; ms.Read(bitarray, 0, bitarray.Length); cryptostream.Write(bitarray, 0, bitarray.Length); cryptostream.Close(); ms.Close(); //now the scores have been added to the file remove them from the datatable jawbreaker.Scoreboard.Rows.Clear(); } public void startPeriodicScoreboardWriteToFile() { while (keepScoreBoardUpdated) { //three minute sleep. Thread.Sleep(intTimer); writeScoreboardToFile(); } } public void stopPeriodicScoreboardWriteToFile() { keepScoreBoardUpdated = false; } public int IntTimer { get { return intTimer; } set { intTimer = value; } } public DataTable getScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardFileLocation); if (!f.Exists) { jawbreaker.writeInfoToLog("Scoreboard not there so creating new one"); return setupNewScoreBoard(); } else { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardFileLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } } public DataTable setupNewScoreBoard() { //scoreboard info into dataset DataTable scoreboard = new DataTable("scoreboard"); scoreboard.Columns.Add(new DataColumn("playername", System.Type.GetType("System.String"))); scoreboard.Columns.Add(new DataColumn("score", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("ballnumber", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("xsize", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("ysize", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("gametype", System.Type.GetType("System.String"))); scoreboard.Columns.Add(new DataColumn("date", System.Type.GetType("System.DateTime"))); scoreboard.Columns.Add(new DataColumn("synced", System.Type.GetType("System.Boolean"))); scoreboard.AcceptChanges(); return scoreboard; } private void Run() { // For additional security Pin the key. GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned); // Remove the Key from memory. ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2); gch.Free(); } } }

    Read the article

  • Load image in device independent and screen independent fashion into a layout view using 1.6 SDK

    - by Mark Wigzell
    I'm having trouble getting an asset image to scale up when I load it. The new call to BitmapDrawable(Resources, BitmapDrawable) is not available on 1.6 SDK. Is there a workaround to load the BitmapDrawable the old way and then somehow manipulate it? I have tried calling setTargetDensity() to no avail. My code (which doesn't scale properly) is: ImageView iv = (ImageView)view.findViewById(R.id.image); iv.setImageDrawable(new BitmapDrawable(view.getContext().getAssets().open(path)));

    Read the article

  • Best method for converting several sets of numbers with several different ratios

    - by C Patton
    I'm working on an open-source harm reduction application for opioid addicts. One of the features in this application is the conversion (in mg/mcg) between common opioids, so people don't overdose by accident. If you're morally against opioid addiction and wouldn't respond because of your morals, please consider that this application is for HARM REDUCTION.. So people don't end up dead. I have this data.. 3mg morphine IV = 10mcg fentanyl IV 2mg morphine oral = 1mg oxycodone oral 3mg oral morphine = 1mg oxymorphone oral 7.0mg morphine oral = 1mg hydromorphone oral 1mg morphine iv = .10mg oxymorphone iv 1mg morphine oral = 1mg hydrocodone oral 1mg morphine oral = 6.67mg codeine oral 1mg morphine oral = .10mg methadone oral And I have a textbox that is the source dosage in mg (a double) that the user can enter in. Underneath this, I have radio boxes for the source substance (ie: morphine) and the destination substance (ie oxycodone) for conversion.. I've been trying to think of the most efficient way to do this, but nearly every seems sloppy. If I were to do something like public static double MorphinetoOxycodone(string morphineValue) { double morphine = Double.Parse(morphineValue); return (morphine / 2 ); } I would also have to make a function for OxycodonetoMorphine, OxycodonetoCodeine, etc.. and then would end up with dozens functions.. There must be an easier way than this that I'm missing. If you'll notice, all of my conversions use morphine as the base value.. what might be the easiest way to use the morphine value to convert one opioid to another? For example, if 1mg morphine oral is equal to 1mg hydrocodone and 1mg morphine oral is equal to .10mg methadone, wouldn't I just multiply 1*.10 to get the hydrocodone-methadone value? Implementing this idea is what I'm having the most trouble with. Any help would be GREATLY appreciated.. and if you'd like, I would add your name/nickname to the credits in this program. It's possible that many, many people around the world will use this (I'm translating it into several languages as well) and to know that your work could've helped an addict from dying.. I think that's a great thing :) -cory

    Read the article

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