· 10 years ago · Apr 20, 2016, 09:33 PM
1# A1 binary search
2## code
3```
4import random
5def binarySearch(alist, searchelement):
6 '''
7 binartsearch using divide and conqure(non-recursive).
8
9 @param: alist, unsorted list
10 @param: item, an element to be searched in alist
11
12 returns: bool, position, the presence of item in alist and position.
13 '''
14 first = 0
15 found = False
16 adict={}
17 pos=0
18 for i in range(len(alist)):
19 adict[alist[i]]=alist.index(alist[i])+1
20 alist.sort()
21
22 last = len(alist)-1
23 while first<=last and not found:
24 midpoint = (first+last)//2
25 if alist[midpoint]==searchelement:
26 found = True
27 pos=adict[searchelement]
28 else:
29 if searchelement<alist[midpoint]:
30 last=midpoint-1
31 else:
32 first=midpoint+1
33 return found,pos
34
35alist = [random.randint(0,99) for i in range(100)]
36print alist
37searchelement = raw_input("Enter element to be Searched: ")
38print(binarySearch(alist,int(searchelement)))
39
40
41s = raw_input("enter few elements ")
42alist = s.split(",")
43findEle = raw_input("enter element to be searched ")
44
45print(binarySearch(alist,findEle))
46
47```
48## Explanation
49```
50binary search runs in at worst logarithmic time, making O(log n) comparisons, where n is the number of elements in the array
51
52Algorithm
53
54Binary search only works on sorted arrays. A binary search begins by comparing the middle element of the array with the target value. If the target value matches the middle element, its position in the array is returned. If the target value is less or more than the middle element, the search continues the lower or upper half of the array respectively with a new middle element, eliminating the other half from consideration. This method can be described recursively or iteratively.
55
56Procedure[edit]
57Given an array A of n elements with values or records A0 ... An−1 and target value T, the following subroutine uses binary search to find the index of T in A.[6]
58
591. Set L to 0 and R to n−1.
602. If L > R, the search terminates as unsuccessful. Set m (the position of the middle element) to the floor of (L + R) / 2.
613. If Am = T, the search is done; return m.
624. If Am < T, set L to m + 1 and go to step 2.
635. If Am > T, set R to m – 1 and go to step 2.
646. This iterative procedure keeps track of the search boundaries via two variables; a recursive version would keep its boundaries in its recursive calls. Some implementations may place the comparison for equality at the end, resulting in a faster comparison loop but costing one more iteration on average.[7]
65```
66# A2 quick sort
67## code
68```
69from xml.dom.minidom import parse
70import xml.dom.minidom
71import random
72import sys
73from threading import Thread, current_thread
74
75def quickSort(alist):
76 quickSortHelper(alist,0,len(alist)-1)
77
78def quickSortHelper(alist,first,last):
79 if first<last:
80 splitpoint = partition(alist,first,last)
81 t =Thread(target = quickSortHelper, args = (alist,first,splitpoint-1))
82 t.start()
83 t.join()
84 t1=Thread(target = quickSortHelper, args = (alist,splitpoint+1,last))
85 t1.start()
86 t1.join()
87 return alist
88
89def partition(alist,first,last):
90 pivotvalue = alist[first]
91
92 leftmark = first+1
93 rightmark = last
94
95 done = False
96 while not done:
97 while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
98 leftmark = leftmark + 1
99 while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
100 rightmark = rightmark -1
101 if rightmark < leftmark:
102 done = True
103 else:
104 swap(alist,leftmark,rightmark)
105
106 swap(alist,first,rightmark)
107
108 return rightmark
109
110def swap(alist,left,right):
111 temp = alist[left]
112 alist[left] = alist[right]
113 alist[right] = temp
114
115def genXML(filename):
116 alist = [random.randint(1,100) for i in range(50)]
117 f = open(filename,"w")
118 f.write("<Number>")
119 for i in range(len(alist)):
120 f.write("\n\t<integer>"+str(alist[i])+"</integer>")
121 f.write("\n</Number>")
122 f.close()
123
124if __name__ == '__main__':
125
126 filename = raw_input("Enter filename: ")
127 filename = filename if filename.find("xml")!=-1 else filename+".xml"
128 genXML(filename)
129
130 DOMTree = xml.dom.minidom.parse(filename)
131 collection = DOMTree.documentElement
132 integers = collection.getElementsByTagName("integer")
133
134 alist=[]
135 for i in range(len(integers)):
136 val = collection.getElementsByTagName("integer")[i]
137 alist.append(int(val.childNodes[0].data))
138
139 quickSort(alist)
140 print(alist)
141```
142## Explanation
143```
144Mathematical analysis of quicksort shows that, on average, the algorithm takes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare.
145
146Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.
147
148The steps are:
149
1501. Pick an element, called a pivot, from the array.
1512. Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
1523. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.
153
154The base case of the recursion is arrays of size zero or one, which never need to be sorted.
155
156The pivot selection and partitioning steps can be done in several different ways; the choice of specific implementation schemes greatly affects the algorithm's performance.
157```
158
159# A3 booth
160## code
161```
162import bitstring
163from bitstring import BitArray
164from flask import Flask, request, render_template
165
166def booths(m,r):
167 x=len(bin(m))
168 y=len(bin(r))
169 totallength = x+y+1
170
171 if m<0 and r<0 or r<0:
172 bugbit = 1
173 else:
174 bugbit = 0
175
176 A = BitArray(int = m,length = totallength) << (y+1)
177 compliment = BitArray(int = -m,length = totallength) << (y+1)
178 P = BitArray(int = r, length = totallength)
179 P = P<<1
180
181 for i in range(1,y+1):
182 if P[-2:]=='0b01':
183 P = BitArray(int = P.int + A.int, length = totallength)
184 elif P[-2:]=='0b10':
185 P = BitArray(int = P.int + compliment.int, length = totallength)
186 P = BitArray(int = P.int>>1, length = totallength)
187
188 P = P[:-1]
189
190 P.int = P.int + bugbit
191 steps =""
192 return '<h1>RESULT</h1><br>'+steps+'<br><h3>decimal value: '+str(P.int)+'</br><br> binary value: '+str(P.bin)+"</h3>"
193
194
195#print(booths(12,13))
196
197app = Flask(__name__)
198
199@app.route('/')
200def rend():
201 return render_template("booths.html")
202
203@app.route('/',methods=['POST'])
204def post_method():
205 m = request.form['multiplier']
206 r = request.form['multiplicand']
207 try:
208 multiplier = int(m)
209 multiplicand = int(r)
210 except:
211 return "<br><h1>Error</h1><br> One of the item found"
212
213 print multiplier, multiplicand
214 return booths(multiplier,multiplicand)
215
216if __name__ == '__main__':
217 app.run(debug=True)
218
219#html file: templates/booths.html
220<!DOCTYPE html>
221<html>
222<body>
223<h1>Booth's Multiplier</h1>
224<h2>Enter two numbers </h2>
225<form action="." method = "POST">
226<input type="number" name="multiplier">*
227<input type="number" name="multiplicand">
228<input type="submit" name="myform" value="=">
229</form>
230<body>
231<html>
232```
233## Explanation
234```
235Booth's algorithm can be implemented by repeatedly adding (with ordinary unsigned binary addition) one of two predetermined values A and S to a product P, then performing a rightward arithmetic shift on P. Let m and r be the multiplicand and multiplier, respectively; and let x and y represent the number of bits in m and r.
236
2371. Determine the values of A and S, and the initial value of P. All of these numbers should have a length equal to (x + y + 1).
2381.1 A: Fill the most significant (leftmost) bits with the value of m. Fill the remaining (y + 1) bits with zeros.
2391.2 S: Fill the most significant bits with the value of (−m) in two's complement notation. Fill the remaining (y + 1) bits with zeros.
2401.3. P: Fill the most significant x bits with zeros. To the right of this, append the value of r. Fill the least significant (rightmost) bit with a zero.
2412. Determine the two least significant (rightmost) bits of P.
2422.1 If they are 01, find the value of P + A. Ignore any overflow.
2432.2 If they are 10, find the value of P + S. Ignore any overflow.
2442.3 If they are 00, do nothing. Use P directly in the next step.
2452.4 If they are 11, do nothing. Use P directly in the next step.
2463. Arithmetically shift the value obtained in the 2nd step by a single place to the right. Let P now equal this new value.
2474. Repeat steps 2 and 3 until they have been done y times.
2485. Drop the least significant (rightmost) bit from P. This is the product of m and r.
249
250multiplying −8 by 2 using 4 bits for the multiplicand and the multiplier:
251
252A = 1 1000 0000 0
253S = 0 1000 0000 0
254P = 0 0000 0010 0
255Perform the loop four times:
256P = 0 0000 0010 0. The last two bits are 00.
257 P = 0 0000 0001 0. Right shift.
258P = 0 0000 0001 0. The last two bits are 10.
259 P = 0 1000 0001 0. P = P + S.
260 P = 0 0100 0000 1. Right shift.
261P = 0 0100 0000 1. The last two bits are 01.
262 P = 1 1100 0000 1. P = P + A.
263 P = 1 1110 0000 0. Right shift.
264P = 1 1110 0000 0. The last two bits are 00.
265 P = 1 1111 0000 0. Right shift.
266
267The product is 11110000 (after discarding the first and the last bit) which is −16.
268```
269
270# A4 dining philosophers
271## Code
272```
273from pymongo import MongoClient
274import threading
275import random
276import time
277
278
279class Philosopher(threading.Thread):
280
281 running = True
282
283 def __init__(self, xname, forkOnLeft, forkOnRight):
284 threading.Thread.__init__(self)
285 self.name = xname
286 self.forkOnLeft = forkOnLeft
287 self.forkOnRight = forkOnRight
288
289 def run(self):
290 while(self.running):
291 # Philosopher is thinking (but really is sleeping).
292 time.sleep( random.uniform(3,13))
293 insertIntoMongo( self.name, 'is hungry')
294 self.dine()
295
296 def dine(self):
297 fork1, fork2 = self.forkOnLeft, self.forkOnRight
298
299 while self.running:
300 fork1.acquire(True)
301 locked = fork2.acquire(False)
302 if locked: break
303 fork1.release()
304 insertIntoMongo( self.name, 'swaps forks')
305 fork1, fork2 = fork2, fork1
306 else:
307 return
308
309 self.dining()
310 fork2.release()
311 fork1.release()
312
313 def dining(self):
314 insertIntoMongo( self.name, 'starts eating' )
315 time.sleep(random.uniform(1,10))
316 insertIntoMongo( self.name, 'finishes eating and leaves to think.')
317
318
319def DiningPhilosophers():
320 forks = [threading.Lock() for n in range(5)]
321 philosopherNames = ('Aristotle','Kant','Buddha','Marx', 'Russel')
322
323 philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
324 for i in range(5)]
325
326 random.seed(507129)
327 Philosopher.running = True
328 for p in philosophers: p.start()
329 time.sleep(100)
330 Philosopher.running = False
331 insertIntoMongo( 'Exit', 'Now we are finishing.')
332
333def insertIntoMongo(key,value):
334 result = db.diningCol.insert_one(
335 {
336 key: value
337 } )
338
339client = MongoClient("mongodb://127.0.0.1:27027")
340db = client.test
341db.drop_collection("diningCol")
342DiningPhilosophers()
343
344cursor = db.diningCol.find()
345for document in cursor:
346 document.pop(u'_id')
347 for key,value in document.items():
348 print key + " " +value
349
350```
351## Explanation
352
353start the server
354
355```
356mongod --dbpath /home/cipher/mongodb --port 27027 --bind_ip 127.0.0.1 --noprealloc
357```
358
359#Dining philosophers
360
361The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
362
363Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
364
365It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
366
367```
368
369# This solution avoids deadlock by never waiting for a fork while having one in hand.
370# If a philosopher acquires one fork but can't acquire the second,
371# he releases the first fork before waiting to acquire the other (which then becomes the first fork acquired).
372# Dining philosophers, 5 Phillies with 5 forks. Must have two forks to eat.
373#
374# Deadlock is avoided by never waiting for a fork while holding a fork (locked)
375# Procedure is to do block while waiting to get first fork, and a nonblocking
376# acquire of second fork. If failed to get second fork, release first fork,
377# swap which fork is first and which is second and retry until getting both.
378#
379
380```
381
382
383# A5 calculator
384Create a new Android Application Project. Let's say your Application Name is "Calculator", your Project Name is "Calculator", and your Package Name is "com.example.calculator". Setup the project with the default settings. Now replace MainActivity.java, activity_main.xml (in res/layout), & strings.xml (in res/values) with the code below. Next, create a new class "CalculatorBrain" and replace CalculatorBrain.java with the code below.
385
386compileSdkVersion 23
387buildToolsVersion "21.1.2"
388
389The calculator should run without errors!
390MainActivity.java
391``` java
392package example.com.calculator;
393import java.io.IOException;
394import java.text.DecimalFormat;
395import android.annotation.SuppressLint;
396import android.app.Activity;
397import android.os.Bundle;
398import android.view.View;
399import android.view.View.OnClickListener;
400import android.view.Window;
401import android.view.WindowManager;
402import android.widget.Button;
403import android.widget.TextView;
404/**
405 * Created by neeraj on 19-03-2016.
406 */
407public class MainActivity extends Activity implements OnClickListener {
408 private TextView mCalculatorDisplay;
409 private Boolean userIsInTheMiddleOfTypingANumber = false;
410 private CalculatorBrain mCalculatorBrain;
411 private static final String DIGITS = "0123456789.";
412 DecimalFormat df = new DecimalFormat("@###########");
413
414 @SuppressLint("NewApi")
415 @Override
416 protected void onCreate(Bundle savedInstanceState) {
417 // hide the window title.
418 requestWindowFeature(Window.FEATURE_NO_TITLE);
419 // hide the status bar and other OS-level chrome
420 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
421 super.onCreate(savedInstanceState);
422 setContentView(R.layout.activity_main);
423 mCalculatorBrain = new CalculatorBrain();
424 mCalculatorDisplay = (TextView) findViewById(R.id.textView1);
425
426 df.setMinimumFractionDigits(0);
427 df.setMinimumIntegerDigits(1);
428 df.setMaximumIntegerDigits(8);
429
430 findViewById(R.id.button0).setOnClickListener(this);
431 findViewById(R.id.button1).setOnClickListener(this);
432 findViewById(R.id.button2).setOnClickListener(this);
433 findViewById(R.id.button3).setOnClickListener(this);
434 findViewById(R.id.button4).setOnClickListener(this);
435 findViewById(R.id.button5).setOnClickListener(this);
436 findViewById(R.id.button6).setOnClickListener(this);
437 findViewById(R.id.button7).setOnClickListener(this);
438 findViewById(R.id.button8).setOnClickListener(this);
439 findViewById(R.id.button9).setOnClickListener(this);
440
441 findViewById(R.id.buttonAdd).setOnClickListener(this);
442 findViewById(R.id.buttonSubtract).setOnClickListener(this);
443 findViewById(R.id.buttonMultiply).setOnClickListener(this);
444 findViewById(R.id.buttonDivide).setOnClickListener(this);
445 findViewById(R.id.buttonToggleSign).setOnClickListener(this);
446 findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
447 findViewById(R.id.buttonEquals).setOnClickListener(this);
448 findViewById(R.id.buttonClear).setOnClickListener(this);
449 findViewById(R.id.buttonClearMemory).setOnClickListener(this);
450 findViewById(R.id.buttonAddToMemory).setOnClickListener(this);
451 findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(this);
452 findViewById(R.id.buttonRecallMemory).setOnClickListener(this);
453
454 // The following buttons only exist in layout-land (Landscape mode) and require extra attention.
455 // The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
456 if (findViewById(R.id.buttonSquareRoot) != null) {
457 findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
458 }
459 if (findViewById(R.id.buttonSquared) != null) {
460 findViewById(R.id.buttonSquared).setOnClickListener(this);
461 }
462 if (findViewById(R.id.buttonInvert) != null) {
463 findViewById(R.id.buttonInvert).setOnClickListener(this);
464 }
465 if (findViewById(R.id.buttonSine) != null) {
466 findViewById(R.id.buttonSine).setOnClickListener(this);
467 }
468 if (findViewById(R.id.buttonCosine) != null) {
469 findViewById(R.id.buttonCosine).setOnClickListener(this);
470 }
471 if (findViewById(R.id.buttonTangent) != null) {
472 findViewById(R.id.buttonTangent).setOnClickListener(this);
473 }
474 }
475
476 @Override
477 public void onClick(View v) {
478 String buttonPressed = ((Button) v).getText().toString();
479 if (DIGITS.contains(buttonPressed)) {
480 // digit was pressed
481 if (userIsInTheMiddleOfTypingANumber) {
482 if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
483 // ERROR PREVENTION
484 // Eliminate entering multiple decimals
485 } else {
486 mCalculatorDisplay.append(buttonPressed);
487 }
488 } else {
489 if (buttonPressed.equals(".")) {
490 // ERROR PREVENTION
491 // This will avoid error if only the decimal is hit before an operator, by placing a leading zero
492 // before the decimal
493 mCalculatorDisplay.setText(0 + buttonPressed);
494 } else {
495 mCalculatorDisplay.setText(buttonPressed);
496 }
497 userIsInTheMiddleOfTypingANumber = true;
498 }
499 } else {
500 // operation was pressed
501 if (userIsInTheMiddleOfTypingANumber) {
502 mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
503 userIsInTheMiddleOfTypingANumber = false;
504 }
505 try {
506 mCalculatorBrain.performOperation(buttonPressed);
507 } catch (IOException e) {
508 e.printStackTrace();
509 }
510 mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
511 }
512 }
513 @Override
514 protected void onSaveInstanceState(Bundle outState) {
515 super.onSaveInstanceState(outState);
516 // Save variables on screen orientation change
517 outState.putDouble("OPERAND", mCalculatorBrain.getResult());
518 outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
519 }
520 @Override
521 protected void onRestoreInstanceState(Bundle savedInstanceState) {
522 super.onRestoreInstanceState(savedInstanceState);
523 // Restore variables on screen orientation change
524 mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
525 mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
526 mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
527 }
528
529}
530```
531CalculatorBrain.java
532``` java
533package example.com.calculator;
534import android.content.Context;
535import java.io.FileOutputStream;
536import java.io.IOException;
537import java.io.OutputStreamWriter;
538/**
539 * Created by neeraj on 19-03-2016.
540 */
541public class CalculatorBrain {
542 // 3 + 6 = 9
543 // 3 & 6 are called the operand.
544 // The + is called the operator.
545 // 9 is the result of the operation.
546 private double mOperand;
547 private double mWaitingOperand;
548 private String mWaitingOperator;
549 private double mCalculatorMemory;
550
551 // operator types
552 public static final String ADD = "+";
553 public static final String SUBTRACT = "-";
554 public static final String MULTIPLY = "*";
555 public static final String DIVIDE = "/";
556
557 public static final String CLEAR = "C" ;
558 public static final String CLEARMEMORY = "MC";
559 public static final String ADDTOMEMORY = "M+";
560 public static final String SUBTRACTFROMMEMORY = "M-";
561 public static final String RECALLMEMORY = "MR";
562 public static final String SQUAREROOT = "√";
563 public static final String SQUARED = "x²";
564 public static final String INVERT = "1/x";
565 public static final String TOGGLESIGN = "+/-";
566 public static final String SINE = "sin";
567 public static final String COSINE = "cos";
568 public static final String TANGENT = "tan";
569
570 // public static final String EQUALS = "=";
571
572 // constructor
573 public CalculatorBrain() {
574 // initialize variables upon start
575 mOperand = 0;
576 mWaitingOperand = 0;
577 mWaitingOperator = "";
578 mCalculatorMemory = 0;
579 }
580 public void setOperand(double operand) {
581 mOperand = operand;
582 }
583 public double getResult() {
584 return mOperand;
585 }
586 // used on screen orientation change
587 public void setMemory(double calculatorMemory) {
588 mCalculatorMemory = calculatorMemory;
589 }
590 // used on screen orientation change
591 public double getMemory() {
592 return mCalculatorMemory;
593 }
594 public String toString() {
595 return Double.toString(mOperand);
596 }
597 protected double performOperation(String operator) throws IOException {
598 if (operator.equals(CLEAR)) {
599 mOperand = 0;
600 mWaitingOperator = "";
601 mWaitingOperand = 0;
602 // mCalculatorMemory = 0;
603 } else if (operator.equals(CLEARMEMORY)) {
604 mCalculatorMemory = 0;
605 } else if (operator.equals(ADDTOMEMORY)) {
606 mCalculatorMemory = mCalculatorMemory + mOperand;
607 } else if (operator.equals(SUBTRACTFROMMEMORY)) {
608 mCalculatorMemory = mCalculatorMemory - mOperand;
609 } else if (operator.equals(RECALLMEMORY)) {
610 mOperand = mCalculatorMemory;
611 } else if (operator.equals(SQUAREROOT)) {
612 mOperand = Math.sqrt(mOperand);
613 } else if (operator.equals(SQUARED)) {
614 mOperand = mOperand * mOperand;
615 } else if (operator.equals(INVERT)) {
616 if (mOperand != 0) {
617 mOperand = 1 / mOperand;
618 }
619 } else if (operator.equals(TOGGLESIGN)) {
620 mOperand = -mOperand;
621 } else if (operator.equals(SINE)) {
622 mOperand = Math.sin(Math.toRadians(mOperand)); // Math.toRadians(mOperand) converts result to degrees
623 } else if (operator.equals(COSINE)) {
624 mOperand = Math.cos(Math.toRadians(mOperand)); // Math.toRadians(mOperand) converts result to degrees
625 } else if (operator.equals(TANGENT)) {
626 mOperand = Math.tan(Math.toRadians(mOperand)); // Math.toRadians(mOperand) converts result to degrees
627 } else {
628 performWaitingOperation();
629 mWaitingOperator = operator;
630 mWaitingOperand = mOperand;
631 }
632 return mOperand;
633 }
634
635 protected void performWaitingOperation() {
636 if (mWaitingOperator.equals(ADD)) {
637 mOperand = mWaitingOperand + mOperand;
638 } else if (mWaitingOperator.equals(SUBTRACT)) {
639 mOperand = mWaitingOperand - mOperand;
640 } else if (mWaitingOperator.equals(MULTIPLY)) {
641 mOperand = mWaitingOperand * mOperand;
642 } else if (mWaitingOperator.equals(DIVIDE)) {
643 if (mOperand != 0) {
644 mOperand = mWaitingOperand / mOperand;
645 }
646 }
647 }
648}
649```
650activity_main.xml (in res/layout)
651``` xml
652<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
653 android:id="@+id/functionPad"
654 android:layout_width="match_parent"
655 android:layout_height="match_parent"
656 android:layout_gravity="center"
657 android:orientation="vertical"
658 android:paddingBottom="@dimen/activity_vertical_margin"
659 android:paddingLeft="@dimen/activity_horizontal_margin"
660 android:paddingRight="@dimen/activity_horizontal_margin"
661 android:paddingTop="@dimen/activity_vertical_margin" >
662
663 <LinearLayout
664 android:id="@+id/row1"
665 android:layout_width="match_parent"
666 android:layout_height="0dp"
667 android:layout_weight=".12" >
668
669 <TextView
670 android:id="@+id/textView1"
671 android:layout_width="match_parent"
672 android:layout_height="wrap_content"
673 android:gravity="right"
674 android:maxLines="1"
675 android:paddingLeft="10dp"
676 android:paddingRight="10dp"
677 android:text="0"
678 android:textAppearance="?android:attr/textAppearanceLarge"
679 android:textSize="40sp" />
680 </LinearLayout>
681
682 <LinearLayout
683 android:id="@+id/row2"
684 android:layout_width="match_parent"
685 android:layout_height="0dp"
686 android:layout_weight=".12" >
687
688 <Button
689 android:id="@+id/buttonClearMemory"
690 android:layout_width="0dp"
691 android:layout_height="match_parent"
692 android:layout_weight=".25"
693 android:text="@string/buttonClearMemory"
694 android:textSize="25sp" />
695
696 <Button
697 android:id="@+id/buttonAddToMemory"
698 android:layout_width="0dp"
699 android:layout_height="match_parent"
700 android:layout_weight=".25"
701 android:text="@string/buttonAddToMemory"
702 android:textSize="25sp" />
703
704 <Button
705 android:id="@+id/buttonSubtractFromMemory"
706 android:layout_width="0dp"
707 android:layout_height="match_parent"
708 android:layout_weight=".25"
709 android:text="@string/buttonSubtractFromMemory"
710 android:textSize="25sp" />
711
712 <Button
713 android:id="@+id/buttonRecallMemory"
714 android:layout_width="0dp"
715 android:layout_height="match_parent"
716 android:layout_weight=".25"
717 android:text="@string/buttonRecallMemory"
718 android:textSize="25sp" />
719 </LinearLayout>
720 <LinearLayout
721 android:id="@+id/row7"
722 android:layout_width="match_parent"
723 android:layout_height="0dp"
724 android:layout_weight=".12" >
725
726 <Button
727 android:id="@+id/buttonSquareRoot"
728 android:layout_width="0dp"
729 android:layout_height="match_parent"
730 android:layout_weight=".25"
731 android:text="@string/buttonSquareRoot"
732 android:textSize="25sp" />
733
734 <Button
735 android:id="@+id/buttonSquared"
736 android:layout_width="0dp"
737 android:layout_height="match_parent"
738 android:layout_weight=".25"
739 android:text="@string/buttonSquared"
740 android:textSize="25sp" />
741
742 <Button
743 android:id="@+id/buttonInvert"
744 android:layout_width="0dp"
745 android:layout_height="match_parent"
746 android:layout_weight=".25"
747 android:text="@string/buttonInvert"
748 android:textSize="17sp" />
749
750 <Button
751 android:id="@+id/buttonSine"
752 android:layout_width="0dp"
753 android:layout_height="match_parent"
754 android:layout_weight=".25"
755 android:text="@string/buttonSine"
756 android:textSize="17sp" />
757 <Button
758 android:id="@+id/buttonCosine"
759 android:layout_width="0dp"
760 android:layout_height="match_parent"
761 android:layout_weight=".25"
762 android:text="@string/buttonCosine"
763 android:textSize="17sp" />
764 <Button
765 android:id="@+id/buttonTangent"
766 android:layout_width="0dp"
767 android:layout_height="match_parent"
768 android:layout_weight=".25"
769 android:text="@string/buttonTangent"
770 android:textSize="17sp" />
771 </LinearLayout>
772 <LinearLayout
773 android:id="@+id/row3"
774 android:layout_width="match_parent"
775 android:layout_height="0dp"
776 android:layout_weight=".12" >
777
778 <Button
779 android:id="@+id/buttonClear"
780 android:layout_width="0dp"
781 android:layout_height="match_parent"
782 android:layout_weight=".25"
783 android:text="@string/buttonClear"
784 android:textSize="25sp" />
785
786 <Button
787 android:id="@+id/buttonToggleSign"
788 android:layout_width="0dp"
789 android:layout_height="match_parent"
790 android:layout_weight=".25"
791 android:text="@string/buttonToggleSign"
792 android:textSize="25sp" />
793
794 <Button
795 android:id="@+id/buttonDivide"
796 android:layout_width="0dp"
797 android:layout_height="match_parent"
798 android:layout_weight=".25"
799 android:text="@string/buttonDivide"
800 android:textSize="25sp" />
801
802 <Button
803 android:id="@+id/buttonMultiply"
804 android:layout_width="0dp"
805 android:layout_height="match_parent"
806 android:layout_weight=".25"
807 android:text="@string/buttonMultiply"
808 android:textSize="25sp" />
809 </LinearLayout>
810
811 <LinearLayout
812 android:id="@+id/row4"
813 android:layout_width="match_parent"
814 android:layout_height="0dp"
815 android:layout_weight=".12" >
816
817 <Button
818 android:id="@+id/button7"
819 android:layout_width="0dp"
820 android:layout_height="match_parent"
821 android:layout_weight=".25"
822 android:text="@string/button7"
823 android:textSize="25sp" />
824
825 <Button
826 android:id="@+id/button8"
827 android:layout_width="0dp"
828 android:layout_height="match_parent"
829 android:layout_weight=".25"
830 android:text="@string/button8"
831 android:textSize="25sp" />
832
833 <Button
834 android:id="@+id/button9"
835 android:layout_width="0dp"
836 android:layout_height="match_parent"
837 android:layout_weight=".25"
838 android:text="@string/button9"
839 android:textSize="25sp" />
840
841 <Button
842 android:id="@+id/buttonSubtract"
843 android:layout_width="0dp"
844 android:layout_height="match_parent"
845 android:layout_weight=".25"
846 android:text="@string/buttonSubtract"
847 android:textSize="25sp" />
848 </LinearLayout>
849
850 <LinearLayout
851 android:id="@+id/row5"
852 android:layout_width="match_parent"
853 android:layout_height="0dp"
854 android:layout_weight=".12" >
855
856 <Button
857 android:id="@+id/button4"
858 android:layout_width="0dp"
859 android:layout_height="match_parent"
860 android:layout_weight=".25"
861 android:text="@string/button4"
862 android:textSize="25sp" />
863
864 <Button
865 android:id="@+id/button5"
866 android:layout_width="0dp"
867 android:layout_height="match_parent"
868 android:layout_weight=".25"
869 android:text="@string/button5"
870 android:textSize="25sp" />
871
872 <Button
873 android:id="@+id/button6"
874 android:layout_width="0dp"
875 android:layout_height="match_parent"
876 android:layout_weight=".25"
877 android:text="@string/button6"
878 android:textSize="25sp" />
879
880 <Button
881 android:id="@+id/buttonAdd"
882 android:layout_width="0dp"
883 android:layout_height="match_parent"
884 android:layout_weight=".25"
885 android:text="@string/buttonAdd"
886 android:textSize="25sp" />
887 </LinearLayout>
888
889 <LinearLayout
890 android:id="@+id/row6"
891 android:layout_width="match_parent"
892 android:layout_height="0dp"
893 android:layout_weight=".24"
894 android:baselineAligned="false" >
895
896 <LinearLayout
897 android:layout_width="0dp"
898 android:layout_height="match_parent"
899 android:layout_weight=".75"
900 android:orientation="vertical" >
901
902 <LinearLayout
903 android:id="@+id/linearLayout1"
904 android:layout_width="match_parent"
905 android:layout_height="0dp"
906 android:layout_weight=".50"
907 android:textSize="25sp" >
908
909 <Button
910 android:id="@+id/button1"
911 android:layout_width="0dp"
912 android:layout_height="match_parent"
913 android:layout_weight=".33"
914 android:text="@string/button1"
915 android:textSize="25sp" />
916
917 <Button
918 android:id="@+id/button2"
919 android:layout_width="0dp"
920 android:layout_height="match_parent"
921 android:layout_weight=".33"
922 android:text="@string/button2"
923 android:textSize="25sp" />
924
925 <Button
926 android:id="@+id/button3"
927 android:layout_width="0dp"
928 android:layout_height="match_parent"
929 android:layout_weight=".34"
930 android:text="@string/button3"
931 android:textSize="25sp" />
932 </LinearLayout>
933
934 <LinearLayout
935 android:id="@+id/linearLayout2"
936 android:layout_width="match_parent"
937 android:layout_height="0dp"
938 android:layout_weight=".50" >
939
940 <Button
941 android:id="@+id/button0"
942 android:layout_width="0dp"
943 android:layout_height="match_parent"
944 android:layout_weight=".66"
945 android:text="@string/button0"
946 android:textSize="25sp" />
947
948 <Button
949 android:id="@+id/buttonDecimalPoint"
950 android:layout_width="0dp"
951 android:layout_height="match_parent"
952 android:layout_weight=".34"
953 android:text="@string/buttonDecimalPoint"
954 android:textSize="25sp" />
955 </LinearLayout>
956 </LinearLayout>
957
958 <Button
959 android:id="@+id/buttonEquals"
960 android:layout_width="0dp"
961 android:layout_height="match_parent"
962 android:layout_weight=".25"
963 android:text="@string/buttonEquals"
964 android:textSize="25sp" />
965 </LinearLayout>
966
967
968</LinearLayout>
969```
970strings.xml (in res/values)
971``` xml
972<?xml version="1.0" encoding="utf-8"?>
973<resources>
974 <string name="app_name">Calculator</string>
975 <string name="menu_settings">Settings</string>
976 <string name="action_settings">Settings</string>
977 <string name="button0">0</string>
978 <string name="button1">1</string>
979 <string name="button2">2</string>
980 <string name="button3">3</string>
981 <string name="button4">4</string>
982 <string name="button5">5</string>
983 <string name="button6">6</string>
984 <string name="button7">7</string>
985 <string name="button8">8</string>
986 <string name="button9">9</string>
987 <string name="buttonAdd">+</string>
988 <string name="buttonSubtract">-</string>
989 <string name="buttonMultiply">*</string>
990 <string name="buttonDivide">/</string>
991 <string name="buttonToggleSign">+/-</string>
992 <string name="buttonDecimalPoint">.</string>
993 <string name="buttonEquals">=</string>
994 <string name="buttonClear">C</string>
995 <string name="buttonClearMemory">MC</string>
996 <string name="buttonAddToMemory">M+</string>
997 <string name="buttonSubtractFromMemory">M-</string>
998 <string name="buttonRecallMemory">MR</string>
999 <string name="buttonSquareRoot">√</string>
1000 <string name="buttonSquared">x²</string>
1001 <string name="buttonInvert">1/x</string>
1002 <string name="buttonSine">sin</string>
1003 <string name="buttonCosine">cos</string>
1004 <string name="buttonTangent">tan</string>
1005
1006</resources>
1007```
1008
1009# A6 encryption
1010## code
1011```
1012#encryption.py
1013import hashlib
1014import sys
1015import os
1016import binascii
1017
1018try:
1019 hash_name = sys.argv[1]
1020except IndexError:
1021 print('1st arg\n'+ str(hashlib.algorithms_guaranteed)+'\n2nd arg username','\n3rd arg password')
1022else:
1023 try:
1024 username = sys.argv[2]
1025 passwd = sys.argv[3]
1026 password = bytes(passwd,'UTF-8')
1027 except IndexError:
1028 print('using default password: password')
1029 password = b'password'
1030
1031
1032
1033 salt = os.urandom(32)
1034 chef_salt = binascii.hexlify(salt)
1035 filename = username+"_salt.key"
1036 salT_file = open(username+"_salt.key","w")
1037 print("Salt\n"+chef_salt.decode('utf-8'))
1038 salT_file.write(chef_salt.decode('utf-8'))
1039 salT_file.close()
1040 dk = hashlib.pbkdf2_hmac(hash_name, password, chef_salt, 100000,128)
1041 store_hash = binascii.hexlify(dk)
1042 filename = username+"_hash.hash"
1043 hash_file = open(username+"_hash.hash","w")
1044 print("hash\n"+store_hash.decode('utf-8'))
1045 hash_file.write(store_hash.decode('utf-8'))
1046 hash_file.close()
1047
1048# verification.py
1049import hashlib
1050import sys
1051import os
1052import binascii
1053
1054try:
1055 hash_name = sys.argv[1]
1056except IndexError:
1057 print('Specify the hash name as the first argument.')
1058else:
1059 try:
1060 username = sys.argv[2]
1061 passwd = sys.argv[3]
1062 password = bytes(passwd,'UTF-8')
1063 except IndexError:
1064 print('using default password: password')
1065 password = b'password'
1066
1067
1068 try:#password = bytes(passwd,'UTF-8')
1069 salT_file = open(username+"_salt.key")
1070 chef_salt = salT_file.read()
1071 print("Salt\n"+chef_salt)
1072 dk = hashlib.pbkdf2_hmac(hash_name, password, bytes(chef_salt,'UTF-8'), 100000,128)
1073 hashk = binascii.hexlify(dk)
1074 new_hash = hashk.decode('utf-8')
1075 hash_file = open(username+"_hash.hash")
1076 old_hash = hash_file.read()
1077 print("hash\n"+old_hash)
1078 if new_hash == old_hash:
1079 print("The user "+username+" has used valid password")
1080 else:
1081 print("Incorrect username or password")
1082 except OSError as e:
1083 print("Incorrect username or password")
1084
1085
1086```
1087## Explanation
1088```
1089Algo
1090
1091To Store a Password
1092
1093 1.Generate a long random salt using a CSPRNG.
1094 2.generate hash using standard cryptographic hash function such as SHA256
1095 3.key stretching using PBKDF2 inpust name = standard cryptographic hash function such as SHA256, password = hash generated, salt = salt, round = 10000 aleast, dklen = 64 atleast length of derived key
1096 4.Save both the salt and the hash in the user's database record.
1097
1098To Validate a Password
1099
1100 1.Retrieve the user's salt and hash from the database.
1101 2.Prepend the salt to the given password and hash it using the same hash function.
1102 3.Compare the hash of the given password with the hash from the database. If they match, the password is correct. Otherwise, the password is incorrect.
1103
1104```
1105
1106# B1 8q
1107## code
1108```
1109#8q.py
1110import json
1111inf=open("8q.json")
1112board=json.loads(inf.read())
1113board=board["matrix"]
1114for i in board:
1115 print(i)
1116
1117def issafe(row,col):
1118 for i in range(8):
1119 for j in range(8):
1120 if(board[i][j]==1): #if a queen exists here, then check if it attacks our queen
1121 if(row==i):
1122 return False
1123 if(col==j):
1124 return False
1125 if(abs(row-i)==abs(col-j)):
1126 return False
1127 return True
1128def place(col):
1129 if(col>=8): #if all 8 queens are placed, then finish
1130 print("\t\tCompleted...")
1131 return True
1132 for i in range(8): #checking for all rows in that column
1133 if(board[i][col]==1): #if a queen is already placed here,
1134 return place(col+1) #then simply place for next column
1135 if(issafe(i,col)): #is it safe?
1136 board[i][col]=1 #queen is placed here
1137 if(place(col+1)==True): #recursive call to place next queen
1138 return True
1139 board[i][col]=0 #if not placed, then backtrack, i.e it sets to zero and the loop iterates to check for next position
1140 return False
1141if(place(0)==True):
1142 print("solution found")
1143else:
1144 print("Solution not possible")
1145for i in board:
1146 print(i)
1147
1148#8q.json
1149{"matrix": [
1150
1151 [0, 0, 1, 0, 0, 0, 0, 0],
1152 [0, 0, 0, 0, 0, 1, 0, 0],
1153 [0, 0, 0, 0, 0, 0, 0, 0],
1154 [0, 0, 0, 0, 0, 0, 0, 1],
1155 [0, 0, 0, 0, 0, 0, 0, 0],
1156 [1, 0, 0, 0, 0, 0, 0, 0],
1157 [0, 0, 0, 0, 0, 0, 0, 0],
1158 [0, 0, 0, 0, 0, 1, 0, 0]]}
1159
1160```
1161## Explanation
1162```
11631. 8 QUEENS PROBLEM USING BACK TRACKING
11642. BACK TRACKING
1165 Backtracking is a general algorithm for finding all (or some) solutions to some computational problem, that incrementally builds candidates to the solutions, and abandons each partial candidate ‘c’ ("backtracks") as soon as it determines that ‘c’ cannot possibly be completed to a valid solution.
1166 Backtracking is an important tool for solving constraint satisfaction problems, such as crosswords, verbal arithmetic, Sudoku, and many other puzzles.
11673.
1168 It is also the basis of the so-called logic programming languages such as Planner and Prolog.
1169 The term "backtrack" was coined by American mathematician D. H. Lehmer in the 1950s.
1170 The pioneer string-processing language SNOBOL (1962) may have been the first to provide a built-in general backtracking facility.
11714.
1172 The good example of the use of backtracking is the eight queens puzzle, that asks for all arrangements of eight queens on a standard chessboard so that no queen attacks any other.
1173 In the common backtracking approach, the partial candidates are arrangements of k queens in the first k rows of the board, all in different rows and columns.
1174 Any partial solution that contains two mutually attacking queens can be abandoned, since it cannot possibly be completed to a valid solution
11755. WHAT IS 8 QUEEN PROBLEM?
1176 The eight queens puzzle is the problem of placing eight chess queens on an 8 8 chessboard so that no two queens attack each other.
1177 Thus, a solution requires that no two queens share the same row, column, or diagonal.
1178 The eight queens puzzle is an example of the more general n-queens problem of placing n queens on an n n chessboard, where solutions exist for all natural numbers n with the exception of 1, 2 and 3.
1179 The solution possibilities are discovered only up to 23 queen.
11806. PROBLEM INVENTOR
1181 The puzzle was originally proposed in 1848 by the chess player Max Bezzel, and over the years, many mathematicians, including Gauss, have worked on this puzzle and its generalized n-queens problem.
11827. SOLUTION INVENTOR
1183 The first solution for 8 queens were provided by Franz Nauck in 1850. Nauck also extended the puzzle to n-queens problem (on an n n board—a chessboard of arbitrary size).
1184 In 1874, S. Günther proposed a method of finding solutions by using determinants, and J.W.L. Glaisher refined this approach.
1185 Edsger Dijkstra used this problem in 1972 to illustrate the power of what he called structured programming.
1186 He published a highly detailed description of the development of a depth-first backtracking algorithm.
11878. Formulation : States: any arrangementof 0 to 8 queens on theboard Initial state: 0 queens onthe board Successor function: adda queen in any squareGoal test: 8 queens onthe board, none attacked
11889. BACKTRACKING CONCEPT
1189 Each recursive call attempts to place a queen in a specificcolumn.
1190 For a given call, the state of the board from previousplacements is known (i.e. where are the other queens?)
1191 Current step backtracking: If a placement within thecolumn does not lead to a solution, the queen is removed andmoved "down" the column
1192 Previous step backtracking: When all rows in a columnhave been tried, the call terminates and backtracks to theprevious call (in the previous column)
119310. CONTINU..Pruning: If a queen cannot be placed into column i, do noteven try to place one onto column i+1 – rather, backtrack to column i-1 and move the queen that had beenplaced there.Using this approach we can reduce the number of potentialsolutions even more
119411. BACKTRACKING DEMO FOR 4 QUEENS
119512. STEPS REVISITED - BACKTRACKING1. Place the first queen in the left upper corner of the table.2. Save the attacked positions.3. Move to the next queen (which can only be placed to the next line).4. Search for a valid position. If there is one go to step 8.5. There is not a valid position for the queen. Delete it (the x coordinate is 0).6. Move to the previous queen.7. Go to step 4.8. Place it to the first valid position.9. Save the attacked positions.10. If the queen processed is the last stop otherwise go to step 3.
119613. EIGHT QUEEN PROBLEM: ALGORITHMputQueen(row){ for every position col on the same row if position col is available place the next queen in position col if (row<8) putQueen(row+1); else success; remove the queen from position col}
119714. THE PUTQUEEN RECURSIVE METHODvoid putQueen(int row) { for (int col=0;col<squares;col++) if (column[col]==available && leftDiagonal[row+col]==available && rightDiagonal[row-col]== available) { positionInRow[row]=col; column[col]=!available; leftDiagonal[row+col]=!available;
119815. rightDiagonal[row-col]=!available; if (row< squares-1) putQueen(row+1); else print(" solution foundâ€); column[col]=available; leftDiagonal[row+col]=available; rightDiagonal[row-col]= available; }}
119916. SOLUTIONS• The eight queens puzzle has 92 distinct solutions.• If solutions that differ only by symmetry operations(rotations and reflections) of the board are counted as one the puzzle has 12 unique (or fundamental) solutions
120017. COUNTING SOLUTIONS
1201 The following table gives the number of solutions for placing n queens on an n n board, both unique and distinct for n=1–26.
1202 Note that the six queens puzzle has fewer solutions than the five queens puzzle.
1203 There is currently no known formula for the exact number of solutions.
120418. Order(“Nâ€) Total Solutions Unique Solutions Exec time---------------------------------------------------------1 1 1 < 0 seconds2 0 0 < 0 seconds3 0 0 < 0 seconds4 2 1 < 0 seconds5 10 2 < 0 seconds6 4 1 < 0 seconds7 40 6 < 0 seconds8 92 12 < 0 seconds9 352 46 < 0 seconds10 724 92 < 0 seconds11 2,680 341 < 0 seconds12 14,200 1,787 < 0 seconds13 73,712 9,233 < 0 seconds14 365,596 45,752 0.2s
120519. 15 2,279,184 285,053 1.9 s16 14,772,512 1,846,955 11.2 s17 95,815,104 11,977,939 77.2 s18 666,090,624 83,263,591 9.6 m19 4,968,057,848 621,012,754 75.0 m20 39,029,188,884 4,878,666,808 10.2 h21 314,666,222,712 39,333,324,973 87.2 h22 2,691,008,701,644 336,376,244,042 31.923 24,233,937,684,440 3,029,242,658,210 296 d24 227,514,171,973,736 28,439,272,956,934 ?25 2,207,893,435,808,352 275,986,683,743,434 ?26 22,317,699,616,364,044 2,789,712,466,510,289 ? (s = seconds m = minutes h = hours d = days)
120620. JEFF SOMER’S ALGORITHM
1207 His algorithm for the N-Queen problem is considered as the fastest algorithm. He uses the concept of back tracking to solve this
1208 Previously the World’s fastest algorithm for the N-Queen problem was given by Sylvain Pion and Joel-Yann Fourre.
1209 His algorithm finds solutions up to 23 queens and uses bit field manipulation in BACKTRACKING.
1210 According to his program the maximum time taken to find all the solutions for a 18 queens problem is 00:19:26 where as in the normal back tracking algorithm it was 00:75:00.
121121. USING NESTED LOOPS FOR SOLUTIONFor a 4x4 board, we could find the solutions like this: for(i0 = 0; i0 < 4; ++i0) { if(isSafe(board, 0, i0)) { board[0][i0] = true; for(i1 = 0; i1 < 4; ++i1) { if(isSafe(board, 1, i1)) { board[1][i1] = true; for(i2 = 0; i2 < 4; ++i2) { if(isSafe(board 2, i2)) { board[2][i2] = true; for(i3 = 0; i3 < 4; ++i3) { if(isSafe(board 3, i3)) { board[3][i3] = true;
121222. { printBoard(board, 4);} board[3][i3] = false; } } board[2][i2] = false; } } board[1][i1] = false; } } board[0][i0] = false; } }
121323. WHY NOT NESTED LOOP
1214 The nested loops are not so preferred because . It Does not scale to different sized boards
1215 You must duplicate identical code (place and remove). and error in one spot is hard to find
1216 The problem with this is that its not very programmer- friendly. We cant vary at runtime the size of the board were searching
121724.
1218 The major advantage of the backtracking algorithm is the abillity to find and count all the possible solutions rather than just one while offering decent speed.
1219 If we go through the algorithm for 8 queens 981 queen moves (876 position tests plus 105 backtracks) are required for the first solution alone. 16,704 moves (14,852 tests and 1852 backtracks) are needed to find all 92 solutions.
1220 Given those figures, its easy to see why the solution is best left to computers.
1221```
1222
1223# B5 plagiarism
1224## code
1225```
1226//index.jsp
1227<%--
1228 Document : index
1229 Created on : 9 Mar, 2016, 11:06:22 AM
1230 Author :
1231--%>
1232
1233<%@page contentType="text/html" pageEncoding="UTF-8"%>
1234<!DOCTYPE html>
1235<html>
1236 <head>
1237 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
1238 <title>JSP Page</title>
1239 </head>
1240 <body>
1241 <form action="Plagarism">
1242
1243 Enter the first input <textarea name="File1" rows="5" cols="10">
1244 </textarea><br>
1245 Enter the second input<textarea name="File2" rows="5" cols="10">
1246 </textarea><br>
1247 <input type="submit" value="Check Plagarism" name="btn"/>
1248 </form>
1249 </body>
1250</html>
1251
1252//Plagarism.java
1253/*
1254 * To change this license header, choose License Headers in Project Properties.
1255 * To change this template file, choose Tools | Templates
1256 * and open the template in the editor.
1257 */
1258
1259import java.io.IOException;
1260import java.io.PrintWriter;
1261import javax.servlet.ServletException;
1262import javax.servlet.annotation.WebServlet;
1263import javax.servlet.http.HttpServlet;
1264import javax.servlet.http.HttpServletRequest;
1265import javax.servlet.http.HttpServletResponse;
1266
1267/**
1268 *
1269 * @author
1270 */
1271@WebServlet(urlPatterns = {"/Plagarism"})
1272public class Plagarism extends HttpServlet {
1273
1274 /**
1275 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
1276 * methods.
1277 *
1278 * @param request servlet request
1279 * @param response servlet response
1280 * @throws ServletException if a servlet-specific error occurs
1281 * @throws IOException if an I/O error occurs
1282 */
1283 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
1284 throws ServletException, IOException {
1285 response.setContentType("text/html;charset=UTF-8");
1286 PrintWriter out = response.getWriter();
1287 try {
1288 out.println("<!DOCTYPE html>");
1289 out.println("<html>");
1290 out.println("<head>");
1291 out.println("<title>Servlet Plagarism</title>");
1292 out.println("</head>");
1293 out.println("<body>");
1294
1295 String fileOne = request.getParameter("File1");
1296 String fileTwo = request.getParameter("File2");
1297 out.println("Comparing the 2 files......");out.println("<br>");
1298 String[] str1 = fileOne.split("\\s");
1299 String[] str2 = fileTwo.split("\\s");
1300
1301 for (int j = 0; j < str1.length; j++) { //alphabetical order sorting of str1
1302 for (int i = j + 1; i < str1.length; i++) {
1303 if (str1[i].compareTo(str1[j]) < 0) {
1304 String t = str1[j];
1305 str1[j] = str1[i];
1306 str1[i] = t;
1307 }
1308 }
1309 }
1310
1311 int results; double plag=0;
1312 for (int key = 0; key < str2.length; key++){
1313 results = searchString(str1, str2[key]);
1314 if (results == 1) {
1315 plag = plag+1;
1316 }
1317
1318 }
1319 double plagPercent = (plag/str2.length)*100;
1320
1321 out.println("Similarity between two text is "+ plagPercent);
1322 out.println("<br>");
1323 out.println("Plagrism "+((plagPercent>50.0) ? "exist" : "does not exist"));
1324
1325 out.println("</body>");
1326 out.println("</html>");
1327 } finally {
1328 out.close();
1329 }
1330 }
1331 //simple binary search
1332 public static int searchString(String[] str1, String key) {
1333 int first = 0;
1334 int last = str1.length;
1335
1336 while (first < last) {
1337 int mid = (first + last) / 2;
1338 if (key.compareTo(str1[mid]) < 0) {
1339 last = mid;
1340 } else if (key.compareTo(str1[mid]) > 0) {
1341 first = mid + 1;
1342 } else {
1343 return 1;
1344 }
1345 }
1346 return -1;
1347 }
1348
1349
1350 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
1351 /**
1352 * Handles the HTTP <code>GET</code> method.
1353 *
1354 * @param request servlet request
1355 * @param response servlet response
1356 * @throws ServletException if a servlet-specific error occurs
1357 * @throws IOException if an I/O error occurs
1358 */
1359 @Override
1360 protected void doGet(HttpServletRequest request, HttpServletResponse response)
1361 throws ServletException, IOException {
1362 processRequest(request, response);
1363 }
1364
1365 /**
1366 * Handles the HTTP <code>POST</code> method.
1367 *
1368 * @param request servlet request
1369 * @param response servlet response
1370 * @throws ServletException if a servlet-specific error occurs
1371 * @throws IOException if an I/O error occurs
1372 */
1373 @Override
1374 protected void doPost(HttpServletRequest request, HttpServletResponse response)
1375 throws ServletException, IOException {
1376 processRequest(request, response);
1377 }
1378
1379 /**
1380 * Returns a short description of the servlet.
1381 *
1382 * @return a String containing servlet description
1383 */
1384 @Override
1385 public String getServletInfo() {
1386 return "Short description";
1387 }// </editor-fold>
1388
1389}
1390//test.java
1391import org.openqa.selenium.By;
1392import org.openqa.selenium.WebDriver;
1393import org.openqa.selenium.WebElement;
1394import org.openqa.selenium.firefox.FirefoxDriver;
1395
1396public class mytest3
1397{
1398
1399
1400 public static void main(String[] args) {
1401
1402
1403 WebDriver driver = new FirefoxDriver();
1404 String baseUrl = "http://localhost:8084/plagraism/";
1405 driver.get(baseUrl);
1406 String expected = "JSP Page";
1407 String actual = "";
1408 driver.manage().window().maximize();
1409 actual = driver.getTitle();
1410 if (actual.equals(expected)) {
1411 System.out.println("Title test passed");
1412 } else {
1413 System.out.println("Title test failed");}
1414 WebElement text=driver.findElement(By.name("File1"));
1415 text.sendKeys("hello");
1416 WebElement text1=driver.findElement(By.name("File2"));
1417 text1.sendKeys("hiee");
1418
1419 WebElement btn=driver.findElement(By.name("btn"));
1420 btn.click();
1421 System.out.println(" test script sucessful");
1422 driver.close();
1423
1424 }
1425}
1426```
1427
1428# BD1 sha
1429## code
1430```
1431#sha1.py
1432def sha1(data):
1433 bytes = ""
1434
1435 h0 = 0x67452301 # Initialize variables
1436 h1 = 0xEFCDAB89
1437 h2 = 0x98BADCFE
1438 h3 = 0x10325476
1439 h4 = 0xC3D2E1F0
1440
1441 for n in range(len(data)):
1442 bytes+='{0:08b}'.format(ord(data[n]))
1443 bits = bytes+"1"
1444 pBits = bits
1445 #pad until length equals 448 mod 512
1446 while len(pBits)%512 != 448:
1447 pBits+="0"
1448 #append the original length
1449 pBits+='{0:064b}'.format(len(bits)-1)
1450
1451
1452 def chunks(l, n):
1453 return [l[i:i+n] for i in range(0, len(l), n)]
1454
1455 def rol(n, b):
1456 return ((n << b) | (n >> (32 - b))) & 0xffffffff
1457
1458 for c in chunks(pBits, 512):
1459 words = chunks(c, 32)
1460 w = [0]*80
1461 for n in range(0, 16):
1462 w[n] = int(words[n], 2)
1463 for i in range(16, 80):
1464 w[i] = rol((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)
1465
1466 a = h0
1467 b = h1
1468 c = h2
1469 d = h3
1470 e = h4
1471
1472 #Main loop
1473
1474 for i in range(0, 80):
1475 if 0 <= i <= 19:
1476 #f = (b & c) | ((~b) & d)
1477 f = b ^ c ^ d
1478 k = 0x5A827999
1479 elif 20 <= i <= 39:
1480 f = b ^ c ^ d
1481 k = 0x6ED9EBA1
1482 elif 40 <= i <= 59:
1483 #f = (b & c) | (b & d) | (c & d)
1484 f = b ^ c ^ d
1485 k = 0x8F1BBCDC
1486 elif 60 <= i <= 79:
1487 #f = b ^ c ^ d
1488 f = b ^ c ^ d
1489 k = 0xCA62C1D6
1490
1491 temp = rol(a, 5) + f + e + k + w[i] & 0xffffffff
1492 e = d
1493 d = c
1494 c = rol(b, 30)
1495 b = a
1496 a = temp
1497
1498 h0 = h0 + a & 0xffffffff
1499 h1 = h1 + b & 0xffffffff
1500 h2 = h2 + c & 0xffffffff
1501 h3 = h3 + d & 0xffffffff
1502 h4 = h4 + e & 0xffffffff
1503
1504 return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4)
1505#print(sha1("hello"))
1506
1507#server.py
1508import socket
1509import sha1
1510ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM,0)
1511ss.bind(("", 5008))
1512ss.listen(5)
1513
1514print "TCPServer1 Waiting for client on port 7998"
1515
1516while 1:
1517 client_socket, address = ss.accept()
1518
1519 print "I got a connection from ", address
1520
1521 stri = client_socket.recv(1024)
1522
1523 alist = stri.split('\n')
1524 print alist[0]
1525 checkHash=sha1.sha1(str(alist[0]))
1526 print checkHash
1527 if checkHash == alist[1]:
1528 print "Message is valid"
1529 client_socket.send("Message is Verified")
1530 else:
1531 client_socket.send("Message could not be verified")
1532 client_socket.close()
1533 ss.close()
1534 print "Data sent!"
1535
1536 break;
1537
1538
1539'''
1540cipher@blackfury-HP-eNVy:~/be-2/BE1$ python server.py
1541TCPServer1 Waiting for client on port 7998
1542I got a connection from ('127.0.0.1', 44144)
1543Hello World!
15442b72790bf888c4427287b3d79a8c8a3320c61986
1545Message is valid
1546Data sent!
1547
1548'''
1549#client.py
1550# TCP client example
1551import socket
1552import sha1
1553TCP_IP = '127.0.0.1'
1554TCP_PORT = 5008
1555BUFFER_SIZE = 1024
1556
1557MESSAGE = raw_input("Enter a message: ")
1558digest = sha1.sha1(MESSAGE)
1559
1560s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1561s.connect((TCP_IP, TCP_PORT))
1562s.send(MESSAGE+"\n")#could directly use s.send(MESSAGE+"\n"+digest) i dont know why but someone told me...
1563s.send(digest)#could comment this.
1564data = s.recv(BUFFER_SIZE)
1565s.close()
1566
1567print "received data:", data
1568
1569```
1570## Explanation
1571```
1572Note 1: All variables are unsigned 32-bit quantities and wrap modulo 232 when calculating, except for
1573 ml, the message length, which is a 64-bit quantity, and
1574 hh, the message digest, which is a 160-bit quantity.
1575Note 2: All constants in this pseudo code are in big endian.
1576 Within each word, the most significant byte is stored in the leftmost byte position
1577
1578Initialize variables:
1579
1580h0 = 0x67452301
1581h1 = 0xEFCDAB89
1582h2 = 0x98BADCFE
1583h3 = 0x10325476
1584h4 = 0xC3D2E1F0
1585
1586ml = message length in bits (always a multiple of the number of bits in a character).
1587
1588Pre-processing:
1589append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits.
1590append 0 ≤ k < 512 bits '0', such that the resulting message length in bits
1591 is congruent to −64 ≡ 448 (mod 512)
1592append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits.
1593
1594Process the message in successive 512-bit chunks:
1595break message into 512-bit chunks
1596for each chunk
1597 break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15
1598
1599 Extend the sixteen 32-bit words into eighty 32-bit words:
1600 for i from 16 to 79
1601 w[i] = (w[i-3] xor w[i-8] xor w[i-14] xor w[i-16]) leftrotate 1
1602
1603 Initialize hash value for this chunk:
1604 a = h0
1605 b = h1
1606 c = h2
1607 d = h3
1608 e = h4
1609
1610 Main loop:[44][2]
1611 for i from 0 to 79
1612 if 0 ≤ i ≤ 19 then
1613 f = (b and c) or ((not b) and d)
1614 k = 0x5A827999
1615 else if 20 ≤ i ≤ 39
1616 f = b xor c xor d
1617 k = 0x6ED9EBA1
1618 else if 40 ≤ i ≤ 59
1619 f = (b and c) or (b and d) or (c and d)
1620 k = 0x8F1BBCDC
1621 else if 60 ≤ i ≤ 79
1622 f = b xor c xor d
1623 k = 0xCA62C1D6
1624
1625 temp = (a leftrotate 5) + f + e + k + w[i]
1626 e = d
1627 d = c
1628 c = b leftrotate 30
1629 b = a
1630 a = temp
1631
1632 Add this chunk's hash to result so far:
1633 h0 = h0 + a
1634 h1 = h1 + b
1635 h2 = h2 + c
1636 h3 = h3 + d
1637 h4 = h4 + e
1638
1639Produce the final hash value (big-endian) as a 160 bit number:
1640hh = (h0 leftshift 128) or (h1 leftshift 96) or (h2 leftshift 64) or (h3 leftshift 32) or h4
1641The number hh is the message digest, which can be written in hexadecimal (base 16), but is often written using Base64 binary to ASCII text encoding.
1642
1643The constant values used are chosen to be nothing up my sleeve numbers: the four round constants k are 230 times the square roots of 2, 3, 5 and 10. The first four starting values for h0 through h3 are the same with the MD5 algorithm, and the fifth (for h4) is similar.
1644```
1645
1646# BD2 random number
1647## code
1648```
1649#!/usr/bin/env python2
1650# -*- coding: utf-8 -*-
1651"""
1652Based on the pseudocode in https://en.wikipedia.org/wiki/Mersenne_Twister.
1653Generates uniformly distributed 32-bit integers in the range [0, 232 − 1] with the MT19937 algorithm
1654
1655
1656"""
1657# Create a length 624 list to store the state of the generator
1658MT = [0 for i in xrange(624)]
1659index = 0
1660
1661# To get last 32 bits
1662bitmask_1 = (2 ** 32) - 1
1663
1664# To get 32. bit
1665bitmask_2 = 2 ** 31
1666
1667# To get last 31 bits
1668bitmask_3 = (2 ** 31) - 1
1669
1670def initialize_generator(seed):
1671 "Initialize the generator from a seed"
1672 global MT
1673 global bitmask_1
1674 MT[0] = seed
1675 for i in xrange(1,624):
1676 MT[i] = ((1812433253 * MT[i-1]) ^ ((MT[i-1] >> 30) + i)) & bitmask_1
1677
1678
1679def extract_number():
1680 """
1681 Extract a tempered pseudorandom number based on the index-th value,
1682 calling generate_numbers() every 624 numbers
1683 """
1684 global index
1685 global MT
1686 if index == 0:
1687 generate_numbers()
1688 y = MT[index]
1689 y ^= y >> 11
1690 y ^= (y << 7) & 2636928640
1691 y ^= (y << 15) & 4022730752
1692 y ^= y >> 18
1693
1694 index = (index + 1) % 624
1695 return y
1696
1697def generate_numbers():
1698 "Generate an array of 624 untempered numbers"
1699 global MT
1700 for i in xrange(624):
1701 y = (MT[i] & bitmask_2) + (MT[(i + 1 ) % 624] & bitmask_3)
1702 MT[i] = MT[(i + 397) % 624] ^ (y >> 1)
1703 if y % 2 != 0:
1704 MT[i] ^= 2567483615
1705
1706if __name__ == "__main__":
1707 from datetime import datetime
1708 now = datetime.now()
1709 initialize_generator(now.microsecond)
1710 for i in xrange(5):
1711 "Print 5 random numbers as an example"
1712 print extract_number()
1713
1714```
1715## Explanation
1716```
1717 // Create a length n array to store the state of the generator
1718 int[0..n-1] MT
1719 int index := n+1
1720 const int lower_mask = (1 << r) - 1 // That is, the binary number of r 1's
1721 const int upper_mask = lowest w bits of (not lower_mask)
1722
1723 // Initialize the generator from a seed
1724 function seed_mt(int seed) {
1725 index := n
1726 MT[0] := seed
1727 for i from 1 to (n - 1) { // loop over each element
1728 MT[i] := lowest w bits of (f * (MT[i-1] xor (MT[i-1] >> (w-2))) + i)
1729 }
1730 }
1731
1732 // Extract a tempered value based on MT[index]
1733 // calling twist() every n numbers
1734 function extract_number() {
1735 if index >= n {
1736 if index > n {
1737 error "Generator was never seeded"
1738 // Alternatively, seed with constant value; 5489 is used in reference C code[44]
1739 }
1740 twist()
1741 }
1742
1743 int y := MT[index]
1744 y := y xor ((y >> u) and d)
1745 y := y xor ((y << s) and b)
1746 y := y xor ((y << t) and c)
1747 y := y xor (y >> l)
1748
1749 index := index + 1
1750 return lowest w bits of (y)
1751 }
1752
1753 // Generate the next n values from the series x_i
1754 function twist() {
1755 for i from 0 to (n-1) {
1756 int x := (MT[i] and upper_mask)
1757 + (MT[(i+1) mod n] and lower_mask)
1758 int xA := x >> 1
1759 if (x mod 2) != 0 { // lowest bit of x is 1
1760 xA := xA xor a
1761 }
1762 MT[i] := MT[(i + m) mod n] xor xA
1763 }
1764 index := 0
1765 }
1766
1767```
1768
1769# BD5 IDS
1770## code
1771
1772```
1773import java.awt.Container;
1774import java.awt.TextArea;
1775import java.awt.event.ActionEvent;
1776import java.awt.event.ActionListener;
1777import java.io.BufferedReader;
1778import java.io.IOException;
1779import java.io.InputStream;
1780import java.io.InputStreamReader;
1781
1782import javax.swing.JButton;
1783import javax.swing.JFrame;
1784import javax.swing.JOptionPane;
1785import javax.swing.JScrollPane;
1786import javax.swing.JTextArea;
1787import javax.swing.JTextField;
1788
1789
1790public class IDS1 {
1791
1792 public static String line;
1793 public static JFrame fr;
1794 public static Container c;
1795 public static JTextArea tx;
1796 public static JScrollPane js;
1797 public static JButton ids_on,ids_off,disp_blocked_ip,disp_rules,unblock_ip;
1798 public static JTextField ip;
1799
1800
1801 public IDS1(){
1802 fr=new JFrame();
1803 c=fr.getContentPane();
1804 c.setLayout(null);
1805
1806 fr.setTitle("Intrusion Detection System Config");
1807
1808 fr.setBounds(0, 0, 920, 550);
1809
1810 //components on the frame
1811 tx=new JTextArea();
1812 js=new JScrollPane(tx,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
1813 ids_on=new JButton("IDS ON");
1814 ids_off=new JButton("IDS OFF");
1815 disp_blocked_ip=new JButton("Blocked IPs");
1816 disp_rules=new JButton("Firewall Rules");
1817 ip=new JTextField("Enter Ip address");
1818 unblock_ip=new JButton("Unblock Ip");
1819
1820
1821 //setting bounds
1822 js.setBounds(5, 20, 900, 400);
1823 ids_on.setBounds(10, 470, 120, 50);
1824 ids_off.setBounds(10, 470, 120, 50);
1825 disp_blocked_ip.setBounds(140, 470, 120, 50);
1826 disp_rules.setBounds(270, 470, 120, 50);
1827 unblock_ip.setBounds(410, 470, 120, 50);
1828 ip.setBounds(410, 520, 220, 50);
1829
1830 ip.setVisible(false);
1831
1832 //adding components on the frame container
1833 c.add(js);
1834 c.add(ids_on);
1835 c.add(ids_off);
1836 c.add(disp_blocked_ip);
1837 c.add(unblock_ip);
1838 c.add(ip);
1839 c.add(disp_rules);
1840
1841
1842 //all button's action listeners
1843
1844 ids_on.addActionListener(new ActionListener() {
1845
1846 @Override
1847 public void actionPerformed(ActionEvent arg0) {
1848 ids_on.setVisible(false);
1849 ids_off.setVisible(true);
1850 exec_commands("sudo service psad start");
1851 exec_commands("sudo service psad status");
1852 }
1853 });
1854
1855 ids_off.addActionListener(new ActionListener() {
1856
1857 @Override
1858 public void actionPerformed(ActionEvent arg0) {
1859 ids_on.setVisible(true);
1860 ids_off.setVisible(false);
1861
1862 exec_commands("sudo service psad stop");
1863 exec_commands("sudo service psad status");
1864 }
1865 });
1866
1867 disp_blocked_ip.addActionListener(new ActionListener() {
1868
1869 @Override
1870 public void actionPerformed(ActionEvent arg0) {
1871 exec_commands("sudo iptables -L INPUT -v -n --line-numbers");
1872
1873 }
1874 });
1875
1876 disp_rules.addActionListener(new ActionListener() {
1877
1878 @Override
1879 public void actionPerformed(ActionEvent arg0) {
1880 //exec_commands("sudo iptables -N TRAFFIC_ACCT");//own traffic chain in order to avoid changes in firewall rules
1881 //exec_commands("sudo iptables -I FORWARD -j TRAFFIC_ACCT");//forwarding all traffic to my created chain
1882 //exec_commands("iptables -A TRAFFIC_ACCT -p tcp && iptables -A TRAFFIC_ACCT -p ip && iptables -A TRAFFIC_ACCT -p icmp");
1883 exec_commands("sudo iptables -L");
1884
1885 }
1886 });
1887
1888 unblock_ip.addActionListener(new ActionListener() {
1889
1890 @Override
1891 public void actionPerformed(ActionEvent arg0) {
1892 String response = JOptionPane.showInputDialog(null,"Enter IP address",
1893 JOptionPane.QUESTION_MESSAGE);
1894 exec_commands("sudo iptables -D INPUT -s "+response+" -j DROP");
1895
1896 }
1897 });
1898
1899 fr.setVisible(true);
1900 fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
1901 }
1902
1903 //Main method
1904public static void main(String arr[]) throws Exception{
1905 IDS1 ids=new IDS1();
1906}
1907
1908//method for execute the commands
1909public void exec_commands(String cmd){
1910 try {
1911 Runtime rt = Runtime.getRuntime();
1912 //Process pr = rt.exec("cmd /c dir");
1913 Process pr = rt.exec(cmd);
1914
1915 BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
1916
1917 String line=null;
1918 tx.setText("");
1919 while((line=input.readLine()) != null) {
1920 System.out.println(line);
1921
1922 //display cmd output on textarea tx
1923
1924 tx.append(line+"\n");
1925 }
1926 //int exitVal = pr.waitFor();
1927 // System.out.println("Exited with error code "+exitVal);
1928
1929 } catch(Exception e) {
1930 System.out.println(e.toString());
1931 e.printStackTrace();
1932 }
1933 }
1934}
1935```
1936
1937## Explantion
1938```
1939https://www.digitalocean.com/community/tutorials/how-to-use-psad-to-detect-network-intrusion-attempts-on-an-ubuntu-vps
1940
1941
1942sudo /sbin/iptables -A INPUT -s 65.55.44.102 -j DROP ---------------add ip address to be blocked
1943
1944sudo apt-get install psad
1945
1946sudo iptables -A INPUT -j LOG ---------------------------For logging purpose(optional)
1947sudo iptables -A FORWARD -j LOG--------------------------
1948
1949sudo iptables -F ---------------Flush rules
1950sudo iptables -L ---------------List all rules
1951
1952sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT --------------------- explicitly allow all traffic related to
1953an existing connection.
1954
1955sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT ---------------------services that we wish to keep open to the public
1956
1957sudo iptables -A INPUT -j LOG
1958sudo iptables -A FORWARD -j LOG
1959
1960sudo iptables -P INPUT DROP ------------------DROP all extraneous messages
1961
1962sudo apt-get install iptables-persistent ------------------- makes these rules persistent(optional)
1963sudo service iptables-persistent start(opyional)
1964
1965sudo gedit /etc/psad/psad.conf -----open and change e-mail address to your email or any other and can also change the domain as per your need
1966
1967sudo psad --sig-update -------------------Update the signatures of the definitions of the known attacks
1968
1969sudo service psad restart --------------Restart the psad IDS
1970
1971
1972-----------end-------------
1973```